diff --git a/ROADMAP.md b/ROADMAP.md index ed8db52..c75b225 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ **Stage: pre-alpha (M2 done)** · next: M3 language server, terminal, CLI and MCP (the MVP); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate)) -> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-19 · **Change:** minor (M3.8: MCP server) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-20 · **Change:** minor (M3.10: autosave) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md). @@ -13,7 +13,7 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in | | Value | Kind | |---|---|---| | **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **~15%** (23 of 155 feature units of the public PhpStorm help have at least partial support; ~21% after the running cycle C4) | estimated | -| **Feature depth** (weighted by use, scored by behaviour) | **~3.2%** (Editor core 10% × weight 12, Navigation 10% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Settings 7% × weight 1, of 101) | estimated | +| **Feature depth** (weighted by use, scored by behaviour) | **~3.3%** (Editor core 11% × weight 12, Navigation 10% × weight 10, Project view 8% × weight 6, Search and replace 8% × weight 6, Settings 7% × weight 1, of 101) | estimated | | **To MVP (M3)** | **~12 h left** (M3 = 80 h raw × 0.15; done so far: M1 ~5.6 h, M2 ~6.1 h, measured); was ~190 h before calibration | estimated (factor per cycle: C1 0.07, C2 0.10, C3 0.14) | | **To full parity** | **~450 h** at the current factor of ~0.15 (range 300–3,300 h; the factor has risen each cycle, and deep areas such as type inference and inspections have no data yet) | estimated | @@ -41,7 +41,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a | Area | % | One agent (h) | |---|---:|---:| -| Editor core (buffers, undo, multi-caret, folding, soft wrap) | 10% (est.) | ~104 | +| Editor core (buffers, undo, multi-caret, folding, soft wrap) | 11% (est.) | ~100 | | Project view, VFS, file watching | 8% (est.) | ~40 | | Navigation (go to class/file/symbol, recent files, structure) | 10% (est.) | ~102 | | Search and replace (in file, in project, structural) | 8% (est.) | ~70 | @@ -75,6 +75,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | What landed | |---|---| +| 2026-10-20 | M3.10: autosave. Changed files are saved when you leave the Lutra window, when you switch tabs and after 15 seconds without typing; each can be turned off in Settings › Editor. Files that were changed outside Lutra are left for you to decide. Later features such as deployment save everything first through the same step. | | 2026-10-19 | M3.8: agents can drive Lutra over MCP: `claude mcp add lutra -- lutra mcp`, then Claude can list and run every command, look at the window, read open files including unsaved changes and follow what happens. Closing Lutra needs an explicit confirmation. | | 2026-10-17 | M3.7: the `lutra` command: `lutra src/Kernel.php:42` opens the file at line 42 in the running Lutra or starts it, `lutra .` opens a folder, `lutra --wait FILE` returns when the tab is closed (for `git commit`). Starting Lutra a second time hands the path to the first window. Only your user account can talk to the running instance. | | 2026-10-17 | M2.6: go to any file, class or symbol by name: `Mod+P`, `Mod+Alt+C` and `Mod+T` open one popup with Files, Classes and Symbols tabs (Tab switches); results update as you type with the matched letters marked, library code is labelled, a hint shows while the index is still building, and Enter jumps there. Agents can open it with a query. | @@ -96,6 +97,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | M3.10: autosave; Editor core 10% → 11% (est.), feature depth ~3.2% → ~3.3% | | 2026-10-18 | minor | Feature breadth measured against the full PhpStorm help inventory (155 units); M7–M9 added | | 2026-10-19 | minor | M3.8: MCP server; agent automation 18% → 26% (est.) | | 2026-10-17 | minor | M3.7: `lutra` CLI and single instance; agent automation 10% → 18% (est.) | diff --git a/crates/control/tests/events.rs b/crates/control/tests/events.rs index bac952a..fddf1ce 100644 --- a/crates/control/tests/events.rs +++ b/crates/control/tests/events.rs @@ -200,7 +200,10 @@ fn settings_changes_stream_and_persist() { "ui.language": "en", "php.executable": "", "phpactor.path": "", - "phpactor.autoDownload": true + "phpactor.autoDownload": true, + "editor.autosave.onBlur": true, + "editor.autosave.onTabSwitch": true, + "editor.autosave.idleSeconds": 15 }), "{r}" ); diff --git a/crates/engine/src/buffers.rs b/crates/engine/src/buffers.rs index a1bd57f..6b8b7cd 100644 --- a/crates/engine/src/buffers.rs +++ b/crates/engine/src/buffers.rs @@ -1,6 +1,6 @@ //! Open buffers: the engine's copy of every file the user is editing. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use lutra_text::{Buffer, LineEnding}; @@ -38,6 +38,16 @@ pub struct Buffers { by_id: BTreeMap, /// The id the next buffer gets. next_id: BufferId, + /// Buffers whose file changed or disappeared on disk while they had + /// unsaved changes ([`crate::Event::FileChangedOnDisk`]). The user has to + /// decide, so `file.saveAll {skipConflicts}` leaves them alone until an + /// explicit save or a reload settles it. + conflicts: BTreeSet, + /// What each buffer's file held when Lutra last read or wrote it: the + /// hash ([`crate::journal::hex_hash`]) of the text and the byte order + /// mark. A change on disk that matches it (our own save reported late, a + /// touch) is not a conflict. + written: BTreeMap, } impl Buffers { @@ -61,9 +71,47 @@ impl Buffers { /// Removes the buffer with `id`. pub fn remove(&mut self, id: BufferId) -> Option { + self.conflicts.remove(&id); + self.written.remove(&id); self.by_id.remove(&id) } + /// Marks buffer `id` as in conflict with its file on disk. + pub fn mark_conflict(&mut self, id: BufferId) { + if self.by_id.contains_key(&id) { + self.conflicts.insert(id); + } + } + + /// Clears the disk conflict of buffer `id` (saved or reloaded). + pub fn clear_conflict(&mut self, id: BufferId) { + self.conflicts.remove(&id); + } + + /// Whether buffer `id` is in conflict with its file on disk. + pub fn has_conflict(&self, id: BufferId) -> bool { + self.conflicts.contains(&id) + } + + /// Remembers what buffer `id`'s file holds after Lutra read or wrote it. + /// + /// # Parameters + /// - `hash`: [`crate::journal::hex_hash`] of the text. + /// - `bom`: whether the file has a byte order mark. + pub fn note_written(&mut self, id: BufferId, hash: String, bom: bool) { + if self.by_id.contains_key(&id) { + self.written.insert(id, (hash, bom)); + } + } + + /// Whether the file content `hash`/`bom` is what Lutra last read or + /// wrote for buffer `id`. + pub fn is_own_write(&self, id: BufferId, hash: &str, bom: bool) -> bool { + self.written + .get(&id) + .is_some_and(|(h, b)| h == hash && *b == bom) + } + /// The id of the buffer for the project-relative `path`, if open. pub fn find(&self, path: &Path) -> Option { self.by_id @@ -98,6 +146,8 @@ impl Buffers { /// Removes every buffer. pub fn clear(&mut self) { + self.conflicts.clear(); + self.written.clear(); self.by_id.clear(); } } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 39296d4..74d71aa 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -1,4 +1,12 @@ //! File commands: `file.open`, `file.save`, `file.saveAll`. +//! +//! `file.saveAll {skipConflicts: true}` is the engine half of "save every +//! dirty buffer and wait" (M3.10): autosave and anything that must see the +//! files on disk first (deployment, run configurations, terminal commands) +//! call it through the frontend's `flushDirty()`. It extends `file.saveAll` +//! instead of adding a command, so there is one save-all with one result +//! shape; the flag only adds the rule that a buffer in conflict with its file +//! on disk is skipped, because only the user can settle that. use serde::Deserialize; use serde_json::{Value, json}; @@ -57,6 +65,9 @@ impl Command for Open { bom: file.bom, }; let new_id = state.buffers.insert(buffer); + state + .buffers + .note_written(new_id, journal::hex_hash(file.text.as_bytes()), file.bom); state.emit(Event::BufferOpened { id: new_id, path: path_string(&rel), @@ -66,7 +77,9 @@ impl Command for Open { } /// Writes buffer `id` to its file, keeping its line ending and byte order -/// mark, and marks it clean. +/// mark, marks it clean, clears a disk conflict (saving is the user's answer +/// to it) and remembers what was written, so the watcher's report of this +/// write is not taken for an outside change. /// /// # Errors /// [`EngineError::Failed`] for an unknown buffer or a failed write. @@ -76,7 +89,13 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result Result { + fn run(&self, state: &mut State, params: Value) -> Result { + let p: SaveAllParams = parse(self.spec().id, params)?; let mut saved = Vec::new(); let mut failed = Vec::new(); + let mut skipped = Vec::new(); for id in state.buffers.dirty_ids() { + if p.skip_conflicts && state.buffers.has_conflict(id) { + skipped.push(id); + continue; + } match save(state, self.spec().id, id) { Ok(_) => saved.push(id), - Err(e) => failed.push(json!({ "id": id, "message": e.to_string() })), + Err(e) => { + let path = state + .buffers + .get(id) + .map(|b| path_string(&b.path)) + .unwrap_or_default(); + failed.push(json!({ "id": id, "path": path, "message": e.to_string() })); + } } } - Ok(Outcome::value(json!({ "saved": saved, "failed": failed }))) + Ok(Outcome::value( + json!({ "saved": saved, "failed": failed, "skipped": skipped }), + )) } } diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 1279729..02194b2 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -224,6 +224,30 @@ pub const DEFS: &[Def] = &[ description_key: "settings.phpactor.autoDownload.description", section: "php", }, + Def { + key: "editor.autosave.onBlur", + kind: Kind::Bool, + default: DefaultValue::Bool(true), + label_key: "settings.editor.autosave.onBlur.label", + description_key: "settings.editor.autosave.onBlur.description", + section: "editor", + }, + Def { + key: "editor.autosave.onTabSwitch", + kind: Kind::Bool, + default: DefaultValue::Bool(true), + label_key: "settings.editor.autosave.onTabSwitch.label", + description_key: "settings.editor.autosave.onTabSwitch.description", + section: "editor", + }, + Def { + key: "editor.autosave.idleSeconds", + kind: Kind::Int { min: 0, max: 600 }, + default: DefaultValue::Int(15), + label_key: "settings.editor.autosave.idleSeconds.label", + description_key: "settings.editor.autosave.idleSeconds.description", + section: "editor", + }, ]; /// Looks a known setting up by key. @@ -584,6 +608,29 @@ mod tests { assert_eq!(s.get("editor.fontSize"), Some(json!(14))); } + #[test] + fn autosave_defaults_and_validation() { + let mut s = Settings::in_memory(); + assert_eq!(s.get("editor.autosave.onBlur"), Some(json!(true))); + assert_eq!(s.get("editor.autosave.onTabSwitch"), Some(json!(true))); + assert_eq!(s.get("editor.autosave.idleSeconds"), Some(json!(15))); + assert_eq!(s.set("editor.autosave.onBlur", json!(false)), Ok(true)); + for bad in [json!(0), json!("false"), json!(null)] { + assert!(matches!( + s.set("editor.autosave.onTabSwitch", bad), + Err(SetError::Invalid(_)) + )); + } + assert_eq!(s.set("editor.autosave.idleSeconds", json!(0)), Ok(true)); + assert_eq!(s.set("editor.autosave.idleSeconds", json!(600)), Ok(true)); + for bad in [json!(-1), json!(601), json!(true)] { + assert!(matches!( + s.set("editor.autosave.idleSeconds", bad), + Err(SetError::Invalid(_)) + )); + } + } + #[test] fn every_default_is_valid() { for d in DEFS { diff --git a/crates/engine/src/workspace.rs b/crates/engine/src/workspace.rs index 2f8204c..4f89729 100644 --- a/crates/engine/src/workspace.rs +++ b/crates/engine/src/workspace.rs @@ -278,6 +278,7 @@ pub fn pump(state: &mut State) { } for path in gone { if let Some(id) = state.buffers.find(&path) { + state.buffers.mark_conflict(id); state.emit(Event::FileChangedOnDisk { path: path_string(&path), id, @@ -297,24 +298,22 @@ pub fn pump(state: &mut State) { /// Brings buffer `id` in line with its file after the file changed: a clean /// buffer takes the new text (unless it already matches, as after our own -/// save), a dirty one keeps its text and the client is told. A file that -/// cannot be read is reported like a removed one. +/// save), a dirty one keeps its text and the client is told, and the buffer +/// is marked as in conflict ([`crate::buffers::Buffers::mark_conflict`]). +/// A dirty buffer whose file holds exactly what Lutra last wrote is left +/// alone: that is our own save reported after the user typed again (an +/// autosave followed by a keystroke). A file that cannot be read is reported +/// like a removed one. fn reload(state: &mut State, id: BufferId, abs: &Path) { let Some(open) = state.buffers.get(id) else { return; }; let path = path_string(&open.path); - if open.dirty() { - state.emit(Event::FileChangedOnDisk { - path, - id, - removed: false, - }); - return; - } + let dirty = open.dirty(); let file = match lutra_vfs::read_text(abs) { Ok(file) => file, Err(_) => { + state.buffers.mark_conflict(id); state.emit(Event::FileChangedOnDisk { path, id, @@ -323,17 +322,40 @@ fn reload(state: &mut State, id: BufferId, abs: &Path) { return; } }; + if dirty { + if state.buffers.is_own_write( + id, + &crate::journal::hex_hash(file.text.as_bytes()), + file.bom, + ) { + return; + } + state.buffers.mark_conflict(id); + state.emit(Event::FileChangedOnDisk { + path, + id, + removed: false, + }); + return; + } + let Some(open) = state.buffers.get(id) else { + return; + }; if file.text == open.buffer.save_text() && file.bom == open.bom { + state.buffers.clear_conflict(id); return; } let Some(open) = state.buffers.get_mut(id) else { return; }; + let hash = crate::journal::hex_hash(file.text.as_bytes()); open.buffer = Buffer::new(&file.text); open.bom = file.bom; open.version = open.version.saturating_add(1); open.saved_version = open.version; let version = open.version; + state.buffers.clear_conflict(id); + state.buffers.note_written(id, hash, file.bom); state.emit(Event::BufferChanged { id, version }); } diff --git a/crates/engine/tests/settings.rs b/crates/engine/tests/settings.rs index dce81b4..076191a 100644 --- a/crates/engine/tests/settings.rs +++ b/crates/engine/tests/settings.rs @@ -49,7 +49,10 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() { "ui.language", "php.executable", "phpactor.path", - "phpactor.autoDownload" + "phpactor.autoDownload", + "editor.autosave.onBlur", + "editor.autosave.onTabSwitch", + "editor.autosave.idleSeconds" ] ); for s in list.as_array().unwrap() { @@ -112,7 +115,10 @@ fn get_set_reset_and_events() { "ui.language": "en", "php.executable": "", "phpactor.path": "", - "phpactor.autoDownload": true + "phpactor.autoDownload": true, + "editor.autosave.onBlur": true, + "editor.autosave.onTabSwitch": true, + "editor.autosave.idleSeconds": 15 }) ); let out = e diff --git a/crates/engine/tests/workspace.rs b/crates/engine/tests/workspace.rs index 38e3a14..265ae2c 100644 --- a/crates/engine/tests/workspace.rs +++ b/crates/engine/tests/workspace.rs @@ -265,7 +265,10 @@ fn save_all_saves_every_dirty_buffer() { ); } let out = run(&mut engine, "file.saveAll", Value::Null); - assert_eq!(out.value, json!({"saved": [a, b], "failed": []})); + assert_eq!( + out.value, + json!({"saved": [a, b], "failed": [], "skipped": []}) + ); assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b"); } @@ -555,3 +558,104 @@ fn buffer_list_names_open_buffers_without_text() { ); assert!(out.events.is_empty()); } + +#[test] +fn save_all_can_skip_buffers_in_conflict_with_the_disk() { + let (dir, mut engine, _) = open_project(&[("mine.php", b"one"), ("other.php", b"one")]); + let (mine, _) = open_file(&mut engine, "mine.php"); + let (other, _) = open_file(&mut engine, "other.php"); + for id in [mine, other] { + run( + &mut engine, + "buffer.edit", + json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "x"}]}), + ); + } + fs::write(dir.path().join("other.php"), "theirs").unwrap(); + wait_for( + &mut engine, + |e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == other), + ); + + let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true})); + assert_eq!( + out.value, + json!({"saved": [mine], "failed": [], "skipped": [other]}) + ); + assert_eq!( + fs::read_to_string(dir.path().join("other.php")).unwrap(), + "theirs" + ); + assert_eq!( + fs::read_to_string(dir.path().join("mine.php")).unwrap(), + "xone" + ); + + run(&mut engine, "file.save", json!({"id": other})); + assert_eq!( + fs::read_to_string(dir.path().join("other.php")).unwrap(), + "xone" + ); + run( + &mut engine, + "buffer.edit", + json!({"id": other, "baseVersion": 2, "edits": [{"from": 0, "to": 0, "insert": "y"}]}), + ); + let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true})); + assert_eq!(out.value["saved"], json!([other])); + assert_eq!(out.value["skipped"], json!([])); + + let err = engine + .execute("file.saveAll", json!({"skip": true})) + .unwrap_err(); + assert_eq!(err.code(), "invalid_params"); +} + +#[test] +fn a_removed_file_is_skipped_instead_of_recreated() { + let (dir, mut engine, _) = open_project(&[("gone.php", b"one")]); + let (id, _) = open_file(&mut engine, "gone.php"); + run( + &mut engine, + "buffer.edit", + json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "x"}]}), + ); + fs::remove_file(dir.path().join("gone.php")).unwrap(); + wait_for( + &mut engine, + |e| matches!(e, Event::FileChangedOnDisk { id: got, removed: true, .. } if *got == id), + ); + let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true})); + assert_eq!(out.value["skipped"], json!([id])); + assert!(!dir.path().join("gone.php").exists()); +} + +#[test] +fn typing_right_after_a_save_is_not_a_conflict() { + let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]); + let (id, _) = open_file(&mut engine, "a.php"); + run( + &mut engine, + "buffer.edit", + json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "b"}]}), + ); + run(&mut engine, "file.saveAll", json!({"skipConflicts": true})); + run( + &mut engine, + "buffer.edit", + json!({"id": id, "baseVersion": 2, "edits": [{"from": 2, "to": 2, "insert": "c"}]}), + ); + let deadline = Instant::now() + Duration::from_millis(600); + while Instant::now() < deadline { + let events = engine.pump_vfs().unwrap(); + assert!( + !events + .iter() + .any(|e| matches!(e, Event::FileChangedOnDisk { .. })), + "{events:?}" + ); + std::thread::sleep(Duration::from_millis(25)); + } + let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true})); + assert_eq!(out.value["saved"], json!([id])); +} diff --git a/docs/architecture.md b/docs/architecture.md index b16150e..50d9371 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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` (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 - `/settings.json`, a flat JSON object of dotted keys, written with `lutra_vfs::write_atomic` on every change. Unknown keys are kept; a stored value that fails validation counts as unset. Read with a 1 MiB cap. - A file that is not a JSON object (invalid JSON, not UTF-8, too large) is renamed to `settings.json.bad-` (with `-n` if taken), the defaults are used and a `notification {level: "warning", messageKey: "notification.settings.corrupt", message, params: {reason, backup}}` is queued. If it cannot be moved, or the directory or file cannot be read, settings stay in memory for the session (`notification.settings.corruptNotMoved`, `notification.settings.unavailable`) so the file is never overwritten. -- Keys: `appearance.theme` (`lutra-dark|lutra-light|system`, default `system`), `editor.fontSize` (int 8–48, default 14), `ui.language` (`en`). 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..label` / `.description`; `section` is an id shown with `settings.section.`), `settings.get {keys?}` → `{values}`, `settings.set {key, value}` → `{value}`, `settings.reset {key}` → `{value}`. Unknown keys and bad values fail with `invalid_params`; a write failure fails with `failed` and changes nothing. - Events: `settingsChanged {keys}` when an effective value changes; `notification {id, level: info|warning|error, messageKey?, message?, params?}` (ids `n1`, `n2`…). @@ -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 `/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 | diff --git a/docs/gaps.md b/docs/gaps.md index 760d214..dc70821 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,13 +1,13 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance, MCP server); G14 English UI catalog in place · **Last updated:** 2026-10-19 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download); G7 under way (`lutra` CLI and single instance, MCP server); G14 English UI catalog in place · **Last updated:** 2026-10-20 Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. | # | Gap | Milestone | Estimate (one agent) | |---|---|---|---| | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | -| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 h | +| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~14 h | | G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar and display modes open) | M1 | ~24 h | | G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | @@ -28,7 +28,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h | | G21 | Feature breadth: the full PhpStorm help inventory has 155 feature units; ~23 have at least partial support (2026-10-18, estimated). The list lives in `plan/phpstorm/00-feature-inventory.md` with public URLs | ongoing | — | -G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. Still open: tab management beyond open/close, a conflict UI (compare and merge with the disk version), autosave, editor settings (font size, soft wrap); estimate lowered to ~16 h. +G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. Still open: tab management beyond open/close, a conflict UI (compare and merge with the disk version), local history, editor settings (soft wrap); estimate lowered to ~14 h. G4 progress: M2.1 added the structural half in `crates/syntax`: tree-sitter PHP parse and incremental reparse, outline (namespaces, class-likes, functions, members, promoted properties, enum cases; anonymous classes marked) and folding ranges, an 8 MiB parse cap, proptests and snapshots. M2.2 made highlighting visible. M2.7 added the Structure tool window: each open PHP buffer keeps a tree-sitter tree, reparsed incrementally on a worker thread off the engine lock (200 ms debounce), `syntax.outline` and `outlineChanged`, and the outline as a tree in the left tool window with jumps through `editor.reveal`. Open in G4: semantic highlighting, folding in the editor, Structure speed search, sorting and filters. Finding: a full parse of 1 MB takes 364–553 ms on the dev machine (target 50 ms; reparse 7–11 ms), so parsing must stay off the engine lock and the index must parse in parallel. @@ -50,6 +50,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | G2 shrunk: autosave and `flushDirty` (M3.10) | | 2026-10-19 | minor | G7: MCP server (M3.8) | | 2026-10-19 | minor | G3: app menu (M3.9) | | 2026-10-18 | minor | G6: PHP detection and pinned Phpactor download (M3.1) | diff --git a/docs/roadmap.md b/docs/roadmap.md index dce6a81..9e353d4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Milestones -> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-19 +> **Status:** M0 done, M1 done, M2 in progress · **Last updated:** 2026-10-20 Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 are scaled ×0.1; M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value). @@ -9,7 +9,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t | M0 | Foundation: workspace, lints, quality gate, command registry, control channel, empty window | done 2026-10-14 (CI workflow written, not yet run: hosted on Forgejo, runners unknown) | ~2 (measured) | | M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) | | M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) | -| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server done) | ~12 | +| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | in progress (M3.7 CLI and single instance, M3.8 MCP server, M3.10 autosave done) | ~12 | | M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 | | M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 | | M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 | @@ -34,6 +34,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | M3.10 autosave | | 2026-10-18 | minor | M7–M9 added from the full PhpStorm help inventory (155 feature units); raw hours, calibrate ×0.15 | | 2026-10-19 | minor | M3.8 MCP server | | 2026-10-17 | minor | M3.7 CLI and single instance | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2454862..6a739bc 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Target-app parity -> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window · **Last updated:** 2026-10-17 · **Target:** PhpStorm 2026.x +> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window · **Last updated:** 2026-10-20 · **Target:** PhpStorm 2026.x ## How this is measured @@ -14,7 +14,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour | Area | Weight | Score | Missing | Hours (one agent) | Evidence | |---|---:|---:|---|---:|---| -| Editor core | 12 | 10% (est.) | semantic highlighting and a colour scheme editor, code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~104 (est.) | M2.2: syntax highlighting by file extension (`ui/src/components/editor/language.ts`): PHP with embedded HTML/CSS/JS through `@codemirror/lang-php` (Lezer), plus HTML, CSS, JS/TS, JSON, YAML, Markdown; spans carry `lt-syntax-*` classes coloured only by the eleven `--lt-syntax-*` tokens of both themes (Lutra's own palette, ≥ 4.5:1 on the editor background and active line, contrast test). `editor.reveal {path, line, column}` opens, activates, places the cursor (UTF-16 column, CRLF-safe) and centres it; agents reach it as a UI command. Checked in the app on Windows 11 (bundled UI, control channel): PHP with embedded HTML in dark and light, `editor.reveal` into a closed CRLF file (last line, then line 302 centred). Vitest: language per extension, classes on spans for PHP/HTML and the other languages, reveal on open and closed files, CRLF mapping, clamping, bad params. keystroke to highlight on a 1 MB PHP file 3.0–11.4 ms median (jsdom, JavaScript work only, measured, not yet in the WebView). M2.1: `crates/syntax` parses PHP with tree-sitter (incremental reparse from `lutra_text` edits) and computes folding ranges (brace blocks, arrays, comments, heredocs, `use` runs); library only, nothing visible in the editor yet, so the score is unchanged. Tests: outline/folding snapshots for five PHP 8.3 fixtures, proptests (random bytes and token soups never panic, reparse equals a fresh parse, undo round trip). 1 MB parse 364–553 ms, reparse after one keystroke 7–11 ms (release, measured, machine busy). M1.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `/recovery//` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) | +| Editor core | 12 | 11% (est.) | semantic highlighting and a colour scheme editor, code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, save before run/commit (no such features yet; they will call `flushDirty`), local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~100 (est.) | M3.10: autosave (`ui/src/stores/autosave.ts`): changed files are saved on window blur / hidden page, on a tab switch and after `editor.autosave.idleSeconds` (default 15) without an edit; three settings in Settings › Editor, all on by default. `flushDirty()` is the one "save all dirty and wait" entry point (waits for pending buffer sync, then `file.saveAll {skipConflicts: true}`), for deployment, run configurations and terminal commands later. Files changed or deleted on disk while dirty are skipped, our own save reported late is not a conflict (hash of the last read/written content); one toast per failed file, not repeated by autosave. Tests: engine (`crates/engine/tests/workspace.rs`: skip conflict, removed file not recreated, typing right after a save; settings validation), Vitest with fake timers (`ui/tests/editor/autosave.test.ts`, 11 tests: idle, idle setting/0, blur, hidden page, tab switch, settings off, pending-sync wait, skipped conflicts, toasts, command failure, serialised flushes). Checked in the app on Windows 11 (bundled UI, `--control 7940`, edits via `buffer.edit`, measured): not saved 10 s after an edit, saved at 15.0 s; edit then switching tabs a→b and b→a saved in ≤ 0.1 s; edit, then another app took focus: saved in 0.75 s; no buffer dirty afterwards. Graded against `plan/phpstorm/15-autosave.md`. M2.2: syntax highlighting by file extension (`ui/src/components/editor/language.ts`): PHP with embedded HTML/CSS/JS through `@codemirror/lang-php` (Lezer), plus HTML, CSS, JS/TS, JSON, YAML, Markdown; spans carry `lt-syntax-*` classes coloured only by the eleven `--lt-syntax-*` tokens of both themes (Lutra's own palette, ≥ 4.5:1 on the editor background and active line, contrast test). `editor.reveal {path, line, column}` opens, activates, places the cursor (UTF-16 column, CRLF-safe) and centres it; agents reach it as a UI command. Checked in the app on Windows 11 (bundled UI, control channel): PHP with embedded HTML in dark and light, `editor.reveal` into a closed CRLF file (last line, then line 302 centred). Vitest: language per extension, classes on spans for PHP/HTML and the other languages, reveal on open and closed files, CRLF mapping, clamping, bad params. keystroke to highlight on a 1 MB PHP file 3.0–11.4 ms median (jsdom, JavaScript work only, measured, not yet in the WebView). M2.1: `crates/syntax` parses PHP with tree-sitter (incremental reparse from `lutra_text` edits) and computes folding ranges (brace blocks, arrays, comments, heredocs, `use` runs); library only, nothing visible in the editor yet, so the score is unchanged. Tests: outline/folding snapshots for five PHP 8.3 fixtures, proptests (random bytes and token soups never panic, reparse equals a fresh parse, undo round trip). 1 MB parse 364–553 ms, reparse after one keystroke 7–11 ms (release, measured, machine busy). M1.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `/recovery//` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) | | Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). M1.12: a folder that cannot be opened from the picker or the command line (including `unsaved_changes` when switching projects) and stopped file watching show as toasts instead of stderr (`apps/lutra-desktop/src/host.rs`, `ui/src/stores/notifications.ts`, `ui/tests/notifications/`, 19 Vitest tests; live check pending, gaming mode); score unchanged. Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not | | Navigation | 10 | 10% (est.) | go-to: recent files on an empty query, a non-project toggle (library items always show), file-type filter, `:line` suffixes, actions and text tabs, sending the list to Find; find usages, go to declaration, recent files and locations, navigation history, File Structure popup, Structure speed search, sorting and filters (visibility, inherited members), autoscroll from the caret, navigation bar, bookmarks (M1.8: a command palette over commands only) | ~102 (est.) | M2.6: go-to popup `ui/src/components/goto/` with Files / Classes / Symbols tabs (Tab and Shift+Tab or a click switch, the text stays), UI commands `goto.fileOpen` `Mod+P`, `goto.classOpen` `Mod+Alt+C`, `goto.symbolOpen` `Mod+T` (optional `{query}` for agents), live query against `goto.*` (60 ms debounce, stale answers dropped), matched characters marked, directory / namespace / container column, library rows dimmed and labelled (`goto.file` items now carry `library`), an indexing hint with progress and a re-query on `indexReady`, Enter or a click opens through `editor.reveal`, Escape closes, one modal at a time; Vitest `ui/tests/goto/`, live-checked in the app (port 7826). M2.7: Structure tool window (`ui/src/components/structure/`) in a new left stripe with Project | Structure: the active tab's outline as a tree with Lucide kind icons and signatures, follows the active tab and edits (`outlineChanged`), click or Enter jumps through `editor.reveal`, arrows fold, `view.toggleStructure` `Mod+2`; engine `syntax.outline {id}` from a per-buffer tree-sitter tree reparsed off the engine lock on a worker thread (200 ms debounce). Tests: 11 engine unit tests, engine integration tests with a proptest of random edit sequences (end at a fresh parse's outline), a control-channel test (`crates/control/tests/syntax.rs`), 13 Vitest tests (`ui/tests/structure/`). Checked in the app on Windows 11 (bundled UI, control port 7827): a class file with namespace, interface, enum, trait, class with promoted property and a function; `outlineChanged` 149 ms after `file.open`, `view.toggleStructure` shows the tree, a jump to `find` centres line 62, an added method appears about 0.3 s after `buffer.edit` (debug build). Rows were not clicked in the app (the control channel has no input method); click and Enter are covered by Vitest. 1 MB file: `buffer.edit` ≤ 0.25 ms and `pump_vfs` ≤ 3.8 ms under the lock, edit to `outlineChanged` 0.43–0.76 s, `syntax.outline` 82 ms (release, measured). Graded against `plan/phpstorm/09-structure.md`. M2.5: symbol index in `crates/index` (every project file listed, `.php` parsed in parallel from tree-sitter outlines, vendor marked library, incremental on disk and buffer changes, capped at 200,000 files) and the engine commands `index.status`, `goto.file`, `goto.class`, `goto.symbol` (fuzzy, file names weighted, `Class::member`, project before library, partial results with `indexing: true`), events `indexProgress`/`indexReady`; 20k-file / 88 MB generated project indexed in 3.9–4.2 s (release, measured), queries 2–12 ms; tests `crates/index/tests/`, `crates/engine/tests/goto.rs`, `crates/control/tests/goto.rs`; reached from the UI by M2.6. M2.1: file outline in `crates/syntax` (namespaces braced and unbraced, classes, interfaces, traits, enums with cases, functions, methods, properties incl. promoted ones, constants; UTF-16 ranges and short signatures), the base for the Structure window (M2.7) and the symbol index (M2.5); not reachable from the UI yet, score unchanged. M1.8: `ui/src/components/palette/`, `ui/src/commands/` (fuzzy ranking, recent commands, global keymap), Vitest `ui/tests/palette/`, `ui/tests/commands/` | | Search and replace | 6 | 8% (est.) | find in the current file, replace in files and in a file, scopes (module, directory, open files, custom), comment/string filters, search history, a tab per search, grouping options, merging matches on one line, find in path from the tree, structural search | ~70 (est.) | M2.4 Find tool window in a new resizable, collapsible bottom panel: query with case / whole word / regex toggles, include and exclude globs, streamed results grouped by file (sorted) with the match highlighted in the line preview, counts and elapsed time, cancel, a truncated hint, a refused regex or glob shown in place; Enter or click opens the match through `editor.reveal`, arrow keys / Page / Home / End walk the results; `find.open` (`Mod+Alt+F`, Lutra's own) prefills the selection or the word at the cursor, `find.open {query}` from an agent searches at once; a new search cancels the running one. Tests: 26 Vitest store and component tests (`ui/tests/find/FindToolWindow.test.ts`). Live check (bundled-ui debug build, control port 7824, 3-file temp project): `find.open {query}` over `uiCommand` showed 14 matches in 3 files (vendor included) grouped and highlighted in 17 ms; with `*.php` include 2 matches; revealing a result's position opened the file at the match; `find.open` without params prefilled the word at the cursor; a bad regex showed the engine's message in place (screenshots read, measured). Opening a result by mouse or Enter is covered by Vitest only (the control channel cannot click). M2.3 backend: `crates/search` (parallel `ignore` walk + `grep-searcher`: literal/regex, case, whole word, include/exclude globs, project ignore rules with `vendor/` searched and `node_modules` skipped, binary and > 8 MiB files skipped, match cap, cancel) and engine `search.find` / `search.cancel` with `searchResults` / `searchDone` events through the pump; dirty buffers are searched in their buffer text. Tests: 9 library tests incl. a property test of random queries and file bytes (`crates/search/tests/search.rs`), 3 preview/column unit tests, 4 engine tests (`crates/engine/tests/search.rs`), a TCP control-channel test (find → results → done, invalid regex, cancel; `crates/control/tests/search.rs`). 20k-file generated tree, release: first result 10–43 ms, full walk 0.66–1.43 s (measured); live over the control channel against the running app: first result 55 ms, done 386 ms on a 5,900-file project (debug build, measured) | @@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated); | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | M3.10: Editor core 10% → 11% (est.), autosave and `flushDirty`; hours 104 → 100 | | 2026-10-18 | minor | Breadth inventory: 155 units from the public help, 23 partially supported | | 2026-10-17 | minor | M2.6: Navigation 4% → 10% (est.), go-to popup; hours 108 → 102 | | 2026-10-17 | minor | M2.7: Navigation 0% → 4% (est.), Structure tool window; hours 112 → 108 | diff --git a/ui/src/App.vue b/ui/src/App.vue index 01b1a30..52a5b0b 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -8,6 +8,7 @@ * `theme.ts`; a failed theme report raises an error toast) and the global * keymap with the UI commands (see `commands/store.ts`), and loads the settings so the * editor font size applies from the start (see `stores/settings.ts`). + * Starts autosave (see `stores/autosave.ts`). */ import { onMounted, onUnmounted } from "vue"; import { useCommandsStore } from "./commands/store"; @@ -19,6 +20,7 @@ import NotificationStack from "./components/notifications/NotificationStack.vue" import RecoveryDialog from "./components/recovery/RecoveryDialog.vue"; import SettingsDialog from "./components/settings/SettingsDialog.vue"; import { useAppStore } from "./stores/app"; +import { useAutosaveStore } from "./stores/autosave"; import { useNotificationsStore } from "./stores/notifications"; import { useSettingsStore } from "./stores/settings"; import { startTheme } from "./theme"; @@ -27,6 +29,7 @@ const app = useAppStore(); const notifications = useNotificationsStore(); const commands = useCommandsStore(); const settings = useSettingsStore(); +const autosave = useAutosaveStore(); /** Stops following the theme; set while mounted. */ let stopTheme: (() => void) | null = null; @@ -36,6 +39,7 @@ onMounted(() => { stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error)); void commands.start(); void settings.start(); + autosave.start(); void app.loadAbout(); }); @@ -43,6 +47,7 @@ onUnmounted(() => { stopTheme?.(); stopTheme = null; commands.stop(); + autosave.stop(); settings.stop(); notifications.stop(); }); diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 75031cf..b537a0c 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -84,6 +84,7 @@ "notification.recovery.corrupt": "Skipped an unreadable recovery file ({file}): {reason}", "notification.recovery.unavailable": "Could not read the recovery journal: {reason}", "notification.recovery.writeFailed": "Could not keep a recovery copy of {path}: {reason}", + "notification.save.failed": "{name} could not be saved: {reason}", "notification.settings.corrupt": "Your settings file could not be read ({reason}). It was moved to {backup} and the defaults are used.", "notification.settings.corruptNotMoved": "Your settings file could not be read ({reason}) or moved aside ({error}). The defaults are used and changes are not saved.", "notification.settings.unavailable": "Settings cannot be loaded ({error}). The defaults are used and changes are not saved.", @@ -123,6 +124,12 @@ "settings.dialog.search": "Search settings", "settings.dialog.sections": "Settings sections", "settings.dialog.title": "Settings", + "settings.editor.autosave.idleSeconds.description": "Save changed files after this many seconds without typing. 0 turns idle saving off.", + "settings.editor.autosave.idleSeconds.label": "Autosave after idle (seconds)", + "settings.editor.autosave.onBlur.description": "Save changed files when the Lutra window loses focus, for example when you switch to a browser or a terminal.", + "settings.editor.autosave.onBlur.label": "Autosave when leaving the window", + "settings.editor.autosave.onTabSwitch.description": "Save changed files when you switch to another editor tab.", + "settings.editor.autosave.onTabSwitch.label": "Autosave on tab switch", "settings.editor.fontSize.description": "Size of the text in the editor, in pixels.", "settings.editor.fontSize.label": "Editor font size", "settings.error.int": "Enter a whole number", diff --git a/ui/src/stores/autosave.ts b/ui/src/stores/autosave.ts new file mode 100644 index 0000000..6c36dd1 --- /dev/null +++ b/ui/src/stores/autosave.ts @@ -0,0 +1,353 @@ +/** + * Autosave and the one "save every dirty buffer and wait" entry point. + * + * {@link useAutosaveStore}'s `flushDirty()` waits until every tab's local + * edits reached the engine (`editor.settleAll`), then runs + * `file.saveAll {skipConflicts: true}` and resolves with what was saved, + * what failed and what was skipped. It never rejects. Buffers whose file + * changed or disappeared on disk are skipped, because only the user can + * settle that (the tab shows the notice). The engine has no untitled + * buffers yet; every buffer has a path. Each failed file gets one error + * toast (`notification.save.failed`). Calls are serialised: a call made + * while a flush runs queues one more flush, and calls made while that one + * waits share it. Autosave uses it, and so must anything that needs the + * files on disk first (deployment, run configurations, terminal commands). + * Nothing is uploaded on save. + * + * Autosave triggers, each with a setting (all on by default): + * - `editor.autosave.onBlur`: the window loses focus. Lutra listens to the + * DOM `blur` event of `window` and to `visibilitychange` (hidden). In the + * Tauri WebView these fire when the native window loses focus or is + * minimised, they need no extra Tauri capability, and they work the same + * in Vitest; Tauri's own window events would add a permission and an + * IPC hop for the same signal. + * - `editor.autosave.onTabSwitch`: the active tab changes. + * - `editor.autosave.idleSeconds` (0 = off): no edit for that many seconds. + * Edits are seen as engine events (`bufferChanged`, `dirtyChanged`), so + * edits from the control channel or an agent count too. + * + * Triggers do nothing while no tab has unsaved changes. An autosave toasts + * a failure only once until that file saves again, so a file that cannot be + * written does not raise a toast on every blur. The recovery journal stays + * the safety net for anything not saved yet. + */ +import { defineStore } from "pinia"; +import { shallowRef, watch } from "vue"; +import { run, type EngineError } from "../ipc"; +import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents"; +import { baseName, EDITOR_COMMANDS, useEditorStore } from "./editor"; +import { useNotificationsStore } from "./notifications"; +import { useSettingsStore } from "./settings"; + +/** Setting keys of autosave. */ +export const AUTOSAVE_SETTINGS = { + /** Save when the window loses focus (bool, default true). */ + onBlur: "editor.autosave.onBlur", + /** Save when the active tab changes (bool, default true). */ + onTabSwitch: "editor.autosave.onTabSwitch", + /** Save after this many seconds without an edit (int 0–600, default 15; 0 = off). */ + idleSeconds: "editor.autosave.idleSeconds", +} as const; + +/** Defaults used until the settings are loaded. */ +export const AUTOSAVE_DEFAULTS = { onBlur: true, onTabSwitch: true, idleSeconds: 15 } as const; + +/** Largest idle time accepted, in seconds (the setting's maximum). */ +const MAX_IDLE_SECONDS = 600; + +/** Catalog key of the toast for a file that could not be saved. Params: `name`, `reason`. */ +export const KEY_SAVE_FAILED = "notification.save.failed"; + +/** What made an autosave run. */ +export type AutosaveTrigger = "blur" | "tabSwitch" | "idle"; + +/** A buffer that could not be saved. */ +export interface FlushFailure { + /** Buffer id. */ + id: number; + /** Project-relative path; empty when the engine did not say. */ + path: string; + /** Why. */ + message: string; +} + +/** What {@link useAutosaveStore}'s `flushDirty` did. */ +export interface FlushResult { + /** Ids of the buffers written. */ + saved: number[]; + /** Buffers that could not be written. */ + failed: FlushFailure[]; + /** Ids of dirty buffers left alone because their file changed on disk. */ + skipped: number[]; + /** Set when `file.saveAll` itself failed (no project, IPC); nothing was saved then. */ + error: EngineError | null; +} + +/** Options of `flushDirty`. */ +export interface FlushOptions { + /** + * Toast a failure again even if the same file failed with the same + * message before (default true). Autosave passes false. + */ + repeatErrors?: boolean; +} + +/** + * The ids in a list, ignoring entries that are not numbers. + * + * @param raw - an array from the engine, unchecked. + */ +function ids(raw: unknown): number[] { + return Array.isArray(raw) ? raw.filter((v): v is number => typeof v === "number") : []; +} + +/** + * Reads the result of `file.saveAll`. + * + * @param raw - `{saved, failed, skipped}`, unchecked. + */ +export function toFlushResult(raw: unknown): FlushResult { + const value = (typeof raw === "object" && raw !== null ? raw : {}) as Record; + const failed = Array.isArray(value.failed) ? value.failed : []; + return { + saved: ids(value.saved), + skipped: ids(value.skipped), + failed: failed.flatMap((f: unknown) => { + const entry = (typeof f === "object" && f !== null ? f : {}) as Record; + return typeof entry.id === "number" + ? [ + { + id: entry.id, + path: typeof entry.path === "string" ? entry.path : "", + message: typeof entry.message === "string" ? entry.message : "", + }, + ] + : []; + }), + error: null, + }; +} + +/** Store of autosave and `flushDirty`. */ +export const useAutosaveStore = defineStore("autosave", () => { + const editor = useEditorStore(); + const settings = useSettingsStore(); + const notifications = useNotificationsStore(); + + /** Result of the last flush, null before the first. */ + const lastResult = shallowRef(null); + /** End of the chain of flushes; each starts after the previous one. */ + let tail: Promise = Promise.resolve(); + /** A flush queued behind a running one and not started yet; later calls share it. */ + let waiting: Promise | null = null; + /** Failures already toasted, as message by buffer id (`""` for the command itself). */ + const reported = new Map(); + /** Idle timer, null when none runs. */ + let idleTimer: ReturnType | null = null; + /** Cleanups of the started listeners. */ + let cleanups: (() => void)[] = []; + + /** + * A boolean setting, its default until the settings are loaded. + * + * @param key - setting key. + * @param fallback - default. + */ + function flag(key: string, fallback: boolean): boolean { + const value = settings.values[key]; + return typeof value === "boolean" ? value : fallback; + } + + /** The idle time in milliseconds, 0 when idle saving is off. */ + function idleMs(): number { + const value = settings.values[AUTOSAVE_SETTINGS.idleSeconds]; + const seconds = typeof value === "number" && Number.isFinite(value) ? value : AUTOSAVE_DEFAULTS.idleSeconds; + return Math.min(Math.max(Math.trunc(seconds), 0), MAX_IDLE_SECONDS) * 1000; + } + + /** + * Shows a failure unless it was shown already and repeats are off. + * + * @param key - buffer id as text, or `""` for the command. + * @param message - the failure. + * @param repeat - show it even if shown before. + * @param show - shows the toast. + */ + function report(key: string, message: string, repeat: boolean, show: () => void): void { + if (!repeat && reported.get(key) === message) { + return; + } + reported.set(key, message); + show(); + } + + /** + * One flush: settle, save, toast the failures. A sync that cannot settle + * is ignored: the engine's text is still saved, and the sync reports its + * own error on the tab. + * + * @param options - see {@link FlushOptions}. + */ + async function flushNow(options: FlushOptions): Promise { + const repeat = options.repeatErrors ?? true; + await editor.settleAll().catch(() => undefined); + const outcome = await run(EDITOR_COMMANDS.saveAll, { skipConflicts: true }); + if (!outcome.ok) { + const result: FlushResult = { saved: [], failed: [], skipped: [], error: outcome.error }; + report("", outcome.error.message, repeat, () => notifications.notifyError(EDITOR_COMMANDS.saveAll, outcome.error)); + lastResult.value = result; + return result; + } + reported.delete(""); + const result = toFlushResult(outcome.value); + for (const id of result.saved) { + reported.delete(String(id)); + } + for (const failure of result.failed) { + const path = failure.path || (editor.tabs.find((tab) => tab.id === failure.id)?.path ?? ""); + const name = path ? baseName(path) : String(failure.id); + report(String(failure.id), failure.message, repeat, () => + notifications.notify({ + level: "error", + messageKey: KEY_SAVE_FAILED, + message: `${name}: ${failure.message}`, + params: { name, reason: failure.message }, + }), + ); + } + lastResult.value = result; + return result; + } + + /** + * Saves every dirty buffer once the pending edits reached the engine and + * resolves when that is done or failed; never rejects. Buffers in + * conflict with the disk are skipped. Call it before anything that needs + * the files on disk (deployment, run configurations, terminal commands). + * + * @param options - see {@link FlushOptions}. + * @returns what was saved, failed and skipped. + */ + function flushDirty(options: FlushOptions = {}): Promise { + if (waiting) { + return waiting; + } + const job = tail.then(() => { + waiting = null; + return flushNow(options); + }); + waiting = job; + tail = job; + return job; + } + + /** + * Runs an autosave if its trigger is on and a tab has unsaved changes. + * + * @param trigger - what happened. + * @returns the flush, or null when nothing ran. + */ + function autosave(trigger: AutosaveTrigger): Promise | null { + if (trigger === "blur" && !flag(AUTOSAVE_SETTINGS.onBlur, AUTOSAVE_DEFAULTS.onBlur)) { + return null; + } + if (trigger === "tabSwitch" && !flag(AUTOSAVE_SETTINGS.onTabSwitch, AUTOSAVE_DEFAULTS.onTabSwitch)) { + return null; + } + if (trigger === "idle" && idleMs() === 0) { + return null; + } + if (!editor.hasUnsaved()) { + return null; + } + return flushDirty({ repeatErrors: false }); + } + + /** Stops the idle timer. */ + function cancelIdle(): void { + if (idleTimer !== null) { + clearTimeout(idleTimer); + idleTimer = null; + } + } + + /** (Re)starts the idle timer after an edit, if idle saving is on. */ + function restartIdle(): void { + cancelIdle(); + const ms = idleMs(); + if (ms > 0) { + idleTimer = setTimeout(() => { + idleTimer = null; + void autosave("idle"); + }, ms); + } + } + + /** + * Restarts the idle timer for an edit seen as an engine event. + * + * @param event - an editor event. + */ + function handleEvent(event: EditorEvent): void { + if (event.kind === "bufferChanged" || (event.kind === "dirtyChanged" && event.dirty)) { + restartIdle(); + } else if (event.kind === "projectClosed" || event.kind === "projectOpened") { + cancelIdle(); + } + } + + /** The window lost focus. */ + function onBlur(): void { + void autosave("blur"); + } + + /** The page became hidden (minimised, another desktop). */ + function onVisibility(): void { + if (document.visibilityState === "hidden") { + void autosave("blur"); + } + } + + /** Starts the triggers; calling it again has no effect. */ + function start(): void { + if (cleanups.length > 0) { + return; + } + window.addEventListener("blur", onBlur); + document.addEventListener("visibilitychange", onVisibility); + const stopTabs = watch( + () => editor.activeId, + (now, before) => { + if (before !== null && now !== before) { + void autosave("tabSwitch"); + } + }, + ); + const stopIdleSetting = watch( + () => settings.values[AUTOSAVE_SETTINGS.idleSeconds], + () => { + if (idleTimer !== null) { + restartIdle(); + } + }, + ); + cleanups = [ + () => { window.removeEventListener("blur", onBlur); }, + () => { document.removeEventListener("visibilitychange", onVisibility); }, + stopTabs, + stopIdleSetting, + onEditorEvent(handleEvent), + cancelIdle, + ]; + } + + /** Stops the triggers. */ + function stop(): void { + for (const cleanup of cleanups) { + cleanup(); + } + cleanups = []; + } + + return { lastResult, flushDirty, autosave, handleEvent, start, stop }; +}); diff --git a/ui/src/stores/editor.ts b/ui/src/stores/editor.ts index 331b369..67b7b6b 100644 --- a/ui/src/stores/editor.ts +++ b/ui/src/stores/editor.ts @@ -26,7 +26,10 @@ export const EDITOR_COMMANDS = { get: "buffer.get", /** Saves a buffer: params `{ id }`. */ save: "file.save", - /** Saves every dirty buffer: result `{ saved, failed: [{ id, message }] }`. */ + /** + * Saves every dirty buffer: params `{ skipConflicts? }`, result + * `{ saved, failed: [{ id, path, message }], skipped }`. + */ saveAll: "file.saveAll", /** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */ close: "buffer.close", @@ -274,6 +277,19 @@ export const useEditorStore = defineStore("editor", () => { await syncs.get(id)?.idle(); } + /** + * Waits until the local edits of every tab reached the engine, so a + * following save writes what the user sees (autosave, `flushDirty`). + */ + async function settleAll(): Promise { + await Promise.all([...syncs.values()].map((sync) => sync.idle())); + } + + /** Whether any tab has unsaved changes or edits still on the way. */ + function hasUnsaved(): boolean { + return tabs.value.some((t) => t.dirty) || [...syncs.values()].some((sync) => sync.pending); + } + /** * Runs `buffer.close`. * @@ -517,6 +533,8 @@ export const useEditorStore = defineStore("editor", () => { resolveClose, save, saveAll, + settleAll, + hasUnsaved, dismissNotice, markShown, handleEvent, diff --git a/ui/tests/editor/autosave.test.ts b/ui/tests/editor/autosave.test.ts new file mode 100644 index 0000000..5d5b373 --- /dev/null +++ b/ui/tests/editor/autosave.test.ts @@ -0,0 +1,273 @@ +/** + * Tests of autosave and `flushDirty` (`stores/autosave.ts`) with fake + * timers: saving after idle, on window blur and hidden pages, on a tab + * switch, the settings that turn each off, waiting for pending buffer sync, + * skipped conflicts, one toast per failed file (not repeated by autosave) + * and serialised flushes. The engine is a fake behind the mocked Tauri + * `invoke`; the editor's syncs use a fake transport whose edits resolve + * when the test says so. + */ +import { createPinia, setActivePinia } from "pinia"; +import { nextTick } from "vue"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { emitEditorEvent } from "../../src/components/editor/engineEvents"; +import type { EditParams, EditResult, SyncTransport } from "../../src/components/editor/bufferSync"; +import type { RunResult } from "../../src/ipc"; +import { AUTOSAVE_SETTINGS, KEY_SAVE_FAILED, useAutosaveStore } from "../../src/stores/autosave"; +import { useEditorStore } from "../../src/stores/editor"; +import { useNotificationsStore } from "../../src/stores/notifications"; +import { useSettingsStore } from "../../src/stores/settings"; + +/** Every `engine_execute` call, in order. */ +let calls: { command: string; params: Record }[]; +/** Next result of `file.saveAll`. */ +let saveAllResult: unknown; +/** Edits the fake transport received and has not answered yet. */ +let pendingEdits: { params: EditParams; resolve: (r: RunResult) => void }[]; + +/** Latest version the fake engine reported per buffer, for `buffer.get`. */ +let versions: Map; + +/** Fake sync transport: edits wait for the test; `get` returns the latest version. */ +const transport: SyncTransport = { + edit: (params) => + new Promise((resolve) => { + pendingEdits.push({ params, resolve }); + }), + get: (id) => + Promise.resolve({ + ok: true, + value: { id, path: "x", text: "abc", version: versions.get(id) ?? 1, dirty: true, lineEnding: "lf" }, + }), +}; + +/** Answers every pending edit with success. */ +function confirmEdits(): void { + for (const edit of pendingEdits.splice(0)) { + versions.set(edit.params.id, edit.params.baseVersion + 1); + edit.resolve({ ok: true, value: { id: edit.params.id, version: edit.params.baseVersion + 1, dirty: true } }); + } +} + +/** The `file.saveAll` calls so far. */ +function saveAllCalls(): Record[] { + return calls.filter((c) => c.command === "file.saveAll").map((c) => c.params); +} + +/** Lets promises and Vue watchers run. */ +async function settle(): Promise { + for (let i = 0; i < 5; i += 1) { + await Promise.resolve(); + await nextTick(); + } +} + +/** + * Opens a tab for a fake buffer. + * + * @param id - buffer id. + * @param path - project-relative path. + * @param dirty - whether it starts dirty. + */ +async function openTab(id: number, path: string, dirty = false): Promise { + const editor = useEditorStore(); + invoke.mockImplementationOnce(() => Promise.resolve({ id, path, text: "abc", version: 1, dirty, lineEnding: "lf" })); + await editor.openFile(path); +} + +/** Marks buffer `id` edited the way the engine reports it. */ +function engineEdit(id: number, version = 2): void { + versions.set(id, version); + emitEditorEvent({ kind: "bufferChanged", id, version }); + emitEditorEvent({ kind: "dirtyChanged", id, dirty: true }); +} + +beforeEach(() => { + vi.useFakeTimers(); + setActivePinia(createPinia()); + calls = []; + pendingEdits = []; + versions = new Map(); + saveAllResult = { saved: [], failed: [], skipped: [] }; + invoke.mockReset(); + invoke.mockImplementation((cmd: string, args: { command?: string; params?: Record }) => { + if (cmd !== "engine_execute") { + return Promise.resolve(null); + } + const command = args.command ?? ""; + calls.push({ command, params: args.params ?? {} }); + if (command === "file.saveAll") { + return Promise.resolve(saveAllResult); + } + return Promise.resolve(null); + }); + useEditorStore().configure(transport, () => []); + useEditorStore().start(); + useAutosaveStore().start(); +}); + +afterEach(() => { + useAutosaveStore().stop(); + useEditorStore().stop(); + vi.useRealTimers(); +}); + +describe("autosave triggers", () => { + it("saves after the idle time without edits, counting from the last edit", async () => { + await openTab(1, "a.php"); + engineEdit(1); + await vi.advanceTimersByTimeAsync(10_000); + engineEdit(1, 3); + await vi.advanceTimersByTimeAsync(14_000); + expect(saveAllCalls()).toHaveLength(0); + await vi.advanceTimersByTimeAsync(1_000); + await settle(); + expect(saveAllCalls()).toEqual([{ skipConflicts: true }]); + }); + + it("follows the idle setting, and 0 turns idle saving off", async () => { + const settings = useSettingsStore(); + settings.values[AUTOSAVE_SETTINGS.idleSeconds] = 3; + await openTab(1, "a.php"); + engineEdit(1); + await vi.advanceTimersByTimeAsync(3_000); + await settle(); + expect(saveAllCalls()).toHaveLength(1); + settings.values[AUTOSAVE_SETTINGS.idleSeconds] = 0; + engineEdit(1, 3); + await vi.advanceTimersByTimeAsync(700_000); + await settle(); + expect(saveAllCalls()).toHaveLength(1); + }); + + it("does nothing while no tab has unsaved changes", async () => { + await openTab(1, "a.php"); + versions.set(1, 2); + emitEditorEvent({ kind: "bufferChanged", id: 1, version: 2 }); + await vi.advanceTimersByTimeAsync(20_000); + window.dispatchEvent(new Event("blur")); + await settle(); + expect(saveAllCalls()).toHaveLength(0); + }); + + it("saves when the window loses focus or the page is hidden", async () => { + await openTab(1, "a.php", true); + window.dispatchEvent(new Event("blur")); + await settle(); + expect(saveAllCalls()).toHaveLength(1); + const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden"); + document.dispatchEvent(new Event("visibilitychange")); + await settle(); + expect(saveAllCalls()).toHaveLength(2); + visibility.mockReturnValue("visible"); + document.dispatchEvent(new Event("visibilitychange")); + await settle(); + expect(saveAllCalls()).toHaveLength(2); + visibility.mockRestore(); + }); + + it("does not save on blur when that setting is off", async () => { + useSettingsStore().values[AUTOSAVE_SETTINGS.onBlur] = false; + await openTab(1, "a.php", true); + window.dispatchEvent(new Event("blur")); + await settle(); + expect(saveAllCalls()).toHaveLength(0); + }); + + it("saves when the active tab changes, unless that setting is off", async () => { + await openTab(1, "a.php"); + await openTab(2, "b.php"); + await settle(); + engineEdit(2); + expect(saveAllCalls()).toHaveLength(0); + const editor = useEditorStore(); + editor.activate(1); + await settle(); + expect(saveAllCalls()).toHaveLength(1); + useSettingsStore().values[AUTOSAVE_SETTINGS.onTabSwitch] = false; + editor.activate(2); + await settle(); + expect(saveAllCalls()).toHaveLength(1); + }); +}); + +describe("flushDirty", () => { + it("waits until pending edits reached the engine before saving", async () => { + await openTab(1, "a.php"); + const editor = useEditorStore(); + editor.syncOf(1)?.dispatch({ changes: { from: 3, insert: "d" } }); + expect(pendingEdits).toHaveLength(1); + const done = useAutosaveStore().flushDirty(); + await settle(); + expect(saveAllCalls()).toHaveLength(0); + confirmEdits(); + await settle(); + expect(saveAllCalls()).toHaveLength(1); + await expect(done).resolves.toMatchObject({ error: null }); + }); + + it("reports skipped conflicts without a toast", async () => { + saveAllResult = { saved: [1], failed: [], skipped: [2] }; + const result = await useAutosaveStore().flushDirty(); + expect(result).toEqual({ saved: [1], failed: [], skipped: [2], error: null }); + expect(useNotificationsStore().toasts).toHaveLength(0); + }); + + it("shows one toast per failed file, and autosave does not repeat it", async () => { + await openTab(1, "src/a.php", true); + saveAllResult = { + saved: [], + failed: [ + { id: 1, path: "src/a.php", message: "access denied" }, + { id: 2, message: "disk full" }, + ], + skipped: [], + }; + const notifications = useNotificationsStore(); + const result = await useAutosaveStore().flushDirty(); + expect(result.failed).toEqual([ + { id: 1, path: "src/a.php", message: "access denied" }, + { id: 2, path: "", message: "disk full" }, + ]); + expect(notifications.toasts.map((t) => t.text)).toEqual([ + "a.php could not be saved: access denied", + "2 could not be saved: disk full", + ]); + expect(notifications.toasts.every((t) => t.level === "error")).toBe(true); + window.dispatchEvent(new Event("blur")); + await settle(); + expect(saveAllCalls()).toHaveLength(2); + expect(notifications.toasts).toHaveLength(2); + await useAutosaveStore().flushDirty(); + expect(notifications.toasts).toHaveLength(4); + expect(KEY_SAVE_FAILED).toBe("notification.save.failed"); + }); + + it("toasts a failure of the command itself and resolves with the error", async () => { + invoke.mockImplementation(() => Promise.reject(Object.assign(new Error("disabled"), { code: "disabled", message: "no project" }))); + const result = await useAutosaveStore().flushDirty(); + expect(result.error?.code).toBe("disabled"); + expect(result.saved).toEqual([]); + expect(useNotificationsStore().toasts).toHaveLength(1); + }); + + it("serialises flushes and lets waiting callers share one", async () => { + await openTab(1, "a.php"); + const editor = useEditorStore(); + editor.syncOf(1)?.dispatch({ changes: { from: 0, insert: "x" } }); + const autosave = useAutosaveStore(); + const first = autosave.flushDirty(); + await settle(); + const second = autosave.flushDirty(); + const third = autosave.flushDirty(); + await settle(); + expect(saveAllCalls()).toHaveLength(0); + confirmEdits(); + await Promise.all([first, second, third]); + expect(saveAllCalls()).toHaveLength(2); + }); +}); diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 91b6b3b..6f535eb 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -54,6 +54,7 @@ const RUNTIME_KEYS = new Set([ "notification.recovery.corrupt", "notification.recovery.unavailable", "notification.recovery.writeFailed", + "notification.save.failed", "notification.settings.corrupt", "notification.settings.corruptNotMoved", "notification.settings.unavailable", @@ -68,6 +69,12 @@ const RUNTIME_KEYS = new Set([ "settings.appearance.theme.value.lutraDark", "settings.appearance.theme.value.lutraLight", "settings.appearance.theme.value.system", + "settings.editor.autosave.idleSeconds.description", + "settings.editor.autosave.idleSeconds.label", + "settings.editor.autosave.onBlur.description", + "settings.editor.autosave.onBlur.label", + "settings.editor.autosave.onTabSwitch.description", + "settings.editor.autosave.onTabSwitch.label", "settings.editor.fontSize.description", "settings.editor.fontSize.label", "settings.php.executable.description",