# Architecture > **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1) · **Last updated:** 2026-10-25 ## 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 (L6) the `lutra` command: open, --wait, mcp; later diff, perf, bench crates/control (L5) JSON-lines control channel (--control PORT) crates/mcp (L5) MCP server over stdio (the CLI supplies the connection) 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/vcs (L3) Git through the installed git command 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/proc (L0) child processes that die with Lutra (job objects, process groups) 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: ```toml [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`. 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, events }`. Commands queue events with `State::emit`; the engine moves them into the outcome. Events queued by a command that then fails stay queued and arrive with the next outcome, `Engine::pump_vfs` or `Engine::take_events`. - 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()` used by the control channel and the frontend: `unknown_command`, `disabled` (e.g. a file command without a project), `invalid_params`, `stale_version` (a `buffer.edit` based on an old version), `unsaved_changes` (closing a dirty buffer or project without `force`), `failed`, `internal`. - Shortcut notation: `Mod` is Ctrl on Windows and Linux and Cmd on macOS (`Mod+Q`). Default shortcuts are Lutra's own. - UI commands (M1.8) are the frontend's own commands, listed next to the engine's; see UI commands, palette and keymap below. ## 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": , "method": "", "params": {...}}`. Response: `{"id": ..., "result": ...}` or `{"id": ..., "error": {"code": "...", "message": "..."}}`. A line that is not valid JSON gets an error response with `"id": null`. - Methods: `app.ping`, `app.auth {token}`, `app.focus`, `engine.execute {command, params}`, `engine.listCommands`, `ui.screenshot {path}`, `events.subscribe`. Names and docs live in `crates/control/src/methods.rs`. - `events.subscribe` answers `{subscribed: true}` and from then on writes `{"event": {...}}` lines for every engine event on that connection, between responses; a shared writer writes each line whole. Subscribing twice is a no-op. Each subscriber has a queue of 4096 events (`lutra_control::EVENT_QUEUE`); a subscriber that falls behind or disconnects is dropped by `Subscribers::publish`, and the connection gets a final `{"event": {"kind": "subscriptionLost"}}` line if it is still open. - `lutra_control` defines a `Backend` trait; the desktop app implements it (engine access, effects, screenshots, event subscribers), tests implement it with a bare engine (`lutra_testkit::EngineBackend`). Hosts publish each outcome's events through `lutra_control::Subscribers`. 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. ### CLI and single instance (M3.7) - **Rendezvous file:** a desktop that owns the single instance serves a second, token-protected control listener on a free port of `127.0.0.1` (`lutra_control::start_with_token`) and writes `/instance.json` = `{port, token, pid, version}` (`lutra_control::rendezvous`). The token is 32 bytes from the OS generator (`getrandom`), hex. The file is written to a temporary file and renamed, so readers never see half a file; on exit the app removes it if it still holds its own token. - **Directory:** `LUTRA_RENDEZVOUS_DIR` if set, else `rendezvous::default_data_dir()`, which computes Tauri's `app_data_dir()` for the identifier `dev.lutra.desktop` without Tauri (`%APPDATA%\dev.lutra.desktop` on Windows, `~/Library/Application Support/dev.lutra.desktop` on macOS, `$XDG_DATA_HOME` or `~/.local/share` + the identifier elsewhere), so the CLI and the desktop agree without sharing a runtime. - **Security:** only the user may read the token. Unix: the file is created with mode `0600`. Windows: it lives in the user's roaming AppData folder, whose inherited ACL grants the user, `SYSTEM` and Administrators only (checked with `icacls` in the M3.7 live check); Lutra sets no ACL of its own. Both listeners bind `127.0.0.1` only. On the token listener the first request must be `app.auth {token}` within 10 s (`AUTH_TIMEOUT`); a wrong token, another method or garbage gets `unauthorized` and the connection is closed. Tokens are compared in constant time. The `--control PORT` listener stays open (no token) for development and agents; it is opt-in and documented as such. - **Second start:** `lutra-desktop [PATH]` without `--control` reads the rendezvous file first. If the listener answers, accepts the token and pings, the start forwards `PATH` (folder → `project.open`, file → `file.open`), calls `app.focus` and exits 0. If the file is missing, unreadable, invalid, or its port refuses or rejects the token, it is stale: this start becomes the instance and replaces the file. Two starts in the same instant can both become instances; the later file wins (accepted, rare). - **Development instances:** a start with `--control PORT` skips the single instance (no forwarding, no rendezvous file) so parallel agents' instances never forward to each other, unless `LUTRA_RENDEZVOUS_DIR` is set, which opts it into the single instance in that directory (used for isolated live checks). - **Data directory isolation (H6):** `lutra-desktop --data-dir DIR` or `LUTRA_DATA_DIR=DIR` makes an isolated instance (`apps/lutra-desktop/src/datadir.rs`): `EngineConfig { config_dir: DIR, data_dir: DIR }` (settings, `recovery/`), the rendezvous file in `DIR`, and the webview's own data in `DIR/webview` (`WebviewWindowBuilder::data_directory`, the WebView2 user data folder, so local storage is separate too). `--control PORT` without either uses `/lutra-control//`, kept between runs. The managed tools stay shared: `Engine::share_tools_from(user app_data_dir)` makes the toolchain look for (and, only if missing, download) `tools/phpactor//` there, SHA-256 checked as before. Rendezvous order: `LUTRA_RENDEZVOUS_DIR` if set; else none for `--control`; else the isolated directory; else the default. `rendezvous::dir()` (CLI, `lutra mcp`) honours `LUTRA_DATA_DIR` after `LUTRA_RENDEZVOUS_DIR`, so `lutra` finds an isolated instance started with the same environment. An isolated instance therefore never forwards to, or registers as, the user's main instance. - **New methods:** `app.auth {token}` (always succeeds on the open listener) and `app.focus` (restore, show and focus the main window; `focus_failed` without a window; `Backend::focus` has a default that fails, so test backends need no change). - **`lutra` CLI** (`apps/lutra-cli`, binary `lutra`, now L6 so it can use `lutra-control`): `lutra [--wait] [PATH[:LINE[:COLUMN]]]...`. - **Targets:** up to two trailing `:N` groups are a 1-based line and column (`N` all digits, something before it; on Windows a lone drive letter is never split). If the path part does not exist but the whole argument does, the argument is the path. Paths are made absolute against the current directory without resolving symlinks. - **Opening:** a folder (at most one, no position) → `project.open`. A file → `file.open`; with no project open its parent folder is opened first. **A file outside the open project is refused** (exit 1, the engine's `… is outside the project`), because Lutra has one window and replacing the project behind the user's back could lose their context; out-of-project buffers are a gap (G7). A line → `editor.reveal {path, line-1, column-1}`, retried for up to 20 s while the window has not registered its UI commands yet (`unknown_command`). - **Starting Lutra:** if no instance answers, the CLI starts the desktop detached (`LUTRA_DESKTOP`, else `lutra-desktop` next to `lutra`, else on `PATH`) and polls the rendezvous file for up to 60 s. - **`--wait`:** subscribes before opening, then blocks until every opened file's `bufferClosed` arrived (or `projectClosed`, or the connection ends because Lutra quit). A `subscriptionLost` renews the subscription and checks the remaining ids with `buffer.get`. Folders are not waited for. - **Exit codes:** 0 ok, 1 error (cannot start, open failed, missing path), 2 bad usage (unknown option, line or column 0 or too big, two folders, a positioned folder, non-Unicode argument). Arguments are untrusted; parsing is property-tested. - **Rendezvous API for M3.8 (`lutra mcp`):** `lutra_control::client::connect_live(&rendezvous::dir()?, timeout)` returns the `Instance` and an authenticated `Client`; `Client::request(method, params)`, `execute(command, params)`, `subscribe()`, `next_event(timeout)` (events read while waiting for a response are queued, at most 4096), `open_folder`, `open_file`, `reveal`, `focus`. Response lines are capped at 64 MiB. `lutra mcp` (M3.8) uses this API from the CLI, so the CLI's `launch` logic stayed in the CLI. ### MCP server (M3.8) - **Shape:** `crates/mcp` (L5) holds the protocol, the tools and the event buffer but opens no sockets and starts no processes; it reaches Lutra through the `lutra_mcp::Connector` / `Connection` traits (`request(method, params)`, `next_event(timeout)`). `lutra mcp` in `apps/lutra-cli` (L6) implements them with `lutra_control::client`: the rendezvous file and token by default (starting Lutra like `lutra PATH` when none runs), `--port PORT` for an open `--control` channel, `--no-start` to never start Lutra. Register it with `claude mcp add lutra -- lutra mcp`. No SDK: the official Rust SDK brings an async runtime and schema generators, and the protocol needed here is small. - **Transport:** stdio, one JSON-RPC 2.0 message per line (UTF-8, at most 16 MiB; a longer or non-UTF-8 line gets a parse error and the next line is read). Batches are rejected. stdout carries only MCP messages; the server exits 0 when stdin closes. Every request runs under `lutra_engine::guard`. - **Protocol versions (dual era):** modern **2026-07-28** (stateless: each request carries `_meta` `io.modelcontextprotocol/protocolVersion` and `io.modelcontextprotocol/clientCapabilities`; `server/discover`; results get `resultType: "complete"` and `_meta` `io.modelcontextprotocol/serverInfo`; another version gets `-32022` with `data {supported, requested}`, missing capabilities `-32602`) and legacy **2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05** through `initialize` (the client's version if known, else 2025-11-25). Only the handshake and the result decoration differ; both eras share every method and tool. A request with neither `_meta` nor a prior `initialize` is served with legacy shapes. - **Methods:** `server/discover`, `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list` (empty). Notifications are accepted silently; any other method is `-32601`. Capabilities: `tools {listChanged: false}`, `resources {}` (no subscriptions yet). Lists come whole (a cursor is ignored). - **Tools (D16):** - `list_commands {filter?, enabledOnly?}`: `engine.listCommands` (id, label, menu path, shortcut, params doc, enabled, ui). - `execute_command {command, params?, confirm?}`: `engine.execute` for every engine and UI command. **`app.quit` is refused with `confirmation_required` unless `confirm: true`.** - `screenshot {path?}`: `ui.screenshot` into a temporary file (deleted afterwards) or `path`, returned as `image/png` content; at most 32 MiB, PNG signature checked. - `read_buffer {path | id}`: the current text with unsaved changes plus `{id, path, version, dirty, lineEnding, truncated}`; a project-relative or absolute path inside the project; cut at 4 MiB. - `get_events {since?, max?, kinds?, waitMs?}`: see Events below. - Results carry `structuredContent` and the same JSON as text. Bad arguments, engine errors and an unreachable Lutra are tool errors (`isError: true`, text `code: message`, `structuredContent.error {code, message}`) with the engine's code, or `invalid_params`, `confirmation_required`, `not_open`, `screenshot_failed`, `unavailable`. An unknown tool is `-32602`. - **Events:** the first connection starts a pump thread with its own subscribed connection (`events.subscribe`). It keeps the last 1000 events in a ring, numbered by a growing `seq`, each capped at 16 KiB (a bigger one keeps only `kind` and `truncated: true`). `get_events` returns the events after `since` (default 100, at most 1000, optionally only `kinds`, optionally waiting up to `waitMs` ≤ 30 s), `latest` to pass as `since` next time, `missed` when the ring dropped events after `since` or the subscription was down, and `subscribed`. A lost subscription reconnects every 0.5 s without starting Lutra. Events from before the first connection are not seen. - **Resources:** one per open buffer (`buffer.list`), URI `lutra://buffer/` with every byte outside the RFC 3986 unreserved set (except `/`) percent-encoded, a MIME type from the extension, and a description for unsaved changes. `resources/read` returns the text with unsaved changes; an unknown or closed buffer is `-32602` with `data {uri}`, an unreachable Lutra `-32603`. - **Connection:** made on the first call that needs Lutra (listing tools never starts it) and pinged (`app.ping`) before each use; a dead one is replaced, which starts Lutra again if it quit. - **Tests:** JSON-RPC and protocol units, a proptest fuzz of message lines and tool arguments (no panic, exactly one valid response line), integration against `lutra_testkit::EngineBackend` behind a real token listener (`crates/mcp/tests/tcp.rs`), and the `lutra mcp` binary on stdio (`apps/lutra-cli/tests/mcp.rs`). ## Frontend ↔ engine The frontend calls `run(id, params)` over Tauri IPC (`engine_execute`, `engine_list_commands`) and subscribes to state events. 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 the stored theme 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-…)`; switching is described under Themes. ### Workspace (M1.3) - `State` holds `project: Option` (the `lutra_vfs::Project`, its watcher and the watched directories) and `buffers` (id → `OpenBuffer { buffer: lutra_text::Buffer, path, version, saved_version, bom }`). A buffer is dirty when `version != saved_version`. Ids are never reused. - Commands: `project.open {path, force?}`, `project.close {force?}`, `project.children {dir?}`, `file.open {path}` (returns the existing buffer if the file is already open), `buffer.get {id}`, `buffer.edit {id, baseVersion, edits}`, `file.save {id}` (`Mod+S`), `file.saveAll {skipConflicts?}` (`Mod+Alt+S`; see Autosave), `buffer.close {id, force?}`, `buffer.list` (M3.8: `[{id, path, version, dirty}]` without text, empty without a project). Everything except `project.open` and `buffer.list` is disabled without a project. Paths are project-relative with `/`; absolute paths are accepted when they lie inside the project; `..` escapes are rejected by the VFS. - Edit protocol: `edits` are `{from, to, insert}` in UTF-16 code units, all relative to the text at `baseVersion` (CodeMirror change-set semantics), non-overlapping, applied atomically. A `baseVersion` other than the current version fails with `stale_version` and changes nothing; the client refetches with `buffer.get` and reapplies its pending changes. Each successful batch increments the version by one. Limits: 100,000 edits and 64 MiB inserted per call. - Saving writes `Buffer::save_text` (the file's dominant line ending) atomically through the VFS and keeps a UTF-8 byte order mark. ### Events `lutra_engine::Event`, serialised as `{"kind": "", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab. Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump. Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. The parent directory of every open buffer is pinned (M1.13, `workspace::sync_buffer_dirs`, run by `Engine::execute` after every command): it is watched even if the tree never listed it, so reloads and `fileChangedOnDisk` arrive for files opened by path from never-expanded folders. Pinned directories count against the cap but are never evicted while a buffer in them is open (with more pinned directories than the cap, the watched set exceeds it); after the last buffer in a directory closes, it ages out like a listed one. A buffer inside an ignored or hidden directory is still not watched. ### Desktop bridge (M1.4) - The desktop host publishes every event, from commands and from its pump thread, to control channel subscribers and to the window as the Tauri event `engine://event` with the engine `Event` as payload. Events are published while the engine lock is held, so their order is the engine's order. - `ui/src/ipc.ts` exposes `onEngineEvent(handler) => unsubscribe` with the typed union `EngineEventPayload`. Once the subscriptions started together (all of them while the page mounts) are registered, `ipc.ts` calls the IPC command `engine_ready` once; the host then replays `projectOpened` and `bufferOpened` for the current state, followed by the notifications and `watchFailed` events published before (M1.12), to the window only. A project opened from the command line (`lutra-desktop --control 7979 PATH`) or before a page reload therefore still reaches the UI. - `project.openDialog` returns `Effect::PickFolder`; the host shows the native folder picker (`tauri-plugin-dialog`, from Rust, non-blocking) and runs `project.open` with the choice. At most one picker is open; cancelling does nothing. A folder that cannot be opened becomes a `notification` (M1.12): `unsaved_changes` a warning, anything else an error. - Capabilities: the main window may only listen to and unlisten from events (`core:event:allow-listen`, `core:event:allow-unlisten`). Engine commands are app commands and need no permission; the dialog plugin is used from Rust only, so the frontend gets no dialog permission. - Contract fix: the project UI from M1.5 was written against assumed shapes. `ui/src/components/project/engineEvents.ts` is now the adapter between the engine contract and the UI types: `toProjectEvent` translates `{kind: "projectOpened", root, name}` and friends into the store's events, and `toTreeEntries` translates `project.children`'s `{dir, entries: [{name, path, kind: file|directory|other, ignored, role}], truncated}` into tree entries (`kind: dir|file`, `role`, `excluded`, `special` for `other`) plus `truncated`. Malformed entries are skipped; a result without `entries` becomes an `ipc` error on the directory. ### Tabs and editor (M1.6) - `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them. - One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text. - Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table. - Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits. - Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Since M3.10 changes are also saved automatically (see Autosave). - Theme: the editor reads colours only from `--lt-*` tokens, including the editor tokens from M1.10 (selection, active line, cursor, gutter, match, editor font size); no fallbacks remain. ### Highlighting and editor.reveal (M2.2) - **Languages:** `ui/src/components/editor/language.ts` picks a language once per tab from the file extension (`languageOf`): PHP (`php`, `phtml`, `inc`, `php3`–`php8`, `phps`) through `@codemirror/lang-php`, whose Lezer grammar also parses the HTML, CSS and JavaScript around `` blocks; HTML, CSS, JavaScript/TypeScript (with JSX), JSON, YAML and Markdown through their `@codemirror/lang-*` packages (all MIT). Other files stay plain text. The editor store passes the tab's path to `editorExtensions(path)` when it creates the tab's state. - **Colours:** the highlighter is a `tagHighlighter` that only sets classes: a span gets `lt-syntax-` for one of the eleven tokens `keyword`, `string`, `number`, `comment`, `variable`, `function`, `type`, `constant`, `tag`, `attribute`, `operator`. The editor theme (`extensions.ts`) colours each class with its `--lt-syntax-` variable. Lezer tags that are not mapped fall back to their parent tag (`controlKeyword` → `keyword`); tags without a mapped ancestor (punctuation, plain names such as the class after `extends`) keep `--lt-fg`. CodeMirror's default highlight style is never active, so no colour bypasses the tokens. - **Tokens:** `lutra_engine::theme::SYNTAX_TOKENS` lists the names; both themes define `syntax-*` values. It is Lutra's own palette, tuned to the raspberry accent (H5: keyword = a muted raspberry, comment near `fg-muted`, operator = `statusbar-fg`). The contrast test checks each one at 4.5:1 on `editor-bg` and on `editor-active-line-bg` in both themes, and that the themes define no syntax token it does not check. Lowest ratios: dark comment 5.42 on the editor background and 4.86 on the active line; light keyword 5.32 and 4.84. Text on the selection colour is not held to 4.5:1 (syntax colours reach 3.06–5.96 there). - **Two highlighters:** Lezer in the UI highlights on every keystroke without IPC; tree-sitter in `crates/syntax` (M2.1) drives outline, folding and the index. They can disagree on broken code; that is accepted (see Decisions). - **Performance:** keystroke to highlight on a 1 MB PHP file (30k lines), measured with `LUTRA_PERF=1 pnpm vitest run tests/editor/highlightPerf.test.ts` in jsdom (the JavaScript work of one `view.dispatch`, no layout or paint), Windows 11, three runs while other builds ran: median 3.0–3.8 ms near the top of the file and 6.3–11.4 ms in the middle; p95 10–16 ms in two runs (one disturbed run: 82 ms). The plain-text baseline is 0.4–0.6 ms. The initial full parse takes 0.7–1.5 s, which CodeMirror spreads over idle slices after the visible part. Not measured in the WebView itself yet (follow-up for `lutra perf`). - **`editor.reveal {path, line, column}`** (`reveal.ts`; a UI command registered through `ui.registerCommands`, label `command.editor.reveal`, provided by `EditorArea.vue`): - **Steps:** it opens the file with `file.open` unless a tab has that exact path, activates the tab and waits one render tick so the view shows it. Then it places the cursor and scrolls it to the centre (`EditorView.scrollIntoView(pos, {y: "center"})`). - **Positions:** `line` is 0-based and `column` counts UTF-16 code units in the line (C3 contract). `positionOf` in `engineText.ts` converts them to a CodeMirror position. Engine and CodeMirror split lines at the same breaks and a `\r\n` is one break on both sides, so the line carries over, and `EngineText.toEngine` maps the result back to the engine offset. Values are clamped into the document: past the end → end of line or last line; negative, fractional or non-finite → truncated or 0. - **Without `path`** it centres the active tab's cursor, which is what running it from the palette does. - **Errors:** wrong types fail with `editor.reveal.invalidParams`, an open failure with the engine's message; both reach the caller as an error toast. - **Agents:** `engine.execute editor.reveal {...}` over the control channel becomes a `uiCommand`. No default shortcut. ### Message catalog (M1.11) - Every interface string comes from `ui/src/i18n/en.json`: flat dotted keys grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`), kept sorted. Components and stores call `t(key, params?)` from `ui/src/i18n`; `{name}` placeholders are filled from `params`, a placeholder without a value stays as it is. A missing key returns the key itself and warns on the console in development builds; it never throws. `hasMessage(key)` tells whether a key exists, for keys that arrive at runtime (settings `labelKey`, notification `messageKey`). - No i18n dependency: the helper is ~20 lines, and plurals, a reactive locale and a second language are G14 work. `vue-i18n` (MIT) remains an option then. - Enforcement: ESLint `vue/no-bare-strings-in-template` is an error (bare text and `title`/`aria-label`/`placeholder`/`alt` attributes); the allowlist is the rule's punctuation plus `;`, `…` and `×`. The test `ui/tests/i18n/catalog.test.ts` scans `ui/src` for `t("…")` calls and fails on a key that is not in `en.json` and on a catalog key that no source uses. Keys used only at runtime need an exception there when they arrive. - Engine messages (`EngineError.message`, the `app.about` slogan, `watchFailed`) are English text from the engine and shown as they are; they move to message keys with G14. Frontend-made errors (`unexpected result of …`) use the catalog. ### Engine construction (M1.9a) - `EngineConfig { config_dir, data_dir }` and `Engine::with_config(config) -> Result`. The desktop builds the Tauri app first, takes `app_config_dir()` and `app_data_dir()` from its path resolver, creates the engine, the host and the control channel, and creates the window in the setup hook. `Engine::new()` has no persistence (settings in memory only) and serves tests and the control test backend; `lutra_testkit::engine_config(root)` gives temp dirs for tests. - Construction never fails because of the settings file. Problems are queued as a warning `notification` event; the desktop takes the startup events and publishes them, and the window receives them on `engine_ready` (M1.12). ### Settings (M1.9a) - `/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap. - A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten. - Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10), the assist keys `editor.completion.autoPopup` (bool, default true), `editor.completion.delayMs` (int 0–2000, default 0) and `editor.hover.delayMs` (int 100–3000, default 350; H4). Defined in `lutra_engine::settings::DEFS`. - Commands: `settings.list` → `[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}]` (catalog keys `settings..label` / `.description`; `section` is an id shown with `settings.section.`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing. - Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…). ### Notifications (M1.12) - **Event:** `notification {id, level: info|warning|error, messageKey?, message?, params?}`; ids `n1`, `n2`… from one sequence per engine. `messageKey` is a catalog key, `message` the English fallback. The engine emits them for settings (M1.9a) and journal (M1.7) problems; the host asks the engine for one with `Engine::notify` (same id sequence) for errors that have no caller to return to: - folder picker and command-line path: `notification.project.unsavedChanges {path, what}` (warning) for `unsaved_changes`, `notification.project.openFailed {path, reason}` (error) otherwise, `notification.project.notLocal {reason}` (error) for a picked folder that is not a local path; - pump: `notification.vfs.pumpFailed {reason}` (warning), once until a pump succeeds again. - **Replay:** the host keeps notifications and `watchFailed` published before the window called `engine_ready` (at most 50) and sends them after the state replay; afterwards nothing is kept. The store ignores an id it already shows, so a second replay does not duplicate. - **`watchFailed`** stays an engine event (control channel clients use it); the frontend maps it to a warning toast `notification.watch.failed {reason}`. `workspace.rs` is unchanged. - **UI:** `ui/src/stores/notifications.ts` (Pinia) turns events into toasts (catalog text with params if the key exists, else `message`, else the key; untrusted fields checked, unknown levels count as errors) and offers `notify` / `notifyError(command, error)` to frontend code. Failed commands that have no UI of their own raise an error toast `notification.command.failed {command, message}` (today `theme.systemPreference` and loading the editor keymap); errors shown in place (tree listings, editor and project errors, the restore dialog) stay in place. `ui/src/components/notifications/NotificationStack.vue`, mounted in `App.vue`, stacks the toasts at the bottom right, newest at the bottom: info as `role="status"`, dismissed after 5 s; warnings and errors as `role="alert"`, until closed. Each toast has a close button and closes with Escape while focused; at most 5 show, older ones collapse into a "+n more" button that expands the stack; at most 100 are kept. Colours are the editor notices' (`--lt-notice-bg`, error tint), with a level stripe (muted, accent, error). ### Themes (M1.10) - `lutra_engine::theme` defines `DARK` (`lutra-dark`) and `LIGHT` (`lutra-light`) with the same token names, plus shared font tokens. Besides the base colours (`bg`, `editor-bg`, `fg`, `fg-muted`, `border`, `accent`, `error`, `statusbar-*`) both define `editor-selection-bg`, `editor-active-line-bg`, `editor-cursor`, `editor-gutter-bg`, `editor-gutter-fg`, `editor-match-bg`, `tab-active-bg`, `tab-modified`, `notice-bg`; `font-size-editor` is shared (14px). Values are opaque `#rrggbb` derived from the palette (selection, match and notice are the accent mixed into the background); the designer may change values, never names. - **Brand alignment (H5, approved by the owner 2026-10-25):** the palettes follow the README banner (raspberry #bc3c79, plum #83224b, cream #f2ecd7) without taking it over: surfaces stay calm and near-neutral (light: cream-tinted, `bg` #f3efe3; dark: a faint plum tint, `bg` #1e1b1e, cream `fg`), the raspberry is only the accent (light #a32c66, dark #e27ba6: cursor, modified dot, focus, active tab, selection and match tints), and the terminal follows the editor surface (ANSI magenta = accent). No new UI fonts. - **Diagnostic and VCS tokens (H5):** `theme::DIAGNOSTIC_TOKENS` → `--lt-diag-error|warning|info|hint` (lint underlines, gutter dots, tooltip stripes, Problems icons; warning is amber, info blue, hint muted) and `theme::VCS_TOKENS` → `--lt-vcs-added|modified|deleted|untracked|ignored|conflicted` (tree and tab file names, change markers; M4.4). Each reaches 4.5:1 on `editor-bg`, `editor-active-line-bg` and `bg` (lowest: `vcs-ignored` 4.67 dark, 4.73 light on the active line). Completion kind icons (Lucide) take `--lt-syntax-*` by kind (`assist/icons.ts` `KIND_COLOURS`), at least 3:1 on the popup and the selected row. - `appearance.theme` selects the theme: a theme id or `system`. `theme::resolve(setting, system_dark)` picks the theme; `system` follows the OS preference the frontend reports, and counts as dark until it has. - Commands: `theme.list` → `[{id, label, dark}]` (`label` is a catalog key, `theme.lutraDark`/`theme.lutraLight`); `theme.systemPreference {dark}` stores the OS preference and returns the resolved theme `{id, dark, tokens}`. Switching goes through `settings.set appearance.theme` (or `settings.reset`). - Event: `themeChanged {id, dark, tokens: {"--lt-…": value}}` (every token, shared ones included) whenever the resolved theme changes: after `settingsChanged` for `appearance.theme`, or after `theme.systemPreference` in system mode. A change that resolves to the same theme (`lutra-dark` → `system` on a dark OS) emits nothing. - First frame: the desktop reads `appearance.theme` before creating the window and passes `theme::init_script(setting)`, which installs `