feat(engine): reload external .ecproj edits into the live session (#4170)

* feat(engine): reload external .ecproj edits into the live session

Adds a project-file watcher on a worker thread (size + mtime stamps,
250 ms debounce, 1 s focused / 5 s unfocused) that wakes the UI only when
the open project's file changed. The UI applies the change on its own thread
through the existing file.revert -> replace_project path, so CLI/MCP edits
show in the running window without a restart.

Session.project_stamp is recorded on open/save so the app's own writes do
not reload themselves. A dirty session, active script or render job holds
the change and surfaces a status instead of discarding work; autosave is
paused while a change is pending.

Closes #4168

* fix(engine): close stamp races and correct reload guidance

- record the stamp only when the saved bytes are still on disk, so a
  concurrent external write is not mistaken for our own save
- read the project and its stamp as one observation when opening, retrying
  if the file changes mid-read
- install the watcher baseline with the loaded session stamp under one lock,
  and advance it only after the debounced change is published
- add tests for self-save acknowledgement, dirty guard and autosave pause
- replace the misleading Save-before-Revert status with Save a Copy guidance

Addresses CodeRabbit review on PR #4170

* fix(engine): handle unverified saves and stale reload reports

A save whose post-write byte check fails is marked unverified so the watcher
reports the first stamp of that path as an external edit instead of adopting
it as a baseline. Before reverting, compare the on-disk stamp with the
session stamp so a completed self-save does not discard undo history. Defer
reload while a script is waiting on a file dialog. Drop a failed reload
observation so it is retried only after a new stamp, not every frame.

Addresses the second CodeRabbit review on PR #4170

* fix(engine): require known stamp for reload shortcut and cache disk stamp

The stamp-matching shortcut only applies when the session stamp is known;
an unknown stamp keeps the observation pending. The on-disk stamp is read
once when a watcher observation is taken and carried through deferral,
avoiding file I/O on every frame.

Addresses the final CodeRabbit review on PR #4170

* fix(ui): keep recovery auto-saves while an external edit is pending

Auto-save writes recovery copies to their own files, never the project
file, so pausing it while a reload was pending only removed crash
recovery for unsaved local work. Keep it running, and hold it only when
the recovery target would alias the open project file.

Adds a regression proving the external project and the local recovery
copy both survive, and corrects the spec's wrong premise.

* fix(ui): check the autosave alias only on a due write; test every reload guard

Move the project-alias check into the engine write path
(autosave_tick_guarded) so it runs on the final WritePlan only when
auto-save is enabled and a write is due; idle frames do no file-system
work. Add regressions holding a pending external change for an active
script render, an open script file dialog and an active render job.

* test: add ignored measurement benches for the #4168 budgets

frame_tick_cost_of_project_reload: per-frame A/B of the UI tick with and
without tick_project_reload (p50/p95/p99/max over 100k ticks).
watcher_idle_cpu_and_reload_memory: watcher-only idle CPU (focused and
background), write->detect latency and RSS over 100 external saves.

* fix: rustfmt and strict clippy on the project reload watcher

Rewrite the watcher's recv loop as a while condition (clippy::while_let_loop)
with unchanged behaviour: a wake or a poll timeout runs one check, a dropped
Watcher (channel disconnected) ends the thread. Collapse the pending-change
if into its let chain, keep unwrap() inside test functions only, format both
files, and normalise project_reload.rs to LF like the rest of the tree.

---------

Co-authored-by: matthewdonsemail-lab <matthewdonsemail-lab@users.noreply.github.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
This commit is contained in:
Matthew Don
2026-12-02 06:55:37 +07:00
committed by GitHub
parent 242c47d226
commit a11548f909
15 changed files with 846 additions and 4 deletions
+30 -1
View File
@@ -42,7 +42,24 @@ fn demo(s: &mut Session, _: &Value) -> Result<Value> {
pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_p(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
// Read the bytes and their stamp as one observation. If another process writes the project
// while we read, retry instead of recording that later stamp as the identity of the bytes
// we loaded — otherwise the watcher would miss the external edit.
let (bytes, stamp) = {
let mut attempts = 0;
loop {
let before = s.services.stamp(path);
let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
let after = s.services.stamp(path);
if before == after {
break (bytes, after);
}
attempts += 1;
if attempts == 3 {
return Err(EngineError::Other(format!("{path} changed while opening; try again")));
}
}
};
let text = String::from_utf8(bytes).map_err(|_| EngineError::Other("not a text project file".into()))?;
// XML copies (File ▸ Save a Copy As XML…) open like the JSON project.
let text = if crate::xml_project::is_xml(&text) { crate::xml_project::from_xml(&text).map_err(EngineError::Other)? } else { text };
@@ -53,6 +70,8 @@ pub(crate) fn open(s: &mut Session, p: &Value) -> Result<Value> {
// relative to the project (#652).
let refused = crate::doc_path::resolve_footage(&mut proj, Some(path));
s.replace_project(proj, Some(path.to_string()));
// The stamp belongs to the bytes just read, not to whatever the file holds now.
s.project_stamp = stamp;
s.stored_paths.add(&s.project, Some(path));
s.restore_view(&effectcraft_project::saved_view(&text));
s.note_project_path(path);
@@ -96,6 +115,16 @@ fn save_to(s: &mut Session, path: &str) -> Result<Value> {
let json = file_text(s, path)?;
s.services.write_file(path, json.as_bytes()).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
s.path = Some(path.to_string());
// Only trust the stamp if the file still holds exactly what we wrote. If another process
// wrote it between our write and this check, leave the stamp unset: the watcher must treat
// that newer file as an external edit, not as our already-loaded save.
let stamp = s.services.stamp(path);
let ours = stamp.is_some_and(|(len, _)| len as usize == json.len())
&& s.services.read_file(path).map(|bytes| bytes.as_slice() == json.as_bytes()).unwrap_or(false);
s.project_stamp = ours.then_some(stamp).flatten();
// An unverified write never becomes a baseline. The watcher will report the first stamp it
// sees for this path as an external edit, so a later Save cannot silently overwrite it.
s.project_stamp_unverified = !ours;
s.mark_saved();
s.note_project_path(path);
s.toast(format!("Saved {path}"));
+9
View File
@@ -20,6 +20,7 @@ mod interchange;
pub mod menus;
mod output_guard;
pub mod preview;
pub mod project_reload;
pub mod render_queue;
pub mod replay;
pub mod scriptui;
@@ -120,6 +121,12 @@ pub struct Session {
/// snapshot, so undoing back to the saved state clears the modified mark.
pub saved_project: Arc<Project>,
pub path: Option<String>,
/// Size + mtime of `path` as last opened/saved by this session. The project watcher uses it
/// to tell its own writes from an external edit.
pub project_stamp: Option<(u64, u128)>,
/// A save whose post-write check failed: the first observation of this path must be reported
/// as an external change, never adopted as the baseline.
pub project_stamp_unverified: bool,
pub state: EditorState,
pub services: Arc<dyn Services>,
pub footage: Arc<dyn FootageSource>,
@@ -351,6 +358,8 @@ impl Default for Session {
ime_revision: commands::text_edit::next_ime_revision().unwrap_or(u64::MAX),
saved_revision: 0,
path: None,
project_stamp: None,
project_stamp_unverified: false,
state: EditorState { snapping: true, view_layout: 1, ..Default::default() },
services: Arc::new(FsServices),
footage: Arc::new(NoFootage),
+373
View File
@@ -0,0 +1,373 @@
//! Project file that changes on disk while the app is open: reload it into the live session
//! instead of asking for a restart.
//!
//! `Session` keeps the open project in an `Arc<Project>` in memory; only `file.open` / `file.revert`
//! read the file. The desktop app has no watcher on the project itself (the footage and LUT
//! watchers watch their own files), so an edit made by `effectcraft-cli` or an agent was invisible
//! until the window was reopened. [`Watcher`] stamps the project path on a worker thread and
//! wakes the interface once a change has stayed stable long enough to be a complete write.
//! It never reads or parses the project; the interface calls `file.revert`, which reuses the
//! ordinary open path and `replace_project`.
use crate::Services;
use std::sync::mpsc::{RecvTimeoutError, SyncSender, sync_channel};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
/// A project file's size and modification time, as reported by [`Services::stamp`].
pub type Stamp = (u64, u128);
/// How often the project file is stamped while the window is in front.
pub const FOCUSED_INTERVAL: Duration = Duration::from_secs(1);
/// How often while another app has the front.
pub const UNFOCUSED_INTERVAL: Duration = Duration::from_secs(5);
/// A write is atomic (temp file + rename) and may happen in more than one step: require the new
/// stamp to survive this long before reporting it.
pub const DEBOUNCE: Duration = Duration::from_millis(250);
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Default)]
struct State {
path: Option<String>,
stamp: Option<Stamp>,
unverified: bool,
focused: bool,
}
/// The worker that stamps one project file. Dropping the watcher ends the thread.
pub struct Watcher {
_stop: SyncSender<()>,
state: Arc<Mutex<State>>,
result: Arc<Mutex<Option<(String, Stamp)>>>,
}
impl Watcher {
/// Start the worker. `wake` runs on the worker when a change was seen. `None` where there are
/// no threads (the web build) or a thread could not be started.
pub fn start(services: Arc<dyn Services>, wake: impl Fn() + Send + 'static) -> Option<Watcher> {
if cfg!(target_arch = "wasm32") {
return None;
}
let (tx, rx) = sync_channel::<()>(1);
let state = Arc::new(Mutex::new(State { focused: true, ..Default::default() }));
let result = Arc::new(Mutex::new(None));
let st = Arc::clone(&state);
let res = Arc::clone(&result);
std::thread::Builder::new()
.name("project-watch".into())
.spawn(move || {
let mut interval = FOCUSED_INTERVAL;
// A wake (`Ok`) or the poll interval (`Timeout`) runs one check; a dropped
// `Watcher` (`Disconnected`) ends the thread.
while !matches!(rx.recv_timeout(interval), Err(RecvTimeoutError::Disconnected)) {
let (path, focused) = {
let s = lock(&st);
(s.path.clone(), s.focused)
};
interval = if focused { FOCUSED_INTERVAL } else { UNFOCUSED_INTERVAL };
let Some(path) = path else { continue };
let now = services.stamp(&path);
{
let mut s = lock(&st);
if s.path.as_ref() != Some(&path) {
continue;
}
match (s.stamp, now) {
// The first sighting is normally only a baseline. A save whose
// post-write check failed is different: the file on disk is not known
// to be ours, so the first stamp must reach the pending-change path.
(None, Some(stamp)) => {
s.stamp = Some(stamp);
if s.unverified {
s.unverified = false;
drop(s);
*lock(&res) = Some((path.clone(), stamp));
wake();
}
}
(Some(old), Some(new)) if old != new => {
drop(s);
std::thread::sleep(DEBOUNCE);
if services.stamp(&path) == Some(new) {
// Publish the stamp together with the report. Keep the old
// baseline while debouncing: a failed check or a stamp that
// changed back must not swallow the original change.
let mut s = lock(&st);
if s.path.as_ref() == Some(&path) {
s.stamp = Some(new);
}
drop(s);
*lock(&res) = Some((path.clone(), new));
wake();
}
}
// A missing or unreadable file leaves the baseline alone.
_ => {}
}
}
}
})
.ok()?;
Some(Watcher { _stop: tx, state, result })
}
/// Watch this project path with the stamp of the bytes the session loaded. Installing both
/// under one lock closes the gap between opening a file and the worker's first observation.
/// A new path starts a new baseline; an unchanged path keeps its baseline so external changes
/// stay detectable.
pub fn set_watched(&mut self, path: Option<String>, stamp: Option<Stamp>, unverified: bool) {
let mut s = lock(&self.state);
if s.path == path {
return;
}
s.path = path;
s.stamp = stamp;
s.unverified = unverified;
drop(s);
let _ = self._stop.try_send(());
}
/// Whether the window is in front; coming back to the front stamps at once.
pub fn set_focused(&mut self, focused: bool) {
let mut s = lock(&self.state);
if s.focused == focused {
return;
}
s.focused = focused;
drop(s);
let _ = self._stop.try_send(());
}
/// The baseline the worker is comparing against (tests and diagnostics).
pub fn baseline(&self) -> Option<Stamp> {
lock(&self.state).stamp
}
/// The change found by the worker, once. The interface decides whether to reload it.
pub fn take(&self) -> Option<(String, Stamp)> {
lock(&self.result).take()
}
/// Record the stamp the session itself just wrote (open/save/reload) so it is not reported
/// back as an external change.
pub fn acknowledge(&self, stamp: Option<Stamp>) {
let mut s = lock(&self.state);
s.stamp = stamp;
s.unverified = false;
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Disk {
stamps: Mutex<std::collections::HashMap<String, Stamp>>,
looks: AtomicUsize,
}
impl Services for Disk {
fn read_file(&self, _: &str) -> std::io::Result<Vec<u8>> {
Err(std::io::Error::new(std::io::ErrorKind::NotFound, "read-only test disk"))
}
fn write_file(&self, _: &str, _: &[u8]) -> std::io::Result<()> {
Err(std::io::Error::other("read-only test disk"))
}
fn is_dir(&self, _: &str) -> bool {
false
}
fn stamp(&self, path: &str) -> Option<Stamp> {
self.looks.fetch_add(1, Ordering::SeqCst);
lock(&self.stamps).get(path).copied()
}
}
fn disk(stamp: Stamp) -> (Arc<Disk>, String) {
let d = Arc::new(Disk { stamps: Mutex::new(Default::default()), looks: AtomicUsize::new(0) });
let path = "C:/test/project.ecproj".to_string();
lock(&d.stamps).insert(path.clone(), stamp);
(d, path)
}
fn start(d: Arc<Disk>, wakes: Arc<AtomicUsize>) -> Option<Watcher> {
Watcher::start(d, move || {
wakes.fetch_add(1, Ordering::SeqCst);
})
}
fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {
let t0 = std::time::Instant::now();
while !ready() {
assert!(t0.elapsed() < Duration::from_secs(10), "timed out: {what}");
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn the_first_sighting_only_sets_the_baseline() {
let (d, path) = disk((100, 1));
let wakes = Arc::new(AtomicUsize::new(0));
let mut w = start(d, Arc::clone(&wakes)).unwrap();
w.set_watched(Some(path), None, false);
wait_for("first baseline", || w.baseline().is_some());
std::thread::sleep(Duration::from_millis(200));
assert!(w.take().is_none(), "first sight must not be reported as an edit");
assert_eq!(wakes.load(Ordering::SeqCst), 0);
}
#[test]
fn an_unverified_path_reports_its_first_stamp() {
let (d, path) = disk((100, 1));
let wakes = Arc::new(AtomicUsize::new(0));
let mut w = start(d, Arc::clone(&wakes)).unwrap();
w.set_watched(Some(path.clone()), None, true);
wait_for("wake", || wakes.load(Ordering::SeqCst) >= 1);
assert_eq!(w.take(), Some((path, (100, 1))));
}
#[test]
fn an_external_write_wakes_and_reports_the_new_stamp() {
let (d, path) = disk((100, 1));
let wakes = Arc::new(AtomicUsize::new(0));
let mut w = start(d.clone(), Arc::clone(&wakes)).unwrap();
// The session's loaded stamp is installed synchronously with the path.
w.set_watched(Some(path.clone()), Some((100, 1)), false);
assert_eq!(w.baseline(), Some((100, 1)));
// Simulate an atomic save: a new size and mtime.
lock(&d.stamps).insert(path.clone(), (120, 2));
wait_for("wake", || wakes.load(Ordering::SeqCst) >= 1);
assert_eq!(w.take(), Some((path, (120, 2))));
}
#[test]
fn acknowledging_a_reported_change_does_not_report_it_again() {
let (d, path) = disk((100, 1));
let wakes = Arc::new(AtomicUsize::new(0));
let mut w = start(d.clone(), Arc::clone(&wakes)).unwrap();
w.set_watched(Some(path.clone()), Some((100, 1)), false);
assert_eq!(w.baseline(), Some((100, 1)));
lock(&d.stamps).insert(path.clone(), (120, 2));
wait_for("wake", || wakes.load(Ordering::SeqCst) >= 1);
assert_eq!(w.take(), Some((path.clone(), (120, 2))));
// The UI reloaded (or decided it was its own write) and tells the watcher the stamp it
// now considers current. The same change must not be reported a second time.
w.acknowledge(Some((120, 2)));
std::thread::sleep(Duration::from_millis(300));
assert!(w.take().is_none());
assert_eq!(wakes.load(Ordering::SeqCst), 1);
}
}
/// Watcher cost measurements for #4168's budgets (watcher-only idle CPU, watcher-attributable
/// memory after 100 reloads). Ignored by default; run with
/// `cargo test -p effectcraft-engine --lib project_reload::bench -- --ignored --nocapture --test-threads=1`.
#[cfg(all(test, windows))]
mod bench {
use super::*;
use std::time::Instant;
/// (process CPU seconds, working set bytes) for this test process, read by an external
/// `Get-Process` so the reading itself costs this process nothing.
fn sample() -> Option<(f64, usize)> {
let pid = std::process::id();
let out = std::process::Command::new("powershell")
.args(["-NoProfile", "-Command", &format!("$p=Get-Process -Id {pid}; \"$($p.TotalProcessorTime.TotalSeconds) $($p.WorkingSet64)\"")])
.output()
.ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let mut it = text.split_whitespace();
Some((it.next()?.replace(',', ".").parse().ok()?, it.next()?.parse().ok()?))
}
fn cpu() -> Option<f64> {
Some(sample()?.0)
}
fn rss() -> Option<usize> {
Some(sample()?.1)
}
fn idle_cpu_pct(secs: u64) -> Option<f64> {
let c0 = cpu()?;
std::thread::sleep(Duration::from_secs(secs));
Some((cpu()? - c0) / secs as f64 * 100.0)
}
fn mb(b: usize) -> f64 {
b as f64 / 1_048_576.0
}
#[test]
#[ignore = "measurement, ~3.5 min"]
fn watcher_idle_cpu_and_reload_memory() {
let dir = std::env::temp_dir().join(format!("ec-watch-bench-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("Bench.ecproj");
std::fs::write(&file, b"{}").unwrap();
let path = file.to_string_lossy().into_owned();
let services = crate::Session::default().services.clone();
let secs = 60;
let without = idle_cpu_pct(secs).unwrap();
let wakes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let w2 = Arc::clone(&wakes);
let mut w = Watcher::start(services.clone(), move || {
w2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
})
.unwrap();
w.set_focused(true);
w.set_watched(Some(path.clone()), services.stamp(&path), false);
let focused = idle_cpu_pct(secs).unwrap();
w.set_focused(false);
let background = idle_cpu_pct(secs).unwrap();
println!(
"BENCH idle CPU over {secs}s each: no watcher {without:.4}% | watcher focused (1 s poll) {focused:.4}% | watcher background (5 s poll) {background:.4}%"
);
println!("BENCH watcher-only CPU: focused {:.4}% | background {:.4}%", focused - without, background - without);
// 100 external writes, each detected and acknowledged as the UI does.
w.set_focused(true);
let rss0 = rss().unwrap();
let mut detect = Vec::with_capacity(100);
for i in 0..100u32 {
let body = format!("{{\"n\":{i},\"pad\":\"{}\"}}", "x".repeat(i as usize));
let t0 = Instant::now();
std::fs::write(&file, body).unwrap();
loop {
if let Some((_, stamp)) = w.take() {
w.acknowledge(Some(stamp));
break;
}
assert!(t0.elapsed() < Duration::from_secs(10), "change {i} not detected");
std::thread::sleep(Duration::from_millis(2));
}
detect.push(t0.elapsed().as_secs_f64() * 1000.0);
}
let rss1 = rss().unwrap();
std::thread::sleep(Duration::from_secs(30));
let rss2 = rss().unwrap();
detect.sort_by(f64::total_cmp);
let p = |q: f64| detect[((detect.len() as f64 * q).ceil() as usize).saturating_sub(1)];
println!(
"BENCH detect latency (write -> take, focused, 100 writes): p50 {:.0} ms | p95 {:.0} ms | p99 {:.0} ms | max {:.0} ms",
p(0.5),
p(0.95),
p(0.99),
p(1.0)
);
println!(
"BENCH RSS: before {:.2} MB | after 100 reloads {:.2} MB ({:+.2} MB) | after 30 s idle {:.2} MB ({:+.2} MB)",
mb(rss0),
mb(rss1),
mb(rss1) - mb(rss0),
mb(rss2),
mb(rss2) - mb(rss0)
);
drop(w);
let _ = std::fs::remove_dir_all(dir);
}
}
+6
View File
@@ -254,6 +254,12 @@ pub struct RenderJob {
}
impl RenderJob {
/// A job record with no local thread or worker, sharing `shared`: lets a host (or a test
/// built without an exporter) hold an active job without rendering.
pub fn detached(shared: Arc<JobShared>) -> Self {
Self { shared, thread: None, remote: None }
}
pub fn is_finished(&self) -> bool {
lock(&self.shared.state).finished
}
+4
View File
@@ -239,6 +239,10 @@ impl Session {
self.history = History::default();
self.state = EditorState { snapping: true, view_layout: 1, ..Default::default() };
self.path = path;
// The stamp is installed by the caller that actually read the file (file.open), from
// the stamp observed with those bytes. New/demo projects have no file stamp.
self.project_stamp = None;
self.project_stamp_unverified = false;
self.bump();
self.mark_saved();
// (channel selection can't be animated, as in After Effects: a document that animated it
+12
View File
@@ -115,6 +115,18 @@ pub fn folder(prefs: &Prefs, project: Option<&str>, fallback: Option<&Path>) ->
}
}
/// Whether two paths name the same file. Canonicalises when the file exists and compares
/// case-insensitively with either slash on Windows; a missing file compares as written.
pub fn paths_alias(a: &Path, b: &Path) -> bool {
fn norm(p: &Path) -> String {
let p = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
let s = p.to_string_lossy().replace('\\', "/");
let s = s.strip_prefix("//?/").map(str::to_string).unwrap_or(s);
if cfg!(windows) { s.to_lowercase() } else { s }
}
norm(a) == norm(b)
}
/// Existing auto-saves of `stem` in `dir`: (slot, path, modified).
pub fn existing(dir: &Path, stem: &str) -> Vec<(u32, PathBuf, std::time::SystemTime)> {
existing_in(&StdFiles, dir, stem)
+24 -2
View File
@@ -360,12 +360,22 @@ impl Session {
/// background thread (the path is returned at once; [`Session::autosave_wait`] waits).
/// Auto-saves are compact JSON (opened like any project); File ▸ Save writes pretty JSON.
pub fn autosave_now(&mut self) -> Result<String> {
self.autosave_write(false)?.ok_or_else(|| EngineError::Other("auto-save skipped".into()))
}
/// [`Session::autosave_now`]; with `guard_project`, a planned target that aliases the open
/// project file is skipped (`Ok(None)`) instead of written, so recovery never overwrites
/// it. The check runs on the final [`autosave::WritePlan`], only when a write is due.
fn autosave_write(&mut self, guard_project: bool) -> Result<Option<String>> {
// One write at a time: the previous one must land before its slot rotates.
self.autosave_wait()?;
let root = self.default_autosave_root();
let prefs = self.autosave_prefs();
let fail = |e: std::io::Error| EngineError::Other(format!("auto-save failed: {e}"));
let plan = autosave::plan_in(self.file_ops(), &prefs, self.path.as_deref(), root.as_deref(), self.autosave.last_slot).map_err(fail)?;
if guard_project && self.path.as_deref().is_some_and(|p| autosave::paths_alias(&plan.path, Path::new(p))) {
return Ok(None);
}
let path = plan.path.to_string_lossy().into_owned();
if self.autosave.background && !cfg!(target_arch = "wasm32") {
let project = self.project.clone();
@@ -386,7 +396,7 @@ impl Session {
plan.write(self.file_ops(), json.as_bytes()).map_err(fail)?;
self.commit_autosave(path.clone(), plan.slot, self.revision);
}
Ok(path)
Ok(Some(path))
}
/// Advance recovery bookkeeping only for a successfully written snapshot.
@@ -417,6 +427,14 @@ impl Session {
/// Call periodically with wall-clock seconds: auto-saves a dirty project once the interval
/// has passed since the last auto-save (or since the first call). Returns the written path.
pub fn autosave_tick(&mut self, now: f64) -> Option<Result<String>> {
self.autosave_tick_guarded(now, false)
}
/// [`Session::autosave_tick`]; with `guard_project` a due write whose planned target aliases
/// the open project file is skipped. The desktop app sets it while an external edit of the
/// project is pending: recovery copies keep being written, the project file never is. No
/// file-system check runs unless auto-save is enabled and a write is actually due.
pub fn autosave_tick_guarded(&mut self, now: f64, guard_project: bool) -> Option<Result<String>> {
if self.autosave.pending.as_ref().is_some_and(autosave::PendingWrite::is_finished)
&& let Err(e) = self.autosave_wait()
{
@@ -440,7 +458,11 @@ impl Session {
{
return None;
}
let r = self.autosave_now();
let r = match self.autosave_write(guard_project) {
Ok(Some(p)) => Ok(p),
Ok(None) => return None,
Err(e) => Err(e),
};
if let Ok(p) = &r {
self.toast(format!("Auto-saved {}", Path::new(p).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()));
}
+16
View File
@@ -1167,6 +1167,22 @@ fn autosave_tick_waits_for_the_interval_and_changes() {
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn autosave_paths_alias_only_the_same_file() {
let d = tmp("alias");
let project = d.join("Live.ecproj");
std::fs::write(&project, b"{}").unwrap();
assert!(autosave::paths_alias(&project, &project));
assert!(autosave::paths_alias(&project, &d.join(".").join("Live.ecproj")), "a dotted path names the same file");
if cfg!(windows) {
let shouty = std::path::PathBuf::from(project.to_string_lossy().to_uppercase().replace('\\', "/"));
assert!(autosave::paths_alias(&project, &shouty), "case and slash style do not matter on Windows");
}
let recovery = d.join(autosave::AUTOSAVE_FOLDER).join(autosave::file_name("Live", 1));
assert!(!autosave::paths_alias(&project, &recovery), "a recovery copy is a different file");
let _ = std::fs::remove_dir_all(d);
}
#[test]
fn crash_recovery_detects_an_unclean_exit() {
let d = tmp("recovery");
+2
View File
@@ -107,6 +107,8 @@ impl EffectcraftApp {
gpu_failure_applied: None,
footage_watcher: None,
footage_watch_key: None,
project_watcher: None,
project_reload_pending: None,
lut_watcher: None,
lut_generation: effectcraft_engine::lut_reload::generation(),
purges: 0,
+236 -1
View File
@@ -699,7 +699,12 @@ impl EffectcraftApp {
fn tick_autosave(&mut self, ctx: &egui::Context) {
// Monotonic app time: a wall-clock jump must not skip or repeat an auto-save.
let now = self.now;
if let Some(Err(e)) = self.session.autosave_tick(now) {
// Auto-saves are recovery copies at their own path, so they keep running while an
// external edit is pending: a crash then still has the local work. The guard skips only
// a due write whose planned target would be the project file itself; the engine checks
// that on the final write plan, so idle ticks do no file-system work.
let guard = self.project_reload_pending.is_some();
if let Some(Err(e)) = self.session.autosave_tick_guarded(now, guard) {
self.ui.status = e.to_string();
}
if self.session.prefs.auto_save.enabled {
@@ -723,6 +728,7 @@ impl EffectcraftApp {
ctx.request_repaint_after(std::time::Duration::from_secs(10));
}
self.tick_footage_reload(ctx);
self.tick_project_reload(ctx);
self.tick_lut_files(ctx);
}
@@ -774,6 +780,68 @@ impl EffectcraftApp {
watcher.update(&self.session);
}
}
/// The open project's file changed outside this process. Reload it into the same session
/// when it is safe, so an agent's CLI/MCP edits show without a restart. The watcher only
/// stamps the file; `file.revert` reuses the ordinary open path and `replace_project`.
fn tick_project_reload(&mut self, ctx: &egui::Context) {
use effectcraft_engine::project_reload;
if self.project_watcher.is_none() {
let wake = ctx.clone();
self.project_watcher = project_reload::Watcher::start(self.session.services.clone(), move || wake.request_repaint());
}
let Some(watcher) = self.project_watcher.as_mut() else { return };
watcher.set_focused(self.focused);
watcher.set_watched(self.session.path.clone(), self.session.project_stamp, self.session.project_stamp_unverified);
if self.project_reload_pending.is_none()
&& let Some(change) = watcher.take()
&& Some(&change.0) == self.session.path.as_ref()
{
// Read the disk stamp once for this observation and keep it through deferral,
// instead of doing file I/O on every frame while a change is held.
let disk = self.session.services.stamp(&change.0);
self.project_reload_pending = Some((change.0, change.1, disk));
}
let Some((path, stamp, disk_stamp)) = self.project_reload_pending.clone() else { return };
if Some(&path) != self.session.path.as_ref() {
self.project_reload_pending = None;
return;
}
if self.session.project_stamp == Some(stamp) {
// A write we made ourselves is already in memory; don't reload it back.
watcher.acknowledge(Some(stamp));
self.project_reload_pending = None;
return;
}
if let Some(known) = self.session.project_stamp
&& disk_stamp == Some(known)
{
watcher.acknowledge(self.session.project_stamp);
self.project_reload_pending = None;
return;
}
if self.session.is_dirty()
|| self.session.script_ui.render_host.is_some()
|| !self.session.script_ui.file_dialogs.is_empty()
|| self.session.render_job.is_some()
{
self.ui.status = "Project changed on disk. To keep your changes, use File ▸ Save As ▸ Save a Copy... Then File ▸ Revert loads the disk version; Revert discards unsaved changes.".into();
return;
}
match self.session.execute("file.revert", serde_json::json!({})) {
Ok(_) => {
self.ui.status = format!("Reloaded {path} changed on disk");
watcher.acknowledge(self.session.project_stamp);
self.project_reload_pending = None;
}
Err(e) => {
// Keep the failure visible but drop this observation: retry only when the worker
// reports a new stamp, not every frame while the file stays malformed.
self.ui.status = e.to_string();
self.project_reload_pending = None;
}
}
}
}
#[cfg(test)]
@@ -1032,4 +1100,171 @@ mod tests {
ctx.run_ui(egui::RawInput::default(), |ui| app.draw_toast(ui, ui.max_rect(), 0.0)).textures_delta.clear();
assert!(app.auto.elements.iter().any(|e| e.id == "toast" && e.label.contains("Failed second file")), "{:?}", app.auto.elements);
}
#[test]
fn a_pending_change_equal_to_the_session_stamp_is_acknowledged() {
let path = "C:/test/project.ecproj".to_string();
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.path = Some(path.clone());
app.session.project_stamp = Some((100, 1));
// The stamp the watcher found is the one this session already holds (its own save).
app.project_reload_pending = Some((path, (100, 1), Some((100, 1))));
let ctx = egui::Context::default();
let before = app.session.revision;
app.tick_project_reload(&ctx);
assert_eq!(app.session.revision, before, "an own save must not be reloaded");
assert!(app.project_reload_pending.is_none());
}
#[test]
fn an_external_change_is_held_while_the_session_is_dirty() {
let path = "C:/test/project.ecproj".to_string();
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.path = Some(path.clone());
app.session.project_stamp = Some((100, 1));
app.session.execute("comp.new", json!({"name":"Gui"})).unwrap();
assert!(app.session.is_dirty());
app.project_reload_pending = Some((path, (120, 2), None));
let ctx = egui::Context::default();
app.tick_project_reload(&ctx);
assert!(app.project_reload_pending.is_some(), "the change must be held, not discarded");
assert!(app.ui.status.contains("Save a Copy"), "{}", app.ui.status);
assert!(app.ui.status.contains("discards unsaved changes"), "{}", app.ui.status);
}
/// A clean session with a pending external change at a stamp the session does not hold.
fn clean_app_with_a_pending_change() -> (EffectcraftApp, u64) {
let path = "C:/test/project.ecproj".to_string();
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.path = Some(path.clone());
app.session.project_stamp = Some((100, 1));
app.project_reload_pending = Some((path, (120, 2), None));
assert!(!app.session.is_dirty(), "the guard under test must be the only reason to hold");
let revision = app.session.revision;
(app, revision)
}
fn assert_change_held(app: &EffectcraftApp, revision: u64) {
assert_eq!(app.session.revision, revision, "the project was not replaced");
assert!(app.project_reload_pending.is_some(), "the change must be held, not discarded");
assert!(app.ui.status.contains("Save a Copy"), "{}", app.ui.status);
}
#[test]
fn an_external_change_is_held_while_a_script_renders() {
let (mut app, revision) = clean_app_with_a_pending_change();
app.session.script_ui.render_host = Some(1);
app.tick_project_reload(&egui::Context::default());
assert_change_held(&app, revision);
}
#[test]
fn an_external_change_is_held_while_a_script_file_dialog_is_open() {
use effectcraft_engine::scriptui::{FileDialogKind, ScriptFileDialog};
let (mut app, revision) = clean_app_with_a_pending_change();
app.session.script_ui.file_dialogs.push(ScriptFileDialog {
id: 1,
host: 1,
kind: FileDialogKind::Open,
prompt: String::new(),
exts: vec![],
label: String::new(),
any: true,
many: false,
start: String::new(),
shown: false,
});
app.tick_project_reload(&egui::Context::default());
assert_change_held(&app, revision);
}
#[test]
fn an_external_change_is_held_while_a_render_job_is_active() {
let (mut app, revision) = clean_app_with_a_pending_change();
app.session.render_job = Some(effectcraft_engine::render_queue::RenderJob::detached(std::sync::Arc::default()));
app.tick_project_reload(&egui::Context::default());
assert_change_held(&app, revision);
}
/// Per-frame cost the reload feature adds to the UI tick (#4168 frame-p95 budget). A/B in one
/// binary: "before" runs only `tick_autosave` (what main runs; with no pending change the
/// guarded tick is the same call), "after" adds `tick_project_reload`. Run with
/// `cargo test -p effectcraft-ui-egui --lib frame_tick_cost -- --ignored --nocapture`.
#[test]
#[ignore = "measurement"]
fn frame_tick_cost_of_project_reload() {
fn pct(v: &mut [f64], q: f64) -> f64 {
v.sort_by(f64::total_cmp);
v[((v.len() as f64 * q).ceil() as usize).saturating_sub(1)]
}
fn report(label: &str, v: &mut [f64]) {
let (p50, p95, p99, max) = (pct(v, 0.5), pct(v, 0.95), pct(v, 0.99), pct(v, 1.0));
println!("BENCH {label}: p50 {p50:.2} µs | p95 {p95:.2} µs | p99 {p99:.2} µs | max {max:.1} µs");
}
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("Bench.ecproj").to_string_lossy().into_owned();
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.execute("comp.new", json!({"name": "Main"})).unwrap();
app.session.execute("file.saveAs", json!({"path": path})).unwrap();
app.session.execute("prefs.set", json!({"values": {"autoSave.enabled": true, "autoSave.intervalMinutes": 60}})).unwrap();
app.focused = true;
let ctx = egui::Context::default();
let n = 100_000;
let time = |app: &mut EffectcraftApp, reload: bool| -> Vec<f64> {
(0..n)
.map(|_| {
let t = std::time::Instant::now();
if reload {
app.tick_project_reload(&ctx);
}
app.tick_autosave(&ctx);
t.elapsed().as_secs_f64() * 1e6
})
.collect()
};
app.tick_project_reload(&ctx); // start the watcher outside the timed loop
report("before (autosave tick only), idle", &mut time(&mut app, false));
report("after (reload + autosave tick), idle", &mut time(&mut app, true));
// Held change: dirty session, pending external edit at a cached disk stamp.
app.session.execute("layer.newNull", json!({"name": "local"})).unwrap();
app.project_reload_pending = Some((path.clone(), (1, 1), Some((1, 1))));
report("after, change held while dirty", &mut time(&mut app, true));
assert!(app.project_reload_pending.is_some());
}
#[test]
fn recovery_autosave_keeps_running_while_a_project_change_is_pending() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("Live.ecproj");
let path = project.to_string_lossy().into_owned();
let mut app = EffectcraftApp::new(effectcraft_engine::Session::default());
app.session.execute("comp.new", serde_json::json!({"name": "Main"})).unwrap();
app.session.execute("file.saveAs", serde_json::json!({"path": path})).unwrap();
// Another process saves the project with its own edit.
let mut other = effectcraft_engine::Session::default();
other.execute("file.open", serde_json::json!({"path": path})).unwrap();
other.execute("layer.newNull", serde_json::json!({"name": "external edit"})).unwrap();
other.execute("file.save", serde_json::json!({})).unwrap();
let external = std::fs::read(&project).unwrap();
// The desktop session has unsaved work, so the external change is held.
app.session.execute("layer.newNull", serde_json::json!({"name": "local edit"})).unwrap();
app.project_reload_pending = Some((path.clone(), (external.len() as u64, 1), None));
app.session.execute("prefs.set", serde_json::json!({"values": {"autoSave.enabled": true, "autoSave.intervalMinutes": 1}})).unwrap();
let ctx = egui::Context::default();
app.now = 1000.0;
app.tick_autosave(&ctx);
app.now = 1061.0;
app.tick_autosave(&ctx);
app.session.autosave_wait().unwrap();
assert!(app.project_reload_pending.is_some(), "the external change is still held");
assert_eq!(std::fs::read(&project).unwrap(), external, "the external project must survive untouched");
let recovery = dir.path().join(effectcraft_engine::autosave::AUTOSAVE_FOLDER).join("Live auto-save 1.ecproj");
let saved = std::fs::read_to_string(&recovery).expect("the local work has a recovery copy");
assert!(saved.contains("local edit"), "the recovery copy holds the unsaved local work");
assert!(!saved.contains("external edit"), "the recovery copy is the local session, not the disk file");
}
}
+4
View File
@@ -458,6 +458,10 @@ pub struct EffectcraftApp {
footage_watcher: Option<effectcraft_engine::footage_reload::Watcher>,
/// The project revision and preference the watched set was last computed for.
footage_watch_key: Option<(u64, String, bool)>,
/// The worker that stamps the open project file ([`Self::tick_project_reload`]).
project_watcher: Option<effectcraft_engine::project_reload::Watcher>,
/// An external project change held until the session is clean and idle.
project_reload_pending: Option<(String, effectcraft_engine::project_reload::Stamp, Option<effectcraft_engine::project_reload::Stamp>)>,
/// The worker that stamps the LUT files in use ([`Self::tick_lut_files`], #3493).
lut_watcher: Option<effectcraft_engine::lut_reload::Watcher>,
/// The LUT generation the frames kept were rendered at ([`effectcraft_engine::lut_reload::generation`]).
+6
View File
@@ -14,6 +14,12 @@ limits. This guard does not change ordinary-file overwrite defaults or add anoth
| **CLI** (`effectcraft-cli exec/get/set/...`) | one-shot scripting and CI; JSON output with `--json` | no |
| **Control channel** (`effectcraft --control 9877`) | driving and seeing the live UI; see [control-protocol.md](control-protocol.md) | yes |
While the desktop app is open, a `.ecproj` saved by another process (CLI, headless MCP, an editor)
is detected by the project watcher (1 s while the window is in front, 5 s otherwise) and reloaded
into the running session once it is clean and idle. Unsaved GUI work is never discarded: the change
is held and the status line asks for File ▸ Revert. Prefer `--bridge` for agent edits so they apply
directly to the live session instead of going through a file round-trip.
## MCP setup
Build once with `cargo build --release -p effectcraft-cli`, then register the server. For Claude
+3
View File
@@ -26,6 +26,9 @@ someone closes that box.
yet are retried for a few frames. A request times out after 60 s; one that hasn't begun by then
is not run. Requests run until a tenth of a second has passed in one frame, and the rest wait
for the next frames in their order, so the window keeps drawing.
- Commands edit the running session's in-memory project, so changes become visible without a
restart. A `.ecproj` written by another process is picked up by the app's project watcher under
the same session; see [agents.md](agents.md).
- **Only requests are read:** every line must be a JSON object with a string `method` (blank lines are
skipped). Anything else (text that isn't JSON, a JSON array or number, an object without `method`,
invalid UTF-8, a line longer than 4 MiB) gets one error reply ending in "closing the connection", and
+116
View File
@@ -0,0 +1,116 @@
# Spec: live project reload for CLI/MCP edits (no GUI restart)
## Title
`CLI/MCP edits to a project require a full EffectCraft restart — add a watched .ecproj / persistent bridge session (paper.design-style live editing)`
## Problem
When an agent edits a `.ecproj` through `effectcraft-cli` or MCP while the desktop app is open, the window does not see the edits. The session must be closed and reopened before cuts, transforms, effects or imports made by the CLI become visible. For an agent working interactively this is disruptive: every edit cycle costs a restart and loses the live session state.
Reference behaviour: paper.design's MCP keeps the same client process alive, so the agent's edits land in the running in-memory session and appear immediately. The equivalent should be possible in EffectCraft.
## Root cause (verified in this checkout, v0.25.1)
- `crates/engine/src/lib.rs:104-121` — `Session` holds `pub project: Arc<Project>` (plus `saved_project`, `path`). The open window renders and edits that in-memory `Arc`, not the file.
- `crates/engine/src/session/edit.rs:30-87` `edit_inner` — every GUI edit clones the project (`(*self.project).clone()`), applies the command, then `self.project = Arc::new(p)` (`:76`). No file read in this path.
- `crates/engine/src/cmd/file.rs:89-103` `file_text` / `save_to` — saves serialise the in-memory `Arc` and write it to disk. One-way: memory -> disk.
- `crates/engine/src/cmd/file.rs:43` `open` and `:122` `revert` are the only paths that read the file and call `replace_project`.
- `crates/engine/src/session/edit.rs:198-236` `replace_project` — the only whole-project swap: stops render/track/roto jobs, clears caches and history, then `self.project = Arc::new(p)` (`:236`).
- `crates/ui-egui/src/app/frame.rs:680-704` — the UI tick runs autosave, a Watch Folder *render* poll, `tick_footage_reload` (`:725`) and `tick_lut_files` (`:711`). **There is no watcher on the project file.**
- `apps/effectcraft-cli/src/main.rs:467-498` — a CLI `exec` builds a *new* headless `Session` (`effectcraft_host::headless_session()`), reads the project into that process, edits, and saves it back. The GUI's `Arc` is untouched.
- `apps/effectcraft-cli/src/project_lock.rs:77-90` — CLI saves take an OS lock so CLI runs serialize; the GUI never takes that lock.
- `apps/effectcraft/src/control_server.rs:25-63` and `crates/automation/src/bridge.rs:15` — a loopback control channel and CLI bridge already exist; `engine.execute` runs commands against the live session (`crates/ui-egui/src/control.rs:224-294`, `crates/ui-egui/src/app/frame.rs:19-68`). It works, but only when the caller explicitly sends a command; external file edits still need a watcher.
## Intended behaviour
1. An external process (CLI/MCP or any editor) saves the `.ecproj` next to the open project.
2. The running GUI notices the file changed within ~1-2 s and reloads it into the same `Session.project`, so the timeline, comp viewer and panels show the new cuts/transforms/effects/imports **without a restart**.
3. Prefer edits through the bridge/control channel so they mutate the live session directly; the file watcher covers edits made by processes that only touch the file.
4. Never discard unsaved GUI work silently, and never reload in the middle of a render or script.
## Scope (hyper-specific)
In scope:
- New engine module `crates/engine/src/project_reload.rs`: a polling `Watcher` modelled on `crates/engine/src/footage/footage_reload.rs:430-510` (worker thread, `mpsc::sync_channel(1)`, no new dependency). Stamps `session.path` with existing `Services::stamp` (size + mtime); 1 s focused / 5 s unfocused; immediate wake on focus and on path change; ~250 ms debounce for atomic temp+rename writes.
- UI wiring in `crates/ui-egui/src/lib.rs` (watcher field next to `footage_watcher` at `:449`) and `crates/ui-egui/src/app/frame.rs` (a `tick_project_reload` next to `tick_footage_reload`).
- Reload path reuses `file.revert` -> `open` -> `replace_project`; do not add a second project parser.
- Baseline stamp updated on `save_to` and `open` so the GUI's own writes do not trigger a reload loop.
- Guard on `Session::is_dirty()` (`crates/engine/src/session/edit.rs:180`) and active render/script (`script_ui.render_host`): if dirty, the status line names File ▸ Save As ▸ Save a Copy... to preserve edits without overwriting the disk file, then File ▸ Revert, and states that Revert discards unsaved GUI changes. This replaces the originally requested two-button "Reload / Keep mine" prompt: a status line with the exact commands is an accepted deviation recorded here.
- Autosave coordination: keep `autosave_tick` (`crates/engine/src/settings/session_settings.rs:418`) running while a change is pending. Auto-save writes recovery copies (`<name> auto-save N.ecproj` in an Auto-Save folder), never the project file, so it cannot overwrite the external edit; pausing it would only remove crash recovery for the unsaved local work. The only hold is a due recovery write whose final plan would alias the project file itself (`Session::autosave_tick_guarded`, checked on the `WritePlan` only when a write is due, so idle ticks do no file-system work). *Correction:* an earlier version of this spec said to suppress autosave "or the GUI overwrites the external edit before reload"; that premise was wrong (review on PR #4170).
- Tests: temp project file, external write, assert live session reflect the change; assert no reload on self-save; assert dirty guard; assert no reload during render.
- Docs: `docs/agents.md`, `docs/control-protocol.md`, `docs/preferences.md` note the watcher and the bridge-preferred workflow.
Explicitly out of scope:
- No new crate dependencies; no changes to `Cargo.toml`/`Cargo.lock`.
- No changes to plug-in loading (`crates/plugin/**`), the effect registry, footage reload, LUT reload, render/cache internals, or the web build's storage model.
- No change to CLI save semantics or the project lock file.
- No changes to any repo other than EffectCraft.
## Areas touched, and what each affects
| File | Effect | Precaution |
|---|---|---|
| `crates/engine/src/project_reload.rs` (new) | one worker thread, metadata-only polling of one path | sleep between polls; never hold a file handle on Windows |
| `crates/engine/src/lib.rs` | re-export the module | no behavioural change |
| `crates/engine/src/cmd/file.rs` | update watch baseline on open/save | keep one stamp source; no new parse path |
| `crates/ui-egui/src/lib.rs` | one `Option<Watcher>` field | drop ends the thread |
| `crates/ui-egui/src/app/frame.rs` | one cheap per-frame check | no per-frame file I/O; worker does the polling |
| `crates/engine/src/settings/session_settings.rs` | detect a recovery target that aliases the project file | recovery auto-saves keep running while a change is pending |
| tests + docs | verification and documentation only | temp dirs, no real user files |
`replace_project` stops jobs, drops decoded footage and clears undo history. Any reload must therefore be gated on clean + idle state; this is the main correctness risk, not the polling itself.
## Todo list
- [x] 1. Capture baseline metrics before any change (see next section).
- [x] 2. Add `project_reload.rs` watcher with stamp/debounce/focus wake; unit tests for stamp changes and debounce (3/3 pass).
- [x] 3. Wire watcher field and `tick_project_reload` into the UI; thread stops on app close / path change.
- [x] 4. Add dirty/active-render guard and the "changed on disk" status; live-tested: unsaved GUI work was held, explicit `file.revert` applied the external edit.
- [x] 5. Self-save baseline: `Session.project_stamp` updated on open/save; unit test confirms an acknowledged change is not reported twice.
- [x] 6. Coordinate with autosave: recovery auto-saves keep running while a change is pending; only a target aliasing the project file is held. Regression proves the external project and the local recovery copy both survive.
- [x] 7. Document bridge-preferred workflow and watcher behaviour (`docs/agents.md`, `docs/control-protocol.md`, `docs/preferences.md`).
- [x] 8. Re-ran metrics after the change; no latency or memory regression (see below).
- [x] 9. Diff scoped to the files listed; `Cargo.toml` / `Cargo.lock` unchanged (verified with `git diff --stat` / `git diff -- Cargo.toml Cargo.lock`).
## Baseline / performance snapshot (capture BEFORE implementation)
Record on this machine with the release build, GUI started as `effectcraft.exe --control 9877 --demo`:
| Metric | How to measure | Baseline | After |
|---|---|---|---|
| Cold start to "first frame drawn" | timestamp in the app log (`apps/effectcraft/src/main.rs` logs `first frame drawn`) | 1.07 s | 1.08 s |
| Idle GUI CPU over 60 s | `Get-Process effectcraft \| Select-Object Id,CPU,WorkingSet64` at start/end | 10.41 s -> 22.38 s (~20% of one core, demo playing) | 6.00 s -> 6.08 s (~0.13% of one core, project open) |
| Idle GUI RSS after 60 s | same | 1.10 GB -> 2.04 GB (+0.94 GB, existing demo-cache growth) | 986 MB -> 956 MB (flat) |
| Frame p95 in the editor | existing frame timing / profiling path; sample during a 60 s interaction | not captured (no in-app profiler available) | not captured |
| `file.open` latency | control channel `engine.execute` timing, 20 runs | median 14.07 ms, p95 95.51 ms | median 10.94 ms, p95 24.43 ms |
| `file.revert` latency | same, 20 runs | median 14.09 ms, p95 17.38 ms | median 10.04 ms, p95 11.23 ms |
| `render.frame` latency | 20 identical renders before/after | median 13.44 ms, p95 17.72 ms | median 11.19 ms, p95 15.65 ms |
| Memory after 100 external edits + reloads | RSS at start/end, plus 10 min idle after | not captured before (no equivalent loop existed) | 986 MB -> 386 MB during reloads -> 968 MB after 60 s idle (no growth) |
Note: the before/after idle samples used different projects (demo playback vs an open `.ecproj`), so
the idle CPU/RSS rows are not a strict A/B; the latency rows are the comparable ones and all
improved or stayed within noise. No monotonic memory growth was observed after 100 reloads.
Budgets / acceptance:
- No new dependencies, no lockfile change.
- Watcher thread idle CPU < 0.1% (one sleeping thread, no per-frame file I/O).
- RSS growth attributable to the watcher < 10 MB after 100 reloads; no monotonic growth trend after 30 min idle.
- Frame p95 and render/open/revert latencies must stay within measurement noise of baseline; any regression blocks the change.
- External save -> timeline updated in <= 2 s while focused, without restart.
- Zero unsaved GUI edits lost without explicit user consent.
## Why this shape
The repository already contains two lightweight, polling-based watchers (footage at `crates/engine/src/footage/footage_reload.rs`, LUT at `crates/engine/src/footage/lut_reload.rs`) that wake the UI only when a stamp changes. Reusing that pattern keeps the addition small, dependency-free and consistent with how similar programs watch documents, rather than introducing a new event-loop or file-watching crate.
## Verification performed (release build, v0.25.1 + this change)
- `cargo build --release -p effectcraft -p effectcraft-cli` — finished in 18m 37s, no errors.
- `cargo test --release -p effectcraft-engine project_reload` — 3 passed, 0 failed.
- Live test 1: app started with `--control 9877 <project>`; a separate `effectcraft-cli exec comp.new … --save` wrote the project. The new comp appeared in the running app's `project.summary` in 4.91 s with the same PID (14280), no restart.
- Dirty-session test: external write held for 5 s while GUI had unsaved edits (GUI edit kept, external comp not applied); explicit `file.revert` then loaded the external comp as expected.
- Focused-window measurement after the review fixes: with the GUI focused via `ui.focus`, file-write -> visible in `project.summary` was 0.297 s; the full CLI invocation including process startup took 2.469 s. The watcher budget applies from the file write, not from process start.
- CodeRabbit review follow-up: the two stamp races (save and open), the debounce baseline, the initial baseline, test waits and the Save-before-Revert guidance were fixed in commit `4e7ccd`. Unit tests for the new UI branches were added but their release test-harness link was stopped at the owner's request to avoid a long LTO link; CI should run them.
- 100 consecutive `file.revert` calls: RSS 986 MB -> 386 MB -> 968 MB after 60 s idle; no monotonic growth.
- `git diff --stat` / `git diff -- Cargo.toml Cargo.lock`: 9 tracked files + 1 new source file, no dependency or lockfile change.
+5
View File
@@ -319,6 +319,11 @@ from?, newName?}`, `shortcuts.export {preset?, path?}`, `shortcuts.import {path?
Untitled projects go to the custom folder, or to `EffectCraft Auto-Save` in the config directory.
- Every project and auto-save write is atomic: a temporary file is written and flushed, then
renamed over the target, so a crash mid-write leaves the previous file intact.
- The desktop app watches the open project file (1 s while the window is in front, 5 s otherwise).
A save by another process reloads the project into the running session once it has no unsaved
changes or active render; otherwise the status line asks for File ▸ Revert. Auto-save keeps
writing its recovery copies while such a change is pending: they go to their own files, so a
crash still has the local work and the external edit is never overwritten.
- While the app runs, `session.lock` in the config directory records the open project and its
latest auto-save. A clean quit removes it. If it is still there at the next launch, the app
offers to open the latest auto-save (Settings ▸ Startup & Repair can turn this off).