M1.7: crash-recovery journal and restore dialog

Dirty buffers are written atomically to <data_dir>/recovery/<project-id>/
about 1 s after the last edit (at most 2 s while typing), from pump_vfs,
never per keystroke. Entries are removed on save, close (also force),
forced project close/open and recovery.discard. project.open emits
recoveryAvailable; recovery.list/restore/discard; restored buffers are
dirty and keep line ending and BOM. Corrupt entries are moved aside and
reported as warning notifications.

UI: restore dialog in ui/src/components/recovery (Restore all, Restore
selected, Discard, time, changed-on-disk hint), catalog keys and runtime
allow-list. Tests: crash/restore with CRLF + BOM, corrupt entries, removal
paths, property test of random edits, headless control-channel test,
Vitest for the dialog. Docs: architecture, parity, gaps, ROADMAP.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 15:54:52 +02:00
parent 6d976ed03e
commit 0b40eb90f8
27 changed files with 2222 additions and 27 deletions

View file

@ -62,7 +62,7 @@ claude mcp add lutra -- lutra mcp
## Status
**Pre-alpha (2026-10-15): M1 in progress.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now); syntax highlighting and PHP features come next. The MVP (M1–M3) is estimated at about 20 agent hours after calibrating on the first cycle (2.5 h done). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
**Pre-alpha (2026-10-16): M1 in progress.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs (plain text for now); unsaved text survives a crash and is offered back on the next open; syntax highlighting and PHP features come next. The MVP (M1–M3) is estimated at about 20 agent hours after calibrating on the first cycle (2.5 h done). [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,

View file

@ -1,8 +1,8 @@
# Lutra Roadmap
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (recovery, palette, settings, themes), then M2 syntax and search; alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
**Stage: pre-alpha (M1 in progress)** · next: the rest of M1 (palette, settings, themes), then M2 syntax and search; 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-15 · **Change:** minor (M1.11: English UI catalog) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
> **Last reviewed:** 2026-10-15 · **Last updated:** 2026-10-16 · **Change:** minor (M1.7: crash-recovery journal) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
@ -13,7 +13,7 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in
| | Value | Kind |
|---|---|---|
| **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **<1%** (project tool window, editor tabs; no inventory to count against yet) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~1.4%** (Editor core 8% × weight 12, Project view 8% × weight 6, of 101) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~1.6%** (Editor core 9% × weight 12, Project view 8% × weight 6, Settings 4% × weight 1, of 101) | estimated |
| **To MVP (M3)** | **~20 h** (M1 ~6 h of which 2.5 h done, M2 ~5 h, M3 ~8 h); was ~190 h before calibration | estimated (×0.1 from cycle C1) |
| **To full parity** | **~330 h** if cycle C1's speed holds (range 300–3,300 h; deep areas such as type inference and inspections have no data yet) | estimated |
@ -25,23 +25,23 @@ Dimension hours overlap: language, framework and tooling hours are part of the f
| Dimension | % | One agent (h) | Doc |
|---|---:|---:|---|
| Features (depth) | ~1.4% | ~2,920 | [target-app-parity.md](docs/target-app-parity.md) |
| Features (depth) | ~1.6% | ~2,920 | [target-app-parity.md](docs/target-app-parity.md) |
| UI/UX fidelity | 1% (est.) | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) |
| PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) |
| Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) |
| Tooling (Git, terminal, debugger, tests, Composer, DB) | 0% | ~730 (in features) | [tooling-parity.md](docs/tooling-parity.md) |
| Localization (en, de) | 5% | ~38 | [localization-parity.md](docs/localization-parity.md) |
| Performance | 0% | ~100 | [gaps.md › G12](docs/gaps.md) |
| Stability | 5% | ~100 | [gaps.md › G11](docs/gaps.md) |
| Stability | 8% | ~95 | [gaps.md › G11](docs/gaps.md) |
| Agent automation | 10% | ~60 | AGENTS.md |
Stability 5%: no-panic lints, the engine guard and a fuzzed control protocol exist; the recovery journal does not. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works; MCP and the CLI do not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open.
Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a crash-recovery journal for unsaved buffers (property-tested: random edits, crash, restore) exist; the journal is not yet checked in the running app. Agent automation 10%: the control channel (ping, execute, listCommands, screenshot) works; MCP and the CLI do not exist yet. Both are estimated. Localization 5% (estimated): every UI string comes from an English catalog enforced by lint; engine messages, the language switch and German are missing. UI/UX fidelity 1% (estimated): light and dark themes switch live and pass a WCAG AA contrast test; the rest of the ui-parity checklist is open.
## Features
| Area | % | One agent (h) |
|---|---:|---:|
| Editor core (buffers, undo, multi-caret, folding, soft wrap) | 8% (est.) | ~110 |
| Editor core (buffers, undo, multi-caret, folding, soft wrap) | 9% (est.) | ~106 |
| Project view, VFS, file watching | 8% (est.) | ~40 |
| Navigation (go to class/file/symbol, recent files, structure) | 0% | ~120 |
| Search and replace (in file, in project, structural) | 0% | ~80 |
@ -77,6 +77,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | What landed |
|---|---|
| 2026-10-16 | M1.7: unsaved text survives a crash. Dirty buffers are journaled about a second after the last edit; the next open offers them in a restore dialog (restore all, selected, or discard), with line endings and BOM kept. |
| 2026-10-16 | M1.10: Lutra Light next to Lutra Dark, switched live through the `appearance.theme` setting or following the OS (`system`); the window starts in the stored theme; the editor, tabs and notices get their own tokens; both themes pass a WCAG AA contrast test. |
| 2026-10-15 | M1.11: every interface string comes from an English message catalog (`ui/src/i18n/en.json`), enforced by a lint rule and a catalog test; the groundwork for German. |
| 2026-10-15 | M1.6: files open in tabs with a CodeMirror editor synced to the engine; save, save all, close with a Save / Don't Save / Cancel question, a notice when a file with unsaved changes changes on disk; a 1 MB file opens in about 90 ms. |
@ -88,6 +89,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.7: Stability 8%, Editor core 9%, feature depth ~1.6% (with Settings 4% from M1.10) |
| 2026-10-16 | minor | M1.10: UI/UX fidelity 1%, Settings row 4% (estimates), progress log |
| 2026-10-15 | minor | M1.11: localization 5% (English UI catalog), progress log |
| 2026-10-15 | minor | Cycle C1 review: stage line, breadth estimate, hours recalibrated ×0.1 |

View file

@ -0,0 +1,143 @@
//! Crash recovery over the control channel, headless: type into a file,
//! drop the backend without saving, start a new one on the same directories,
//! get `recoveryAvailable` after `project.open`, restore and check the text.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::Arc;
use std::time::{Duration, Instant};
use lutra_testkit::{EngineBackend, engine_config};
use serde_json::{Value, json};
/// A control client that keeps event lines apart from responses.
struct Client {
reader: BufReader<TcpStream>,
writer: TcpStream,
events: Vec<Value>,
}
impl Client {
fn connect(addr: std::net::SocketAddr) -> Self {
let stream = TcpStream::connect(addr).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
Self {
writer: stream.try_clone().unwrap(),
reader: BufReader::new(stream),
events: Vec::new(),
}
}
fn call(&mut self, request: Value) -> Value {
self.writer
.write_all(format!("{request}\n").as_bytes())
.unwrap();
loop {
let mut line = String::new();
self.reader.read_line(&mut line).expect("line within 5 s");
let line: Value = serde_json::from_str(&line).unwrap();
if line.get("event").is_some() {
self.events.push(line["event"].clone());
} else {
return line;
}
}
}
/// Waits until an event of `kind` has arrived and returns it.
fn event(&mut self, kind: &str) -> Value {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
if let Some(at) = self.events.iter().position(|e| e["kind"] == kind) {
return self.events.remove(at);
}
assert!(
Instant::now() < deadline,
"no {kind} event; got {:?}",
self.events
);
let mut line = String::new();
self.reader.read_line(&mut line).expect("line within 5 s");
let line: Value = serde_json::from_str(&line).unwrap();
if line.get("event").is_some() {
self.events.push(line["event"].clone());
}
}
}
fn execute(&mut self, command: &str, params: Value) -> Value {
let r = self.call(json!({"id": command, "method": "engine.execute", "params": {"command": command, "params": params}}));
assert!(r.get("error").is_none(), "{command}: {r}");
r["result"].clone()
}
}
#[test]
fn typed_text_survives_a_crash_and_is_restored() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("project");
std::fs::create_dir(&project).unwrap();
std::fs::write(project.join("a.php"), b"\xEF\xBB\xBF<?php\r\n").unwrap();
let config = engine_config(dir.path());
let backend = Arc::new(EngineBackend::with_config(config.clone()));
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call(json!({"id": 0, "method": "events.subscribe"}));
client.execute("project.open", json!({"path": project}));
let id = client.execute("file.open", json!({"path": "a.php"}))["id"].clone();
for (version, ch) in "echo 1;".chars().enumerate() {
client.execute(
"buffer.edit",
json!({"id": id, "baseVersion": version + 1, "edits": [{"from": 7 + version, "to": 7 + version, "insert": ch.to_string()}]}),
);
}
let typed = client.execute("buffer.get", json!({"id": id}))["text"].clone();
assert_eq!(typed, "<?php\r\necho 1;");
let entries = config.data_dir.join("recovery");
let deadline = Instant::now() + Duration::from_secs(5);
while std::fs::read_dir(&entries).map_or(0, |d| d.flatten().count()) == 0 {
assert!(Instant::now() < deadline, "journal not written");
std::thread::sleep(Duration::from_millis(100));
backend.pump();
}
drop(client);
drop(backend);
let backend = Arc::new(EngineBackend::with_config(config));
let server = lutra_control::start(0, backend.clone()).unwrap();
let mut client = Client::connect(server.local_addr());
client.call(json!({"id": 0, "method": "events.subscribe"}));
client.execute("project.open", json!({"path": project}));
let offered = client.event("recoveryAvailable");
assert_eq!(offered["entries"][0]["path"], "a.php");
assert_eq!(offered["entries"][0]["diskChanged"], false);
let out = client.execute("recovery.restore", json!({}));
let id = out["restored"][0]["id"].clone();
let got = client.execute("buffer.get", json!({"id": id}));
assert_eq!(got["text"], typed);
assert_eq!(got["lineEnding"], "crlf");
assert_eq!(got["dirty"], true);
client.execute("file.save", json!({"id": id}));
assert_eq!(
std::fs::read(project.join("a.php")).unwrap(),
b"\xEF\xBB\xBF<?php\r\necho 1;"
);
assert!(
client.execute("recovery.list", json!({}))["entries"]
.as_array()
.unwrap()
.is_empty()
);
}

View file

@ -4,7 +4,7 @@ use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use lutra_text::{Buffer, LineEnding};
use serde::Serialize;
use serde::{Deserialize, Serialize};
/// Identifier of an open buffer, unique for the engine's lifetime.
pub type BufferId = u64;
@ -103,7 +103,7 @@ impl Buffers {
}
/// A line ending as sent to clients: `"lf"`, `"crlf"` or `"cr"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineEndingName {
/// `\n`.
@ -123,3 +123,13 @@ impl From<LineEnding> for LineEndingName {
}
}
}
impl From<LineEndingName> for LineEnding {
fn from(name: LineEndingName) -> Self {
match name {
LineEndingName::Lf => Self::Lf,
LineEndingName::Crlf => Self::CrLf,
LineEndingName::Cr => Self::Cr,
}
}
}

View file

@ -12,6 +12,7 @@ use serde_json::{Value, json};
use super::params::parse;
use crate::buffers::{BufferId, LineEndingName};
use crate::journal;
use crate::workspace::path_string;
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
@ -163,6 +164,7 @@ impl Command for Edit {
.map_err(|e| EngineError::invalid_params(command, e.to_string()))?;
open.version = open.version.saturating_add(1);
let (version, dirty) = (open.version, open.dirty());
journal::mark_edited(state, p.id, std::time::Instant::now());
state.emit(Event::BufferChanged { id: p.id, version });
if dirty != was_dirty {
state.emit(Event::DirtyChanged { id: p.id, dirty });
@ -212,6 +214,7 @@ impl Command for Close {
if open.dirty() && !p.force {
return Err(EngineError::UnsavedChanges(path_string(&open.path)));
}
journal::forget(state, p.id);
state.buffers.remove(p.id);
state.emit(Event::BufferClosed { id: p.id });
Ok(Outcome::value(Value::Null))

View file

@ -6,6 +6,7 @@ use serde_json::{Value, json};
use super::buffer::describe;
use super::params::{absolute, parse, project_path};
use crate::buffers::{BufferId, OpenBuffer};
use crate::journal;
use crate::workspace::{path_string, vfs_error};
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
@ -80,6 +81,7 @@ fn save(state: &mut State, command: &str, id: BufferId) -> Result<u64, EngineErr
let was_dirty = open.dirty();
open.saved_version = open.version;
let version = open.version;
journal::forget(state, id);
if was_dirty {
state.emit(Event::DirtyChanged { id, dirty: false });
}

View file

@ -5,6 +5,7 @@ mod buffer;
mod file;
mod params;
mod project;
mod recovery;
mod settings;
pub mod theme;
@ -27,6 +28,9 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(buffer::Get))?;
registry.register(Box::new(buffer::Edit))?;
registry.register(Box::new(buffer::Close))?;
registry.register(Box::new(recovery::List))?;
registry.register(Box::new(recovery::Restore))?;
registry.register(Box::new(recovery::Discard))?;
registry.register(Box::new(settings::List))?;
registry.register(Box::new(settings::Get))?;
registry.register(Box::new(settings::Set))?;

View file

@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::params::{parse, project_path};
use crate::journal::{self, Journal};
use crate::workspace::{Workspace, path_string, vfs_error};
use crate::{Command, CommandSpec, Effect, EngineError, Event, Outcome, State};
@ -51,9 +52,11 @@ pub fn close_project(state: &mut State, force: bool) -> Result<(), EngineError>
return Err(EngineError::UnsavedChanges(what));
}
for id in state.buffers.ids() {
journal::forget(state, id);
state.buffers.remove(id);
state.emit(Event::BufferClosed { id });
}
state.journal = None;
state.project = None;
state.emit(Event::ProjectClosed);
Ok(())
@ -70,7 +73,9 @@ struct OpenParams {
force: bool,
}
/// `project.open`: opens a folder as the project, closing the current one.
/// `project.open`: opens a folder as the project, closing the current one,
/// and offers the unsaved texts its recovery journal holds with
/// [`Event::RecoveryAvailable`] (only when there are any).
pub struct Open;
impl Command for Open {
@ -80,7 +85,7 @@ impl Command for Open {
label: "Open Folder",
menu_path: None,
default_shortcut: None,
params: "{ path: string (absolute folder), force?: bool (discard unsaved changes of the open project) }; returns { root, name }",
params: "{ path: string (absolute folder), force?: bool (discard unsaved changes of the open project) }; returns { root, name }; emits recoveryAvailable when the recovery journal holds unsaved texts",
}
}
@ -89,6 +94,10 @@ impl Command for Open {
let (workspace, events) = Workspace::open(std::path::Path::new(&p.path))?;
close_project(state, p.force)?;
let root = workspace.project.root().to_path_buf();
state.journal = state
.config
.as_ref()
.map(|c| Journal::new(&c.data_dir, &root));
state.project = Some(workspace);
let mut name = String::new();
for event in events {
@ -97,6 +106,10 @@ impl Command for Open {
}
state.emit(event);
}
let entries = super::recovery::infos(state);
if !entries.is_empty() {
state.emit(Event::RecoveryAvailable { entries });
}
Ok(Outcome::value(json!({
"root": root.to_string_lossy(),
"name": name,

View file

@ -0,0 +1,191 @@
//! Recovery commands: `recovery.list`, `recovery.restore`,
//! `recovery.discard`. See [`crate::journal`] for the journal itself.
use std::path::PathBuf;
use serde::Deserialize;
use serde_json::{Value, json};
use super::params::parse;
use crate::buffers::OpenBuffer;
use crate::journal::{self, Entry, EntryInfo};
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// Params naming journal entries; all entries when `paths` is missing.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PathsParams {
/// Project-relative paths with `/`.
#[serde(default)]
paths: Option<Vec<String>>,
}
/// The journal entries `paths` names, or all of them, plus the requested
/// paths that have no entry.
fn select(state: &mut State, paths: Option<Vec<String>>) -> (Vec<Entry>, Vec<String>) {
let entries = journal::scan(state);
match paths {
None => (entries, Vec::new()),
Some(paths) => {
let missing = paths
.iter()
.filter(|p| !entries.iter().any(|e| &e.path == *p))
.cloned()
.collect();
let chosen = entries
.into_iter()
.filter(|e| paths.contains(&e.path))
.collect();
(chosen, missing)
}
}
}
/// The entries of the open project's journal as clients see them.
pub fn infos(state: &mut State) -> Vec<EntryInfo> {
let entries = journal::scan(state);
entries.iter().map(|e| journal::info(state, e)).collect()
}
/// `recovery.list`: the unsaved texts the journal holds.
pub struct List;
impl Command for List {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "recovery.list",
label: "List Recovered Files",
menu_path: None,
default_shortcut: None,
params: "none; returns { entries: [{ path, savedAt (ms since the Unix epoch), diskChanged }] }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
Ok(Outcome::value(json!({ "entries": infos(state) })))
}
}
/// Opens `entry` as a dirty buffer, or puts its text into the clean buffer
/// that already holds the file. Returns the buffer id.
///
/// # Errors
/// [`EngineError::UnsavedChanges`] if the file is open with unsaved changes,
/// which are newer than the journal.
fn restore(state: &mut State, entry: Entry) -> Result<u64, EngineError> {
let rel: PathBuf = PathBuf::from(&entry.path).components().collect();
let mut buffer = lutra_text::Buffer::new(&entry.text);
buffer.set_line_ending(entry.line_ending.into());
if let Some(id) = state.buffers.find(&rel) {
let open = state
.buffers
.get_mut(id)
.ok_or_else(|| EngineError::Failed(format!("no buffer {id}")))?;
if open.dirty() {
return Err(EngineError::UnsavedChanges(entry.path));
}
open.buffer = buffer;
open.bom = entry.bom;
open.version = open.version.saturating_add(1);
let version = open.version;
state.emit(Event::BufferChanged { id, version });
state.emit(Event::DirtyChanged { id, dirty: true });
journal::adopt(state, &entry.path);
return Ok(id);
}
let id = state.buffers.insert(OpenBuffer {
buffer,
path: rel,
version: 1,
saved_version: 0,
bom: entry.bom,
});
state.emit(Event::BufferOpened {
id,
path: entry.path.clone(),
});
state.emit(Event::DirtyChanged { id, dirty: true });
journal::adopt(state, &entry.path);
Ok(id)
}
/// `recovery.restore`: opens journal entries as dirty buffers.
pub struct Restore;
impl Command for Restore {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "recovery.restore",
label: "Restore Unsaved Changes",
menu_path: None,
default_shortcut: None,
params: "{ paths?: [string] (all entries if missing) }; opens each file as a dirty buffer with the journal text, line ending and BOM; returns { restored: [{ path, id }], failed: [{ path, message }] }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: PathsParams = parse(self.spec().id, params)?;
let (entries, missing) = select(state, p.paths);
let mut restored = Vec::new();
let mut failed: Vec<Value> = missing
.into_iter()
.map(|path| json!({ "path": path, "message": "no recovery entry" }))
.collect();
for entry in entries {
let path = entry.path.clone();
match restore(state, entry) {
Ok(id) => restored.push(json!({ "path": path, "id": id })),
Err(e) => failed.push(json!({ "path": path, "message": e.to_string() })),
}
}
Ok(Outcome::value(
json!({ "restored": restored, "failed": failed }),
))
}
}
/// `recovery.discard`: deletes journal entries.
pub struct Discard;
impl Command for Discard {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "recovery.discard",
label: "Discard Unsaved Changes",
menu_path: None,
default_shortcut: None,
params: "{ paths?: [string] (all entries if missing) }; deletes the journal entries; an open buffer with unsaved changes is journaled again; returns { discarded: [path] }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: PathsParams = parse(self.spec().id, params)?;
let (entries, _) = select(state, p.paths);
let mut discarded = Vec::new();
let now = std::time::Instant::now();
for entry in entries {
if journal::remove(state, &entry.path) {
let rel: PathBuf = PathBuf::from(&entry.path).components().collect();
if let Some(id) = state.buffers.find(&rel)
&& state.buffers.get(id).is_some_and(OpenBuffer::dirty)
{
journal::mark_edited(state, id, now);
}
discarded.push(entry.path);
}
}
Ok(Outcome::value(json!({ "discarded": discarded })))
}
}

View file

@ -114,7 +114,8 @@ impl Engine {
}
/// Applies pending changes on disk (reloads clean buffers, reports
/// changed directories and conflicts) and returns every queued event.
/// changed directories and conflicts), writes due recovery-journal
/// entries (see [`crate::journal`]) and returns every queued event.
/// Hosts call it regularly, e.g. every 100 ms from a background thread.
///
/// # Errors
@ -124,6 +125,23 @@ impl Engine {
let state = &mut self.state;
guard::run(|| {
crate::workspace::pump(state);
crate::journal::tick(state, std::time::Instant::now());
Ok(())
})?;
Ok(state.take_events())
}
/// Writes every unsaved edit to the recovery journal now instead of
/// after the debounce, and returns every queued event. For tests and
/// for hosts that are about to stop.
///
/// # Errors
/// [`EngineError::Internal`] if writing panicked; the queued events stay
/// queued.
pub fn flush_journal(&mut self) -> Result<Vec<crate::Event>, EngineError> {
let state = &mut self.state;
guard::run(|| {
crate::journal::flush(state);
Ok(())
})?;
Ok(state.take_events())
@ -283,6 +301,9 @@ mod tests {
"project.close",
"project.open",
"project.openDialog",
"recovery.discard",
"recovery.list",
"recovery.restore",
"settings.get",
"settings.list",
"settings.reset",

View file

@ -15,6 +15,8 @@ use std::collections::BTreeMap;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::journal::EntryInfo;
/// A state change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(
@ -96,6 +98,13 @@ pub enum Event {
/// Every token as `--lt-<name>` → CSS value.
tokens: BTreeMap<String, String>,
},
/// The recovery journal of the project just opened holds unsaved texts
/// from an earlier session; offer `recovery.restore` /
/// `recovery.discard`.
RecoveryAvailable {
/// The entries, sorted by path.
entries: Vec<EntryInfo>,
},
/// A message for the user, shown as a toast.
Notification {
/// Unique id of this notification, for dismissing it.

View file

@ -0,0 +1,460 @@
//! Crash-recovery journal: unsaved buffers written to disk so a crash never
//! loses the user's text.
//!
//! # Layout
//! `<data_dir>/recovery/<project-id>/<entry-id>.json`, where the project id
//! is the FNV-1a 64-bit hash of the canonical project root and the entry id
//! the same hash of the project-relative path, both as 16 hex digits. FNV is
//! used instead of `std`'s hasher because its output must stay the same
//! across Rust versions. One file per dirty buffer holds an [`Entry`]:
//! `{path, text, lineEnding, bom, savedAt}`; `text` is the buffer's text as
//! held in memory, `savedAt` milliseconds since the Unix epoch.
//!
//! # When entries are written and removed
//! - `buffer.edit` only records the time ([`mark_edited`]); nothing is
//! written per keystroke. [`tick`], called from every
//! [`crate::Engine::pump_vfs`], writes a buffer once it has been idle for
//! [`IDLE`], or [`MAX_WAIT`] after its first unwritten edit during
//! continuous typing. With the desktop's 100 ms pump an entry is on disk at
//! most about 1.1 s after the last edit.
//! - Writes go through [`lutra_vfs::write_atomic`], so an entry is either the
//! old or the new version, never half written.
//! - Saving, closing (also with `force`), `project.close`/`project.open`
//! with `force` and `recovery.discard` remove entries ([`forget`]). Only
//! entries this session wrote or restored are removed by save and close;
//! entries left by a crashed session stay until they are restored or
//! discarded. Editing such a file without restoring it overwrites its
//! entry with the new text.
//!
//! # Untrusted input
//! Entries are read with a size cap ([`MAX_ENTRY_BYTES`]), at most
//! [`MAX_ENTRIES`] per project. An entry that cannot be read or parsed, or
//! whose path escapes the project, is renamed to `<entry>.bad`, skipped and
//! reported as a warning notification; it never stops the project from
//! opening.
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::buffers::{BufferId, LineEndingName};
use crate::workspace::path_string;
use crate::{NotificationLevel, State};
/// A buffer is written after this long without an edit.
pub const IDLE: Duration = Duration::from_millis(1000);
/// A buffer edited continuously is written at least this often.
pub const MAX_WAIT: Duration = Duration::from_millis(2000);
/// Largest entry file read; larger ones count as corrupt.
pub const MAX_ENTRY_BYTES: u64 = 512 * 1024 * 1024;
/// Most entry files read per project.
pub const MAX_ENTRIES: usize = 1000;
/// Extension of entry files.
const ENTRY_EXT: &str = "json";
/// Suffix appended to an entry that could not be read.
const BAD_SUFFIX: &str = ".bad";
/// Catalog key of the warning for an unreadable entry.
pub const KEY_CORRUPT: &str = "notification.recovery.corrupt";
/// Catalog key of the warning for a failed journal write.
pub const KEY_WRITE_FAILED: &str = "notification.recovery.writeFailed";
/// Catalog key of the warning for an unreadable journal directory.
pub const KEY_UNAVAILABLE: &str = "notification.recovery.unavailable";
/// One journal file: the unsaved text of one buffer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Entry {
/// Project-relative path with `/` separators.
pub path: String,
/// The buffer's text as held in memory.
pub text: String,
/// The line ending the buffer saves with.
pub line_ending: LineEndingName,
/// The file has a UTF-8 byte order mark.
pub bom: bool,
/// When the entry was written, in milliseconds since the Unix epoch.
pub saved_at: u64,
}
/// What `recoveryAvailable` and `recovery.list` report about an entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EntryInfo {
/// Project-relative path.
pub path: String,
/// When the entry was written, in milliseconds since the Unix epoch.
pub saved_at: u64,
/// The file was modified after the entry was written, or is gone.
pub disk_changed: bool,
}
/// Edit times of a buffer whose latest text is not in the journal yet.
#[derive(Debug, Clone, Copy)]
struct Pending {
/// The first edit since the last write.
first: Instant,
/// The latest edit.
last: Instant,
}
impl Pending {
/// Whether the buffer is due for writing at `now`: idle for [`IDLE`] or
/// waiting for [`MAX_WAIT`].
fn due(&self, now: Instant) -> bool {
now.saturating_duration_since(self.last) >= IDLE
|| now.saturating_duration_since(self.first) >= MAX_WAIT
}
}
/// The journal of the open project.
#[derive(Debug)]
pub struct Journal {
/// `<data_dir>/recovery/<project-id>`; created on the first write.
dir: PathBuf,
/// Buffers with edits not written yet.
pending: BTreeMap<BufferId, Pending>,
/// Paths whose entry this session wrote or restored.
owned: BTreeSet<String>,
/// A write failure was reported and no write has succeeded since.
write_failed: bool,
}
impl Journal {
/// The journal of the project at the canonical `root`, stored below
/// `data_dir`. Touches nothing on disk.
pub fn new(data_dir: &Path, root: &Path) -> Self {
Self {
dir: data_dir
.join("recovery")
.join(hex_hash(root.to_string_lossy().as_bytes())),
pending: BTreeMap::new(),
owned: BTreeSet::new(),
write_failed: false,
}
}
/// The directory holding the entries.
pub fn dir(&self) -> &Path {
&self.dir
}
/// The file of the entry for `path`.
fn file(&self, path: &str) -> PathBuf {
self.dir
.join(format!("{}.{ENTRY_EXT}", hex_hash(path.as_bytes())))
}
}
/// FNV-1a 64-bit hash of `bytes` as 16 lowercase hex digits.
pub fn hex_hash(bytes: &[u8]) -> String {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
format!("{hash:016x}")
}
/// Milliseconds since the Unix epoch, 0 for a clock before it.
fn millis(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH)
.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
.unwrap_or(0)
}
/// Records an edit of buffer `id` at `now`; [`tick`] writes it later.
pub fn mark_edited(state: &mut State, id: BufferId, now: Instant) {
if let Some(journal) = state.journal.as_mut() {
journal
.pending
.entry(id)
.and_modify(|p| p.last = now)
.or_insert(Pending {
first: now,
last: now,
});
}
}
/// Writes every buffer that has been idle for [`IDLE`] or waiting for
/// [`MAX_WAIT`] at `now`.
pub fn tick(state: &mut State, now: Instant) {
let Some(journal) = state.journal.as_ref() else {
return;
};
let due: Vec<BufferId> = journal
.pending
.iter()
.filter(|(_, p)| p.due(now))
.map(|(id, _)| *id)
.collect();
for id in due {
write(state, id);
}
}
/// Writes every buffer with unwritten edits now.
pub fn flush(state: &mut State) {
let ids: Vec<BufferId> = state
.journal
.as_ref()
.map(|j| j.pending.keys().copied().collect())
.unwrap_or_default();
for id in ids {
write(state, id);
}
}
/// Writes the entry of buffer `id` if it is dirty. A failed write keeps the
/// buffer pending, so the next tick tries again, and is reported once until
/// a write succeeds.
fn write(state: &mut State, id: BufferId) {
let Some(open) = state.buffers.get(id) else {
if let Some(journal) = state.journal.as_mut() {
journal.pending.remove(&id);
}
return;
};
if !open.dirty() {
if let Some(journal) = state.journal.as_mut() {
journal.pending.remove(&id);
}
return;
}
let entry = Entry {
path: path_string(&open.path),
text: open.buffer.text(),
line_ending: LineEndingName::from(open.buffer.line_ending()),
bom: open.bom,
saved_at: millis(SystemTime::now()),
};
let Some(journal) = state.journal.as_mut() else {
return;
};
let file = journal.file(&entry.path);
let result = serde_json::to_vec(&entry)
.map_err(|e| e.to_string())
.and_then(|bytes| {
std::fs::create_dir_all(&journal.dir).map_err(|e| e.to_string())?;
lutra_vfs::write_atomic(&file, &bytes).map_err(|e| e.to_string())
});
match result {
Ok(()) => {
journal.pending.remove(&id);
journal.owned.insert(entry.path);
journal.write_failed = false;
}
Err(reason) => {
if journal.write_failed {
return;
}
journal.write_failed = true;
let mut params = Map::new();
params.insert("path".into(), Value::String(entry.path.clone()));
params.insert("reason".into(), Value::String(reason.clone()));
state.notify(
NotificationLevel::Warning,
Some(KEY_WRITE_FAILED),
Some(format!(
"Could not write the recovery copy of {}: {reason}",
entry.path
)),
Some(params),
);
}
}
}
/// Drops the journal state of buffer `id` and removes its entry if this
/// session owns it. Called when the buffer is saved or closed, before it is
/// removed. A file that cannot be removed is left behind: it is offered
/// again on the next open, which is safer than failing the save or close.
pub fn forget(state: &mut State, id: BufferId) {
let path = state.buffers.get(id).map(|b| path_string(&b.path));
let Some(journal) = state.journal.as_mut() else {
return;
};
journal.pending.remove(&id);
let Some(path) = path else {
return;
};
if journal.owned.remove(&path) {
let _ = std::fs::remove_file(journal.file(&path));
}
}
/// Reads every valid entry of the open project's journal, sorted by path.
/// Unreadable entries are renamed to `<entry>.bad` and reported as warning
/// notifications. A missing journal directory means no entries.
pub fn scan(state: &mut State) -> Vec<Entry> {
let Some(journal) = state.journal.as_ref() else {
return Vec::new();
};
let dir = journal.dir.clone();
let listing = match std::fs::read_dir(&dir) {
Ok(listing) => listing,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Vec::new(),
Err(e) => {
let mut params = Map::new();
params.insert("reason".into(), Value::String(e.to_string()));
state.notify(
NotificationLevel::Warning,
Some(KEY_UNAVAILABLE),
Some(format!("Could not read the recovery journal: {e}")),
Some(params),
);
return Vec::new();
}
};
let mut files: Vec<PathBuf> = listing
.filter_map(Result::ok)
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|ext| ext == ENTRY_EXT) && p.is_file())
.collect();
files.sort();
files.truncate(MAX_ENTRIES);
let mut entries = Vec::new();
for file in files {
match read_entry(state, &file) {
Ok(entry) => entries.push(entry),
Err(reason) => quarantine(state, &file, &reason),
}
}
entries.sort_by(|a, b| a.path.cmp(&b.path));
entries.dedup_by(|a, b| a.path == b.path);
entries
}
/// Reads and checks one entry file.
///
/// # Errors
/// A description of why the entry is unusable.
fn read_entry(state: &State, file: &Path) -> Result<Entry, String> {
let bytes = lutra_vfs::read_bytes(file, MAX_ENTRY_BYTES).map_err(|e| e.to_string())?;
let entry: Entry = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
if entry.path.is_empty() {
return Err("empty path".into());
}
let journal = state.journal.as_ref().ok_or("no journal")?;
if journal.file(&entry.path).file_name() != file.file_name() {
return Err("the file name does not match the path".into());
}
let workspace = state.project.as_ref().ok_or("no project")?;
workspace
.project
.resolve(Path::new(&entry.path))
.map_err(|e| e.to_string())?;
Ok(entry)
}
/// Moves an unusable entry aside and reports it. The text inside may still
/// be worth something to the user, so it is renamed, not deleted.
fn quarantine(state: &mut State, file: &Path, reason: &str) {
let mut bad = file.as_os_str().to_os_string();
bad.push(BAD_SUFFIX);
let _ = std::fs::rename(file, PathBuf::from(&bad));
let name = file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let mut params = Map::new();
params.insert("file".into(), Value::String(name.clone()));
params.insert("reason".into(), Value::String(reason.to_string()));
state.notify(
NotificationLevel::Warning,
Some(KEY_CORRUPT),
Some(format!(
"Skipped an unreadable recovery entry {name}: {reason}"
)),
Some(params),
);
}
/// What clients see about `entry`: whether the file changed on disk after
/// the entry was written (or is gone) is judged by its modification time.
pub fn info(state: &State, entry: &Entry) -> EntryInfo {
let disk_changed = state
.project
.as_ref()
.and_then(|w| w.project.resolve(Path::new(&entry.path)).ok())
.and_then(|abs| std::fs::metadata(abs).ok())
.and_then(|meta| meta.modified().ok())
.is_none_or(|modified| millis(modified) > entry.saved_at);
EntryInfo {
path: entry.path.clone(),
saved_at: entry.saved_at,
disk_changed,
}
}
/// Marks `path` as written by this session, so save and close remove it.
pub fn adopt(state: &mut State, path: &str) {
if let Some(journal) = state.journal.as_mut() {
journal.owned.insert(path.to_string());
}
}
/// Removes the entry for `path`. Returns whether a file was removed.
pub fn remove(state: &mut State, path: &str) -> bool {
let Some(journal) = state.journal.as_mut() else {
return false;
};
journal.owned.remove(path);
std::fs::remove_file(journal.file(path)).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hashes_are_stable() {
assert_eq!(hex_hash(b""), "cbf29ce484222325");
assert_eq!(hex_hash(b"a"), "af63dc4c8601ec8c");
assert_eq!(hex_hash(b"src/a.php").len(), 16);
}
#[test]
fn entries_serialise_in_camel_case() {
let entry = Entry {
path: "a.php".into(),
text: "x\r\n".into(),
line_ending: LineEndingName::Crlf,
bom: true,
saved_at: 5,
};
assert_eq!(
serde_json::to_value(&entry).unwrap(),
serde_json::json!({"path": "a.php", "text": "x\r\n", "lineEnding": "crlf", "bom": true, "savedAt": 5})
);
}
#[test]
fn due_after_idle_or_max_wait() {
let start = Instant::now();
let typing = Pending {
first: start,
last: start + Duration::from_millis(1500),
};
assert!(!typing.due(start + Duration::from_millis(1900)));
assert!(typing.due(start + MAX_WAIT));
let once = Pending {
first: start,
last: start,
};
assert!(!once.due(start + Duration::from_millis(999)));
assert!(once.due(start + IDLE));
assert!(!once.due(start));
}
}

View file

@ -12,6 +12,7 @@ mod engine;
mod error;
mod event;
pub mod guard;
pub mod journal;
mod registry;
pub mod settings;
mod state;

View file

@ -3,6 +3,7 @@
use serde_json::{Map, Value};
use crate::buffers::Buffers;
use crate::journal::Journal;
use crate::settings::Settings;
use crate::workspace::Workspace;
use crate::{EngineConfig, Event, NotificationLevel};
@ -24,6 +25,9 @@ pub struct State {
/// Where the engine stores its files; `None` for an engine without
/// persistence ([`crate::Engine::new`]).
pub config: Option<EngineConfig>,
/// The crash-recovery journal of the open project; `None` without a
/// project or without persistence.
pub journal: Option<Journal>,
/// Number of notifications emitted, for their ids.
notifications: u64,
/// Events queued for the host, oldest first.

View file

@ -0,0 +1,497 @@
//! Crash-recovery journal: unsaved text survives dropping the engine and is
//! restored exactly by a new engine on the same directories.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use lutra_engine::{Engine, EngineConfig, Event, journal};
use proptest::prelude::*;
use serde_json::{Value, json};
use tempfile::TempDir;
/// A project folder and engine directories that outlive the engines.
struct Setup {
/// Holds everything.
_tmp: TempDir,
/// The project root.
project: PathBuf,
/// The engine directories.
config: EngineConfig,
}
impl Setup {
fn new(files: &[(&str, &[u8])]) -> Self {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
std::fs::create_dir(&project).unwrap();
for (name, bytes) in files {
let path = project.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, bytes).unwrap();
}
let config = EngineConfig {
config_dir: tmp.path().join("config"),
data_dir: tmp.path().join("data"),
};
Self {
_tmp: tmp,
project,
config,
}
}
/// A fresh engine with the project open, and the events of opening it.
fn engine(&self) -> (Engine, Vec<Event>) {
let mut engine = Engine::with_config(self.config.clone()).unwrap();
engine.take_events();
let out = engine
.execute("project.open", json!({"path": self.project}))
.unwrap();
(engine, out.events)
}
/// The journal directory of the project.
fn journal_dir(&self) -> PathBuf {
let root = std::fs::canonicalize(&self.project).unwrap();
let (engine, _) = self.engine();
let dir = engine.state().journal.as_ref().unwrap().dir().to_path_buf();
assert!(dir.starts_with(self.config.data_dir.join("recovery")));
assert!(!root.as_os_str().is_empty());
dir
}
/// The entry files in the journal directory.
fn entry_files(&self) -> Vec<PathBuf> {
let Ok(listing) = std::fs::read_dir(self.journal_dir()) else {
return Vec::new();
};
let mut files: Vec<PathBuf> = listing
.map(|e| e.unwrap().path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
files.sort();
files
}
}
fn run(engine: &mut Engine, command: &str, params: Value) -> Value {
engine
.execute(command, params)
.unwrap_or_else(|e| panic!("{command}: {e}"))
.value
}
fn open(engine: &mut Engine, path: &str) -> u64 {
run(engine, "file.open", json!({"path": path}))["id"]
.as_u64()
.unwrap()
}
fn edit(engine: &mut Engine, id: u64, from: usize, to: usize, insert: &str) {
let version = run(engine, "buffer.get", json!({"id": id}))["version"].clone();
run(
engine,
"buffer.edit",
json!({"id": id, "baseVersion": version, "edits": [{"from": from, "to": to, "insert": insert}]}),
);
}
fn recovery_entries(events: &[Event]) -> Option<Vec<Value>> {
events.iter().find_map(|e| match e {
Event::RecoveryAvailable { entries } => {
Some(serde_json::to_value(entries).unwrap().as_array()?.clone())
}
_ => None,
})
}
#[test]
fn a_dropped_engine_leaves_text_that_a_new_engine_restores_exactly() {
let original = b"\xEF\xBB\xBF<?php\r\necho 1;\r\n";
let setup = Setup::new(&[("src/a.php", original)]);
let (mut engine, events) = setup.engine();
assert!(
recovery_entries(&events).is_none(),
"nothing to recover yet"
);
let id = open(&mut engine, "src/a.php");
edit(&mut engine, id, 7, 7, "$x = 'ü';\r\n");
let expected = run(&mut engine, "buffer.get", json!({"id": id}))["text"].clone();
assert_eq!(expected, "<?php\r\n$x = 'ü';\r\necho 1;\r\n");
engine.pump_vfs().unwrap();
assert!(setup.entry_files().is_empty(), "not written per keystroke");
let deadline = Instant::now() + Duration::from_secs(5);
while setup.entry_files().is_empty() {
assert!(Instant::now() < deadline, "journal not written within 5 s");
std::thread::sleep(Duration::from_millis(100));
engine.pump_vfs().unwrap();
}
drop(engine);
assert_eq!(
std::fs::read(setup.project.join("src/a.php")).unwrap(),
original,
"the file itself is untouched"
);
let (mut engine, events) = setup.engine();
let entries = recovery_entries(&events).expect("recoveryAvailable after project.open");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0]["path"], "src/a.php");
assert_eq!(entries[0]["diskChanged"], false);
assert!(entries[0]["savedAt"].as_u64().unwrap() > 0);
assert_eq!(
run(&mut engine, "recovery.list", Value::Null)["entries"],
Value::Array(entries)
);
let out = engine
.execute("recovery.restore", json!({"paths": ["src/a.php"]}))
.unwrap();
assert_eq!(out.value["failed"], json!([]));
let id = out.value["restored"][0]["id"].as_u64().unwrap();
assert!(
out.events
.contains(&Event::DirtyChanged { id, dirty: true })
);
let got = run(&mut engine, "buffer.get", json!({"id": id}));
assert_eq!(got["text"], expected);
assert_eq!(got["lineEnding"], "crlf");
assert_eq!(got["dirty"], true);
assert!(engine.state().buffers.get(id).unwrap().bom);
run(&mut engine, "file.save", json!({"id": id}));
assert_eq!(
std::fs::read(setup.project.join("src/a.php")).unwrap(),
"\u{feff}<?php\r\n$x = 'ü';\r\necho 1;\r\n".as_bytes()
);
assert!(setup.entry_files().is_empty(), "saving removes the entry");
}
#[test]
fn close_force_discard_and_project_close_remove_entries() {
let setup = Setup::new(&[("a.php", b"a"), ("b.php", b"b"), ("c.php", b"c")]);
let (mut engine, _) = setup.engine();
let a = open(&mut engine, "a.php");
let b = open(&mut engine, "b.php");
let c = open(&mut engine, "c.php");
for id in [a, b, c] {
edit(&mut engine, id, 0, 0, "x");
}
engine.flush_journal().unwrap();
assert_eq!(setup.entry_files().len(), 3);
run(&mut engine, "buffer.close", json!({"id": a, "force": true}));
assert_eq!(setup.entry_files().len(), 2);
let out = run(&mut engine, "recovery.discard", json!({"paths": ["b.php"]}));
assert_eq!(out["discarded"], json!(["b.php"]));
assert_eq!(setup.entry_files().len(), 1);
engine.flush_journal().unwrap();
assert_eq!(
setup.entry_files().len(),
2,
"a discarded entry of a dirty open buffer is journaled again"
);
run(&mut engine, "project.close", json!({"force": true}));
assert!(setup.entry_files().is_empty());
assert!(engine.state().journal.is_none());
}
#[test]
fn entries_of_a_crashed_session_survive_until_restored_or_discarded() {
let setup = Setup::new(&[("a.php", b"a"), ("b.php", b"b")]);
let (mut engine, _) = setup.engine();
for path in ["a.php", "b.php"] {
let id = open(&mut engine, path);
edit(&mut engine, id, 1, 1, "!");
}
engine.flush_journal().unwrap();
drop(engine);
let (mut engine, events) = setup.engine();
assert_eq!(recovery_entries(&events).unwrap().len(), 2);
let id = open(&mut engine, "a.php");
run(&mut engine, "buffer.close", json!({"id": id}));
assert_eq!(
setup.entry_files().len(),
2,
"closing a clean buffer keeps the old entry"
);
let out = run(&mut engine, "recovery.discard", Value::Null);
assert_eq!(out["discarded"], json!(["a.php", "b.php"]));
assert!(setup.entry_files().is_empty());
assert_eq!(
run(&mut engine, "recovery.list", Value::Null)["entries"],
json!([])
);
}
#[test]
fn restore_reports_missing_entries_and_newer_unsaved_buffers() {
let setup = Setup::new(&[("a.php", b"a"), ("b.php", b"b")]);
let (mut engine, _) = setup.engine();
for path in ["a.php", "b.php"] {
let id = open(&mut engine, path);
edit(&mut engine, id, 1, 1, "1");
}
engine.flush_journal().unwrap();
drop(engine);
let (mut engine, _) = setup.engine();
let a = open(&mut engine, "a.php");
let b = open(&mut engine, "b.php");
edit(&mut engine, b, 0, 0, "newer");
let out = run(
&mut engine,
"recovery.restore",
json!({"paths": ["a.php", "b.php", "nope.php"]}),
);
assert_eq!(out["restored"], json!([{"path": "a.php", "id": a}]));
let failed: Vec<&str> = out["failed"]
.as_array()
.unwrap()
.iter()
.map(|f| f["path"].as_str().unwrap())
.collect();
assert_eq!(failed, vec!["nope.php", "b.php"]);
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": a}))["text"],
"a1"
);
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": b}))["text"],
"newerb"
);
}
#[test]
fn disk_changes_after_the_entry_are_flagged() {
let setup = Setup::new(&[("a.php", b"a"), ("gone.php", b"g")]);
let (mut engine, _) = setup.engine();
for path in ["a.php", "gone.php"] {
let id = open(&mut engine, path);
edit(&mut engine, id, 0, 0, "x");
}
engine.flush_journal().unwrap();
drop(engine);
std::thread::sleep(Duration::from_millis(50));
std::fs::write(setup.project.join("a.php"), "changed").unwrap();
std::fs::remove_file(setup.project.join("gone.php")).unwrap();
let (mut engine, events) = setup.engine();
let entries = recovery_entries(&events).unwrap();
assert_eq!(entries[0]["path"], "a.php");
assert_eq!(entries[0]["diskChanged"], true);
assert_eq!(entries[1]["path"], "gone.php");
assert_eq!(entries[1]["diskChanged"], true);
let out = run(&mut engine, "recovery.restore", Value::Null);
assert_eq!(out["restored"].as_array().unwrap().len(), 2);
let gone = out["restored"][1]["id"].as_u64().unwrap();
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": gone}))["text"],
"xg"
);
run(&mut engine, "file.save", json!({"id": gone}));
assert_eq!(
std::fs::read_to_string(setup.project.join("gone.php")).unwrap(),
"xg"
);
}
#[test]
fn corrupt_entries_are_skipped_with_a_warning() {
let setup = Setup::new(&[("a.php", b"a")]);
let (mut engine, _) = setup.engine();
let id = open(&mut engine, "a.php");
edit(&mut engine, id, 0, 0, "ok ");
engine.flush_journal().unwrap();
drop(engine);
let dir = setup.journal_dir();
let bad_cases: [(&str, &[u8]); 4] = [
("0000000000000001.json", b"{not json"),
("0000000000000002.json", b"\xff\xfe\x00"),
(
"0000000000000003.json",
br#"{"path":"../evil.php","text":"x","lineEnding":"lf","bom":false,"savedAt":1}"#,
),
(
"0000000000000004.json",
br#"{"path":"a.php","text":"x","lineEnding":"lf","bom":false,"savedAt":1}"#,
),
];
for (name, bytes) in bad_cases {
std::fs::write(dir.join(name), bytes).unwrap();
}
let (mut engine, events) = setup.engine();
let entries = recovery_entries(&events).unwrap();
assert_eq!(entries.len(), 1, "only the good entry: {entries:?}");
assert_eq!(entries[0]["path"], "a.php");
let warnings: Vec<&Event> = events
.iter()
.filter(|e| matches!(e, Event::Notification { message_key: Some(k), .. } if k == journal::KEY_CORRUPT))
.collect();
assert_eq!(warnings.len(), 4);
for (name, _) in bad_cases {
assert!(
dir.join(format!("{name}.bad")).is_file(),
"{name} kept aside"
);
assert!(!dir.join(name).exists());
}
let out = run(&mut engine, "recovery.restore", Value::Null);
let id = out["restored"][0]["id"].as_u64().unwrap();
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": id}))["text"],
"ok a"
);
assert!(
engine.take_events().iter().all(
|e| !matches!(e, Event::Notification { message_key: Some(k), .. } if k == journal::KEY_CORRUPT)
),
"reported once"
);
}
#[test]
fn an_engine_without_persistence_has_no_journal() {
let setup = Setup::new(&[("a.php", b"a")]);
let mut engine = Engine::new().unwrap();
run(&mut engine, "project.open", json!({"path": setup.project}));
let id = open(&mut engine, "a.php");
edit(&mut engine, id, 0, 0, "x");
engine.flush_journal().unwrap();
assert!(engine.state().journal.is_none());
assert_eq!(
run(&mut engine, "recovery.list", Value::Null)["entries"],
json!([])
);
assert!(!setup.config.data_dir.exists());
}
#[test]
fn an_unwritable_journal_warns_once_and_keeps_editing() {
let setup = Setup::new(&[("a.php", b"a")]);
std::fs::create_dir_all(&setup.config.data_dir).unwrap();
std::fs::write(setup.config.data_dir.join("recovery"), "a file").unwrap();
let (mut engine, _) = setup.engine();
let id = open(&mut engine, "a.php");
edit(&mut engine, id, 0, 0, "x");
let events = engine.flush_journal().unwrap();
assert!(events.iter().any(|e| matches!(
e,
Event::Notification { message_key: Some(k), .. } if k == journal::KEY_WRITE_FAILED
)));
edit(&mut engine, id, 0, 0, "y");
assert!(engine.flush_journal().unwrap().is_empty(), "warned once");
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": id}))["text"],
"yxa"
);
}
#[test]
fn journal_write_cost_for_a_one_megabyte_buffer() {
let line = "$value = str_repeat('lutra', 10); // äöü\n";
let text = line.repeat(1024 * 1024 / line.len() + 1);
let setup = Setup::new(&[("big.php", text.as_bytes())]);
let (mut engine, _) = setup.engine();
let id = open(&mut engine, "big.php");
let mut samples = Vec::new();
for i in 0..10 {
edit(&mut engine, id, 0, 0, &i.to_string());
let start = Instant::now();
engine.flush_journal().unwrap();
samples.push(start.elapsed());
}
samples.sort();
let median = samples[samples.len() / 2];
eprintln!(
"journal write of {} bytes: median {:?}, min {:?}, max {:?}",
text.len(),
median,
samples[0],
samples[samples.len() - 1]
);
assert!(median < Duration::from_millis(500), "median {median:?}");
let size = std::fs::metadata(&setup.entry_files()[0]).unwrap().len();
assert!(size > 1024 * 1024);
}
/// One random edit: where (as a fraction of the text), how much to delete,
/// and what to insert.
fn edit_strategy() -> impl Strategy<Value = (f64, usize, String)> {
(
0.0..=1.0f64,
0usize..6,
prop::string::string_regex("(a|ü|😀|\r\n|\n|\r| |x){0,6}").unwrap(),
)
}
/// Applies random edits through `buffer.edit`; edits whose offsets fall
/// inside a character or a CRLF are rejected by the engine and skipped.
fn apply_random(engine: &mut Engine, id: u64, edits: &[(f64, usize, String)]) {
for (at, del, insert) in edits {
let got = run(engine, "buffer.get", json!({"id": id}));
let len = got["text"].as_str().unwrap().encode_utf16().count();
let from = ((len as f64) * at) as usize;
let to = (from + del).min(len);
let _ = engine.execute(
"buffer.edit",
json!({"id": id, "baseVersion": got["version"], "edits": [{"from": from, "to": to, "insert": insert}]}),
);
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(24))]
#[test]
fn random_edits_then_crash_restore_the_buffer(
crlf in any::<bool>(),
bom in any::<bool>(),
edits in prop::collection::vec(edit_strategy(), 1..20),
more in prop::collection::vec(edit_strategy(), 0..5),
) {
let ending = if crlf { "\r\n" } else { "\n" };
let mut bytes = Vec::new();
if bom {
bytes.extend_from_slice(b"\xEF\xBB\xBF");
}
bytes.extend_from_slice(format!("<?php{ending}echo 1;{ending}").as_bytes());
let setup = Setup::new(&[("a.php", &bytes)]);
let (mut engine, _) = setup.engine();
let id = open(&mut engine, "a.php");
apply_random(&mut engine, id, &edits);
engine.flush_journal().unwrap();
let before = engine.state().buffers.get(id).unwrap().clone();
apply_random(&mut engine, id, &more);
drop(engine);
let (mut engine, events) = setup.engine();
let offered = recovery_entries(&events).is_some();
prop_assert_eq!(offered, before.dirty());
if !offered {
return Ok(());
}
let out = run(&mut engine, "recovery.restore", Value::Null);
let rid = out["restored"][0]["id"].as_u64().unwrap();
let after = engine.state().buffers.get(rid).unwrap();
prop_assert_eq!(after.buffer.text(), before.buffer.text());
prop_assert_eq!(after.buffer.line_ending(), before.buffer.line_ending());
prop_assert_eq!(after.buffer.save_text(), before.buffer.save_text());
prop_assert_eq!(after.bom, before.bom);
prop_assert!(after.dirty());
prop_assert!(Path::new(&setup.project).join("a.php").is_file());
}
}

View file

@ -1,6 +1,6 @@
# Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings and themes documented · **Last updated:** 2026-10-16
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes and the recovery journal documented · **Last updated:** 2026-10-16
## Overview
@ -78,7 +78,7 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus
### Events
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`. Events say what changed; clients fetch data with `project.children` and `buffer.get`.
`lutra_engine::Event`, serialised as `{"kind": "<camelCase>", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal). Events say what changed; clients fetch data with `project.children` and `buffer.get`.
Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump.
@ -132,6 +132,16 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- Accessibility: `ui/tests/theme/contrast.test.ts` checks every text/background pair the components draw with against WCAG AA (4.5:1 text, 3:1 cursor and modified dot) in both themes. It reads `ui/tests/theme/themes.json`, which the Rust test `theme::tests::ui_snapshot_is_current` keeps equal to the Rust definition (`LUTRA_UPDATE_SNAPSHOTS=1` rewrites it). `ui/tests/theme/theme.test.ts` fails on a `var(--lt-x)` the themes lack and on a fallback for a token they define.
- Not themed yet: the native title bar follows the OS, not the Lutra theme; spacing and size tokens (`--lt-space-*`, `--lt-radius`, `--lt-row-height`…) are still CSS fallbacks in components; `editor.fontSize` does not drive `--lt-font-size-editor` yet.
### Recovery journal (M1.7)
- **Storage:** `<data_dir>/recovery/<project-id>/<entry-id>.json`. The project id is the FNV-1a 64-bit hash of the canonical project root, the entry id the same hash of the project-relative path, each as 16 hex digits (FNV instead of `std`'s hasher, whose output may change between Rust versions). One file per dirty buffer: `{path, text, lineEnding, bom, savedAt}`; `text` is the buffer text as held in memory (mixed line breaks included), `lineEnding` the ending it saves with, `savedAt` milliseconds since the Unix epoch. Engines without a config (`Engine::new`) keep no journal. Code: `crates/engine/src/journal.rs`, commands in `cmd/recovery.rs`.
- **Writing:** `buffer.edit` only records the edit time. `Engine::pump_vfs` (the desktop's pump thread, every 100 ms) writes a buffer once it has been idle for 1 s, or 2 s after its first unwritten edit while typing continues, so an entry is on disk at most ~1.1 s after the last edit and never per keystroke. Writes use `lutra_vfs::write_atomic`. `Engine::flush_journal()` writes everything now (tests, hosts about to stop). Cost for a 1 MiB buffer (measured on Windows 11, `journal_write_cost_for_a_one_megabyte_buffer`): median 8.5 ms in a release build, 67 ms in a debug build, under the engine lock; a keystroke arriving meanwhile waits that long. Moving the write to a background thread is a follow-up if large files make it noticeable.
- **Removal:** `file.save`/`file.saveAll`, `buffer.close` (also `force`), `project.close`/`project.open` with `force` and `recovery.discard` remove entries. Save and close remove only entries this session wrote or restored; entries left by a crashed session stay until restored or discarded. Editing such a file without restoring it overwrites its entry.
- **Commands and event:** after `project.open`, `recoveryAvailable {entries: [{path, savedAt, diskChanged}]}` when the journal is not empty. `recovery.list` → `{entries}`; `recovery.restore {paths?}` → `{restored: [{path, id}], failed: [{path, message}]}` opens each file as a dirty buffer (version 1, saved version 0) with the journal text, line ending and BOM, or puts the text into a clean open buffer; a buffer with unsaved changes is newer than the journal and is left alone (`failed`); a file gone from disk is restored too and saving recreates it. `recovery.discard {paths?}` → `{discarded}`; a discarded entry of an open dirty buffer is written again on the next tick. `diskChanged` is true when the file's modification time is after `savedAt` or the file is gone.
- **Untrusted input:** entries are read with a 512 MiB cap, at most 1,000 per project. An entry that is not valid JSON of that shape, whose path escapes the project or does not match its file name is renamed to `<entry>.bad`, skipped, and reported once as `notification {level: warning, messageKey: "notification.recovery.corrupt", params: {file, reason}}`. A failed write is reported once until a write succeeds (`notification.recovery.writeFailed {path, reason}`); an unreadable journal directory gives `notification.recovery.unavailable {reason}`. Neither stops editing or opening.
- **UI:** `ui/src/components/recovery/` (store `recovery.ts`, `RecoveryDialog.vue`, mounted in `App.vue`). The list comes from `recoveryAvailable` and, because that event is not replayed after a page reload, from `recovery.list` on `projectOpened`. Restore all, Restore selected (the rest stay listed) and Discard always pass explicit paths; Escape closes and keeps the journal for the next open.
- **Limits:** two Lutra instances on the same project share one journal directory; `diskChanged` misses a disk change that happened before the last journal write.
## Decisions (M0)
| Question | Decision | Why |
@ -149,6 +159,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.7: recovery journal (storage, debounce, removal, commands, recoveryAvailable, restore dialog) |
| 2026-10-16 | minor | M1.10: themes (light theme, editor tokens, theme.list, theme.systemPreference, themeChanged, init script from the setting, live switch, contrast test) |
| 2026-10-16 | minor | M1.9a: engine construction (EngineConfig, with_config) and settings (file, commands, settingsChanged, notification) |
| 2026-10-15 | minor | M1.11: message catalog (`t`, lint rule, catalog test, engine messages stay English) |

View file

@ -1,13 +1,13 @@
# Gaps
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app); G3 project tree works in the app, settings backend and theme switching landed; G14 English UI catalog in place · **Last updated:** 2026-10-16
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal); G3 project tree works in the app, settings backend and theme switching landed; G14 English UI catalog in place · **Last updated:** 2026-10-16
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
| # | Gap | Milestone | Estimate (one agent) |
|---|---|---|---|
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), recovery journal, tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~18 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 option | M1 | ~16 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, error notifications for the folder picker, ~~tabs~~ (M1.6); command palette, settings (backend: M1.9a; dialog: M1.9b), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker comes with the dialog) | M1 | ~24 h |
| G4 | Syntax and structure: tree-sitter PHP, Lezer highlighting, file structure | M2 | ~15 h |
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
@ -16,14 +16,16 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| G8 | Git integration | M4 | ~150 h |
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
| G11 | Stability: crash-free operation on real projects and machines | ongoing | ~100 h |
| G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h |
| G12 | Performance budgets: start, open, type, search, index | ongoing | ~100 h |
| G13 | Frameworks: Symfony, Laravel, Shopware, WordPress | M6 | ~300 h |
| G14 | Localization: English and German interface: ~~English message catalog for UI strings~~ (M1.11), engine messages (`EngineError.message`) as message keys, language switch, plurals, German catalog | later | ~38 h |
| G15 | Database tools, HTTP client, Docker and remote | later | ~430 h |
| G16 | Plug-ins and ecosystem | later | ~120 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. Still open: the recovery journal, 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 ~18 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). 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.
G11 progress: M1.7 added the crash-recovery journal: unsaved buffers are written atomically about 1 s after the last edit and offered back after a crash; corrupt entries are skipped with a warning. Covered by a property test (random edits, crash, restore equals the buffer) and a headless control-channel test; not yet checked by killing the running app (gaming mode). Open: journal writes run under the engine lock (8.5 ms for 1 MiB, release), two instances on one project share a journal, local history.
G14 progress: M1.11 moved every UI string in `ui/src` into the English catalog `ui/src/i18n/en.json` behind `t(key, params?)`, enforced by `vue/no-bare-strings-in-template` and a catalog test. Messages the engine sends (`EngineError.message`, the slogan from `app.about`) are still English text; they need message keys with params before a second language can cover them.
@ -39,6 +41,7 @@ Known smaller items from M0:
|---|---|---|
| 2026-10-15 | minor | G14 note: English message catalog (M1.11) |
| 2026-10-15 | minor | G2 shrunk: tabs and editor (M1.6) |
| 2026-10-16 | minor | G2 shrunk, G11 note: recovery journal (M1.7) |
| 2026-10-16 | minor | G3: theme switching (M1.10) |
| 2026-10-16 | minor | G3: settings backend (M1.9a) |
| 2026-10-15 | minor | G3 shrunk: project tree wired to the engine (M1.4) |

View file

@ -7,7 +7,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
| Milestone | Goal | State | Hours |
|---|---|---|---:|
| 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 | in progress (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) | ~6 (2.5 measured for M1.1–M1.6) |
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | in progress (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) | ~6 (2.5 measured for M1.1–M1.6) |
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | not started | ~5 |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | not started | ~8 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | not started | ~150 |
@ -31,6 +31,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.7 recovery journal |
| 2026-10-16 | minor | M1.9a settings backend, M1.10 themes |
| 2026-10-15 | minor | M1.11 message catalog |
| 2026-10-15 | minor | Cycle C1 review: M1–M3 hours recalibrated ×0.1, M0 CI note |

View file

@ -12,7 +12,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
| Area | Weight | Score | Missing | Hours (one agent) | Evidence |
|---|---:|---:|---|---:|---|
| Editor core | 12 | 8% (est.) | crash-recovery journal, syntax highlighting (M2), code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs | ~110 (est.) | M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) |
| Editor core | 12 | 9% (est.) | syntax highlighting (M2), code folding, soft wrap and other editor settings, preview tab, pinned/split/reordered tabs, close others/all, reopen closed tab, tab limit, conflict UI for files changed on disk, autosave, local history, encodings other than UTF-8, large-file mode, column selection and multi-caret checked against the docs; recovery journal not yet checked in the running app (gaming mode) | ~106 (est.) | M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `<data_dir>/recovery/<project-id>/` about 1 s after the last edit (at least every 2 s while typing), never per keystroke; removed on save, close and discard; `recoveryAvailable` after `project.open`, `recovery.list/restore/discard`; restored buffers are dirty and keep line ending and BOM; corrupt entries are moved aside with a warning. Restore dialog (`ui/src/components/recovery/`: Restore all / selected / Discard, time, changed-on-disk hint). Tests: engine dropped mid-edit and a new engine restores the exact CRLF + BOM text, corrupt entries, removal paths, a property test of random edit sequences → crash → restore equals the buffer (`crates/engine/tests/recovery.rs`, 10 tests), the same flow headless over the control channel (`crates/control/tests/recovery.rs`), 10 Vitest tests for the dialog. 1 MiB entry write: 8.5 ms median (release, measured). Graded against `plan/phpstorm/04-recovery.md`. M1.6: tabs and a CodeMirror 6 editor in the app (`ui/src/components/editor/`, `ui/src/stores/editor.ts`): open from the project tree or engine events, activate, close by button, middle click or `Mod+W`, dirty dot, Save / Don't Save / Cancel on closing a dirty tab, `Mod+S` / `Mod+Alt+S` from engine command specs, non-blocking notice for a dirty file changed or deleted on disk; local edits go to `buffer.edit` with version-based resync, CRLF files keep `\r\n`; undo/redo, multiple selections, search and bracket matching from CodeMirror's basic setup. Vitest: a burst of 400 keystrokes with stale versions and remote edits loses none, a CRLF burst with deletions converges, store and component tests against a fake engine (`ui/tests/editor/`, 22 tests). Checked in the app on Windows 11 with `--control` and `ui.screenshot`: typing via the UI and via `buffer.edit`, save to disk, close question, middle click, disk-change notice. 1 MB file (16,385 lines): engine `file.open` 80 ms over the control channel (debug build, measured), editor state 1–6 ms and first rendered view 4–11 ms in Chromium (measured), ≈ 90 ms in total (estimated, budget 150 ms). Graded against `plan/phpstorm/03-editor-tabs.md`. `crates/text`: rope buffer, positions, edits (M1.1, unit tests + proptests). M1.3: engine buffers with versions and dirty state, `file.open`, `buffer.get`, `buffer.edit` (UTF-16 change sets, `stale_version`), `file.save`, `file.saveAll`, `buffer.close` with unsaved-changes guard, line ending and BOM kept on save, clean buffers reload on external change; 14 integration tests on temp dirs (`crates/engine/tests/workspace.rs`) |
| Project view, VFS | 6 | 8% (est.) | views list (project / scopes), toolbar (Select Opened File, Expand/Collapse All), sort and display options, show/hide excluded, distinct icons for library and excluded folders, file colours, speed search, preview, file operations, showing truncated listings | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). Graded against `plan/phpstorm/02-project-view.md`: tool window, folder-first tree, dimmed ignored/excluded, keyboard navigation and live refresh exist; most toolbar, view and display options do not |
| Navigation | 10 | 0% | everything | ~120 (est.) | — |
| Search and replace | 6 | 0% | everything | ~80 (est.) | — |
@ -62,6 +62,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.7: Editor core 8% → 9% (est.), crash-recovery journal and restore dialog |
| 2026-10-16 | minor | M1.10: Settings row 2% → 4% (est.), light/dark themes with live switching |
| 2026-10-16 | minor | M1.9a: Settings row 0% → 2% (est.), settings backend without UI |
| 2026-10-15 | minor | Calibration note after cycle C1 (factor 0.07) |

View file

@ -1,6 +1,6 @@
# UI parity checklist
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10) · **Last updated:** 2026-10-16
> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7) · **Last updated:** 2026-10-16
- [ ] Main window: tool window stripes, editor area, status bar, navigation bar
- M1.5 (2026-10-14): left tool window with header, hide button, collapsed stripe with a show button, resizable by pointer and keyboard; editor area placeholder; status bar. Missing: stripes with several tool windows, bottom/right docking, navigation bar, layout persistence. Not checked in the running app yet (needs M1.4).
@ -9,6 +9,8 @@
- M1.4 (2026-10-15): runs against the real engine in the app: projects open from the folder picker or the command line, the tree updates live when files change on disk; checked with `ui.screenshot` on Windows 11. Missing: scroll from source (Select Opened File), expand/collapse all, views list, sort options, speed search, file colours, file operations. Behaviour notes: `plan/phpstorm/02-project-view.md`.
- [ ] Editor tabs (pin, split, reorder, close others)
- M1.6 (2026-10-15): tab bar above a CodeMirror 6 editor; files open from the project tree (Enter, double click) next to the active tab, or from engine events (control channel, page reload); click and Left/Right activate, the close button, a middle click and `Mod+W` close; a dot marks unsaved changes; closing a dirty tab asks Save / Don't Save / Cancel; `Mod+S` saves, `Mod+Alt+S` saves all (shortcuts read from the engine's command specs); a non-blocking notice when a dirty file changes or disappears on disk. Checked with `ui.screenshot` on Windows 11 and Vitest. Missing: preview tab, pin, split, reorder by drag, close others/all, reopen closed tab, tab limit, tab context menu, recent-files switcher, duplicate-name disambiguation. Behaviour notes: `plan/phpstorm/03-editor-tabs.md`.
- [ ] Restore dialog for unsaved changes after a crash
- M1.7 (2026-10-16): modal dialog after a project opens when the recovery journal holds unsaved texts: files with the time they were journaled and a hint when the file changed on disk since; Restore All, Restore Selected (the others stay listed), Discard; Escape keeps the journal for the next open; restore failures listed. Catalog strings, `--lt-*` tokens, Vitest (10 tests). Live check pending (gaming mode). Missing: a diff against the disk version, local history. Behaviour notes: `plan/phpstorm/04-recovery.md`.
- [ ] Command palette / search everywhere
- [ ] Settings dialog with search
- [ ] Keymap editor (Lutra's own default keymap; no copied keymaps)
@ -25,6 +27,7 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | Restore dialog (M1.7) |
| 2026-10-16 | minor | Themes partial (M1.10) |
| 2026-10-15 | minor | Editor tabs partial (M1.6) |
| 2026-10-15 | minor | Project tool window runs against the engine (M1.4) |

View file

@ -1,12 +1,14 @@
<script setup lang="ts">
/**
* Root component: mounts the main window layout with the editor area; the
* slogan shows while no tab is open. Loads product information from the
* slogan shows while no tab is open, and the restore dialog for unsaved
* texts from the recovery journal. Loads product information from the
* engine on mount and starts following the theme (see `theme.ts`).
*/
import { onMounted, onUnmounted } from "vue";
import EditorArea from "./components/editor/EditorArea.vue";
import MainLayout from "./components/layout/MainLayout.vue";
import RecoveryDialog from "./components/recovery/RecoveryDialog.vue";
import { useAppStore } from "./stores/app";
import { startTheme } from "./theme";
@ -34,6 +36,7 @@ onUnmounted(() => {
</p>
</EditorArea>
</MainLayout>
<RecoveryDialog />
</template>
<style scoped>

View file

@ -0,0 +1,316 @@
<script setup lang="ts">
/**
* The restore dialog: lists the unsaved texts the recovery journal holds
* after a project opened, with the time each was written and a hint when
* the file changed on disk since. Restore all, Restore selected (the ticked
* files; the rest stay listed) or Discard (every listed file). Escape closes
* the dialog and keeps the journal for the next open. When a restore leaves
* failures, they are listed until the dialog is closed.
*/
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { t } from "../../i18n";
import { useRecoveryStore } from "./recovery";
const recovery = useRecoveryStore();
/** The Restore all button, focused when the dialog appears. */
const restoreAllButton = ref<HTMLButtonElement | null>(null);
/** The Close button shown when only failures are left. */
const closeButton = ref<HTMLButtonElement | null>(null);
onMounted(() => {
recovery.start();
});
onUnmounted(() => {
recovery.stop();
});
/**
* What the dialog shows: the list, only failures, or nothing. Focus moves
* to the first button whenever this changes to something visible.
*/
function mode(): "list" | "failures" | "hidden" {
if (!recovery.open) {
return "hidden";
}
return recovery.entries.length > 0 ? "list" : "failures";
}
watch(
mode,
async (shown) => {
if (shown !== "hidden") {
await nextTick();
(restoreAllButton.value ?? closeButton.value)?.focus();
}
},
{ immediate: true },
);
/**
* Formats a journal time for the list.
*
* @param savedAt - ms since the Unix epoch.
*/
function formatTime(savedAt: number): string {
return new Date(savedAt).toLocaleString();
}
/**
* Closes on Escape.
*
* @param event - the key event inside the dialog.
*/
function onKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") {
event.preventDefault();
recovery.close();
}
}
/**
* Ticks or unticks an entry from its checkbox.
*
* @param path - the entry's path.
* @param event - the change event of the checkbox.
*/
function onToggle(path: string, event: Event): void {
recovery.toggle(path, (event.target as HTMLInputElement).checked);
}
</script>
<template>
<div
v-if="recovery.open"
class="recovery"
data-test="recovery-dialog"
>
<div
class="recovery__dialog"
role="dialog"
aria-modal="true"
aria-labelledby="lt-recovery-title"
aria-describedby="lt-recovery-intro"
@keydown="onKeydown"
>
<h2
id="lt-recovery-title"
class="recovery__title"
>
{{ t("recovery.dialog.title") }}
</h2>
<p
id="lt-recovery-intro"
class="recovery__intro"
>
{{ t("recovery.dialog.intro") }}
</p>
<ul
v-if="recovery.entries.length > 0"
class="recovery__list"
>
<li
v-for="entry in recovery.entries"
:key="entry.path"
class="recovery__entry"
data-test="recovery-entry"
>
<label class="recovery__label">
<input
type="checkbox"
:checked="recovery.selected.has(entry.path)"
:data-test="`recovery-select-${entry.path}`"
@change="onToggle(entry.path, $event)"
>
<span class="recovery__path">{{ entry.path }}</span>
</label>
<span class="recovery__meta">
{{ t("recovery.dialog.savedAt", { time: formatTime(entry.savedAt) }) }}
</span>
<span
v-if="entry.diskChanged"
class="recovery__changed"
data-test="recovery-changed"
>
{{ t("recovery.dialog.changedOnDisk") }}
</span>
</li>
</ul>
<ul
v-if="recovery.failures.length > 0"
class="recovery__failures"
role="alert"
data-test="recovery-failures"
>
<li
v-for="failure in recovery.failures"
:key="failure.path"
>
{{ t("recovery.dialog.failed", { path: failure.path, message: failure.message }) }}
</li>
</ul>
<p
v-if="recovery.error"
class="recovery__error"
role="alert"
data-test="recovery-error"
>
{{ recovery.error }}
</p>
<div class="recovery__buttons">
<template v-if="recovery.entries.length > 0">
<button
ref="restoreAllButton"
type="button"
class="recovery__button recovery__button--primary"
data-test="recovery-restore-all"
:disabled="recovery.busy"
@click="recovery.restoreAll()"
>
{{ t("recovery.dialog.restoreAll") }}
</button>
<button
type="button"
class="recovery__button"
data-test="recovery-restore-selected"
:disabled="recovery.busy || recovery.selected.size === 0"
@click="recovery.restoreSelected()"
>
{{ t("recovery.dialog.restoreSelected") }}
</button>
<button
type="button"
class="recovery__button"
data-test="recovery-discard"
:disabled="recovery.busy"
@click="recovery.discard()"
>
{{ t("recovery.dialog.discard") }}
</button>
</template>
<button
v-else
ref="closeButton"
type="button"
class="recovery__button recovery__button--primary"
data-test="recovery-close"
@click="recovery.close()"
>
{{ t("common.close") }}
</button>
</div>
</div>
</div>
</template>
<style scoped>
.recovery {
position: fixed;
inset: 0;
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 10%;
background: color-mix(in srgb, var(--lt-bg) 50%, transparent);
z-index: 20;
}
.recovery__dialog {
min-width: 360px;
max-width: min(640px, 90vw);
max-height: 70vh;
display: flex;
flex-direction: column;
padding: 16px;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
}
.recovery__title {
margin: 0 0 8px;
font-size: var(--lt-font-size-ui);
font-weight: 600;
}
.recovery__intro {
margin: 0 0 12px;
}
.recovery__list,
.recovery__failures {
margin: 0 0 12px;
padding: 0;
list-style: none;
overflow-y: auto;
}
.recovery__entry {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 12px;
padding: 4px 0;
border-bottom: 1px solid var(--lt-border);
}
.recovery__label {
display: flex;
align-items: baseline;
gap: 6px;
}
.recovery__path {
overflow-wrap: anywhere;
}
.recovery__meta {
color: var(--lt-fg-muted);
font-size: var(--lt-font-size-small);
}
.recovery__changed {
color: var(--lt-accent);
font-size: var(--lt-font-size-small);
}
.recovery__failures,
.recovery__error {
color: var(--lt-error);
}
.recovery__error {
margin: 0 0 12px;
}
.recovery__buttons {
display: flex;
justify-content: flex-end;
gap: 8px;
}
.recovery__button {
padding: 4px 12px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: 4px;
}
.recovery__button--primary {
border-color: var(--lt-accent);
}
.recovery__button:disabled {
color: var(--lt-fg-muted);
}
.recovery__button:focus-visible,
.recovery__label input:focus-visible {
outline: 1px solid var(--lt-accent);
}
</style>

View file

@ -0,0 +1,236 @@
/**
* State of the restore dialog: the unsaved texts the engine's crash-recovery
* journal offers after a project opens (see `docs/architecture.md` ›
* Recovery journal).
*
* The list arrives with the `recoveryAvailable` event. Because that event is
* not replayed after a page reload, `projectOpened` also asks the engine with
* `recovery.list`. Every action names its paths explicitly, so entries of
* files restored earlier in the dialog are never discarded by accident.
*/
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { onEngineEvent, run, type EngineEventPayload, type JsonValue } from "../../ipc";
/** One unsaved text the journal holds. */
export interface RecoveryEntry {
/** Project-relative path with `/`. */
path: string;
/** When the text was written to the journal, ms since the Unix epoch. */
savedAt: number;
/** The file changed on disk after that, or is gone. */
diskChanged: boolean;
}
/** A path the engine could not restore, with its message. */
export interface RecoveryFailure {
/** Project-relative path. */
path: string;
/** English message from the engine. */
message: string;
}
/**
* Checks the entry list of `recoveryAvailable` or `recovery.list`; it
* crosses the IPC boundary. Malformed entries are skipped.
*
* @param raw - the `entries` value, untrusted.
* @returns the valid entries.
*/
export function toRecoveryEntries(raw: unknown): RecoveryEntry[] {
if (!Array.isArray(raw)) {
return [];
}
return raw.flatMap((item: unknown) => {
if (typeof item !== "object" || item === null) {
return [];
}
const e = item as Record<string, unknown>;
return typeof e.path === "string" &&
typeof e.savedAt === "number" &&
Number.isFinite(e.savedAt) &&
typeof e.diskChanged === "boolean"
? [{ path: e.path, savedAt: e.savedAt, diskChanged: e.diskChanged }]
: [];
});
}
/**
* Checks the `failed` list of `recovery.restore`.
*
* @param raw - the `failed` value, untrusted.
* @returns the valid failures.
*/
function toFailures(raw: unknown): RecoveryFailure[] {
if (!Array.isArray(raw)) {
return [];
}
return raw.flatMap((item: unknown) => {
if (typeof item !== "object" || item === null) {
return [];
}
const f = item as Record<string, unknown>;
return typeof f.path === "string" && typeof f.message === "string"
? [{ path: f.path, message: f.message }]
: [];
});
}
/** Store behind the restore dialog. */
export const useRecoveryStore = defineStore("recovery", () => {
/** Entries still waiting for a decision; the dialog shows while non-empty. */
const entries = ref<RecoveryEntry[]>([]);
/** Paths ticked for "Restore selected". */
const selected = ref<Set<string>>(new Set());
/** Paths the last restore could not open. */
const failures = ref<RecoveryFailure[]>([]);
/** Error of the last failed call, shown in the dialog. */
const error = ref<string | null>(null);
/** A restore or discard is running. */
const busy = ref(false);
/** Whether the dialog is shown. */
const open = computed(() => entries.value.length > 0 || failures.value.length > 0);
/** Ends the event subscription; null while not subscribed. */
let unsubscribe: (() => void) | null = null;
/**
* Shows `list` in the dialog, with nothing ticked.
*
* @param list - the entries.
*/
function show(list: RecoveryEntry[]): void {
entries.value = list;
selected.value = new Set();
failures.value = [];
error.value = null;
}
/** Hides the dialog; the journal keeps its entries for the next open. */
function close(): void {
show([]);
}
/** Asks the engine for the entries, after a project opened. */
async function refresh(): Promise<void> {
const result = await run<{ entries?: unknown }>("recovery.list");
if (result.ok) {
show(toRecoveryEntries(result.value.entries));
}
}
/**
* Reacts to an engine event.
*
* @param event - the event, untrusted.
*/
function handleEvent(event: EngineEventPayload): void {
switch (event.kind) {
case "recoveryAvailable":
show(toRecoveryEntries((event as { entries?: unknown }).entries));
break;
case "projectOpened":
void refresh();
break;
case "projectClosed":
close();
break;
default:
break;
}
}
/** Subscribes to engine events; repeated calls do nothing. */
function start(): void {
unsubscribe ??= onEngineEvent(handleEvent);
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/**
* Ticks or unticks a path.
*
* @param path - the entry's path.
* @param on - whether it is ticked.
*/
function toggle(path: string, on: boolean): void {
const next = new Set(selected.value);
if (on) {
next.add(path);
} else {
next.delete(path);
}
selected.value = next;
}
/**
* Runs a recovery command on `paths` and removes them from the list when
* it succeeds.
*
* @param command - `recovery.restore` or `recovery.discard`.
* @param paths - the paths, never empty.
*/
async function act(command: string, paths: string[]): Promise<void> {
if (busy.value || paths.length === 0) {
return;
}
busy.value = true;
error.value = null;
const params: JsonValue = { paths };
const result = await run<{ failed?: unknown }>(command, params);
busy.value = false;
if (!result.ok) {
error.value = result.error.message;
return;
}
const done = new Set(paths);
entries.value = entries.value.filter((e) => !done.has(e.path));
selected.value = new Set([...selected.value].filter((p) => !done.has(p)));
failures.value = toFailures(result.value.failed);
}
/** Restores every listed entry. */
async function restoreAll(): Promise<void> {
await act(
"recovery.restore",
entries.value.map((e) => e.path),
);
}
/** Restores the ticked entries; the others stay listed. */
async function restoreSelected(): Promise<void> {
await act(
"recovery.restore",
entries.value.filter((e) => selected.value.has(e.path)).map((e) => e.path),
);
}
/** Discards every listed entry. */
async function discard(): Promise<void> {
await act(
"recovery.discard",
entries.value.map((e) => e.path),
);
}
return {
entries,
selected,
failures,
error,
busy,
open,
handleEvent,
start,
stop,
toggle,
close,
restoreAll,
restoreSelected,
discard,
};
});

View file

@ -1,6 +1,7 @@
{
"app.statusBar.version": "{name} {version}",
"common.cancel": "Cancel",
"common.close": "Close",
"common.dismiss": "Dismiss",
"common.dontSave": "Don't Save",
"common.error.unexpectedResult": "unexpected result of {command}",
@ -15,10 +16,21 @@
"editor.tabs.close": "Close {name}",
"editor.tabs.label": "Editor tabs",
"editor.tabs.unsaved": "unsaved changes",
"notification.recovery.corrupt": "Skipped an unreadable recovery file ({file}): {reason}",
"notification.recovery.unavailable": "Could not read the recovery journal: {reason}",
"notification.recovery.writeFailed": "Could not keep a recovery copy of {path}: {reason}",
"project.empty.noFolder": "No folder is open.",
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",
"project.tree.loading": "Loading…",
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
"recovery.dialog.discard": "Discard",
"recovery.dialog.failed": "{path} could not be restored: {message}",
"recovery.dialog.intro": "Lutra stopped before these files were saved. Restore your unsaved changes?",
"recovery.dialog.restoreAll": "Restore All",
"recovery.dialog.restoreSelected": "Restore Selected",
"recovery.dialog.savedAt": "Saved {time}",
"recovery.dialog.title": "Unsaved changes found",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light"
}

View file

@ -26,7 +26,11 @@ export type EngineEventPayload =
| { kind: "bufferClosed"; id: number }
| { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }
| { kind: "watchFailed"; message: string }
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> };
| { kind: "themeChanged"; id: string; dark: boolean; tokens: Record<string, string> }
| {
kind: "recoveryAvailable";
entries: { path: string; savedAt: number; diskChanged: boolean }[];
};
/** Callback receiving engine events. */
export type EngineEventHandler = (event: EngineEventPayload) => void;

View file

@ -37,9 +37,16 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
/**
* Keys the source never passes to `t` literally because they arrive at
* runtime from the engine: theme labels from `theme.list`.
* runtime from the engine: theme labels from `theme.list` and the
* `messageKey` of `notification` events.
*/
const RUNTIME_KEYS = new Set(["theme.lutraDark", "theme.lutraLight"]);
const RUNTIME_KEYS = new Set([
"notification.recovery.corrupt",
"notification.recovery.unavailable",
"notification.recovery.writeFailed",
"theme.lutraDark",
"theme.lutraLight",
]);
afterEach(() => {
vi.restoreAllMocks();
@ -87,7 +94,9 @@ describe("t", () => {
describe("en.json", () => {
it("uses flat dotted keys of known areas with string values", () => {
for (const [key, value] of Object.entries(en)) {
expect(key).toMatch(/^(app|project|editor|common|theme)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/);
expect(key).toMatch(
/^(app|project|editor|common|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");
}

View file

@ -0,0 +1,236 @@
/**
* Tests for the restore dialog and its store: the list from
* `recoveryAvailable` and from `recovery.list` after `projectOpened`, the
* "changed on disk" hint, Restore all / Restore selected / Discard with
* explicit paths, failures, errors, Escape, and checking untrusted entries.
* The engine is a fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import RecoveryDialog from "../../src/components/recovery/RecoveryDialog.vue";
import { toRecoveryEntries, useRecoveryStore } from "../../src/components/recovery/recovery";
/** Entries as the engine sends them. */
const ENTRIES = [
{ path: "src/a.php", savedAt: Date.UTC(2026, 9, 16, 12, 0), diskChanged: false },
{ path: "src/b.php", savedAt: Date.UTC(2026, 9, 16, 12, 5), diskChanged: true },
{ path: "c.php", savedAt: Date.UTC(2026, 9, 16, 12, 9), diskChanged: false },
];
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** Result of `recovery.restore`, per test. */
let restoreResult: unknown;
/** Error `recovery.discard` fails with, if any. */
let discardError: { code: string; message: string } | null;
/**
* Rejects like the shell does with an engine error.
*
* @param code - error code.
* @param message - error message.
*/
function fail(code: string, message: string): Promise<never> {
return Promise.reject(Object.assign(new Error(message), { code, message }));
}
/** Mounted wrappers, unmounted after each test. */
const mounted: VueWrapper[] = [];
/** Mounts the dialog. */
function mountDialog(): VueWrapper {
const wrapper = mount(RecoveryDialog, { attachTo: document.body });
mounted.push(wrapper);
return wrapper;
}
/** Shows the entries as if `recoveryAvailable` arrived. */
async function offer(entries: unknown = ENTRIES): Promise<void> {
useRecoveryStore().handleEvent({
kind: "recoveryAvailable",
entries: entries as never,
});
await flushPromises();
}
beforeEach(() => {
setActivePinia(createPinia());
calls = [];
restoreResult = { restored: [], failed: [] };
discardError = null;
invoke.mockReset();
invoke.mockImplementation(
(cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd !== "engine_execute" || !args) {
return Promise.reject(new Error("no shell"));
}
calls.push({ command: args.command, params: args.params });
switch (args.command) {
case "recovery.list":
return Promise.resolve({ entries: ENTRIES });
case "recovery.restore":
return Promise.resolve(restoreResult);
case "recovery.discard":
return discardError
? fail(discardError.code, discardError.message)
: Promise.resolve({ discarded: args.params.paths });
default:
return fail("unknown_command", args.command);
}
},
);
});
afterEach(() => {
for (const wrapper of mounted.splice(0)) {
wrapper.unmount();
}
});
describe("RecoveryDialog", () => {
it("is hidden without entries", () => {
const wrapper = mountDialog();
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
});
it("lists the offered files with time and the changed-on-disk hint", async () => {
const wrapper = mountDialog();
await offer();
const dialog = wrapper.get("[data-test=recovery-dialog]");
expect(dialog.get("[role=dialog]").attributes("aria-modal")).toBe("true");
const rows = wrapper.findAll("[data-test=recovery-entry]");
expect(rows.map((r) => r.find(".recovery__path").text())).toEqual([
"src/a.php",
"src/b.php",
"c.php",
]);
expect(rows[0]?.text()).toContain(
`Saved ${new Date(ENTRIES[0]?.savedAt ?? 0).toLocaleString()}`,
);
expect(rows[0]?.find("[data-test=recovery-changed]").exists()).toBe(false);
expect(rows[1]?.get("[data-test=recovery-changed]").text()).toBe(
"The file changed on disk since then",
);
expect(document.activeElement).toBe(
wrapper.get("[data-test=recovery-restore-all]").element,
);
});
it("asks the engine after projectOpened, for reloads and late subscribers", async () => {
const wrapper = mountDialog();
useRecoveryStore().handleEvent({ kind: "projectOpened", root: "/p", name: "p" });
await flushPromises();
expect(calls).toEqual([{ command: "recovery.list", params: {} }]);
expect(wrapper.findAll("[data-test=recovery-entry]")).toHaveLength(3);
});
it("restores all listed files with explicit paths and closes", async () => {
const wrapper = mountDialog();
await offer();
await wrapper.get("[data-test=recovery-restore-all]").trigger("click");
await flushPromises();
expect(calls).toEqual([
{ command: "recovery.restore", params: { paths: ["src/a.php", "src/b.php", "c.php"] } },
]);
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
});
it("restores the selected files and keeps the others listed", async () => {
const wrapper = mountDialog();
await offer();
const selected = wrapper.get("[data-test=recovery-restore-selected]");
expect(selected.attributes("disabled")).toBeDefined();
await wrapper.get("[data-test='recovery-select-src/b.php']").setValue(true);
expect(selected.attributes("disabled")).toBeUndefined();
await selected.trigger("click");
await flushPromises();
expect(calls).toEqual([{ command: "recovery.restore", params: { paths: ["src/b.php"] } }]);
expect(
wrapper.findAll("[data-test=recovery-entry]").map((r) => r.find(".recovery__path").text()),
).toEqual(["src/a.php", "c.php"]);
await wrapper.get("[data-test=recovery-discard]").trigger("click");
await flushPromises();
expect(calls[1]).toEqual({
command: "recovery.discard",
params: { paths: ["src/a.php", "c.php"] },
});
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
});
it("unticking a file disables Restore selected again", async () => {
const wrapper = mountDialog();
await offer();
const box = wrapper.get("[data-test='recovery-select-c.php']");
await box.setValue(true);
await box.setValue(false);
expect(
wrapper.get("[data-test=recovery-restore-selected]").attributes("disabled"),
).toBeDefined();
});
it("lists files that could not be restored until closed", async () => {
restoreResult = {
restored: [],
failed: [{ path: "src/a.php", message: "unsaved changes in src/a.php" }, { bad: 1 }],
};
const wrapper = mountDialog();
await offer([ENTRIES[0]]);
await wrapper.get("[data-test=recovery-restore-all]").trigger("click");
await flushPromises();
const failures = wrapper.get("[data-test=recovery-failures]");
expect(failures.attributes("role")).toBe("alert");
expect(failures.findAll("li")).toHaveLength(1);
expect(failures.text()).toBe(
"src/a.php could not be restored: unsaved changes in src/a.php",
);
expect(document.activeElement).toBe(wrapper.get("[data-test=recovery-close]").element);
await wrapper.get("[data-test=recovery-close]").trigger("click");
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
});
it("shows a failed call and keeps the list", async () => {
discardError = { code: "failed", message: "disk full" };
const wrapper = mountDialog();
await offer();
await wrapper.get("[data-test=recovery-discard]").trigger("click");
await flushPromises();
expect(wrapper.get("[data-test=recovery-error]").text()).toBe("disk full");
expect(wrapper.findAll("[data-test=recovery-entry]")).toHaveLength(3);
});
it("closes on Escape and on projectClosed without touching the journal", async () => {
const wrapper = mountDialog();
await offer();
await wrapper.get("[role=dialog]").trigger("keydown", { key: "Escape" });
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
await offer();
useRecoveryStore().handleEvent({ kind: "projectClosed" });
await flushPromises();
expect(wrapper.find("[data-test=recovery-dialog]").exists()).toBe(false);
expect(calls).toEqual([]);
});
});
describe("toRecoveryEntries", () => {
it("skips malformed entries", () => {
expect(
toRecoveryEntries([
ENTRIES[0],
null,
"x",
{ path: 1, savedAt: 1, diskChanged: false },
{ path: "a", savedAt: Number.NaN, diskChanged: false },
{ path: "a", savedAt: 1, diskChanged: "yes" },
]),
).toEqual([ENTRIES[0]]);
expect(toRecoveryEntries({ path: "a" })).toEqual([]);
});
});