M3.10: autosave and flushDirty

Autosave saves dirty buffers when the window loses focus (DOM blur and
visibilitychange), when the active tab changes and after
editor.autosave.idleSeconds (default 15) without an edit; three settings,
all on by default. flushDirty() in ui/src/stores/autosave.ts is the one
save-all-dirty-and-wait entry point for later deployment, run and
terminal features: it waits for pending buffer sync, then runs
file.saveAll {skipConflicts: true}; one toast per failed file.

Engine: file.saveAll takes skipConflicts and returns skipped; Buffers
tracks buffers in conflict with their file and the hash of the last
read/written content, so our own save reported late is not a conflict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-20 20:59:44 +02:00
parent 228669036c
commit e1dc24dc25
18 changed files with 996 additions and 37 deletions

View file

@ -1,6 +1,6 @@
# 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 · **Last updated:** 2026-10-19
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty` · **Last updated:** 2026-10-20
## Overview
@ -107,7 +107,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
### Workspace (M1.3)
- `State` holds `project: Option<Workspace>` (the `lutra_vfs::Project`, its watcher and the watched directories) and `buffers` (id → `OpenBuffer { buffer: lutra_text::Buffer, path, version, saved_version, bom }`). A buffer is dirty when `version != saved_version`. Ids are never reused.
- Commands: `project.open {path, force?}`, `project.close {force?}`, `project.children {dir?}`, `file.open {path}` (returns the existing buffer if the file is already open), `buffer.get {id}`, `buffer.edit {id, baseVersion, edits}`, `file.save {id}` (`Mod+S`), `file.saveAll` (`Mod+Alt+S`), `buffer.close {id, force?}`, `buffer.list` (M3.8: `[{id, path, version, dirty}]` without text, empty without a project). Everything except `project.open` and `buffer.list` is disabled without a project. Paths are project-relative with `/`; absolute paths are accepted when they lie inside the project; `..` escapes are rejected by the VFS.
- Commands: `project.open {path, force?}`, `project.close {force?}`, `project.children {dir?}`, `file.open {path}` (returns the existing buffer if the file is already open), `buffer.get {id}`, `buffer.edit {id, baseVersion, edits}`, `file.save {id}` (`Mod+S`), `file.saveAll {skipConflicts?}` (`Mod+Alt+S`; see Autosave), `buffer.close {id, force?}`, `buffer.list` (M3.8: `[{id, path, version, dirty}]` without text, empty without a project). Everything except `project.open` and `buffer.list` is disabled without a project. Paths are project-relative with `/`; absolute paths are accepted when they lie inside the project; `..` escapes are rejected by the VFS.
- Edit protocol: `edits` are `{from, to, insert}` in UTF-16 code units, all relative to the text at `baseVersion` (CodeMirror change-set semantics), non-overlapping, applied atomically. A `baseVersion` other than the current version fails with `stale_version` and changes nothing; the client refetches with `buffer.get` and reapplies its pending changes. Each successful batch increments the version by one. Limits: 100,000 edits and 64 MiB inserted per call.
- Saving writes `Buffer::save_text` (the file's dominant line ending) atomically through the VFS and keeps a UTF-8 byte order mark.
@ -133,7 +133,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits.
- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Lutra saves only on request for now (no autosave).
- Closing a dirty tab asks Save / Don't Save / Cancel; `buffer.close` without `force` failing with `unsaved_changes` also leads to the question. Since M3.10 changes are also saved automatically (see Autosave).
- Theme: the editor reads colours only from `--lt-*` tokens, including the editor tokens from M1.10 (selection, active line, cursor, gutter, match, editor font size); no fallbacks remain.
### Highlighting and editor.reveal (M2.2)
@ -166,7 +166,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- `<config_dir>/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap.
- A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-<YYYYMMDDTHHMMSSZ>` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten.
- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`). Defined in `lutra_engine::settings::DEFS`.
- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`), the autosave keys `editor.autosave.onBlur`, `editor.autosave.onTabSwitch` (bool, default true) and `editor.autosave.idleSeconds` (int 0–600, default 15; M3.10). Defined in `lutra_engine::settings::DEFS`.
- Commands: `settings.list` → `[{key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section}]` (catalog keys `settings.<key>.label` / `.description`; `section` is an id shown with `settings.section.<id>`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing.
- Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…).
@ -344,6 +344,18 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Notifications:** `notification.toolchain.phpMissing {reason, min}` (warning, when the PHP result changes to unusable), `notification.toolchain.downloadStarted {version}` and `notification.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, `downloadStarted` after 0.35 s, the real download from GitHub plus SHA-256 check took 2.8 s (notification to notification, measured), `toolchain.status` then `ready` with `<data_dir>/tools/phpactor/2026.06.25.0/phpactor.phar`, whose hash on disk equals the pin. A second run through `toolchain.downloadPhpactor` after 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 runs `file.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.saveAll` got the optional flag `skipConflicts` instead of a new command, so there is one save-all with one result shape (`{saved, failed: [{id, path, message}], skipped}`; `skipped` is always present). The flag leaves a dirty buffer alone while it is in conflict with its file: `Buffers` remembers the buffers it reported with `fileChangedOnDisk` (changed or removed while dirty); an explicit `file.save`/`file.saveAll`, a reload from disk or closing the buffer clears it. `Buffers` also 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 by `App.vue`):
- `editor.autosave.onBlur`: the DOM `blur` event of `window` and `visibilitychange` to 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`: no `bufferChanged` / `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 of `file.saveAll` itself becomes `notification.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 |
@ -361,6 +373,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 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-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.1: toolchain (PHP detection, pinned Phpactor download with SHA-256 check, network access note, D15), `toolchain.status`/`toolchain.downloadPhpactor`, `toolchainChanged`, bool and string settings |