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;