Lutra/docs/architecture.md
danny 55acb0dffb M0.5: Tauri desktop shell with themed main window
The window is built in setup with the theme tokens injected by an
initialization script and the background colour taken from the theme, so
the first frame is already themed. Frontend IPC (engine_execute,
engine_list_commands) and the control channel both run commands through
the Host, which applies effects such as Quit. ui.screenshot captures the
window's client area from the screen because xcap skips windows of its own
process. build.rs generates the placeholder icon into the gitignored
icons/ directory. Verified on Windows: window opens, ping, listCommands,
screenshot, app.quit, and exit status 1 when the control port is taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:39:49 +02:00

8.2 KiB
Raw Blame History

Architecture

Status: M0 decisions recorded · Last updated: 2026-10-14

Overview

apps/lutra-desktop  (L6)  Tauri 2 shell: windows, menus, IPC bridge to the engine
ui/                 (L6)  Vue 3 + TypeScript + Vite frontend, Pinia, CodeMirror 6
apps/lutra-cli      (L5)  the `lutra` command: open, diff, --wait, mcp, perf, bench
crates/control      (L5)  JSON-lines control channel (--control PORT)
crates/mcp          (L5)  MCP server over stdio
crates/engine       (L4)  command registry, workspace state, guard, recovery journal, theme tokens
crates/lsp          (L3)  LSP client (Phpactor first), later DAP client
crates/terminal     (L3)  pseudo-terminal sessions (portable-pty)
crates/index        (L2)  symbol index, usages, later type inference
crates/vfs          (L2)  project model, file watching, ignore rules, encodings
crates/search       (L2)  find in files (ignore + grep-searcher crates)
crates/syntax       (L1)  tree-sitter parsing (PHP first), outlines, highlight tokens
crates/text         (L0)  rope buffer, positions, UTF-8/UTF-16 conversion, edits
crates/testkit      (—)   test helpers and fixtures, tests only
xtask               (—)   ci, layers, assets, cleanroom, dev, fixtures, lints-selftest, ui-licences

Each crate declares its layer in its manifest:

[package.metadata.lutra]
layer = 4        # or "tool" for testkit and xtask

cargo xtask layers reads cargo metadata and fails when

  • a crate has no layer;
  • a normal or build dependency points to a workspace crate of the same or a higher layer;
  • a crate with a numeric layer has a tool crate (testkit, xtask) as a normal or build dependency (dev-dependencies are fine);
  • a crate below L6 reaches a tauri or tauri-* package through its normal dependencies, directly or transitively.

Commands

Every user-visible action is a command: id, label, menu_path, default_shortcut, params (documented schema), enabled(&State) -> bool, run(&mut State, Params) -> Result<Output, EngineError>. Menus, the palette, keymaps, the CLI, the control channel and MCP all call the registry. Long-running commands report progress and can be cancelled.

As built in M0:

  • lutra_engine::Command is a trait with spec(), enabled() and run(). spec() returns a CommandSpec with the static metadata. Params and results are serde_json::Value; each command documents its params in CommandSpec::params.
  • Engine::execute(id, params) looks the command up, checks enabled, runs it inside the guard and returns an Outcome { value, effects }.
  • Effects are requests the engine cannot fulfil below L6 (Effect::Quit so far). The host (desktop, tests) applies them after the command returns. Commands never call into Tauri.
  • EngineError has a stable string code() (unknown_command, disabled, invalid_params, failed, internal) used by the control channel and the frontend.
  • Shortcut notation: Mod is Ctrl on Windows and Linux and Cmd on macOS (Mod+Q). Default shortcuts are Lutra's own.

Guard

lutra_engine::guard::run wraps a closure in std::panic::catch_unwind and turns a panic into EngineError::Internal. Release builds keep panic = "unwind" for this reason; panic = "abort" is never set. The engine is held in a Mutex by the hosts; because the guard runs inside the lock, a panicking command never poisons it, and hosts still recover a poisoned lock with into_inner instead of unwrapping.

Control channel

--control PORT binds 127.0.0.1:PORT only. If binding fails, the desktop app prints the error and exits with status 1.

  • Transport: one JSON object per line, UTF-8, at most 16 MiB per line; longer lines get an error response and the connection is closed.
  • Request: {"id": <number|string>, "method": "<name>", "params": {...}}. Response: {"id": ..., "result": ...} or {"id": ..., "error": {"code": "...", "message": "..."}}. A line that is not valid JSON gets an error response with "id": null.
  • Methods (M0): app.ping, engine.execute {command, params}, engine.listCommands, ui.screenshot {path}.
  • lutra_control defines a Backend trait; the desktop app implements it (engine access, effects, screenshots), tests implement it with a bare engine. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate.
  • Screenshots: xcap does not enumerate windows of its own process (querying their titles can deadlock), so the desktop focuses its main window, reads the client area's physical position and size from Tauri and captures that region of the monitor with xcap::Monitor::capture_region. Windows covering Lutra at that moment appear in the image. A webview-native capture (WebView2 CapturePreview, WKWebView snapshots) can replace it later.

Frontend ↔ engine

The frontend calls run(id, params) over Tauri IPC (engine_execute, engine_list_commands) and subscribes to state events (open buffers, diagnostics, tree changes). Buffer contents live in the engine; CodeMirror sends edits as transactions and receives authoritative changes back.

Theme tokens are defined in Rust (lutra_engine::theme) and rendered as CSS custom properties (--lt-*). The desktop injects them with the window's initialization script, so the first frame is already themed and the frontend needs no round trip. Components use only var(--lt-…).

Decisions (M0)

Question Decision Why
Highlighting A Lezer grammar (@lezer/php, MIT) in CodeMirror highlights instantly on the UI thread. tree-sitter in crates/syntax stays the structural source (outline, folding, index) and later adds semantic tokens on top. The keystroke-to-highlight budget (< 16 ms) leaves no room for an IPC round trip per keystroke; Lezer is incremental inside CodeMirror. tree-sitter gives the core one parser for every structural feature.
Git library gix (MIT OR Apache-2.0) for reading: status, log, diff, blame, refs. Writes the library doesn't cover well (push, pull, rebase, merge, hooks, signing) run the user's git executable. git2/libgit2 is not used. gix is pure Rust and permissively licensed; libgit2 is GPL-2.0 with a linking exception, outside the permitted licences. Shelling out for writes keeps the user's hooks, credential helpers and config working.
Terminal portable-pty (MIT) in the new L3 crate crates/terminal; xterm.js (MIT) renders in the frontend. Output is streamed as events, input goes through commands. ConPTY on Windows and Unix PTYs behind one API; xterm.js is the standard web terminal. A separate crate keeps PTY code out of the engine.
Text buffer ropey (MIT) in crates/text. Mature rope with line and UTF-16 helpers.
Clippy panic lints unwrap_used, expect_used, panic, unreachable, todo, unimplemented, indexing_slicing, string_slice are denied workspace-wide; clippy.toml allows them in #[test]/#[cfg(test)]; integration tests in tests/ and testkit allow them at crate level. missing_docs is denied too, to back the doc-comment code style. unsafe_code is denied; a crate that needs it allows it locally with a doc comment saying why. AGENTS.md › Never crash.
Desktop dev mode Plain cargo build/cargo run -p lutra-desktop is a Tauri dev build that loads the Vite dev server. cargo xtask dev [-- ARGS] starts both. A self-contained build embeds ui/dist through the bundled-ui feature. Keeps cargo build --workspace independent of the frontend build.
App identifier dev.lutra.desktop is a placeholder. The final reverse-DNS identifier depends on the project's domain and hosting, which are the owner's decision (execution plan §4); bundling stays off until then. Tauri requires an identifier to build.
App icon A placeholder (rounded otter-brown square with a pale stone) is generated by apps/lutra-desktop/build.rs into the gitignored apps/lutra-desktop/icons/. The real icon is the owner's to commission; ASSETS.md allows generated-in-code art.

Revision history

Date Change Summary
2026-10-14 minor Screenshot method, placeholder app identifier
2026-10-13 major M0: layers metadata, command and guard design, control protocol, open questions decided
2026-10-13 major Initial draft