New layer-0 crate lutra-proc: spawn(Command) puts the child into a kill-on-close group. Windows: one job object per child with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE (windows-sys), nested jobs work. Unix: a new process group plus a /bin/sh watchdog that kills the group when Lutra's pipe closes (drop, kill, quit or SIGKILL of Lutra). Child::kill and Drop take the whole group. Phpactor (supervision spawn) and the php -v probe in lutra-lsp start through it. Tests kill a parent hard and check that its child is gone (with and without the parent in a group), plus kill and drop of a tree. Docs: architecture "Child processes", G6 note. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
125 KiB
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 andflushDirty, 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) · Last updated: 2026-10-24
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/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:
[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
tauriortauri-*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::Commandis a trait withspec(),enabled()andrun().spec()returns aCommandSpecwith the static metadata. Params and results areserde_json::Value; each command documents its params inCommandSpec::params.Engine::execute(id, params)looks the command up, checksenabled, runs it inside the guard and returns anOutcome { value, effects, events }. Commands queue events withState::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_vfsorEngine::take_events.- Effects are requests the engine cannot fulfil below L6 (
Effect::Quitso far). The host (desktop, tests) applies them after the command returns. Commands never call into Tauri. EngineErrorhas a stable stringcode()used by the control channel and the frontend:unknown_command,disabled(e.g. a file command without a project),invalid_params,stale_version(abuffer.editbased on an old version),unsaved_changes(closing a dirty buffer or project withoutforce),failed,internal.- Shortcut notation:
Modis 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": <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:
app.ping,app.auth {token},app.focus,engine.execute {command, params},engine.listCommands,ui.screenshot {path},events.subscribe. Names and docs live incrates/control/src/methods.rs. events.subscribeanswers{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 bySubscribers::publish, and the connection gets a final{"event": {"kind": "subscriptionLost"}}line if it is still open.lutra_controldefines aBackendtrait; 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 throughlutra_control::Subscribers. One thread accepts connections and each connection gets its own thread; no async runtime is needed in the crate.- Screenshots:
xcapdoes 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 withxcap::Monitor::capture_region. Windows covering Lutra at that moment appear in the image. A webview-native capture (WebView2CapturePreview, 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<data_dir>/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_DIRif set, elserendezvous::default_data_dir(), which computes Tauri'sapp_data_dir()for the identifierdev.lutra.desktopwithout Tauri (%APPDATA%\dev.lutra.desktopon Windows,~/Library/Application Support/dev.lutra.desktopon macOS,$XDG_DATA_HOMEor~/.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,SYSTEMand Administrators only (checked withicaclsin the M3.7 live check); Lutra sets no ACL of its own. Both listeners bind127.0.0.1only. On the token listener the first request must beapp.auth {token}within 10 s (AUTH_TIMEOUT); a wrong token, another method or garbage getsunauthorizedand the connection is closed. Tokens are compared in constant time. The--control PORTlistener stays open (no token) for development and agents; it is opt-in and documented as such. - Second start:
lutra-desktop [PATH]without--controlreads the rendezvous file first. If the listener answers, accepts the token and pings, the start forwardsPATH(folder →project.open, file →file.open), callsapp.focusand 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 PORTskips the single instance (no forwarding, no rendezvous file) so parallel agents' instances never forward to each other, unlessLUTRA_RENDEZVOUS_DIRis set, which opts it into the single instance in that directory (used for isolated live checks). - New methods:
app.auth {token}(always succeeds on the open listener) andapp.focus(restore, show and focus the main window;focus_failedwithout a window;Backend::focushas a default that fails, so test backends need no change). lutraCLI (apps/lutra-cli, binarylutra, now L6 so it can uselutra-control):lutra [--wait] [PATH[:LINE[:COLUMN]]]....- Targets: up to two trailing
:Ngroups are a 1-based line and column (Nall 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, elselutra-desktopnext tolutra, else onPATH) and polls the rendezvous file for up to 60 s. --wait: subscribes before opening, then blocks until every opened file'sbufferClosedarrived (orprojectClosed, or the connection ends because Lutra quit). AsubscriptionLostrenews the subscription and checks the remaining ids withbuffer.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.
- Targets: up to two trailing
- Rendezvous API for M3.8 (
lutra mcp):lutra_control::client::connect_live(&rendezvous::dir()?, timeout)returns theInstanceand an authenticatedClient;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'slaunchlogic 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 thelutra_mcp::Connector/Connectiontraits (request(method, params),next_event(timeout)).lutra mcpinapps/lutra-cli(L6) implements them withlutra_control::client: the rendezvous file and token by default (starting Lutra likelutra PATHwhen none runs),--port PORTfor an open--controlchannel,--no-startto never start Lutra. Register it withclaude 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
_metaio.modelcontextprotocol/protocolVersionandio.modelcontextprotocol/clientCapabilities;server/discover; results getresultType: "complete"and_metaio.modelcontextprotocol/serverInfo; another version gets-32022withdata {supported, requested}, missing capabilities-32602) and legacy 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05 throughinitialize(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_metanor a priorinitializeis 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.executefor every engine and UI command.app.quitis refused withconfirmation_requiredunlessconfirm: true.screenshot {path?}:ui.screenshotinto a temporary file (deleted afterwards) orpath, returned asimage/pngcontent; 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
structuredContentand the same JSON as text. Bad arguments, engine errors and an unreachable Lutra are tool errors (isError: true, textcode: message,structuredContent.error {code, message}) with the engine's code, orinvalid_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 growingseq, each capped at 16 KiB (a bigger one keeps onlykindandtruncated: true).get_eventsreturns the events aftersince(default 100, at most 1000, optionally onlykinds, optionally waiting up towaitMs≤ 30 s),latestto pass assincenext time,missedwhen the ring dropped events aftersinceor the subscription was down, andsubscribed. 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), URIlutra://buffer/<project-relative path>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/readreturns the text with unsaved changes; an unknown or closed buffer is-32602withdata {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::EngineBackendbehind a real token listener (crates/mcp/tests/tcp.rs), and thelutra mcpbinary 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)
Stateholdsproject: Option<Workspace>(thelutra_vfs::Project, its watcher and the watched directories) andbuffers(id →OpenBuffer { buffer: lutra_text::Buffer, path, version, saved_version, bom }). A buffer is dirty whenversion != 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 exceptproject.openandbuffer.listis 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:
editsare{from, to, insert}in UTF-16 code units, all relative to the text atbaseVersion(CodeMirror change-set semantics), non-overlapping, applied atomically. AbaseVersionother than the current version fails withstale_versionand changes nothing; the client refetches withbuffer.getand 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": "<camelCase>", ...}: 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://eventwith the engineEventas payload. Events are published while the engine lock is held, so their order is the engine's order. ui/src/ipc.tsexposesonEngineEvent(handler) => unsubscribewith the typed unionEngineEventPayload. Once the subscriptions started together (all of them while the page mounts) are registered,ipc.tscalls the IPC commandengine_readyonce; the host then replaysprojectOpenedandbufferOpenedfor the current state, followed by the notifications andwatchFailedevents 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.openDialogreturnsEffect::PickFolder; the host shows the native folder picker (tauri-plugin-dialog, from Rust, non-blocking) and runsproject.openwith the choice. At most one picker is open; cancelling does nothing. A folder that cannot be opened becomes anotification(M1.12):unsaved_changesa 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.tsis now the adapter between the engine contract and the UI types:toProjectEventtranslates{kind: "projectOpened", root, name}and friends into the store's events, andtoTreeEntriestranslatesproject.children's{dir, entries: [{name, path, kind: file|directory|other, ignored, role}], truncated}into tree entries (kind: dir|file,role,excluded,specialforother) plustruncated. Malformed entries are skipped; a result withoutentriesbecomes anipcerror on the directory.
Tabs and editor (M1.6)
ui/src/stores/editor.tsholds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from thefile.openresult (opened from the tree) or, for abufferOpenedevent it did not cause (control channel, replay after a reload), frombuffer.get.bufferClosed,dirtyChanged,fileChangedOnDiskand project open/close update it;bufferFocusedactivates 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.tschecks event fields before the store sees them.- One
BufferSyncper tab (ui/src/components/editor/bufferSync.ts) owns the tab's CodeMirrorEditorState; oneEditorViewshows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent withbuffer.editagainst the confirmed version, one call in flight, later keystrokes composed into the next call. Onstale_version, or abufferChangedwith a newer version than ours, the sync fetchesbuffer.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\nas two UTF-16 units; CodeMirror counts every break as one position.EngineTextremembers which breaks are\r\nand 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.saveMod+S,file.saveAllMod+Alt+S,buffer.closeMod+W), loaded withlistCommandsand 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.closewithoutforcefailing withunsaved_changesalso 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.tspicks 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<?php … ?>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 toeditorExtensions(path)when it creates the tab's state. - Colours: the highlighter is a
tagHighlighterthat only sets classes: a span getslt-syntax-<token>for one of the eleven tokenskeyword,string,number,comment,variable,function,type,constant,tag,attribute,operator. The editor theme (extensions.ts) colours each class with its--lt-syntax-<token>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 afterextends) keep--lt-fg. CodeMirror's default highlight style is never active, so no colour bypasses the tokens. - Tokens:
lutra_engine::theme::SYNTAX_TOKENSlists the names; both themes definesyntax-*values. It is Lutra's own palette, derived from the copper accent and the warm neutrals (keyword = accent, comment nearfg-muted, operator =statusbar-fg). The contrast test checks each one at 4.5:1 oneditor-bgand oneditor-active-line-bgin 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.tsin jsdom (the JavaScript work of oneview.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 forlutra perf). editor.reveal {path, line, column}(reveal.ts; a UI command registered throughui.registerCommands, labelcommand.editor.reveal, provided byEditorArea.vue):- Steps: it opens the file with
file.openunless 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:
lineis 0-based andcolumncounts UTF-16 code units in the line (C3 contract).positionOfinengineText.tsconverts them to a CodeMirror position. Engine and CodeMirror split lines at the same breaks and a\r\nis one break on both sides, so the line carries over, andEngineText.toEnginemaps 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
pathit 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 auiCommand. No default shortcut.
- Steps: it opens the file with
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 callt(key, params?)fromui/src/i18n;{name}placeholders are filled fromparams, 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 (settingslabelKey, notificationmessageKey). - 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-templateis an error (bare text andtitle/aria-label/placeholder/altattributes); the allowlist is the rule's punctuation plus;,…and×. The testui/tests/i18n/catalog.test.tsscansui/srcfort("…")calls and fails on a key that is not inen.jsonand on a catalog key that no source uses. Keys used only at runtime need an exception there when they arrive. - Engine messages (
EngineError.message, theapp.aboutslogan,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 }andEngine::with_config(config) -> Result<Engine, EngineError>. The desktop builds the Tauri app first, takesapp_config_dir()andapp_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
notificationevent; the desktop takes the startup events and publishes them, and the window receives them onengine_ready(M1.12).
Settings (M1.9a)
<config_dir>/settings.json, a flat JSON object of dotted keys, written withlutra_vfs::write_atomicon 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-<YYYYMMDDTHHMMSSZ>(with-nif taken), the defaults are used and anotification {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, defaultsystem),editor.fontSize(int 8–48, default 14),ui.language(en), the autosave keyseditor.autosave.onBlur,editor.autosave.onTabSwitch(bool, default true) andeditor.autosave.idleSeconds(int 0–600, default 15; M3.10). Defined inlutra_engine::settings::DEFS. - Commands:
settings.list→[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}](catalog keyssettings.<key>.label/.description;sectionis an id shown withsettings.section.<id>),settings.get {keys?}→{values},settings.set {key, value}→{value},settings.reset {key}→{value}. Unknown keys and bad values fail withinvalid_params; a write failure fails withfailedand changes nothing. - Events:
settingsChanged {keys}when an effective value changes;notification {id, level: info|warning|error, messageKey?, message?, params?}(idsn1,n2…).
Notifications (M1.12)
- Event:
notification {id, level: info|warning|error, messageKey?, message?, params?}; idsn1,n2… from one sequence per engine.messageKeyis a catalog key,messagethe English fallback. The engine emits them for settings (M1.9a) and journal (M1.7) problems; the host asks the engine for one withEngine::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) forunsaved_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.
- folder picker and command-line path:
- Replay: the host keeps notifications and
watchFailedpublished before the window calledengine_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. watchFailedstays an engine event (control channel clients use it); the frontend maps it to a warning toastnotification.watch.failed {reason}.workspace.rsis unchanged.- UI:
ui/src/stores/notifications.ts(Pinia) turns events into toasts (catalog text with params if the key exists, elsemessage, else the key; untrusted fields checked, unknown levels count as errors) and offersnotify/notifyError(command, error)to frontend code. Failed commands that have no UI of their own raise an error toastnotification.command.failed {command, message}(todaytheme.systemPreferenceand 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 inApp.vue, stacks the toasts at the bottom right, newest at the bottom: info asrole="status", dismissed after 5 s; warnings and errors asrole="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::themedefinesDARK(lutra-dark) andLIGHT(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 defineeditor-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-editoris shared (14px). Values are opaque#rrggbbderived from the palette (selection, match and notice are the accent mixed into the background); the designer may change values, never names.appearance.themeselects the theme: a theme id orsystem.theme::resolve(setting, system_dark)picks the theme;systemfollows the OS preference the frontend reports, and counts as dark until it has.- Commands:
theme.list→[{id, label, dark}](labelis a catalog key,theme.lutraDark/theme.lutraLight);theme.systemPreference {dark}stores the OS preference and returns the resolved theme{id, dark, tokens}. Switching goes throughsettings.set appearance.theme(orsettings.reset). - Event:
themeChanged {id, dark, tokens: {"--lt-…": value}}(every token, shared ones included) whenever the resolved theme changes: aftersettingsChangedforappearance.theme, or aftertheme.systemPreferencein system mode. A change that resolves to the same theme (lutra-dark→systemon a dark OS) emits nothing. - First frame: the desktop reads
appearance.themebefore creating the window and passestheme::init_script(setting), which installs<style id="lt-theme">. Forsystemthe CSS is the dark theme plus the light one inside@media (prefers-color-scheme: light), so the first frame follows the OS without a round trip; the native window background is set from the resolved theme (Window::theme()for system). - Live switch:
ui/src/theme.ts(startTheme, called byApp.vue) reportsmatchMedia("(prefers-color-scheme: dark)")now and on every change, applies the result and everythemeChanged: tokens go onto:root's inline style (which wins over the injected style element),color-schemeis set, anddata-themeholds the id. No reload. - Accessibility:
ui/tests/theme/contrast.test.tschecks every text/background pair the components draw with against WCAG AA (4.5:1 text, 3:1 cursor and modified dot) in both themes. It readsui/tests/theme/themes.json, which the Rust testtheme::tests::ui_snapshot_is_currentkeeps equal to the Rust definition (LUTRA_UPDATE_SNAPSHOTS=1rewrites it).ui/tests/theme/theme.test.tsfails on avar(--lt-x)the themes lack and on a fallback for a token they define. - Not themed yet: the native title bar follows the OS, not the Lutra theme; spacing and size tokens (
--lt-space-*,--lt-radius,--lt-row-height…) are still CSS fallbacks in components.editor.fontSizedrives--lt-font-size-editorsince M1.9b (see Settings dialog).
Recovery journal (M1.7)
- Storage:
<data_dir>/recovery/<project-id>/<entry-id>.json. The project id is the FNV-1a 64-bit hash of the canonical project root, the entry id the same hash of the project-relative path, each as 16 hex digits (FNV instead ofstd's hasher, whose output may change between Rust versions). One file per dirty buffer:{path, text, lineEnding, bom, savedAt};textis the buffer text as held in memory (mixed line breaks included),lineEndingthe ending it saves with,savedAtmilliseconds since the Unix epoch. Engines without a config (Engine::new) keep no journal. Code:crates/engine/src/journal.rs, commands incmd/recovery.rs. - Writing:
buffer.editonly records the edit time.Engine::pump_vfs(the desktop's pump thread, every 100 ms) writes a buffer once it has been idle for 1 s, or 2 s after its first unwritten edit while typing continues, so an entry is on disk at most ~1.1 s after the last edit and never per keystroke. Writes uselutra_vfs::write_atomic.Engine::flush_journal()writes everything now (tests, hosts about to stop). Cost for a 1 MiB buffer (measured on Windows 11,journal_write_cost_for_a_one_megabyte_buffer): median 8.5 ms in a release build, 67 ms in a debug build, under the engine lock; a keystroke arriving meanwhile waits that long. Moving the write to a background thread is a follow-up if large files make it noticeable. - Removal:
file.save/file.saveAll,buffer.close(alsoforce),project.close/project.openwithforceandrecovery.discardremove entries. Save and close remove only entries this session wrote or restored; entries left by a crashed session stay until restored or discarded. Editing such a file without restoring it overwrites its entry. - Commands and event: after
project.open,recoveryAvailable {entries: [{path, savedAt, diskChanged}]}when the journal is not empty.recovery.list→{entries};recovery.restore {paths?}→{restored: [{path, id}], failed: [{path, message}]}opens each file as a dirty buffer (version 1, saved version 0) with the journal text, line ending and BOM, or puts the text into a clean open buffer; a buffer with unsaved changes is newer than the journal and is left alone (failed); a file gone from disk is restored too and saving recreates it.recovery.discard {paths?}→{discarded}; a discarded entry of an open dirty buffer is written again on the next tick. Both emitrecoveryResolved {paths}(sorted, only when not empty) with the restored or discarded paths (M1.15): a restored entry stays in the journal as the dirty buffer's own entry, so "journal empty" is not the signal; the settled paths are.diskChangedis true when the file's modification time is aftersavedAtor the file is gone. - Untrusted input: entries are read with a 512 MiB cap, at most 1,000 per project. An entry that is not valid JSON of that shape, whose path escapes the project or does not match its file name is renamed to
<entry>.bad, skipped, and reported once asnotification {level: warning, messageKey: "notification.recovery.corrupt", params: {file, reason}}. A failed write is reported once until a write succeeds (notification.recovery.writeFailed {path, reason}); an unreadable journal directory givesnotification.recovery.unavailable {reason}. Neither stops editing or opening. - UI:
ui/src/components/recovery/(storerecovery.ts,RecoveryDialog.vue, mounted inApp.vue). The list comes fromrecoveryAvailableand, because that event is not replayed after a page reload, fromrecovery.listonprojectOpened. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open.recoveryResolveddrops the settled paths from the list, so a restore or discard over the control channel closes the dialog when nothing is left (M1.15). The dialog is queued behind the other modals (see UI commands › Modal rule). - Limits: two Lutra instances on the same project share one journal directory;
diskChangedmisses a disk change that happened before the last journal write.
UI commands, palette and keymap (M1.8)
- Registration: the frontend calls
ui.registerCommands {commands: [{id, labelKey, menuPath?, defaultShortcut?}]}when it starts (ui/src/commands/store.ts). A registration replaces the previous one, so a page reload registers again. The engine keeps them inState::ui_commands(crates/engine/src/cmd/ui.rs). It checks every entry and changes nothing on a bad one (invalid_params):- ids have the
area.actionshape (ASCII alphanumeric parts), at most 128 bytes; - an id may not be an engine command or listed twice;
labelKeyis not empty;- texts are at most 256 bytes; at most 1,000 commands.
- ids have the
- Listing:
listCommandsreturns one list in id order: engine commands and UI commands.CommandInfohasui: bool; UI commands also carrylabelKey, use it aslabel(the engine has no English for them) and are alwaysenabledas far as the engine knows. - Running from outside:
Engine::executeon a UI command id queuesuiCommand {id, params}and returnsnull(params are passed on unchanged). The desktop publishes the event to the window and to control subscribers like any other. The frontend runs the command, soengine.execute palette.openover the control channel opens the palette. AuiCommandthe frontend cannot run (no handler, or disabled) becomes a warning toast. - Frontend:
ui/src/commands/:uiCommands.tslists the UI commands:editor.reveal(no shortcut, M2.2),find.openMod+Alt+F(M2.4),menu.openAlt+M(M3.9),palette.openMod+Shift+P,settings.openMod+,,terminal.openMod+Shift+T(M3.6),view.toggleProjectTreeMod+1. Since M3.9 the user-facing ones carry amenuPath.keymap.tsparses Lutra notation and matches by key code (letters, digits and US punctuation bycode, so Alt and Shift layout effects don't matter). It also formats shortcuts for display with catalog modifier names.rank.tsranks for the palette.store.ts(Piniacommands) holds the merged list, the keymap, the handlers and the recent commands.
- Handlers: components supply behaviour with
provide(id, {run, enabled?}):- the palette provides
palette.open; - the main layout provides
view.toggleProjectTree; - the editor area provides
file.save,file.saveAllandbuffer.closewith the active buffer as context (they replace the editor-only keymap of M1.6), andeditor.reveal(M2.2). - A UI command without a handler is disabled. The settings dialog provides
settings.open(M1.9b). - An engine command without a handler runs through
run(id, {}).
- the palette provides
- Modal rule (M1.15,
ui/src/commands/modals.ts): at most one modal is open. The palette, the settings dialog and the close question are exclusive: each reportsopened(id, close)/closed(id)to the Piniamodalsstore, and opening one closes the open one (the close question closes as Cancel; the store followseditor.closePrompt, so the editor has no code for it). Running any command butpalette.openthroughexecute(keyboard, palette,uiCommand) closes the palette first. The restore dialog is queued instead: hidden while an exclusive modal is open, shown again with its list intact when it closes. Reason: its offer must survive a palette or settings dialog opened by an agent, and closing it would only hide the journal until the next open. - Enabled state: a handler's
enableddecides, else the engine's. The list is refreshed onprojectOpened/projectClosedand whenever the palette opens. - Keyboard: one window
keydownlistener in the capture phase (works while CodeMirror or an input has focus). A matching shortcut is always swallowed; a disabled command does nothing. A failure raisesnotification.command.failed. - Palette (
ui/src/components/palette/CommandPalette.vue, mounted inApp.vue):- Contents: it offers UI commands and engine commands that have a menu path or a default shortcut. Protocol commands such as
buffer.editare left out. - Ranking: labels are catalog text for UI commands and the engine's label otherwise. Tiers: prefix, word prefix, query spread over consecutive word starts, substring, in-order characters; the label or the id may match. Within a tier recent commands come first (in memory, 20, not
palette.openitself), then shorter texts, then the label. - Keys: arrow keys wrap, Enter runs an enabled row, Escape or a click outside closes.
- Running: the command runs after the palette closed and returned the focus.
- Rows: disabled rows are dimmed with
aria-disabled. - Accessibility: combobox with listbox and
aria-activedescendant.
- Contents: it offers UI commands and engine commands that have a menu path or a default shortcut. Protocol commands such as
App menu (M3.9)
- Where:
MainLayout.vuehas a slim header bar (28 px,--lt-bg, aheaderslot) whose default content isui/src/components/menu/AppMenu.vue: a button with the Lucidemenuicon top left. - Contents (
menu.ts): every command in the store's entries with amenuPath(engine and UI), grouped by the path's first segment. Groups in Lutra's order File, Edit, View, Go, Help (unknown groups before Help, empty ones hidden), group headings from the catalog (menu.group.*). Items follow a fixed id order, others sorted by label after them. A UI command shows its catalog label; an engine command shows the rest of its path (the engine has no catalog, and the path is written for menus), sobuffer.closereads Close Tab. Deeper paths are flattened asA › B. - Paths: File (
project.openDialog,file.save,file.saveAll,buffer.close→File/Close Tab,project.close,app.quit), View (palette.open,view.toggleProjectTree,view.toggleStructure,find.open,terminal.open→View/Terminal,settings.open), Go (goto.fileOpen,goto.classOpen,goto.symbolOpen), Help (app.about). Edit stays empty until there are edit commands. - Opening: the button (a second click closes) or
menu.open(Alt+M, Lutra's own; also asuiCommand). It refreshes the enabled states and focuses the first item. - Keyboard: WAI-ARIA menu with roving focus: arrows wrap, Home/End, Enter/Space runs, Escape or Tab closes, printable keys type ahead (500 ms buffer; one letter cycles through items with that initial). Disabled items are focusable, dimmed (
aria-disabled) and do nothing. - Modal rule:
menuis an exclusiveModalId; the menu is a launcher like the palette:commands/store.ts›executecloses it for every command butmenu.open, so a shortcut, a palette command or an agent'suiCommandnever leaves it open. A chosen command runs after the menu closed and returned the focus. - Why a dropdown with headings instead of a menu bar: one keyboard path (open, type, Enter) like the palette, no nested popups to manage, and it fits the slim header. A native macOS menu bar and a display-mode setting are follow-ups.
Settings dialog (M1.9b)
- Store:
ui/src/stores/settings.ts(Piniasettings, started byApp.vue) loadssettings.listandsettings.get, reads both defensively (unknown types and malformed entries dropped, values must be scalars), changes values throughsettings.set/settings.resetand keeps a refused change's message per key.settingsChangedreloads the named keys withsettings.get {keys}and drops their errors, so changes from the control channel or an agent show at once. - Text: labels, descriptions and section names come from the catalog keys the engine sends (
settings.<key>.label,.description,settings.section.<id>); enum values usesettings.<key>.value.<value in camelCase>. A key the catalog lacks shows the setting key (or the raw value). These keys are in the catalog test's runtime list. - Font size:
theme.tshassetTokenOverride(name, value): a value above the theme's thatapplyThemekeeps across theme switches. The store sets--lt-font-size-editortoeditor.fontSizepx; the editor reads only that token. - Dialog:
ui/src/components/settings/SettingsDialog.vue(mounted inApp.vue) providessettings.open(Mod+,, palette,uiCommand). Sections on the left, the chosen section's settings on the right; enum → select, int → number field (min/max, applied when committed; text that is no whole number in range is refused in place withsettings.error.intRange), bool → switch. The theme picker is theappearance.themeselect; the engine answers withthemeChanged.- Search matches label, description, key and section name (every word, ignoring case); while it has text every match shows, grouped by section, and sections without matches are dimmed.
- Reset to default per setting, enabled while the value differs from the default.
- Errors show under the control (
role="alert",aria-invalid) and keep the typed text until the value changes. - Keyboard: Escape or a click outside closes; Tab and Shift+Tab wrap inside the dialog, focus that leaves it is pulled back to the search field, and focus returns to where it was on close.
- No OK/Apply/Cancel: every change applies at once, as agents change settings through the same commands.
Syntax (M2.1)
crates/syntax (L1, depends on lutra-text only) parses PHP with tree-sitter (tree-sitter 0.26, tree-sitter-php 0.25, both MIT; the grammar variant that accepts inline HTML around <?php tags). It has no engine types; M2.7 wires it to buffers and M2.5 builds the index on it.
- API:
Parser::new()?,parser.parse(&str) -> Tree(never fails),parser.reparse(&Tree, &[lutra_text::Edit]) -> Result<Tree, SyntaxError>,outline(&Tree) -> Vec<OutlineItem>,folding(&Tree) -> Vec<Range>.Treecarries the text it was parsed from (alutra_text::Buffer, cheap to clone) plustruncated()andhas_errors(); that is whyoutlinetakes no separate text argument (the contract sketch hadoutline(tree, text)): a tree and a mismatching text can't be combined. - Reparse: the edit batch has
Buffer::applysemantics (ranges against the old text, any order). It is mapped to one tree-sitterInputEditcovering the smallest start to the largest end, with points (row, byte column, rows by\nas tree-sitter counts them) computed from the old and new text. Proptests check that a reparse gives the same tree, outline and folding as a fresh parse whenever the edited text is error-free, and that an undo round trip ends at the original tree. On broken code tree-sitter's error recovery may legitimately differ between an incremental and a fresh parse; the engine can reparse from scratch when it wants a canonical tree (for example on save). - Outline:
OutlineItem {kind, name, detail, range, selection_range, children};OutlineKind::as_str()gives the contract names (namespace,class, …,enumCase). Braced and unbraced namespaces (an unbraced one owns everything up to the next namespace statement), promoted constructor parameters as properties after the constructor, enum cases with backing values, multi-elementconst/property declarations as one item each, attributes inside the declaration range. Anonymous classes are classes namedclass@anonymous(OutlineItem::is_anonymous, for the index to skip). Function, method and closure bodies are not searched; statements at file level are (if (!function_exists(…)) { function … }). Error nodes are transparent and nameless declarations are dropped. The search descends at most 96 levels. - Folding: multi-line brace blocks (class-like bodies, function and control bodies,
switch/match), arrays, comments, heredoc/nowdoc,use A\{…}groups and runs of two or moreusestatements; ranges include the delimiters. The walk is iterative and skips the inside of single-line nodes. - Positions: 0-based line and UTF-16 column through
Buffer::offset_to_position(about 1 µs per conversion on a 1 MB rope; the parse dominates). - Limits: texts over 8 MiB (
MAX_PARSE_BYTES) are not parsed (truncated, empty outline and folding). The grammar's identifier rule covers the Basic Multilingual Plane only: PHP accepts any byte ≥ 0x80 in names, so an identifier with an emoji is an error node in tree-sitter. - Timing (release, Windows 11, MSVC
/O2, generated 1 MB file, best of 5, other builds running in parallel, measured): full parse 364–553 ms, reparse after one inserted character 7–11 ms, outline 70–133 ms, folding 61–73 ms (143 ms before skipping single-line nodes). The full parse misses the 50 ms target by about 8×: tree-sitter-php runs at roughly 2–3 MB/s here. Consequences: parse off the engine lock and debounce (M2.7), parse files in parallel for the index (M2.5);cargo test --release -p lutra-syntax --test perf -- --ignored --nocapturerepeats the measurement.
Search (M2.3)
crates/search(L2) is the library:Search::new(&Query)compiles a literal or regex (grep-regex; empty, invalid, oversized or newline-matching patterns and bad globs fail up front),runwalks the project with theignorecrate's parallel walker (at most 8 threads) and searches each file withgrep-searcher;spawnruns it on a thread of its own and deliversSearchEvent::Fileper file with matches, then oneSearchEvent::Done. ACancelTokenstops it between files and lines.- Which files: the same rules as
lutra-vfs(.gitignore,.ignore,.git/info/exclude, global excludes, applied without a git repository; ignore files above the root are not read)..gitandnode_modulesare skipped, the root'svendor/is searched as library code even when an ignore file lists it (it is walked as a second root, so its own nested ignore files still apply), dot files are searched, symbolic links are not followed. Include globs keep matching files, exclude globs drop files and whole directories; a glob without/matches the name, one with/the project-relative path. Files over 8 MiB, binary files (a NUL byte) and unreadable files are skipped silently. The library does not depend onlutra-vfs: the walker is configured to the same rules instead, because the VFS reads rules per directory listing and the walker needs them per walk. - Results: positions are 0-based, columns and lengths in UTF-16 code units, lines end at
(a precedingis not part of the line; a loneis not a line break here, unlike inlutra-text). Invalid UTF-8 is replaced before matching. The preview is the line, or a window of 300 characters starting up to 80 characters before the match. Files arrive in no fixed order. The cap (maxResults, default 10,000, at most 100,000) counts matches;truncatedis set only when a match was left out. - Engine:
search.find {query, regex?, caseSensitive?, wholeWord?, include?, exclude?, maxResults?}(disabled without a project) snapshots the text of every dirty buffer as an overlay (searched instead of the file; only for files the walk visits), starts the search and returns{searchId}at once. Searches run outside the engine lock. Each search's results wait in its own channel inState::searches;Engine::pump_vfsdrains them (cmd::search::pump) intosearchResultsevents (one per file) and a finalsearchDone. Hosts already publish the pump's events, so the desktop (pump every 100 ms) and the control channel get them without new plumbing; there are at most 10 batches per second and at most 500searchResultsper pump (MAX_RESULTS_PER_PUMP), which keeps a control subscriber's queue of 4096 events from overflowing; the rest wait for the next pump.search.cancel {searchId}returns{cancelled}(false once the search ended) and the search still ends withsearchDone {cancelled: true}. Starting a search does not cancel older ones. A search whose project is no longer open is cancelled by the next pump, its remaining results are dropped and it ends withcancelled: true. - Measured (release, Windows 11, 16 threads, generated 20,006-file tree from
lutra_testkit::generate_search_tree, other builds running): common literalfunctionfirst result 10–43 ms, capped at 10,000 matches after 112–209 ms; a rare literal (full walk, 376 files) first result 17–22 ms, total 0.66–1.43 s (the first round cold);functionwith the 100,000 cap 0.53 s. Through the engine add up to one pump interval (100 ms) before results reach clients. Live check over the control channel against the running app (debug build, 5,900-file project with a dirty buffer):search.findanswered in 4.5 ms, firstsearchResultsline after 55 ms,searchDoneafter 386 ms; vendor hits present,var/,node_modulesand the binary file absent; the dirty buffer's text was found;search.cancelended a search withcancelled: true.
Find tool window (M2.4)
- Bottom panel:
ui/src/components/layout/BottomPanel.vue, under the editor and the left tool window, above the status bar: header with title, collapse/expand and close; a splitter on the top edge (pointer, or Up/Down with Shift for larger steps; 80–900 px, at most 75 % of the window). Height is view state ofMainLayout.vue; later bottom tool windows (Problems, Terminal) reuse it. Since M3.6 it also holds the Terminal tool window and shows tabs while both are visible (see Terminal). - Store:
ui/src/stores/find.ts(Piniafind, started by the main layout) holds the query, the options (regex,caseSensitive,wholeWord, include/exclude as comma-separated globs), the currentsearchId, the files with their matches (ashallowRef, replaced per event, kept sorted by path because files arrive in no fixed order), thesearchDonesummary and an inline error.- One search at a time: a new search cancels the running one with
search.cancel(the engine does not); results of other searches are ignored, and the answer of a search overtaken by a newer one is dropped and cancelled. - Event race: events and the
search.findanswer travel on different channels (Tauri event vs. invoke response), and the pump may publish results before the answer arrives. Whilesearch.findhas not answered, search events are held (at most 5,000) and replayed for the returned id. - Errors: a refused search (
invalid_paramsfor a bad regex or glob) shows its message under the fields (role="alert",aria-invalid), not as a toast. - Untrusted fields: non-integer positions or a non-string preview drop the match; the highlight is clamped into the preview.
projectOpened/projectClosedclear everything.
- One search at a time: a new search cancels the running one with
- Window:
ui/src/components/find/FindToolWindow.vue. Enter in a field searches, a toggle repeats the last search, cancel while running. The status line shows counts while streaming, then matches, files and elapsed time, "No matches" or "Cancelled"; a truncated search adds a hint. Results are a listbox witharia-activedescendant: file headers (name, directory, count) and one option per match (1-based line number, preview without leading indentation, the match in a<mark>with--lt-editor-match-bg). Down in a field enters the list; Up/Down, Page Up/Down (10), Home, End move; Enter or a click runseditor.reveal {path, line, column}through the command store. Every match is rendered; with the default cap of 10,000 that stays a plain DOM list (virtual scrolling is a follow-up if it shows up as slow). find.open(UI command,Mod+Alt+F, Lutra's own; provided byMainLayout.vue, so it works before the panel exists): shows and expands the panel and focuses and selects the query field. Without params it takes the main selection (single line, at most 1,000 characters) or else the word at the cursor of the active editor state (prefillFrom), and waits for Enter. With a stringquery(and optionalregex,caseSensitive,wholeWord,include,exclude), as an agent sends it throughuiCommand, it searches at once. The panel is a tool window, not a modal: it is not part of the modal rule.
Index and go-to (M2.5)
crates/index(L2, depends onlutra-syntax,lutra-text,ignoreandnucleo-matcher0.3, MPL-2.0 as a separate crate, built without itsunicode-segmentationfeature) lists every file of the project and the declarations of its PHP files. ASymbolis{name, fqn, kind, container, line, column}: names as written ($idfor properties), FQNs without a leading\(App\Models\User, membersApp\Models\User::find),containerthe declaring class-like FQN, the position of the name (0-based line, UTF-16 column) from the outline'sselectionRange. Namespaces only prefix FQNs; anonymous classes and their members are skipped; at most 20,000 symbols per file.- Which files: the walk is configured to the same rules as
crates/search(ignore files without a git repository,.gitandnode_modulesskipped, the root'svendor/walked as a second root even when gitignored and markedlibrary, dot files listed, links not followed). Every file is listed for Go to File; only.phpfiles up to 2 MiB (MAX_PARSE_BYTES) are parsed, larger ones are listed without symbols. At most 200,000 files (MAX_FILES); further files are left out (Summary::capped). - Build:
build/spawn_buildwalk first (parallelignorewalker), report non-PHP files at once, then parse PHP files ondefault_threads()workers (cores − 1, at most 32), each with its ownParserand one file in memory, taking files from a shared counter: project files before library files, larger files first in each group. Workers sendUpdate::Filesbatches of 64 files (or every 100 ms) andUpdate::Progress {done, total}; the build ends withUpdate::Ready(Summary). A panic while parsing a file (a parser bug) is caught per file: the file is listed without symbols and the worker gets a fresh parser. Reads are capped, invalid UTF-8 is replaced, a BOM dropped. - Incremental:
Updateris one background thread takingJob::File {path, text?}(re-index from a buffer's text, or re-read from disk; a file no longer found or now excluded is reportedRemoved) andJob::Dir {path}(drop the subtree, list it again with a walk restricted to the path, so ignore files on the way still apply). Jobs queued while it works are coalesced to the last per path, so a burst of keystrokes parses a buffer once. - Queries:
Index(aBTreeMapby path, so a directory's files drop with one range) answersfind_files,find_classesandfind_symbols. Every whitespace-separated query word must match fuzzily (fzf-style scoring, smart case, no other special syntax); queries are capped at 256 characters and 1,000 results. Files: a query without/(a\counts as/) is matched against the file name first with double weight, else the path; match ranges are merged UTF-16 ranges in the path. Classes: by name, by FQN when the query has a\. Symbols: by name;Class::membermatches the container's short name (FQN with a\) and the member separately,Class::lists members. Order: project before library, higher score, shorter name, byte order. Indexes over 20,000 files plus symbols are scanned ondefault_threads()threads, each keeping its own best hits. - Engine (
cmd/goto.rs):State::indexholds the index of the open project.goto::syncruns on everyEngine::pump_vfsand before every index command: it starts the build and the updater when a project is open and the index belongs to another root (or none), drops them without a project (dropping cancels the threads;project.closealso drops it at once), merges up to 4,096 updates, emitsindexProgress {done, total}at most every 250 ms while building andindexReady {files, symbols, elapsedMs}at the end, and re-indexes buffers. The engine lock is held only for inserts and queries; walking and parsing never run under it. Updater results that arrive while the build runs mark their paths, and later build results for those paths are ignored, so a buffer edit or a disk change is never overwritten by the stale build. - Incremental sources:
workspace::pumphands the VFS events togoto::note_disk_changes(removed paths dropped at once, created or modified files re-read, created directories and rename targets rescanned); the watcher is not recursive, so only watched directories (root, listed, pinned) report changes. A buffer whose version changed is re-indexed from its text when its path is in the index (or the build still runs); while it is dirty, disk changes for it are ignored; closing it dirty re-reads the file. - Commands:
index.status→{state: "idle"|"indexing", files, symbols}(idle and zero without a project).goto.file {query, limit?}→{items: [{path, score, matches: [[start, end]], library}], indexing}(libraryadded by M2.6, PM decision: vendor files, as in class and symbol items);goto.class→{items: [{name, fqn, kind, path, line, column, library}], indexing};goto.symbol→ the same pluscontainer(FQN ornull), for functions, methods, properties, constants and enum cases.limitdefaults to 50 (at most 1,000); an empty query returns no items. The go-to commands are disabled without a project; none has a menu path or shortcut; the popup's UI commands do (below). - Measured (release, Windows 11, 8 cores / 16 threads, 15 workers, generated
lutra_testkit::generate_php_project(20_000): 20,001 files, 19,000 PHP of ~5 KB, 87.7 MB, 324,080 symbols): build 3.9–4.2 s on an idle machine (target < 5 s met), 4.6–5.7 s while other agents' builds ran; the walk takes 25–35 ms and the first batch arrives after ~30 ms, so the parse dominates (~21 MB/s over 15 workers, ~1.4 MB/s per worker). Queries on the full index, median of 7:goto.class2–4 ms,goto.symbol7–11 ms,Class::member11–12 ms,goto.file2 ms (single-threaded before the parallel scan:goto.symbol72–100 ms).cargo test --release -p lutra-index --test perf -- --ignored --nocapturerepeats it. - Live check over the control channel against the running app (debug build, port 7825, generated 6,002-file project with gitignored
vendor/andvar/):index.statusansweredindexingright afterproject.open, a go-to query during the build returnedindexing: true, 25indexProgressevents at least 251 ms apart,indexReadyafter 8.2 s (debug build: the tree-sitter C code and the workers are unoptimised) with 6,002 files and 62,000 symbols;goto.file,goto.class(vendor markedlibrary),goto.symbolwithClass::memberanswered in 5–25 ms; the gitignoredvar/class was absent; abuffer.editrenaming a class and a file created on disk were found within a second;project.closereset the status to idle.
Structure (M2.7)
- Engine:
crates/engine/src/cmd/syntax.rskeeps a syntax tree per open PHP buffer (.php,.phtml,.inc) inState::syntax. Nothing is parsed under the engine lock.buffer.editrecords each applied batch (byte-offsetlutra_textedits, at most 64 batches or 8 MiB of inserted text per buffer, beyond that the record is dropped).Engine::pump_vfs(cmd::syntax::pump) adds new buffers, drops closed ones, notices version changes that did not come throughbuffer.edit(reload from disk, restore), and once a buffer has been quiet for 200 ms (a new buffer at once) hands its text snapshot (a rope clone), the last tree and the recorded batches to one worker thread (lutra-syntax, its ownParser, created lazily). At most one parse per buffer is in flight. The worker reparses batch by batch, checks that the result's text equals the snapshot, otherwise parses from scratch, builds the outline as JSON and compares it with the previous one. The next pump stores tree and outline and queuesoutlineChanged {id}if the outline changed, at most once per 200 ms per buffer; the first outline is always announced. Replaced trees and outlines go back to the worker to be freed (dropping a 1 MB file's outline took 60–80 ms on the lock before). A panic in a parse is caught on the worker (the parser is recreated, that version is not retried); a vanished worker is restarted by the next pump. syntax.outline {id}answers from the stored outline:{items, truncated, version}, items{kind, name, detail?, range, selectionRange, children}with{start, end}of{line, column}(0-based, UTF-16).versionis the buffer version the items describe,nullbefore the first parse finished.versionis part of the C3 contract (added by M2.7, accepted by the PM on 2026-10-17): it lets an agent or the UI tell "not parsed yet" from "no declarations"; non-PHP buffers have no items.- UI:
MainLayout.vuehas a left stripe (a vertical tab list, LucideFolderTreeandListTree) with Project and Structure; the left tool window shows one of them, both stay mounted while it is open (v-show). Clicking the shown one's tab or running its command again hides the window. UI commandsview.toggleProjectTree(Mod+1) andview.toggleStructure(Mod+2, Lutra's own).ui/src/components/structure/structure.ts(Piniastructure, started by the window) follows the editor's active tab andoutlineChangedfor that buffer, drops answers overtaken by a newer request, validates the untrusted outline (depth cap 64, at most 50,000 items) and remembers collapsed nodes per buffer by the path of kinds and names.StructureToolWindow.vueis a WAI-ARIA tree: kind icons from Lucide coloured with--lt-syntax-*tokens, the name and the signature; arrows, Home/End, Left/Right fold, Enter or a click jumps througheditor.revealto the start of the name; empty states for no file, no declarations, still parsing and too large. - Measured (release, Windows 11, generated 1 MB PHP file with 16,281 outline items, other builds running):
buffer.editunder the lock at most 0.07–0.25 ms,pump_vfsat most 3.8 ms; first outline 0.9–1.3 s afterfile.open(full parse ~0.75 s plus outline); edit tooutlineChanged0.43–0.76 s (200 ms debounce, incremental reparse 9–14 ms, outline with JSON 0.2–0.3 s, pump interval).syntax.outlineitself takes 82 ms on that file, because the engine deep-copies the stored JSON into the command result; typing is not blocked by it (the editor syncs asynchronously), but the engine lock is. Typical files (10–50 KB) are a few milliseconds end to end.cargo test --release -p lutra-engine --test syntax -- --ignored --nocapturerepeats it.
Go-to popup (M2.6)
ui/src/components/goto/GotoPopup.vue(mounted inApp.vue) with the state inui/src/stores/goto.ts. One popup, three modes (file,class,symbol) as tabs; Tab / Shift+Tab or a click switches the mode and re-runs the same text in it.- UI commands
goto.fileOpen(Mod+P),goto.classOpen(Mod+Alt+C),goto.symbolOpen(Mod+T), each with an optional{query}so an agent can open the popup on a query overuiCommand; enabled only while a project is open. The shortcuts are Lutra's own. - Live query: typing waits 60 ms after the last keystroke, then runs the mode's
goto.*withlimit: 100; every query takes a sequence number, and an answer that is not the newest is dropped (also after the popup closed). Mode switches and a{query}from the params query at once. - Rows: file items split
matchesat the file name (name marked in the label, directory in the second column); class and symbol answers carry no ranges, so the popup marks the query's characters in order in the name (after::forClass::member). The second column is the namespace, or the container for members.library: truerows are dimmed and labelled. Untrusted fields are checked; malformed items and ranges are dropped or clamped. - Indexing:
indexing: trueshows a hint with the latestindexProgress {done, total};indexReadyre-runs the open query. - Opening: Enter or a click closes the popup (focus goes back) and runs
editor.revealwith{path}for files (the file's cursor stays) or{path, line, column}for symbols. The popup is an exclusive modal (ModalIdgotoincommands/modals.ts). Like the palette it is a launcher: running any command other than the three open commands closes it (commands/store.ts›execute), so an agent'seditor.revealnever leaves it open. - Live check (debug build, bundled UI, port 7826, temp project with 34 files and a
vendor/folder):goto.fileOpen {query: "user"}listed the two project files before the vendor one with itslibrarylabel;goto.classOpen {query: "usr"}andgoto.symbolOpen {query: "User::find"}switched the tab with marks shown;palette.openthengoto.fileOpenleft only the popup; aneditor.revealof the symbol item closed the popup and put the cursor onfind.goto.fileanswered in < 1 ms over the control channel. Enter and clicks cannot be sent over the control channel; Vitest covers them.
LSP client (M3.2)
crates/lsp(L3; the client depends onlutra-textandserde_jsononly, the toolchain module of M3.1 addslutra-vfs,ureq,rustls,ringandrustls-native-certs) is a library; the engine wiring is M3.3.Server::spawn(command, args, root, ServerOptions)starts the process inrootwith piped stdio (on Windows withCREATE_NO_WINDOW) and returns at once with the server and a boundedReceiver<ServerEvent>(capacity 4096; overflow drops and counts,dropped_events()). A spawn error (missing executable, relative root) is returned synchronously.- Threads, no async runtime: per process a writer (the only one touching stdin, fed by a channel), a reader (frames from stdout), a stderr drain; per server a supervisor that watches the process, expires timeouts every 20 ms, restarts and shuts down. A server is a few blocking pipes and the engine pump is synchronous, so threads with channels are simpler than pulling an executor into L3. All writes happen under the client's one mutex, so messages leave in the order the state changed; callbacks always run outside it (a panicking callback is caught).
- Framing (
jsonrpc):Content-Lengthheaders (case-insensitive, other headers ignored, header lines capped at 1 KiB and 16 per frame), bodies capped at 32 MiB (MAX_MESSAGE_BYTES; an oversized body is read and discarded without buffering). A malformed header block, invalid JSON or a message that is neither request, response nor notification becomesServerEvent::ProtocolError(reason)(the log line) and the reader carries on with the next frame. serde_json's recursion limit bounds nesting. Proptests: message round trips, random bytes, header-like noise, recovery after bad frames, random JSON bodies. - Initialize:
initialize(processId, clientInfo, rootUri/rootPath, one workspace folder,initializationOptionsfrom the options) with the capabilities ofclient_capabilities(): incremental sync withdidSave, completion (no snippets, markdown/plain documentation, context), hover, signatureHelp, definition (links), references, rename with prepare,publishDiagnosticswith versions,workspace/configuration, workspace folders, work-done progress,positionEncodings: ["utf-16"]; no dynamic registration and noapplyEdit. Theninitialized, every open document is (re)opened, queued requests are sent, and the status becomesReady. A server choosing another encoding is logged.initializetimes out after 30 s; a failed or lateinitializecounts as a crash. - Requests:
request/request_timeoutreturn aRequestHandle(wait,wait_timeout,try_result,cancel);request_withtakes a callback instead. Typed helpers:completion(path, position, trigger),hover,signature_help,definition,references(..., include_declaration),prepare_rename,rename(..., new_name); results are raw JSON, with parsers intypesforLocation::list_from_json,WorkspaceEdit::from_json(documentChanges or changes; resource operations flagged, malformed edits mark itincomplete) andPublishDiagnostics. Requests issued beforeReadyare queued (the timeout runs from the call). Every request resolves exactly once: result,Responseerror,Timeout(default 10 s;$/cancelRequestis sent),Cancelled(also sends$/cancelRequest),ServerCrashed, orStopped. At most 1024 requests are pending. - Server requests:
workspace/configurationgets onenullper item (at most 1000);window/workDoneProgress/createand capability (un)registration are acknowledged withnull;window/showMessageRequestis shown as aShowMessageevent and answerednull;workspace/workspaceFoldersreturns the root; everything else getsMethodNotFound. Notifications becomeDiagnostics,LogMessage,ShowMessage,Progressor the genericNotification; stderr lines becomeStderr(4 KiB cap). - Supervision: a process exit, a failed
initializeor a broken watch is a crash. Requests sent to that process fail withServerCrashed, queued ones wait. The status goes toRestarting {crashes, delay, reason}with delays 1 s, 2 s, 4 s ... capped at 30 s (doubling per crash in the window); the fifth crash within 2 min ends inFailed {message}and fails everything withStopped. All of it isRestartPolicyin the options (the tests use milliseconds). After a restart every open document is reopened with its current text and version. - Document sync: the client keeps each open document in a
lutra_text::Buffer.did_open(path, language_id, text)(version 1),did_change(path, &[Edit])with byte-range edits as inBuffer::apply,did_change_full(path, text),did_save(path)(with the text if the server asks),did_close(path); each change bumps the version and returns it. Edits become UTF-16 content changes (content_changes): touching edits are merged and the changes are sent from the end of the text to the start, so sequential application on the server equals the atomic batch, also across CRLF and surrogate pairs (property-tested). The server'stextDocumentSyncdecides incremental, full or nodidChange. Edits that do not fit the client's copy fail withLspError::Textand leave it unchanged. Document operations never fail because of the server's state: beforeReadyor while restarting they only update the copy. - Shutdown:
shutdown(self)sendsshutdown(waits up to 2 s),exit, kills after 1 s, fails what is pending withStoppedand reportsStopped; it blocks for up to about 3 s, so callers run it off the engine lock. Dropping theServerrequests the same stop in the background. - URIs (
uri):path_to_uripercent-encodes everything except unreserved characters,/and a drive colon (file:///C:/a%20b.php, UNC asfile://host/share);uri_to_pathaccepts escapes in any case, an encoded drive colon andlocalhost, and upper-cases the drive letter; bad escapes, NUL and other schemes giveNone. - Tests: the fake server
src/bin/lutra-lsp-fake.rs(a test fixture, started viaCARGO_BIN_EXE_lutra-lsp-fake) covers initialize, server requests, log and stderr, typed requests and errors, queueing before ready, timeout and cancel with$/cancelRequest, incremental and full sync (the fake applies the changes and publishes the text as a diagnostic), malformed output, crash, restart and reopen, initialize errors, giving up with the backoff sequence, shutdown and spawn errors (13 tests, about 0.5 s).real_phpactoris ignored and runs withLUTRA_PHPACTOR(path tophpactor.phar,LUTRA_PHPfor PHP); it was not run in M3.2 (no Phpactor on the dev machine yet; M3.1 downloads it).
Child processes (H1)
lutra_proc::spawn(Command) -> io::Result<lutra_proc::Child> starts every external tool Lutra runs (Phpactor and the php -v probe now; git, php -l and others next) in a group the OS tears down when Lutra's process ends, even when Lutra is killed hard.
- Windows: one job object per child with
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE(windows-sys). Lutra holds the only handle, so dropping theChildor the end of Lutra's process (the kernel closes its handles) kills the child and everything it started. Jobs nest (Windows 8+), so this works when Lutra itself runs in a job (terminal,cargo, CI).crates/proc/src/windows.rsis the only module that allowsunsafe(FFI). - Unix: the child leads a new process group; a
/bin/shwatchdog in its own group blocks on a pipe only Lutra holds and sendsSIGKILLto the child's group when the pipe closes (drop, kill, quit, or aSIGKILLof Lutra). Left behind after aSIGKILLof Lutra: processes that left the group themselves (setsid/setpgid, daemons), and the child if Lutra dies between starting it and starting its watchdog. Compiled and tested by CI only (no Unix machine here). Childdereferences tostd::process::Child.Child::killreplaces the standardkilland takes the whole group;kill_and_waitalso reaps;Dropkills the group and reaps.- A child runs for a moment before it joins its job (Windows) or before its watchdog exists (Unix); a grandchild started in those microseconds can escape.
- Tests:
crates/proc/tests/process_tree.rsstartslutra-proc-helper, which starts a sleeping grandchild holding the test's pipe. A hard kill of the helper (TerminateProcess/SIGKILL, with and without the helper itself in a group),Child::killand drop each end the tree; the pipe reaches end of file. WithoutKILL_ON_JOB_CLOSEthe hard-kill tests fail. - The integrated terminal (portable-pty) does not use it yet. On Unix portable-pty makes the shell a session leader, and closing the PTY master on Lutra's exit hangs it up. On Windows the ConPTY host ends its clients when its pipes break; joining the shell to a job needs an adopt-by-handle API (
portable_pty::Child::as_raw_handle), a follow-up.
Terminal (M3.6)
- Library:
crates/terminal(L3) wrapsportable-pty(MIT; ConPTY on Windows, a Unix pty elsewhere).Session::spawn(SpawnOptions {shell, cwd, cols, rows, env})starts the shell withTERM=xterm-256color,COLORTERM=truecolor,TERM_PROGRAM=Lutra. Each session has three threads, so no call blocks the caller: a reader (16 KiB reads,Utf8Chunkerjoins a character split across reads and turns invalid bytes into U+FFFD likefrom_utf8_lossy), a writer (input queue of at most 64 pieces of 64 KiB; a full queue fails withInputFullinstead of blocking), and a waiter that records the exit code and then closes the pty, because ConPTY reports the end of output only once the pseudo console is closed.default_shell():pwsh.exefromPATH(with-NoLogo), thenpowershell.exe, then%COMSPEC%/cmd.exeon Windows;$SHELLor/bin/shon Unix. - Buffer and drop policy: each session buffers at most 1 MiB of decoded text (
OUTPUT_CAP). When it is full the reader stops reading, so the shell blocks on its next write (backpressure): nothing is dropped while a session runs. Output still buffered when a session is closed or killed is dropped.exit()reports the code once the shell exited, its output was read to the end (or 500 ms passed, for a background process that keeps the pty open) and the buffer is empty, so the exit always follows the last output. - Engine:
cmd/terminal.rs.terminal.create {cwd?, shell?, cols, rows}→{terminalId}(enabled with a project; cwd project-relative or absolute, default the root; 1–1000 columns and rows; at most 16 terminals),terminal.input {terminalId, data}(≤ 1 MiB),terminal.resize {terminalId, cols, rows},terminal.close {terminalId}→{closed}. EventsterminalOutput {terminalId, data}andterminalExited {terminalId, code}(code: nullwhen Lutra closed the terminal) are the variants ofcmd::terminal::TerminalEvent, appended toEventas one untagged variant so thatevent.rstakes a one-line append and each variant keeps its ownkind. The pump emits oneterminalOutputper terminal with at most 64 KiB, at most 256 KiB over all terminals, round-robin; with the desktop's 100 ms pump that caps the stream at about 2.5 MB/s and the shell waits beyond it. Under the engine lock only spawning, queueing input, resizing and killing happen. - Lifecycle: a terminal belongs to the project open when it was created.
cmd::terminal::sync_projectruns after every command and every pump and closes terminals whose project is gone (project.close, anotherproject.open);app.quitcloses all of them. Dropping a session kills its shell; when the process ends without that, the OS closes the pseudo console (ConPTY) or hangs up the pty (Unix). - Cursor query: ConPTY starts with
ESC[6nand waits for the answer. xterm.js answers in the app; tests answer it themselves (crates/terminal/tests/session.rs,crates/engine/tests/terminal.rs,crates/control/tests/terminal.rs). - Store:
ui/src/stores/terminal.ts(Piniaterminal): tabs, the active terminal, visibility and expansion of the Terminal tab, an output history per terminal (at most 512 Ki UTF-16 units, oldest event chunks dropped first) that a view replays when it mounts, output that arrives beforeterminal.createanswered kept by id, input sent in order with oneterminal.inputin flight (keys typed meanwhile go together), sizes deduplicated.projectCloseddrops everything. - Views:
ui/src/components/terminal/TerminalToolWindow.vuehas the sub-tab strip ("Local", "Local (2)"…, close buttons, a new-terminal button; Left/Right/Home/End/Delete on a tab) and oneTerminalView.vueper terminal, kept mounted withv-show, so switching sub-tabs keeps xterm's screen; collapsing or hiding the panel unmounts them and the history restores them.xterm.tsis the only file that imports@xterm/xtermand@xterm/addon-fit(MIT), so tests mock it. The fit addon follows aResizeObserverand reports the size withterminal.resize. Colours come from the--lt-terminal-*tokens (terminal-bg,-fg,-cursor,-selection-bgand 16-ansi-*colours, Lutra's own palette), font and size from--lt-font-monoand--lt-font-size-editor;themeChangedre-themes running terminals. Every ANSI colour that shows as text reaches 4.5:1 onterminal-bg(contrast test), except the one meant to vanish (black in dark, white and bright white in light); xterm'sminimumContrastRatiois 4.5, so text a program prints in such a colour (PSReadLine uses white) is darkened or lightened until it is readable. xterm's stylesheet paints the viewport black; the view overrides it with--lt-terminal-bg. - Focus and shortcut rule (
ui/src/components/terminal/keys.ts, applied by the commands store's keydown listener): while a terminal has the focus, only shortcuts with Mod+Shift or Mod+Alt reach Lutra (on macOS every Cmd shortcut); plain Ctrl keys (Ctrl+C,Ctrl+W,Ctrl+P,Ctrl+1…) go to the shell. Copy:Mod+Shift+C, orCtrl+Cwith a selection (Cmd+Con macOS) throughnavigator.clipboard.writeText. Paste:Mod+Shift+VorCtrl+V(Cmd+V) are left to the browser, whosepasteevent xterm handles, so no clipboard-read permission is needed. - Bottom panel tabs:
BottomPanel.vuetakestabsandv-model:active; with tabs the header shows a tab list instead of the title.MainLayout.vueshows Find and Terminal as tabs while both are visible;find.openandterminal.openmake their tool window the active tab, the close button hides the active one, and expansion is kept per tool window. terminal.open(UI command,Mod+Shift+T, Lutra's own; enabled with a project): shows the Terminal tab, creates a terminal if none is running (always with{new: true}) and focuses it.
Engine wiring and diagnostics (M3.3)
-
Where:
crates/engine/src/lsp/(mod.rs: state, pump, sync, diagnostics;session.rs: the session thread), commands incrates/engine/src/cmd/lsp_diagnostics.rs. One-line hooks inbuffer.edit(lsp::record_edits), the pump (lsp::pump),app.quit(lsp::shutdown_now),State,Eventand the registry. -
Lifecycle: one session per open project.
- It starts at the first pump where a project is open and
toolchain.statusreports a usable PHP and a ready Phpactor (php <phar> language-serverin the project root). With a host-set server (Engine::set_language_server, the fake server in tests) it starts at once. - A change of root, PHP or PHAR replaces the session. Closing the project,
lsp.restartand dropping the engine stop it. app.quitstops it synchronously (shutdown,exit, kill; quit measured at 1.55 s on Windows). The host exits right after, which would cut a background shutdown short and leavephp.exerunning.
- It starts at the first pump where a project is open and
-
Nothing heavy under the lock: each session has one thread (
lsp-session) that owns thelutra_lsp::Server, and it also spawns the process. The engine lock only enqueues jobs on the thread's FIFO:Open/Fullcarry an O(1) rope clone of the buffer; the text is built on the thread.Changecarries the edit batch thatbuffer.editapplied.Save,Close, andRun(closure)for requests.
Requests from M3.4/M3.5 go through
lsp::submiton the same queue, so a request never overtakes an edit'sdidChange(tested). -
Document sync: PHP buffers (
.php,.phtml,.inc) are opened when the pump first sees them and closed when they close.buffer.editqueues its batch asdidChangewhen the server's copy is at the edit's base version.- Otherwise the next pump resends the whole text: after a reload from disk, a restore, or a
didChangethe client copy rejected. - When the saved version of a clean buffer moves, the pump sends
didSave. - Property-tested with random edits (incremental and full sync): the fake server's copy always ends equal to the buffer.
-
Events and commands:
lspStatus {state: starting|ready|restarting|failed|stopped, message?}follows the client's status.failed(spawn error, too many crashes) also raisesnotification.lsp.failed.diagnosticsChanged {path, items: [{range: {start: {line, column}, end}, severity: error|warning|info|hint, message, source?, code?}]}per project file.- Columns are UTF-16, and files outside the project are ignored.
- A missing severity counts as error.
- Caps: at most 10,000 files, and 10,000 items each from the client.
diagnostics.list {path?}returns{files: [{path, items}]}sorted by path.lsp.statusreturns{state, message?, startupMs?}.lsp.restartis in the Tools menu.- Diagnostics are cleared (an empty
diagnosticsChangedper file) when the session ends or the server fails, so stale ones never stay. The pump handles at most 2,000 server events per call.
-
UI:
- Editor:
ui/src/components/editor/lint.tsfeeds CodeMirror's lint extension (@codemirror/lint, MIT) with wavy underlines, a gutter dot, and the message with source and code on hover.- Colours come only from tokens: error
--lt-error, warning--lt-accent, info/hint--lt-fg-muted. Dedicated diagnostic tokens are a design follow-up. - A view plugin per editor state applies its path's list when the view shows the state and on every change. CodeMirror maps ranges through edits until the next publication.
- Colours come only from tokens: error
- Problems:
ui/src/components/problems/holds the store and the tab.- The store loads
diagnostics.listandlsp.statuson start and on project open, follows the events, and hands each file tolint.ts. - The Problems tab in the bottom panel groups by file, errors first; click or Enter runs
editor.reveal. problems.openisMod+Alt+P, menu View/Problems.
- The store loads
- Editor:
-
Phpactor 2026.06.25.0 on Windows: the live check found two problems, worked around without touching the user's project.
- The event loop stalls. Its amphp event loop only runs when a message arrives on stdin, so timers stall while the client is quiet: the diagnostics debounce (
language_server.diagnostic_sleep_time) and the file watcher.- Seen: the server answered
initializein 0.8 s, but published nothing afterdidOpenand only a clearing empty list afterdidChange. - Fix: while busy (a job in the last 60 s and the server ready), the session thread sends the no-op notification
$/lutra/tick. It comes from the thread's ownrecv_timeoutloop, so it does not depend on the host's pump. - The interval sets the latency, because Phpactor's analysis advances one step per message. Edit to diagnostics (engine test with the real PHAR, measured): 5.9 s at 200 ms, 2.5 s at 50 ms, 1.5 s at 20 ms. Lutra uses 25 ms.
- The same stall means Phpactor rarely answers
shutdownin time, so the shutdown timeout is 500 ms before the kill.
- Seen: the server answered
- Subprocesses fail. Every subprocess it starts through amphp fails with
CreateProcess failed: outsourced diagnostics, the PHP lint provider, the indexer'sfindwatcher.- Fix:
initializationOptionssetlanguage_server.diagnostic_outsource: false(diagnostics run in the server process) andindexer.enabled_watchers: ["php"](a polling watcher). - The PHP lint provider still fails once and removes itself; its
window/showMessagewarning is not shown. - So Lutra has no
php -lsyntax errors on Windows yet. The worse-reflection diagnostics (missing members, unknown classes, …) work.
- Fix:
- These adjustments (tick, initialization options, short shutdown timeout) apply on Windows only (
lsp::phpactor_launch). macOS and Linux are untested.
- The event loop stalls. Its amphp event loop only runs when a message arrives on stdin, so timers stall while the client is quiet: the diagnostics debounce (
-
Measured (Windows 11, PHP 8.4.24, debug build, 16-line file):
- Phpactor is ready 0.8–0.9 s after the session starts (
startupMs). - First diagnostics after
file.open: 1.7 s in the engine test, 2.7 s in the app over the control channel. - After an edit: 1.8 s and 2.7–2.9 s, including Phpactor's 1 s debounce.
- Without the adjustments: no diagnostics within 180 s.
- Phpactor is ready 0.8–0.9 s after the session starts (
-
Known gaps:
A Phpactor process outlives Lutra when Lutra is killed.Fixed by H1: Phpactor starts throughlutra_proc::spawn(see Child processes).window/showMessageandlogMessageare dropped, and server-initiated progress is not shown.
-
Tests:
crates/engine/tests/lsp.rshas 10 tests againstlutra-lsp-fake: sync incl. UTF-16 and CRLF edits, diagnostics list/clear, reload resync, requests after edits, project close, restart, quit, missing server, crash and give-up, no server without a project, and a proptest of random edits. The ignoredreal_phpactor_reports_diagnosticsruns withLUTRA_PHPACTOR=<phar>.- Unit tests cover severity, paths, the Phpactor launch and the tick rule.
crates/control/tests/lsp.rsruns over TCP with ticks on.- Vitest:
ui/tests/editor/lint.test.tsandui/tests/problems/ProblemsToolWindow.test.ts.
Pending outcomes: commands that wait for the language server (M3.5)
- Why:
lsp.definitionreturns{locations},lsp.completionreturns items. The answer comes from Phpactor, and nothing may wait for it under the engine lock (M3.3). - API (
crates/engine/src/command.rs,engine.rs):- A command queues its request with
lsp::submit(state, |server| server.request_with(…, callback)); the callback sends into anmpscchannel. - The command returns
Outcome::pending(Pending::new(receiver, timeout, finish))at once. - The host calls
Pending::wait()without the lock. It returns when the answer arrives, the sender is dropped or the deadline passes (timeout + 1 s of grace; the request's own timeout should be shorter, so it reports first). - Then, with the lock again,
Engine::resolve(answered)runsfinish(state, reply)in the guard.replyisSome(Ok(value)),Some(Err(LspError))orNone(no answer). The finish builds the value and may change the state; a rename applies its edit here. lutra_engine::run_waiting(lock, command, params, publish)does all three steps for a host. Events of each step are published while the lock is held. Effects come from the first step.
- A command queues its request with
- Hosts:
Host::run(desktop),testkit::EngineBackendand the control protocol's test backend userun_waiting. Control-channel and MCP callers (one thread per connection) get the final value directly. - IPC and ordering:
engine_executestays a synchronous Tauri command on the main thread, so every ordinary command (buffer.editabove all) runs in call order, as before.- The new
engine_execute_waiting(#[tauri::command(async)],runWaitinginui/src/ipc.ts) runsHost::runoff the main thread, so the window stays responsive while Phpactor works. Onlylsp.*requests use it. engine_executeitself did not move off the main thread, unlike the first plan: moving it would let two ordinary commands race for the lock, and the order ofbuffer.editcalls must stay the call order.- The order towards Phpactor is fixed under the engine lock:
buffer.editqueues itsdidChangeon the session queue (lsp::record_edits) before it returns, andsubmitqueues the request on the same FIFO queue. A request therefore sees every edit whosebuffer.editreturned before it, and the frontend awaits the buffer sync'sidle()before sending one.
- Failures:
- Phpactor stalls: the request times out in
lutra-lsp; the waiter's deadline is the backstop. lsp.restart, project close,app.quit(shutdown_now) or a crash: queued jobs are dropped and in-flight requests resolve withStopped/ServerCrashed, so the waiter gets an error at once instead of hanging (test:crates/engine/tests/pending.rs).- A finish must check that its answer still applies to the state;
lsp.renamerefuses when a buffer's version changed since the request.
- Phpactor stalls: the request times out in
Code assistance: completion, hover, signature help (M3.4)
- Where:
crates/engine/src/cmd/lsp_assist.rs(commands and conversion),ui/src/components/editor/assist/(CodeMirror extensions, Markdown renderer, UI commands). One-line hooks:editorExtensions(path, buffer)inextensions.ts, the buffer handle in the editor store'sadopt, threeprovidecalls inEditorArea.vue. - Commands:
lsp.completion {id, position, triggerCharacter?}returns{items: [{label, kind, detail?, documentation?, insertText, textEdit?, additionalTextEdits?, sortText?, filterText?, deprecated?}], incomplete}.- Items are sorted by
sortText, then label, and cut at 500; a cut list isincomplete. - Snippet texts become plain text (tab stops dropped, placeholders kept), because Lutra announces no snippet support.
- Plain-text documentation is escaped into Markdown.
- Items are sorted by
lsp.hover {id, position}returns{contents (markdown, empty for nothing), range?}.lsp.signatureHelp {id, position}returns{signatures: [{label, documentation?, parameters: [{label: [start, end] | null, documentation?}], activeParameter?}], activeSignature, activeParameter}. Parameter labels become UTF-16 offsets into the signature label.- The position is checked against the buffer (UTF-16 column, not past the line end, not inside a surrogate pair). A non-PHP buffer, or a server without the provider, gives the empty result. Without a session the command fails with
failed. - Every string and list from the server is capped (labels 1 KiB, documentation 64 KiB, 32 imports per item, 32 signatures).
- Off the lock (on M3.5's pending outcomes):
- Under the lock the command validates, runs the LSP pump once (so a buffer opened a moment ago is opened on the server first) and queues a closure with
lsp::submit. That runs after every queueddidChange. - The closure sends the request with
request_with(timeout 10 s). The reply callback converts the answer on the client thread, so a big list is never converted under the lock. - It sends the result into the
Pending's channel. The host waits without the lock (wait 11 s + 1 s grace) and resolves. - The UI calls these commands with
runWaiting(engine_execute_waiting, off the main thread).
- Under the lock the command validates, runs the LSP pump once (so a buffer opened a moment ago is opened on the server first) and queues a closure with
- Editor:
- Before a request, the UI awaits the buffer sync's
idle()and drops the request if the document changed meanwhile. Positions are lines and UTF-16 columns, which CodeMirror counts the same way within a line, so CRLF files need no conversion. - Completion source (overrides CodeMirror's word completion in PHP files).
- Lutra's triggers: identifiers (not after a digit),
$,->,?->,::and namespace\, sent astriggerCharacter. Nothing inside strings or comments unless asked (Ctrl-Space,editor.complete). - The server's order becomes the boost. A complete list is filtered locally while typing; an incomplete one is asked again on each keystroke.
- Applying an item uses its
textEdit(else replaces the typed word withinsertText) and itsadditionalTextEditsin one transaction. Text typed after the request is accounted for, and overlapping imports are skipped. - The kind icon is a Lucide component rendered into the list row.
- Lutra's triggers: identifiers (not after a digit),
- Hover:
hoverTooltipafter 350 ms;editor.quickDocumentation(Mod+I) shows the same tooltip at the cursor. - Signature help:
- A state field holds the tooltip; a view plugin asks on
(and,, and while open on every edit or cursor move (120 ms debounce), dropping stale answers. Escapecloses it,Mod-Shift-Spaceandeditor.parameterInfoopen it.
- A state field holds the tooltip; a view plugin asks on
- Markdown: Lutra's own renderer builds DOM nodes with
createElement/textContentfrom a fixed element set (paragraphs, code blocks, emphasis, lists, quotes, rules). HTML in the source stays text; links and images show their text only (nohref, nosrc). No Markdown or sanitizer dependency. - Colours come only from tokens. New dependency:
@codemirror/autocomplete(MIT, already transitive).
- Before a request, the UI awaits the buffer sync's
- Measured with the real Phpactor (Windows 11, PHP 8.4, debug build, 25 ms tick,
real_phpactor_assist_latency):- Latency: completion while typing 61–109 ms (median 76 ms), ~107 ms through the control channel in the app; hover median 15–16 ms; signature help median 16 ms.
- After 70 s idle (ticks stopped): the first completion takes 92–262 ms.
- Indexing first: Phpactor answers an empty
incompletelist until it has indexed the project, which takes 2.3 s for 20 classes and ~65 s for 2,000. Its loop advances one step per stdin message, so indexing uses only ~15% of one core. - Phpactor process: 56–59 MB working set for 20 classes and 70–71 MB for 2,000. CPU while typing ~6% of one core; idle 1.5–4% while the tick window runs, ~0.1% after it.
- Tests:
crates/engine/tests/lsp_assist.rs: 6 tests againstlutra-lsp-fake, which now answers completion and signature help. They cover conversion, the trigger character, an edit seen before the request, the 500 cap, positions on CRLF and emoji lines, non-PHP buffers and no server. There is also the ignored real-PHAR test above.- Unit tests: kinds, lists, snippets, hover parts, signature spans, caps.
- Vitest
ui/tests/editor/assist/: triggers, the query, applying (text edits, typing since the request, imports, CRLF), the Markdown renderer (incl. an XSS set), hover, signature help and the UI commands.
Definition, references, rename (M3.5)
-
Commands (
crates/engine/src/cmd/lsp_nav.rs). All take{id, position: {line, column}}(buffer id, 0-based, UTF-16 column) and return a pending outcome (see above):lsp.definition(F12) returns{locations: [{path, range}]}.lsp.references(Shift+F12,includeDeclaration?default true) returns{locations: [{path, range, preview, previewColumn}]}, sorted.lsp.prepareRenamereturns{range, placeholder}or null. It uses the word at the cursor when the server has noprepareProvider.lsp.rename {…, newName}(F2) returns{files: [{path, edits, bufferId?, version?}], edits, written}.- Locations are project-relative, deduplicated and capped at 10,000. Locations outside the project are dropped: Phpactor stubs inside the PHAR, other folders, symlinks that resolve outside.
- A position outside the buffer is
invalid_params; no running server isfailed.
-
Workspace edits (
cmd/lsp_nav/edit.rs), all or nothing as far as a file system allows:- Check everything first:
- The edit is complete and has no file operations.
- Every document is inside the project.
- Every range converts (UTF-16 columns, CRLF as one break) and applies to a copy.
- Every open buffer is still at the version it had when the request was sent.
- Write closed files, each atomically through the VFS, keeping the BOM and line endings. If a write fails, the files written so far get their old text back; a failed restore is named in the error. No buffer is touched then.
- Change open buffers through
buffer.edit, one batch per buffer. They become dirty and get journal, LSP and syntax updates like typing. - Follow-up: each written file is sent to Phpactor as
didOpen→didSave→didClosewith its new text (files the user opened meanwhile are skipped), plusworkspace/didChangeWatchedFilesfor servers that watch through the client. Phpactor ignored the notification alone and kept the old names until its polling watcher noticed: in the live check a "method does not exist" error stayed, and renaming back found one use instead of four.didOpenalone reindexed only class files, not the member references of a function file. With all three, its index followed in 140 ms (real_phpactor_navigates_and_renames_across_files). Then the notificationnotification.lsp.renamed {name, edits, files, written}.
- Check everything first:
-
Undo: the frontend calls
BufferSync.beginUndoableRemote()on every tab beforelsp.renameandendUndoableRemote(version)after it. The engine's change to an open buffer then enters the CodeMirror history as one step, and Mod+Z reverts it throughbuffer.edit. Files written on disk are not part of any editor history. Without the UI (control channel, MCP) the change is applied the same way but is not undoable in an editor. -
UI (
ui/src/components/editor/nav/):nav.ts(store) supplies the context of the three engine commands withcommands.provideand calls them withrunWaitingafter the sync is idle.navExtension.ts: Mod+click goes to the definition; the cursor becomes a pointer while Mod is held; the extension remembers the view for placing the rename field.NavPicker.vue(exclusive modalnavPicker),RenameInput.vue(exclusive modalrename, the preview count fromlsp.references),ReferencesToolWindow.vue(bottom panel tabreferences), all mounted byNavLayer.vue.
-
Tests:
crates/engine/tests/lsp_nav.rsruns against the fake server's--scriptanswers. It covers definition, bad positions, references (sorted, deduplicated, outside dropped), prepareRename with and without the server, a multi-file rename over an open buffer and two closed files (one CRLF), refusals (outside the project, a bad range, a buffer edited meanwhile, bad names) and no server.- The ignored
real_phpactor_navigates_and_renames_across_filesruns withLUTRA_PHPACTOR=<phar>. - Vitest:
ui/tests/nav/nav.test.ts.
-
Live (Phpactor 2026.06.25.0, Windows 11, debug build, tick on, a 3-file temp project), measured:
Request Latency definition across files 93 ms cold, 7–18 ms warm references (4 uses in 3 files) 137–150 ms prepareRename 10–11 ms rename (4 edits, 2 files written) 28 ms in the app, 44–59 ms in the real test index follows the written files 140 ms - Phpactor took 57 MB working set (45 MB private) and 4 s of CPU over the session, about 1.6% of one core while ticking idle.
- The keys and Mod+click were not pressed in the live app: sending keys would need the window focused, and the owner was using another app. Vitest covers them.
Toolchain (M3.1)
- Owner decision D15: Lutra downloads the Phpactor PHAR itself; PHP is the user's (found through
php.executableorPATH). Library code lives incrates/lsp/src/toolchain/(L3), the engine side incrates/engine/src/cmd/toolchain.rs. - Network access: downloading the pinned Phpactor is the only network access in Lutra. It is minimal (one GET of one URL, following at most 5 redirects, HTTPS only, also on redirects), visible (a notification when it starts, ends or fails) and verifiable (pinned version, URL and SHA-256 as constants in
lutra_lsp::toolchain::phpactor; the body is checked before it is written).phpactor.autoDownload: falseturns the automatic download off,phpactor.pathreplaces the managed PHAR. An engine downloads nothing until the host callsEngine::allow_downloads(); the desktop does, tests never do, so no test reaches the network (download tests use a local HTTP server on 127.0.0.1). - Pin: phpactor
2026.06.25.0, SHA-256832510fe4cdaf27ba056b8cb66a779d18352585c74fdaac54e45a37b589559e9(4,474,352 bytes, equal to GitHub's published asset digest). The newer releases (from 2026.06.23.0 on, latest 2026.10.07.0) requireext-posix, which PHP on Windows does not have; they refuse to start there. The pin needs PHP ≥ 8.2 ("php": "^8.2"), not 8.1 as first planned, sophp::MIN_VERSIONis 8.2.0. Updating the pin means changing version, URL, hash and size together after checking the PHAR on all three platforms. - HTTP client:
ureq3 withrustls(theringprovider) and the operating system's trusted roots loaded withrustls-native-certs(Windows store, macOS keychain, Linux files orSSL_CERT_FILE).rustls-platform-verifierand ureq's defaultwebpki-rootswere rejected: both pull a CDLA-Permissive-2.0 crate (webpki-root-certs/webpki-roots), outside the licence allow list. Proxies come fromHTTPS_PROXY/ALL_PROXY/NO_PROXY. Timeouts: 15 s connect, 300 s per attempt. - Download:
download::installreads the body into memory with a cap of 32 MiB (Content-Length checked first, then the bytes read), compares its SHA-256 with the pin and only then writes<data_dir>/tools/phpactor/<version>/phpactor.pharwithlutra_vfs::write_atomic. A mismatch discards the body and leaves an existing file untouched; nothing unverified ever lies at the target path.install_with_retryretries network errors, 5xx, 408 and 429 up to 4 attempts with 2 s, 4 s, 8 s backoff; a mismatch, an oversized body and other client errors are final. A managed PHAR that no longer matches its hash counts as missing and is downloaded again. - PHP detection:
php::detectresolves the setting (a path, or a bare name looked up inPATH; empty meansphp, on Windowsphp.exe,php.bat,php.cmd), runsphp -vwithout a console window, with a 5 s timeout (killed after it) and at most 64 KiB of output read, and parses the first line starting withPHP <major>.<minor>[.<patch>](suffixes such as-devor-1ubuntu1are ignored; property-tested with random bytes). - Engine: settings
php.executable(string, default""),phpactor.path(string, default"") andphpactor.autoDownload(bool, defaulttrue), sectionphp;settings.listnow has the typesboolandstring(the settings dialog shows bool switches; a text control for string settings is a UI follow-up). One worker thread (lutra-toolchain) runs checks and the download; commands and the pump only queue jobs (merged while it works, the strongest mode wins), and its reports reach the state throughEngine::pump_vfs(cmd::toolchain::pump), like search results. Jobs start with the firsttoolchain.status, when a project opens (a download if the project has PHP files: a rootcomposer.jsonor a.php/.phtml/.incfile within 6 levels, at most 20,000 entries, skippingvendor,node_modules, hidden and cache directories; PHP is usable; Phpactor is missing; auto-download is on), when one of the three settings changes after the first check, and withtoolchain.downloadPhpactor(also with auto-download off;failedif the host allows no downloads). - Commands and event:
toolchain.status→{php: {found, path, version, error?}, phpactor: {state: missing|downloading|ready|failed|disabled, path?, version?, error?}}as last checked (the first call starts a check);toolchain.downloadPhpactor→{started}; eventtoolchainChangedwith the same shape whenever it changes. Aphpactor.pathPHAR is ready if it is a file, with no version and no hash check (the user chose it). - Notifications:
notification.toolchain.phpMissing {reason, min}(warning, when the PHP result changes to unusable),notification.toolchain.downloadStarted {version}andnotification.toolchain.downloadDone {version, seconds}(info),notification.toolchain.downloadFailed {version, reason}(error). - Live check (debug build, bundled UI, port 7931, Windows 11, PHP 8.4.24 from WinGet, a temp project with one PHP file, empty data directory):
project.open→ PHP found after 0.15 s,downloadStartedafter 0.35 s, the real download from GitHub plus SHA-256 check took 2.8 s (notification to notification, measured),toolchain.statusthenreadywith<data_dir>/tools/phpactor/2026.06.25.0/phpactor.phar, whose hash on disk equals the pin. A second run throughtoolchain.downloadPhpactorafter deleting the PHAR took 0.3 s; both toasts showed in the window.
Autosave and flushDirty (M3.10)
- One entry point:
useAutosaveStore().flushDirty(options?)(ui/src/stores/autosave.ts) waits until every tab's sync has no pending edits (editor.settleAll()), then runsfile.saveAll {skipConflicts: true}and resolves with{saved, failed: [{id, path, message}], skipped, error}; it never rejects. Calls are serialised; a call made while a flush runs queues one more flush, which later callers share. Autosave uses it, and so must every feature that needs the files on disk first (deployment after the MVP, D18; run configurations; terminal commands). Nothing is uploaded on save ("save when deploying, not deploy when saving"). - Engine helper:
file.saveAllgot the optional flagskipConflictsinstead of a new command, so there is one save-all with one result shape ({saved, failed: [{id, path, message}], skipped};skippedis always present). The flag leaves a dirty buffer alone while it is in conflict with its file:Buffersremembers the buffers it reported withfileChangedOnDisk(changed or removed while dirty); an explicitfile.save/file.saveAll, a reload from disk or closing the buffer clears it.Buffersalso keeps the FNV hash and BOM of what the file held when Lutra last read or wrote it; a dirty buffer whose file still matches it is not a conflict (our own save reported by the watcher after the user typed again, or a touch). The engine has no untitled buffers; every buffer has a path. - Triggers (each on by default,
stores/autosave.ts, started byApp.vue):editor.autosave.onBlur: the DOMblurevent ofwindowandvisibilitychangeto hidden. In the Tauri WebView they fire when the native window loses focus or is minimised; they need no Tauri capability (the window may only listen to engine events) and behave the same in Vitest. Tauri's window focus events would add a permission and an IPC hop for the same signal.editor.autosave.onTabSwitch: the editor store's active tab changes (also when a newly opened tab becomes active).editor.autosave.idleSeconds: nobufferChanged/dirtyChanged {dirty: true}event for that many seconds; edits over the control channel or from an agent count too. 0 turns it off; a changed value restarts a running timer.- A trigger does nothing while no tab is dirty and no sync has pending edits.
- Errors: one error toast per failed file,
notification.save.failed {name, reason}; a failure offile.saveAllitself becomesnotification.command.failed. Autosave shows the same failure of the same file only once until it saves again;flushDirty()called by a feature shows it every time. Skipped conflicts raise no toast: the tab already shows the changed-on-disk notice. - Safety net: the recovery journal is unchanged; it covers everything between saves.
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 | apps/lutra-desktop/build.rs downscales the owner's master assets/app-icon/icon.png (720 px, see ASSETS.md) with an area-averaging box filter into the gitignored apps/lutra-desktop/icons/: icon.png (256 px window icon) and a multi-size icon.ico (16, 32, 48, 64, 128, 256 px, PNG entries). If the master is missing or unreadable, the build prints a cargo warning and uses the placeholder generated in code (rounded otter-brown square with a pale stone). |
The icon is the owner's (M1.14); decoding uses the png build dependency already present, so no new dependency. The fallback keeps a checkout without the asset buildable and never fails the build over an icon. |
Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-24 | minor | H1: crates/proc (L0), child processes in kill-on-close groups (Windows job objects, Unix process groups with a watchdog); Phpactor and the PHP probe use it |
| 2026-10-22 | minor | M3.5: definition, references, rename (lsp_nav, workspace edits, undoable remote edits, nav UI) |
| 2026-10-22 | minor | M3.4: code assistance (lsp.completion, lsp.hover, lsp.signatureHelp on pending outcomes; editor completion source, hover, signature help, safe Markdown, assist UI commands), Phpactor latency and resources |
| 2026-10-22 | minor | M3.5 step 1: pending outcomes (Pending, Engine::resolve, run_waiting), engine_execute_waiting / runWaiting |
| 2026-10-20 | minor | M3.10: autosave (blur, tab switch, idle), flushDirty, file.saveAll {skipConflicts}, disk conflicts and own-write hashes in Buffers |
| 2026-10-21 | minor | M3.3: engine ↔ Phpactor wiring (session thread, ordered sync, lspStatus, diagnosticsChanged, diagnostics.list, lsp.status, lsp.restart), Phpactor-on-Windows workarounds, lint extension, Problems tab |
| 2026-10-19 | minor | M3.8: MCP server (lutra mcp, dual era 2026-07-28 + legacy initialize), tools, resources, event buffer; buffer.list |
| 2026-10-19 | minor | M3.9: app menu (header bar, menu.open, grouping by menuPath, launcher under the modal rule); menu paths for user commands |
| 2026-10-18 | minor | M3.6: integrated terminal (crates/terminal sessions, backpressure, terminal.*, terminalOutput/terminalExited via the pump, lifecycle, xterm.js views, terminal tokens, focus rule, bottom panel tabs) |
| 2026-10-18 | minor | M3.1: toolchain (PHP detection, pinned Phpactor download with SHA-256 check, network access note, D15), toolchain.status/toolchain.downloadPhpactor, toolchainChanged, bool and string settings |
| 2026-10-18 | minor | M3.2: LSP client library (crates/lsp: framing, supervision and restart, initialize, requests with timeout and cancel, server requests, document sync, fake server tests) |
| 2026-10-17 | minor | M3.7: lutra CLI, single instance, rendezvous file and token listener, app.auth/app.focus, CLI to L6 |
| 2026-10-17 | minor | M2.6: go-to popup (store, debounce and stale drop, modes, editor.reveal), library on goto.file items |
| 2026-10-17 | minor | M2.7: per-buffer syntax tree off the engine lock, syntax.outline, outlineChanged, left stripe, Structure tool window |
| 2026-10-17 | minor | M2.5: symbol index (crates/index: parallel build, updater, fuzzy queries), index.status, goto.file/goto.class/goto.symbol, indexProgress/indexReady via the pump, timing |
| 2026-10-17 | minor | M2.4: bottom panel, Find tool window (store, event race, one search at a time), find.open |
| 2026-10-16 | minor | M2.2: highlighting by file extension (Lezer), --lt-syntax-* tokens and classes, editor.reveal, keystroke-to-highlight measurement |
| 2026-10-16 | minor | M2.3: find in files backend (crates/search, search.find/search.cancel, searchResults/searchDone via the pump) |
| 2026-10-16 | minor | M2.1: syntax layer (tree-sitter PHP parser, incremental reparse, outline, folding, size cap, timing) |
| 2026-10-16 | minor | M1.15: modal rule (one modal at a time, restore dialog queued), recoveryResolved event |
| 2026-10-16 | minor | M1.9b: settings dialog (store, search, controls by type, reset, live updates, font-size token override) |
| 2026-10-16 | minor | M1.14: app icon from the owner's master, multi-size ICO, placeholder as fallback |
| 2026-10-16 | minor | M1.8: UI commands (ui.registerCommands, uiCommand, ui in listCommands), global keymap, command palette |
| 2026-10-16 | minor | M1.12: notifications (host emission, early-event replay, toast store and stack, deferred engine_ready) |
| 2026-10-16 | minor | M1.13: open buffers pin their parent directory in the watcher, bufferFocused, truncated listing row |
| 2026-10-16 | minor | M1.7: recovery journal (storage, debounce, removal, commands, recoveryAvailable, restore dialog) |
| 2026-10-16 | minor | M1.10: themes (light theme, editor tokens, theme.list, theme.systemPreference, themeChanged, init script from the setting, live switch, contrast test) |
| 2026-10-16 | minor | M1.9a: engine construction (EngineConfig, with_config) and settings (file, commands, settingsChanged, notification) |
| 2026-10-15 | minor | M1.11: message catalog (t, lint rule, catalog test, engine messages stay English) |
| 2026-10-15 | minor | M1.6: tabs and editor (buffer sync, CRLF offsets, shortcuts from command specs) |
| 2026-10-15 | minor | M1.4: desktop bridge (engine://event, engine_ready replay, folder picker, capabilities), UI contract fix |
| 2026-10-14 | minor | M1.3: workspace commands, edit protocol, events, events.subscribe, watched-directory limits |
| 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 |