Diese Seite ist noch nicht übersetzt. Der folgende Text ist auf Englisch.
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-corehas zero OS, GUI, YAML, or i18n dependencies.tessera-backenddepends ontessera-core, never the reverse.tessera-uidepends only ontessera-core,tessera-settings, andtessera-i18n.tessera-appsits at the composition root. It wirestessera-core,tessera-backend-*,tessera-ui-*,tessera-config,tessera-worker, andtessera-mcptogether.
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:
- Observed state:
windows,outputs,workspaces,active_window,observed_seq(ObsSeq), andvalidity(SessionValidity). OnlySession::observewrites this half. - User intent:
intent(SessionIntent), which tracks pending user actions (focus, workspace switches, layout changes) awaiting confirmation in a future snapshot. - Model:
areas(BTreeMap<(WorkspaceId, OutputId), Area>) holding per-area window ranks, weights, BSP trees, and focus history, pluslayouts(BTreeMap<LayoutSlot, SlotLayout>) andnatural_sizes. - Policy:
policy: Arc<Policy>, replaced atomically on configuration reload or toggle. It governs margins, gaps, minimum sizes, layout memory, and window rules. - Computed placements: Target
Rectplacements 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 aCommandand returnsVec<Effect>.tessera-corenever performs I/O.tessera-appinterprets eachEffectagainst the active backend, UI, or worker. - Observed confirmation: A requested window move or resize counts as
Appliedonly 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 perSlot(Frame,Iconify,Workspace).Order::Frame(Rect)represents a frame request, whileStateOrder(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 fromplacements.order_frame(window, frame)issues a one-off frame (such as moving a floating window to another output) that persists acrossplan_framescalls until satisfied or given up. - Monotonic
generationcounter: Every issued order receives a strictly increasingu64generation. A stable refill also increments the generation so each give-up (GiveUp) reports at most once per generation. - Retry budget and refill (
RetryPolicy): Defaults aremax_attempts = 2andsettle_timeout = 500ms. After sending a request, the order waits up tosettle_timeoutbefore retrying. The budget refills to zero attempts only after the order stays satisfied or explained for at leastsettle_timeout. - Rearm backoff: When a frame order exhausts its budget,
rearm_backoffwaits before trying again. The wait starts atREARM_FLOOR(2s), doubles on each subsequent give-up, and caps atREARM_CEILING(30s). - Slow-client
Gate: A window that applies requests later thanlate_threshold()(settle_timeout / 2) enters theslowset and holds its current space for up tohold()(settle_timeout * max_attempts * 2).Gateholds 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,Gatereleases the whole cycle together. - Settlement and
explains:SettleOutcomecarriesSettleStatus(Applied,Clamped,Rejected,Suppressed).explains(outcome, observed)returnstruefor aClampedresult whose size changed toobserved, or aRejected/Suppressedresult matchingobserved. AClampedframe 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:
reconcilereturnsReconciliation { corrections, divergences, explained, pending, give_up }.Correctionlists requests to send now (RequestFrame,Iconify,MoveToWorkspace).Divergencerecords unmet orders (FrameMismatch,StillMapped,WrongWorkspace,Missing).GiveUpcarries aGiveUpAction(Teach(SettleOutcome),Release(WindowIntentKind), orAnnounce).
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
plannedmap: Stores the latestVec<Placement>perOutputIdon the active workspace. Switching workspaces clearsplanned, and unplugging an output drops its entries. - Ordered outcome capture (
unobserved_outcomes): Synchronous or lateSettleOutcomevalues that arrive after the last snapshot sit inunobserved_outcomes.FrameConciliation::capturedrains them intoLayoutConciliator::settlebefore updatingobservedfrom the fresh snapshot. - Single geometry executor (
App::reconcile_now):App::reconcile_atgathersheld_windows()(pointer drags and drop holds), callsFrameConciliation::reconcile, and receivesDecision { released, corrections }. It drops released intents onSession, handles give-ups, and executes everyCorrection. This path is the only place intessera-appthat sends window geometry requests to the backend. - Window-limit iconify tracking (
window_limit_iconified):LimitIconifiedtracks windows minimized for exceeding the window limit.minimize_over_limitissuesStateOrder::Iconifyonce 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_membershiprecords the tiled window set on the active workspace.membership_differsdetects when an inventory read adds or removes a tiled window.owe(RelayoutCause)records the earliest pending relayout reason (WindowTopology,OutputGeometry,WorkspaceChanged,Snapshot), andtake_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,
DecorationPolicyasks 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 atRETRY_MAX_SHIFT = 6). - Batch restore on exit: On shutdown or preference toggle,
DecorationFacet::restore_allrestores all hidden and forgotten windows in one pass. Tessera then waits up toHIDE_SETTLEfor 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 acceptedwidthandheight. The layout uses that floor to prevent overlapping neighbors. - Overflow actions (
OverflowPolicy): When floors exceed the output area, Tessera appliesMoveToOutput,Float,ShrinkNeighbors, orMinimize. - Window count limits (
window_limit_range): Whenwindow_max_countis non-zero, Tessera minimizes excess windows. Paned layouts protect main panes (0..main_pane_count), andnew_windows_to_maindecides 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_floatprecedence:should_floatchecks in this order: blacklist or whitelist, transient, modal, fixed size, small window, minimized or fullscreen or maximized, thenNotFloating. - Sticky windows: Sticky windows stay visible on every workspace and never claim a tiling slot.
Sessionexcludes them from tiling without marking them as floating. - Identity & title matching: Rules match
IdentityFieldvalues (WmClass,BundleId,ProcessName,AppUserModelId,AppId) using case-insensitive*globs. Optionalwindow_titlesentries 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:- Drain pending
SignalIntents (ReloadorShutdown). - Reconcile backend events (
Input::Tick). Ifnext_deadline()is due, the session requeststick_fresh()instead of a cachedtick().poll_outcometreats an inventory-read failure as a failed poll even if event application returnedOk, preventing silent streak resets. - Track consecutive failures against
BACKEND_FAILURE_LIMIT(10). Reaching the limit callsstop_after_backend_failure, which restores window decorations and original frames viastop_controller, notifies the service manager, and stops the loop. - Run queued tray actions (
TrayAction). - Show queued HUD feedback and desktop announcements.
- Mirror the updated tray menu model and handle quit or relaunch requests.
- Drain pending
- Wake-up state machine (
wakeup/machine.rs):WakeStateandwake_stepdecide 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 beforetick_startedso a past deadline (such as a refused focus hover) never causes a busy spin.WakeStatereplaces timers and backend descriptor watches by incrementing monotonicu64generations (WakeEvent::{Readable, WatchFailed, Deadline, Stop}->WakeEffect::{Ignore, RunTick, EndWatch, FallBackToPoll, Release}). - Service manager lifecycle (
daemon.rs):DaemonNotifieremitsNotification::{Ready, Reloading, Watchdog, Stopping}. On Linux, it callssd-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.ReadinessGatewrapsReadinessState(Pending,Declared) andReadinessEvent(Layout,Sent,SendFailed) soREADY=1sends 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 intotessera-appand register statically inBackendRegistry. 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 aBox<dyn SessionDriver>.probe()inspects the session without taking a WM role and returnsProbe::available(OperationSet),Probe::available_degraded(...), orProbe::unavailable(UnavailableReason). - Atomic capability facets:
SessionDriver(crates/tessera-backend/src/session.rs) requires onlysnapshot(),events(), andscreen_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 returningNoneby default. Missing operations return an explicitUnsupportedReason, never silent success. - Bounded
EventQueueand resync:EventQueue<E>(crates/tessera-backend/src/events/queue.rs) enforcesEVENT_QUEUE_LIMITand pairs withResyncTracker. 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::BackoffandBackoffPolicy(FREE_FAILURES = 3,BASE_COOLDOWN = 100ms,MAX_COOLDOWN = 5s) govern retry cooldowns for failing helpers or repeated rejections.tessera-corenever reads a wall clock. Time enters as an explicitInstantparameter. - Shared semantic contract suite: Every adapter runs against
tessera_backend::contract. The suite exercises only the operations declared byprobe()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 byPROTOCOL_VERSION(currently3). Request and response DTOs use#[serde(deny_unknown_fields)]so stale or mismatched peers fail loudly withInvalidRequestinstead of misinterpreting fields. - QuickJS runtime (
rquickjs):tessera-workerevaluates 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,prlimit64on other PIDs, path-based inode metadata calls, and tracing syscalls. Fails closed (SandboxUnavailable) if Landlock isNotEnforcedor seccomp cannot be installed. - macOS: Applies a deny-all Seatbelt (
sandbox_init) profile.
- Linux: Applies
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-uiandtessera-coreboth depend on it.tessera-config: Owns YAML serialization (serde-saphyr),AppConfig,CONFIG_KEYSschema diagnostics, unknown-key preservation, and atomic file writes. Preference keys (KeyKind::Preference) live verbatim inAppConfig::extra. TypedPreferencesviews read them sosave_configpreserves 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) enforcesMode::ReadOnly(inspection and read tools/resources only) vsMode::Control(layout and window mutations). An optionalallow: Option<BTreeSet<String>>can only narrow, never widen, the active mode. - Peer authentication: On Unix sockets,
tessera-mcpverifies every accepted connection using kernelSO_PEERCREDto ensure the connecting peer’s UID matches the daemon owner. - Two-tier rate limiting:
TokenBucket(RateLimits::STANDARDfromtessera_core::mcp) enforces both a per-connectionlocalbucket and a listener-wideSharedLimiterceiling 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
cfgisolation: Lint rules allow#[cfg(target_os = ...)],#[cfg(unix)],#[cfg(windows)], and OS conditionals only incrates/tessera-app/src/platform*and the adapter crates (tessera-backend-*,tessera-ui-*). Neutral crates receivetessera_ui::Platformas a value. - Environment isolation:
std::env::var,var_os,vars,vars_os, andhome_dirare forbidden byclippy.toml(disallowed_methods) outsidetessera-appand 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)]). Intessera-ui, lint rules allowunsafeonly insidesrc/plugin/. - Typed errors: Ports and adapters define
thiserrorerror enums and never returnResult<_, String>or referenceAppError. Onlytessera-appconverts domain and port errors intoAppErrorand localizes them before showing them. - Internationalization: Every user-facing string lives in
crates/tessera-i18n/i18n/<locale>/tessera.ftlacross all 10 locales, verified bycargo test -p tessera-i18n --test locale_parity.