PM: merge M3.10 autosave and flushDirty
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
5fa7f0c8b3
18 changed files with 996 additions and 37 deletions
|
|
@ -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))
|
**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).
|
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 |
|
| | 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 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 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 |
|
| **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) |
|
| 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 |
|
| Project view, VFS, file watching | 8% (est.) | ~40 |
|
||||||
| Navigation (go to class/file/symbol, recent files, structure) | 10% (est.) | ~102 |
|
| Navigation (go to class/file/symbol, recent files, structure) | 10% (est.) | ~102 |
|
||||||
| Search and replace (in file, in project, structural) | 8% (est.) | ~70 |
|
| 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 |
|
| 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-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 | 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. |
|
| 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 |
|
| 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-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-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.) |
|
| 2026-10-17 | minor | M3.7: `lutra` CLI and single instance; agent automation 10% → 18% (est.) |
|
||||||
|
|
|
||||||
|
|
@ -200,7 +200,10 @@ fn settings_changes_stream_and_persist() {
|
||||||
"ui.language": "en",
|
"ui.language": "en",
|
||||||
"php.executable": "",
|
"php.executable": "",
|
||||||
"phpactor.path": "",
|
"phpactor.path": "",
|
||||||
"phpactor.autoDownload": true
|
"phpactor.autoDownload": true,
|
||||||
|
"editor.autosave.onBlur": true,
|
||||||
|
"editor.autosave.onTabSwitch": true,
|
||||||
|
"editor.autosave.idleSeconds": 15
|
||||||
}),
|
}),
|
||||||
"{r}"
|
"{r}"
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
//! Open buffers: the engine's copy of every file the user is editing.
|
//! 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 std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use lutra_text::{Buffer, LineEnding};
|
use lutra_text::{Buffer, LineEnding};
|
||||||
|
|
@ -38,6 +38,16 @@ pub struct Buffers {
|
||||||
by_id: BTreeMap<BufferId, OpenBuffer>,
|
by_id: BTreeMap<BufferId, OpenBuffer>,
|
||||||
/// The id the next buffer gets.
|
/// The id the next buffer gets.
|
||||||
next_id: BufferId,
|
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<BufferId>,
|
||||||
|
/// 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<BufferId, (String, bool)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Buffers {
|
impl Buffers {
|
||||||
|
|
@ -61,9 +71,47 @@ impl Buffers {
|
||||||
|
|
||||||
/// Removes the buffer with `id`.
|
/// Removes the buffer with `id`.
|
||||||
pub fn remove(&mut self, id: BufferId) -> Option<OpenBuffer> {
|
pub fn remove(&mut self, id: BufferId) -> Option<OpenBuffer> {
|
||||||
|
self.conflicts.remove(&id);
|
||||||
|
self.written.remove(&id);
|
||||||
self.by_id.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.
|
/// The id of the buffer for the project-relative `path`, if open.
|
||||||
pub fn find(&self, path: &Path) -> Option<BufferId> {
|
pub fn find(&self, path: &Path) -> Option<BufferId> {
|
||||||
self.by_id
|
self.by_id
|
||||||
|
|
@ -98,6 +146,8 @@ impl Buffers {
|
||||||
|
|
||||||
/// Removes every buffer.
|
/// Removes every buffer.
|
||||||
pub fn clear(&mut self) {
|
pub fn clear(&mut self) {
|
||||||
|
self.conflicts.clear();
|
||||||
|
self.written.clear();
|
||||||
self.by_id.clear();
|
self.by_id.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,12 @@
|
||||||
//! File commands: `file.open`, `file.save`, `file.saveAll`.
|
//! 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::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
@ -57,6 +65,9 @@ impl Command for Open {
|
||||||
bom: file.bom,
|
bom: file.bom,
|
||||||
};
|
};
|
||||||
let new_id = state.buffers.insert(buffer);
|
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 {
|
state.emit(Event::BufferOpened {
|
||||||
id: new_id,
|
id: new_id,
|
||||||
path: path_string(&rel),
|
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
|
/// 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
|
/// # Errors
|
||||||
/// [`EngineError::Failed`] for an unknown buffer or a failed write.
|
/// [`EngineError::Failed`] for an unknown buffer or a failed write.
|
||||||
|
|
@ -76,7 +89,13 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineErr
|
||||||
.get(id)
|
.get(id)
|
||||||
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
|
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
|
||||||
let abs = absolute(state, command, &open.path)?;
|
let abs = absolute(state, command, &open.path)?;
|
||||||
lutra_vfs::write_text(&abs, &open.buffer.save_text(), open.bom).map_err(vfs_error)?;
|
let text = open.buffer.save_text();
|
||||||
|
let bom = open.bom;
|
||||||
|
lutra_vfs::write_text(&abs, &text, bom).map_err(vfs_error)?;
|
||||||
|
state
|
||||||
|
.buffers
|
||||||
|
.note_written(id, journal::hex_hash(text.as_bytes()), bom);
|
||||||
|
state.buffers.clear_conflict(id);
|
||||||
let open = state
|
let open = state
|
||||||
.buffers
|
.buffers
|
||||||
.get_mut(id)
|
.get_mut(id)
|
||||||
|
|
@ -124,8 +143,20 @@ impl Command for Save {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Params of `file.saveAll`.
|
||||||
|
#[derive(Deserialize, Default)]
|
||||||
|
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||||
|
struct SaveAllParams {
|
||||||
|
/// Leave buffers in conflict with their file on disk unsaved and list
|
||||||
|
/// them under `skipped`.
|
||||||
|
#[serde(default)]
|
||||||
|
skip_conflicts: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// `file.saveAll`: writes every dirty buffer. A failure doesn't stop the
|
/// `file.saveAll`: writes every dirty buffer. A failure doesn't stop the
|
||||||
/// others; failures are listed in the result.
|
/// others; failures are listed in the result. With `skipConflicts` a dirty
|
||||||
|
/// buffer whose file changed or disappeared on disk is not written and is
|
||||||
|
/// listed under `skipped`.
|
||||||
pub struct SaveAll;
|
pub struct SaveAll;
|
||||||
|
|
||||||
impl Command for SaveAll {
|
impl Command for SaveAll {
|
||||||
|
|
@ -135,7 +166,7 @@ impl Command for SaveAll {
|
||||||
label: "Save All",
|
label: "Save All",
|
||||||
menu_path: Some("File/Save All"),
|
menu_path: Some("File/Save All"),
|
||||||
default_shortcut: Some("Mod+Alt+S"),
|
default_shortcut: Some("Mod+Alt+S"),
|
||||||
params: "none; returns { saved: [id], failed: [{ id, message }] }",
|
params: "{ skipConflicts?: boolean (leave buffers whose file changed on disk unsaved) }; returns { saved: [id], failed: [{ id, path, message }], skipped: [id] }",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -143,15 +174,30 @@ impl Command for SaveAll {
|
||||||
state.has_project()
|
state.has_project()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
|
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
||||||
|
let p: SaveAllParams = parse(self.spec().id, params)?;
|
||||||
let mut saved = Vec::new();
|
let mut saved = Vec::new();
|
||||||
let mut failed = Vec::new();
|
let mut failed = Vec::new();
|
||||||
|
let mut skipped = Vec::new();
|
||||||
for id in state.buffers.dirty_ids() {
|
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) {
|
match save(state, self.spec().id, id) {
|
||||||
Ok(_) => saved.push(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 }),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -224,6 +224,30 @@ pub const DEFS: &[Def] = &[
|
||||||
description_key: "settings.phpactor.autoDownload.description",
|
description_key: "settings.phpactor.autoDownload.description",
|
||||||
section: "php",
|
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.
|
/// Looks a known setting up by key.
|
||||||
|
|
@ -584,6 +608,29 @@ mod tests {
|
||||||
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
|
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]
|
#[test]
|
||||||
fn every_default_is_valid() {
|
fn every_default_is_valid() {
|
||||||
for d in DEFS {
|
for d in DEFS {
|
||||||
|
|
|
||||||
|
|
@ -278,6 +278,7 @@ pub fn pump(state: &mut State) {
|
||||||
}
|
}
|
||||||
for path in gone {
|
for path in gone {
|
||||||
if let Some(id) = state.buffers.find(&path) {
|
if let Some(id) = state.buffers.find(&path) {
|
||||||
|
state.buffers.mark_conflict(id);
|
||||||
state.emit(Event::FileChangedOnDisk {
|
state.emit(Event::FileChangedOnDisk {
|
||||||
path: path_string(&path),
|
path: path_string(&path),
|
||||||
id,
|
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
|
/// 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
|
/// 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
|
/// save), a dirty one keeps its text and the client is told, and the buffer
|
||||||
/// cannot be read is reported like a removed one.
|
/// 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) {
|
fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
||||||
let Some(open) = state.buffers.get(id) else {
|
let Some(open) = state.buffers.get(id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let path = path_string(&open.path);
|
let path = path_string(&open.path);
|
||||||
if open.dirty() {
|
let dirty = open.dirty();
|
||||||
state.emit(Event::FileChangedOnDisk {
|
|
||||||
path,
|
|
||||||
id,
|
|
||||||
removed: false,
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let file = match lutra_vfs::read_text(abs) {
|
let file = match lutra_vfs::read_text(abs) {
|
||||||
Ok(file) => file,
|
Ok(file) => file,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
|
state.buffers.mark_conflict(id);
|
||||||
state.emit(Event::FileChangedOnDisk {
|
state.emit(Event::FileChangedOnDisk {
|
||||||
path,
|
path,
|
||||||
id,
|
id,
|
||||||
|
|
@ -323,17 +322,40 @@ fn reload(state: &mut State, id: BufferId, abs: &Path) {
|
||||||
return;
|
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 {
|
if file.text == open.buffer.save_text() && file.bom == open.bom {
|
||||||
|
state.buffers.clear_conflict(id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(open) = state.buffers.get_mut(id) else {
|
let Some(open) = state.buffers.get_mut(id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
let hash = crate::journal::hex_hash(file.text.as_bytes());
|
||||||
open.buffer = Buffer::new(&file.text);
|
open.buffer = Buffer::new(&file.text);
|
||||||
open.bom = file.bom;
|
open.bom = file.bom;
|
||||||
open.version = open.version.saturating_add(1);
|
open.version = open.version.saturating_add(1);
|
||||||
open.saved_version = open.version;
|
open.saved_version = open.version;
|
||||||
let 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 });
|
state.emit(Event::BufferChanged { id, version });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -49,7 +49,10 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() {
|
||||||
"ui.language",
|
"ui.language",
|
||||||
"php.executable",
|
"php.executable",
|
||||||
"phpactor.path",
|
"phpactor.path",
|
||||||
"phpactor.autoDownload"
|
"phpactor.autoDownload",
|
||||||
|
"editor.autosave.onBlur",
|
||||||
|
"editor.autosave.onTabSwitch",
|
||||||
|
"editor.autosave.idleSeconds"
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
for s in list.as_array().unwrap() {
|
for s in list.as_array().unwrap() {
|
||||||
|
|
@ -112,7 +115,10 @@ fn get_set_reset_and_events() {
|
||||||
"ui.language": "en",
|
"ui.language": "en",
|
||||||
"php.executable": "",
|
"php.executable": "",
|
||||||
"phpactor.path": "",
|
"phpactor.path": "",
|
||||||
"phpactor.autoDownload": true
|
"phpactor.autoDownload": true,
|
||||||
|
"editor.autosave.onBlur": true,
|
||||||
|
"editor.autosave.onTabSwitch": true,
|
||||||
|
"editor.autosave.idleSeconds": 15
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
let out = e
|
let out = e
|
||||||
|
|
|
||||||
|
|
@ -265,7 +265,10 @@ fn save_all_saves_every_dirty_buffer() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
let out = run(&mut engine, "file.saveAll", Value::Null);
|
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");
|
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());
|
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]));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Architecture
|
# 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
|
## Overview
|
||||||
|
|
||||||
|
|
@ -107,7 +107,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
|
||||||
### Workspace (M1.3)
|
### 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.
|
- `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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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.
|
- 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)
|
### 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.
|
- `<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.
|
- 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.
|
- 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`…).
|
- 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).
|
- **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.
|
- **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)
|
## Decisions (M0)
|
||||||
|
|
||||||
| Question | Decision | Why |
|
| Question | Decision | Why |
|
||||||
|
|
@ -361,6 +373,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
|
||||||
|
|
||||||
| Date | Change | Summary |
|
| 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.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-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 |
|
| 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 |
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,13 @@
|
||||||
# Gaps
|
# 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.
|
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) |
|
| # | Gap | Milestone | Estimate (one agent) |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 | — |
|
| 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.
|
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 |
|
| 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 | G7: MCP server (M3.8) |
|
||||||
| 2026-10-19 | minor | G3: app menu (M3.9) |
|
| 2026-10-19 | minor | G3: app menu (M3.9) |
|
||||||
| 2026-10-18 | minor | G6: PHP detection and pinned Phpactor download (M3.1) |
|
| 2026-10-18 | minor | G6: PHP detection and pinned Phpactor download (M3.1) |
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
# Milestones
|
# 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).
|
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) |
|
| 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) |
|
| 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) |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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-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-19 | minor | M3.8 MCP server |
|
||||||
| 2026-10-17 | minor | M3.7 CLI and single instance |
|
| 2026-10-17 | minor | M3.7 CLI and single instance |
|
||||||
|
|
|
||||||
File diff suppressed because one or more lines are too long
|
|
@ -8,6 +8,7 @@
|
||||||
* `theme.ts`; a failed theme report raises an error toast) and the global
|
* `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
|
* 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`).
|
* editor font size applies from the start (see `stores/settings.ts`).
|
||||||
|
* Starts autosave (see `stores/autosave.ts`).
|
||||||
*/
|
*/
|
||||||
import { onMounted, onUnmounted } from "vue";
|
import { onMounted, onUnmounted } from "vue";
|
||||||
import { useCommandsStore } from "./commands/store";
|
import { useCommandsStore } from "./commands/store";
|
||||||
|
|
@ -19,6 +20,7 @@ import NotificationStack from "./components/notifications/NotificationStack.vue"
|
||||||
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
|
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
|
||||||
import SettingsDialog from "./components/settings/SettingsDialog.vue";
|
import SettingsDialog from "./components/settings/SettingsDialog.vue";
|
||||||
import { useAppStore } from "./stores/app";
|
import { useAppStore } from "./stores/app";
|
||||||
|
import { useAutosaveStore } from "./stores/autosave";
|
||||||
import { useNotificationsStore } from "./stores/notifications";
|
import { useNotificationsStore } from "./stores/notifications";
|
||||||
import { useSettingsStore } from "./stores/settings";
|
import { useSettingsStore } from "./stores/settings";
|
||||||
import { startTheme } from "./theme";
|
import { startTheme } from "./theme";
|
||||||
|
|
@ -27,6 +29,7 @@ const app = useAppStore();
|
||||||
const notifications = useNotificationsStore();
|
const notifications = useNotificationsStore();
|
||||||
const commands = useCommandsStore();
|
const commands = useCommandsStore();
|
||||||
const settings = useSettingsStore();
|
const settings = useSettingsStore();
|
||||||
|
const autosave = useAutosaveStore();
|
||||||
|
|
||||||
/** Stops following the theme; set while mounted. */
|
/** Stops following the theme; set while mounted. */
|
||||||
let stopTheme: (() => void) | null = null;
|
let stopTheme: (() => void) | null = null;
|
||||||
|
|
@ -36,6 +39,7 @@ onMounted(() => {
|
||||||
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
|
stopTheme = startTheme((error) => notifications.notifyError("theme.systemPreference", error));
|
||||||
void commands.start();
|
void commands.start();
|
||||||
void settings.start();
|
void settings.start();
|
||||||
|
autosave.start();
|
||||||
void app.loadAbout();
|
void app.loadAbout();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -43,6 +47,7 @@ onUnmounted(() => {
|
||||||
stopTheme?.();
|
stopTheme?.();
|
||||||
stopTheme = null;
|
stopTheme = null;
|
||||||
commands.stop();
|
commands.stop();
|
||||||
|
autosave.stop();
|
||||||
settings.stop();
|
settings.stop();
|
||||||
notifications.stop();
|
notifications.stop();
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -84,6 +84,7 @@
|
||||||
"notification.recovery.corrupt": "Skipped an unreadable recovery file ({file}): {reason}",
|
"notification.recovery.corrupt": "Skipped an unreadable recovery file ({file}): {reason}",
|
||||||
"notification.recovery.unavailable": "Could not read the recovery journal: {reason}",
|
"notification.recovery.unavailable": "Could not read the recovery journal: {reason}",
|
||||||
"notification.recovery.writeFailed": "Could not keep a recovery copy of {path}: {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.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.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.",
|
"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.search": "Search settings",
|
||||||
"settings.dialog.sections": "Settings sections",
|
"settings.dialog.sections": "Settings sections",
|
||||||
"settings.dialog.title": "Settings",
|
"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.description": "Size of the text in the editor, in pixels.",
|
||||||
"settings.editor.fontSize.label": "Editor font size",
|
"settings.editor.fontSize.label": "Editor font size",
|
||||||
"settings.error.int": "Enter a whole number",
|
"settings.error.int": "Enter a whole number",
|
||||||
|
|
|
||||||
353
ui/src/stores/autosave.ts
Normal file
353
ui/src/stores/autosave.ts
Normal file
|
|
@ -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<string, unknown>;
|
||||||
|
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<string, unknown>;
|
||||||
|
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<FlushResult | null>(null);
|
||||||
|
/** End of the chain of flushes; each starts after the previous one. */
|
||||||
|
let tail: Promise<unknown> = Promise.resolve();
|
||||||
|
/** A flush queued behind a running one and not started yet; later calls share it. */
|
||||||
|
let waiting: Promise<FlushResult> | null = null;
|
||||||
|
/** Failures already toasted, as message by buffer id (`""` for the command itself). */
|
||||||
|
const reported = new Map<string, string>();
|
||||||
|
/** Idle timer, null when none runs. */
|
||||||
|
let idleTimer: ReturnType<typeof setTimeout> | 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<FlushResult> {
|
||||||
|
const repeat = options.repeatErrors ?? true;
|
||||||
|
await editor.settleAll().catch(() => undefined);
|
||||||
|
const outcome = await run<unknown>(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<FlushResult> {
|
||||||
|
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<FlushResult> | 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 };
|
||||||
|
});
|
||||||
|
|
@ -26,7 +26,10 @@ export const EDITOR_COMMANDS = {
|
||||||
get: "buffer.get",
|
get: "buffer.get",
|
||||||
/** Saves a buffer: params `{ id }`. */
|
/** Saves a buffer: params `{ id }`. */
|
||||||
save: "file.save",
|
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",
|
saveAll: "file.saveAll",
|
||||||
/** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */
|
/** Closes a buffer: params `{ id, force }`; fails with `unsaved_changes`. */
|
||||||
close: "buffer.close",
|
close: "buffer.close",
|
||||||
|
|
@ -274,6 +277,19 @@ export const useEditorStore = defineStore("editor", () => {
|
||||||
await syncs.get(id)?.idle();
|
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<void> {
|
||||||
|
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`.
|
* Runs `buffer.close`.
|
||||||
*
|
*
|
||||||
|
|
@ -517,6 +533,8 @@ export const useEditorStore = defineStore("editor", () => {
|
||||||
resolveClose,
|
resolveClose,
|
||||||
save,
|
save,
|
||||||
saveAll,
|
saveAll,
|
||||||
|
settleAll,
|
||||||
|
hasUnsaved,
|
||||||
dismissNotice,
|
dismissNotice,
|
||||||
markShown,
|
markShown,
|
||||||
handleEvent,
|
handleEvent,
|
||||||
|
|
|
||||||
273
ui/tests/editor/autosave.test.ts
Normal file
273
ui/tests/editor/autosave.test.ts
Normal file
|
|
@ -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<string, unknown> }[];
|
||||||
|
/** 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<EditResult>) => void }[];
|
||||||
|
|
||||||
|
/** Latest version the fake engine reported per buffer, for `buffer.get`. */
|
||||||
|
let versions: Map<number, number>;
|
||||||
|
|
||||||
|
/** 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<string, unknown>[] {
|
||||||
|
return calls.filter((c) => c.command === "file.saveAll").map((c) => c.params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lets promises and Vue watchers run. */
|
||||||
|
async function settle(): Promise<void> {
|
||||||
|
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<void> {
|
||||||
|
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<string, unknown> }) => {
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -54,6 +54,7 @@ const RUNTIME_KEYS = new Set([
|
||||||
"notification.recovery.corrupt",
|
"notification.recovery.corrupt",
|
||||||
"notification.recovery.unavailable",
|
"notification.recovery.unavailable",
|
||||||
"notification.recovery.writeFailed",
|
"notification.recovery.writeFailed",
|
||||||
|
"notification.save.failed",
|
||||||
"notification.settings.corrupt",
|
"notification.settings.corrupt",
|
||||||
"notification.settings.corruptNotMoved",
|
"notification.settings.corruptNotMoved",
|
||||||
"notification.settings.unavailable",
|
"notification.settings.unavailable",
|
||||||
|
|
@ -68,6 +69,12 @@ const RUNTIME_KEYS = new Set([
|
||||||
"settings.appearance.theme.value.lutraDark",
|
"settings.appearance.theme.value.lutraDark",
|
||||||
"settings.appearance.theme.value.lutraLight",
|
"settings.appearance.theme.value.lutraLight",
|
||||||
"settings.appearance.theme.value.system",
|
"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.description",
|
||||||
"settings.editor.fontSize.label",
|
"settings.editor.fontSize.label",
|
||||||
"settings.php.executable.description",
|
"settings.php.executable.description",
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue