M1.13: watch open buffers' folders, bufferFocused, truncated tree row

- The parent directory of every open buffer is pinned in the project
  watcher (workspace::sync_buffer_dirs after every command): it counts
  against the cap but is never evicted while a buffer in it is open, so
  reloads and fileChangedOnDisk arrive for never-expanded folders.
- file.open on an already-open buffer emits the new bufferFocused {id};
  the editor activates that tab and it outranks pending adoptions.
- The project tree shows a "Listing truncated" note row
  (project.tree.truncated) after a partly listed directory.
- Tests: engine (pinning, eviction, focus), control channel
  (bufferFocused), Vitest (tab switch, race, truncated row).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 16:20:11 +02:00
parent 7b7273a947
commit 8a71f7bd08
19 changed files with 312 additions and 30 deletions

View file

@ -107,6 +107,9 @@ fn streams_command_and_disk_events() {
let r = client.call(execute("file.open", json!({"path": "a.php"})));
let id = r["result"]["id"].as_u64().unwrap();
assert_eq!(client.event("bufferOpened")["id"], id);
let r = client.call(execute("file.open", json!({"path": "a.php"})));
assert_eq!(r["result"]["id"], id);
assert_eq!(client.event("bufferFocused")["id"], id);
let r = client.call(execute(
"buffer.edit",

View file

@ -18,8 +18,9 @@ struct OpenParams {
path: String,
}
/// `file.open`: opens a file into a buffer, or returns the buffer that
/// already holds it.
/// `file.open`: opens a file into a buffer and emits
/// [`Event::BufferOpened`], or returns the buffer that already holds it and
/// emits [`Event::BufferFocused`] so clients switch to it.
pub struct Open;
impl Command for Open {
@ -29,7 +30,7 @@ impl Command for Open {
label: "Open File",
menu_path: None,
default_shortcut: None,
params: "{ path: string (project-relative or absolute inside the project) }; returns { id, path, text, version, dirty, lineEnding: lf|crlf|cr }",
params: "{ path: string (project-relative or absolute inside the project) }; returns { id, path, text, version, dirty, lineEnding: lf|crlf|cr }; emits bufferOpened for a new buffer, bufferFocused for one already open",
}
}
@ -42,7 +43,9 @@ impl Command for Open {
let p: OpenParams = parse(id, params)?;
let rel = project_path(state, id, &p.path)?;
if let Some(existing) = state.buffers.find(&rel) {
return describe(state, id, existing).map(Outcome::value);
let value = describe(state, id, existing)?;
state.emit(Event::BufferFocused { id: existing });
return Ok(Outcome::value(value));
}
let abs = absolute(state, id, &rel)?;
let file = lutra_vfs::read_text(&abs).map_err(vfs_error)?;

View file

@ -89,7 +89,9 @@ impl Engine {
/// event queued so far. When the command fails, events it queued before
/// failing (real changes, such as files saved before another failed) stay
/// queued and arrive with the next successful outcome or
/// [`Engine::take_events`].
/// [`Engine::take_events`]. After every command the parent directories of
/// open buffers are re-pinned in the project watcher
/// ([`crate::workspace::sync_buffer_dirs`]).
///
/// # Errors
/// [`EngineError::UnknownCommand`] for an unknown id,
@ -104,7 +106,9 @@ impl Engine {
if !command.enabled(state) {
return Err(EngineError::Disabled(id.to_string()));
}
command.run(state, params)
let outcome = command.run(state, params);
crate::workspace::sync_buffer_dirs(state);
outcome
});
state.commands_run = state.commands_run.saturating_add(1);
result.map(|mut outcome| {

View file

@ -47,6 +47,13 @@ pub enum Event {
/// File path.
path: String,
},
/// `file.open` asked for a file whose buffer was already open; clients
/// show (activate) that buffer. A new buffer gets
/// [`Event::BufferOpened`] instead.
BufferFocused {
/// Buffer id.
id: u64,
},
/// A buffer's text changed; `version` is the new version.
BufferChanged {
/// Buffer id.

View file

@ -11,8 +11,17 @@
//! interval. When the limit is reached the directory listed least recently
//! is unwatched; listing it again watches it again. Changes inside an
//! unwatched directory are not reported until then.
//!
//! The parent directory of every open buffer is pinned by
//! [`sync_buffer_dirs`]: it is watched even if no client listed it, so
//! [`Event::FileChangedOnDisk`] and reloads arrive for files in folders the
//! tree never expanded. Pinned directories count against the limit but are
//! never unwatched while a buffer in them is open, so with more pinned
//! directories than the limit allows, the watched set exceeds it. A
//! directory the watcher refuses (hidden, ignored or excluded) stays
//! unwatched even when pinned.
use std::collections::VecDeque;
use std::collections::{BTreeSet, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{Receiver, TryRecvError};
@ -42,6 +51,8 @@ pub struct Workspace {
events: Option<Receiver<VfsEvent>>,
/// Directories watched besides the root, least recently listed first.
watched: VecDeque<PathBuf>,
/// Parent directories of open buffers; never unwatched while pinned.
pinned: BTreeSet<PathBuf>,
}
impl Workspace {
@ -76,39 +87,73 @@ impl Workspace {
watcher,
events: receiver,
watched: VecDeque::new(),
pinned: BTreeSet::new(),
},
events,
))
}
/// Records that a client listed `dir` and watches it, unwatching the
/// least recently listed directory if the limit is reached. Watching is
/// best effort: a directory the watcher refuses or cannot read is simply
/// not watched, because listing it worked and that is what the caller
/// asked for.
/// least recently listed unpinned directory if the limit is reached.
/// Watching is best effort: a directory the watcher refuses or cannot
/// read is simply not watched, because listing it worked and that is
/// what the caller asked for.
pub fn touch_dir(&mut self, dir: &Path) {
let Some(watcher) = &self.watcher else {
if self.watch(dir) {
self.evict();
}
}
/// Makes `dirs` the pinned directories: each is watched and kept watched
/// until a later call leaves it out, after which it ages out like a
/// listed directory. The root (`""`) is always watched and is skipped.
pub fn pin_dirs(&mut self, dirs: BTreeSet<PathBuf>) {
if self.watcher.is_none() || dirs == self.pinned {
return;
}
for dir in &dirs {
if !self.pinned.contains(dir) {
self.watch(dir);
}
}
self.pinned = dirs;
self.evict();
}
/// Watches `dir` and moves it to the most recently used end. Returns
/// whether it is watched now.
fn watch(&mut self, dir: &Path) -> bool {
let Some(watcher) = &self.watcher else {
return false;
};
if dir.as_os_str().is_empty() {
return;
return false;
}
if let Some(at) = self.watched.iter().position(|d| d == dir) {
if let Some(d) = self.watched.remove(at) {
self.watched.push_back(d);
}
return;
return true;
}
if !matches!(watcher.watch_dir(dir), Ok(true)) {
return;
return false;
}
self.watched.push_back(dir.to_path_buf());
true
}
/// Unwatches the least recently used unpinned directories until the
/// watched set fits the limit or only pinned directories remain.
fn evict(&mut self) {
let limit = self.watch_limit();
let Some(watcher) = &self.watcher else {
return;
};
while self.watched.len() > limit {
if let Some(old) = self.watched.pop_front() {
let Some(at) = self.watched.iter().position(|d| !self.pinned.contains(d)) else {
return;
};
if let Some(old) = self.watched.remove(at) {
watcher.unwatch_dir(&old);
}
}
@ -129,6 +174,11 @@ impl Workspace {
self.watched.iter().cloned().collect()
}
/// The pinned directories (parents of open buffers), sorted.
pub fn pinned_dirs(&self) -> Vec<PathBuf> {
self.pinned.iter().cloned().collect()
}
/// Whether the project is watched.
pub fn is_watching(&self) -> bool {
self.watcher.is_some()
@ -160,11 +210,30 @@ impl Workspace {
self.watcher = None;
self.events = None;
self.watched.clear();
self.pinned.clear();
}
(out, failure)
}
}
/// Pins the parent directory of every open buffer in the workspace watcher
/// (see the module docs). The engine calls it after every command, so
/// opening, restoring and closing buffers keep the pins current.
pub fn sync_buffer_dirs(state: &mut State) {
let Some(workspace) = state.project.as_mut() else {
return;
};
let dirs: BTreeSet<PathBuf> = state
.buffers
.ids()
.into_iter()
.filter_map(|id| state.buffers.get(id))
.filter_map(|b| b.path.parent().map(Path::to_path_buf))
.filter(|d| !d.as_os_str().is_empty())
.collect();
workspace.pin_dirs(dirs);
}
/// Applies pending changes on disk to the state: queues
/// [`Event::TreeChanged`] for affected directories, reloads clean buffers
/// whose file changed, and queues [`Event::FileChangedOnDisk`] for dirty

View file

@ -403,6 +403,92 @@ fn watched_directories_are_capped_least_recently_listed_first() {
assert!(watched.iter().any(|d| d == Path::new("d0006")));
}
#[test]
fn files_in_never_listed_folders_report_changes_on_disk() {
let (dir, mut engine, _) =
open_project(&[("src/deep/clean.php", b"one"), ("lib/dirty.php", b"one")]);
let (clean, _) = open_file(&mut engine, "src/deep/clean.php");
let (dirty, _) = open_file(&mut engine, "lib/dirty.php");
let workspace = engine.state().project.as_ref().unwrap();
assert_eq!(
workspace.pinned_dirs(),
vec![
Path::new("lib").to_path_buf(),
Path::new("src/deep").to_path_buf()
]
);
run(
&mut engine,
"buffer.edit",
json!({"id": dirty, "baseVersion": 1, "edits": [{"from": 0, "to": 0, "insert": "mine "}]}),
);
fs::write(dir.path().join("src/deep/clean.php"), "two, longer").unwrap();
fs::write(dir.path().join("lib/dirty.php"), "theirs, longer").unwrap();
let mut events = wait_for(
&mut engine,
|e| matches!(e, Event::BufferChanged { id, .. } if *id == clean),
);
if !events
.iter()
.any(|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty))
{
events = wait_for(
&mut engine,
|e| matches!(e, Event::FileChangedOnDisk { id, .. } if *id == dirty),
);
}
assert!(!events.is_empty());
assert_eq!(
run(&mut engine, "buffer.get", json!({"id": clean})).value["text"],
"two, longer"
);
}
#[test]
fn parent_dirs_of_open_buffers_are_never_evicted_and_age_out_after_close() {
let (dir, mut engine, _) = open_project(&[("pinned/a.php", b"a")]);
let limit = engine.state().project.as_ref().unwrap().watch_limit();
assert!(limit > 0, "the watcher should start on a temp dir");
let (id, _) = open_file(&mut engine, "pinned/a.php");
let count = limit + 5;
for n in 0..count {
fs::create_dir(dir.path().join(format!("d{n:04}"))).unwrap();
run(
&mut engine,
"project.children",
json!({"dir": format!("d{n:04}")}),
);
}
let watched = engine.state().project.as_ref().unwrap().watched_dirs();
assert_eq!(watched.len(), limit);
assert!(watched.iter().any(|d| d == Path::new("pinned")));
assert!(!watched.iter().any(|d| d == Path::new("d0000")));
run(&mut engine, "buffer.close", json!({"id": id}));
let workspace = engine.state().project.as_ref().unwrap();
assert!(workspace.pinned_dirs().is_empty());
run(&mut engine, "project.children", json!({"dir": "d0000"}));
let watched = engine.state().project.as_ref().unwrap().watched_dirs();
assert_eq!(watched.len(), limit);
assert!(!watched.iter().any(|d| d == Path::new("pinned")));
}
#[test]
fn opening_an_open_file_again_focuses_its_buffer() {
let (_dir, mut engine, _) = open_project(&[("a.php", b"a"), ("src/b.php", b"b")]);
let first = run(&mut engine, "file.open", json!({"path": "src/b.php"}));
let id = first.value["id"].as_u64().unwrap();
assert!(first.events.contains(&Event::BufferOpened {
id,
path: "src/b.php".into()
}));
open_file(&mut engine, "a.php");
let again = run(&mut engine, "file.open", json!({"path": "src/b.php"}));
assert_eq!(again.value["id"], id);
assert_eq!(again.events, vec![Event::BufferFocused { id }]);
assert_eq!(engine.state().buffers.len(), 2);
}
/// A command that reads the state and then panics on an index.
struct PanicsMidway;

View file

@ -78,11 +78,11 @@ 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}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal). 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}`, `bufferFocused {id}` (M1.13), `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`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab.
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.
Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched.
Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. The parent directory of every open buffer is pinned (M1.13, `workspace::sync_buffer_dirs`, run by `Engine::execute` after every command): it is watched even if the tree never listed it, so reloads and `fileChangedOnDisk` arrive for files opened by path from never-expanded folders. Pinned directories count against the cap but are never evicted while a buffer in them is open (with more pinned directories than the cap, the watched set exceeds it); after the last buffer in a directory closes, it ages out like a listed one. A buffer inside an ignored or hidden directory is still not watched.
### Desktop bridge (M1.4)
@ -94,7 +94,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
### Tabs and editor (M1.6)
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it. `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them.
- One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text.
- Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table.
- Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context. Saving and closing wait until the sync has no pending edits.
@ -159,6 +159,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | M1.13: open buffers pin their parent directory in the watcher, `bufferFocused`, truncated listing row |
| 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) |

View file

@ -8,7 +8,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
|---|---|---|---|
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, autosave option | M1 | ~16 h |
| 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 |
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), error notifications for the folder picker, ~~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 |
| G6 | Language server: completion, diagnostics, definition, hover, rename via Phpactor | M3 | ~45 h |
@ -23,7 +23,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| 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. 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.
G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. Still open: tab management beyond open/close, a conflict UI (compare and merge with the disk version), autosave, editor settings (font size, soft wrap); estimate lowered to ~16 h.
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.
@ -39,6 +39,7 @@ Known smaller items from M0:
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | G2/G3: re-open focuses the tab, open buffers' folders watched, truncated listings shown (M1.13) |
| 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) |

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, M1.7 recovery journal) | ~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, M1.13 C1 follow-ups) | ~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.13 C1 follow-ups |
| 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 |

View file

@ -12,8 +12,8 @@ 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 | 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 |
| 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.13: opening a file that is already open switches to its tab (`bufferFocused`; engine test, Vitest, control-channel test; live check pending (gaming mode)); files in folders the tree never expanded still reload or report changes on disk, because the parent directory of every open buffer stays watched (engine tests). M1.7: crash-recovery journal (`crates/engine/src/journal.rs`, `cmd/recovery.rs`): dirty buffers are written atomically to `<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 | ~37 (est.) | `lutra-vfs` (M1.2): lazy sorted listing, ignore rules (.gitignore, .ignore, info/exclude, global excludes, Lutra defaults), native file watching via `notify` with a polling fallback, capped UTF-8 reads, atomic writes; 34 tests on temp dirs, watcher tests run on both backends (`crates/vfs/tests`). M1.5: project tree UI (lazy listing, keyboard navigation, dimmed ignored entries, event refresh) in `ui/src/components/project/`, Vitest against a mocked engine. M1.3: `project.open`, `project.close`, `project.children` (watches listed directories, capped at 256 native / 32 polling, least recently listed dropped), `treeChanged` events from disk, `events.subscribe` on the control channel with a TCP test (`crates/control/tests/events.rs`). M1.4: the tree runs against the engine in the app: folder picker (`project.openDialog`) and `lutra-desktop --control PORT PATH` open a project, the tree lists it lazily with ignored (`var/` from `.gitignore`) and excluded (`node_modules`) entries dimmed, a file created on disk appears in an expanded folder within ~100 ms; verified with `ui.screenshot` on Windows 11 and Vitest (`ui/tests/project/`, `ui/tests/ipcEvents.test.ts`). M1.13: a directory listed only partly (more than 100,000 entries) ends with a "Listing truncated" note row (Vitest). 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.) | — |
| Code completion | 10 | 0% | everything | ~250 (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.13: Editor core and Project view evidence (focus on re-open, watched buffer folders, truncated note), scores unchanged |
| 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 |

View file

@ -6,7 +6,7 @@
- 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).
- [ ] Project tool window (tree, scroll from source, file operations)
- M1.5 (2026-10-14): tree of the open folder with lazy `project.children` listings, folders and PHP files with Lucide icons, ignored/excluded entries dimmed, keyboard navigation (WAI-ARIA tree: arrows, Home/End, Enter), double-click opens, refresh on `TreeChanged`, listing errors shown in the tree, empty state with Open Folder…. Vitest only, against a mocked engine.
- 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`.
- 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. M1.13 (2026-10-16): a partly listed folder ends with a "Listing truncated" note; opening a file that is already open (tree, control channel) switches to its tab (Vitest; live check pending (gaming mode)). 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
@ -27,6 +27,7 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-16 | minor | Truncated listing note, re-open switches tab (M1.13) |
| 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) |

View file

@ -14,6 +14,7 @@ export type EditorEvent =
| { kind: "projectOpened" }
| { kind: "projectClosed" }
| { kind: "bufferOpened"; id: number; path: string }
| { kind: "bufferFocused"; id: number }
| { kind: "bufferChanged"; id: number; version: number }
| { kind: "dirtyChanged"; id: number; dirty: boolean }
| { kind: "bufferClosed"; id: number }
@ -41,6 +42,8 @@ export function toEditorEvent(payload: EngineEventPayload): EditorEvent | null {
return id !== null && typeof raw.path === "string"
? { kind: "bufferOpened", id, path: raw.path }
: null;
case "bufferFocused":
return id !== null ? { kind: "bufferFocused", id } : null;
case "bufferChanged": {
const version = num("version");
return id !== null && version !== null ? { kind: "bufferChanged", id, version } : null;

View file

@ -6,7 +6,8 @@
* Keys: Up/Down move the selection, Home/End jump to the first/last row,
* Right expands a folder or moves into it, Left collapses a folder or moves
* to the parent, Enter opens a file or toggles a folder. Double-click does
* the same as Enter. Ignored and excluded entries are dimmed.
* the same as Enter. Ignored and excluded entries are dimmed. A directory
* the engine listed only partly ends with a "listing truncated" note.
*/
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
@ -286,6 +287,14 @@ function onFocus(): void {
>
{{ t("project.tree.loading") }}
</div>
<div
v-else-if="row.kind === 'truncated'"
class="tree__row tree__row--note"
:style="{ '--tree-depth': row.depth }"
data-test="tree-truncated"
>
{{ t("project.tree.truncated") }}
</div>
<div
v-else
class="tree__row tree__row--note tree__row--error"

View file

@ -23,6 +23,7 @@
"project.openFolder": "Open Folder…",
"project.toolWindow.title": "Project",
"project.tree.loading": "Loading…",
"project.tree.truncated": "Listing truncated: more entries than can be shown",
"recovery.dialog.changedOnDisk": "The file changed on disk since then",
"recovery.dialog.discard": "Discard",
"recovery.dialog.failed": "{path} could not be restored: {message}",

View file

@ -21,6 +21,7 @@ export type EngineEventPayload =
| { kind: "projectClosed" }
| { kind: "treeChanged"; dir: string }
| { kind: "bufferOpened"; id: number; path: string }
| { kind: "bufferFocused"; id: number }
| { kind: "bufferChanged"; id: number; version: number }
| { kind: "dirtyChanged"; id: number; dirty: boolean }
| { kind: "bufferClosed"; id: number }

View file

@ -3,7 +3,7 @@
* dirty state, notices, and the Save / Don't save / Cancel question when a
* dirty tab closes.
*
* Fed by engine events (`bufferOpened`, `bufferChanged`, `dirtyChanged`,
* Fed by engine events (`bufferOpened`, `bufferFocused`, `bufferChanged`, `dirtyChanged`,
* `bufferClosed`, `fileChangedOnDisk`, project open/close) and by command
* results. Text lives in the engine and in one {@link BufferSync} per tab,
* kept outside reactive state. Command failures are stored and shown, never
@ -425,6 +425,18 @@ export const useEditorStore = defineStore("editor", () => {
}
}
/**
* Activates the tab of a buffer that `file.open` found already open
* (`bufferFocused`). It also outranks adoptions still fetching, so the
* most recent open wins.
*
* @param id - buffer id.
*/
function focusOpened(id: number): void {
++openSequence;
activate(id);
}
/**
* Applies one editor event.
*
@ -439,6 +451,9 @@ export const useEditorStore = defineStore("editor", () => {
case "bufferOpened":
void adoptOpened(event.id);
break;
case "bufferFocused":
focusOpened(event.id);
break;
case "bufferChanged":
syncs.get(event.id)?.notifyVersion(event.version);
break;

View file

@ -70,6 +70,14 @@ export type TreeRow =
depth: number;
/** The error to show. */
error: EngineError;
}
| {
/** Note after the entries of a listing the engine cut short. */
kind: "truncated";
/** Directory whose listing is incomplete. */
dir: string;
/** Nesting depth of the note. */
depth: number;
};
/**
@ -300,7 +308,7 @@ export const useProjectStore = defineStore("project", () => {
/**
* The tree flattened into visible rows: entries of the root and of every
* expanded directory, with a loading or error row where a listing is
* pending or failed.
* pending or failed, and a truncated row after an incomplete listing.
*/
const rows = computed<TreeRow[]>(() => {
const out: TreeRow[] = [];
@ -325,6 +333,9 @@ export const useProjectStore = defineStore("project", () => {
visit(entry.path, depth + 1);
}
}
if (state.truncated) {
out.push({ kind: "truncated", dir, depth });
}
};
if (root.value !== null) {
visit("", 0);

View file

@ -399,6 +399,47 @@ describe("EditorArea", () => {
expect(area.find("[aria-selected=true]").text()).toBe("b.txt");
});
it("switches to an open tab when the engine reports bufferFocused", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await editor.openFile("b.txt");
await flushPromises();
expect(editor.activeId).toBe(2);
emitEditorEvent({ kind: "bufferFocused", id: 1 });
await flushPromises();
expect(editor.activeId).toBe(1);
expect(area.find("[aria-selected=true]").text()).toBe("a.php");
emitEditorEvent({ kind: "bufferFocused", id: 99 });
expect(editor.activeId).toBe(1);
});
it("lets bufferFocused outrank an adoption that is still fetching", async () => {
await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php");
await flushPromises();
await execute("file.open", { path: "b.txt" });
let release: () => void = () => undefined;
const fallback = invoke.getMockImplementation();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (args?.command === "buffer.get" && args.params.id === 2) {
return new Promise((resolve) => {
release = () => {
resolve(describeBuffer(2));
};
});
}
return fallback?.(cmd, args) as Promise<unknown>;
});
emitEditorEvent({ kind: "bufferOpened", id: 2, path: "b.txt" });
emitEditorEvent({ kind: "bufferFocused", id: 1 });
release();
await flushPromises();
expect(editor.tabs.map((t) => t.path).sort()).toEqual(["a.php", "b.txt"]);
expect(editor.activeId).toBe(1);
});
it("shows a notice when a dirty file changes on disk, and an open error", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);

View file

@ -1,6 +1,7 @@
/**
* Tests for the Project tool window: empty state, lazy expansion, keyboard
* navigation, refresh on `TreeChanged` and error display. The engine is
* navigation, refresh on `TreeChanged`, error display and the truncated
* listing note. The engine is
* mocked: `invoke` answers `project.children` from an in-memory folder and
* events go through the local dispatcher in `engineEvents.ts`.
*/
@ -14,6 +15,7 @@ vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { emitEngineEvent } from "../../src/components/project/engineEvents";
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
import { useProjectStore } from "../../src/stores/project";
import { t } from "../../src/i18n";
/** An entry as the engine's `project.children` returns it. */
interface EngineEntry {
@ -32,6 +34,9 @@ interface EngineEntry {
/** In-memory folder listings by directory, as `project.children` returns them. */
let folder: Record<string, EngineEntry[]>;
/** Directories whose mock listing reports `truncated: true`. */
let truncatedDirs: Set<string>;
/**
* Builds an entry.
*
@ -54,7 +59,7 @@ function engine(command: string, args: { command: string; params: { dir?: string
const dir = args.params.dir ?? "";
const entries = folder[dir];
return entries
? Promise.resolve({ dir, entries, truncated: false })
? Promise.resolve({ dir, entries, truncated: truncatedDirs.has(dir) })
: Promise.reject(Object.assign(new Error(`cannot list ${dir}`), { code: "not_found" }));
}
return Promise.resolve(null);
@ -104,6 +109,7 @@ describe("ProjectToolWindow", () => {
setActivePinia(createPinia());
invoke.mockReset();
invoke.mockImplementation(engine);
truncatedDirs = new Set();
folder = {
"": [entry("src", "dir"), entry("vendor", "dir"), entry("node_modules", "dir", true), entry("index.php", "file")],
src: [entry("src/Controller", "dir"), entry("src/App.php", "file")],
@ -233,6 +239,24 @@ describe("ProjectToolWindow", () => {
expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]);
});
it("shows a truncated note after a directory the engine listed only partly", async () => {
truncatedDirs = new Set(["src"]);
wrapper = await mountOpen();
expect(wrapper.find("[data-test=tree-truncated]").exists()).toBe(false);
await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click");
await flushPromises();
const notes = wrapper.findAll("[data-test=tree-truncated]");
expect(notes).toHaveLength(1);
expect(notes[0]?.text()).toBe(t("project.tree.truncated"));
expect(notes[0]?.attributes("role")).toBeUndefined();
const order = wrapper
.findAll("[data-test=tree-row], [data-test=tree-truncated]")
.map((row) => row.attributes("data-path") ?? "note");
expect(order).toEqual(["src", "src/Controller", "src/App.php", "note", "vendor", "node_modules", "index.php"]);
await press(wrapper, "End");
expect(selectedPath(wrapper)).toBe("index.php");
});
it("returns to the empty state on ProjectClosed and unsubscribes on unmount", async () => {
wrapper = await mountOpen();
emitEngineEvent({ kind: "projectClosed" });