M3.10: autosave and flushDirty

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

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

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

View file

@ -200,7 +200,10 @@ fn settings_changes_stream_and_persist() {
"ui.language": "en",
"php.executable": "",
"phpactor.path": "",
"phpactor.autoDownload": true
"phpactor.autoDownload": true,
"editor.autosave.onBlur": true,
"editor.autosave.onTabSwitch": true,
"editor.autosave.idleSeconds": 15
}),
"{r}"
);

View file

@ -1,6 +1,6 @@
//! Open buffers: the engine's copy of every file the user is editing.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use lutra_text::{Buffer, LineEnding};
@ -38,6 +38,16 @@ pub struct Buffers {
by_id: BTreeMap<BufferId, OpenBuffer>,
/// The id the next buffer gets.
next_id: BufferId,
/// Buffers whose file changed or disappeared on disk while they had
/// unsaved changes ([`crate::Event::FileChangedOnDisk`]). The user has to
/// decide, so `file.saveAll {skipConflicts}` leaves them alone until an
/// explicit save or a reload settles it.
conflicts: BTreeSet<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 {
@ -61,9 +71,47 @@ impl Buffers {
/// Removes the buffer with `id`.
pub fn remove(&mut self, id: BufferId) -> Option<OpenBuffer> {
self.conflicts.remove(&id);
self.written.remove(&id);
self.by_id.remove(&id)
}
/// Marks buffer `id` as in conflict with its file on disk.
pub fn mark_conflict(&mut self, id: BufferId) {
if self.by_id.contains_key(&id) {
self.conflicts.insert(id);
}
}
/// Clears the disk conflict of buffer `id` (saved or reloaded).
pub fn clear_conflict(&mut self, id: BufferId) {
self.conflicts.remove(&id);
}
/// Whether buffer `id` is in conflict with its file on disk.
pub fn has_conflict(&self, id: BufferId) -> bool {
self.conflicts.contains(&id)
}
/// Remembers what buffer `id`'s file holds after Lutra read or wrote it.
///
/// # Parameters
/// - `hash`: [`crate::journal::hex_hash`] of the text.
/// - `bom`: whether the file has a byte order mark.
pub fn note_written(&mut self, id: BufferId, hash: String, bom: bool) {
if self.by_id.contains_key(&id) {
self.written.insert(id, (hash, bom));
}
}
/// Whether the file content `hash`/`bom` is what Lutra last read or
/// wrote for buffer `id`.
pub fn is_own_write(&self, id: BufferId, hash: &str, bom: bool) -> bool {
self.written
.get(&id)
.is_some_and(|(h, b)| h == hash && *b == bom)
}
/// The id of the buffer for the project-relative `path`, if open.
pub fn find(&self, path: &Path) -> Option<BufferId> {
self.by_id
@ -98,6 +146,8 @@ impl Buffers {
/// Removes every buffer.
pub fn clear(&mut self) {
self.conflicts.clear();
self.written.clear();
self.by_id.clear();
}
}

View file

@ -1,4 +1,12 @@
//! File commands: `file.open`, `file.save`, `file.saveAll`.
//!
//! `file.saveAll {skipConflicts: true}` is the engine half of "save every
//! dirty buffer and wait" (M3.10): autosave and anything that must see the
//! files on disk first (deployment, run configurations, terminal commands)
//! call it through the frontend's `flushDirty()`. It extends `file.saveAll`
//! instead of adding a command, so there is one save-all with one result
//! shape; the flag only adds the rule that a buffer in conflict with its file
//! on disk is skipped, because only the user can settle that.
use serde::Deserialize;
use serde_json::{Value, json};
@ -57,6 +65,9 @@ impl Command for Open {
bom: file.bom,
};
let new_id = state.buffers.insert(buffer);
state
.buffers
.note_written(new_id, journal::hex_hash(file.text.as_bytes()), file.bom);
state.emit(Event::BufferOpened {
id: new_id,
path: path_string(&rel),
@ -66,7 +77,9 @@ impl Command for Open {
}
/// Writes buffer `id` to its file, keeping its line ending and byte order
/// mark, and marks it clean.
/// mark, marks it clean, clears a disk conflict (saving is the user's answer
/// to it) and remembers what was written, so the watcher's report of this
/// write is not taken for an outside change.
///
/// # Errors
/// [`EngineError::Failed`] for an unknown buffer or a failed write.
@ -76,7 +89,13 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineErr
.get(id)
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
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
.buffers
.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
/// 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;
impl Command for SaveAll {
@ -135,7 +166,7 @@ impl Command for SaveAll {
label: "Save All",
menu_path: Some("File/Save All"),
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()
}
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 failed = Vec::new();
let mut skipped = Vec::new();
for id in state.buffers.dirty_ids() {
if p.skip_conflicts && state.buffers.has_conflict(id) {
skipped.push(id);
continue;
}
match save(state, self.spec().id, id) {
Ok(_) => saved.push(id),
Err(e) => failed.push(json!({ "id": id, "message": e.to_string() })),
Err(e) => {
let path = state
.buffers
.get(id)
.map(|b| path_string(&b.path))
.unwrap_or_default();
failed.push(json!({ "id": id, "path": path, "message": e.to_string() }));
}
}
}
Ok(Outcome::value(json!({ "saved": saved, "failed": failed })))
Ok(Outcome::value(
json!({ "saved": saved, "failed": failed, "skipped": skipped }),
))
}
}

View file

@ -224,6 +224,30 @@ pub const DEFS: &[Def] = &[
description_key: "settings.phpactor.autoDownload.description",
section: "php",
},
Def {
key: "editor.autosave.onBlur",
kind: Kind::Bool,
default: DefaultValue::Bool(true),
label_key: "settings.editor.autosave.onBlur.label",
description_key: "settings.editor.autosave.onBlur.description",
section: "editor",
},
Def {
key: "editor.autosave.onTabSwitch",
kind: Kind::Bool,
default: DefaultValue::Bool(true),
label_key: "settings.editor.autosave.onTabSwitch.label",
description_key: "settings.editor.autosave.onTabSwitch.description",
section: "editor",
},
Def {
key: "editor.autosave.idleSeconds",
kind: Kind::Int { min: 0, max: 600 },
default: DefaultValue::Int(15),
label_key: "settings.editor.autosave.idleSeconds.label",
description_key: "settings.editor.autosave.idleSeconds.description",
section: "editor",
},
];
/// Looks a known setting up by key.
@ -584,6 +608,29 @@ mod tests {
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
}
#[test]
fn autosave_defaults_and_validation() {
let mut s = Settings::in_memory();
assert_eq!(s.get("editor.autosave.onBlur"), Some(json!(true)));
assert_eq!(s.get("editor.autosave.onTabSwitch"), Some(json!(true)));
assert_eq!(s.get("editor.autosave.idleSeconds"), Some(json!(15)));
assert_eq!(s.set("editor.autosave.onBlur", json!(false)), Ok(true));
for bad in [json!(0), json!("false"), json!(null)] {
assert!(matches!(
s.set("editor.autosave.onTabSwitch", bad),
Err(SetError::Invalid(_))
));
}
assert_eq!(s.set("editor.autosave.idleSeconds", json!(0)), Ok(true));
assert_eq!(s.set("editor.autosave.idleSeconds", json!(600)), Ok(true));
for bad in [json!(-1), json!(601), json!(true)] {
assert!(matches!(
s.set("editor.autosave.idleSeconds", bad),
Err(SetError::Invalid(_))
));
}
}
#[test]
fn every_default_is_valid() {
for d in DEFS {

View file

@ -278,6 +278,7 @@ pub fn pump(state: &mut State) {
}
for path in gone {
if let Some(id) = state.buffers.find(&path) {
state.buffers.mark_conflict(id);
state.emit(Event::FileChangedOnDisk {
path: path_string(&path),
id,
@ -297,24 +298,22 @@ pub fn pump(state: &mut State) {
/// Brings buffer `id` in line with its file after the file changed: a clean
/// buffer takes the new text (unless it already matches, as after our own
/// save), a dirty one keeps its text and the client is told. A file that
/// cannot be read is reported like a removed one.
/// save), a dirty one keeps its text and the client is told, and the buffer
/// is marked as in conflict ([`crate::buffers::Buffers::mark_conflict`]).
/// A dirty buffer whose file holds exactly what Lutra last wrote is left
/// alone: that is our own save reported after the user typed again (an
/// autosave followed by a keystroke). A file that cannot be read is reported
/// like a removed one.
fn reload(state: &mut State, id: BufferId, abs: &Path) {
let Some(open) = state.buffers.get(id) else {
return;
};
let path = path_string(&open.path);
if open.dirty() {
state.emit(Event::FileChangedOnDisk {
path,
id,
removed: false,
});
return;
}
let dirty = open.dirty();
let file = match lutra_vfs::read_text(abs) {
Ok(file) => file,
Err(_) => {
state.buffers.mark_conflict(id);
state.emit(Event::FileChangedOnDisk {
path,
id,
@ -323,17 +322,40 @@ fn reload(state: &mut State, id: BufferId, abs: &Path) {
return;
}
};
if dirty {
if state.buffers.is_own_write(
id,
&crate::journal::hex_hash(file.text.as_bytes()),
file.bom,
) {
return;
}
state.buffers.mark_conflict(id);
state.emit(Event::FileChangedOnDisk {
path,
id,
removed: false,
});
return;
}
let Some(open) = state.buffers.get(id) else {
return;
};
if file.text == open.buffer.save_text() && file.bom == open.bom {
state.buffers.clear_conflict(id);
return;
}
let Some(open) = state.buffers.get_mut(id) else {
return;
};
let hash = crate::journal::hex_hash(file.text.as_bytes());
open.buffer = Buffer::new(&file.text);
open.bom = file.bom;
open.version = open.version.saturating_add(1);
open.saved_version = open.version;
let version = open.version;
state.buffers.clear_conflict(id);
state.buffers.note_written(id, hash, file.bom);
state.emit(Event::BufferChanged { id, version });
}

View file

@ -49,7 +49,10 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() {
"ui.language",
"php.executable",
"phpactor.path",
"phpactor.autoDownload"
"phpactor.autoDownload",
"editor.autosave.onBlur",
"editor.autosave.onTabSwitch",
"editor.autosave.idleSeconds"
]
);
for s in list.as_array().unwrap() {
@ -112,7 +115,10 @@ fn get_set_reset_and_events() {
"ui.language": "en",
"php.executable": "",
"phpactor.path": "",
"phpactor.autoDownload": true
"phpactor.autoDownload": true,
"editor.autosave.onBlur": true,
"editor.autosave.onTabSwitch": true,
"editor.autosave.idleSeconds": 15
})
);
let out = e

View file

@ -265,7 +265,10 @@ fn save_all_saves_every_dirty_buffer() {
);
}
let out = run(&mut engine, "file.saveAll", Value::Null);
assert_eq!(out.value, json!({"saved": [a, b], "failed": []}));
assert_eq!(
out.value,
json!({"saved": [a, b], "failed": [], "skipped": []})
);
assert_eq!(fs::read_to_string(dir.path().join("b.php")).unwrap(), ">b");
}
@ -555,3 +558,104 @@ fn buffer_list_names_open_buffers_without_text() {
);
assert!(out.events.is_empty());
}
#[test]
fn save_all_can_skip_buffers_in_conflict_with_the_disk() {
let (dir, mut engine, _) = open_project(&[("mine.php", b"one"), ("other.php", b"one")]);
let (mine, _) = open_file(&mut engine, "mine.php");
let (other, _) = open_file(&mut engine, "other.php");
for id in [mine, other] {
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "x"}]}),
);
}
fs::write(dir.path().join("other.php"), "theirs").unwrap();
wait_for(
&mut engine,
|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == other),
);
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
assert_eq!(
out.value,
json!({"saved": [mine], "failed": [], "skipped": [other]})
);
assert_eq!(
fs::read_to_string(dir.path().join("other.php")).unwrap(),
"theirs"
);
assert_eq!(
fs::read_to_string(dir.path().join("mine.php")).unwrap(),
"xone"
);
run(&mut engine, "file.save", json!({"id": other}));
assert_eq!(
fs::read_to_string(dir.path().join("other.php")).unwrap(),
"xone"
);
run(
&mut engine,
"buffer.edit",
json!({"id": other, "baseVersion": 2, "edits": [{"from": 0, "to": 0, "insert": "y"}]}),
);
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
assert_eq!(out.value["saved"], json!([other]));
assert_eq!(out.value["skipped"], json!([]));
let err = engine
.execute("file.saveAll", json!({"skip": true}))
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
}
#[test]
fn a_removed_file_is_skipped_instead_of_recreated() {
let (dir, mut engine, _) = open_project(&[("gone.php", b"one")]);
let (id, _) = open_file(&mut engine, "gone.php");
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "x"}]}),
);
fs::remove_file(dir.path().join("gone.php")).unwrap();
wait_for(
&mut engine,
|e| matches!(e, Event::FileChangedOnDisk { id: got, removed: true, .. } if *got == id),
);
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
assert_eq!(out.value["skipped"], json!([id]));
assert!(!dir.path().join("gone.php").exists());
}
#[test]
fn typing_right_after_a_save_is_not_a_conflict() {
let (_dir, mut engine, _) = open_project(&[("a.php", b"a")]);
let (id, _) = open_file(&mut engine, "a.php");
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 1, "edits": [{"from": 1, "to": 1, "insert": "b"}]}),
);
run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
run(
&mut engine,
"buffer.edit",
json!({"id": id, "baseVersion": 2, "edits": [{"from": 2, "to": 2, "insert": "c"}]}),
);
let deadline = Instant::now() + Duration::from_millis(600);
while Instant::now() < deadline {
let events = engine.pump_vfs().unwrap();
assert!(
!events
.iter()
.any(|e| matches!(e, Event::FileChangedOnDisk { .. })),
"{events:?}"
);
std::thread::sleep(Duration::from_millis(25));
}
let out = run(&mut engine, "file.saveAll", json!({"skipConflicts": true}));
assert_eq!(out.value["saved"], json!([id]));
}