読了目安 13 分GitHub で編集

このページはまだ翻訳されていません。以下の本文は英語です。

Architecture

Home · UI Architecture · Development · Adding a backend · Platform support

Tessera is a cooperative tiling controller. It never becomes a window manager and never competes with the session’s own compositor or window manager. Instead, it observes window and monitor state, computes target placements in a pure Rust core, and asks the native window manager to apply them.

Macro overview

flowchart TD
    App["tessera-app (Composition root, CLI, daemon loop, platform seam, BackendId)"]
    Core["tessera-core (Pure tiling policy, layouts, workspaces, conciliation)"]
    Backend["tessera-backend (Capability facets, SessionDriver, EventQueue, contract)"]
    UI["tessera-ui (Neutral UI tree, LayoutSpec solver, tokens, plugin ABI)"]
    Worker["tessera-protocol v3 + tessera-worker (QuickJS sandbox)"]
    Adapters["Backend adapters: x11, gnome, kwin, macos, windows"]
    Providers["UI providers: gtk, adwaita, qt, macos, windows, freedesktop"]

    App --> Core
    App --> Backend
    App --> UI
    App --> Worker
    Backend --> Adapters
    UI --> Providers

Supporting neutral crates:

  • tessera-settings: pure preferences, defaults, numeric bounds, and shortcut grammar.
  • tessera-config: YAML codec, unknown-key preservation, and atomic writes.
  • tessera-i18n: 10 embedded Fluent catalogs and locale negotiation.
  • tessera-mcp: embedded MCP server over stdio or Unix sockets with peer UID checks.

The dependency arrow always points inward toward pure domain crates:

  • tessera-core has zero OS, GUI, YAML, or i18n dependencies.
  • tessera-backend depends on tessera-core, never the reverse.
  • tessera-ui depends only on tessera-core, tessera-settings, and tessera-i18n.
  • tessera-app sits at the composition root. It wires tessera-core, tessera-backend-*, tessera-ui-*, tessera-config, tessera-worker, and tessera-mcp together.

Workspace crates (23 crates)

The Cargo workspace under crates/ is flat, with one crate per architectural boundary:

Layer Crate Responsibility
Domain tessera-core Pure tiling engine: built-in layouts, geometry, placements, workspaces, rules, overflow, backoff circuits, and Session reconciliation. Zero OS, GUI, YAML, or i18n dependencies.
Settings & Config tessera-settings Pure settings model: preferences, numeric bounds, defaults, shortcut grammar, and validation.
tessera-config YAML persistence (AppConfig), schema diagnostics (CONFIG_KEYS), unknown-key preservation, and atomic writes.
Localization tessera-i18n Embedded Fluent catalogs for 10 languages (en, pt-BR, es, fr, de, it, ru, zh-CN, ja, ko) and pure locale negotiation.
Backend Port tessera-backend Atomic capability facets, SessionDriver, BackendRegistry, EventQueue, deadline driver, and shared semantic contract suite (tessera_backend::contract).
tessera-backend-bridge Shared serde wire types (WireRect, Page, IpcFault) used by the GNOME and KWin IPC bridges.
Backend Adapters tessera-backend-x11 XFCE / X11 (xfwm4) adapter using EWMH, RandR, XKB, and XTest (the only crate using x11rb).
tessera-backend-gnome GNOME Shell Wayland IPC client over Unix socket with SO_PEERCRED and extension hash verification.
tessera-backend-kwin KDE Plasma Wayland KWin script IPC client over D-Bus and Unix socket with SHA-256 verification.
tessera-backend-macos macOS Accessibility (AXUIElement) and CoreGraphics adapter with event-tap hotkeys.
tessera-backend-windows Windows 11 Win32 (User32), DWM extended frame bounds, WinEvent hooks, and IVirtualDesktopManager.
UI Model & ABI tessera-ui Toolkit-neutral UI model: node trees, LayoutSpec solver, DrawnValues, semantic tokens, view models, provider traits, conformance suite, and tessera_ui_plugin_v1 C ABI.
UI Providers tessera-ui-gtk GTK 4 Preferences window, GtkLook seam, HUD overlay, and AT-SPI announcements (XFCE and GNOME base).
tessera-ui-adwaita Libadwaita look loaded at runtime via libloading for GNOME.
tessera-ui-plugin-gtk Shared library (cdylib) exporting GTK 4 and Libadwaita providers over tessera_ui_plugin_v1.
tessera-ui-qt Qt 6 / QML / Kirigami cdylib plugin for KDE Plasma.
tessera-ui-freedesktop Linux StatusNotifierItem tray (ksni), desktop notifications, and .desktop/systemd autostart.
tessera-ui-macos Native AppKit Preferences, NSStatusItem menu-bar icon, NSPanel HUD, and LaunchAgent autostart.
tessera-ui-windows Native WinUI 3 Preferences window plus Win32 tray, layered HUD, and Registry Run autostart.
Custom Layouts tessera-protocol Versioned (PROTOCOL_VERSION = 3) length-delimited JSON wire contract shared between tessera-app and tessera-worker.
tessera-worker Sandboxed QuickJS (rquickjs) sidecar process (tessera-layout-worker), confined with Landlock and seccomp on Linux and Seatbelt on macOS.
Integration tessera-mcp Embedded Model Context Protocol server (rmcp) over stdio and Unix sockets.
Composition Root tessera-app tessera binary: BackendId enum, static backend registration, src/platform* env/OS seam, CLI, daemon loop, and AppError.

Core design patterns

Cooperative tiling & the Session reconciliation loop

The tiling domain is a pure, deterministic state machine around tessera_core::model::Session. Session separates state into five concerns so observed truth never gets overwritten by optimistic assumptions:

  1. Observed state: windows, outputs, workspaces, active_window, observed_seq (ObsSeq), and validity (SessionValidity). Only Session::observe writes this half.
  2. User intent: intent (SessionIntent), which tracks pending user actions (focus, workspace switches, layout changes) awaiting confirmation in a future snapshot.
  3. Model: areas (BTreeMap<(WorkspaceId, OutputId), Area>) holding per-area window ranks, weights, BSP trees, and focus history, plus layouts (BTreeMap<LayoutSlot, SlotLayout>) and natural_sizes.
  4. Policy: policy: Arc<Policy>, replaced atomically on configuration reload or toggle. It governs margins, gaps, minimum sizes, layout memory, and window rules.
  5. Computed placements: Target Rect placements computed through one layout path (compute). Backend geometry requests, overflow checks, and diagnostic dumps all consume this output.

State transitions flow through a strict reducer and conciliation loop:

flowchart TD
    Tick["Backend tick (events + snapshot)"] --> Capture["FrameConciliation::capture"]
    Capture --> Observe["Session::observe (ObservedChange)"]
    Observe --> Command["apply_command(&mut Session, Command) -> Vec<Effect>"]
    Command --> Plan["FrameConciliation::plan_frames"]
    Plan --> Conciliate["LayoutConciliator::reconcile + Gate"]
    Conciliate --> Decision["Decision (released intents, corrections)"]
    Decision --> Execute["App::reconcile_now -> SessionDriver facets"]
    Execute -->|"Next tick / GeometryReconciled"| Settle["SettleOutcome -> LayoutConciliator::settle"]
    Settle -.->|"Next tick (unobserved_outcomes)"| Capture
  • Typed commands and effects: apply_command (crates/tessera-core/src/commands.rs) takes a Command and returns Vec<Effect>. tessera-core never performs I/O. tessera-app interprets each Effect against the active backend, UI, or worker.
  • Observed confirmation: A requested window move or resize counts as Applied only when a subsequent observed snapshot matches the requested geometry.

LayoutConciliator

LayoutConciliator (crates/tessera-core/src/conciliation/) decides which geometry and window-state requests reach the backend and when to stop asking. It runs with pure time: callers pass now: Instant into reconcile(observed, held, now) instead of reading a system clock.

  • Order ledger (BTreeMap<(WindowId, Slot), Ledger>): Each window holds at most one order per Slot (Frame, Iconify, Workspace). Order::Frame(Rect) represents a frame request, while StateOrder (Iconify, Workspace(WorkspaceId)) covers non-frame state requests.
  • Planned vs. one-off frames: plan_frames(&[Placement]) sets the full layout answer for the active workspace and drops planned orders for windows absent from placements. order_frame(window, frame) issues a one-off frame (such as moving a floating window to another output) that persists across plan_frames calls until satisfied or given up.
  • Monotonic generation counter: Every issued order receives a strictly increasing u64 generation. A stable refill also increments the generation so each give-up (GiveUp) reports at most once per generation.
  • Retry budget and refill (RetryPolicy): Defaults are max_attempts = 2 and settle_timeout = 500ms. After sending a request, the order waits up to settle_timeout before retrying. The budget refills to zero attempts only after the order stays satisfied or explained for at least settle_timeout.
  • Rearm backoff: When a frame order exhausts its budget, rearm_backoff waits before trying again. The wait starts at REARM_FLOOR (2s), doubles on each subsequent give-up, and caps at REARM_CEILING (30s).
  • Slow-client Gate: A window that applies requests later than late_threshold() (settle_timeout / 2) enters the slow set and holds its current space for up to hold() (settle_timeout * max_attempts * 2). Gate holds back due frame requests whose target overlaps a moving slow neighbor on the same workspace. If due windows form a mutual-swap cycle with no external blockers, Gate releases the whole cycle together.
  • Settlement and explains: SettleOutcome carries SettleStatus (Applied, Clamped, Rejected, Suppressed). explains(outcome, observed) returns true for a Clamped result whose size changed to observed, or a Rejected/Suppressed result matching observed. A Clamped frame that kept the requested size and only shifted position indicates window-manager displacement, such as a panel strut. It is not a minimum-size clamp, so it remains a divergence.
  • Reconciliation output: reconcile returns Reconciliation { corrections, divergences, explained, pending, give_up }. Correction lists requests to send now (RequestFrame, Iconify, MoveToWorkspace). Divergence records unmet orders (FrameMismatch, StillMapped, WrongWorkspace, Missing). GiveUp carries a GiveUpAction (Teach(SettleOutcome), Release(WindowIntentKind), or Announce).

FrameConciliation and wiring

FrameConciliation (crates/tessera-app/src/wiring/frame_conciliation/) bridges Session, LayoutConciliator, and tessera-app side effects (wiring/effects/conciliation.rs, wiring/events/reconcile.rs):

  • Per-output planned map: Stores the latest Vec<Placement> per OutputId on the active workspace. Switching workspaces clears planned, and unplugging an output drops its entries.
  • Ordered outcome capture (unobserved_outcomes): Synchronous or late SettleOutcome values that arrive after the last snapshot sit in unobserved_outcomes. FrameConciliation::capture drains them into LayoutConciliator::settle before updating observed from the fresh snapshot.
  • Single geometry executor (App::reconcile_now): App::reconcile_at gathers held_windows() (pointer drags and drop holds), calls FrameConciliation::reconcile, and receives Decision { released, corrections }. It drops released intents on Session, handles give-ups, and executes every Correction. This path is the only place in tessera-app that sends window geometry requests to the backend.
  • Window-limit iconify tracking (window_limit_iconified): LimitIconified tracks windows minimized for exceeding the window limit. minimize_over_limit issues StateOrder::Iconify once per stay over the limit so Tessera never fights a user who restores the window from the taskbar.
  • Membership diffing and relayout debt (owed): record_membership records the tiled window set on the active workspace. membership_differs detects when an inventory read adds or removes a tiled window. owe(RelayoutCause) records the earliest pending relayout reason (WindowTopology, OutputGeometry, WorkspaceChanged, Snapshot), and take_owed() pays that debt on the next observed tick.

Window decorations policy & restore

tessera-app/src/wiring/decorations/ manages window titlebars and borders according to the hide-tiled or keep preference:

  • Stateless recovery: At first sight, DecorationPolicy asks the backend to restore any non-tiled window. Windows carry their own restoration hints (mementos), so a fresh controller recovers windows left bare by a crashed session.
  • Partial restores: When a window is fullscreen or on another desktop without frame extents, the adapter returns OperationResult::Partial. Tessera keeps the window’s memento and finishes the restore when the window returns.
  • Settle & retry backoff: After hiding decorations, Tessera waits HIDE_SETTLE (500ms) before issuing another decoration change. Repeated failures use exponential backoff (RETRY_BASE = 1s, capped at RETRY_MAX_SHIFT = 6).
  • Batch restore on exit: On shutdown or preference toggle, DecorationFacet::restore_all restores all hidden and forgotten windows in one pass. Tessera then waits up to HIDE_SETTLE for pending frames.

Overflow & window limits

tessera-core/src/overflow.rs and tessera-core/src/window_limit.rs handle windows that do not fit their assigned layout or exceed the configured count:

  • Learned minimum sizes (LearnedMinimum): When a window manager clamps a frame below its target size, Tessera records the accepted width and height. The layout uses that floor to prevent overlapping neighbors.
  • Overflow actions (OverflowPolicy): When floors exceed the output area, Tessera applies MoveToOutput, Float, ShrinkNeighbors, or Minimize.
  • Window count limits (window_limit_range): When window_max_count is non-zero, Tessera minimizes excess windows. Paned layouts protect main panes (0..main_pane_count), and new_windows_to_main decides whether the oldest window sits at the front or back.

Window rules matching & precedence

tessera-core/src/rules.rs evaluates floating rules before tiling (see Rules):

  • Seven-step should_float precedence: should_float checks in this order: blacklist or whitelist, transient, modal, fixed size, small window, minimized or fullscreen or maximized, then NotFloating.
  • Sticky windows: Sticky windows stay visible on every workspace and never claim a tiling slot. Session excludes them from tiling without marking them as floating.
  • Identity & title matching: Rules match IdentityField values (WmClass, BundleId, ProcessName, AppUserModelId, AppId) using case-insensitive * globs. Optional window_titles entries match unanchored, case-sensitive regular expressions.

Runtime loop, WakeState, and DaemonNotifier

tessera-app drives the controller from crates/tessera-app/src/runtime/:

  • Poll tick order (poller.rs): Each tick runs in a fixed sequence:
    1. Drain pending SignalIntents (Reload or Shutdown).
    2. Reconcile backend events (Input::Tick). If next_deadline() is due, the session requests tick_fresh() instead of a cached tick(). poll_outcome treats an inventory-read failure as a failed poll even if event application returned Ok, preventing silent streak resets.
    3. Track consecutive failures against BACKEND_FAILURE_LIMIT (10). Reaching the limit calls stop_after_backend_failure, which restores window decorations and original frames via stop_controller, notifies the service manager, and stops the loop.
    4. Run queued tray actions (TrayAction).
    5. Show queued HUD feedback and desktop announcements.
    6. Mirror the updated tray menu model and handle quit or relaunch requests.
  • Wake-up state machine (wakeup/machine.rs): WakeState and wake_step decide when the loop sleeps or ticks with pure state transitions. HEARTBEAT (1s) bounds maximum sleep time so watchdog progress checks keep running. next_wake(tick_started, now, deadline) ignores deadlines at or before tick_started so a past deadline (such as a refused focus hover) never causes a busy spin. WakeState replaces timers and backend descriptor watches by incrementing monotonic u64 generations (WakeEvent::{Readable, WatchFailed, Deadline, Stop} -> WakeEffect::{Ignore, RunTick, EndWatch, FallBackToPoll, Release}).
  • Service manager lifecycle (daemon.rs): DaemonNotifier emits Notification::{Ready, Reloading, Watchdog, Stopping}. On Linux, it calls sd-notify (READY=1, RELOADING=1, WATCHDOG=1, STOPPING=1) and advances the watchdog only on real main-loop progress. On macOS and Windows, notifications are no-ops. ReadinessGate wraps ReadinessState (Pending, Declared) and ReadinessEvent (Layout, Sent, SendFailed) so READY=1 sends exactly once after the first successful layout pass.

Backend ports & adapters (tessera-backend)

Window-manager integration follows a strict Ports & Adapters architecture:

  • Static registration: BackendId (crates/tessera-app/src/platform/backend_id.rs) is a closed enum with one variant per adapter. Backends compile into tessera-app and register statically in BackendRegistry. There are no dynamic backend plugins. One active adapter serves each session, and unknown or unavailable backends fail explicitly without silent fallback.
  • Factory and driver lifecycle: Each adapter implements BackendFactory (id, serves, probe, open, open_inspection) and returns a Box<dyn SessionDriver>. probe() inspects the session without taking a WM role and returns Probe::available(OperationSet), Probe::available_degraded(...), or Probe::unavailable(UnavailableReason).
  • Atomic capability facets: SessionDriver (crates/tessera-backend/src/session.rs) requires only snapshot(), events(), and screen_space(). Every other capability (geometry_request, geometry_submit, window_maximize, window_focus_request, workspace_activation, output_enumeration, hotkey_register, decorations, picker, inspection, and others) is an optional facet accessor returning None by default. Missing operations return an explicit UnsupportedReason, never silent success.
  • Bounded EventQueue and resync: EventQueue<E> (crates/tessera-backend/src/events/queue.rs) enforces EVENT_QUEUE_LIMIT and pairs with ResyncTracker. High-rate event bursts evict deterministically and trigger a full snapshot resync instead of unbounded memory growth or silent state drift.
  • Circuit-breaker Backoff: tessera_core::backoff::Backoff and BackoffPolicy (FREE_FAILURES = 3, BASE_COOLDOWN = 100ms, MAX_COOLDOWN = 5s) govern retry cooldowns for failing helpers or repeated rejections. tessera-core never reads a wall clock. Time enters as an explicit Instant parameter.
  • Shared semantic contract suite: Every adapter runs against tessera_backend::contract. The suite exercises only the operations declared by probe() and verifies that effects appear in the snapshot or event stream.

Neutral UI peer architecture (tessera-ui)

tessera-ui owns every surface’s node tree, stable NodeIds, LayoutSpec solver, DrawnValues, semantic tokens, and state (PreferencesModel, UiModel). Native provider crates (tessera-ui-gtk, tessera-ui-adwaita, tessera-ui-qt, tessera-ui-macos, tessera-ui-windows, tessera-ui-freedesktop) act strictly as peers that map semantic names to native widgets and toolkit values.

On Linux, the tessera binary links no GUI toolkit at compile time. Instead, it loads libtessera_ui_plugin_gtk.so or libtessera_ui_plugin_qt.so at runtime over the tessera_ui_plugin_v1 C ABI (ABI_VERSION = 2). See UI Architecture for the full deep dive.

Sandboxed QuickJS custom layouts (tessera-protocol & tessera-worker)

User-supplied JavaScript layouts never run inside the tessera daemon process. Instead, tessera-app spawns tessera-layout-worker (tessera-worker) as an isolated sidecar process:

flowchart LR
    App["tessera-app"] -->|"stdin / stdout IPC (tessera-protocol v3)"| Worker["tessera-layout-worker (rquickjs)"]
    Worker -->|"Linux: PR_SET_NO_NEW_PRIVS + Landlock + seccomp-BPF"| Sandbox["OS Sandbox (macOS: Seatbelt)"]
  • Wire contract (tessera-protocol): Both processes communicate over length-delimited JSON frames versioned by PROTOCOL_VERSION (currently 3). Request and response DTOs use #[serde(deny_unknown_fields)] so stale or mismatched peers fail loudly with InvalidRequest instead of misinterpreting fields.
  • QuickJS runtime (rquickjs): tessera-worker evaluates custom layout scripts in an embedded QuickJS engine with no filesystem, network, process, or module-loader APIs. Strict execution-time and memory limits bound each evaluation.
  • OS sandboxing (tessera-worker/src/hardening.rs): Before reading any untrusted script or IPC frame, the worker drops ambient authority:
    • Linux: Applies PR_SET_NO_NEW_PRIVS, a best-effort Landlock ruleset, and a seccomp-BPF filter (seccomp + x32_guard). Up to ABI v9, Landlock denies filesystem read/write/exec, TCP bind/connect, and scopes abstract Unix sockets and signals where supported. The seccomp filter blocks socket creation, execve/execveat, SysV/POSIX IPC, cross-process signals, prlimit64 on other PIDs, path-based inode metadata calls, and tracing syscalls. Fails closed (SandboxUnavailable) if Landlock is NotEnforced or seccomp cannot be installed.
    • macOS: Applies a deny-all Seatbelt (sandbox_init) profile.

tessera-settings vs tessera-config split

Configuration splits across two crates to keep domain validation pure and YAML persistence isolated:

  • tessera-settings: Pure preferences model, numeric bounds, defaults, shortcut chord grammar, and typed validation. It has no YAML or filesystem dependencies. tessera-ui and tessera-core both depend on it.
  • tessera-config: Owns YAML serialization (serde-saphyr), AppConfig, CONFIG_KEYS schema diagnostics, unknown-key preservation, and atomic file writes. Preference keys (KeyKind::Preference) live verbatim in AppConfig::extra. Typed Preferences views read them so save_config preserves exact user spelling (such as integer vs float formatting). Round-trips keep comments and unknown keys intact.

Embedded MCP server (tessera-mcp)

tessera-mcp embeds a Model Context Protocol server (rmcp) supporting stdio and Unix domain socket transports:

  • Modes and allow-lists: Policy (crates/tessera-mcp/src/policy.rs) enforces Mode::ReadOnly (inspection and read tools/resources only) vs Mode::Control (layout and window mutations). An optional allow: Option<BTreeSet<String>> can only narrow, never widen, the active mode.
  • Peer authentication: On Unix sockets, tessera-mcp verifies every accepted connection using kernel SO_PEERCRED to ensure the connecting peer’s UID matches the daemon owner.
  • Two-tier rate limiting: TokenBucket (RateLimits::STANDARD from tessera_core::mcp) enforces both a per-connection local bucket and a listener-wide SharedLimiter ceiling that persists across reconnects.

Architectural boundaries

Workspace lints in clippy.toml and integration tests in crates/tessera-app/tests/ enforce strict isolation across all 23 crates:

  • Platform cfg isolation: Lint rules allow #[cfg(target_os = ...)], #[cfg(unix)], #[cfg(windows)], and OS conditionals only in crates/tessera-app/src/platform* and the adapter crates (tessera-backend-*, tessera-ui-*). Neutral crates receive tessera_ui::Platform as a value.
  • Environment isolation: std::env::var, var_os, vars, vars_os, and home_dir are forbidden by clippy.toml (disallowed_methods) outside tessera-app and adapter crates. The composition root reads configuration and paths and passes them down explicitly.
  • Unsafe isolation: Core, protocol, settings, config, backend-port, and i18n crates forbid unsafe (#![forbid(unsafe_code)] or #![deny(unsafe_code)]). In tessera-ui, lint rules allow unsafe only inside src/plugin/.
  • Typed errors: Ports and adapters define thiserror error enums and never return Result<_, String> or reference AppError. Only tessera-app converts domain and port errors into AppError and localizes them before showing them.
  • Internationalization: Every user-facing string lives in crates/tessera-i18n/i18n/<locale>/tessera.ftl across all 10 locales, verified by cargo test -p tessera-i18n --test locale_parity.