Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Keep desktop files in sync with their originals on disk (#7674)

Anthony Stirlingafc945ad7d22
diff --git a/.github/workflows/e2e-stubbed.yml b/.github/workflows/e2e-stubbed.yml
index 2553f38f84..3d0cf057ba 100644
--- a/.github/workflows/e2e-stubbed.yml
+++ b/.github/workflows/e2e-stubbed.yml
@@ -63,6 +63,21 @@ jobs:
NPM_CONFIG_FETCH_RETRY_MINTIMEOUT: "1000"
NPM_CONFIG_FETCH_RETRY_MAXTIMEOUT: "120000"
run: task e2e:stubbed-project PROJECT=${{ matrix.project }} -- --workers=3
+ # The disk-link suite exercises a seam chosen at build time, so it needs
+ # a desktop-mode bundle of its own. Chromium only: it is not testing
+ # engine behaviour, and building twice on all three would treble the job.
+ - name: Build frontend (desktop mode, for the disk-link suite)
+ if: matrix.browser == 'chromium'
+ env:
+ VITE_BUILD_FOR_PREVIEW: "1"
+ run: task frontend:build:desktop:e2e
+ - name: Run disk-link E2E tests (desktop mode)
+ if: matrix.browser == 'chromium'
+ env:
+ HOME: /root
+ DOCKER_CONFIG: /tmp/playwright-docker-config
+ PLAYWRIGHT_JSON_OUTPUT_FILE: ${{ github.workspace }}/frontend/playwright-report/results-desktop.json
+ run: task e2e:stubbed-desktop -- --workers=3
- name: Flag flaky tests
# Runs regardless of the test outcome: a flaky test (passed on retry)
# leaves the step green, so this is the only place it surfaces. Emits
diff --git a/.taskfiles/e2e.yml b/.taskfiles/e2e.yml
index 084906960b..23c7043d60 100644
--- a/.taskfiles/e2e.yml
+++ b/.taskfiles/e2e.yml
@@ -15,6 +15,15 @@ tasks:
cmds:
- npx playwright test --project=stubbed {{.CLI_ARGS}}
+ stubbed-desktop:
+ desc: "Run the disk-link E2E suite against a desktop-mode build"
+ dir: frontend/editor
+ deps: [ ':frontend:prepare' ]
+ env:
+ PW_DESKTOP: "1"
+ cmds:
+ - npx playwright test --project=stubbed-desktop {{.CLI_ARGS}}
+
stubbed-project:
desc: "Run the stubbed E2E suite for a single Playwright project"
dir: frontend/editor
diff --git a/.taskfiles/frontend.yml b/.taskfiles/frontend.yml
index f10eadae2d..caf9c608ef 100644
--- a/.taskfiles/frontend.yml
+++ b/.taskfiles/frontend.yml
@@ -239,6 +239,14 @@ tasks:
cmds:
- npx vite build editor --mode desktop
+ build:desktop:e2e:
+ desc: "Desktop build in its own outDir, for the disk-link E2E project"
+ deps:
+ - task: prepare
+ vars: { MODE: desktop }
+ cmds:
+ - npx vite build editor --mode desktop --outDir dist-desktop
+
build:prototypes:
desc: "Build for prototypes mode"
deps: [prepare]
diff --git a/frontend/.gitignore b/frontend/.gitignore
index 9ab1c65091..3f9122a6f7 100644
--- a/frontend/.gitignore
+++ b/frontend/.gitignore
@@ -16,6 +16,7 @@
/editor/build
/editor/dist
+/editor/dist-desktop
# misc
.DS_Store
diff --git a/frontend/editor/playwright.config.ts b/frontend/editor/playwright.config.ts
index 865f03020f..ad47be40c6 100644
--- a/frontend/editor/playwright.config.ts
+++ b/frontend/editor/playwright.config.ts
@@ -29,6 +29,12 @@ const chromiumViewport = {
// vite already on 5173 from other parallel work. Defaults to 5173.
const DEV_PORT = process.env.V2_PORT ?? "5173";
+// The disk-link suite needs `--mode desktop`: on any other build the file-link
+// seam is the core no-op, nothing reconciles, and every spec in it skips. Its
+// own port so it can run beside a dev server already on DEV_PORT.
+const DESKTOP_PORT = process.env.V2_DESKTOP_PORT ?? "5273";
+const DISK_LINK_SPECS = /disk-link-.*\.spec\.ts/;
+
export default defineConfig({
testDir: "./src/core/tests",
testMatch: "**/*.spec.ts",
@@ -67,9 +73,22 @@ export default defineConfig({
{
name: "stubbed",
testDir: "./src/core/tests/stubbed",
+ testIgnore: DISK_LINK_SPECS,
use: chromiumViewport,
},
+ // Desktop-mode arm of the stubbed suite. Separate project because it needs
+ // its own server: the seam it exercises is chosen at build time.
+ {
+ name: "stubbed-desktop",
+ testDir: "./src/core/tests/stubbed",
+ testMatch: DISK_LINK_SPECS,
+ use: {
+ ...chromiumViewport,
+ baseURL: `http://localhost:${DESKTOP_PORT}`,
+ },
+ },
+
// Live setup - runs once before the live suite to perform the real
// forced-password-change first-login flow against a freshly-booted
// backend. The live project depends on it.
@@ -106,11 +125,13 @@ export default defineConfig({
{
name: "stubbed-firefox",
testDir: "./src/core/tests/stubbed",
+ testIgnore: DISK_LINK_SPECS,
use: { ...devices["Desktop Firefox"], viewport: STUBBED_VIEWPORT },
},
{
name: "stubbed-webkit",
testDir: "./src/core/tests/stubbed",
+ testIgnore: DISK_LINK_SPECS,
// Desktop Safari ships deviceScaleFactor 2; the editor now renders
// bitmaps at dpr x zoom, so leaving it would 4x every page raster in
// this suite. The HiDPI spec opts into 2x deliberately where it matters.
@@ -122,16 +143,29 @@ export default defineConfig({
},
],
- webServer: {
- // In CI, serve a pre-built `dist/` via `vite preview` so the heavy tool
- // pages don't pay vite's on-demand transform cost on first hit (which
- // blew the 30s navigationTimeout under --workers=3 - see
- // all-tool-pages-load.spec.ts). Locally, keep `vite` dev for HMR.
- command: process.env.CI
- ? `npx vite preview --port ${DEV_PORT} --strictPort`
- : `npx vite --port ${DEV_PORT} --strictPort`,
- url: process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,
- reuseExistingServer: !process.env.CI,
- timeout: 120_000,
- },
+ // PW_DESKTOP picks the desktop-mode server instead of the default one, so a
+ // normal run never pays for a second build it has no project for.
+ webServer:
+ process.env.PW_DESKTOP === "1"
+ ? {
+ command: process.env.CI
+ ? `npx vite preview --outDir dist-desktop --port ${DESKTOP_PORT} --strictPort`
+ : `npx vite --mode desktop --port ${DESKTOP_PORT} --strictPort`,
+ url: `http://localhost:${DESKTOP_PORT}`,
+ reuseExistingServer: !process.env.CI,
+ timeout: 120_000,
+ }
+ : {
+ // In CI, serve a pre-built `dist/` via `vite preview` so the heavy tool
+ // pages don't pay vite's on-demand transform cost on first hit (which
+ // blew the 30s navigationTimeout under --workers=3 - see
+ // all-tool-pages-load.spec.ts). Locally, keep `vite` dev for HMR.
+ command: process.env.CI
+ ? `npx vite preview --port ${DEV_PORT} --strictPort`
+ : `npx vite --port ${DEV_PORT} --strictPort`,
+ url:
+ process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,
+ reuseExistingServer: !process.env.CI,
+ timeout: 120_000,
+ },
});
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 02d1113775..4f3cb2a41d 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -36,7 +36,10 @@ editSecret = "Edit this value"
editYourNewFiles = "Edit your new file(s)"
exportAndContinue = "Export & Continue"
false = "False"
+fileChangedOnDisk = "Changed on disk since you edited it"
+fileDiskUnavailable = "Cannot reach the file on disk"
fileNotSavedToDisk = "Not saved to disk"
+fileOriginalDeleted = "Original deleted - save to keep a copy"
fileSavedToDisk = "File saved to disk"
fileSelected = "{{filename}}"
filesSelected = "{{count}} files"
@@ -4088,6 +4091,36 @@ title = "Settings Opened"
message = "Stirling PDF is now your default PDF editor"
title = "Default App Set"
+[desktopFileLink]
+saveAs = "Save as…"
+useDiskVersion = "Use disk version"
+
+[desktopFileLink.conflict]
+hint = "Keeping your changes overwrites the file on disk when you next save."
+keepMine = "Keep my changes"
+prompt = "This file changed on disk while you had unsaved changes here. Only one version can be kept."
+remaining = "{{count}} more to review"
+title = "File changed on disk"
+useDisk = "Use the disk version"
+
+[desktopFileLink.missing]
+body = "\"{{name}}\" has been deleted or moved on disk, so it has been removed from your files."
+title = "File no longer exists"
+
+[desktopFileLink.openDeleted]
+body_one = "\"{{name}}\" no longer exists on disk. It is still open here - saving will ask you for a new location."
+body_other = "{{count}} files no longer exist on disk. They are still open here - saving each one will ask you for a new location."
+title_one = "File deleted on disk"
+title_other = "Files deleted on disk"
+
+[desktopFileLink.reloaded]
+body = "\"{{name}}\" changed on disk and has been reloaded."
+title = "Updated from disk"
+
+[desktopFileLink.tooLarge]
+body = "\"{{name}}\" changed on disk. It is large enough that reloading it will take a while, so the version here has been left alone."
+title = "File changed on disk"
+
[desktopUpdate]
downloading = "Downloading update..."
installing = "Installing update..."
@@ -4609,6 +4642,16 @@ deviceHint = "Removes the local copy. The cloud copy is kept."
everywhere = "Everywhere"
everywhereHint = "Deletes the file from this device and the cloud."
+[filesPage.diskLink]
+conflict = "Disk changed"
+conflictHint = "The file on disk changed while you had unsaved edits. Your version is shown - saving will overwrite the one on disk."
+orphaned = "Not on disk"
+orphanedHint = "The original at {{path}} is gone. This copy is only here - saving it will ask for a new location."
+unavailable = "Unavailable"
+unavailableHintOffline = "The drive or share this file lives on is not connected. Reconnect it to pick up changes again."
+unavailableHintPermission = "Stirling is not allowed to read this location. Grant access in System Settings to pick up changes again."
+unavailableHintUnknown = "This file cannot be reached right now. The copy here is unchanged."
+
[filesPage.diskState]
all = "All"
done = "Ready"
diff --git a/frontend/editor/src-tauri/Cargo.lock b/frontend/editor/src-tauri/Cargo.lock
index a875adc740..d47a578aa9 100644
--- a/frontend/editor/src-tauri/Cargo.lock
+++ b/frontend/editor/src-tauri/Cargo.lock
@@ -1378,6 +1378,15 @@ dependencies = [
"percent-encoding",
]
+[[package]]
+name = "fsevent-sys"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "funty"
version = "2.0.0"
@@ -2190,6 +2199,26 @@ dependencies = [
"cfb",
]
+[[package]]
+name = "inotify"
+version = "0.11.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"
+dependencies = [
+ "bitflags 2.11.0",
+ "inotify-sys",
+ "libc",
+]
+
+[[package]]
+name = "inotify-sys"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "ipnet"
version = "2.11.0"
@@ -2333,6 +2362,26 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "kqueue"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"
+dependencies = [
+ "kqueue-sys",
+ "libc",
+]
+
+[[package]]
+name = "kqueue-sys"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
+dependencies = [
+ "bitflags 2.11.0",
+ "libc",
+]
+
[[package]]
name = "kuchikiki"
version = "0.8.8-speedreader"
@@ -2546,6 +2595,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
dependencies = [
"libc",
+ "log",
"wasi 0.11.1+wasi-snapshot-preview1",
"windows-sys 0.61.2",
]
@@ -2613,6 +2663,24 @@ version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb"
+[[package]]
+name = "notify"
+version = "8.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"
+dependencies = [
+ "bitflags 2.11.0",
+ "fsevent-sys",
+ "inotify",
+ "kqueue",
+ "libc",
+ "log",
+ "mio",
+ "notify-types",
+ "walkdir",
+ "windows-sys 0.60.2",
+]
+
[[package]]
name = "notify-rust"
version = "4.12.0"
@@ -2627,6 +2695,15 @@ dependencies = [
"zbus",
]
+[[package]]
+name = "notify-types"
+version = "2.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"
+dependencies = [
+ "bitflags 2.11.0",
+]
+
[[package]]
name = "num-conv"
version = "0.2.0"
@@ -4556,6 +4633,7 @@ dependencies = [
"core-services",
"keyring",
"log",
+ "notify",
"objc2",
"objc2-app-kit",
"objc2-foundation",
diff --git a/frontend/editor/src-tauri/Cargo.toml b/frontend/editor/src-tauri/Cargo.toml
index f617cd0738..b6a436d08f 100644
--- a/frontend/editor/src-tauri/Cargo.toml
+++ b/frontend/editor/src-tauri/Cargo.toml
@@ -39,6 +39,7 @@ tauri-plugin-updater = "2"
tauri-plugin-window-state = "2.2.1"
keyring = { version = "3.6.1", features = ["apple-native", "windows-native"] }
tokio = { version = "1.50", features = ["time", "sync"] }
+notify = "8.2"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "rustls-tls-native-roots"] }
tiny_http = "0.12"
url = "2.5"
diff --git a/frontend/editor/src-tauri/src/commands/files.rs b/frontend/editor/src-tauri/src/commands/files.rs
index 1e3c9b61cb..5acc8d51f5 100644
--- a/frontend/editor/src-tauri/src/commands/files.rs
+++ b/frontend/editor/src-tauri/src/commands/files.rs
@@ -1,4 +1,7 @@
use crate::utils::add_log;
+use serde::Serialize;
+use std::io::ErrorKind;
+use std::path::Path;
use std::sync::Mutex;
// Store the opened file paths globally (supports multiple files)
@@ -39,6 +42,271 @@ pub async fn pop_opened_files() -> Result<Vec<String>, String> {
let mut opened_files = OPENED_FILES.lock().unwrap();
let all_files = opened_files.clone();
opened_files.clear();
- add_log(format!("📂 Returning and clearing {} opened file(s)", all_files.len()));
+ add_log(format!(
+ "📂 Returning and clearing {} opened file(s)",
+ all_files.len()
+ ));
Ok(all_files)
}
+
+// On-disk state of a linked file. Desktop files are meant to stay 1:1 with disk,
+// so the frontend stats the real file rather than trusting its IndexedDB copy.
+
+#[derive(Serialize, Debug, PartialEq, Eq, Clone, Copy)]
+#[serde(rename_all = "camelCase")]
+pub enum DiskUnavailableReason {
+ Permission,
+ Offline,
+ Unknown,
+}
+
+#[derive(Serialize, Debug, PartialEq, Eq)]
+#[serde(tag = "availability", rename_all = "camelCase")]
+pub enum DiskFileState {
+ #[serde(rename_all = "camelCase")]
+ Present {
+ size: u64,
+ // Epoch ms; 0 when the platform gives us no mtime.
+ modified_ms: u64,
+ },
+ Gone,
+ #[serde(rename_all = "camelCase")]
+ Unavailable {
+ reason: DiskUnavailableReason,
+ },
+}
+
+fn unavailable(reason: DiskUnavailableReason) -> DiskFileState {
+ DiskFileState::Unavailable { reason }
+}
+
+fn reason_for(kind: ErrorKind) -> DiskUnavailableReason {
+ match kind {
+ ErrorKind::PermissionDenied => DiskUnavailableReason::Permission,
+ ErrorKind::TimedOut | ErrorKind::NotConnected => DiskUnavailableReason::Offline,
+ _ => DiskUnavailableReason::Unknown,
+ }
+}
+
+fn modified_ms(meta: &std::fs::Metadata) -> u64 {
+ meta.modified()
+ .ok()
+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
+
+#[cfg(target_os = "macos")]
+const MOUNT_PARENTS: &[&str] = &["/Volumes"];
+#[cfg(target_os = "linux")]
+const MOUNT_PARENTS: &[&str] = &["/mnt", "/media", "/run/media"];
+#[cfg(not(any(target_os = "macos", target_os = "linux")))]
+const MOUNT_PARENTS: &[&str] = &[];
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Absence {
+ Deleted,
+ Unreachable,
+}
+
+pub fn classify_absence(path: &Path) -> Absence {
+ for ancestor in path
+ .ancestors()
+ .skip(1)
+ .filter(|a| !a.as_os_str().is_empty())
+ {
+ match std::fs::metadata(ancestor) {
+ Ok(meta) if meta.is_dir() => {
+ return if is_mount_parent(ancestor) {
+ Absence::Unreachable
+ } else {
+ Absence::Deleted
+ };
+ }
+ Ok(_) => return Absence::Unreachable,
+ Err(error) if error.kind() == ErrorKind::NotFound => continue,
+ Err(_) => return Absence::Unreachable,
+ }
+ }
+
+ Absence::Unreachable
+}
+
+fn classify_absent(path: &Path) -> DiskFileState {
+ match classify_absence(path) {
+ Absence::Deleted => DiskFileState::Gone,
+ Absence::Unreachable => match std::fs::metadata(path.parent().unwrap_or(path)) {
+ Err(error) if error.kind() == ErrorKind::PermissionDenied => {
+ unavailable(DiskUnavailableReason::Permission)
+ }
+ _ => unavailable(DiskUnavailableReason::Offline),
+ },
+ }
+}
+
+fn is_mount_parent(path: &Path) -> bool {
+ MOUNT_PARENTS.iter().any(|root| path == Path::new(root))
+}
+
+#[tauri::command]
+pub fn file_disk_state(path: String) -> DiskFileState {
+ let path = Path::new(&path);
+ match std::fs::metadata(path) {
+ Ok(meta) if meta.is_file() => DiskFileState::Present {
+ size: meta.len(),
+ modified_ms: modified_ms(&meta),
+ },
+ Ok(_) => unavailable(DiskUnavailableReason::Unknown),
+ Err(error) if error.kind() == ErrorKind::NotFound => classify_absent(path),
+ Err(error) => unavailable(reason_for(error.kind())),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp_dir(tag: &str) -> std::path::PathBuf {
+ let dir = std::env::temp_dir().join(format!("stirling_{}_{}", tag, std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ fn state(path: &Path) -> DiskFileState {
+ file_disk_state(path.to_string_lossy().to_string())
+ }
+
+ #[test]
+ fn a_real_file_reports_its_size_and_mtime() {
+ let dir = temp_dir("present");
+ let file = dir.join("report.pdf");
+ std::fs::write(&file, b"hello world").unwrap();
+
+ match state(&file) {
+ DiskFileState::Present { size, modified_ms } => {
+ assert_eq!(size, 11);
+ assert!(modified_ms > 0);
+ }
+ other => panic!("expected Present, got {:?}", other),
+ }
+
+ // A rewrite with different content is visible as a new size.
+ std::fs::write(&file, b"hello world, edited externally").unwrap();
+ assert!(matches!(
+ state(&file),
+ DiskFileState::Present { size: 30, .. }
+ ));
+
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_deleted_file_in_a_folder_that_is_still_there_is_gone() {
+ let dir = temp_dir("gone");
+ let file = dir.join("report.pdf");
+ std::fs::write(&file, b"x").unwrap();
+ std::fs::remove_file(&file).unwrap();
+
+ assert_eq!(state(&file), DiskFileState::Gone);
+
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn losing_the_containing_folder_still_counts_as_gone() {
+ let dir = temp_dir("gone_folder");
+ let inner = dir.join("sub");
+ std::fs::create_dir_all(&inner).unwrap();
+ let file = inner.join("report.pdf");
+ std::fs::write(&file, b"x").unwrap();
+ std::fs::remove_dir_all(&inner).unwrap();
+
+ assert_eq!(state(&file), DiskFileState::Gone);
+
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn a_drive_that_is_not_mounted_is_offline_not_gone() {
+ assert_eq!(
+ state(Path::new(r"Q:\Docs\report.pdf")),
+ unavailable(DiskUnavailableReason::Offline),
+ "an unreachable location must never be reported as a deletion"
+ );
+ }
+
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn an_ejected_volume_is_offline_because_volumes_is_a_mount_parent() {
+ assert_eq!(
+ state(Path::new("/Volumes/StirlingEjectedTestDisk/report.pdf")),
+ unavailable(DiskUnavailableReason::Offline)
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_folder_we_may_not_read_is_unavailable_not_gone() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = temp_dir("denied");
+ let file = dir.join("report.pdf");
+ std::fs::write(&file, b"x").unwrap();
+ std::fs::set_permissions(&dir, PermissionsExt::from_mode(0o000)).unwrap();
+
+ let denied = state(&file);
+ std::fs::set_permissions(&dir, PermissionsExt::from_mode(0o755)).unwrap();
+ std::fs::remove_dir_all(&dir).unwrap();
+
+ if denied
+ != (DiskFileState::Present {
+ size: 1,
+ modified_ms: 0,
+ })
+ {
+ assert_eq!(
+ denied,
+ unavailable(DiskUnavailableReason::Permission),
+ "a declined file-access prompt must not read as a deletion"
+ );
+ }
+ }
+
+ #[test]
+ fn a_directory_is_not_a_file() {
+ let dir = temp_dir("is_dir");
+ assert_eq!(state(&dir), unavailable(DiskUnavailableReason::Unknown));
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
+ #[test]
+ fn a_relative_path_cannot_reach_the_destructive_answer() {
+ assert_ne!(
+ file_disk_state("report.pdf".to_string()),
+ DiskFileState::Gone
+ );
+ }
+
+ #[test]
+ fn the_wire_shape_is_a_tagged_union_the_frontend_can_narrow_on() {
+ let present = serde_json::to_string(&DiskFileState::Present {
+ size: 7,
+ modified_ms: 1,
+ })
+ .unwrap();
+ assert_eq!(
+ present,
+ r#"{"availability":"present","size":7,"modifiedMs":1}"#
+ );
+ assert_eq!(
+ serde_json::to_string(&DiskFileState::Gone).unwrap(),
+ r#"{"availability":"gone"}"#
+ );
+ assert_eq!(
+ serde_json::to_string(&unavailable(DiskUnavailableReason::Permission)).unwrap(),
+ r#"{"availability":"unavailable","reason":"permission"}"#
+ );
+ }
+}
diff --git a/frontend/editor/src-tauri/src/commands/mod.rs b/frontend/editor/src-tauri/src/commands/mod.rs
index 1637c926c7..e8ae386b48 100644
--- a/frontend/editor/src-tauri/src/commands/mod.rs
+++ b/frontend/editor/src-tauri/src/commands/mod.rs
@@ -7,10 +7,14 @@ pub mod local_proxy;
pub mod platform;
pub mod print;
pub mod updater;
+pub mod watcher;
pub mod window;
pub use backend::{cleanup_backend, get_backend_port, start_backend};
-pub use files::{add_opened_file, clear_opened_files, get_opened_files, pop_opened_files};
+pub use files::{
+ add_opened_file, clear_opened_files, file_disk_state, get_opened_files, pop_opened_files,
+};
+pub use watcher::{release_window_watches, unwatch_disk_paths, watch_disk_paths};
pub use window::{
forward_files_to_window,
open_files_in_new_window,
diff --git a/frontend/editor/src-tauri/src/commands/watcher.rs b/frontend/editor/src-tauri/src/commands/watcher.rs
new file mode 100644
index 0000000000..758551953e
--- /dev/null
+++ b/frontend/editor/src-tauri/src/commands/watcher.rs
@@ -0,0 +1,655 @@
+use crate::commands::files::{classify_absence, Absence};
+use crate::utils::add_log;
+use notify::event::{ModifyKind, RemoveKind};
+use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
+use serde::Serialize;
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use std::io;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use tauri::{AppHandle, Emitter, Manager, WebviewWindow};
+
+static WATCHER: Mutex<Option<RecommendedWatcher>> = Mutex::new(None);
+static CLAIMS: Mutex<BTreeMap<String, Vec<String>>> = Mutex::new(BTreeMap::new());
+static WATCHED_DIRS: Mutex<BTreeSet<PathBuf>> = Mutex::new(BTreeSet::new());
+static ROUTES: Mutex<Option<Arc<Routes>>> = Mutex::new(None);
+
+#[derive(Default)]
+struct Routes {
+ files: HashMap<PathBuf, Vec<String>>,
+ dirs: HashMap<PathBuf, Vec<String>>,
+}
+
+impl Routes {
+ fn add(&mut self, dir: &Path, file_name: &Path, given: &str) {
+ push_unique(self.files.entry(dir.join(file_name)).or_default(), given);
+ push_unique(self.dirs.entry(dir.to_path_buf()).or_default(), given);
+ }
+
+ fn all_given(&self) -> Vec<String> {
+ let mut all: Vec<String> = Vec::new();
+ for given in self.files.values().flatten() {
+ push_unique(&mut all, given);
+ }
+ all
+ }
+}
+
+fn push_unique(into: &mut Vec<String>, given: &str) {
+ if !into.iter().any(|held| held == given) {
+ into.push(given.to_string());
+ }
+}
+
+struct WatchTarget<'a> {
+ given: &'a str,
+ parent: PathBuf,
+ file_name: PathBuf,
+}
+
+impl<'a> WatchTarget<'a> {
+ fn parse(given: &'a str) -> Option<Self> {
+ let path = Path::new(given);
+ if !path.is_absolute() {
+ return None;
+ }
+ Some(Self {
+ given,
+ parent: path.parent()?.to_path_buf(),
+ file_name: PathBuf::from(path.file_name()?),
+ })
+ }
+}
+
+#[derive(Clone, Serialize)]
+struct DiskChangePayload {
+ paths: Vec<String>,
+}
+
+pub const DISK_CHANGE_EVENT: &str = "disk-files-changed";
+
+fn build_routes(paths: &[String]) -> (Routes, BTreeSet<PathBuf>) {
+ let mut routes = Routes::default();
+ let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
+
+ for given in paths {
+ let Some(target) = WatchTarget::parse(given) else {
+ add_log(format!("⚠️ Not a watchable file path: {}", given));
+ continue;
+ };
+
+ let resolved = target
+ .parent
+ .canonicalize()
+ .unwrap_or_else(|_| target.parent.clone());
+
+ // A case- or normalisation-differing spelling still opens the file on
+ // Windows and macOS, so the frontend can hold one spelling while the OS
+ // reports another and every event misses, silently.
+ let on_disk_name = Path::new(target.given)
+ .canonicalize()
+ .ok()
+ .and_then(|full| full.file_name().map(PathBuf::from));
+
+ for parent in [&target.parent, &resolved] {
+ routes.add(parent, &target.file_name, target.given);
+ if let Some(name) = &on_disk_name {
+ routes.add(parent, name, target.given);
+ }
+ }
+
+ dirs.insert(target.parent);
+ }
+
+ (routes, dirs)
+}
+
+// Only content/existence changes matter. Access events (someone opened the file
+// for reading) would fire constantly and mean nothing to us.
+fn is_interesting(kind: &EventKind) -> bool {
+ matches!(
+ kind,
+ EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
+ )
+}
+
+fn may_be_folder_loss(kind: &EventKind) -> bool {
+ matches!(
+ kind,
+ EventKind::Remove(RemoveKind::Folder | RemoveKind::Any)
+ | EventKind::Modify(ModifyKind::Name(_))
+ )
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum DirState {
+ Present,
+ Gone,
+ Unknown,
+}
+
+fn classify_dir_metadata(
+ metadata: io::Result<std::fs::Metadata>,
+ absence: impl Fn() -> Absence,
+) -> DirState {
+ match metadata {
+ Ok(meta) if meta.is_dir() => DirState::Present,
+ Ok(_) => DirState::Gone,
+ Err(e) if e.kind() == io::ErrorKind::NotFound => match absence() {
+ Absence::Deleted => DirState::Gone,
+ Absence::Unreachable => DirState::Unknown,
+ },
+ Err(_) => DirState::Unknown,
+ }
+}
+
+fn route_event(
+ routes: &Routes,
+ event: &Event,
+ probe: impl Fn(&Path) -> DirState,
+) -> Option<DiskChangePayload> {
+ if event.need_rescan() {
+ return payload(routes.all_given());
+ }
+ if !is_interesting(&event.kind) {
+ return None;
+ }
+
+ let mut affected: Vec<String> = Vec::new();
+ for path in &event.paths {
+ if let Some(given) = routes.files.get(path) {
+ for one in given {
+ push_unique(&mut affected, one);
+ }
+ }
+ if !may_be_folder_loss(&event.kind) {
+ continue;
+ }
+ let Some(children) = routes.dirs.get(path) else {
+ continue;
+ };
+ match probe(path) {
+ DirState::Gone => {
+ for one in children {
+ push_unique(&mut affected, one);
+ }
+ }
+ DirState::Present | DirState::Unknown => {}
+ }
+ }
+
+ payload(affected)
+}
+
+fn payload(paths: Vec<String>) -> Option<DiskChangePayload> {
+ if paths.is_empty() {
+ None
+ } else {
+ Some(DiskChangePayload { paths })
+ }
+}
+
+fn dir_state(dir: &Path) -> DirState {
+ classify_dir_metadata(std::fs::metadata(dir), || classify_absence(dir))
+}
+
+fn current_routes() -> Option<Arc<Routes>> {
+ let guard = ROUTES.lock().ok()?;
+ (*guard).clone()
+}
+
+fn reconcile(
+ app: &AppHandle,
+ label: &str,
+ paths: Vec<String>,
+ live: &[String],
+) -> Result<(), String> {
+ let mut watcher_guard = WATCHER.lock().map_err(|e| e.to_string())?;
+
+ let union = {
+ let mut claims = CLAIMS.lock().map_err(|e| e.to_string())?;
+ claims.retain(|owner, _| live.iter().any(|l| l == owner));
+ if paths.is_empty() || !live.iter().any(|l| l == label) {
+ claims.remove(label);
+ } else {
+ claims.insert(label.to_string(), paths);
+ }
+ claims.values().flatten().cloned().collect::<Vec<String>>()
+ };
+
+ let (routes, dirs) = build_routes(&union);
+ *ROUTES.lock().map_err(|e| e.to_string())? = Some(Arc::new(routes));
+
+ if dirs.is_empty() {
+ *watcher_guard = None;
+ WATCHED_DIRS.lock().map_err(|e| e.to_string())?.clear();
+ return Ok(());
+ }
+
+ let mut current = WATCHED_DIRS.lock().map_err(|e| e.to_string())?;
+ if watcher_guard.is_some() && *current == dirs {
+ return Ok(());
+ }
+
+ let handler_app = app.clone();
+ let mut watcher = notify::recommended_watcher(move |result| match result {
+ Ok(event) => {
+ let Some(routes) = current_routes() else {
+ return;
+ };
+ if let Some(payload) = route_event(&routes, &event, dir_state) {
+ if let Err(e) = handler_app.emit(DISK_CHANGE_EVENT, payload) {
+ add_log(format!("⚠️ Failed to emit disk change event: {}", e));
+ }
+ }
+ }
+ Err(e) => add_log(format!("⚠️ File watcher error: {}", e)),
+ })
+ .map_err(|e| e.to_string())?;
+
+ // A folder that has itself been removed just means nothing to watch there.
+ let mut watched: BTreeSet<PathBuf> = BTreeSet::new();
+ for dir in dirs {
+ match watcher.watch(&dir, RecursiveMode::NonRecursive) {
+ Ok(()) => {
+ watched.insert(dir);
+ }
+ Err(e) => add_log(format!("⚠️ Could not watch {}: {}", dir.display(), e)),
+ }
+ }
+
+ add_log(format!(
+ "👀 Watching {} folder(s) for disk changes",
+ watched.len()
+ ));
+ *current = watched;
+ *watcher_guard = Some(watcher);
+ Ok(())
+}
+
+fn live_labels(app: &AppHandle) -> Vec<String> {
+ app.webview_windows().into_keys().collect()
+}
+
+#[tauri::command]
+pub fn watch_disk_paths(window: WebviewWindow, paths: Vec<String>) -> Result<(), String> {
+ let app = window.app_handle().clone();
+ let live = live_labels(&app);
+ reconcile(&app, window.label(), paths, &live)
+}
+
+#[tauri::command]
+pub fn unwatch_disk_paths(window: WebviewWindow) -> Result<(), String> {
+ let app = window.app_handle().clone();
+ let live = live_labels(&app);
+ reconcile(&app, window.label(), Vec::new(), &live)
+}
+
+pub fn release_window_watches(app: &AppHandle, label: &str) {
+ let live = live_labels(app);
+ if let Err(e) = reconcile(app, label, Vec::new(), &live) {
+ add_log(format!("⚠️ Failed to release watches for {}: {}", label, e));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use notify::event::{CreateKind, DataChange, Flag, RenameMode};
+
+ fn event(kind: EventKind, paths: &[&str]) -> Event {
+ Event {
+ kind,
+ paths: paths.iter().map(PathBuf::from).collect(),
+ attrs: Default::default(),
+ }
+ }
+
+ fn routed(routes: &Routes, event: &Event, probe: DirState) -> Vec<String> {
+ route_event(routes, event, |_| probe)
+ .map(|p| {
+ let mut paths = p.paths;
+ paths.sort();
+ paths
+ })
+ .unwrap_or_default()
+ }
+
+ fn temp_dir(tag: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!("stirling_w_{}_{}", tag, std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn only_content_and_existence_events_are_interesting() {
+ assert!(is_interesting(&EventKind::Create(CreateKind::File)));
+ assert!(is_interesting(&EventKind::Modify(ModifyKind::Data(
+ DataChange::Content
+ ))));
+ assert!(is_interesting(&EventKind::Remove(RemoveKind::File)));
+ // A read is not a change; these would otherwise fire constantly.
+ assert!(!is_interesting(&EventKind::Access(
+ notify::event::AccessKind::Read
+ )));
+ assert!(!is_interesting(&EventKind::Any));
+ }
+
+ #[test]
+ fn events_outside_the_linked_set_are_ignored() {
+ let (routes, _) = build_routes(&[abs("/docs/report.pdf")]);
+
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Data(DataChange::Content)),
+ &[&abs("/docs/report.pdf")]
+ ),
+ DirState::Present
+ ),
+ vec![abs("/docs/report.pdf")]
+ );
+ // Same folder, different file - a busy Downloads folder must stay quiet.
+ assert!(routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Data(DataChange::Content)),
+ &[&abs("/docs/unrelated.pdf")]
+ ),
+ DirState::Present
+ )
+ .is_empty());
+ assert!(routed(
+ &routes,
+ &event(EventKind::Create(CreateKind::File), &[&abs("/docs")]),
+ DirState::Gone
+ )
+ .is_empty());
+ }
+
+ #[test]
+ fn a_lost_folder_stands_for_the_linked_files_that_were_in_it() {
+ let (routes, _) = build_routes(&[abs("/docs/a.pdf"), abs("/docs/b.pdf")]);
+ let removed = event(EventKind::Remove(RemoveKind::Folder), &[&abs("/docs")]);
+
+ assert_eq!(
+ routed(&routes, &removed, DirState::Gone),
+ vec![abs("/docs/a.pdf"), abs("/docs/b.pdf")]
+ );
+ assert!(routed(&routes, &removed, DirState::Present).is_empty());
+ assert!(routed(&routes, &removed, DirState::Unknown).is_empty());
+ }
+
+ #[test]
+ fn a_renamed_folder_is_a_loss_too() {
+ let (routes, _) = build_routes(&[abs("/docs/a.pdf")]);
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Name(RenameMode::Any)),
+ &[&abs("/docs")]
+ ),
+ DirState::Gone
+ ),
+ vec![abs("/docs/a.pdf")]
+ );
+ }
+
+ #[test]
+ fn an_unmounted_volume_is_not_a_deleted_folder() {
+ let (routes, _) = build_routes(&[abs("/docs/a.pdf")]);
+ assert!(!may_be_folder_loss(&EventKind::Remove(RemoveKind::Other)));
+ assert!(routed(
+ &routes,
+ &event(EventKind::Remove(RemoveKind::Other), &[&abs("/docs")]),
+ DirState::Gone
+ )
+ .is_empty());
+ }
+
+ #[test]
+ fn a_dropped_event_notice_stands_for_every_linked_file() {
+ let (routes, _) = build_routes(&[abs("/docs/a.pdf"), abs("/other/b.pdf")]);
+ let mut rescan = event(EventKind::Other, &[]);
+ rescan.attrs.set_flag(Flag::Rescan);
+
+ assert_eq!(
+ routed(&routes, &rescan, DirState::Present),
+ vec![abs("/docs/a.pdf"), abs("/other/b.pdf")]
+ );
+ }
+
+ #[test]
+ fn only_absolute_paths_naming_a_file_are_watchable() {
+ assert!(WatchTarget::parse("report.pdf").is_none());
+ assert!(WatchTarget::parse(&abs("/docs/report.pdf")).is_some());
+ }
+
+ #[test]
+ fn each_folder_is_registered_once() {
+ let (_, dirs) =
+ build_routes(&[abs("/docs/a.pdf"), abs("/docs/b.pdf"), abs("/other/c.pdf")]);
+ assert_eq!(dirs.len(), 2);
+ }
+
+ #[test]
+ fn a_watch_list_is_handed_over_exactly_as_given() {
+ let given = abs("/docs/report.pdf");
+ let (_, dirs) = build_routes(std::slice::from_ref(&given));
+ let parent = Path::new(&given).parent().unwrap();
+ assert!(dirs.contains(parent));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn both_spellings_of_one_folder_are_registered() {
+ let root = temp_dir("aliased");
+ let real = root.join("real");
+ std::fs::create_dir_all(&real).unwrap();
+ let link = root.join("link");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+
+ let via_link = link.join("a.pdf").to_string_lossy().to_string();
+ let via_real = real.join("b.pdf").to_string_lossy().to_string();
+ let (_, dirs) = build_routes(&[via_link, via_real]);
+
+ assert!(
+ dirs.contains(&link),
+ "the symlinked spelling must be watched"
+ );
+ assert!(
+ dirs.contains(&real),
+ "the real spelling must be watched too"
+ );
+
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ #[test]
+ fn only_a_removal_or_rename_is_worth_asking_the_filesystem_about() {
+ assert!(may_be_folder_loss(&EventKind::Remove(RemoveKind::Folder)));
+ assert!(may_be_folder_loss(&EventKind::Remove(RemoveKind::Any)));
+ assert!(may_be_folder_loss(&EventKind::Modify(ModifyKind::Name(
+ RenameMode::Any
+ ))));
+ assert!(!may_be_folder_loss(&EventKind::Create(CreateKind::Folder)));
+ assert!(!may_be_folder_loss(&EventKind::Modify(
+ ModifyKind::Metadata(notify::event::MetadataKind::Extended)
+ )));
+ }
+
+ #[test]
+ fn an_unreadable_folder_is_not_a_deleted_one() {
+ let denied = io::Error::from(io::ErrorKind::PermissionDenied);
+ assert_eq!(
+ classify_dir_metadata(Err(denied), || Absence::Deleted),
+ DirState::Unknown
+ );
+ }
+
+ #[test]
+ fn a_missing_folder_defers_to_the_shared_absence_classifier() {
+ let missing = || io::Error::from(io::ErrorKind::NotFound);
+ assert_eq!(
+ classify_dir_metadata(Err(missing()), || Absence::Deleted),
+ DirState::Gone
+ );
+ assert_eq!(
+ classify_dir_metadata(Err(missing()), || Absence::Unreachable),
+ DirState::Unknown
+ );
+ }
+
+ #[test]
+ fn a_folder_state_is_read_off_the_filesystem() {
+ let dir = temp_dir("dir_state");
+ assert_eq!(dir_state(&dir), DirState::Present);
+ std::fs::remove_dir_all(&dir).unwrap();
+ assert_eq!(dir_state(&dir), DirState::Gone);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_file_under_a_symlinked_folder_is_keyed_by_its_resolved_parent() {
+ let root = temp_dir("symlink");
+ let real = root.join("real");
+ std::fs::create_dir_all(&real).unwrap();
+ let link = root.join("link");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+
+ let given = link.join("report.pdf").to_string_lossy().to_string();
+ let reported = real.canonicalize().unwrap().join("report.pdf");
+
+ let (routes, dirs) = build_routes(std::slice::from_ref(&given));
+
+ assert_ne!(
+ reported.to_string_lossy().to_string(),
+ given,
+ "the symlink must actually resolve for this to test anything"
+ );
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Data(DataChange::Content)),
+ &[&reported.to_string_lossy()]
+ ),
+ DirState::Present
+ ),
+ vec![given.clone()]
+ );
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Data(DataChange::Content)),
+ &[&given]
+ ),
+ DirState::Present
+ ),
+ vec![given]
+ );
+ assert_eq!(dirs.len(), 1, "one folder, reached by two names");
+
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_lost_symlinked_folder_stands_for_the_files_reached_through_it() {
+ let root = temp_dir("symlink_loss");
+ let real = root.join("real");
+ std::fs::create_dir_all(&real).unwrap();
+ let link = root.join("link");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+
+ let given = link.join("report.pdf").to_string_lossy().to_string();
+ let (routes, _) = build_routes(std::slice::from_ref(&given));
+
+ let reported_dir = real.canonicalize().unwrap();
+ assert_ne!(reported_dir, real, "the symlink must actually resolve");
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Remove(RemoveKind::Folder),
+ &[&reported_dir.to_string_lossy()]
+ ),
+ DirState::Gone
+ ),
+ vec![given]
+ );
+
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn two_names_for_one_file_both_come_back() {
+ let root = temp_dir("two_names");
+ let real = root.join("real");
+ std::fs::create_dir_all(&real).unwrap();
+ let link = root.join("link");
+ std::os::unix::fs::symlink(&real, &link).unwrap();
+
+ let via_link = link.join("report.pdf").to_string_lossy().to_string();
+ let via_real = real.join("report.pdf").to_string_lossy().to_string();
+ let (routes, _) = build_routes(&[via_link.clone(), via_real.clone()]);
+
+ let mut expected = vec![via_link, via_real];
+ expected.sort();
+ let reported = real.canonicalize().unwrap().join("report.pdf");
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Data(DataChange::Content)),
+ &[&reported.to_string_lossy()]
+ ),
+ DirState::Present
+ ),
+ expected
+ );
+
+ std::fs::remove_dir_all(&root).unwrap();
+ }
+
+ #[test]
+ fn the_union_of_two_windows_is_what_gets_watched() {
+ let mut claims: BTreeMap<String, Vec<String>> = BTreeMap::new();
+ claims.insert("main".into(), vec![abs("/docs/a.pdf")]);
+ claims.insert("main-2".into(), vec![abs("/other/b.pdf")]);
+ let union: Vec<String> = claims.values().flatten().cloned().collect();
+
+ let (routes, dirs) = build_routes(&union);
+ assert_eq!(dirs.len(), 2);
+ for path in [abs("/docs/a.pdf"), abs("/other/b.pdf")] {
+ assert_eq!(
+ routed(
+ &routes,
+ &event(
+ EventKind::Modify(ModifyKind::Data(DataChange::Content)),
+ &[&path]
+ ),
+ DirState::Present
+ ),
+ vec![path]
+ );
+ }
+
+ claims.remove("main-2");
+ let (_, remaining) = build_routes(&claims.values().flatten().cloned().collect::<Vec<_>>());
+ assert_eq!(remaining.len(), 1);
+ }
+
+ fn abs(unix_path: &str) -> String {
+ if cfg!(windows) {
+ format!("C:{}", unix_path.replace('/', "\\"))
+ } else {
+ unix_path.to_string()
+ }
+ }
+}
diff --git a/frontend/editor/src-tauri/src/lib.rs b/frontend/editor/src-tauri/src/lib.rs
index b2cf60afda..0a948645cf 100644
--- a/frontend/editor/src-tauri/src/lib.rs
+++ b/frontend/editor/src-tauri/src/lib.rs
@@ -11,6 +11,7 @@ use commands::{
clear_opened_files,
clear_refresh_token,
clear_user_info,
+ file_disk_state,
forward_files_to_window,
is_default_pdf_handler,
get_auth_token,
@@ -21,6 +22,9 @@ use commands::{
open_in_new_window,
pop_opened_files,
pop_window_file_ids,
+ release_window_watches,
+ unwatch_disk_paths,
+ watch_disk_paths,
get_refresh_token,
get_user_info,
is_first_launch,
@@ -212,6 +216,9 @@ pub fn run() {
get_opened_files,
pop_opened_files,
clear_opened_files,
+ file_disk_state,
+ watch_disk_paths,
+ unwatch_disk_paths,
open_in_new_window,
open_files_in_new_window,
pop_window_file_ids,
@@ -269,6 +276,9 @@ pub fn run() {
}
}
}
+ RunEvent::WindowEvent { event: WindowEvent::Destroyed, label, .. } => {
+ release_window_watches(app_handle, &label);
+ }
RunEvent::WindowEvent { event: WindowEvent::DragDrop(drag_drop_event), label, .. } => {
use tauri::DragDropEvent;
if let DragDropEvent::Drop { paths, .. } = drag_drop_event {
diff --git a/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx b/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx
new file mode 100644
index 0000000000..46bc68ec82
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/DiskLinkBadge.stories.tsx
@@ -0,0 +1,76 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { DiskLinkBadge } from "@app/components/filesPage/DiskLinkBadge";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+/** The healthy and never-on-disk cases are here because they must render nothing;
+ * a story is the cheapest way to keep that honest. */
+const meta: Meta<typeof DiskLinkBadge> = {
+ title: "FilesPage/DiskLinkBadge",
+ component: DiskLinkBadge,
+ parameters: { layout: "padded" },
+};
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+function stub(overrides: Partial<StirlingFileStub>): StirlingFileStub {
+ return {
+ id: "story-file" as FileId,
+ name: "quarterly-report.pdf",
+ type: "application/pdf",
+ size: 1105,
+ lastModified: 1_700_000_000_000,
+ isLeaf: true,
+ originalFileId: "story-file",
+ versionNumber: 1,
+ ...overrides,
+ } as StirlingFileStub;
+}
+
+/** Its original was deleted or moved; this copy is the only one left. */
+export const Orphaned: Story = {
+ args: {
+ file: stub({ orphanedFilePath: "C:\\Users\\ada\\Documents\\report.pdf" }),
+ },
+};
+
+/** Disk moved on while there were unsaved edits here. */
+export const Conflict: Story = {
+ args: {
+ file: stub({
+ localFilePath: "C:\\Users\\ada\\Documents\\report.pdf",
+ diskConflictAt: 1_700_000_500_000,
+ isDirty: true,
+ }),
+ },
+};
+
+/** Icon-only, as it appears in the dense list rows. */
+export const OrphanedCompact: Story = {
+ args: {
+ file: stub({ orphanedFilePath: "C:\\Users\\ada\\Documents\\report.pdf" }),
+ compact: true,
+ },
+};
+
+export const ConflictCompact: Story = {
+ args: {
+ file: stub({
+ localFilePath: "C:\\Users\\ada\\Documents\\report.pdf",
+ diskConflictAt: 1_700_000_500_000,
+ }),
+ compact: true,
+ },
+};
+
+/** Healthy link - renders nothing. */
+export const Linked: Story = {
+ args: {
+ file: stub({ localFilePath: "C:\\Users\\ada\\Documents\\report.pdf" }),
+ },
+};
+
+/** Never came from disk - renders nothing. */
+export const NotFromDisk: Story = {
+ args: { file: stub({}) },
+};
diff --git a/frontend/editor/src/core/components/filesPage/DiskLinkBadge.tsx b/frontend/editor/src/core/components/filesPage/DiskLinkBadge.tsx
new file mode 100644
index 0000000000..c0b94807eb
--- /dev/null
+++ b/frontend/editor/src/core/components/filesPage/DiskLinkBadge.tsx
@@ -0,0 +1,100 @@
+import { useTranslation } from "react-i18next";
+import { Tooltip } from "@mantine/core";
+import LinkOffIcon from "@mui/icons-material/LinkOff";
+import SyncProblemIcon from "@mui/icons-material/SyncProblem";
+import CloudOffIcon from "@mui/icons-material/CloudOff";
+
+import { StirlingFileStub } from "@app/types/fileContext";
+import { diskLinkState } from "@app/services/diskLinkState";
+
+/** Keeps a lost or diverged disk link on screen, where only a transient toast said so.
+ * Silent when healthy or never from disk, so it always means trouble. */
+interface DiskLinkBadgeProps {
+ file: StirlingFileStub;
+ /** Icon-only, for dense rows. */
+ compact?: boolean;
+}
+
+const unavailableHint = {
+ permission: [
+ "filesPage.diskLink.unavailableHintPermission",
+ "Stirling is not allowed to read this location. Grant access in System Settings to pick up changes again.",
+ ],
+ offline: [
+ "filesPage.diskLink.unavailableHintOffline",
+ "The drive or share this file lives on is not connected. Reconnect it to pick up changes again.",
+ ],
+ unknown: [
+ "filesPage.diskLink.unavailableHintUnknown",
+ "This file cannot be reached right now. The copy here is unchanged.",
+ ],
+} as const;
+
+const badgeStyle = {
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "0.25rem",
+ padding: "0.1rem 0.4rem",
+ borderRadius: "999px",
+ fontSize: "0.68rem",
+ fontWeight: 600,
+ textTransform: "uppercase" as const,
+ letterSpacing: "0.04em",
+ lineHeight: 1.2,
+ background:
+ "color-mix(in srgb, var(--mantine-color-yellow-6) 18%, transparent)",
+ color: "var(--color-amber-dark)",
+};
+
+export function DiskLinkBadge({ file, compact = false }: DiskLinkBadgeProps) {
+ const { t } = useTranslation();
+ const state = diskLinkState(file);
+
+ if (state === "none" || state === "linked") return null;
+
+ const config =
+ state === "unavailable"
+ ? {
+ label: t("filesPage.diskLink.unavailable", "Unavailable"),
+ icon: <CloudOffIcon style={{ fontSize: "0.85rem" }} />,
+ tooltip: t(
+ ...unavailableHint[file.diskUnavailableReason ?? "unknown"],
+ ),
+ tone: {
+ background: "var(--c-hover)",
+ color: "var(--c-text-muted)",
+ },
+ }
+ : state === "orphaned"
+ ? {
+ label: t("filesPage.diskLink.orphaned", "Not on disk"),
+ icon: <LinkOffIcon style={{ fontSize: "0.85rem" }} />,
+ tooltip: t(
+ "filesPage.diskLink.orphanedHint",
+ "The original at {{path}} is gone. This copy is only here - saving it will ask for a new location.",
+ { path: file.orphanedFilePath ?? "" },
+ ),
+ }
+ : {
+ label: t("filesPage.diskLink.conflict", "Disk changed"),
+ icon: <SyncProblemIcon style={{ fontSize: "0.85rem" }} />,
+ tooltip: t(
+ "filesPage.diskLink.conflictHint",
+ "The file on disk changed while you had unsaved edits. Your version is shown - saving will overwrite the one on disk.",
+ ),
+ };
+
+ return (
+ <Tooltip label={config.tooltip} withinPortal multiline maw={300}>
+ {/* Icon-only needs its own name, but aria-label is prohibited on a bare
+ span, hence role="img". With the label visible it would shadow the text. */}
+ <span
+ style={{ ...badgeStyle, ...("tone" in config ? config.tone : {}) }}
+ {...(compact ? { role: "img", "aria-label": config.label } : {})}
+ >
+ {config.icon}
+ {!compact && config.label}
+ </span>
+ </Tooltip>
+ );
+}
diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
index ee90caca1e..116ad56586 100644
--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx
@@ -39,6 +39,7 @@ import {
import { useDropTarget } from "@app/components/filesPage/useDropTarget";
import { getFileOrigin } from "@app/components/filesPage/fileOrigin";
import { FileOriginBadge } from "@app/components/filesPage/FileOriginBadge";
+import { DiskLinkBadge } from "@app/components/filesPage/DiskLinkBadge";
import { FolderThumbnail } from "@app/components/filesPage/FolderThumbnail";
import { findFolderIcon } from "@app/components/filesPage/folderIcons";
import { FolderAppearancePicker } from "@app/components/filesPage/FolderAppearancePicker";
@@ -1437,6 +1438,7 @@ const FileCard = React.memo(function FileCard({
)}
<div className="files-page-card-origin">
<FileOriginBadge origin={getFileOrigin(file)} compact />
+ <DiskLinkBadge file={file} compact />
</div>
<FileStateBadge
state={processingState}
@@ -2078,6 +2080,7 @@ const FileRow = React.memo(function FileRow({
)}
</span>
<FileOriginBadge origin={getFileOrigin(file)} compact />
+ <DiskLinkBadge file={file} compact />
<PolicyBadgeRow policies={badges} />
<FileStateBadge
state={processingState}
diff --git a/frontend/editor/src/core/components/pageEditor/PageEditor.tsx b/frontend/editor/src/core/components/pageEditor/PageEditor.tsx
index 08971c0c59..6c34e9f9f6 100644
--- a/frontend/editor/src/core/components/pageEditor/PageEditor.tsx
+++ b/frontend/editor/src/core/components/pageEditor/PageEditor.tsx
@@ -65,6 +65,7 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
updateCurrentPages,
savePersistedDocument,
clearPersistedDocument,
+ contentRevision,
} = usePageEditor();
const [visiblePageIds, setVisiblePageIds] = useState<string[]>([]);
@@ -194,6 +195,13 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
const initialDocument = useInitialPageDocument();
const { document: mergedPdfDocument } = usePageDocument();
+ // The undo manager is created below this hook, so the reset is forwarded
+ // through a ref rather than reordering the two.
+ const clearUndoHistoryRef = useRef<() => void>(() => {});
+ const handleDocumentReplaced = useCallback(() => {
+ clearUndoHistoryRef.current();
+ }, []);
+
const { setEditedDocument, displayDocument, getEditedDocument } =
useEditedDocumentState({
initialDocument,
@@ -202,6 +210,8 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
clearReorderedPages,
fileOrder,
updateCurrentPages,
+ contentRevision,
+ onDocumentReplaced: handleDocumentReplaced,
});
const displayDocumentRef = useRef(displayDocument);
@@ -402,6 +412,7 @@ const PageEditor = ({ onFunctionsReady }: PageEditorProps) => {
} = useUndoManagerState({
setHasUnsavedChanges,
});
+ clearUndoHistoryRef.current = clearUndoHistory;
const {
createRotateCommand,
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts b/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts
index 86473719ab..3fdb2f89dc 100644
--- a/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts
+++ b/frontend/editor/src/core/components/pageEditor/hooks/useEditedDocumentState.ts
@@ -10,6 +10,11 @@ interface UseEditedDocumentStateParams {
clearReorderedPages: () => void;
fileOrder: FileId[];
updateCurrentPages: (pages: PDFPage[] | null) => void;
+ /** Bumps when the bytes behind the open files are replaced. */
+ contentRevision: number;
+ /** Runs when that discards the working document, so the caller can drop the
+ * undo history and the unsaved-changes flag that described it. */
+ onDocumentReplaced: () => void;
}
export const useEditedDocumentState = ({
@@ -19,6 +24,8 @@ export const useEditedDocumentState = ({
clearReorderedPages,
fileOrder,
updateCurrentPages,
+ contentRevision,
+ onDocumentReplaced,
}: UseEditedDocumentStateParams) => {
const [editedDocument, setEditedDocument] = useState<PDFDocument | null>(
null,
@@ -68,6 +75,19 @@ export const useEditedDocumentState = ({
});
}, [editedDocument]);
+ // A disk reload swaps the bytes under an unchanged file id, so the merge
+ // below - which is built to fold in additions and removals while preserving
+ // the user's edits - would carry edits belonging to a document that no longer
+ // exists. The next rebuild is taken whole instead.
+ const replaceOnNextRebuild = useRef(false);
+ const seenContentRevision = useRef(contentRevision);
+ useEffect(() => {
+ if (seenContentRevision.current === contentRevision) return;
+ seenContentRevision.current = contentRevision;
+ replaceOnNextRebuild.current = true;
+ onDocumentReplaced();
+ }, [contentRevision, onDocumentReplaced]);
+
const fileOrderKey = useMemo(() => fileOrder.join(","), [fileOrder]);
const mergedDocSignature = useMemo(() => {
if (!mergedPdfDocument?.pages) return "";
@@ -97,20 +117,25 @@ export const useEditedDocumentState = ({
currentEditedDocument.id !== mergedPdfDocument.id ||
currentEditedDocument.file !== mergedPdfDocument.file ||
currentEditedDocument.name !== mergedPdfDocument.name;
+ // Replacing the bytes can leave the page ids identical - same file, same
+ // page count, different content - so a pending replace is its own reason to
+ // rebuild, not just a modifier on one.
+ const replacing = replaceOnNextRebuild.current;
- if (!signatureChanged && !metadataChanged) return;
+ if (!signatureChanged && !metadataChanged && !replacing) return;
+ replaceOnNextRebuild.current = false;
setEditedDocument((prev) => {
if (!prev) return prev;
let pages = prev.pages;
- if (signatureChanged) {
+ if (signatureChanged || replacing) {
const sourcePages = mergedPdfDocument.pages;
const sourceIds = new Set(sourcePages.map((p) => p.id));
const prevIds = new Set(prev.pages.map((p) => p.id));
const hasOverlap = sourcePages.some((page) => prevIds.has(page.id));
- const shouldResetToMerged = !hasOverlap;
+ const shouldResetToMerged = replacing || !hasOverlap;
const newPages: PDFPage[] = [];
for (const page of sourcePages) {
@@ -221,7 +246,8 @@ export const useEditedDocumentState = ({
}
}
- const shouldReplaceBase = metadataChanged || signatureChanged;
+ const shouldReplaceBase =
+ metadataChanged || signatureChanged || replacing;
const baseDocument = shouldReplaceBase
? {
...mergedPdfDocument,
@@ -240,10 +266,10 @@ export const useEditedDocumentState = ({
};
});
- if (signatureChanged) {
+ if (signatureChanged || replacing) {
lastSyncedSignatureRef.current = mergedDocSignature;
}
- }, [mergedPdfDocument, fileOrderKey, mergedDocSignature]);
+ }, [mergedPdfDocument, fileOrderKey, mergedDocSignature, contentRevision]);
const displayDocument = editedDocument || initialDocument;
diff --git a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
index 7b81278a53..370cb32188 100644
--- a/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
+++ b/frontend/editor/src/core/components/pageEditor/hooks/usePageEditorExport.ts
@@ -1,6 +1,7 @@
import { Dispatch, SetStateAction, useCallback } from "react";
import type { useFileActions, useFileState } from "@app/contexts/FileContext";
+import { inheritedSourceLink } from "@app/contexts/file/storedFileReconciler";
import { documentManipulationService } from "@app/services/documentManipulationService";
import { pdfExportService } from "@app/services/pdfExportService";
import { exportProcessedDocumentsToFiles } from "@app/services/pdfExportHelpers";
@@ -323,6 +324,15 @@ export const usePageEditorExport = ({
// Store source file IDs before adding new files
const sourceFileIds = [...selectedFileIds];
+ // Read before the removal below, which takes the source out of the
+ // workbench and out of storage: a read afterwards finds nothing, and the
+ // file this produces silently loses its link to the one it came from.
+ const sourceStub =
+ sourceFileIds.length === 1
+ ? selectors.getStirlingFileStub(sourceFileIds[0])
+ : undefined;
+ const inherited = sourceStub ? inheritedSourceLink(sourceStub) : {};
+
// Clear all cached page state to prevent stale data from being merged
clearPersistedDocument();
updateCurrentPages(null);
@@ -344,19 +354,11 @@ export const usePageEditorExport = ({
actions.setSelectedFiles(newStirlingFiles.map((file) => file.fileId));
}
- if (sourceFileIds.length === 1 && newStirlingFiles.length === 1) {
- const sourceStub = selectors.getStirlingFileStub(sourceFileIds[0]);
- if (sourceStub?.localFilePath) {
- actions.updateStirlingFileStub(newStirlingFiles[0].fileId, {
- localFilePath: sourceStub.localFilePath,
- isDirty: true,
- });
- }
- }
-
- // Remove source files from context
- if (sourceFileIds.length > 0) {
- await actions.removeFiles(sourceFileIds, true);
+ if (newStirlingFiles.length === 1 && Object.keys(inherited).length > 0) {
+ actions.updateStirlingFileStub(newStirlingFiles[0].fileId, {
+ ...inherited,
+ isDirty: true,
+ });
}
setHasUnsavedChanges(false);
diff --git a/frontend/editor/src/core/components/shared/DiskConflictModal.stories.tsx b/frontend/editor/src/core/components/shared/DiskConflictModal.stories.tsx
new file mode 100644
index 0000000000..32f4145970
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/DiskConflictModal.stories.tsx
@@ -0,0 +1,37 @@
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { DiskConflictModal } from "@app/components/shared/DiskConflictModal";
+
+/** The queued variant matters as much as the single one: a watcher burst can
+ * raise several at once, and the count is the only cue that more follow. */
+const meta: Meta<typeof DiskConflictModal> = {
+ title: "Shared/DiskConflictModal",
+ component: DiskConflictModal,
+ parameters: { layout: "centered" },
+};
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const Default: Story = {
+ args: {
+ opened: true,
+ fileName: "quarterly-report.pdf",
+ remainingCount: 0,
+ },
+};
+
+export const MoreQueued: Story = {
+ args: {
+ opened: true,
+ fileName: "quarterly-report.pdf",
+ remainingCount: 2,
+ },
+};
+
+export const LongFileName: Story = {
+ args: {
+ opened: true,
+ fileName:
+ "2026-q3-consolidated-financial-statements-and-appendices-final-v7.pdf",
+ remainingCount: 0,
+ },
+};
diff --git a/frontend/editor/src/core/components/shared/DiskConflictModal.tsx b/frontend/editor/src/core/components/shared/DiskConflictModal.tsx
new file mode 100644
index 0000000000..4deb519661
--- /dev/null
+++ b/frontend/editor/src/core/components/shared/DiskConflictModal.tsx
@@ -0,0 +1,77 @@
+import { Modal, Stack, Text, Group } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+
+import { Button } from "@app/ui/Button";
+import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from "@app/styles/zIndex";
+
+interface DiskConflictModalProps {
+ opened: boolean;
+ fileName?: string;
+ /** Conflicts still queued behind this one. */
+ remainingCount: number;
+ onKeepMine: () => void;
+ onUseDisk: () => void;
+}
+
+/** Two real versions of a document exist, so the user picks one. No dismiss:
+ * whichever way this closes, one of the two versions is being discarded. */
+export function DiskConflictModal({
+ opened,
+ fileName,
+ remainingCount,
+ onKeepMine,
+ onUseDisk,
+}: DiskConflictModalProps) {
+ const { t } = useTranslation();
+
+ return (
+ <Modal
+ opened={opened}
+ onClose={onKeepMine}
+ title={t("desktopFileLink.conflict.title", "File changed on disk")}
+ centered
+ size="md"
+ withCloseButton={false}
+ closeOnClickOutside={false}
+ closeOnEscape={false}
+ zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
+ >
+ <Stack gap="md">
+ <Text fw={600} ta="center">
+ {fileName}
+ </Text>
+ <Text c="dimmed">
+ {t(
+ "desktopFileLink.conflict.prompt",
+ "This file changed on disk while you had unsaved changes here. Only one version can be kept.",
+ )}
+ </Text>
+ {remainingCount > 0 && (
+ <Text c="dimmed" size="sm" ta="center">
+ {t(
+ "desktopFileLink.conflict.remaining",
+ "{{count}} more to review",
+ {
+ count: remainingCount,
+ },
+ )}
+ </Text>
+ )}
+ <Group grow>
+ <Button variant="secondary" onClick={onUseDisk}>
+ {t("desktopFileLink.conflict.useDisk", "Use the disk version")}
+ </Button>
+ <Button onClick={onKeepMine}>
+ {t("desktopFileLink.conflict.keepMine", "Keep my changes")}
+ </Button>
+ </Group>
+ <Text c="dimmed" size="xs" ta="center">
+ {t(
+ "desktopFileLink.conflict.hint",
+ "Keeping your changes overwrites the file on disk when you next save.",
+ )}
+ </Text>
+ </Stack>
+ </Modal>
+ );
+}
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
index f95da82024..8aaae3bf70 100644
--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx
@@ -31,7 +31,13 @@ import type {
SignatureOverlayAPI,
} from "@app/components/viewer/viewerTypes";
import { createStirlingFilesAndStubs } from "@app/services/fileStubHelpers";
-import { isStirlingFile, getFormFillFileId } from "@app/types/fileContext";
+import {
+ isStirlingFile,
+ getFormFillFileId,
+ type StirlingFile,
+ documentBytesReplaced,
+ type DocumentIdentity,
+} from "@app/types/fileContext";
import { useViewerWorkbenchBarButtons } from "@app/components/viewer/useViewerWorkbenchBarButtons";
import { StampPlacementOverlay } from "@app/components/viewer/StampPlacementOverlay";
import {
@@ -67,6 +73,13 @@ export interface EmbedPdfViewerProps {
portfolioPinned?: boolean;
}
+/** Cache identity of a document, not of the file holding it: a disk reload
+ * replaces the bytes under an unchanged fileId, and an outline cached under the
+ * id alone would then describe a document nobody is looking at. Preload keys are
+ * matched against this, so both call sites must derive it the same way. */
+const documentCacheKey = (file: StirlingFile): string =>
+ `${file.fileId}|${file.quickKey}`;
+
const EmbedPdfViewerContent = ({
sidebarsVisible: _sidebarsVisible,
setSidebarsVisible: _setSidebarsVisible,
@@ -283,16 +296,19 @@ const EmbedPdfViewerContent = ({
return null;
}, [previewFile, activeFiles, activeFileId]);
- // Namespaced identifier for form-fill state; keep this aligned with FormFill.
+ // Identity of the bytes: the viewer's mount key, its blob URL and form-fill
+ // state all have to turn over when a disk reload swaps the file under an
+ // unchanged fileId. Keep aligned with FormFill.
const currentFileId = React.useMemo(
() => getFormFillFileId(currentFile),
[currentFile],
);
- // Stable id — avoids blob URL churn when FileContext recreates file objects each render.
+ // The workbench record to act on. Bare id, not the content key above: the
+ // consume/undo paths below pass it back as a FileId.
const currentFileStableId =
currentFile && isStirlingFile(currentFile) ? currentFile.fileId : null;
- const fileWithUrl = useFileWithUrl(currentFile, currentFileStableId);
+ const fileWithUrl = useFileWithUrl(currentFile, currentFileId);
// Determine the effective file to display
const effectiveFile = React.useMemo(() => {
@@ -316,7 +332,7 @@ const EmbedPdfViewerContent = ({
const bookmarkCacheKey = React.useMemo(() => {
if (currentFile && isStirlingFile(currentFile)) {
- return currentFile.fileId;
+ return documentCacheKey(currentFile);
}
if (previewFile) {
@@ -343,12 +359,9 @@ const EmbedPdfViewerContent = ({
}
return activeFiles
- .map((file) => {
- if (isStirlingFile(file)) {
- return file.fileId;
- }
- return undefined;
- })
+ .map((file) =>
+ isStirlingFile(file) ? documentCacheKey(file) : undefined,
+ )
.filter(Boolean) as string[];
}, [activeFiles, previewFile, bookmarkCacheKey]);
@@ -524,6 +537,31 @@ const EmbedPdfViewerContent = ({
getScrollState,
]);
+ // Accepting a disk reload swaps the bytes under an unchanged fileId, which
+ // remounts the inner viewer with a clean history but leaves these flags
+ // describing edits that no longer exist: every later disk change then reads as
+ // a conflict, and navigation keeps warning about work already discarded.
+ const documentIdentityRef = useRef<DocumentIdentity | null>(null);
+ useEffect(() => {
+ const previous = documentIdentityRef.current;
+ const current =
+ currentFileStableId && currentFileId
+ ? { id: currentFileStableId, key: currentFileId }
+ : null;
+ documentIdentityRef.current = current;
+
+ if (!documentBytesReplaced(previous, current)) return;
+
+ hasAnnotationChangesRef.current = false;
+ setHasUnsavedChanges(false);
+ setRedactionsApplied(false);
+ }, [
+ currentFileStableId,
+ currentFileId,
+ setHasUnsavedChanges,
+ setRedactionsApplied,
+ ]);
+
// Watch the annotation history API to detect when the document becomes "dirty".
// We treat any change that makes the history undoable as unsaved changes until
// the user explicitly applies them via applyChanges.
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index 4f6d1f8a5b..086d2487cb 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -42,6 +42,7 @@ import { createFileSelectors } from "@app/contexts/file/fileSelectors";
import {
addFiles,
addStirlingFileStubs,
+ reconcileOpenFilesAt,
consumeFiles,
undoConsumeFiles,
createFileActions,
@@ -391,6 +392,12 @@ function FileContextInner({
[],
);
+ const reconcileOpenFilesAction = useCallback(
+ (locations: string[]) =>
+ reconcileOpenFilesAt(locations, stateRef, filesRef, lifecycleManager),
+ [],
+ );
+
// Action creators
const baseActions = useMemo(() => createFileActions(dispatch), []);
@@ -641,6 +648,7 @@ function FileContextInner({
addFiles: addRawFiles,
addFilesWithOptions,
addStirlingFileStubs: addStirlingFileStubsAction,
+ reconcileOpenFiles: reconcileOpenFilesAction,
removeFiles: async (fileIds: FileId[], deleteFromStorage?: boolean) => {
// Remove from memory and cleanup resources
lifecycleManager.removeFiles(fileIds, stateRef);
@@ -707,6 +715,7 @@ function FileContextInner({
baseActions,
addRawFiles,
addStirlingFileStubsAction,
+ reconcileOpenFilesAction,
lifecycleManager,
setHasUnsavedChanges,
consumeFilesWrapper,
diff --git a/frontend/editor/src/core/contexts/FilesPageContext.tsx b/frontend/editor/src/core/contexts/FilesPageContext.tsx
index ac03a475b6..bfb771b9de 100644
--- a/frontend/editor/src/core/contexts/FilesPageContext.tsx
+++ b/frontend/editor/src/core/contexts/FilesPageContext.tsx
@@ -25,6 +25,7 @@ import { writeIntoMount } from "@app/services/mountWrites";
import { folderSyncService } from "@app/services/folderSyncService";
import { uploadHistoryChain } from "@app/services/serverStorageUpload";
import { reconcileServerFiles } from "@app/services/fileSyncService";
+import { pruneMissingRecentFiles } from "@app/services/pruneMissingRecentFiles";
import {
deleteServerFile,
type DeleteScope,
@@ -34,6 +35,7 @@ import {
useIndexedDBRevision,
} from "@app/contexts/IndexedDBContext";
import { useFileActions } from "@app/contexts/file/fileHooks";
+import { useDiskLinkReconcile } from "@app/hooks/useDiskLinkReconcile";
import { useFolders } from "@app/contexts/FolderContext";
import { useAppConfig } from "@app/contexts/AppConfigContext";
import { useAuth } from "@app/auth/UseSession";
@@ -161,6 +163,10 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {
const { config: appConfig } = useAppConfig();
const { isAnonymous } = useAuth();
+ // Refs inside, so refresh isn't recreated (and re-run) every time the
+ // workbench changes - it only needs whichever files are open when it runs.
+ const { openFileIdsRef, onOpenFilesDetached } = useDiskLinkReconcile();
+
const [allFiles, setAllFiles] = useState<StirlingFileStub[]>([]);
const [loading, setLoading] = useState(true);
// Generation counter to drop stale reconcile results when a second refresh
@@ -183,7 +189,18 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {
const localStubs = await fileStorage.getAllStirlingFileStubs();
// Bail if a newer refresh started while IDB was reading.
if (gen !== refreshGenRef.current) return;
- const localLeaf = localStubs.filter((s) => s.isLeaf !== false);
+ // A file the user deleted outside the app must not be offered here, so
+ // reconcile before anything is rendered. Leaves only: every version behind
+ // them shares a source, and checking all of them multiplies the work by
+ // the length of the history.
+ const localLeaf = await pruneMissingRecentFiles(
+ localStubs.filter((s) => s.isLeaf !== false),
+ {
+ openFileIds: new Set(openFileIdsRef.current),
+ onOpenFilesDetached,
+ },
+ );
+ if (gen !== refreshGenRef.current) return;
// Render the cache immediately while the server fetch is in flight.
setAllFiles(localLeaf);
const merged = await reconcileServerFiles(localLeaf, {
@@ -205,7 +222,14 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {
// Only the latest refresh should clear the loading state.
if (gen === refreshGenRef.current) setLoading(false);
}
- }, [setFoldersError, storageEnabled, shareLinksEnabled, isAnonymous]);
+ }, [
+ setFoldersError,
+ storageEnabled,
+ shareLinksEnabled,
+ isAnonymous,
+ openFileIdsRef,
+ onOpenFilesDetached,
+ ]);
useEffect(() => {
void refresh();
diff --git a/frontend/editor/src/core/contexts/NavigationContext.tsx b/frontend/editor/src/core/contexts/NavigationContext.tsx
index fed0daebb8..85c51f7701 100644
--- a/frontend/editor/src/core/contexts/NavigationContext.tsx
+++ b/frontend/editor/src/core/contexts/NavigationContext.tsx
@@ -9,6 +9,7 @@ import React, {
import { WorkbenchType, getDefaultWorkbench } from "@app/types/workbench";
import { ToolId, isValidToolId } from "@app/types/toolId";
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
+import { registerUnsavedWorkChecker } from "@app/services/unsavedWork";
/**
* NavigationContext - Complete navigation management system
@@ -281,6 +282,19 @@ export const NavigationProvider: React.FC<{
dispatch({ type: "SET_UNSAVED_CHANGES", payload: { hasChanges } });
}, []);
+ // Same answer the navigation guard uses, published where the disk reconciliation
+ // can reach it: without this an external edit replaces the bytes under an open
+ // page editor, annotation or redaction session with no conflict prompt.
+ React.useEffect(
+ () =>
+ registerUnsavedWorkChecker(
+ () =>
+ unsavedChangesCheckerRef.current?.() === true ||
+ state.hasUnsavedChanges,
+ ),
+ [state.hasUnsavedChanges],
+ );
+
const registerUnsavedChangesChecker = useCallback(
(checker: () => boolean) => {
unsavedChangesCheckerRef.current = checker;
diff --git a/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsx b/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsx
new file mode 100644
index 0000000000..9e5f78b0bf
--- /dev/null
+++ b/frontend/editor/src/core/contexts/NavigationContext.unsavedWork.test.tsx
@@ -0,0 +1,73 @@
+import React from "react";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { render, act } from "@testing-library/react";
+
+vi.mock("@app/contexts/ToolRegistryContext", () => ({
+ useToolRegistry: () => ({ allTools: {} }),
+}));
+
+import {
+ NavigationProvider,
+ useNavigation,
+} from "@app/contexts/NavigationContext";
+import { hasUnsavedWork, __resetUnsavedWork } from "@app/services/unsavedWork";
+
+// The bug this pins: every editor marks itself dirty on NavigationContext, while
+// the disk reconciliation read FileContext's own flag - which nothing sets. An
+// external edit therefore replaced the bytes under an open editor with no prompt.
+
+let editor: ReturnType<typeof useNavigation>;
+
+function OpenEditor() {
+ editor = useNavigation();
+ return null;
+}
+
+function renderEditor() {
+ return render(
+ <NavigationProvider>
+ <OpenEditor />
+ </NavigationProvider>,
+ );
+}
+
+beforeEach(() => {
+ __resetUnsavedWork();
+ vi.spyOn(console, "log").mockImplementation(() => {});
+});
+afterEach(() => vi.restoreAllMocks());
+
+describe("the dirty state the disk reconciliation reads", () => {
+ it("is clean while no editor has touched anything", () => {
+ renderEditor();
+ expect(hasUnsavedWork()).toBe(false);
+ });
+
+ it("reports edits an editor made but no version has captured", () => {
+ renderEditor();
+ act(() => editor.setHasUnsavedChanges(true));
+ expect(hasUnsavedWork()).toBe(true);
+ });
+
+ it("reports edits held only by a registered checker", () => {
+ // How PageEditor and FormFill answer: their dirty state lives in their own
+ // undo stack, and never reaches the reducer until navigation asks.
+ renderEditor();
+ act(() => editor.registerUnsavedChangesChecker(() => true));
+ expect(hasUnsavedWork()).toBe(true);
+ });
+
+ it("is clean again once the editor commits or closes", () => {
+ renderEditor();
+ act(() => editor.setHasUnsavedChanges(true));
+ act(() => editor.setHasUnsavedChanges(false));
+ expect(hasUnsavedWork()).toBe(false);
+ });
+
+ it("is clean once the provider unmounts", () => {
+ const view = renderEditor();
+ act(() => editor.setHasUnsavedChanges(true));
+ view.unmount();
+ expect(hasUnsavedWork()).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx b/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
new file mode 100644
index 0000000000..a9d8a9669a
--- /dev/null
+++ b/frontend/editor/src/core/contexts/PageEditorContentRevision.test.tsx
@@ -0,0 +1,106 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { renderHook, act } from "@testing-library/react";
+import type { ReactNode } from "react";
+import type { FileId, StirlingFileStub } from "@app/types/fileContext";
+
+const fileState = {
+ state: {
+ files: {
+ ids: [] as FileId[],
+ byId: {} as Record<FileId, Partial<StirlingFileStub>>,
+ },
+ },
+};
+
+vi.mock("@app/contexts/FileContext", () => ({
+ useFileActions: () => ({ actions: {} }),
+ useFileState: () => fileState,
+}));
+
+vi.mock("@app/contexts/NavigationContext", () => ({
+ useNavigationState: () => ({ currentMode: "pageEditor" }),
+}));
+
+const { PageEditorProvider, usePageEditor } =
+ await import("@app/contexts/PageEditorContext");
+
+const stub = (size: number, lastModified: number) =>
+ ({ size, lastModified }) as Partial<StirlingFileStub>;
+
+const setFiles = (entries: [string, Partial<StirlingFileStub>][]) => {
+ fileState.state = {
+ files: {
+ ids: entries.map(([id]) => id as FileId),
+ byId: Object.fromEntries(entries) as Record<
+ FileId,
+ Partial<StirlingFileStub>
+ >,
+ },
+ };
+};
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <PageEditorProvider>{children}</PageEditorProvider>
+);
+
+describe("PageEditorContext contentRevision", () => {
+ beforeEach(() => setFiles([["A", stub(100, 1)]]));
+
+ it("does not bump when another file is added", () => {
+ const view = renderHook(() => usePageEditor(), { wrapper });
+ const before = view.result.current.contentRevision;
+
+ act(() => {
+ setFiles([
+ ["A", stub(100, 1)],
+ ["B", stub(200, 2)],
+ ]);
+ view.rerender();
+ });
+
+ expect(view.result.current.contentRevision).toBe(before);
+ });
+
+ it("does not bump when a file is removed", () => {
+ setFiles([
+ ["A", stub(100, 1)],
+ ["B", stub(200, 2)],
+ ]);
+ const view = renderHook(() => usePageEditor(), { wrapper });
+ const before = view.result.current.contentRevision;
+
+ act(() => {
+ setFiles([["A", stub(100, 1)]]);
+ view.rerender();
+ });
+
+ expect(view.result.current.contentRevision).toBe(before);
+ });
+
+ it("bumps when the bytes behind an open file are replaced", () => {
+ const view = renderHook(() => usePageEditor(), { wrapper });
+ const before = view.result.current.contentRevision;
+
+ act(() => {
+ setFiles([["A", stub(555, 9)]]);
+ view.rerender();
+ });
+
+ expect(view.result.current.contentRevision).toBe(before + 1);
+ });
+
+ it("still bumps on a replacement that arrives alongside an addition", () => {
+ const view = renderHook(() => usePageEditor(), { wrapper });
+ const before = view.result.current.contentRevision;
+
+ act(() => {
+ setFiles([
+ ["A", stub(555, 9)],
+ ["B", stub(200, 2)],
+ ]);
+ view.rerender();
+ });
+
+ expect(view.result.current.contentRevision).toBe(before + 1);
+ });
+});
diff --git a/frontend/editor/src/core/contexts/PageEditorContext.tsx b/frontend/editor/src/core/contexts/PageEditorContext.tsx
index 330ec8fb08..d58439f512 100644
--- a/frontend/editor/src/core/contexts/PageEditorContext.tsx
+++ b/frontend/editor/src/core/contexts/PageEditorContext.tsx
@@ -143,6 +143,11 @@ interface PageEditorContextValue {
persistedDocumentSignature: string | null;
savePersistedDocument: (document: PDFDocument, signature: string) => void;
clearPersistedDocument: () => void;
+ /** Bumps whenever the bytes behind the open files are replaced under an
+ * unchanged file id, which is what a disk reload does. Anything laid out
+ * from those bytes has to start over rather than merge into what replaced
+ * them. */
+ contentRevision: number;
}
const PageEditorContext = createContext<PageEditorContextValue | undefined>(
@@ -234,7 +239,23 @@ export function PageEditorProvider({ children }: PageEditorProviderProps) {
.join(",");
}, [state.files.ids, state.files.byId]);
+ // Bytes can be replaced under an unchanged id and version - reconciling a
+ // record with its source does exactly that - and the laid-out document would
+ // then describe pages that no longer exist. Keyed per id rather than joined:
+ // a join also changes when the file set does, and adding a file would then
+ // read as every open document being replaced.
+ const fileContentKeys = useMemo(() => {
+ const keys = new Map<FileId, string>();
+ for (const id of state.files.ids) {
+ const stub = state.files.byId[id];
+ keys.set(id, `${stub?.size ?? 0}:${stub?.lastModified ?? 0}`);
+ }
+ return keys;
+ }, [state.files.ids, state.files.byId]);
+
const prevFileContextSignature = useRef<string | null>(null);
+ const prevFileContentKeys = useRef<Map<FileId, string> | null>(null);
+ const [contentRevision, setContentRevision] = useState(0);
const haveFileIdSetsChanged = (prevIds: FileId[], currentIds: FileId[]) => {
if (prevIds.length !== currentIds.length) {
return true;
@@ -251,9 +272,26 @@ export function PageEditorProvider({ children }: PageEditorProviderProps) {
const currentFileIds = state.files.ids;
const prevFileIds = prevFileContextIdsRef.current;
const idsChanged = haveFileIdSetsChanged(prevFileIds, currentFileIds);
+ const previousContentKeys = prevFileContentKeys.current;
+ // Only an id carried over from the previous set can have had its bytes
+ // replaced. One that arrived or left is a file-set change, which the merge
+ // below folds in without discarding the edits on everything else.
+ const contentChanged =
+ previousContentKeys !== null &&
+ currentFileIds.some((id) => {
+ const previousKey = previousContentKeys.get(id);
+ return (
+ previousKey !== undefined && previousKey !== fileContentKeys.get(id)
+ );
+ });
+ prevFileContentKeys.current = fileContentKeys;
+ // Clearing the persisted document only invalidates the cache. The live
+ // document is held by the editor and has to be told to start over too.
+ if (contentChanged) setContentRevision((revision) => revision + 1);
if (
!idsChanged &&
+ !contentChanged &&
prevFileContextSignature.current === fileContextSignature
) {
return;
@@ -262,20 +300,26 @@ export function PageEditorProvider({ children }: PageEditorProviderProps) {
const previousSignature = prevFileContextSignature.current;
prevFileContextSignature.current = fileContextSignature;
- if (!idsChanged) {
+ if (!idsChanged && !contentChanged) {
// Signature changed due to metadata/version updates but file set is unchanged.
return;
}
console.log(
- "[PageEditorContext] File signature changed (IDs/versions changed), clearing persisted document:",
+ "[PageEditorContext] Files changed, clearing persisted document:",
{
+ reason: idsChanged ? "file set" : "content",
prev: previousSignature?.substring(0, 50),
current: fileContextSignature.substring(0, 50),
},
);
clearPersistedDocument();
- }, [fileContextSignature, clearPersistedDocument, state.files.ids]);
+ }, [
+ fileContextSignature,
+ fileContentKeys,
+ clearPersistedDocument,
+ state.files.ids,
+ ]);
// Keep a ref to always read latest state in stable callbacks
const stateRef = useRef(state);
@@ -513,8 +557,10 @@ export function PageEditorProvider({ children }: PageEditorProviderProps) {
persistedDocumentSignature,
savePersistedDocument,
clearPersistedDocument,
+ contentRevision,
}),
[
+ contentRevision,
currentPages,
updateCurrentPages,
reorderedPages,
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 72be6a7cd8..341f0d718a 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -25,6 +25,12 @@ import {
reportBulkAddProgress,
clearBulkAddProgress,
} from "@app/services/bulkAddProgress";
+import {
+ type ReconcilePort,
+ reconcileBeforeOpen,
+ reconcileOpenFiles,
+ sourceLinkForNewFile,
+} from "@app/contexts/file/storedFileReconciler";
const DEBUG = process.env.NODE_ENV === "development";
/** How long a file may sit unhydrated before the console says so. Reporting only:
* the read is never abandoned, because large files legitimately take time. */
@@ -225,6 +231,11 @@ export function createChildStub(
// Mark as dirty if parent has a localFilePath (modified file not yet saved to disk)
isDirty: parentStub.localFilePath ? true : undefined,
+
+ // Disk markers describe the parent's relationship with disk at conflict
+ // time; inheriting diskConflictAt also suppresses the child's own prompt.
+ diskConflictAt: undefined,
+ diskReloadedAt: undefined,
};
if (DEBUG) {
@@ -487,34 +498,7 @@ export async function addFiles(
}
}
- // Check for pending file path mapping from Tauri file dialog (desktop only)
- try {
- const { pendingFilePathMappings } =
- await import("@app/services/pendingFilePathMappings");
- // DEBUG-gated: these fire per file, and a 300-file drop emitting 4 log
- // lines each measurably stalls the main thread with devtools open.
- if (DEBUG) {
- console.log(
- `[FileActions] Checking for localFilePath mapping for quickKey: ${quickKey}`,
- );
- }
- const localFilePath = pendingFilePathMappings.get(quickKey);
- if (localFilePath) {
- if (DEBUG)
- console.log(
- `[FileActions] ✓ Found localFilePath: ${localFilePath}`,
- );
- fileStub.localFilePath = localFilePath;
- pendingFilePathMappings.delete(quickKey); // Clean up after use
- }
- } catch (error) {
- if (DEBUG)
- console.log(
- "[FileActions] Could not check for localFilePath:",
- error,
- );
- // FileManagerContext may not be available in all contexts
- }
+ Object.assign(fileStub, await sourceLinkForNewFile(quickKey));
// Store insertion position if provided
if (options.insertAfterPageId !== undefined) {
@@ -783,14 +767,22 @@ export async function undoConsumeFiles(
}
// Restore isLeaf in IDB — modal reads IDB directly and misses files if isLeaf=false.
+ // isDirty rides along: the dispatch above only reaches memory, and a restored
+ // version that reads clean on the next open is reloaded from the disk copy the
+ // undone operation wrote, putting the undone bytes back for good.
await Promise.all(
- inputStirlingFileStubs.map((stub) =>
- fileStorage.markFileAsLeaf(stub.id).catch((error) => {
- console.warn(
- `📄 undoConsumeFiles: Failed to restore isLeaf for ${stub.id}:`,
- error,
- );
- }),
+ stubsWithDirtyMarked.map((stub) =>
+ fileStorage
+ .updateFileMetadata(stub.id, {
+ isLeaf: true,
+ ...(stub.isDirty ? { isDirty: true } : {}),
+ })
+ .catch((error) => {
+ console.warn(
+ `📄 undoConsumeFiles: Failed to restore isLeaf for ${stub.id}:`,
+ error,
+ );
+ }),
),
);
@@ -817,6 +809,79 @@ export async function undoConsumeFiles(
* Action factory functions
*/
+/** Regenerate page metadata and thumbnails for a file whose bytes are current.
+ * Queued, because parsing several PDFs at once is what the limit bounds. */
+function hydrateMetadataFor(
+ fileId: FileId,
+ stirlingFile: StirlingFile,
+ stateRef: React.MutableRefObject<FileContextState>,
+ lifecycleManager: FileLifecycleManager,
+): void {
+ if (!stirlingFile.type.startsWith("application/pdf")) return;
+ scheduleMetadataHydration(async () => {
+ const processedFileMetadata =
+ await generateProcessedFileMetadata(stirlingFile);
+ if (!processedFileMetadata) return;
+
+ const updates: Partial<StirlingFileStub> = {
+ processedFile: processedFileMetadata,
+ };
+
+ // Update thumbnail only if current stub doesn't have one
+ const currentStub = stateRef.current.files.byId[fileId];
+ if (!currentStub?.thumbnailUrl && processedFileMetadata.thumbnailUrl) {
+ updates.thumbnailUrl = processedFileMetadata.thumbnailUrl;
+ if (processedFileMetadata.thumbnailUrl.startsWith("blob:")) {
+ lifecycleManager.trackBlobUrl(processedFileMetadata.thumbnailUrl);
+ }
+ }
+
+ lifecycleManager.updateStirlingFileStub(fileId, updates, stateRef);
+ });
+}
+
+/** Hand the reconciler the workbench, so it can settle a record in place
+ * without core knowing what it settles it against. */
+function reconcilePort(
+ stateRef: React.MutableRefObject<FileContextState>,
+ filesRef: React.MutableRefObject<Map<FileId, File>>,
+ lifecycleManager: FileLifecycleManager,
+): ReconcilePort {
+ return {
+ getStub: (fileId) => stateRef.current.files.byId[fileId],
+ listStubs: () => Object.values(stateRef.current.files.byId),
+ putFile: (fileId, file) =>
+ filesRef.current.set(fileId, createStirlingFile(file, fileId)),
+ updateStub: (fileId, updates) =>
+ lifecycleManager.updateStirlingFileStub(fileId, updates, stateRef),
+ dropFile: (fileId) => lifecycleManager.removeFiles([fileId], stateRef),
+ reprocessFile: (fileId) => {
+ const file = filesRef.current.get(fileId);
+ if (file) {
+ hydrateMetadataFor(
+ fileId,
+ createStirlingFile(file, fileId),
+ stateRef,
+ lifecycleManager,
+ );
+ }
+ },
+ };
+}
+
+/** Tell the reconciler that something changed at these source locations. */
+export async function reconcileOpenFilesAt(
+ locations: string[],
+ stateRef: React.MutableRefObject<FileContextState>,
+ filesRef: React.MutableRefObject<Map<FileId, File>>,
+ lifecycleManager: FileLifecycleManager,
+): Promise<void> {
+ await reconcileOpenFiles(
+ locations,
+ reconcilePort(stateRef, filesRef, lifecycleManager),
+ );
+}
+
/**
* Add files using existing StirlingFileStubs from storage - preserves all metadata
* Use this when loading files that already exist in storage (FileManager, etc.)
@@ -880,33 +945,8 @@ export async function addStirlingFileStubs(
// Load File object and hydrate metadata in background (non-blocking)
const fileId = stub.id;
- // Regenerate page metadata + thumbnails. Queued, because parsing several
- // PDFs at once is what the concurrency limit exists to bound.
- const scheduleMetadataFor = (stirlingFile: StirlingFile): void => {
- scheduleMetadataHydration(async () => {
- const processedFileMetadata =
- await generateProcessedFileMetadata(stirlingFile);
- if (!processedFileMetadata) return;
-
- const updates: Partial<StirlingFileStub> = {
- processedFile: processedFileMetadata,
- };
-
- // Update thumbnail only if current stub doesn't have one
- const currentStub = stateRef.current.files.byId[fileId];
- if (
- !currentStub?.thumbnailUrl &&
- processedFileMetadata.thumbnailUrl
- ) {
- updates.thumbnailUrl = processedFileMetadata.thumbnailUrl;
- if (processedFileMetadata.thumbnailUrl.startsWith("blob:")) {
- lifecycleManager.trackBlobUrl(processedFileMetadata.thumbnailUrl);
- }
- }
-
- lifecycleManager.updateStirlingFileStub(fileId, updates, stateRef);
- });
- };
+ const scheduleMetadataFor = (stirlingFile: StirlingFile): void =>
+ hydrateMetadataFor(fileId, stirlingFile, stateRef, lifecycleManager);
// Load and publish the File, ahead of any parsing. NOT queued: whether a
// file opens at all must not wait on other files' parses.
@@ -920,9 +960,22 @@ export async function addStirlingFileStubs(
),
STALLED_LOAD_MS,
);
- const stirlingFile = await fileStorage
- .getStirlingFile(fileId)
- .finally(() => clearTimeout(stall));
+ // A record can be a cache of something outside the app, so settle it
+ // BEFORE serving it, or an edit made out there stays invisible and a
+ // file deleted out there still opens.
+ const port = reconcilePort(stateRef, filesRef, lifecycleManager);
+ const decision = await reconcileBeforeOpen(stub, port);
+ if (decision.drop) {
+ lifecycleManager.removeFiles([fileId], stateRef);
+ clearTimeout(stall);
+ return;
+ }
+ // Bytes the reconciler holds win over the stored copy.
+ const stirlingFile = await (
+ decision.file
+ ? Promise.resolve(createStirlingFile(decision.file, fileId))
+ : fileStorage.getStirlingFile(fileId)
+ ).finally(() => clearTimeout(stall));
if (!stirlingFile) {
// A row with no bytes renders empty and its clicks look dead, so take it
// back out. Storage keeps the record; fileStorage has said why.
@@ -934,19 +987,26 @@ export async function addStirlingFileStubs(
}
filesRef.current.set(fileId, stirlingFile);
- // filesRef is a ref, so the selectors gating the workbench only see the
- // file once something dispatches. Parsing it can't be a precondition.
- lifecycleManager.updateStirlingFileStub(fileId, {}, stateRef);
+
+ // Workbench selectors only see the file once something dispatches, and
+ // updateStirlingFileStub drops updates for a file not yet in filesRef,
+ // so this must follow the write above - and must happen even when the
+ // reconciler had nothing to say, or the bytes never become visible.
+ lifecycleManager.updateStirlingFileStub(
+ fileId,
+ decision.updates ?? {},
+ stateRef,
+ );
+ decision.afterPublish?.();
const needsProcessing =
+ // Bytes just changed underneath us, so whatever was cached is stale.
+ decision.contentReplaced === true ||
!stub.processedFile ||
!stub.processedFile.pages ||
stub.processedFile.pages.length === 0 ||
stub.processedFile.totalPages !== stub.processedFile.pages.length;
- if (
- stirlingFile.type.startsWith("application/pdf") &&
- needsProcessing
- ) {
+ if (needsProcessing) {
scheduleMetadataFor(stirlingFile);
}
})().catch((error) =>
diff --git a/frontend/editor/src/core/contexts/file/lifecycle.ts b/frontend/editor/src/core/contexts/file/lifecycle.ts
index 4b3d639ad9..478199b610 100644
--- a/frontend/editor/src/core/contexts/file/lifecycle.ts
+++ b/frontend/editor/src/core/contexts/file/lifecycle.ts
@@ -9,6 +9,11 @@ import {
StirlingFileStub,
ProcessedFilePage,
} from "@app/types/fileContext";
+import {
+ forgetFile,
+ noteFileSaved,
+ persistedSourceFields,
+} from "@app/contexts/file/storedFileReconciler";
const DEBUG = process.env.NODE_ENV === "development";
@@ -42,6 +47,7 @@ export class FileLifecycleManager {
fileId: FileId,
stateRef?: React.MutableRefObject<FileContextState>,
): void => {
+ forgetFile(fileId);
// Use comprehensive cleanup (same as removeFiles)
this.cleanupAllResourcesForFile(fileId, stateRef);
@@ -120,6 +126,7 @@ export class FileLifecycleManager {
stateRef?: React.MutableRefObject<FileContextState>,
): void => {
fileIds.forEach((fileId) => {
+ forgetFile(fileId);
// Clean up all resources for this file
this.cleanupAllResourcesForFile(fileId, stateRef);
});
@@ -211,6 +218,29 @@ export class FileLifecycleManager {
type: "UPDATE_FILE_RECORD",
payload: { id: fileId, updates },
});
+
+ // Fire-and-forget: the dispatch above is what the UI reads, and a storage
+ // hiccup must not stall it. Worst case the link reverts to its stored value.
+ const linkUpdates = persistedSourceFields(updates);
+ if (linkUpdates) {
+ void import("@app/services/fileStorage")
+ .then(({ fileStorage }) =>
+ fileStorage.updateFileMetadata(fileId, linkUpdates),
+ )
+ .catch((error) =>
+ console.error(
+ `[Lifecycle] Failed to persist disk link for ${fileId}:`,
+ error,
+ ),
+ );
+ }
+
+ noteFileSaved(fileId, updates, (patch) =>
+ this.dispatch({
+ type: "UPDATE_FILE_RECORD",
+ payload: { id: fileId, updates: patch },
+ }),
+ );
};
/**
diff --git a/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts b/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts
new file mode 100644
index 0000000000..6eeac53b9c
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from "vitest";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+import {
+ persistedSourceFields,
+ inheritedSourceLink,
+ sourceLinkForNewFile,
+ reconcileBeforeOpen,
+} from "@app/contexts/file/storedFileReconciler";
+
+// Where IndexedDB is the only truth there is nothing to reconcile against, and
+// the workbench has to be able to rely on that: a stub that started answering
+// would put link fields on files that have no source.
+
+const stub = { id: "f1" as FileId, name: "a.pdf" } as StirlingFileStub;
+
+describe("reconciling a record with no source", () => {
+ it("serves the stored copy untouched", async () => {
+ await expect(
+ reconcileBeforeOpen(stub, {
+ getStub: () => undefined,
+ listStubs: () => [],
+ putFile: () => {},
+ updateStub: () => {},
+ dropFile: () => {},
+ reprocessFile: () => {},
+ }),
+ ).resolves.toEqual({});
+ });
+
+ it("mirrors no field into storage beyond the stored copy itself", () => {
+ expect(persistedSourceFields({ localFilePath: "C:/x.pdf" })).toBe(null);
+ });
+
+ it("gives a derived file no link to inherit", () => {
+ expect(inheritedSourceLink(stub)).toEqual({});
+ });
+
+ it("leaves a newly added file unlinked", async () => {
+ await expect(sourceLinkForNewFile("k")).resolves.toEqual({});
+ });
+});
diff --git a/frontend/editor/src/core/contexts/file/storedFileReconciler.ts b/frontend/editor/src/core/contexts/file/storedFileReconciler.ts
new file mode 100644
index 0000000000..845bdcc802
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/storedFileReconciler.ts
@@ -0,0 +1,88 @@
+import { FileId, StirlingFileStub } from "@app/types/fileContext";
+
+// Seam for settling a stored record against wherever it came from. Core owns
+// when a record is reconciled - on open, and when a source reports a change -
+// and nothing about what "current" means. The no-ops here are the answer
+// wherever IndexedDB is the only truth, which is every build but the desktop
+// app.
+
+/** The workbench access a reconciler needs to settle a record in place. */
+export interface ReconcilePort {
+ getStub(fileId: FileId): StirlingFileStub | undefined;
+ listStubs(): StirlingFileStub[];
+ /** Publish bytes for a record already in state. */
+ putFile(fileId: FileId, file: File): void;
+ updateStub(fileId: FileId, updates: Partial<StirlingFileStub>): void;
+ dropFile(fileId: FileId): void;
+ /** Re-derive page data and thumbnails from the bytes now published. Every
+ * path that replaces a record's content owes this: the cached page data
+ * describes the old bytes, and the editors lay out from it. */
+ reprocessFile(fileId: FileId): void;
+}
+
+/** What to do with a stored record before the workbench serves it. */
+export interface OpenDecision {
+ /** Bytes fresher than the ones storage holds. */
+ file?: File;
+ updates?: Partial<StirlingFileStub>;
+ /** The record's source is gone and it held nothing the source did not. */
+ drop?: boolean;
+ /** Whether the cached page data now describes bytes that have moved on. */
+ contentReplaced?: boolean;
+ /** Runs once the bytes and the updates are both in state. Anything that asks
+ * the user belongs here: answering against a record still being published
+ * loses the answer to the publish that lands after it. */
+ afterPublish?: () => void;
+}
+
+/** Of a stub update, the fields worth mirroring into storage because they
+ * describe the record's source rather than its content. Null where a record
+ * has no source and the stored copy is written whole. */
+export function persistedSourceFields(
+ _updates: Partial<StirlingFileStub>,
+): Partial<StirlingFileStub> | null {
+ return null;
+}
+
+/** Source-link fields a derived file inherits from the file it was made from,
+ * given that deriving it wrote nothing back to that source. */
+export function inheritedSourceLink(
+ _sourceStub: StirlingFileStub,
+): Partial<StirlingFileStub> {
+ return {};
+}
+
+/** Fields recording the source a newly added file was read from, keyed by the
+ * quickKey the open dialog registered it under. Empty where files have no
+ * source outside the app. */
+export async function sourceLinkForNewFile(
+ _quickKey: string,
+): Promise<Partial<StirlingFileStub>> {
+ return {};
+}
+
+/** Settle one stored record against its source before the workbench serves it. */
+export async function reconcileBeforeOpen(
+ _stub: StirlingFileStub,
+ _port: ReconcilePort,
+): Promise<OpenDecision> {
+ return {};
+}
+
+/** Something changed at these source locations; settle every open record that
+ * came from one of them. */
+export async function reconcileOpenFiles(
+ _locations: string[],
+ _port: ReconcilePort,
+): Promise<void> {}
+
+/** A record was just written back to the source it came from.
+ * @param applyUpdates stamps late-arriving fields, e.g. a re-read baseline. */
+export function noteFileSaved(
+ _fileId: FileId,
+ _updates: Partial<StirlingFileStub>,
+ _applyUpdates: (updates: Partial<StirlingFileStub>) => void,
+): void {}
+
+/** A record is leaving the workbench; abandon anything pending against it. */
+export function forgetFile(_fileId: FileId): void {}
diff --git a/frontend/editor/src/core/contexts/file/undoPersistsDirty.test.ts b/frontend/editor/src/core/contexts/file/undoPersistsDirty.test.ts
new file mode 100644
index 0000000000..48c3c988c7
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/undoPersistsDirty.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import type { FileId, StirlingFileStub } from "@app/types/fileContext";
+
+const updateFileMetadata = vi.fn().mockResolvedValue(true);
+const markFileAsLeaf = vi.fn().mockResolvedValue(true);
+
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { updateFileMetadata, markFileAsLeaf },
+}));
+
+const { undoConsumeFiles } = await import("@app/contexts/file/fileActions");
+
+const stub = (id: string, localFilePath?: string) =>
+ ({
+ id: id as FileId,
+ name: `${id}.pdf`,
+ isLeaf: false,
+ ...(localFilePath ? { localFilePath } : {}),
+ }) as StirlingFileStub;
+
+const runUndo = async (stubs: StirlingFileStub[]) => {
+ const filesRef = { current: new Map<FileId, File>() };
+ const files = stubs.map((s) => new File(["x"], s.name));
+ await undoConsumeFiles(files, stubs, [], filesRef, vi.fn(), null);
+};
+
+describe("undoConsumeFiles persistence", () => {
+ beforeEach(() => {
+ updateFileMetadata.mockClear();
+ markFileAsLeaf.mockClear();
+ });
+
+ it("persists the dirty mark for a disk-linked file, not just isLeaf", async () => {
+ await runUndo([stub("A", "/tmp/a.pdf")]);
+
+ expect(updateFileMetadata).toHaveBeenCalledWith("A", {
+ isLeaf: true,
+ isDirty: true,
+ });
+ });
+
+ it("leaves a file with no disk link clean", async () => {
+ await runUndo([stub("B")]);
+
+ expect(updateFileMetadata).toHaveBeenCalledWith("B", { isLeaf: true });
+ });
+});
diff --git a/frontend/editor/src/core/hooks/useDiskLinkReconcile.ts b/frontend/editor/src/core/hooks/useDiskLinkReconcile.ts
new file mode 100644
index 0000000000..fb59c7cddc
--- /dev/null
+++ b/frontend/editor/src/core/hooks/useDiskLinkReconcile.ts
@@ -0,0 +1,26 @@
+import { useCallback, useRef } from "react";
+import { FileId } from "@app/types/fileContext";
+import { useAllFiles } from "@app/contexts/file/fileHooks";
+import type { DetachedOpenFile } from "@app/services/pruneMissingRecentFiles";
+
+// Wiring the file list and the recent-files list share for reconciling their
+// records. Only the detach handler is build-specific; the open-file set the
+// prune reads is the workbench's own and is always needed.
+
+/** Test seam for the build that keeps state here; a no-op where none is kept. */
+export function __resetDetachReports(): void {}
+
+export function useDiskLinkReconcile() {
+ const { fileIds } = useAllFiles();
+ // Read through a ref so the returned callbacks stay stable - their consumers
+ // re-run on identity change, which would loop on every workbench update.
+ const openFileIdsRef = useRef<FileId[]>(fileIds);
+ openFileIdsRef.current = fileIds;
+
+ const onOpenFilesDetached = useCallback(
+ (_files: DetachedOpenFile[]) => {},
+ [],
+ );
+
+ return { openFileIdsRef, onOpenFilesDetached };
+}
diff --git a/frontend/editor/src/core/hooks/useFileManager.ts b/frontend/editor/src/core/hooks/useFileManager.ts
index 0b9da5d4da..87cde4d83c 100644
--- a/frontend/editor/src/core/hooks/useFileManager.ts
+++ b/frontend/editor/src/core/hooks/useFileManager.ts
@@ -1,10 +1,12 @@
import { useState, useCallback } from "react";
import { useIndexedDB } from "@app/contexts/IndexedDBContext";
import { fileStorage } from "@app/services/fileStorage";
+import { pruneMissingRecentFiles } from "@app/services/pruneMissingRecentFiles";
import { StirlingFileStub, StirlingFile } from "@app/types/fileContext";
import { FileId } from "@app/types/fileContext";
import apiClient from "@app/services/apiClient";
import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { useDiskLinkReconcile } from "@app/hooks/useDiskLinkReconcile";
interface StoredFileResponse {
id: number;
@@ -36,6 +38,10 @@ export const useFileManager = () => {
const indexedDB = useIndexedDB();
const { config } = useAppConfig();
+ // Refs inside, so loadRecentFiles isn't recreated on every workbench change -
+ // its consumers re-run it on identity change, which would loop.
+ const { openFileIdsRef, onOpenFilesDetached } = useDiskLinkReconcile();
+
const normalizeServerFileName = useCallback(
(fileName: string | undefined | null): string => {
const fallback = fileName?.trim() || "server-file";
@@ -105,7 +111,13 @@ export const useFileManager = () => {
}
// Load only leaf files metadata (processed files that haven't been used as input for other tools)
- const stirlingFileStubs = await fileStorage.getLeafStirlingFileStubs();
+ const storedStubs = await fileStorage.getLeafStirlingFileStubs();
+ // A file deleted outside the app must not be offered here, so reconcile
+ // before the list is built.
+ const stirlingFileStubs = await pruneMissingRecentFiles(storedStubs, {
+ openFileIds: new Set(openFileIdsRef.current),
+ onOpenFilesDetached,
+ });
const remoteIdSet = new Set(
stirlingFileStubs
.map((stub) => stub.remoteStorageId)
@@ -369,6 +381,8 @@ export const useFileManager = () => {
config?.storageEnabled,
config?.storageShareLinksEnabled,
normalizeServerFileName,
+ openFileIdsRef,
+ onOpenFilesDetached,
]);
const handleRemoveFile = useCallback(
diff --git a/frontend/editor/src/core/i18n.ts b/frontend/editor/src/core/i18n.ts
index e69488c4e5..da8575b972 100644
--- a/frontend/editor/src/core/i18n.ts
+++ b/frontend/editor/src/core/i18n.ts
@@ -206,4 +206,8 @@ function applyDefaultLocale(defaultLocale: string) {
setLanguageWithPriority(defaultLocale, LanguageSource.ServerDefault);
}
+// Non-React modules off the hydration path (diskFileSync's toasts) read the
+// translator from globalThis; the ESM build does not register itself.
+(globalThis as Record<string, unknown>).i18next = i18n;
+
export default i18n;
diff --git a/frontend/editor/src/core/services/desktopFileLink.ts b/frontend/editor/src/core/services/desktopFileLink.ts
new file mode 100644
index 0000000000..43c0dcb441
--- /dev/null
+++ b/frontend/editor/src/core/services/desktopFileLink.ts
@@ -0,0 +1,38 @@
+// Seam for keeping desktop files 1:1 with disk. Non-desktop builds get this
+// no-op via @app alias order, so web/SaaS keep IndexedDB as sole truth.
+
+export type DiskUnavailableReason = "permission" | "offline" | "unknown";
+
+export type DiskFileState =
+ | { availability: "present"; size: number; modifiedMs: number }
+ | { availability: "gone" }
+ | { availability: "unavailable"; reason: DiskUnavailableReason };
+
+export type PresentDiskFileState = Extract<
+ DiskFileState,
+ { availability: "present" }
+>;
+
+// False on web: disk-linked reads, pruning and the missing-file alert are skipped.
+export const desktopFileLinkingSupported = false;
+
+export async function getDiskFileState(_path: string): Promise<DiskFileState> {
+ return { availability: "unavailable", reason: "unknown" };
+}
+
+// No disk to read from outside the desktop app.
+export async function readFileFromDisk(
+ _path: string,
+): Promise<ArrayBuffer | null> {
+ return null;
+}
+
+// Nothing to watch: web files have no disk original that can change underneath us.
+export async function watchDiskPaths(_paths: string[]): Promise<void> {}
+
+// Never fires off the desktop app; returns a no-op unsubscribe.
+export async function onDiskFilesChanged(
+ _handler: (paths: string[]) => void,
+): Promise<() => void> {
+ return () => {};
+}
diff --git a/frontend/editor/src/core/services/diskLinkState.test.ts b/frontend/editor/src/core/services/diskLinkState.test.ts
new file mode 100644
index 0000000000..524c2c82ae
--- /dev/null
+++ b/frontend/editor/src/core/services/diskLinkState.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from "vitest";
+import { diskLinkState } from "@app/services/diskLinkState";
+
+describe("diskLinkState", () => {
+ it("is 'none' for a file that never came from disk", () => {
+ expect(diskLinkState({})).toBe("none");
+ });
+
+ it("is 'unavailable' while the original cannot be reached", () => {
+ expect(
+ diskLinkState({
+ localFilePath: "/Volumes/Backup/report.pdf",
+ diskUnavailableReason: "offline",
+ }),
+ ).toBe("unavailable");
+ });
+
+ it("still reports a conflict when disk has also gone quiet", () => {
+ expect(
+ diskLinkState({
+ localFilePath: "/Volumes/Backup/report.pdf",
+ diskConflictAt: 1,
+ diskUnavailableReason: "offline",
+ }),
+ ).toBe("conflict");
+ });
+
+ it("is 'linked' while the original is present and agrees", () => {
+ expect(diskLinkState({ localFilePath: "C:/docs/report.pdf" })).toBe(
+ "linked",
+ );
+ });
+
+ it("is 'orphaned' once the original is gone", () => {
+ // The distinction the UI could not previously draw: this is NOT the same as
+ // a file that was never saved, and it must not read like one.
+ expect(diskLinkState({ orphanedFilePath: "C:/docs/report.pdf" })).toBe(
+ "orphaned",
+ );
+ });
+
+ it("is 'conflict' while a divergence is unresolved", () => {
+ expect(
+ diskLinkState({
+ localFilePath: "C:/docs/report.pdf",
+ diskConflictAt: 1234,
+ }),
+ ).toBe("conflict");
+ });
+});
diff --git a/frontend/editor/src/core/services/diskLinkState.ts b/frontend/editor/src/core/services/diskLinkState.ts
new file mode 100644
index 0000000000..590cde6617
--- /dev/null
+++ b/frontend/editor/src/core/services/diskLinkState.ts
@@ -0,0 +1,31 @@
+import { StirlingFileStub } from "@app/types/fileContext";
+
+/** How a file stands relative to the original it was opened from. Derived
+ * rather than stored so every surface gets the same answer instead of
+ * re-deriving it. Always "none" where nothing links files to an original. */
+export type DiskLinkState =
+ /** Never came from a disk original: a web upload, or a tool output. */
+ | "none"
+ /** Backed by a real file that is present and matches what we hold. */
+ | "linked"
+ /** Came from disk, but the original is gone. Saving needs a new location. */
+ | "orphaned"
+ | "unavailable"
+ /** Disk moved on while we held unsaved edits; two real versions exist. */
+ | "conflict";
+
+export function diskLinkState(
+ stub: Pick<
+ StirlingFileStub,
+ | "localFilePath"
+ | "orphanedFilePath"
+ | "diskConflictAt"
+ | "diskUnavailableReason"
+ >,
+): DiskLinkState {
+ if (stub.localFilePath) {
+ if (stub.diskConflictAt) return "conflict";
+ return stub.diskUnavailableReason ? "unavailable" : "linked";
+ }
+ return stub.orphanedFilePath ? "orphaned" : "none";
+}
diff --git a/frontend/editor/src/core/services/fileStorage.ts b/frontend/editor/src/core/services/fileStorage.ts
index bd637bed4d..e05f884a45 100644
--- a/frontend/editor/src/core/services/fileStorage.ts
+++ b/frontend/editor/src/core/services/fileStorage.ts
@@ -33,6 +33,23 @@ export interface StoredStirlingFileRecord extends BaseFileMetadata {
thumbnail?: string;
thumbnailStoredAt?: number; // Epoch ms - sliding 30-day TTL
url?: string; // For compatibility with existing components
+ // Disk path this file came from (desktop only). Persisted so the link to the
+ // real file survives a reload - without it every restart drops to the stored copy.
+ localFilePath?: string;
+ // Size/mtime of the disk file when we last read it, so an external edit is
+ // detectable without hashing. Only meaningful alongside localFilePath.
+ diskSyncedSize?: number;
+ diskSyncedModifiedMs?: number;
+ // Disk path whose original is gone. Persisted so the "not on disk" state
+ // survives a reload instead of dying with the toast.
+ orphanedFilePath?: string;
+ // Epoch ms of an unresolved disk-vs-unsaved-edits divergence.
+ diskConflictAt?: number;
+ // Epoch ms of the last pickup of an external edit.
+ diskReloadedAt?: number;
+ // In-app edits not yet written to localFilePath. Persisted because a reload
+ // would otherwise forget them and let a disk re-read overwrite the user's work.
+ isDirty?: boolean;
// Cached classification labels — mirrors the stub field so the sidebar can
// group by label without re-reading PDF bytes, and it survives versioning.
// See StirlingFileStub.classificationLabels.
@@ -323,6 +340,13 @@ class FileStorageService {
: await copyBlobBytes(stirlingFile),
thumbnail: stub.thumbnailUrl,
thumbnailStoredAt: stub.thumbnailUrl ? Date.now() : undefined,
+ localFilePath: stub.localFilePath,
+ diskSyncedSize: stub.diskSyncedSize,
+ diskSyncedModifiedMs: stub.diskSyncedModifiedMs,
+ orphanedFilePath: stub.orphanedFilePath,
+ diskConflictAt: stub.diskConflictAt,
+ diskReloadedAt: stub.diskReloadedAt,
+ isDirty: stub.isDirty,
isLeaf: stub.isLeaf ?? true,
remoteStorageId: stub.remoteStorageId,
remoteStorageUpdatedAt: stub.remoteStorageUpdatedAt,
@@ -700,6 +724,13 @@ class FileStorageService {
lastModified: record.lastModified,
quickKey: record.quickKey,
thumbnailUrl: fresh ? record.thumbnail : undefined,
+ localFilePath: record.localFilePath,
+ diskSyncedSize: record.diskSyncedSize,
+ diskSyncedModifiedMs: record.diskSyncedModifiedMs,
+ orphanedFilePath: record.orphanedFilePath,
+ diskConflictAt: record.diskConflictAt,
+ diskReloadedAt: record.diskReloadedAt,
+ isDirty: record.isDirty,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
@@ -769,6 +800,13 @@ class FileStorageService {
lastModified: record.lastModified,
quickKey: record.quickKey,
thumbnailUrl: fresh ? record.thumbnail : undefined,
+ localFilePath: record.localFilePath,
+ diskSyncedSize: record.diskSyncedSize,
+ diskSyncedModifiedMs: record.diskSyncedModifiedMs,
+ orphanedFilePath: record.orphanedFilePath,
+ diskConflictAt: record.diskConflictAt,
+ diskReloadedAt: record.diskReloadedAt,
+ isDirty: record.isDirty,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
@@ -870,6 +908,13 @@ class FileStorageService {
lastModified: record.lastModified,
quickKey: record.quickKey,
thumbnailUrl: fresh ? record.thumbnail : undefined,
+ localFilePath: record.localFilePath,
+ diskSyncedSize: record.diskSyncedSize,
+ diskSyncedModifiedMs: record.diskSyncedModifiedMs,
+ orphanedFilePath: record.orphanedFilePath,
+ diskConflictAt: record.diskConflictAt,
+ diskReloadedAt: record.diskReloadedAt,
+ isDirty: record.isDirty,
isLeaf: record.isLeaf,
remoteStorageId: record.remoteStorageId,
remoteStorageUpdatedAt: record.remoteStorageUpdatedAt,
diff --git a/frontend/editor/src/core/services/pruneMissingRecentFiles.ts b/frontend/editor/src/core/services/pruneMissingRecentFiles.ts
new file mode 100644
index 0000000000..30c5ae8b93
--- /dev/null
+++ b/frontend/editor/src/core/services/pruneMissingRecentFiles.ts
@@ -0,0 +1,31 @@
+import { StirlingFileStub, FileId } from "@app/types/fileContext";
+
+// Seam for reconciling the file list against wherever its records came from.
+// Where IndexedDB is the only truth a stored record cannot have gone missing,
+// so the list is already the answer.
+
+/** A file that lost its original while the user had it open. */
+export interface DetachedOpenFile {
+ id: FileId;
+ name: string;
+ /** The now-dead path, so the caller can record it as the orphaned path. */
+ path: string;
+}
+
+export interface PruneOptions {
+ /** Files open in the workbench. Deleting one would leave an on-screen
+ * document existing nowhere, so open files are detached rather than
+ * deleted whatever their edit state. */
+ openFileIds?: ReadonlySet<FileId>;
+ /** Open files whose original vanished. The caller MUST apply the same detach
+ * to its own stubs: save paths read the workbench stub and would otherwise
+ * keep writing to the dead path. */
+ onOpenFilesDetached?: (files: DetachedOpenFile[]) => void;
+}
+
+export async function pruneMissingRecentFiles(
+ stubs: StirlingFileStub[],
+ _options: PruneOptions = {},
+): Promise<StirlingFileStub[]> {
+ return stubs;
+}
diff --git a/frontend/editor/src/core/services/unsavedWork.test.ts b/frontend/editor/src/core/services/unsavedWork.test.ts
new file mode 100644
index 0000000000..c83e7ee2d1
--- /dev/null
+++ b/frontend/editor/src/core/services/unsavedWork.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ registerUnsavedWorkChecker,
+ hasUnsavedWork,
+ __resetUnsavedWork,
+} from "@app/services/unsavedWork";
+
+beforeEach(() => __resetUnsavedWork());
+afterEach(() => vi.restoreAllMocks());
+
+describe("hasUnsavedWork", () => {
+ it("is clean before anything registers", () => {
+ expect(hasUnsavedWork()).toBe(false);
+ });
+
+ it("reads the checker each time, not the value at registration", () => {
+ let dirty = false;
+ registerUnsavedWorkChecker(() => dirty);
+ expect(hasUnsavedWork()).toBe(false);
+ dirty = true;
+ expect(hasUnsavedWork()).toBe(true);
+ });
+
+ it("is clean again once the provider unregisters", () => {
+ const stop = registerUnsavedWorkChecker(() => true);
+ stop();
+ expect(hasUnsavedWork()).toBe(false);
+ });
+
+ it("keeps the newer checker when an unregister arrives late", () => {
+ const stop = registerUnsavedWorkChecker(() => false);
+ registerUnsavedWorkChecker(() => true);
+ stop();
+ expect(hasUnsavedWork()).toBe(true);
+ });
+
+ it("assumes unsaved work when the checker throws", () => {
+ // Reading false here would let disk silently overwrite the user's edits.
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ registerUnsavedWorkChecker(() => {
+ throw new Error("provider unmounted mid-check");
+ });
+ expect(hasUnsavedWork()).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/core/services/unsavedWork.ts b/frontend/editor/src/core/services/unsavedWork.ts
new file mode 100644
index 0000000000..dc1bdd1eb9
--- /dev/null
+++ b/frontend/editor/src/core/services/unsavedWork.ts
@@ -0,0 +1,36 @@
+// Bridge from the non-React disk reconciliation to the editors' live dirty state.
+// NavigationProvider mounts inside FileContextProvider, so FileContext cannot read
+// it through a hook; a module seam is how the toast and conflict prompt cross the
+// same boundary.
+
+type Checker = () => boolean;
+
+let checker: Checker | null = null;
+
+/** Publish the app's live "something is edited but not committed" answer.
+ * Returns the unregister; a later register replaces an earlier one. */
+export function registerUnsavedWorkChecker(next: Checker): () => void {
+ checker = next;
+ return () => {
+ if (checker === next) checker = null;
+ };
+}
+
+/** Whether an open editor holds edits no version has captured yet. No checker
+ * means no editor is mounted to hold any, so that answer is false; a checker
+ * that throws fails closed, because "unknown" must not read as safe to
+ * overwrite. */
+export function hasUnsavedWork(): boolean {
+ if (!checker) return false;
+ try {
+ return checker();
+ } catch (error) {
+ console.error("[unsavedWork] checker threw; assuming unsaved work:", error);
+ return true;
+ }
+}
+
+/** Test seam: the checker is module state and would leak between cases. */
+export function __resetUnsavedWork(): void {
+ checker = null;
+}
diff --git a/frontend/editor/src/core/tests/helpers/stub-test-base.ts b/frontend/editor/src/core/tests/helpers/stub-test-base.ts
index 8419b93e28..e8c4467811 100644
--- a/frontend/editor/src/core/tests/helpers/stub-test-base.ts
+++ b/frontend/editor/src/core/tests/helpers/stub-test-base.ts
@@ -3,7 +3,6 @@ import {
bypassOnboarding,
mockAppApis,
seedCookieConsent,
- skipOnboarding,
type MockAppApiOptions,
} from "@app/tests/helpers/api-stubs";
import { suppressNativeFilePicker } from "@app/tests/helpers/ui-helpers";
@@ -63,16 +62,11 @@ export const test = base.extend<StubFixtures>({
page: async ({ page, stubOptions, autoGoto, seedJwt }, use) => {
suppressNativeFilePicker(page);
await seedCookieConsent(page);
+ await bypassOnboarding(page);
if (seedJwt) {
- // Logged-in users hit the orchestrator path that surfaces the
- // analytics opt-in / MFA prompts — use the stronger bypass-all flag
- // so those overlays don't block clicks.
- await bypassOnboarding(page);
await page.addInitScript((token) => {
localStorage.setItem("stirling_jwt", token);
}, STUB_JWT);
- } else {
- await skipOnboarding(page);
}
await mockAppApis(page, stubOptions);
if (autoGoto !== false) {
diff --git a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
new file mode 100644
index 0000000000..5d94211f67
--- /dev/null
+++ b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
@@ -0,0 +1,337 @@
+// oxlint-disable typescript/no-explicit-any -- impersonates Tauri's untyped
+// `__TAURI_INTERNALS__` bridge; typing it would re-declare Tauri's private IPC.
+import type { Page } from "@playwright/test";
+
+// Runs the real desktop build against an in-memory disk the test mutates
+// between steps, so the disk-link paths execute for real without a Tauri
+// process. Requires `vite --mode desktop`, or desktopFileLinkingSupported is
+// false and every helper here is a no-op the app never consults.
+
+export type DiskEntry = { bytes: number[]; modifiedMs: number };
+export type SeedFile = {
+ id: string;
+ name: string;
+ path: string;
+ bytes: number[];
+ baseline?: { size: number; modifiedMs: number };
+ isDirty?: boolean;
+ /** false seeds a superseded version, as a tool run leaves its input. */
+ isLeaf?: boolean;
+ versionNumber?: number;
+ originalFileId?: string;
+ parentFileId?: string;
+};
+
+/** Fake Tauri IPC over an in-memory disk the test mutates between steps. */
+
+export async function installTauri(page: Page) {
+ await page.addInitScript(() => {
+ const w = window as any;
+ w.isTauri = true;
+ // Init script re-runs on every navigation, so the disk lives in sessionStorage -
+ // a reload would otherwise empty it and make every file look deleted.
+ w.__disk = JSON.parse(sessionStorage.getItem("__disk") || "{}");
+ w.__saveDisk = () =>
+ sessionStorage.setItem("__disk", JSON.stringify(w.__disk));
+ w.__callbacks = {};
+ // Lets a spec tell a build that reconciles against disk from one that
+ // stubs it out: only the former ever asks for a file's disk state.
+ w.__invoked = [];
+ w.__listeners = {};
+ let nextCb = 1;
+
+ const stat = (p: string) => {
+ const e = w.__disk[p];
+ return e
+ ? {
+ availability: "present",
+ size: e.bytes.length,
+ modifiedMs: e.modifiedMs,
+ }
+ : { availability: "gone" };
+ };
+
+ // Desktop API calls go through tauri-plugin-http, not window.fetch, so
+ // page.route() never sees them; delegating to fetch restores interception.
+ const httpReqs: Record<number, any> = {};
+ const httpRes: Record<number, { body: Uint8Array; read: boolean }> = {};
+ let nextRid = 1;
+
+ w.__TAURI_INTERNALS__ = {
+ // getCurrentWindow()/getCurrentWebview() read straight off this.
+ metadata: {
+ currentWindow: { label: "main" },
+ currentWebview: { windowLabel: "main", label: "main" },
+ },
+ transformCallback(cb: (v: unknown) => void) {
+ const id = nextCb++;
+ w.__callbacks[id] = cb;
+ return id;
+ },
+ unregisterListener() {},
+ async invoke(cmd: string, args: any = {}) {
+ w.__invoked.push(cmd);
+ switch (cmd) {
+ case "file_disk_state":
+ return stat(args.path);
+ case "plugin:fs|read_file": {
+ const e = w.__disk[args.path];
+ if (!e) throw new Error(`ENOENT ${args.path}`);
+ return e.bytes;
+ }
+ case "watch_disk_paths":
+ case "unwatch_disk_paths":
+ return null;
+
+ case "plugin:http|fetch": {
+ const rid = nextRid++;
+ httpReqs[rid] = args.clientConfig;
+ return rid;
+ }
+ case "plugin:http|fetch_send": {
+ const cfg = httpReqs[args.rid];
+ const res = await window.fetch(cfg.url, {
+ method: cfg.method,
+ headers: cfg.headers,
+ body: cfg.data ? new Uint8Array(cfg.data) : undefined,
+ });
+ const bodyRid = nextRid++;
+ httpRes[bodyRid] = {
+ body: new Uint8Array(await res.arrayBuffer()),
+ read: false,
+ };
+ return {
+ status: res.status,
+ statusText: res.statusText,
+ url: res.url,
+ headers: Array.from(res.headers.entries()),
+ rid: bodyRid,
+ };
+ }
+ case "plugin:http|fetch_read_body": {
+ const entry = httpRes[args.rid];
+ if (!entry || entry.read) return [1]; // terminator: stream closed
+ entry.read = true;
+ return [...entry.body, 0]; // 0 = more may follow
+ }
+ case "plugin:http|fetch_cancel":
+ case "plugin:http|fetch_cancel_body":
+ return null;
+
+ case "plugin:event|listen":
+ w.__listeners[args.event] = args.handler;
+ return Object.keys(w.__listeners).length;
+ case "plugin:event|unlisten":
+ return null;
+
+ case "get_backend_port":
+ return 8080;
+ case "pop_opened_files":
+ case "get_opened_files":
+ case "pop_window_file_ids":
+ return [];
+ case "get_desktop_os":
+ return "windows";
+ case "get_app_version":
+ return "2.14.0";
+ case "is_first_launch":
+ return false;
+ case "is_default_pdf_handler":
+ return true;
+ case "can_install_updates":
+ return false;
+ case "get_update_mode":
+ return "manual";
+ case "get_connection_config":
+ return { mode: "local", serverUrl: null, setupCompleted: true };
+ default:
+ return null;
+ }
+ },
+ };
+
+ // `unlisten()` goes through this object, not __TAURI_INTERNALS__.
+ w.__TAURI_EVENT_PLUGIN_INTERNALS__ = {
+ unregisterListener(event: string) {
+ delete w.__listeners[event];
+ },
+ };
+
+ /** Fire a watcher event at the app, as the Rust side would. */
+ w.__emitDisk = (paths: string[]) => {
+ const handler = w.__listeners["disk-files-changed"];
+ if (handler && w.__callbacks[handler]) {
+ w.__callbacks[handler]({
+ event: "disk-files-changed",
+ id: 1,
+ payload: { paths },
+ });
+ }
+ };
+ });
+}
+
+export async function setDisk(page: Page, disk: Record<string, DiskEntry>) {
+ await page.evaluate((d) => {
+ const w = window as any;
+ w.__disk = d;
+ w.__saveDisk();
+ }, disk);
+}
+
+/** Remove one path, as an external delete would. */
+export async function deleteOnDisk(page: Page, p: string) {
+ await page.evaluate((path) => {
+ const w = window as any;
+ delete w.__disk[path];
+ w.__saveDisk();
+ }, p);
+}
+
+/** Overwrite a path with different bytes and a newer mtime. */
+export async function editOnDisk(page: Page, p: string, bytes: number[]) {
+ await page.evaluate(
+ ({ path, b }) => {
+ const w = window as any;
+ w.__disk[path] = { bytes: b, modifiedMs: 1_800_000_000_000 };
+ w.__saveDisk();
+ },
+ { path: p, b: bytes },
+ );
+}
+
+export async function emitWatch(page: Page, paths: string[]) {
+ await page.evaluate((p) => (window as any).__emitDisk(p), paths);
+}
+
+/** Write file records straight into IndexedDB, as an earlier session would. */
+export async function seedFiles(page: Page, files: SeedFile[]) {
+ await page.evaluate(async (seed: SeedFile[]) => {
+ const open = () =>
+ new Promise<IDBDatabase>((resolve, reject) => {
+ const req = indexedDB.open("stirling-pdf-files");
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () =>
+ reject(req.error ?? new Error("indexedDB.open failed"));
+ });
+ let db: IDBDatabase = await open();
+ for (let i = 0; i < 100 && !db.objectStoreNames.contains("files"); i++) {
+ db.close();
+ await new Promise((r) => setTimeout(r, 100));
+ db = await open();
+ }
+ if (!db.objectStoreNames.contains("files")) {
+ throw new Error("the app never created the files store");
+ }
+ const tx = db.transaction(["files"], "readwrite");
+ const store = tx.objectStore("files");
+ store.clear();
+ for (const f of seed) {
+ const bytes = new Uint8Array(f.bytes);
+ const baseline = f.baseline ?? {
+ size: bytes.length,
+ modifiedMs: (window as any).__disk[f.path]?.modifiedMs ?? 0,
+ };
+ store.put({
+ id: f.id,
+ fileId: f.id,
+ name: f.name,
+ type: "application/pdf",
+ size: bytes.length,
+ lastModified: baseline.modifiedMs,
+ createdAt: Date.now(),
+ data: bytes.buffer,
+ quickKey: `${f.name}|${bytes.length}|${baseline.modifiedMs}`,
+ isLeaf: f.isLeaf ?? true,
+ versionNumber: f.versionNumber ?? 1,
+ originalFileId: f.originalFileId ?? f.id,
+ parentFileId: f.parentFileId,
+ toolHistory: [],
+ localFilePath: f.path,
+ diskSyncedSize: baseline.size,
+ diskSyncedModifiedMs: baseline.modifiedMs,
+ isDirty: f.isDirty ?? undefined,
+ });
+ }
+ await new Promise((resolve, reject) => {
+ tx.oncomplete = () => resolve(null);
+ const fail = (what: string) => () =>
+ reject(
+ new Error(
+ `${what}: ${tx.error?.name ?? "no error"} ${tx.error?.message ?? ""}`,
+ ),
+ );
+ tx.onerror = fail("transaction failed");
+ tx.onabort = fail("transaction aborted");
+ });
+ db.close();
+ }, files);
+}
+
+/** The desktop profile opens onto a welcome carousel and a sign-in prompt. */
+
+export async function dismissModals(page: Page) {
+ for (let i = 0; i < 8; i++) {
+ // Dialog-scoped first, and deliberately not by aria-label: the welcome
+ // carousel's close button carries none, so an attribute match lands on the
+ // window chrome's Close - which is earlier in the DOM and does nothing -
+ // and the carousel's overlay then eats every click that follows.
+ const inDialog = page
+ .getByRole("dialog")
+ .getByRole("button", { name: "Close" })
+ .first();
+ const close =
+ (await inDialog.count()) > 0
+ ? inDialog
+ : page.locator('[aria-label="Close"]:visible').first();
+ if ((await close.count()) === 0) break;
+ await close.click({ timeout: 2000 }).catch(() => {});
+ await page.waitForTimeout(250);
+ }
+ // Deliberately no Escape here: it backs the file manager out to the editor,
+ // which silently moved every later scenario off the file list.
+ await page.waitForTimeout(300);
+}
+
+export async function openCard(page: Page, name: string) {
+ // Scope to the grid card: a bare text match also hits the library rail on the
+ // left, which navigates without loading the file into the workbench.
+ const card = page
+ .locator(".files-page-card", { hasText: name.replace(/\.pdf$/, "") })
+ .first();
+ await card.scrollIntoViewIfNeeded();
+ await card.dblclick();
+ // Wait for the workbench to actually take the file, not just for the route to
+ // change - otherwise the capture can fire on an empty workbench.
+ await page
+ .getByRole("button", { name: /Open Files/i })
+ .waitFor({ state: "detached", timeout: 15_000 })
+ .catch(() => {});
+ // And for the document itself to render - a re-read from disk re-parses the
+ // file, so the viewer sits on "Loading tool…" well after the toast has fired.
+ await page
+ .getByText(/Loading tool/i)
+ .waitFor({ state: "detached", timeout: 20_000 })
+ .catch(() => {});
+ await page.waitForTimeout(1200);
+}
+
+export async function gotoFiles(page: Page) {
+ await page.goto("/files");
+ await page.waitForLoadState("networkidle");
+ await page.waitForTimeout(800);
+}
+
+/** Stage disk contents and stored records, then navigate so the app re-reads
+ * IndexedDB cold. Always ends on the file list with onboarding dismissed. */
+export async function stage(
+ page: Page,
+ disk: Record<string, DiskEntry>,
+ files: SeedFile[],
+) {
+ await setDisk(page, disk);
+ await seedFiles(page, files);
+ await gotoFiles(page);
+ await dismissModals(page);
+ await page.waitForTimeout(1200);
+}
diff --git a/frontend/editor/src/core/tests/stubbed/disk-link-capture.spec.ts b/frontend/editor/src/core/tests/stubbed/disk-link-capture.spec.ts
new file mode 100644
index 0000000000..64349001fd
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/disk-link-capture.spec.ts
@@ -0,0 +1,138 @@
+import { test } from "@app/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import {
+ type DiskEntry,
+ type SeedFile,
+ installTauri,
+ editOnDisk,
+ deleteOnDisk,
+ emitWatch,
+ gotoFiles,
+ openCard,
+ stage,
+} from "@app/tests/helpers/tauriDiskStub";
+import fs from "node:fs";
+import path from "node:path";
+
+/** Capture harness, not a regression test: fakes Tauri IPC over an in-memory disk.
+ * Needs `vite --mode desktop` (for desktopFileLinkingSupported) and SHOT_DIR set. */
+
+const SHOT_DIR = process.env.SHOT_DIR;
+// Playwright runs from the editor dir, so this is stable without __dirname
+// (the config is ESM, where __dirname does not exist).
+const FIXTURES = path.resolve("src/core/tests/test-fixtures");
+// 1.08 KB and 1.55 KB - the two sizes the walkthrough quotes for the
+// external-edit step, so the numbers on screen match the prose.
+const PDF_SMALL = Array.from(
+ fs.readFileSync(path.join(FIXTURES, "compare_sample_a.pdf")),
+);
+const PDF_LARGE = Array.from(
+ fs.readFileSync(path.join(FIXTURES, "compare_sample_b.pdf")),
+);
+
+const MTIME = 1_700_000_000_000;
+const P = {
+ report: "C:/Docs/quarterly-report.pdf",
+ notes: "C:/Docs/notes.pdf",
+ archived: "C:/Docs/archived.pdf",
+};
+
+async function shoot(page: Page, name: string, theme: string) {
+ if (!SHOT_DIR) return;
+ fs.mkdirSync(SHOT_DIR, { recursive: true });
+ await page.screenshot({ path: path.join(SHOT_DIR, `${name}_${theme}.png`) });
+ console.log(` shot ${name}_${theme}`);
+}
+
+const ALL_PRESENT: Record<string, DiskEntry> = {
+ [P.report]: { bytes: PDF_SMALL, modifiedMs: MTIME },
+ [P.notes]: { bytes: PDF_SMALL, modifiedMs: MTIME },
+ [P.archived]: { bytes: PDF_SMALL, modifiedMs: MTIME },
+};
+
+const THREE_FILES: SeedFile[] = [
+ {
+ id: "f-report",
+ name: "quarterly-report.pdf",
+ path: P.report,
+ bytes: PDF_SMALL,
+ },
+ { id: "f-notes", name: "notes.pdf", path: P.notes, bytes: PDF_SMALL },
+ {
+ id: "f-archived",
+ name: "archived.pdf",
+ path: P.archived,
+ bytes: PDF_SMALL,
+ },
+];
+
+test.use({ autoGoto: false, viewport: { width: 2076, height: 1096 } });
+test.describe.configure({ mode: "serial", timeout: 240_000 });
+
+// A capture run, not a gate: it needs a desktop-mode dev server and takes
+// minutes, so it stays out of the way unless someone asks for the shots.
+test.skip(!SHOT_DIR, "set SHOT_DIR to regenerate the walkthrough screenshots");
+
+for (const theme of ["light", "dark"] as const) {
+ test(`capture disk-link states (${theme})`, async ({ page }) => {
+ test.setTimeout(240_000);
+ await page.emulateMedia({ colorScheme: theme });
+ await installTauri(page);
+
+ // 1. Everything in sync
+ await gotoFiles(page);
+ await stage(page, ALL_PRESENT, THREE_FILES);
+ await shoot(page, "01_in_sync", theme);
+
+ // 3. Deleted while the app was closed
+ // (before 2, because 2 leaves the workbench populated)
+ const withoutArchived = { ...ALL_PRESENT };
+ delete withoutArchived[P.archived];
+ await stage(page, withoutArchived, THREE_FILES);
+ await shoot(page, "03_pruned_after_delete", theme);
+
+ // 2. Edited in another app
+ await stage(page, ALL_PRESENT, THREE_FILES);
+ await editOnDisk(page, P.report, PDF_LARGE);
+ await openCard(page, "quarterly-report.pdf");
+ await page.waitForTimeout(2500);
+ await shoot(page, "02_external_edit_picked_up", theme);
+
+ // 4. Deleted between listing and clicking
+ await stage(page, ALL_PRESENT, THREE_FILES);
+ // The list-time check has already passed; now it goes.
+ await deleteOnDisk(page, P.notes);
+ await openCard(page, "notes.pdf");
+ await page.waitForTimeout(2000);
+ await shoot(page, "04_vanished_on_open", theme);
+
+ // 5. Deleted while open, caught live by the watcher
+ await stage(page, ALL_PRESENT, THREE_FILES);
+ await openCard(page, "archived.pdf");
+ await page.waitForTimeout(1500);
+ await deleteOnDisk(page, P.archived);
+ await emitWatch(page, [P.archived]);
+ await page.waitForTimeout(2500);
+ await shoot(page, "05_open_file_deleted", theme);
+
+ // The badge outlives the toast - go back to the list and show it.
+ await gotoFiles(page);
+ await page.waitForTimeout(2000);
+ await shoot(page, "05b_orphaned_badge", theme);
+
+ // 6. Disk moved on while unsaved edits were held
+ await stage(page, ALL_PRESENT, [
+ { ...THREE_FILES[0], isDirty: true },
+ THREE_FILES[1],
+ THREE_FILES[2],
+ ]);
+ await editOnDisk(page, P.report, PDF_LARGE);
+ await openCard(page, "quarterly-report.pdf");
+ await page.waitForTimeout(2500);
+ await shoot(page, "06_conflict", theme);
+
+ await gotoFiles(page);
+ await page.waitForTimeout(2000);
+ await shoot(page, "06b_conflict_badge", theme);
+ });
+}
diff --git a/frontend/editor/src/core/tests/stubbed/disk-link-regressions.spec.ts b/frontend/editor/src/core/tests/stubbed/disk-link-regressions.spec.ts
new file mode 100644
index 0000000000..ad442fbb8f
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/disk-link-regressions.spec.ts
@@ -0,0 +1,333 @@
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import type { Page } from "@playwright/test";
+import {
+ type DiskEntry,
+ type SeedFile,
+ installTauri,
+ deleteOnDisk,
+ dismissModals,
+ editOnDisk,
+ emitWatch,
+ gotoFiles,
+ openCard,
+ stage,
+} from "@app/tests/helpers/tauriDiskStub";
+import fs from "node:fs";
+import path from "node:path";
+
+// The three ways an external edit could still cost the user work, driven through
+// the real desktop build rather than asserted on the units underneath it.
+// Needs `vite --mode desktop`: on any other build desktopFileLinkingSupported is
+// false, nothing reconciles, and every case below passes for the wrong reason.
+
+const FIXTURES = path.resolve("src/core/tests/test-fixtures");
+// One page vs eight: the viewer's own page DOM is then the assertion, and a
+// stale document cannot fake it the way a byte count or a blob URL can.
+const PDF_1_PAGE = Array.from(
+ fs.readFileSync(path.join(FIXTURES, "annotation-text-sample.pdf")),
+);
+const PDF_8_PAGES = Array.from(
+ fs.readFileSync(path.join(FIXTURES, "many-pages-sample.pdf")),
+);
+
+const MTIME = 1_700_000_000_000;
+const REPORT = "C:/Docs/quarterly-report.pdf";
+
+const onDisk = (): Record<string, DiskEntry> => ({
+ [REPORT]: { bytes: PDF_1_PAGE, modifiedMs: MTIME },
+});
+
+const report = (over: Partial<SeedFile> = {}): SeedFile => ({
+ id: "f-report",
+ name: "quarterly-report.pdf",
+ path: REPORT,
+ bytes: PDF_1_PAGE,
+ ...over,
+});
+
+/** Every assertion below describes a build that reconciles records against
+ * disk. A core or proprietary bundle stubs that out, so the whole file would
+ * be checking that nothing happened - skip rather than fail such a run.
+ * Call after staging: listing the files is what first asks disk anything. */
+async function requireDiskLinking(page: Page) {
+ const invoked = await page.evaluate(
+ () => (window as unknown as { __invoked?: string[] }).__invoked ?? [],
+ );
+ test.skip(
+ !invoked.includes("file_disk_state"),
+ "needs `vite --mode desktop`; this build has no disk linking",
+ );
+}
+
+/** Pages the page editor has laid out - it renders the whole document, so this
+ * is a straight count of what the editor is working on. */
+function editorPages(page: Page) {
+ return page.locator("[data-page-id]");
+}
+
+/** Open the file, dirty it in the page editor, then move the file on disk.
+ * Leaves the conflict modal on screen. */
+async function conflictInPageEditor(page: Page) {
+ await installTauri(page);
+ await gotoFiles(page);
+ await stage(page, onDisk(), [report()]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await openCard(page, "quarterly-report.pdf");
+
+ await page.getByText("PDF Multi Tool", { exact: true }).first().click();
+ const firstPage = editorPages(page).first();
+ await firstPage.waitFor({ state: "visible", timeout: 30_000 });
+ await firstPage.hover();
+ await firstPage.getByRole("button", { name: "Rotate Right" }).click();
+
+ await editOnDisk(page, REPORT, PDF_8_PAGES);
+ await emitWatch(page, [REPORT]);
+ await expect(
+ page.getByRole("button", { name: /Keep my changes/i }),
+ ).toBeVisible({ timeout: 20_000 });
+}
+
+/** The viewer's own page count. Not the mounted [data-page-index] elements:
+ * the viewer virtualises, so those count what is scrolled into view. */
+function viewerPageCount(page: Page, pages: number) {
+ return page.getByText(`/ ${pages}`, { exact: true });
+}
+
+test.use({ autoGoto: false, viewport: { width: 2076, height: 1096 } });
+
+test.describe.configure({ mode: "serial", timeout: 180_000 });
+
+test.describe("an external edit never silently costs the user work", () => {
+ test("a reload under an open viewer replaces what is on screen", async ({
+ page,
+ }) => {
+ await installTauri(page);
+ await gotoFiles(page);
+ await stage(page, onDisk(), [report()]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await openCard(page, "quarterly-report.pdf");
+
+ await expect(viewerPageCount(page, 1)).toBeVisible({ timeout: 30_000 });
+
+ // Deliberately without navigating away: re-opening from the file list
+ // remounts the viewer and rebuilds its blob URL either way, hiding the bug.
+ // This is the live path - the file stays open and the watcher fires.
+ await editOnDisk(page, REPORT, PDF_8_PAGES);
+ await emitWatch(page, [REPORT]);
+
+ await expect(page.getByText(/Updated from disk/i).first()).toBeVisible({
+ timeout: 20_000,
+ });
+ // The bug this pins: the toast fired while the viewer kept the old document,
+ // so it went on rendering one page of bytes nobody had any more.
+ await expect(viewerPageCount(page, 8)).toBeVisible({ timeout: 20_000 });
+ });
+
+ test("the second external edit reaches the editor too", async ({ page }) => {
+ await installTauri(page);
+ await gotoFiles(page);
+ await stage(page, onDisk(), [report()]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await openCard(page, "quarterly-report.pdf");
+
+ await page.getByText("PDF Multi Tool", { exact: true }).first().click();
+ await expect(editorPages(page)).toHaveCount(1, { timeout: 30_000 });
+
+ // The bug this pins: picking up a reload left the record with no page data
+ // and nothing regenerated it, so the editor fell back to a placeholder
+ // built from deps a bytes-only change cannot move. The first reload looked
+ // right; every one after it was dropped, in either direction.
+ for (const [bytes, pages] of [
+ [PDF_8_PAGES, 8],
+ [PDF_1_PAGE, 1],
+ [PDF_8_PAGES, 8],
+ ] as const) {
+ await editOnDisk(page, REPORT, bytes);
+ await emitWatch(page, [REPORT]);
+ await expect(editorPages(page)).toHaveCount(pages, { timeout: 30_000 });
+ }
+ });
+
+ test("an open page editor's edits are offered as a choice, not overwritten", async ({
+ page,
+ }) => {
+ await installTauri(page);
+ await gotoFiles(page);
+ await stage(page, onDisk(), [report()]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await openCard(page, "quarterly-report.pdf");
+
+ await page.getByText("PDF Multi Tool", { exact: true }).first().click();
+ const firstPage = page.locator("[data-page-id]").first();
+ await firstPage.waitFor({ state: "visible", timeout: 30_000 });
+ await firstPage.hover();
+ await firstPage.getByRole("button", { name: "Rotate Right" }).click();
+
+ // Nothing has committed a version, so the stub is still clean. Before the
+ // fix that was the only dirty signal reconciliation looked at.
+ await editOnDisk(page, REPORT, PDF_8_PAGES);
+ await emitWatch(page, [REPORT]);
+
+ await expect(
+ page.getByRole("button", { name: /Keep my changes/i }),
+ ).toBeVisible({ timeout: 20_000 });
+ await expect(page.getByText(/Updated from disk/i)).toHaveCount(0);
+ });
+
+ test("an earlier version opens as itself, not as today's file", async ({
+ page,
+ }) => {
+ await installTauri(page);
+ await gotoFiles(page);
+ // A tool ran and its output was saved over the path, so v2 is the leaf and
+ // v1 keeps a baseline describing the file as it was when v1 was current.
+ await stage(page, onDisk(), [
+ report({ id: "f-v1", isLeaf: false, versionNumber: 1 }),
+ report({
+ id: "f-v2",
+ isLeaf: true,
+ versionNumber: 2,
+ parentFileId: "f-v1",
+ originalFileId: "f-v1",
+ }),
+ ]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await editOnDisk(page, REPORT, PDF_8_PAGES);
+
+ const card = page.locator(".files-page-card").first();
+ await card.scrollIntoViewIfNeeded();
+ await card.getByRole("button", { name: /File actions/i }).click();
+ await page
+ .getByText(/Version history/i)
+ .first()
+ .click();
+ await page
+ .getByRole("button", { name: /Version actions/i })
+ .first()
+ .click();
+ await page
+ .getByText(/Open in workspace/i)
+ .first()
+ .click();
+
+ // "Open in workspace" lands in the viewer. The historical version has one
+ // page while today's disk file has eight, so the rendered page count tells
+ // us which bytes were actually opened.
+ await expect(viewerPageCount(page, 1)).toBeVisible({ timeout: 30_000 });
+ // Reconciliation is the first thing hydration does, so anything it was
+ // going to replace has been replaced by the time the viewer settles.
+ await page.waitForTimeout(4000);
+ await expect(viewerPageCount(page, 1)).toBeVisible();
+ await expect(viewerPageCount(page, 8)).toHaveCount(0);
+ await expect(page.getByText(/Updated from disk/i)).toHaveCount(0);
+
+ const storedSize = await page.evaluate(async () => {
+ const db = await new Promise<IDBDatabase>((resolve, reject) => {
+ const req = indexedDB.open("stirling-pdf-files");
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ });
+ const record = await new Promise<{ size?: number } | undefined>(
+ (resolve, reject) => {
+ const req = db
+ .transaction(["files"], "readonly")
+ .objectStore("files")
+ .get("f-v1");
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ },
+ );
+ db.close();
+ return record?.size ?? null;
+ });
+ // The data loss this pins: reconciliation reloaded the path and wrote
+ // today's bytes over the only copy that version had.
+ expect(storedSize).toBe(PDF_1_PAGE.length);
+ });
+
+ test("taking the disk version replaces what the editor is showing", async ({
+ page,
+ }) => {
+ await conflictInPageEditor(page);
+ await expect(editorPages(page)).toHaveCount(1);
+
+ await page.getByRole("button", { name: /Use the disk version/i }).click();
+
+ // Resolving towards disk has to reach the open editor, not just storage.
+ await expect(editorPages(page)).toHaveCount(8, { timeout: 30_000 });
+ await expect(
+ page.getByRole("button", { name: /Keep my changes/i }),
+ ).toHaveCount(0);
+ });
+
+ test("keeping my changes leaves the document alone and flags the file", async ({
+ page,
+ }) => {
+ await conflictInPageEditor(page);
+
+ await page.getByRole("button", { name: /Keep my changes/i }).click();
+ await expect(
+ page.getByRole("button", { name: /Keep my changes/i }),
+ ).toHaveCount(0);
+ await expect(editorPages(page)).toHaveCount(1);
+
+ // The decision outlives the modal: the list has to say the two still differ.
+ await gotoFiles(page);
+ await dismissModals(page);
+ await expect(
+ page.getByRole("img", { name: /Disk changed/i }).first(),
+ ).toBeVisible({ timeout: 20_000 });
+ });
+
+ test("a file deleted on disk stays open and says saving will relocate it", async ({
+ page,
+ }) => {
+ await installTauri(page);
+ await gotoFiles(page);
+ await stage(page, onDisk(), [report()]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await openCard(page, "quarterly-report.pdf");
+
+ await deleteOnDisk(page, REPORT);
+ await emitWatch(page, [REPORT]);
+
+ await expect(
+ page.getByText(/no longer exists on disk/i).first(),
+ ).toBeVisible({ timeout: 20_000 });
+ // Never deleted from under the user: the document is the only copy now.
+ await expect(viewerPageCount(page, 1)).toBeVisible();
+
+ await gotoFiles(page);
+ await dismissModals(page);
+ await expect(
+ page.getByRole("img", { name: /Not on disk/i }).first(),
+ ).toBeVisible({ timeout: 20_000 });
+ });
+
+ test("a conflict raised at open time still shows the stored document", async ({
+ page,
+ }) => {
+ await installTauri(page);
+ await gotoFiles(page);
+ // Already dirty from a previous session, and disk moved on while the app
+ // was closed: the conflict is raised by the open itself, not the watcher.
+ await stage(page, onDisk(), [report({ isDirty: true })]);
+ await dismissModals(page);
+ await requireDiskLinking(page);
+ await editOnDisk(page, REPORT, PDF_8_PAGES);
+ await openCard(page, "quarterly-report.pdf");
+
+ await expect(
+ page.getByRole("button", { name: /Keep my changes/i }),
+ ).toBeVisible({ timeout: 20_000 });
+ // Asking the user to choose over a blank viewer gives them nothing to
+ // choose between: their own version has to be on screen behind the modal.
+ await expect(viewerPageCount(page, 1)).toBeVisible({ timeout: 20_000 });
+ });
+});
diff --git a/frontend/editor/src/core/types/documentIdentity.test.ts b/frontend/editor/src/core/types/documentIdentity.test.ts
new file mode 100644
index 0000000000..e5f8a5f0f7
--- /dev/null
+++ b/frontend/editor/src/core/types/documentIdentity.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect } from "vitest";
+import {
+ createStirlingFile,
+ getFormFillFileId,
+ documentBytesReplaced,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+const ID = "file-1" as FileId;
+
+function diskFile(bytes: number[], modifiedMs: number): File {
+ return new File([new Uint8Array(bytes)], "report.pdf", {
+ type: "application/pdf",
+ lastModified: modifiedMs,
+ });
+}
+
+describe("getFormFillFileId", () => {
+ it("turns over when a disk reload swaps the bytes under one id", () => {
+ // The viewer keys its mount, its blob URL and its form state on this. An
+ // id-only key left the previous document on screen under "Updated from disk".
+ const before = createStirlingFile(diskFile([1, 2, 3], 5000), ID);
+ const after = createStirlingFile(diskFile([1, 2, 3, 4], 9000), ID);
+
+ expect(after.fileId).toBe(before.fileId);
+ expect(getFormFillFileId(after)).not.toBe(getFormFillFileId(before));
+ });
+
+ it("is stable while the same bytes are re-wrapped each render", () => {
+ const first = createStirlingFile(diskFile([1, 2, 3], 5000), ID);
+ const second = createStirlingFile(diskFile([1, 2, 3], 5000), ID);
+ expect(getFormFillFileId(second)).toBe(getFormFillFileId(first));
+ });
+
+ it("still separates two files that share content", () => {
+ const mine = createStirlingFile(diskFile([1, 2, 3], 5000), ID);
+ const theirs = createStirlingFile(
+ diskFile([1, 2, 3], 5000),
+ "file-2" as FileId,
+ );
+ expect(getFormFillFileId(theirs)).not.toBe(getFormFillFileId(mine));
+ });
+});
+
+describe("documentBytesReplaced", () => {
+ const identity = (id: string, key: string) => ({ id: id as FileId, key });
+
+ it("reports a disk reload that swapped the bytes under one id", () => {
+ expect(
+ documentBytesReplaced(identity(ID, "before"), identity(ID, "after")),
+ ).toBe(true);
+ });
+
+ it("ignores a switch to a different file", () => {
+ expect(
+ documentBytesReplaced(
+ identity(ID, "before"),
+ identity("file-2", "after"),
+ ),
+ ).toBe(false);
+ });
+
+ it("ignores a re-render that changed nothing", () => {
+ expect(
+ documentBytesReplaced(identity(ID, "same"), identity(ID, "same")),
+ ).toBe(false);
+ });
+
+ it("ignores a first sighting and an emptied viewer", () => {
+ expect(documentBytesReplaced(null, identity(ID, "after"))).toBe(false);
+ expect(documentBytesReplaced(identity(ID, "before"), null)).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/core/types/fileContext.ts b/frontend/editor/src/core/types/fileContext.ts
index 3fb15a1687..262a69cbb4 100644
--- a/frontend/editor/src/core/types/fileContext.ts
+++ b/frontend/editor/src/core/types/fileContext.ts
@@ -5,6 +5,7 @@
import { PageOperation } from "@app/types/pageEditor";
import { FileId, BaseFileMetadata } from "@app/types/file";
import { generateId } from "@app/utils/generateId";
+import type { DiskUnavailableReason } from "@app/services/desktopFileLink";
// Re-export FileId for convenience
export type { FileId };
@@ -53,6 +54,20 @@ export interface StirlingFileStub extends BaseFileMetadata {
thumbnailUrl?: string; // Generated thumbnail blob URL for visual display
blobUrl?: string; // File access blob URL for downloads/processing
localFilePath?: string; // Original local filesystem path (desktop app only)
+ // Size/mtime of the disk file the last time we read it. An external edit moves
+ // one of them, which is how a stale stored copy is spotted without hashing.
+ diskSyncedSize?: number;
+ diskSyncedModifiedMs?: number;
+ // Disk path whose original is deleted, kept so the badge keeps saying "not on
+ // disk" long after the toast has gone.
+ orphanedFilePath?: string;
+ // Epoch ms of an unresolved divergence: disk moved on while we held unsaved
+ // edits, so two real versions exist and the user has not picked one yet.
+ diskConflictAt?: number;
+ // Epoch ms of the last pickup of an external edit, so the user can tell whose
+ // version is on screen instead of having to catch a toast.
+ diskReloadedAt?: number;
+ diskUnavailableReason?: DiskUnavailableReason;
processedFile?: ProcessedFileMetadata; // PDF page data and processing results
insertAfterPageId?: string; // Page ID after which this file should be inserted
isPinned?: boolean; // Protected from tool consumption (replace/remove)
@@ -123,9 +138,11 @@ export function isStirlingFile(file: File | Blob): file is StirlingFile {
}
/**
- * Generate a unique identifier for form fill state tracking.
- * This ensures that form widgets/values are correctly isolated between files
- * even if they have the same name or are re-scanned.
+ * Identity of the bytes on screen, for state that must not outlive them: form
+ * widgets and values, and the viewer's document mount.
+ *
+ * <p>Keyed on content, not on the file: a disk reload swaps the bytes under an
+ * unchanged fileId, and an id-only key leaves the previous document mounted.
*/
export function getFormFillFileId(
file: File | Blob | null | undefined,
@@ -133,7 +150,7 @@ export function getFormFillFileId(
if (!file) return null;
if (isStirlingFile(file)) {
- return `stirling-${file.fileId}`;
+ return `stirling-${file.fileId}-${file.quickKey}`;
}
if (file instanceof File) {
@@ -144,6 +161,25 @@ export function getFormFillFileId(
return `blob-${file.size || 0}`;
}
+/** A document as the viewer tracks it: which workbench record, and which bytes.
+ * The key is a {@link getFormFillFileId} value. */
+export interface DocumentIdentity {
+ id: FileId;
+ key: string;
+}
+
+/** Whether the same record is now showing different bytes, which is what
+ * accepting a disk reload does. A different record is a file switch and a
+ * missing side is a first sighting; neither invalidates work held against the
+ * document that was on screen. */
+export function documentBytesReplaced(
+ previous: DocumentIdentity | null,
+ current: DocumentIdentity | null,
+): boolean {
+ if (!previous || !current) return false;
+ return previous.id === current.id && previous.key !== current.key;
+}
+
// Create a StirlingFile from a regular File object
export function createStirlingFile(file: File, id?: FileId): StirlingFile {
// If the file already has Stirling metadata and we aren't trying to override it,
@@ -391,6 +427,9 @@ export interface FileContextActions {
id: FileId,
updates: Partial<StirlingFileStub>,
) => void;
+ /** Something changed at these source locations; settle any open record
+ * that came from one of them. */
+ reconcileOpenFiles: (locations: string[]) => Promise<void>;
reorderFiles: (orderedFileIds: FileId[]) => void;
clearAllFiles: () => Promise<void>;
clearAllData: () => Promise<void>;
diff --git a/frontend/editor/src/desktop/components/AppProviders.tsx b/frontend/editor/src/desktop/components/AppProviders.tsx
index 0285c107ae..c9dcafb1e3 100644
--- a/frontend/editor/src/desktop/components/AppProviders.tsx
+++ b/frontend/editor/src/desktop/components/AppProviders.tsx
@@ -5,6 +5,7 @@ import { WindowTitleBar } from "@app/components/WindowTitleBar";
import { DesktopQueryCacheReset } from "@app/components/DesktopQueryCacheReset";
import { DesktopBannerInitializer } from "@app/components/DesktopBannerInitializer";
import { SaveShortcutListener } from "@app/components/SaveShortcutListener";
+import { DiskConflictHost } from "@app/components/shared/DiskConflictHost";
import { DesktopOnboardingModal } from "@app/components/DesktopOnboardingModal";
import { DesktopSaasOnboardingBootstrap } from "@app/components/DesktopSaasOnboardingBootstrap";
import UsageLimitModalHost from "@app/components/UsageLimitModalHost";
@@ -361,6 +362,7 @@ export function AppProviders({ children }: { children: ReactNode }) {
<DesktopConfigSync />
<DesktopBannerInitializer />
<SaveShortcutListener />
+ <DiskConflictHost />
{children}
{/* Desktop onboarding modal: welcome slide → sign-in slide, shown once on first launch */}
<DesktopOnboardingModal />
diff --git a/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx b/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx
new file mode 100644
index 0000000000..bf2ccc65ed
--- /dev/null
+++ b/frontend/editor/src/desktop/components/DesktopOnboardingModal.test.tsx
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { DesktopOnboardingModal } from "@app/components/DesktopOnboardingModal";
+
+const { isAuthenticated } = vi.hoisted(() => ({
+ isAuthenticated: vi.fn<() => Promise<boolean>>(),
+}));
+
+vi.mock("@app/services/authService", () => ({
+ authService: { isAuthenticated },
+}));
+
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: { switchToLocal: vi.fn() },
+}));
+
+vi.mock("@app/components/onboarding/OnboardingSlideShell", () => ({
+ default: ({ opened }: { opened: boolean }) =>
+ opened ? <div role="dialog">Desktop onboarding</div> : null,
+ ShellHero: () => null,
+}));
+
+vi.mock("@app/components/SetupWizard", () => ({
+ SetupWizard: () => null,
+}));
+
+vi.mock("@app/components/onboarding/slides/WelcomeSlide", () => ({
+ default: () => ({ title: "Welcome", body: null }),
+}));
+
+vi.mock(
+ "@app/components/onboarding/classificationDemo/ClassificationDemoModal",
+ () => ({ ClassificationDemoModal: () => null }),
+);
+
+function renderModal() {
+ return render(
+ <MemoryRouter>
+ <DesktopOnboardingModal />
+ </MemoryRouter>,
+ );
+}
+
+describe("DesktopOnboardingModal", () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ isAuthenticated.mockReset().mockResolvedValue(true);
+ });
+
+ it("shows onboarding to a new desktop user", async () => {
+ renderModal();
+
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("honours the shared onboarding bypass", async () => {
+ sessionStorage.setItem("onboarding::bypass-all", "true");
+
+ renderModal();
+
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx b/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
index a5e6fac680..397bdfaac6 100644
--- a/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
+++ b/frontend/editor/src/desktop/components/DesktopOnboardingModal.tsx
@@ -9,6 +9,7 @@ import { SetupWizard } from "@app/components/SetupWizard";
import WelcomeSlide from "@app/components/onboarding/slides/WelcomeSlide";
import { connectionModeService } from "@app/services/connectionModeService";
import { ClassificationDemoModal } from "@app/components/onboarding/classificationDemo/ClassificationDemoModal";
+import { useBypassOnboarding } from "@app/components/onboarding/useBypassOnboarding";
/** Bumped whenever the welcome copy changes materially: it means "has seen the current
* welcome", not "has launched before". The old key is left behind, not migrated. */
@@ -20,6 +21,7 @@ const CLASSIFICATION_DEMO_KEY = "stirling-desktop-classification-demo-seen";
* aimed at server admins. Uses the shared shell, as every other onboarding does. */
export function DesktopOnboardingModal() {
const { t } = useTranslation();
+ const bypassOnboarding = useBypassOnboarding();
const [visible, setVisible] = useState(
() => !localStorage.getItem(ONBOARDING_KEY),
);
@@ -85,6 +87,8 @@ export function DesktopOnboardingModal() {
// reconstructed on every render while the modal is open.
const welcomeSlide = useMemo(() => WelcomeSlide(), []);
+ if (bypassOnboarding) return null;
+
if (!visible) {
// Accepting the offer hands the workbench canvas to the sweep, which outlives this
// modal — the session store owns it from there, so nothing else needs to stay mounted.
diff --git a/frontend/editor/src/desktop/components/SaveShortcutListener.tsx b/frontend/editor/src/desktop/components/SaveShortcutListener.tsx
index e4204e6a24..a1ecf84a44 100644
--- a/frontend/editor/src/desktop/components/SaveShortcutListener.tsx
+++ b/frontend/editor/src/desktop/components/SaveShortcutListener.tsx
@@ -2,6 +2,7 @@ import { useSaveShortcut } from "@app/hooks/useSaveShortcut";
import { useExitWarning } from "@app/hooks/useExitWarning";
import { useNewWindowShortcut } from "@app/hooks/useNewWindowShortcut";
import { useOpenWindowFiles } from "@app/hooks/useOpenWindowFiles";
+import { useDiskWatcher } from "@app/hooks/useDiskWatcher";
/**
* Desktop-only component that sets up keyboard shortcuts and exit warnings
@@ -9,6 +10,7 @@ import { useOpenWindowFiles } from "@app/hooks/useOpenWindowFiles";
* - Ctrl/Cmd+N to open an empty new window
* - Loads files queued for this window ("Open in new window" from My Files)
* - Warning on app exit if unsaved files
+ * - Watches open files' disk originals for external edits and deletions
* Renders nothing, just sets up the listeners
*/
export function SaveShortcutListener() {
@@ -16,5 +18,6 @@ export function SaveShortcutListener() {
useNewWindowShortcut();
useOpenWindowFiles();
useExitWarning();
+ useDiskWatcher();
return null;
}
diff --git a/frontend/editor/src/desktop/components/fileEditor/FileEditorStatusDot.tsx b/frontend/editor/src/desktop/components/fileEditor/FileEditorStatusDot.tsx
index e27b50dadc..72c9df88c0 100644
--- a/frontend/editor/src/desktop/components/fileEditor/FileEditorStatusDot.tsx
+++ b/frontend/editor/src/desktop/components/fileEditor/FileEditorStatusDot.tsx
@@ -1,6 +1,7 @@
import { Tooltip } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { StirlingFileStub } from "@app/types/fileContext";
+import { diskLinkState } from "@app/services/diskLinkState";
import styles from "@app/components/fileEditor/FileEditorThumbnail.module.css";
interface FileEditorStatusDotProps {
@@ -10,17 +11,45 @@ interface FileEditorStatusDotProps {
export function FileEditorStatusDot({ file }: FileEditorStatusDotProps) {
const { t } = useTranslation();
- const label = !file.localFilePath
- ? t("fileNotSavedToDisk", "Not saved to disk")
- : file.isDirty
- ? t("unsavedChanges", "Unsaved changes")
- : t("fileSavedToDisk", "Saved to disk");
-
- const color = !file.localFilePath
- ? "var(--mantine-color-red-6)"
- : file.isDirty
- ? "var(--mantine-color-yellow-6)"
- : "var(--mantine-color-green-6)";
+ // Orphaned needs its own case: sharing "not saved to disk" would make a
+ // deleted original indistinguishable from a file never saved.
+ const { label, color } = (() => {
+ switch (diskLinkState(file)) {
+ case "orphaned":
+ return {
+ label: t(
+ "fileOriginalDeleted",
+ "Original deleted - save to keep a copy",
+ ),
+ color: "var(--mantine-color-red-6)",
+ };
+ case "conflict":
+ return {
+ label: t("fileChangedOnDisk", "Changed on disk since you edited it"),
+ color: "var(--mantine-color-orange-6)",
+ };
+ case "unavailable":
+ return {
+ label: t("fileDiskUnavailable", "Cannot reach the file on disk"),
+ color: "var(--mantine-color-gray-5)",
+ };
+ case "none":
+ return {
+ label: t("fileNotSavedToDisk", "Not saved to disk"),
+ color: "var(--mantine-color-red-6)",
+ };
+ default:
+ return file.isDirty
+ ? {
+ label: t("unsavedChanges", "Unsaved changes"),
+ color: "var(--mantine-color-yellow-6)",
+ }
+ : {
+ label: t("fileSavedToDisk", "Saved to disk"),
+ color: "var(--mantine-color-green-6)",
+ };
+ }
+ })();
return (
<div className={styles.thumbBadgesRight}>
diff --git a/frontend/editor/src/desktop/components/shared/DiskConflictHost.tsx b/frontend/editor/src/desktop/components/shared/DiskConflictHost.tsx
new file mode 100644
index 0000000000..2124e4842b
--- /dev/null
+++ b/frontend/editor/src/desktop/components/shared/DiskConflictHost.tsx
@@ -0,0 +1,27 @@
+import { useEffect, useState } from "react";
+
+import { DiskConflictModal } from "@app/components/shared/DiskConflictModal";
+import {
+ DiskConflictRequest,
+ resolveDiskConflict,
+ subscribeDiskConflicts,
+} from "@app/services/diskConflictPrompt";
+
+/** Renders the conflict modal for whatever the hydration path has queued.
+ * Mounted once, desktop-side; renders nothing while the queue is empty. */
+export function DiskConflictHost() {
+ const [queue, setQueue] = useState<DiskConflictRequest[]>([]);
+
+ useEffect(() => subscribeDiskConflicts(setQueue), []);
+
+ const current = queue[0];
+ return (
+ <DiskConflictModal
+ opened={Boolean(current)}
+ fileName={current?.name}
+ remainingCount={Math.max(0, queue.length - 1)}
+ onKeepMine={() => resolveDiskConflict("mine")}
+ onUseDisk={() => resolveDiskConflict("disk")}
+ />
+ );
+}
diff --git a/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts b/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts
new file mode 100644
index 0000000000..83e7980d1e
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/diskConflictMark.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import type {
+ FileContextState,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// updateStirlingFileStub drops updates for a file not yet in filesRef, so marking
+// the conflict before the bytes are published loses the badge with no visible failure.
+
+const diskState = vi.hoisted(() => ({
+ state: { availability: "present", size: 999, modifiedMs: 9_000 },
+}));
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState: vi.fn(async () => diskState.state),
+ readFileFromDisk: vi.fn(async () => new Uint8Array([1, 2, 3]).buffer),
+}));
+
+const getStirlingFile = vi.hoisted(() => vi.fn());
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { getStirlingFile, updateFileMetadata: vi.fn(async () => true) },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: () => new Promise(() => {}),
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+const dirtyLinkedStub = (): StirlingFileStub =>
+ ({
+ id: "f1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 10,
+ lastModified: 0,
+ localFilePath: "C:/docs/report.pdf",
+ // Baseline differs from the disk state above, so the file has moved on...
+ diskSyncedSize: 10,
+ diskSyncedModifiedMs: 1_000,
+ // ...and unsaved edits mean we keep ours: a conflict.
+ isDirty: true,
+ }) as StirlingFileStub;
+
+beforeEach(() => {
+ getStirlingFile.mockImplementation(
+ async () =>
+ new File(["%PDF-1.7"], "report.pdf", { type: "application/pdf" }),
+ );
+});
+
+async function hydrate() {
+ vi.resetModules();
+ const { addStirlingFileStubs } =
+ await import("@app/contexts/file/fileActions");
+
+ const state = {
+ files: { ids: [], byId: {} },
+ pinnedFiles: new Set(),
+ ui: { selectedFileIds: [], selectedPageNumbers: [] },
+ } as unknown as FileContextState;
+ const stateRef = { current: state };
+ const filesRef = { current: new Map<FileId, File>() };
+ const updates: Partial<StirlingFileStub>[] = [];
+
+ const lifecycleManager = {
+ // Mirrors the real guard: an update for a file absent from filesRef is
+ // dropped. Without this the test would pass against the broken ordering.
+ updateStirlingFileStub: (
+ fileId: FileId,
+ patch: Partial<StirlingFileStub>,
+ ) => {
+ if (!filesRef.current.has(fileId)) return;
+ updates.push(patch);
+ },
+ removeFiles: () => {},
+ trackBlobUrl: () => {},
+ };
+
+ await addStirlingFileStubs(
+ [dirtyLinkedStub()],
+ {},
+ stateRef,
+ filesRef,
+ () => {},
+ lifecycleManager as never,
+ );
+ return updates;
+}
+
+describe("a disk conflict is recorded on the stub, not just toasted", () => {
+ test("diskConflictAt survives the filesRef ordering guard", async () => {
+ const updates = await hydrate();
+ await vi.waitFor(() =>
+ expect(updates.some((u) => typeof u.diskConflictAt === "number")).toBe(
+ true,
+ ),
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/diskMarkerLifecycle.test.ts b/frontend/editor/src/desktop/contexts/file/diskMarkerLifecycle.test.ts
new file mode 100644
index 0000000000..1245369b55
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/diskMarkerLifecycle.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId, ToolOperation } from "@app/types/file";
+
+// A conflict marker must not outlive its file, nor precede one: the modal would
+// name a file that is gone, and an inherited marker suppresses the child's own.
+
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState: vi.fn(async () => ({
+ availability: "present" as const,
+ size: 1,
+ modifiedMs: 1,
+ })),
+ readFileFromDisk: vi.fn(async () => null),
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile: vi.fn(),
+ updateFileMetadata: vi.fn(async () => true),
+ },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: () => new Promise(() => {}),
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+import { FileLifecycleManager } from "@app/contexts/file/lifecycle";
+import { createChildStub } from "@app/contexts/file/fileActions";
+import {
+ requestDiskConflictChoice,
+ subscribeDiskConflicts,
+ __resetDiskConflicts,
+} from "@app/services/diskConflictPrompt";
+
+beforeEach(() => __resetDiskConflicts());
+
+function manager() {
+ const filesRef = { current: new Map<FileId, File>() };
+ return new FileLifecycleManager(filesRef, vi.fn());
+}
+
+function queuedIds(): FileId[] {
+ let seen: { fileId: FileId }[] = [];
+ const off = subscribeDiskConflicts((queue) => {
+ seen = queue;
+ });
+ off();
+ return seen.map((q) => q.fileId);
+}
+
+describe("closing a file drops its queued conflict", () => {
+ test("removeFiles cancels the prompt", () => {
+ requestDiskConflictChoice({
+ fileId: "a" as FileId,
+ name: "a.pdf",
+ onUseDisk: vi.fn(),
+ });
+ requestDiskConflictChoice({
+ fileId: "b" as FileId,
+ name: "b.pdf",
+ onUseDisk: vi.fn(),
+ });
+ manager().removeFiles(["a" as FileId]);
+ expect(queuedIds()).toEqual(["b"]);
+ });
+
+ test("the delayed-cleanup path cancels it too", () => {
+ requestDiskConflictChoice({
+ fileId: "a" as FileId,
+ name: "a.pdf",
+ onUseDisk: vi.fn(),
+ });
+ manager().cleanupFile("a" as FileId);
+ expect(queuedIds()).toEqual([]);
+ });
+});
+
+describe("a tool output does not inherit its parent's disk markers", () => {
+ const parent = {
+ id: "p1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 10,
+ lastModified: 0,
+ isLeaf: true,
+ versionNumber: 1,
+ localFilePath: "C:/docs/report.pdf",
+ diskSyncedSize: 500,
+ diskSyncedModifiedMs: 400,
+ diskConflictAt: 123,
+ diskReloadedAt: 456,
+ } as StirlingFileStub;
+
+ const operation: ToolOperation = { toolId: "split", timestamp: 1 };
+
+ test("clears the markers but keeps the link and its baseline", () => {
+ const child = createChildStub(
+ parent,
+ operation,
+ new File(["%PDF-1.7"], "report_split.pdf", { type: "application/pdf" }),
+ );
+
+ // Inheriting these shows a badge the child never earned, and the conflict
+ // short-circuit in resyncFilesFromDisk would suppress its own prompt.
+ expect(child.diskConflictAt).toBeUndefined();
+ expect(child.diskReloadedAt).toBeUndefined();
+ // The link and baseline must survive: dropping them would raise a bogus
+ // conflict on every open, and Ctrl+S would stop writing back.
+ expect(child.localFilePath).toBe("C:/docs/report.pdf");
+ expect(child.diskSyncedSize).toBe(500);
+ expect(child.diskSyncedModifiedMs).toBe(400);
+ expect(child.isDirty).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/diskMissingHydration.test.ts b/frontend/editor/src/desktop/contexts/file/diskMissingHydration.test.ts
new file mode 100644
index 0000000000..3c03a5c033
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/diskMissingHydration.test.ts
@@ -0,0 +1,143 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import { expectConsole } from "@app/tests/failOnConsole";
+import type {
+ FileContextState,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId, ToolOperation } from "@app/types/file";
+
+// A vanished original must not take unsaved work or version history with it:
+// only an unedited v1 passthrough holds nothing the disk file did not.
+
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState: vi.fn(async () => ({ availability: "gone" as const })),
+ readFileFromDisk: vi.fn(async () => null),
+}));
+
+const getStirlingFile = vi.hoisted(() => vi.fn());
+const deleteStirlingFile = vi.hoisted(() => vi.fn(async () => undefined));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile,
+ deleteStirlingFile,
+ updateFileMetadata: vi.fn(async () => true),
+ },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: () => new Promise(() => {}),
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+const LOST_PATH = "C:/docs/report.pdf";
+
+const linkedStub = (
+ overrides: Partial<StirlingFileStub> = {},
+): StirlingFileStub =>
+ ({
+ id: "f1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 10,
+ lastModified: 0,
+ isLeaf: true,
+ versionNumber: 1,
+ localFilePath: LOST_PATH,
+ diskSyncedSize: 10,
+ diskSyncedModifiedMs: 1_000,
+ ...overrides,
+ }) as StirlingFileStub;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getStirlingFile.mockImplementation(
+ async () =>
+ new File(["%PDF-1.7"], "report.pdf", { type: "application/pdf" }),
+ );
+});
+
+async function hydrate(stub: StirlingFileStub) {
+ vi.resetModules();
+ const { addStirlingFileStubs } =
+ await import("@app/contexts/file/fileActions");
+
+ const state = {
+ files: { ids: [], byId: {} },
+ pinnedFiles: new Set(),
+ ui: { selectedFileIds: [], selectedPageNumbers: [] },
+ } as unknown as FileContextState;
+ const stateRef = { current: state };
+ const filesRef = { current: new Map<FileId, File>() };
+ const updates: Partial<StirlingFileStub>[] = [];
+ const removed: FileId[] = [];
+
+ const lifecycleManager = {
+ // Mirrors the real guard: an update for a file absent from filesRef is
+ // dropped, so a detach recorded too early would be lost.
+ updateStirlingFileStub: (
+ fileId: FileId,
+ patch: Partial<StirlingFileStub>,
+ ) => {
+ if (!filesRef.current.has(fileId)) return;
+ updates.push(patch);
+ },
+ removeFiles: (fileIds: FileId[]) => removed.push(...fileIds),
+ trackBlobUrl: () => {},
+ };
+
+ await addStirlingFileStubs(
+ [stub],
+ {},
+ stateRef,
+ filesRef,
+ () => {},
+ lifecycleManager as never,
+ );
+ return { updates, removed, filesRef };
+}
+
+const operation: ToolOperation = { toolId: "split", timestamp: 1 };
+
+// The link is cut, but the old path is kept so the badge can still say where
+// the original was.
+const detachUpdate = () =>
+ expect.objectContaining({
+ localFilePath: undefined,
+ orphanedFilePath: LOST_PATH,
+ });
+
+describe("a linked file whose original vanished", () => {
+ test("detaches an edited version instead of destroying its only copy", async () => {
+ const { updates, removed, filesRef } = await hydrate(
+ linkedStub({
+ isDirty: true,
+ versionNumber: 2,
+ toolHistory: [operation],
+ }),
+ );
+
+ await vi.waitFor(() => expect(updates).toContainEqual(detachUpdate()));
+ expect(removed).toHaveLength(0);
+ expect(deleteStirlingFile).not.toHaveBeenCalled();
+ // Still served from the stored copy, so the document stays on screen.
+ expect(filesRef.current.has("f1" as FileId)).toBe(true);
+ });
+
+ test("still deletes an unedited passthrough, which holds nothing extra", async () => {
+ expectConsole.warn(/no longer exists at/);
+ const { removed } = await hydrate(linkedStub());
+
+ await vi.waitFor(() => expect(removed).toContain("f1" as FileId));
+ await vi.waitFor(() =>
+ expect(deleteStirlingFile).toHaveBeenCalledWith("f1"),
+ );
+ });
+
+ test("detaches a non-leaf root, which version history still needs", async () => {
+ const { updates, removed } = await hydrate(linkedStub({ isLeaf: false }));
+
+ await vi.waitFor(() => expect(updates).toContainEqual(detachUpdate()));
+ expect(removed).toHaveLength(0);
+ expect(deleteStirlingFile).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts b/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts
new file mode 100644
index 0000000000..47d4c0a09f
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/diskResyncFanOut.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import type {
+ FileContextState,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+const disk = vi.hoisted(() => ({ gone: new Set<string>() }));
+
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState: vi.fn(async (path: string) =>
+ disk.gone.has(path)
+ ? { availability: "gone" as const }
+ : { availability: "present" as const, size: 1, modifiedMs: 1 },
+ ),
+ readFileFromDisk: vi.fn(async () => null),
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile: vi.fn(),
+ updateFileMetadata: vi.fn(async () => true),
+ deleteStirlingFile: vi.fn(async () => undefined),
+ },
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+import { reconcileOpenFilesAt } from "@app/contexts/file/fileActions";
+
+const SHARED = "/Users/x/Documents/report.pdf";
+
+function stub(id: string, path?: string): StirlingFileStub {
+ return {
+ id: id as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 1,
+ lastModified: 1,
+ createdAt: 1,
+ quickKey: `report.pdf|1|${id}`,
+ versionNumber: 1,
+ originalFileId: id as FileId,
+ toolHistory: [],
+ isLeaf: true,
+ localFilePath: path,
+ diskSyncedSize: 1,
+ diskSyncedModifiedMs: 1,
+ } as StirlingFileStub;
+}
+
+function harness(stubs: StirlingFileStub[]) {
+ const byId = Object.fromEntries(stubs.map((s) => [s.id, s]));
+ const stateRef = {
+ current: {
+ files: { byId, ids: stubs.map((s) => s.id) },
+ ui: { hasUnsavedChanges: false },
+ } as unknown as FileContextState,
+ };
+ const updates: { id: FileId; updates: Partial<StirlingFileStub> }[] = [];
+ const lifecycleManager = {
+ updateStirlingFileStub: (id: FileId, u: Partial<StirlingFileStub>) => {
+ updates.push({ id, updates: u });
+ Object.assign(byId[id], u);
+ },
+ };
+ return {
+ stateRef,
+ updates,
+ run: (paths: string[]) =>
+ reconcileOpenFilesAt(
+ paths,
+ stateRef as never,
+ { current: new Map<FileId, File>() },
+ lifecycleManager as never,
+ ),
+ };
+}
+
+beforeEach(() => disk.gone.clear());
+
+describe("a disk path that backs more than one record", () => {
+ test("every record holding it is reconciled, not just the last", async () => {
+ disk.gone.add(SHARED);
+ const h = harness([stub("first", SHARED), stub("second", SHARED)]);
+
+ await h.run([SHARED]);
+
+ const detached = h.updates.filter((u) => "orphanedFilePath" in u.updates);
+ expect(detached.map((u) => u.id).sort()).toEqual(["first", "second"]);
+ for (const update of detached) {
+ expect(update.updates.localFilePath).toBeUndefined();
+ expect(update.updates.orphanedFilePath).toBe(SHARED);
+ }
+ });
+
+ test("a path no record holds does nothing", async () => {
+ const h = harness([stub("first", SHARED)]);
+ await h.run(["/Users/x/Documents/someone-elses-window.pdf"]);
+ expect(h.updates).toEqual([]);
+ });
+
+ test("records on other paths are left alone", async () => {
+ const other = "/Users/x/Documents/notes.pdf";
+ disk.gone.add(SHARED);
+ const h = harness([stub("first", SHARED), stub("other", other)]);
+
+ await h.run([SHARED]);
+
+ expect(h.updates.map((u) => u.id)).toEqual(["first"]);
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/diskTooLargeHydration.test.ts b/frontend/editor/src/desktop/contexts/file/diskTooLargeHydration.test.ts
new file mode 100644
index 0000000000..e0b1730877
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/diskTooLargeHydration.test.ts
@@ -0,0 +1,133 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import type {
+ FileContextState,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// Opening a linked file too large to re-read serves a copy we know is stale, so
+// the open path has to say so exactly as the watcher does.
+
+const AUTO_RELOAD_MAX_BYTES = 512 * 1024 * 1024;
+
+const getDiskFileState = vi.hoisted(() => vi.fn());
+const readFileFromDisk = vi.hoisted(() => vi.fn(async () => null));
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState,
+ readFileFromDisk,
+}));
+
+const getStirlingFile = vi.hoisted(() => vi.fn());
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile,
+ deleteStirlingFile: vi.fn(async () => undefined),
+ updateFileMetadata: vi.fn(async () => true),
+ },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: () => new Promise(() => {}),
+}));
+
+const alert = vi.hoisted(() => vi.fn());
+vi.mock("@app/components/toast", () => ({ alert }));
+
+const PATH = "C:/docs/huge.pdf";
+const STALE_BYTES = "%PDF-old";
+
+const linkedStub = (): StirlingFileStub =>
+ ({
+ id: "f1" as FileId,
+ name: "huge.pdf",
+ type: "application/pdf",
+ size: STALE_BYTES.length,
+ lastModified: 0,
+ isLeaf: true,
+ versionNumber: 1,
+ localFilePath: PATH,
+ diskSyncedSize: STALE_BYTES.length,
+ diskSyncedModifiedMs: 1_000,
+ }) as StirlingFileStub;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getStirlingFile.mockImplementation(
+ async () =>
+ new File([STALE_BYTES], "huge.pdf", { type: "application/pdf" }),
+ );
+});
+
+async function hydrate(diskSize: number) {
+ getDiskFileState.mockImplementation(async () => ({
+ availability: "present" as const,
+ size: diskSize,
+ modifiedMs: 2_000,
+ }));
+ readFileFromDisk.mockImplementation(
+ async () => new TextEncoder().encode("%PDF-new") as unknown as null,
+ );
+
+ vi.resetModules();
+ const { addStirlingFileStubs } =
+ await import("@app/contexts/file/fileActions");
+
+ const state = {
+ files: { ids: [], byId: {} },
+ pinnedFiles: new Set(),
+ ui: { selectedFileIds: [], selectedPageNumbers: [] },
+ } as unknown as FileContextState;
+ const stateRef = { current: state };
+ const filesRef = { current: new Map<FileId, File>() };
+ const updates: Partial<StirlingFileStub>[] = [];
+
+ const lifecycleManager = {
+ updateStirlingFileStub: (
+ fileId: FileId,
+ patch: Partial<StirlingFileStub>,
+ ) => {
+ if (!filesRef.current.has(fileId)) return;
+ updates.push(patch);
+ },
+ removeFiles: () => {},
+ trackBlobUrl: () => {},
+ };
+
+ await addStirlingFileStubs(
+ [linkedStub()],
+ {},
+ stateRef,
+ filesRef,
+ () => {},
+ lifecycleManager as never,
+ );
+ return { updates, filesRef };
+}
+
+describe("opening a linked file that grew past the auto-reload ceiling", () => {
+ test("says the file changed instead of serving stale bytes silently", async () => {
+ const { filesRef } = await hydrate(AUTO_RELOAD_MAX_BYTES + 1);
+
+ await vi.waitFor(() =>
+ expect(alert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "File changed on disk",
+ isPersistentPopup: true,
+ buttonText: "Use disk version",
+ }),
+ ),
+ );
+ // The point of the ceiling: the stored copy is still what opens.
+ expect(readFileFromDisk).not.toHaveBeenCalled();
+ expect(filesRef.current.get("f1" as FileId)?.size).toBe(STALE_BYTES.length);
+ });
+
+ test("stays silent below the ceiling, where the change is just read", async () => {
+ await hydrate(8);
+
+ await vi.waitFor(() => expect(readFileFromDisk).toHaveBeenCalled());
+ expect(alert).not.toHaveBeenCalledWith(
+ expect.objectContaining({ title: "File changed on disk" }),
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts b/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts
new file mode 100644
index 0000000000..68c179fc3b
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/diskVersionHistoryHydration.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import type {
+ FileContextState,
+ StirlingFileStub,
+} from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// Version History hands its records straight to addStirlingFileStubs, and a
+// superseded version still carries the path its child was saved over. Disk
+// therefore reads as changed while these bytes are the only copy that version
+// has, so reloading it here destroys the journey the modal exists to show.
+
+const getDiskFileState = vi.hoisted(() => vi.fn());
+const readFileFromDisk = vi.hoisted(() => vi.fn());
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState,
+ readFileFromDisk,
+}));
+
+const getStirlingFile = vi.hoisted(() => vi.fn());
+const updateFileMetadata = vi.hoisted(() => vi.fn(async () => true));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile,
+ deleteStirlingFile: vi.fn(async () => undefined),
+ updateFileMetadata,
+ },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: () => new Promise(() => {}),
+}));
+
+const alert = vi.hoisted(() => vi.fn());
+vi.mock("@app/components/toast", () => ({ alert }));
+
+const PATH = "C:/docs/report.pdf";
+const V1_BYTES = "%PDF-v1";
+const SAVED_CHILD_BYTES = "%PDF-v2-on-disk";
+
+const versionStub = (isLeaf: boolean): StirlingFileStub =>
+ ({
+ id: "v1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: V1_BYTES.length,
+ lastModified: 1_000,
+ isLeaf,
+ originalFileId: "v1",
+ versionNumber: 1,
+ localFilePath: PATH,
+ // Stamped when v1 was the live file, so it predates the child's write.
+ diskSyncedSize: V1_BYTES.length,
+ diskSyncedModifiedMs: 1_000,
+ }) as StirlingFileStub;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getStirlingFile.mockImplementation(
+ async () => new File([V1_BYTES], "report.pdf", { type: "application/pdf" }),
+ );
+ getDiskFileState.mockImplementation(async () => ({
+ availability: "present" as const,
+ size: SAVED_CHILD_BYTES.length,
+ modifiedMs: 9_000,
+ }));
+ readFileFromDisk.mockImplementation(
+ async () => new TextEncoder().encode(SAVED_CHILD_BYTES).buffer,
+ );
+});
+
+async function openFromHistory(isLeaf: boolean) {
+ vi.resetModules();
+ const { addStirlingFileStubs } =
+ await import("@app/contexts/file/fileActions");
+
+ const state = {
+ files: { ids: [], byId: {} },
+ pinnedFiles: new Set(),
+ ui: { selectedFileIds: [], selectedPageNumbers: [] },
+ } as unknown as FileContextState;
+ const stateRef = { current: state };
+ const filesRef = { current: new Map<FileId, File>() };
+ const updates: Partial<StirlingFileStub>[] = [];
+
+ const lifecycleManager = {
+ updateStirlingFileStub: (
+ fileId: FileId,
+ patch: Partial<StirlingFileStub>,
+ ) => {
+ if (!filesRef.current.has(fileId)) return;
+ updates.push(patch);
+ },
+ removeFiles: () => {},
+ trackBlobUrl: () => {},
+ };
+
+ await addStirlingFileStubs(
+ [versionStub(isLeaf)],
+ {},
+ stateRef,
+ filesRef,
+ () => {},
+ lifecycleManager as never,
+ );
+ return { updates, filesRef };
+}
+
+describe("opening an earlier version from Version History", () => {
+ test("opens that version's own bytes, not what is on the path today", async () => {
+ const { filesRef } = await openFromHistory(false);
+
+ await vi.waitFor(() =>
+ expect(filesRef.current.get("v1" as FileId)).toBeDefined(),
+ );
+ // The two versions differ in length, so size alone says which one opened.
+ expect(filesRef.current.get("v1" as FileId)?.size).toBe(V1_BYTES.length);
+ });
+
+ test("never writes today's disk bytes over the stored version", async () => {
+ const { updates } = await openFromHistory(false);
+
+ // The marker patch is the last thing hydration does on this branch, so the
+ // fire-and-forget persist would already have been queued behind it.
+ await vi.waitFor(() => expect(updates.length).toBeGreaterThan(0));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(updateFileMetadata).not.toHaveBeenCalledWith(
+ "v1",
+ expect.objectContaining({ data: expect.anything() }),
+ );
+ expect(readFileFromDisk).not.toHaveBeenCalled();
+ expect(alert).not.toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Updated from disk" }),
+ );
+ });
+
+ test("still reloads the leaf, which does answer for that path", async () => {
+ const { filesRef } = await openFromHistory(true);
+
+ await vi.waitFor(() =>
+ expect(alert).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Updated from disk" }),
+ ),
+ );
+ expect(filesRef.current.get("v1" as FileId)?.size).toBe(
+ SAVED_CHILD_BYTES.length,
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts
new file mode 100644
index 0000000000..811268c8e6
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// The three hooks that carry a record's link to its disk original around the
+// app. They have no other home now, so a change here is a silent one.
+
+const getDiskFileState = vi.hoisted(() => vi.fn());
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState,
+ readFileFromDisk: vi.fn(async () => null),
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: {
+ getStirlingFile: vi.fn(),
+ deleteStirlingFile: vi.fn(),
+ updateFileMetadata: vi.fn(async () => true),
+ },
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
+import {
+ persistedSourceFields,
+ inheritedSourceLink,
+ sourceLinkForNewFile,
+} from "@app/contexts/file/storedFileReconciler";
+
+const PATH = "C:/docs/report.pdf";
+
+const stub = (over: Partial<StirlingFileStub> = {}): StirlingFileStub =>
+ ({
+ id: "f1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 100,
+ lastModified: 5000,
+ isLeaf: true,
+ versionNumber: 1,
+ ...over,
+ }) as StirlingFileStub;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ pendingFilePathMappings.clear();
+ getDiskFileState.mockResolvedValue({
+ availability: "present",
+ size: 100,
+ modifiedMs: 5000,
+ });
+});
+
+describe("persistedSourceFields", () => {
+ it("ignores an update that only touches content", () => {
+ expect(persistedSourceFields({ size: 12, thumbnailUrl: "blob:x" })).toBe(
+ null,
+ );
+ });
+
+ it("picks out the link fields and leaves the rest behind", () => {
+ expect(
+ persistedSourceFields({
+ localFilePath: PATH,
+ diskSyncedSize: 100,
+ thumbnailUrl: "blob:x",
+ }),
+ ).toEqual({ localFilePath: PATH, diskSyncedSize: 100 });
+ });
+
+ it("carries a cleared field through, since a detach is written as undefined", () => {
+ const fields = persistedSourceFields({ localFilePath: undefined });
+ expect(fields).not.toBe(null);
+ expect(fields).toHaveProperty("localFilePath", undefined);
+ });
+});
+
+describe("inheritedSourceLink", () => {
+ it("passes the path and its baseline to the derived file", () => {
+ expect(
+ inheritedSourceLink(
+ stub({
+ localFilePath: PATH,
+ diskSyncedSize: 100,
+ diskSyncedModifiedMs: 5000,
+ }),
+ ),
+ ).toEqual({
+ localFilePath: PATH,
+ diskSyncedSize: 100,
+ diskSyncedModifiedMs: 5000,
+ });
+ });
+
+ it("gives an unlinked source nothing to pass on", () => {
+ expect(inheritedSourceLink(stub())).toEqual({});
+ });
+});
+
+describe("sourceLinkForNewFile", () => {
+ it("links a file the open dialog registered, and baselines it", async () => {
+ pendingFilePathMappings.set("k", PATH);
+ await expect(sourceLinkForNewFile("k")).resolves.toEqual({
+ localFilePath: PATH,
+ diskSyncedSize: 100,
+ diskSyncedModifiedMs: 5000,
+ });
+ // Consumed: a later file sharing the quickKey is not the same file.
+ expect(pendingFilePathMappings.has("k")).toBe(false);
+ });
+
+ it("links without a baseline when disk cannot be read right now", async () => {
+ pendingFilePathMappings.set("k", PATH);
+ getDiskFileState.mockResolvedValue({
+ availability: "unavailable",
+ reason: "permission",
+ });
+ await expect(sourceLinkForNewFile("k")).resolves.toEqual({
+ localFilePath: PATH,
+ });
+ });
+
+ it("leaves a file that came from nowhere unlinked", async () => {
+ await expect(sourceLinkForNewFile("unknown")).resolves.toEqual({});
+ expect(getDiskFileState).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/desktop/contexts/file/storedFileReconciler.ts b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.ts
new file mode 100644
index 0000000000..fa48a50ab8
--- /dev/null
+++ b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.ts
@@ -0,0 +1,338 @@
+import { FileId, StirlingFileStub } from "@app/types/fileContext";
+import type {
+ OpenDecision,
+ ReconcilePort,
+} from "@core/contexts/file/storedFileReconciler";
+import {
+ syncLinkedFileFromDisk,
+ persistDiskUpdate,
+ deleteVanishedFile,
+ detachedFields,
+ diskBaseline,
+ loadDiskVersion,
+ refreshDiskBaselineAfterSave,
+ notifyFileVanished,
+ notifyDiskReloaded,
+ notifyDiskTooLarge,
+ notifyOpenFileDeleted,
+ saveOrphanAsCopy,
+} from "@app/services/diskFileSync";
+import {
+ getDiskFileState,
+ type PresentDiskFileState,
+} from "@app/services/desktopFileLink";
+import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
+import { isPristineLocalPassthrough } from "@app/services/pruneMissingRecentFiles";
+import {
+ cancelDiskConflict,
+ requestDiskConflictChoice,
+} from "@app/services/diskConflictPrompt";
+import { hasUnsavedWork } from "@app/services/unsavedWork";
+
+export type { OpenDecision, ReconcilePort };
+
+// Desktop side of the reconcile seam: here a stored record is a cache of a file
+// on disk, so every read re-checks disk and the workbench is told what changed.
+
+/** Take the disk version of a conflicted file, discarding the unsaved in-app
+ * edits shadowing it. Only reachable from the conflict modal's action. */
+async function useDiskVersion(
+ stub: StirlingFileStub,
+ port: ReconcilePort,
+): Promise<void> {
+ const loaded = await loadDiskVersion(stub);
+ if (!loaded) return;
+ const { file, state } = loaded;
+ const reloadedAt = Date.now();
+ port.putFile(stub.id, file);
+ await persistDiskUpdate(stub.id, file, state, reloadedAt);
+ // Must follow putFile: the workbench drops updates for a file it cannot find.
+ port.updateStub(stub.id, pickedUpFields(file, state, reloadedAt));
+ // pickedUpFields cleared the cached page data; without this the editors lay
+ // out from a placeholder and never get the real document back.
+ port.reprocessFile(stub.id);
+}
+
+/** Fields marking a picked-up disk read, shared by both reconcile paths. */
+function pickedUpFields(
+ file: File,
+ state: PresentDiskFileState,
+ reloadedAt: number,
+): Partial<StirlingFileStub> {
+ return {
+ size: file.size,
+ lastModified: file.lastModified,
+ // The cached page data describes the previous bytes.
+ processedFile: undefined,
+ thumbnailUrl: undefined,
+ isDirty: false,
+ diskConflictAt: undefined,
+ diskReloadedAt: reloadedAt,
+ ...diskBaseline(state),
+ };
+}
+
+// A record's link to its disk original is stamped long after the record was
+// stored, so a change to any of these fields is mirrored back into IndexedDB.
+// In memory only, the link would die on reload.
+const DISK_LINK_FIELDS = [
+ "localFilePath",
+ "isDirty",
+ "diskSyncedSize",
+ "diskSyncedModifiedMs",
+ "orphanedFilePath",
+ "diskConflictAt",
+ "diskReloadedAt",
+] as const satisfies readonly (keyof StirlingFileStub)[];
+
+export function persistedSourceFields(
+ updates: Partial<StirlingFileStub>,
+): Partial<StirlingFileStub> | null {
+ const persisted: Partial<StirlingFileStub> = {};
+ let found = false;
+ for (const field of DISK_LINK_FIELDS) {
+ if (field in updates) {
+ // Object.assign-style copy keeps each field's own type.
+ (persisted as Record<string, unknown>)[field] = updates[field];
+ found = true;
+ }
+ }
+ return found ? persisted : null;
+}
+
+export function inheritedSourceLink(
+ sourceStub: StirlingFileStub,
+): Partial<StirlingFileStub> {
+ if (!sourceStub.localFilePath) return {};
+ return {
+ localFilePath: sourceStub.localFilePath,
+ // Deriving the file wrote nothing to disk, so the source's baseline still
+ // describes it. Without one, the next open reads the link as changed and
+ // claims a false conflict.
+ diskSyncedSize: sourceStub.diskSyncedSize,
+ diskSyncedModifiedMs: sourceStub.diskSyncedModifiedMs,
+ };
+}
+
+export async function sourceLinkForNewFile(
+ quickKey: string,
+): Promise<Partial<StirlingFileStub>> {
+ const localFilePath = pendingFilePathMappings.get(quickKey);
+ if (!localFilePath) return {};
+ pendingFilePathMappings.delete(quickKey);
+ // Baseline what disk held at read time; without it the next open has nothing
+ // to compare against and re-reads the file needlessly.
+ const state = await getDiskFileState(localFilePath);
+ return {
+ localFilePath,
+ ...(state.availability === "present" ? diskBaseline(state) : {}),
+ };
+}
+
+export async function reconcileBeforeOpen(
+ stub: StirlingFileStub,
+ port: ReconcilePort,
+): Promise<OpenDecision> {
+ const fileId = stub.id;
+ const outcome = await syncLinkedFileFromDisk(stub, hasUnsavedWork());
+
+ if (outcome.status === "missing") {
+ // Only an unedited v1 passthrough holds nothing the disk file did not;
+ // anything else is detached, never deleted.
+ if (isPristineLocalPassthrough(stub)) {
+ console.warn(
+ `[Reconcile] ${stub.name} (${fileId}) no longer exists at ${stub.localFilePath}; removing it`,
+ );
+ notifyFileVanished(stub.name);
+ void deleteVanishedFile(fileId);
+ return { drop: true };
+ }
+ return {
+ updates: detachedFields(stub.localFilePath),
+ afterPublish: () => notifyOpenFileDeleted([stub.name]),
+ };
+ }
+
+ if (outcome.status === "updated") {
+ // An edit committed while we were reading disk must not be discarded by a
+ // decision taken before it existed.
+ if (port.getStub(fileId)?.isDirty || hasUnsavedWork()) return {};
+ const { file, state } = outcome;
+ const reloadedAt = Date.now();
+ void persistDiskUpdate(fileId, file, state, reloadedAt).catch((error) =>
+ console.error(
+ `[Reconcile] Failed to persist disk update for ${fileId}:`,
+ error,
+ ),
+ );
+ return {
+ file,
+ updates: pickedUpFields(file, state, reloadedAt),
+ contentReplaced: true,
+ // Swapping the bytes under the user is the right default, but doing it
+ // with no trace leaves them unable to tell whose version they have.
+ afterPublish: () => notifyDiskReloaded(stub.name),
+ };
+ }
+
+ const conflictAt = outcome.status === "conflict" ? Date.now() : undefined;
+ const updates: Partial<StirlingFileStub> = {
+ ...(conflictAt ? { diskConflictAt: conflictAt } : {}),
+ diskUnavailableReason:
+ outcome.status === "unavailable" ? outcome.reason : undefined,
+ };
+
+ if (conflictAt) {
+ return {
+ updates,
+ afterPublish: () =>
+ requestDiskConflictChoice({
+ fileId,
+ name: stub.name,
+ onUseDisk: () => void useDiskVersion(stub, port),
+ }),
+ };
+ }
+
+ if (outcome.status === "too-large") {
+ // The copy served is knowingly stale: too big to re-read unasked. The
+ // baseline is left un-stamped so every reopen asks again, which only works
+ // if the ask is visible.
+ return {
+ updates,
+ afterPublish: () =>
+ notifyDiskTooLarge(stub.name, () => void useDiskVersion(stub, port)),
+ };
+ }
+
+ return { updates };
+}
+
+/** Re-check one open record against disk. Returns it when its original is gone,
+ * so the caller can report a whole batch's losses in one toast. */
+async function resyncRecord(
+ stub: StirlingFileStub,
+ port: ReconcilePort,
+): Promise<StirlingFileStub | null> {
+ const fileId = stub.id;
+ const outcome = await syncLinkedFileFromDisk(stub, hasUnsavedWork());
+
+ if (outcome.status === "missing") {
+ // Never delete what is on screen: cutting the link leaves the document
+ // intact and makes the next save ask for somewhere to put it.
+ port.updateStub(fileId, detachedFields(stub.localFilePath));
+ return stub;
+ }
+
+ if (outcome.status === "unavailable") {
+ port.updateStub(fileId, { diskUnavailableReason: outcome.reason });
+ return null;
+ }
+
+ if (stub.diskUnavailableReason) {
+ port.updateStub(fileId, { diskUnavailableReason: undefined });
+ }
+
+ // Nothing to reconcile: the change on disk is the child that superseded this
+ // version, and its bytes are not ours to replace.
+ if (outcome.status === "superseded") return null;
+
+ if (outcome.status === "too-large") {
+ notifyDiskTooLarge(stub.name, () => void useDiskVersion(stub, port));
+ return null;
+ }
+
+ if (outcome.status === "conflict") {
+ // Already flagged; re-toasting on every write the other app makes would be
+ // unusable.
+ if (stub.diskConflictAt) return null;
+ port.updateStub(fileId, { diskConflictAt: Date.now() });
+ requestDiskConflictChoice({
+ fileId,
+ name: stub.name,
+ onUseDisk: () => void useDiskVersion(stub, port),
+ });
+ return null;
+ }
+
+ if (outcome.status === "updated") {
+ // The stat, the read and this commit are all awaited, so the decision was
+ // made against a snapshot. Re-check before overwriting the user's bytes.
+ const latest = port.getStub(fileId);
+ if (
+ !latest ||
+ latest.isDirty ||
+ hasUnsavedWork() ||
+ latest.localFilePath !== stub.localFilePath
+ ) {
+ return null;
+ }
+ const { file, state } = outcome;
+ const reloadedAt = Date.now();
+ port.putFile(fileId, file);
+ await persistDiskUpdate(fileId, file, state, reloadedAt);
+ port.updateStub(fileId, pickedUpFields(file, state, reloadedAt));
+ port.reprocessFile(fileId);
+ notifyDiskReloaded(stub.name);
+ }
+
+ return null;
+}
+
+export async function reconcileOpenFiles(
+ locations: string[],
+ port: ReconcilePort,
+): Promise<void> {
+ const wanted = new Set(locations);
+ const byPath = new Map<string, StirlingFileStub[]>();
+ for (const stub of port.listStubs()) {
+ if (!stub.localFilePath || !wanted.has(stub.localFilePath)) continue;
+ const held = byPath.get(stub.localFilePath);
+ if (held) held.push(stub);
+ else byPath.set(stub.localFilePath, [stub]);
+ }
+
+ const detached: StirlingFileStub[] = [];
+ for (const stubs of byPath.values()) {
+ for (const stub of stubs) {
+ const lost = await resyncRecord(stub, port);
+ if (lost) detached.push(lost);
+ }
+ }
+
+ if (detached.length === 0) return;
+ const single = detached.length === 1 ? detached[0] : undefined;
+ notifyOpenFileDeleted(
+ detached.map((stub) => stub.name),
+ single
+ ? () => {
+ void saveOrphanAsCopy(single).then((saved) => {
+ if (saved) port.updateStub(single.id, saved.updates);
+ });
+ }
+ : undefined,
+ );
+}
+
+export function noteFileSaved(
+ fileId: FileId,
+ updates: Partial<StirlingFileStub>,
+ applyUpdates: (updates: Partial<StirlingFileStub>) => void,
+): void {
+ // A save just made disk and app agree, so re-baseline against the file we
+ // wrote. Without this the next open reads it back as an external change.
+ if (updates.isDirty !== false || !updates.localFilePath) return;
+ void refreshDiskBaselineAfterSave(fileId, updates.localFilePath)
+ .then((baseline) => {
+ if (baseline) applyUpdates(baseline);
+ })
+ .catch((error) =>
+ console.error(`[Reconcile] Failed to re-baseline ${fileId}:`, error),
+ );
+}
+
+export function forgetFile(fileId: FileId): void {
+ // A queued conflict for a file that is gone would name it in a blocking modal
+ // whose Use-disk button then no-ops against the workbench's own guard.
+ cancelDiskConflict(fileId);
+}
diff --git a/frontend/editor/src/desktop/hooks/useAppInitialization.ts b/frontend/editor/src/desktop/hooks/useAppInitialization.ts
index 176442cb06..b5df4e26ff 100644
--- a/frontend/editor/src/desktop/hooks/useAppInitialization.ts
+++ b/frontend/editor/src/desktop/hooks/useAppInitialization.ts
@@ -3,6 +3,7 @@ import { useOpenedFile } from "@app/hooks/useOpenedFile";
import { fileOpenService } from "@app/services/fileOpenService";
import { useFileManagement } from "@app/contexts/file/fileHooks";
import { createQuickKey } from "@app/types/fileContext";
+import { getDiskFileState } from "@app/services/desktopFileLink";
/**
* App initialization hook
@@ -80,12 +81,24 @@ export function useAppInitialization(): void {
);
const addedFiles = await addFiles(filesArray, { selectFiles: true });
- addedFiles.forEach((file) => {
- const localFilePath = quickKeyToPath.get(file.quickKey);
- if (localFilePath) {
- updateStirlingFileStub(file.fileId, { localFilePath });
- }
- });
+ // Path is stamped after addFiles stores records, so the link survives restart.
+ // The baseline goes too, or the next open sees a false external change.
+ await Promise.all(
+ addedFiles.map(async (file) => {
+ const localFilePath = quickKeyToPath.get(file.quickKey);
+ if (!localFilePath) return;
+ const state = await getDiskFileState(localFilePath);
+ updateStirlingFileStub(file.fileId, {
+ localFilePath,
+ ...(state.availability === "present"
+ ? {
+ diskSyncedSize: state.size,
+ diskSyncedModifiedMs: state.modifiedMs,
+ }
+ : {}),
+ });
+ }),
+ );
console.log(
`[Desktop] ${loadedFiles.length} opened file(s) added to FileContext`,
diff --git a/frontend/editor/src/desktop/hooks/useDiskLinkReconcile.ts b/frontend/editor/src/desktop/hooks/useDiskLinkReconcile.ts
new file mode 100644
index 0000000000..d348b50508
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useDiskLinkReconcile.ts
@@ -0,0 +1,78 @@
+import { useCallback, useRef } from "react";
+import { FileId } from "@app/types/fileContext";
+import { useAllFiles, useFileActions } from "@app/contexts/file/fileHooks";
+import {
+ detachedFields,
+ notifyOpenFileDeleted,
+ saveOrphanAsCopy,
+} from "@app/services/diskFileSync";
+import type { DetachedOpenFile } from "@app/services/pruneMissingRecentFiles";
+
+// Shared reconcile wiring for the files page and the recent-files list: the detach
+// must reach the workbench stub too, or saves keep writing to the deleted path.
+
+// Both list builders can be in flight at once; ids are remembered briefly so the
+// same loss is reported once.
+const RECENTLY_REPORTED_MS = 5000;
+const reportedAt = new Map<FileId, number>();
+
+function claimReport(ids: FileId[], now: number): boolean {
+ for (const [id, at] of reportedAt) {
+ if (now - at > RECENTLY_REPORTED_MS) reportedAt.delete(id);
+ }
+ const fresh = ids.filter((id) => !reportedAt.has(id));
+ ids.forEach((id) => reportedAt.set(id, now));
+ return fresh.length > 0;
+}
+
+/** Test seam: the guard is module state and would leak between cases. */
+export function __resetDetachReports(): void {
+ reportedAt.clear();
+}
+
+export function useDiskLinkReconcile() {
+ const { actions } = useFileActions();
+ // Read through a ref so the returned callbacks stay stable - their consumers
+ // re-run on identity change, which would loop on every workbench update.
+ const { fileIds, fileStubs } = useAllFiles();
+ const openFileIdsRef = useRef<FileId[]>(fileIds);
+ openFileIdsRef.current = fileIds;
+ const stubsRef = useRef(fileStubs);
+ stubsRef.current = fileStubs;
+
+ const onOpenFilesDetached = useCallback(
+ (files: DetachedOpenFile[]) => {
+ // Cut the link in the workbench too, so Ctrl+S becomes Save As in this
+ // session rather than only after a restart.
+ files.forEach((file) =>
+ actions.updateStirlingFileStub(file.id, detachedFields(file.path)),
+ );
+
+ if (
+ !claimReport(
+ files.map((f) => f.id),
+ Date.now(),
+ )
+ )
+ return;
+
+ const single = files.length === 1 ? files[0] : undefined;
+ notifyOpenFileDeleted(
+ files.map((f) => f.name),
+ single
+ ? () => {
+ const stub = stubsRef.current.find((s) => s.id === single.id);
+ if (!stub) return;
+ void saveOrphanAsCopy(stub).then((saved) => {
+ if (saved)
+ actions.updateStirlingFileStub(stub.id, saved.updates);
+ });
+ }
+ : undefined,
+ );
+ },
+ [actions],
+ );
+
+ return { openFileIdsRef, onOpenFilesDetached };
+}
diff --git a/frontend/editor/src/desktop/hooks/useDiskWatcher.ts b/frontend/editor/src/desktop/hooks/useDiskWatcher.ts
new file mode 100644
index 0000000000..73457f8bab
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useDiskWatcher.ts
@@ -0,0 +1,84 @@
+import { useEffect, useRef } from "react";
+import { useAllFiles, useFileActions } from "@app/contexts/FileContext";
+import {
+ onDiskFilesChanged,
+ watchDiskPaths,
+} from "@app/services/desktopFileLink";
+
+// Watches disk originals of open files: every other reconcile is user-triggered, so
+// an edit or delete under an open file otherwise goes unnoticed until a rebuild.
+
+// Saves arrive as bursts (truncate-then-write, or temp file renamed over the
+// target); settling avoids reading a half-written PDF.
+const SETTLE_MS = 400;
+
+export function useDiskWatcher(): void {
+ const { actions } = useFileActions();
+ const { fileStubs } = useAllFiles();
+
+ const paths = [
+ ...new Set(
+ fileStubs
+ .map((stub) => stub.localFilePath)
+ .filter((path): path is string => Boolean(path)),
+ ),
+ ].sort();
+ // Re-registered whenever the linked set changes. JSON rather than a joined
+ // string: no separator character is safe inside Windows paths.
+ const watchKey = JSON.stringify(paths);
+
+ const pathsRef = useRef(paths);
+ pathsRef.current = paths;
+
+ useEffect(() => {
+ void watchDiskPaths(pathsRef.current);
+ }, [watchKey]);
+
+ useEffect(() => {
+ let unlisten: (() => void) | undefined;
+ let disposed = false;
+ const pending = new Set<string>();
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const flush = () => {
+ timer = undefined;
+ const changed = [...pending];
+ pending.clear();
+ if (changed.length > 0) void actions.reconcileOpenFiles(changed);
+ };
+
+ void onDiskFilesChanged((changed) => {
+ for (const path of changed) pending.add(path);
+ if (pending.size === 0) return;
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(flush, SETTLE_MS);
+ }).then((off) => {
+ // The effect may have been torn down while the listener was registering.
+ if (disposed) off();
+ else unlisten = off;
+ });
+
+ return () => {
+ disposed = true;
+ if (timer) clearTimeout(timer);
+ unlisten?.();
+ };
+ }, [actions]);
+
+ // Every linked path, not just the ones already marked unreachable: a volume
+ // that goes away takes its watches with it, so nothing can raise the first
+ // mark. This also picks up what the watcher cannot see at all - on Windows,
+ // a watched folder being renamed or moved.
+ useEffect(() => {
+ const recheck = () => {
+ const linked = pathsRef.current;
+ if (linked.length > 0) void actions.reconcileOpenFiles(linked);
+ };
+ window.addEventListener("focus", recheck);
+ return () => window.removeEventListener("focus", recheck);
+ }, [actions]);
+
+ // Stop watching when the window goes away, so the watcher does not outlive
+ // the files it was watching for.
+ useEffect(() => () => void watchDiskPaths([]), []);
+}
diff --git a/frontend/editor/src/desktop/services/desktopFileLink.ts b/frontend/editor/src/desktop/services/desktopFileLink.ts
new file mode 100644
index 0000000000..de651541bc
--- /dev/null
+++ b/frontend/editor/src/desktop/services/desktopFileLink.ts
@@ -0,0 +1,79 @@
+import { invoke, isTauri } from "@tauri-apps/api/core";
+import type {
+ DiskFileState,
+ DiskUnavailableReason,
+ PresentDiskFileState,
+} from "@core/services/desktopFileLink";
+
+// Desktop side of the file-link seam; overrides the core no-op via @app alias
+// order so disk-opened files stay 1:1 instead of drifting from IndexedDB.
+
+export type { DiskFileState, DiskUnavailableReason, PresentDiskFileState };
+
+export const desktopFileLinkingSupported = true;
+
+const COULD_NOT_LOOK: DiskFileState = {
+ availability: "unavailable",
+ reason: "unknown",
+};
+
+export async function getDiskFileState(path: string): Promise<DiskFileState> {
+ if (!isTauri()) return COULD_NOT_LOOK;
+ try {
+ return await invoke<DiskFileState>("file_disk_state", { path });
+ } catch (error) {
+ console.error("[desktopFileLink] file_disk_state failed:", error);
+ return COULD_NOT_LOOK;
+ }
+}
+
+export async function watchDiskPaths(paths: string[]): Promise<void> {
+ if (!isTauri()) return;
+ try {
+ await invoke(paths.length > 0 ? "watch_disk_paths" : "unwatch_disk_paths", {
+ paths,
+ });
+ } catch (error) {
+ console.error("[desktopFileLink] watch_disk_paths failed:", error);
+ }
+}
+
+/** Subscribe to watcher events. Resolves to an unsubscribe function. */
+export async function onDiskFilesChanged(
+ handler: (paths: string[]) => void,
+): Promise<() => void> {
+ if (!isTauri()) return () => {};
+ try {
+ const { listen } = await import("@tauri-apps/api/event");
+ return await listen<{ paths: string[] }>("disk-files-changed", (event) =>
+ handler(event.payload?.paths ?? []),
+ );
+ } catch (error) {
+ console.error("[desktopFileLink] disk change listener failed:", error);
+ return () => {};
+ }
+}
+
+/** Live bytes of a linked file, or null when gone/unreadable so callers fall
+ * back to the stored copy instead of showing an empty document. */
+export async function readFileFromDisk(
+ path: string,
+): Promise<ArrayBuffer | null> {
+ if (!isTauri()) return null;
+ try {
+ const { readFile } = await import("@tauri-apps/plugin-fs");
+ const bytes = await readFile(path);
+ // Use a tightly-packed buffer directly; slicing copies the whole file
+ // (2x memory spike on large PDFs). Only slice a view over a larger buffer.
+ return bytes.byteOffset === 0 &&
+ bytes.byteLength === bytes.buffer.byteLength
+ ? bytes.buffer
+ : bytes.buffer.slice(
+ bytes.byteOffset,
+ bytes.byteOffset + bytes.byteLength,
+ );
+ } catch (error) {
+ console.error("[desktopFileLink] readFileFromDisk failed:", path, error);
+ return null;
+ }
+}
diff --git a/frontend/editor/src/desktop/services/diskConflictPrompt.test.ts b/frontend/editor/src/desktop/services/diskConflictPrompt.test.ts
new file mode 100644
index 0000000000..d320ede598
--- /dev/null
+++ b/frontend/editor/src/desktop/services/diskConflictPrompt.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import type { FileId } from "@app/types/file";
+import { expectConsole } from "@app/tests/failOnConsole";
+
+import {
+ requestDiskConflictChoice,
+ resolveDiskConflict,
+ cancelDiskConflict,
+ subscribeDiskConflicts,
+ __resetDiskConflicts,
+} from "@app/services/diskConflictPrompt";
+
+const req = (id: string, onUseDisk = vi.fn()) => ({
+ fileId: id as FileId,
+ name: `${id}.pdf`,
+ onUseDisk,
+});
+
+beforeEach(() => __resetDiskConflicts());
+
+describe("diskConflictPrompt", () => {
+ it("hands the queue to a new subscriber immediately", () => {
+ requestDiskConflictChoice(req("a"));
+ const seen = vi.fn();
+ subscribeDiskConflicts(seen);
+ expect(seen).toHaveBeenCalledWith([
+ expect.objectContaining({ name: "a.pdf" }),
+ ]);
+ });
+
+ it("keeps conflicts in order so the modal answers one at a time", () => {
+ const seen = vi.fn();
+ subscribeDiskConflicts(seen);
+ requestDiskConflictChoice(req("a"));
+ requestDiskConflictChoice(req("b"));
+ expect(seen).toHaveBeenLastCalledWith([
+ expect.objectContaining({ fileId: "a" }),
+ expect.objectContaining({ fileId: "b" }),
+ ]);
+ });
+
+ it("ignores a repeat for the same file", () => {
+ // A re-check of the same divergence must not stack modals behind each other.
+ requestDiskConflictChoice(req("a"));
+ requestDiskConflictChoice(req("a"));
+ const seen = vi.fn();
+ subscribeDiskConflicts(seen);
+ expect(seen.mock.calls[0][0]).toHaveLength(1);
+ });
+
+ it("runs the swap only when the disk version is chosen", () => {
+ const onUseDisk = vi.fn();
+ requestDiskConflictChoice(req("a", onUseDisk));
+ resolveDiskConflict("disk");
+ expect(onUseDisk).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps the local version untouched when mine is chosen", () => {
+ const onUseDisk = vi.fn();
+ requestDiskConflictChoice(req("a", onUseDisk));
+ resolveDiskConflict("mine");
+ expect(onUseDisk).not.toHaveBeenCalled();
+ });
+
+ it("advances to the next conflict once one is answered", () => {
+ const seen = vi.fn();
+ subscribeDiskConflicts(seen);
+ requestDiskConflictChoice(req("a"));
+ requestDiskConflictChoice(req("b"));
+ resolveDiskConflict("mine");
+ expect(seen).toHaveBeenLastCalledWith([
+ expect.objectContaining({ fileId: "b" }),
+ ]);
+ });
+
+ it("survives a swap that throws, so the queue cannot wedge", () => {
+ // The failure must be logged, not swallowed.
+ expectConsole.error("[diskConflictPrompt] use-disk failed");
+ const boom = vi.fn(() => {
+ throw new Error("swap failed");
+ });
+ const seen = vi.fn();
+ subscribeDiskConflicts(seen);
+ requestDiskConflictChoice(req("a", boom));
+ requestDiskConflictChoice(req("b"));
+ expect(() => resolveDiskConflict("disk")).not.toThrow();
+ expect(seen).toHaveBeenLastCalledWith([
+ expect.objectContaining({ fileId: "b" }),
+ ]);
+ });
+
+ it("drops a queued conflict for a file that went away", () => {
+ const seen = vi.fn();
+ subscribeDiskConflicts(seen);
+ requestDiskConflictChoice(req("a"));
+ requestDiskConflictChoice(req("b"));
+ cancelDiskConflict("a" as FileId);
+ expect(seen).toHaveBeenLastCalledWith([
+ expect.objectContaining({ fileId: "b" }),
+ ]);
+ });
+
+ it("does nothing when answering an empty queue", () => {
+ expect(() => resolveDiskConflict("disk")).not.toThrow();
+ });
+
+ it("stops notifying after unsubscribe", () => {
+ const seen = vi.fn();
+ const off = subscribeDiskConflicts(seen);
+ off();
+ seen.mockClear();
+ requestDiskConflictChoice(req("a"));
+ expect(seen).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/editor/src/desktop/services/diskConflictPrompt.ts b/frontend/editor/src/desktop/services/diskConflictPrompt.ts
new file mode 100644
index 0000000000..58331d2ecf
--- /dev/null
+++ b/frontend/editor/src/desktop/services/diskConflictPrompt.ts
@@ -0,0 +1,62 @@
+import { FileId } from "@app/types/fileContext";
+
+// Bridge from the non-React hydration path to a modal, mirroring the toast
+// seam. A divergence is a decision, so it must not be dismissable like a toast.
+
+export interface DiskConflictRequest {
+ fileId: FileId;
+ name: string;
+ /** Swap the workbench copy for the disk one. Nothing happens if unused. */
+ onUseDisk: () => void;
+}
+
+type Listener = (queue: DiskConflictRequest[]) => void;
+
+const queue: DiskConflictRequest[] = [];
+const listeners = new Set<Listener>();
+
+function emit(): void {
+ const snapshot = [...queue];
+ for (const listener of listeners) listener(snapshot);
+}
+
+/** Queue a conflict. Same file twice is ignored so a re-check cannot stack up. */
+export function requestDiskConflictChoice(request: DiskConflictRequest): void {
+ if (queue.some((q) => q.fileId === request.fileId)) return;
+ queue.push(request);
+ emit();
+}
+
+export function subscribeDiskConflicts(listener: Listener): () => void {
+ listeners.add(listener);
+ listener([...queue]);
+ return () => listeners.delete(listener);
+}
+
+/** Answer the front of the queue. "disk" runs the swap; "mine" just clears it. */
+export function resolveDiskConflict(choice: "mine" | "disk"): void {
+ const request = queue.shift();
+ if (!request) return;
+ if (choice === "disk") {
+ try {
+ request.onUseDisk();
+ } catch (error) {
+ console.error("[diskConflictPrompt] use-disk failed:", error);
+ }
+ }
+ emit();
+}
+
+/** Drop a queued conflict without answering, e.g. the file was closed. */
+export function cancelDiskConflict(fileId: FileId): void {
+ const at = queue.findIndex((q) => q.fileId === fileId);
+ if (at === -1) return;
+ queue.splice(at, 1);
+ emit();
+}
+
+/** Test seam: the queue is module state and would leak between cases. */
+export function __resetDiskConflicts(): void {
+ queue.length = 0;
+ listeners.clear();
+}
diff --git a/frontend/editor/src/desktop/services/diskFileSync.test.ts b/frontend/editor/src/desktop/services/diskFileSync.test.ts
new file mode 100644
index 0000000000..2fd9efdb1d
--- /dev/null
+++ b/frontend/editor/src/desktop/services/diskFileSync.test.ts
@@ -0,0 +1,537 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// The seam is a module-level const, so each behaviour is exercised by re-importing
+// the module under a fresh mock rather than by mutating a flag.
+const diskState = vi.hoisted(
+ () =>
+ ({
+ supported: true,
+ state: { availability: "present", size: 100, modifiedMs: 5000 },
+ bytes: new Uint8Array([1, 2, 3]).buffer as ArrayBuffer | null,
+ }) as {
+ supported: boolean;
+ state:
+ | { availability: "present"; size: number; modifiedMs: number }
+ | { availability: "gone" }
+ | {
+ availability: "unavailable";
+ reason: "permission" | "offline" | "unknown";
+ };
+ bytes: ArrayBuffer | null;
+ },
+);
+
+vi.mock("@app/services/desktopFileLink", () => ({
+ get desktopFileLinkingSupported() {
+ return diskState.supported;
+ },
+ getDiskFileState: vi.fn(async () => diskState.state),
+ readFileFromDisk: vi.fn(async () => diskState.bytes),
+}));
+
+const updateFileMetadata = vi.hoisted(() => vi.fn(async () => true));
+const deleteStirlingFile = vi.hoisted(() => vi.fn(async () => undefined));
+const getStirlingFile = vi.hoisted(() =>
+ vi.fn(async () => new File([new Uint8Array([9])], "report.pdf")),
+);
+
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { updateFileMetadata, deleteStirlingFile, getStirlingFile },
+}));
+
+const downloadFileWithPolicy = vi.hoisted(() =>
+ vi.fn(
+ async (
+ _request: Record<string, unknown>,
+ ): Promise<{ savedPath?: string; cancelled?: boolean }> => ({
+ savedPath: "C:/elsewhere/report.pdf",
+ }),
+ ),
+);
+vi.mock("@app/services/exportWithPolicy", () => ({ downloadFileWithPolicy }));
+
+const alertMock = vi.hoisted(() => vi.fn());
+vi.mock("@app/components/toast", () => ({ alert: alertMock }));
+
+import { getDiskFileState } from "@app/services/desktopFileLink";
+import {
+ syncLinkedFileFromDisk,
+ hasDiskChanged,
+ detachedFields,
+ loadDiskVersion,
+ persistDiskUpdate,
+ refreshDiskBaselineAfterSave,
+ saveOrphanAsCopy,
+ notifyFileVanished,
+ notifyDiskReloaded,
+ notifyOpenFileDeleted,
+ beginSelfWrite,
+ endSelfWrite,
+ __resetSelfWrites,
+} from "@app/services/diskFileSync";
+
+function stub(overrides: Partial<StirlingFileStub> = {}): StirlingFileStub {
+ return {
+ id: "file-1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 100,
+ lastModified: 5000,
+ isLeaf: true,
+ originalFileId: "file-1",
+ versionNumber: 1,
+ localFilePath: "C:/docs/report.pdf",
+ diskSyncedSize: 100,
+ diskSyncedModifiedMs: 5000,
+ ...overrides,
+ } as StirlingFileStub;
+}
+
+beforeEach(() => {
+ diskState.supported = true;
+ diskState.state = { availability: "present", size: 100, modifiedMs: 5000 };
+ diskState.bytes = new Uint8Array([1, 2, 3]).buffer;
+ __resetSelfWrites();
+ vi.clearAllMocks();
+ downloadFileWithPolicy.mockResolvedValue({
+ savedPath: "C:/elsewhere/report.pdf",
+ });
+ getStirlingFile.mockResolvedValue(
+ new File([new Uint8Array([9])], "report.pdf"),
+ );
+});
+
+afterEach(() => vi.clearAllMocks());
+
+describe("hasDiskChanged", () => {
+ it("treats a record with no baseline as changed so it re-reads once", () => {
+ expect(
+ hasDiskChanged(
+ { diskSyncedSize: undefined, diskSyncedModifiedMs: undefined },
+ { availability: "present", size: 100, modifiedMs: 5000 },
+ ),
+ ).toBe(true);
+ });
+
+ it("is unchanged when size and mtime both match", () => {
+ expect(
+ hasDiskChanged(
+ { diskSyncedSize: 100, diskSyncedModifiedMs: 5000 },
+ { availability: "present", size: 100, modifiedMs: 5000 },
+ ),
+ ).toBe(false);
+ });
+
+ it("spots an edit that changed the size", () => {
+ expect(
+ hasDiskChanged(
+ { diskSyncedSize: 100, diskSyncedModifiedMs: 5000 },
+ { availability: "present", size: 240, modifiedMs: 5000 },
+ ),
+ ).toBe(true);
+ });
+
+ it("spots an edit that kept the size but moved the mtime", () => {
+ expect(
+ hasDiskChanged(
+ { diskSyncedSize: 100, diskSyncedModifiedMs: 5000 },
+ { availability: "present", size: 100, modifiedMs: 9999 },
+ ),
+ ).toBe(true);
+ });
+
+ it("falls back to size alone when the platform reports no mtime", () => {
+ expect(
+ hasDiskChanged(
+ { diskSyncedSize: 100, diskSyncedModifiedMs: 5000 },
+ { availability: "present", size: 100, modifiedMs: 0 },
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("syncLinkedFileFromDisk", () => {
+ it("ignores files with no disk link", async () => {
+ const result = await syncLinkedFileFromDisk(
+ stub({ localFilePath: undefined }),
+ );
+ expect(result.status).toBe("not-linked");
+ });
+
+ it("ignores every file when the platform has no disk linking", async () => {
+ diskState.supported = false;
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("not-linked");
+ });
+
+ it("reports a deleted file as missing", async () => {
+ diskState.state = { availability: "gone" };
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("missing");
+ });
+
+ it("reports a disk it could not look at as unavailable, not missing", async () => {
+ diskState.state = { availability: "unavailable", reason: "permission" };
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("unavailable");
+ if (result.status !== "unavailable")
+ throw new Error("expected unavailable");
+ expect(result.reason).toBe("permission");
+ });
+
+ it("does not mistake an unreadable stat for a truncation", async () => {
+ diskState.state = { availability: "unavailable", reason: "offline" };
+ const result = await syncLinkedFileFromDisk(
+ stub({ diskSyncedSize: 100, diskSyncedModifiedMs: 5000 }),
+ );
+ expect(result.status).not.toBe("updated");
+ });
+
+ it("leaves an untouched file alone", async () => {
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("unchanged");
+ });
+
+ it("reads the live bytes when the file was edited outside the app", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("updated");
+ if (result.status !== "updated") throw new Error("expected updated");
+ expect(result.file.name).toBe("report.pdf");
+ expect(await result.file.arrayBuffer()).toEqual(
+ new Uint8Array([1, 2, 3]).buffer,
+ );
+ expect(result.file.lastModified).toBe(9000);
+ });
+
+ it("keeps unsaved in-app edits instead of overwriting them from disk", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(stub({ isDirty: true }));
+ expect(result.status).toBe("conflict");
+ });
+
+ it("keeps an open editor's edits, which no stub flag records", async () => {
+ // A page editor, annotation or redaction session is dirty long before any
+ // version exists to set isDirty, so disk must not simply win.
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(stub({ isDirty: false }), true);
+ expect(result.status).toBe("conflict");
+ });
+
+ it("never replaces a superseded version from disk", async () => {
+ // Its child was saved over the path, so disk reads as changed while these
+ // are the only bytes that version has.
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(
+ stub({ isLeaf: false, versionNumber: 1 }),
+ );
+ expect(result.status).toBe("superseded");
+ });
+
+ it("still reloads the leaf that does answer for the path", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(
+ stub({ isLeaf: true, versionNumber: 2 }),
+ );
+ expect(result.status).toBe("updated");
+ });
+
+ it("treats a record predating the leaf flag as the live one", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(
+ stub({ isLeaf: undefined as unknown as boolean }),
+ );
+ expect(result.status).toBe("updated");
+ });
+
+ it("keeps the stored copy when the disk file cannot be read", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ diskState.bytes = null;
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("unchanged");
+ });
+
+ it("re-reads a legacy record that has no baseline", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 5000 };
+ const result = await syncLinkedFileFromDisk(
+ stub({ diskSyncedSize: undefined, diskSyncedModifiedMs: undefined }),
+ );
+ expect(result.status).toBe("updated");
+ });
+
+ it("refuses bytes that moved on disk while we were reading them", async () => {
+ // Another process was mid-write: committing this read would install a
+ // truncated PDF and then persist it over the cached copy.
+ const stat = vi.mocked(getDiskFileState);
+ stat.mockResolvedValueOnce({
+ availability: "present",
+ size: 200,
+ modifiedMs: 9000,
+ });
+ stat.mockResolvedValueOnce({
+ availability: "present",
+ size: 400,
+ modifiedMs: 9500,
+ });
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("unchanged");
+ });
+
+ it("refuses a read shorter than the file it was stat'd against", async () => {
+ const stat = vi.mocked(getDiskFileState);
+ stat.mockResolvedValueOnce({
+ availability: "present",
+ size: 400,
+ modifiedMs: 9000,
+ });
+ stat.mockResolvedValueOnce({
+ availability: "present",
+ size: 400,
+ modifiedMs: 9000,
+ });
+ const result = await syncLinkedFileFromDisk(stub());
+ expect(result.status).toBe("unchanged");
+ });
+});
+
+describe("self-write muting", () => {
+ const path = "C:/docs/report.pdf";
+ const moved = () => stub({ diskSyncedSize: 1, diskSyncedModifiedMs: 1 });
+
+ it("does not report our own save as an external change", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ beginSelfWrite(path);
+ const result = await syncLinkedFileFromDisk(moved());
+ expect(result.status).toBe("unchanged");
+ // Muted before the stat, so a half-written file is never even read.
+ expect(vi.mocked(getDiskFileState)).not.toHaveBeenCalled();
+ });
+
+ it("picks the file up again once the write is accounted for", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ beginSelfWrite(path);
+ endSelfWrite(path);
+ const result = await syncLinkedFileFromDisk(moved());
+ expect(result.status).toBe("updated");
+ });
+
+ it("releases itself if the save never re-baselines", async () => {
+ vi.useFakeTimers();
+ try {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ beginSelfWrite(path);
+ vi.advanceTimersByTime(11_000);
+ const result = await syncLinkedFileFromDisk(moved());
+ expect(result.status).toBe("updated");
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("detachedFields", () => {
+ it("cuts the link but remembers where it pointed", () => {
+ const fields = detachedFields("C:/docs/gone.pdf");
+ expect(fields.localFilePath).toBeUndefined();
+ expect(fields.diskSyncedSize).toBeUndefined();
+ expect(fields.diskSyncedModifiedMs).toBeUndefined();
+ expect(fields.diskConflictAt).toBeUndefined();
+ // Kept so the badge can go on saying "not on disk" after the toast has gone.
+ expect(fields.orphanedFilePath).toBe("C:/docs/gone.pdf");
+ });
+});
+
+describe("loadDiskVersion", () => {
+ it("reads the disk copy so a conflict can be resolved towards it", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const loaded = await loadDiskVersion(stub({ isDirty: true }));
+ expect(loaded?.file.name).toBe("report.pdf");
+ expect(loaded?.state.modifiedMs).toBe(9000);
+ });
+
+ it("gives nothing when the disk file has since gone too", async () => {
+ diskState.state = { availability: "gone" };
+ expect(await loadDiskVersion(stub())).toBeNull();
+ });
+});
+
+describe("persistDiskUpdate", () => {
+ it("stores the new bytes, re-baselines, and drops the stale thumbnail", async () => {
+ const file = new File([new Uint8Array([1, 2, 3])], "report.pdf", {
+ type: "application/pdf",
+ lastModified: 9000,
+ });
+ await persistDiskUpdate(
+ "file-1" as FileId,
+ file,
+ { availability: "present", size: 3, modifiedMs: 9000 },
+ 12345,
+ );
+
+ expect(updateFileMetadata).toHaveBeenCalledWith(
+ "file-1",
+ expect.objectContaining({
+ data: file,
+ size: 3,
+ lastModified: 9000,
+ quickKey: "report.pdf|3|9000",
+ thumbnail: undefined,
+ thumbnailStoredAt: undefined,
+ diskSyncedSize: 3,
+ diskSyncedModifiedMs: 9000,
+ // What is on screen is now the disk version, so nothing is unsaved and
+ // any earlier divergence is settled.
+ isDirty: false,
+ diskConflictAt: undefined,
+ diskReloadedAt: 12345,
+ }),
+ );
+ });
+});
+
+describe("saveOrphanAsCopy", () => {
+ it("prompts for a location and re-links the file there", async () => {
+ diskState.state = { availability: "present", size: 42, modifiedMs: 8000 };
+ const saved = await saveOrphanAsCopy(
+ stub({ localFilePath: undefined, orphanedFilePath: "C:/docs/gone.pdf" }),
+ );
+
+ // No localPath passed, which is what forces the save dialog.
+ expect(downloadFileWithPolicy).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: "report.pdf" }),
+ );
+ expect(downloadFileWithPolicy.mock.calls[0][0]).not.toHaveProperty(
+ "localPath",
+ );
+
+ expect(saved?.path).toBe("C:/elsewhere/report.pdf");
+ expect(saved?.updates).toMatchObject({
+ localFilePath: "C:/elsewhere/report.pdf",
+ orphanedFilePath: undefined,
+ isDirty: false,
+ diskSyncedSize: 42,
+ diskSyncedModifiedMs: 8000,
+ });
+ });
+
+ it("changes nothing when the user cancels the picker", async () => {
+ downloadFileWithPolicy.mockResolvedValue({ cancelled: true });
+ expect(await saveOrphanAsCopy(stub())).toBeNull();
+ expect(updateFileMetadata).not.toHaveBeenCalled();
+ });
+});
+
+describe("refreshDiskBaselineAfterSave", () => {
+ it("re-baselines against the file just written and clears the conflict", async () => {
+ diskState.state = { availability: "present", size: 512, modifiedMs: 7777 };
+ const baseline = await refreshDiskBaselineAfterSave(
+ "file-1" as FileId,
+ "C:/docs/report.pdf",
+ );
+ expect(baseline).toEqual({
+ diskSyncedSize: 512,
+ diskSyncedModifiedMs: 7777,
+ // Writing our version out settles the divergence one way.
+ diskConflictAt: undefined,
+ });
+ expect(updateFileMetadata).toHaveBeenCalledWith("file-1", baseline);
+ });
+
+ it("stamps nothing when the save did not land on disk", async () => {
+ diskState.state = { availability: "gone" };
+ const baseline = await refreshDiskBaselineAfterSave(
+ "file-1" as FileId,
+ "C:/docs/report.pdf",
+ );
+ expect(baseline).toBeNull();
+ expect(updateFileMetadata).not.toHaveBeenCalled();
+ });
+
+ it("does nothing off the desktop app", async () => {
+ diskState.supported = false;
+ expect(
+ await refreshDiskBaselineAfterSave("file-1" as FileId, "/x.pdf"),
+ ).toBeNull();
+ });
+
+ it("releases the self-write mute, even when it stamps nothing", async () => {
+ diskState.state = { availability: "gone" };
+ beginSelfWrite("C:/docs/report.pdf");
+ await refreshDiskBaselineAfterSave(
+ "file-1" as FileId,
+ "C:/docs/report.pdf",
+ );
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(
+ stub({ diskSyncedSize: 1, diskSyncedModifiedMs: 1 }),
+ );
+ expect(result.status).toBe("updated");
+ });
+});
+
+describe("user-facing notifications", () => {
+ // The toast module is imported lazily, so the alert lands a microtask later.
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+ it("names the file that vanished", async () => {
+ notifyFileVanished("report.pdf");
+ await flush();
+ expect(alertMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ alertType: "warning",
+ body: expect.stringContaining("report.pdf"),
+ }),
+ );
+ });
+
+ it("tells the user an open file lost its original but is still here", async () => {
+ notifyOpenFileDeleted(["report.pdf"]);
+ await flush();
+ expect(alertMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ alertType: "warning",
+ body: expect.stringContaining("still open here"),
+ }),
+ );
+ expect(alertMock.mock.calls[0][0].body).toContain("report.pdf");
+ });
+
+ it("warns that saving will ask for a new location, and offers to do it", async () => {
+ const onSaveAs = vi.fn();
+ notifyOpenFileDeleted(["report.pdf"], onSaveAs);
+ await flush();
+ const toast = alertMock.mock.calls[0][0];
+ // Saying "save it" without saying where makes the file picker read as an error.
+ expect(toast.body).toContain("new location");
+ expect(toast.isPersistentPopup).toBe(true);
+ toast.buttonCallback();
+ expect(onSaveAs).toHaveBeenCalled();
+ });
+
+ it("counts them instead of listing when several are lost at once", async () => {
+ notifyOpenFileDeleted(["a.pdf", "b.pdf", "c.pdf"]);
+ await flush();
+ expect(alertMock.mock.calls[0][0].body).toContain("3 files");
+ });
+
+ it("offers no single-file action when several were lost", async () => {
+ notifyOpenFileDeleted(["a.pdf", "b.pdf"], vi.fn());
+ await flush();
+ expect(alertMock.mock.calls[0][0].buttonText).toBeUndefined();
+ });
+
+ it("leaves a trace when an external edit is picked up", async () => {
+ notifyDiskReloaded("report.pdf");
+ await flush();
+ // Neutral, not a warning: nothing went wrong, the user just needs to be able
+ // to tell whose version is on screen.
+ expect(alertMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ alertType: "neutral",
+ body: expect.stringContaining("report.pdf"),
+ }),
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/services/diskFileSync.ts b/frontend/editor/src/desktop/services/diskFileSync.ts
new file mode 100644
index 0000000000..11fdbd364f
--- /dev/null
+++ b/frontend/editor/src/desktop/services/diskFileSync.ts
@@ -0,0 +1,418 @@
+import { FileId, StirlingFileStub } from "@app/types/fileContext";
+import {
+ DiskFileState,
+ DiskUnavailableReason,
+ PresentDiskFileState,
+ desktopFileLinkingSupported,
+ getDiskFileState,
+ readFileFromDisk,
+} from "@app/services/desktopFileLink";
+import { fileStorage } from "@app/services/fileStorage";
+
+// Keeps desktop files 1:1 with disk: the stored copy is a cache, not truth, so
+// every read re-checks disk. No-op off desktop, where the copy is the truth.
+
+/** What a linked file's disk state means for the copy we are holding. */
+export type DiskSyncOutcome =
+ /** Not a desktop-linked file: the stored copy is the only truth. */
+ | { status: "not-linked" }
+ /** A superseded version. It inherited the path but no longer represents it,
+ * and its stored bytes are the only copy of that version. */
+ | { status: "superseded" }
+ | { status: "missing" }
+ | { status: "unavailable"; reason: DiskUnavailableReason }
+ /** Disk matches what we last read; the stored copy is current. */
+ | { status: "unchanged" }
+ /** Disk moved on, but we hold unsaved in-app edits, so we keep ours. */
+ | { status: "conflict" }
+ | { status: "too-large"; size: number }
+ /** Disk moved on and we had nothing unsaved, so these are the live bytes. */
+ | { status: "updated"; file: File; state: PresentDiskFileState };
+
+/** Did disk change since our last read? No baseline means we cannot prove the
+ * copy is current, so re-read once; size settles it when mtime is missing. */
+export function hasDiskChanged(
+ stub: Pick<StirlingFileStub, "diskSyncedSize" | "diskSyncedModifiedMs">,
+ state: PresentDiskFileState,
+): boolean {
+ if (stub.diskSyncedSize == null || stub.diskSyncedModifiedMs == null) {
+ return true;
+ }
+ if (state.size !== stub.diskSyncedSize) return true;
+ if (state.modifiedMs === 0) return false;
+ return state.modifiedMs !== stub.diskSyncedModifiedMs;
+}
+
+export function diskAvailabilityFields(
+ state: DiskFileState,
+): Pick<StirlingFileStub, "diskUnavailableReason"> {
+ return {
+ diskUnavailableReason:
+ state.availability === "unavailable" ? state.reason : undefined,
+ };
+}
+
+/** The fields a fresh disk read stamps onto the stub and the stored record. */
+export function diskBaseline(
+ state: PresentDiskFileState,
+): Pick<StirlingFileStub, "diskSyncedSize" | "diskSyncedModifiedMs"> {
+ return {
+ diskSyncedSize: state.size,
+ diskSyncedModifiedMs: state.modifiedMs,
+ };
+}
+
+/** Fields marking a file as having lost its disk original. Applied in storage
+ * and the workbench so save paths stop writing to the deleted path. */
+export function detachedFields(
+ path: string | undefined,
+): Pick<
+ StirlingFileStub,
+ | "localFilePath"
+ | "diskSyncedSize"
+ | "diskSyncedModifiedMs"
+ | "diskConflictAt"
+ | "diskUnavailableReason"
+ | "orphanedFilePath"
+> {
+ return {
+ localFilePath: undefined,
+ diskSyncedSize: undefined,
+ diskSyncedModifiedMs: undefined,
+ diskConflictAt: undefined,
+ diskUnavailableReason: undefined,
+ orphanedFilePath: path,
+ };
+}
+
+const AUTO_RELOAD_MAX_BYTES = 512 * 1024 * 1024; // 512 MB
+
+// A save writes onto the watched path, so the watcher reports our own write as
+// an external change. Paths are muted until the post-save re-baseline lands.
+const SELF_WRITE_MAX_MS = 10_000;
+const selfWrites = new Map<string, number>();
+
+/** Mute disk checks for a path we are about to write ourselves. */
+export function beginSelfWrite(path: string): void {
+ selfWrites.set(path, Date.now() + SELF_WRITE_MAX_MS);
+}
+
+/** Unmute once the write is accounted for. Safe for an unknown path. */
+export function endSelfWrite(path: string): void {
+ selfWrites.delete(path);
+}
+
+function isSelfWrite(path: string): boolean {
+ const until = selfWrites.get(path);
+ if (until == null) return false;
+ // A save that never re-baselined must not blind us forever.
+ if (Date.now() > until) {
+ selfWrites.delete(path);
+ return false;
+ }
+ return true;
+}
+
+/** Test seam: the register is module state and would leak between cases. */
+export function __resetSelfWrites(): void {
+ selfWrites.clear();
+}
+
+/** @param hasUnsavedWork in-app edits not yet committed to a version. The stub's
+ * own isDirty only says a tool produced one, so an open page editor, annotation
+ * or redaction session is invisible to it and disk would silently win. */
+export async function syncLinkedFileFromDisk(
+ stub: StirlingFileStub,
+ hasUnsavedWork = false,
+): Promise<DiskSyncOutcome> {
+ if (!desktopFileLinkingSupported || !stub.localFilePath) {
+ return { status: "not-linked" };
+ }
+
+ // Our own write is in flight: reporting it as an external change would accuse
+ // the user of conflicting with themselves.
+ if (isSelfWrite(stub.localFilePath)) return { status: "unchanged" };
+
+ const state = await getDiskFileState(stub.localFilePath);
+ if (state.availability === "gone") return { status: "missing" };
+ if (state.availability === "unavailable") {
+ return { status: "unavailable", reason: state.reason };
+ }
+ if (!hasDiskChanged(stub, state)) return { status: "unchanged" };
+ // Deliberately below the missing and unavailable checks: a superseded version
+ // still wants its link state reported, it just must never be replaced.
+ // createChildStub copies the parent's path onto the child, so every version in
+ // a chain claims the same file while only the leaf still answers for it. The
+ // rest hold the sole copy of their bytes against a baseline that predates the
+ // child's write, so "changed" here means the child was saved - and reloading
+ // would overwrite that version for good.
+ if (stub.isLeaf === false) return { status: "superseded" };
+ if (stub.isDirty || hasUnsavedWork) return { status: "conflict" };
+ if (state.size > AUTO_RELOAD_MAX_BYTES) {
+ return { status: "too-large", size: state.size };
+ }
+
+ const bytes = await readFileFromDisk(stub.localFilePath);
+ if (!bytes) return { status: "unchanged" };
+
+ // The file may still have been being written while we read it. Only commit
+ // bytes whose size and mtime held still across the read.
+ const after = await getDiskFileState(stub.localFilePath);
+ if (
+ after.availability !== "present" ||
+ after.size !== state.size ||
+ after.modifiedMs !== state.modifiedMs ||
+ bytes.byteLength !== state.size
+ ) {
+ // Baseline deliberately left un-stamped, so the next event re-reads.
+ return { status: "unchanged" };
+ }
+
+ const file = new File([bytes], stub.name, {
+ type: stub.type || "application/pdf",
+ lastModified: state.modifiedMs || Date.now(),
+ });
+ return { status: "updated", file, state };
+}
+
+/** Read the disk version, discarding unsaved in-app edits. Only from the "Use
+ * disk version" action - losing unsaved work must be the user's choice. No
+ * settle check here: declining silently would make the button look dead. */
+export async function loadDiskVersion(
+ stub: StirlingFileStub,
+): Promise<{ file: File; state: PresentDiskFileState } | null> {
+ if (!desktopFileLinkingSupported || !stub.localFilePath) return null;
+ const state = await getDiskFileState(stub.localFilePath);
+ if (state.availability !== "present") return null;
+ const bytes = await readFileFromDisk(stub.localFilePath);
+ if (!bytes) return null;
+ const file = new File([bytes], stub.name, {
+ type: stub.type || "application/pdf",
+ lastModified: state.modifiedMs || Date.now(),
+ });
+ return { file, state };
+}
+
+/** Replace stored bytes with the disk read and re-stamp the baseline. Cached
+ * metadata and thumbnail describe the old bytes, so both are cleared. */
+export async function persistDiskUpdate(
+ fileId: FileId,
+ file: File,
+ state: PresentDiskFileState,
+ reloadedAt: number,
+): Promise<void> {
+ await fileStorage.updateFileMetadata(fileId, {
+ data: file,
+ size: file.size,
+ lastModified: file.lastModified,
+ quickKey: `${file.name}|${file.size}|${file.lastModified}`,
+ thumbnail: undefined,
+ thumbnailStoredAt: undefined,
+ // The disk version is now the one on screen, so any earlier divergence is
+ // settled and the pickup is recorded where the UI can show it.
+ isDirty: false,
+ diskConflictAt: undefined,
+ diskReloadedAt: reloadedAt,
+ ...diskBaseline(state),
+ });
+}
+
+/** After a write-back, disk IS our copy, so re-stamp the baseline or the next
+ * open re-reads for nothing. Returns the new baseline, or null if none. */
+export async function refreshDiskBaselineAfterSave(
+ fileId: FileId,
+ path: string,
+): Promise<Pick<
+ StirlingFileStub,
+ "diskSyncedSize" | "diskSyncedModifiedMs" | "diskConflictAt"
+> | null> {
+ try {
+ if (!desktopFileLinkingSupported) return null;
+ const state = await getDiskFileState(path);
+ if (state.availability !== "present") return null;
+ // Writing our version out is one way of resolving a divergence, so the
+ // conflict marker goes with it.
+ const baseline = { ...diskBaseline(state), diskConflictAt: undefined };
+ await fileStorage.updateFileMetadata(fileId, baseline);
+ return baseline;
+ } finally {
+ // The write is now accounted for, however it went.
+ endSelfWrite(path);
+ }
+}
+
+/** Drop a linked file whose disk original is gone, copy and all. */
+export async function deleteVanishedFile(fileId: FileId): Promise<void> {
+ try {
+ await fileStorage.deleteStirlingFile(fileId);
+ } catch (error) {
+ console.error("[diskFileSync] Failed to delete vanished file:", error);
+ }
+}
+
+/** Write an orphaned file somewhere new and re-link it; backs the toast's
+ * "Save as…" action. Returns the new path, or null if cancelled or failed. */
+export async function saveOrphanAsCopy(
+ stub: StirlingFileStub,
+): Promise<{ path: string; updates: Partial<StirlingFileStub> } | null> {
+ try {
+ // Only the export gateway is lazy - it is heavy and this path is rare.
+ // fileStorage is already a module-level import.
+ const { downloadFileWithPolicy } =
+ await import("@app/services/exportWithPolicy");
+ const file = await fileStorage.getStirlingFile(stub.id);
+ if (!file) return null;
+
+ // No localPath, so this always prompts for a location - which is the point.
+ const result = await downloadFileWithPolicy({
+ data: file,
+ filename: stub.name,
+ fileId: stub.id,
+ });
+ if (result.cancelled || !result.savedPath) return null;
+
+ const state = await getDiskFileState(result.savedPath);
+ const updates: Partial<StirlingFileStub> = {
+ localFilePath: result.savedPath,
+ orphanedFilePath: undefined,
+ diskConflictAt: undefined,
+ diskUnavailableReason: undefined,
+ isDirty: false,
+ ...(state.availability === "present" ? diskBaseline(state) : {}),
+ };
+ await fileStorage.updateFileMetadata(stub.id, updates);
+ return { path: result.savedPath, updates };
+ } catch (error) {
+ console.error("[diskFileSync] Save as copy failed:", error);
+ return null;
+ }
+}
+
+/** The bit of i18next this module needs, if it has been initialised at all. */
+interface Translator {
+ t: (key: string, options?: Record<string, unknown>) => string;
+}
+
+function isTranslator(value: unknown): value is Translator {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ typeof (value as Translator).t === "function"
+ );
+}
+
+/** Best-effort translation: runs from hydration paths with no i18n context,
+ * and the English default is already interpolated. */
+function translate(
+ key: string,
+ defaultValue: string,
+ params?: Record<string, string | number>,
+): string {
+ try {
+ const i18next = (globalThis as Record<string, unknown>).i18next;
+ if (isTranslator(i18next)) {
+ return i18next.t(key, { defaultValue, ...params });
+ }
+ } catch {
+ /* translation is best-effort; the English default still reads fine */
+ }
+ return defaultValue;
+}
+
+interface ToastSpec {
+ title: string;
+ body: string;
+ durationMs?: number;
+ isPersistentPopup?: boolean;
+ alertType?: "warning" | "neutral";
+ buttonText?: string;
+ buttonCallback?: () => void;
+}
+
+/** Lazy: this sits on the hydration path and the toast barrel pulls in the
+ * whole icon set, costing ~3s of module load per file open. */
+function toast({ alertType = "warning", ...options }: ToastSpec): void {
+ void import("@app/components/toast")
+ .then(({ alert }) => alert({ alertType, expandable: false, ...options }))
+ .catch((error) => console.error("[diskFileSync] toast failed:", error));
+}
+
+/** Tell the user a file they were opening is gone - the race the list-time
+ * prune cannot catch. Nothing to offer, so it stays a plain notice. */
+export function notifyFileVanished(name: string): void {
+ toast({
+ title: translate("desktopFileLink.missing.title", "File no longer exists"),
+ body: translate(
+ "desktopFileLink.missing.body",
+ `"${name}" has been deleted or moved on disk, so it has been removed from your files.`,
+ { name },
+ ),
+ durationMs: 8000,
+ });
+}
+
+/** An open file lost its disk original - an unresolved decision, not an event,
+ * so the toast persists and says saving will ask for a new location. */
+export function notifyOpenFileDeleted(
+ names: string[],
+ onSaveAs?: () => void,
+): void {
+ const single = names.length === 1;
+ toast({
+ title: translate(
+ "desktopFileLink.openDeleted.title",
+ single ? "File deleted on disk" : "Files deleted on disk",
+ { count: names.length },
+ ),
+ body: translate(
+ "desktopFileLink.openDeleted.body",
+ single
+ ? `"${names[0]}" no longer exists on disk. It is still open here - saving will ask you for a new location.`
+ : `${names.length} files no longer exist on disk. They are still open here - saving each one will ask you for a new location.`,
+ { count: names.length, name: names[0] },
+ ),
+ isPersistentPopup: true,
+ ...(onSaveAs && single
+ ? {
+ buttonText: translate("desktopFileLink.saveAs", "Save as…"),
+ buttonCallback: onSaveAs,
+ }
+ : {}),
+ });
+}
+
+export function notifyDiskTooLarge(name: string, onReload?: () => void): void {
+ toast({
+ title: translate("desktopFileLink.tooLarge.title", "File changed on disk"),
+ body: translate(
+ "desktopFileLink.tooLarge.body",
+ `"${name}" changed on disk. It is large enough that reloading it will take a while, so the version here has been left alone.`,
+ { name },
+ ),
+ isPersistentPopup: true,
+ ...(onReload
+ ? {
+ buttonText: translate(
+ "desktopFileLink.useDiskVersion",
+ "Use disk version",
+ ),
+ buttonCallback: onReload,
+ }
+ : {}),
+ });
+}
+
+/** Say an external edit was picked up: swapping bytes silently is right, but
+ * with no trace nobody can tell whose version is on screen. */
+export function notifyDiskReloaded(name: string): void {
+ toast({
+ alertType: "neutral",
+ title: translate("desktopFileLink.reloaded.title", "Updated from disk"),
+ body: translate(
+ "desktopFileLink.reloaded.body",
+ `"${name}" changed on disk and has been reloaded.`,
+ { name },
+ ),
+ durationMs: 6000,
+ });
+}
diff --git a/frontend/editor/src/desktop/services/localFileSaveService.test.ts b/frontend/editor/src/desktop/services/localFileSaveService.test.ts
new file mode 100644
index 0000000000..bc080c282f
--- /dev/null
+++ b/frontend/editor/src/desktop/services/localFileSaveService.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, test, vi, beforeEach } from "vitest";
+import { expectConsole } from "@app/tests/failOnConsole";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+
+// A save writes onto the watched path, so the watcher reports our own write as
+// an external change. The save must mute the path, and unmute if it failed.
+
+const writeFile = vi.hoisted(() => vi.fn(async () => undefined));
+vi.mock("@tauri-apps/plugin-fs", () => ({ writeFile }));
+
+const getDiskFileState = vi.hoisted(() =>
+ vi.fn(async () => ({
+ availability: "present" as const,
+ size: 3,
+ modifiedMs: 9000,
+ })),
+);
+vi.mock("@app/services/desktopFileLink", () => ({
+ desktopFileLinkingSupported: true,
+ getDiskFileState,
+ readFileFromDisk: vi.fn(async () => new Uint8Array([1, 2, 3]).buffer),
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { updateFileMetadata: vi.fn(async () => true) },
+}));
+
+import { saveToLocalPath } from "@app/services/localFileSaveService";
+import {
+ syncLinkedFileFromDisk,
+ __resetSelfWrites,
+} from "@app/services/diskFileSync";
+
+const PATH = "C:/docs/report.pdf";
+const bytes = new Uint8Array([1, 2, 3]);
+
+// Baseline deliberately stale, so anything but a mute reports "updated".
+const linked = () =>
+ ({
+ id: "f1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 3,
+ lastModified: 0,
+ localFilePath: PATH,
+ diskSyncedSize: 1,
+ diskSyncedModifiedMs: 1,
+ }) as StirlingFileStub;
+
+beforeEach(() => {
+ __resetSelfWrites();
+ vi.clearAllMocks();
+ writeFile.mockResolvedValue(undefined);
+});
+
+describe("saveToLocalPath", () => {
+ test("writes the bytes straight to the path it was given", async () => {
+ const file = new File([bytes], "report.pdf");
+ // jsdom mangles binary Blob parts, so compare against what this very Blob
+ // yields: what matters is that the save passes it through untouched.
+ const expected = new Uint8Array(await file.arrayBuffer());
+
+ const result = await saveToLocalPath(file, PATH);
+ expect(result).toEqual({ success: true });
+ expect(writeFile).toHaveBeenCalledWith(PATH, expected);
+ });
+
+ test("mutes the path so the watcher cannot re-read our own write", async () => {
+ await saveToLocalPath(new File([bytes], "report.pdf"), PATH);
+ const outcome = await syncLinkedFileFromDisk(linked());
+ expect(outcome.status).toBe("unchanged");
+ // Muted before the stat, so a half-written file is never even read.
+ expect(getDiskFileState).not.toHaveBeenCalled();
+ });
+
+ test("unmutes when the write failed, so a real change is not missed", async () => {
+ expectConsole.error(/Failed to save/);
+ writeFile.mockRejectedValueOnce(new Error("EACCES"));
+
+ const result = await saveToLocalPath(new File([bytes], "report.pdf"), PATH);
+ expect(result.success).toBe(false);
+
+ const outcome = await syncLinkedFileFromDisk(linked());
+ expect(outcome.status).toBe("updated");
+ });
+});
diff --git a/frontend/editor/src/desktop/services/localFileSaveService.ts b/frontend/editor/src/desktop/services/localFileSaveService.ts
index bd8e2bc009..347c4927e4 100644
--- a/frontend/editor/src/desktop/services/localFileSaveService.ts
+++ b/frontend/editor/src/desktop/services/localFileSaveService.ts
@@ -2,6 +2,7 @@ import type {
SaveResult,
MultiFileSaveResult,
} from "@core/services/localFileSaveService";
+import { beginSelfWrite, endSelfWrite } from "@app/services/diskFileSync";
export type { SaveResult, MultiFileSaveResult };
import { assertFilesNotBlocked } from "@app/services/policyFileGuard";
@@ -16,6 +17,9 @@ export async function saveToLocalPath(
data: Blob | File,
filePath: string,
): Promise<SaveResult> {
+ // Muted before the first byte so the watcher cannot report our own write as an
+ // external change. Released by the post-save re-baseline, or by its deadline.
+ beginSelfWrite(filePath);
try {
const { writeFile } = await import("@tauri-apps/plugin-fs");
const arrayBuffer = await data.arrayBuffer();
@@ -23,6 +27,7 @@ export async function saveToLocalPath(
await writeFile(filePath, new Uint8Array(arrayBuffer));
return { success: true };
} catch (error) {
+ endSelfWrite(filePath);
const message = error instanceof Error ? error.message : String(error);
console.error("[LocalFileSave] Failed to save:", message);
return { success: false, error: message };
diff --git a/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts b/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts
new file mode 100644
index 0000000000..7396295dff
--- /dev/null
+++ b/frontend/editor/src/desktop/services/pruneMissingRecentFiles.test.ts
@@ -0,0 +1,319 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import type { StirlingFileStub } from "@app/types/fileContext";
+import type { FileId } from "@app/types/file";
+import type { ToolId } from "@app/types/toolId";
+
+const disk = vi.hoisted(() => ({
+ supported: true,
+ present: new Set<string>(),
+ unreachable: new Set<string>(),
+}));
+
+vi.mock("@app/services/desktopFileLink", () => ({
+ get desktopFileLinkingSupported() {
+ return disk.supported;
+ },
+ getDiskFileState: vi.fn(async (path: string) =>
+ disk.present.has(path)
+ ? { availability: "present" as const, size: 0, modifiedMs: 0 }
+ : disk.unreachable.has(path)
+ ? { availability: "unavailable" as const, reason: "offline" as const }
+ : { availability: "gone" as const },
+ ),
+ readFileFromDisk: vi.fn(async () => null),
+}));
+
+const deleteMultipleStirlingFiles = vi.hoisted(() => vi.fn(async () => 0));
+const updateFileMetadata = vi.hoisted(() => vi.fn(async () => true));
+
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { deleteMultipleStirlingFiles, updateFileMetadata },
+}));
+
+import {
+ pruneMissingRecentFiles,
+ hasLocalRecord,
+} from "@app/services/pruneMissingRecentFiles";
+
+function stub(overrides: Partial<StirlingFileStub> = {}): StirlingFileStub {
+ return {
+ id: "file-1" as FileId,
+ name: "report.pdf",
+ type: "application/pdf",
+ size: 100,
+ lastModified: 5000,
+ isLeaf: true,
+ originalFileId: "file-1",
+ versionNumber: 1,
+ toolHistory: [],
+ ...overrides,
+ } as StirlingFileStub;
+}
+
+beforeEach(() => {
+ disk.supported = true;
+ disk.present = new Set(["C:/docs/kept.pdf"]);
+ vi.clearAllMocks();
+});
+
+describe("hasLocalRecord", () => {
+ it("rejects the synthetic server and share stubs", () => {
+ expect(hasLocalRecord(stub({ id: "server-12" as FileId }))).toBe(false);
+ expect(hasLocalRecord(stub({ id: "shared-abc" as FileId }))).toBe(false);
+ expect(hasLocalRecord(stub())).toBe(true);
+ });
+});
+
+describe("pruneMissingRecentFiles", () => {
+ it("passes everything through off the desktop app", async () => {
+ disk.supported = false;
+ const stubs = [stub({ localFilePath: "C:/docs/gone.pdf" })];
+ expect(await pruneMissingRecentFiles(stubs)).toBe(stubs);
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ });
+
+ it("leaves files whose disk original is still there", async () => {
+ const stubs = [stub({ localFilePath: "C:/docs/kept.pdf" })];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(result).toHaveLength(1);
+ expect(result[0].localFilePath).toBe("C:/docs/kept.pdf");
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ });
+
+ it("deletes a pristine passthrough whose disk file was removed", async () => {
+ const stubs = [
+ stub({ id: "gone" as FileId, localFilePath: "C:/docs/gone.pdf" }),
+ stub({ id: "kept" as FileId, localFilePath: "C:/docs/kept.pdf" }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(result.map((s) => s.id)).toEqual(["kept"]);
+ expect(deleteMultipleStirlingFiles).toHaveBeenCalledWith(["gone"]);
+ });
+
+ it("keeps an edited file but detaches its dead disk link", async () => {
+ const stubs = [
+ stub({
+ id: "edited" as FileId,
+ localFilePath: "C:/docs/gone.pdf",
+ versionNumber: 3,
+ toolHistory: [{ toolId: "split" as ToolId, timestamp: 1 }],
+ }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(result).toHaveLength(1);
+ expect(result[0].localFilePath).toBeUndefined();
+ expect(result[0].diskSyncedSize).toBeUndefined();
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ expect(updateFileMetadata).toHaveBeenCalledWith(
+ "edited",
+ expect.objectContaining({ localFilePath: undefined }),
+ );
+ });
+
+ it("records where a detached file used to live", async () => {
+ const stubs = [
+ stub({
+ id: "edited" as FileId,
+ localFilePath: "C:/docs/gone.pdf",
+ versionNumber: 3,
+ }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ // Without this the "not on disk" state dies with the toast that announced it.
+ expect(result[0].orphanedFilePath).toBe("C:/docs/gone.pdf");
+ expect(updateFileMetadata).toHaveBeenCalledWith(
+ "edited",
+ expect.objectContaining({ orphanedFilePath: "C:/docs/gone.pdf" }),
+ );
+ });
+
+ it("keeps a version-history root even though it looks like a passthrough", async () => {
+ // A v1 root has no tool history of its own so it reads as pristine, but later
+ // versions point at it: deleting it takes "revert to original" with them.
+ const stubs = [
+ stub({
+ id: "root" as FileId,
+ localFilePath: "C:/docs/gone.pdf",
+ isLeaf: false,
+ }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ expect(result).toHaveLength(1);
+ expect(result[0].localFilePath).toBeUndefined();
+ expect(result[0].orphanedFilePath).toBe("C:/docs/gone.pdf");
+ });
+
+ it("never touches the synthetic server and share stubs", async () => {
+ const stubs = [
+ stub({ id: "server-7" as FileId, localFilePath: "C:/docs/gone.pdf" }),
+ stub({ id: "shared-x" as FileId, localFilePath: "C:/docs/gone.pdf" }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(result).toHaveLength(2);
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ expect(updateFileMetadata).not.toHaveBeenCalled();
+ });
+
+ it("keeps a file with unsaved edits even though its disk file is gone", async () => {
+ const stubs = [
+ stub({
+ id: "dirty" as FileId,
+ localFilePath: "C:/docs/gone.pdf",
+ isDirty: true,
+ }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(result).toHaveLength(1);
+ expect(result[0].localFilePath).toBeUndefined();
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ });
+
+ it("never touches a server-backed file here", async () => {
+ const stubs = [
+ stub({
+ id: "server-backed" as FileId,
+ localFilePath: "C:/docs/gone.pdf",
+ remoteStorageId: 42,
+ }),
+ ];
+ const result = await pruneMissingRecentFiles(stubs);
+ expect(result).toHaveLength(1);
+ expect(result[0].localFilePath).toBe("C:/docs/gone.pdf");
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ });
+
+ it("ignores files that never came from disk", async () => {
+ const stubs = [stub({ localFilePath: undefined })];
+ expect(await pruneMissingRecentFiles(stubs)).toBe(stubs);
+ });
+
+ describe("a file the user still has open", () => {
+ const openStub = () =>
+ stub({ id: "open" as FileId, localFilePath: "C:/docs/gone.pdf" });
+
+ it("is kept and detached rather than deleted under the user", async () => {
+ const onOpenFilesDetached = vi.fn();
+ const result = await pruneMissingRecentFiles([openStub()], {
+ openFileIds: new Set(["open" as FileId]),
+ onOpenFilesDetached,
+ });
+
+ // Deleting it would leave a document on screen that exists nowhere.
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ expect(result).toHaveLength(1);
+ expect(result[0].localFilePath).toBeUndefined();
+ // The id and old path go with it: the caller has to apply the same detach
+ // to the workbench stub, or every save path keeps writing to the dead path.
+ expect(onOpenFilesDetached).toHaveBeenCalledWith([
+ { id: "open", name: "report.pdf", path: "C:/docs/gone.pdf" },
+ ]);
+ });
+
+ it("would have been deleted had it not been open", async () => {
+ const result = await pruneMissingRecentFiles([openStub()]);
+ expect(deleteMultipleStirlingFiles).toHaveBeenCalledWith(["open"]);
+ expect(result).toHaveLength(0);
+ });
+
+ it("says nothing when the open file's disk original is fine", async () => {
+ const onOpenFilesDetached = vi.fn();
+ await pruneMissingRecentFiles(
+ [stub({ id: "open" as FileId, localFilePath: "C:/docs/kept.pdf" })],
+ { openFileIds: new Set(["open" as FileId]), onOpenFilesDetached },
+ );
+ expect(onOpenFilesDetached).not.toHaveBeenCalled();
+ });
+
+ it("reports every open file lost in one go", async () => {
+ const onOpenFilesDetached = vi.fn();
+ await pruneMissingRecentFiles(
+ [
+ stub({
+ id: "a" as FileId,
+ name: "a.pdf",
+ localFilePath: "C:/docs/a.pdf",
+ }),
+ stub({
+ id: "b" as FileId,
+ name: "b.pdf",
+ localFilePath: "C:/docs/b.pdf",
+ }),
+ ],
+ {
+ openFileIds: new Set(["a" as FileId, "b" as FileId]),
+ onOpenFilesDetached,
+ },
+ );
+ expect(onOpenFilesDetached).toHaveBeenCalledWith([
+ { id: "a", name: "a.pdf", path: "C:/docs/a.pdf" },
+ { id: "b", name: "b.pdf", path: "C:/docs/b.pdf" },
+ ]);
+ });
+ });
+
+ describe("a location we could not look at", () => {
+ it("keeps a pristine record whose volume is unreachable", async () => {
+ disk.unreachable.add("/Volumes/Backup/report.pdf");
+
+ const kept = await pruneMissingRecentFiles([
+ stub({
+ id: "a" as FileId,
+ name: "report.pdf",
+ localFilePath: "/Volumes/Backup/report.pdf",
+ }),
+ ]);
+
+ expect(deleteMultipleStirlingFiles).not.toHaveBeenCalled();
+ expect(updateFileMetadata).not.toHaveBeenCalled();
+ expect(kept[0].localFilePath).toBe("/Volumes/Backup/report.pdf");
+ });
+
+ it("marks the record so the list can say why disk looks quiet", async () => {
+ disk.unreachable.add("/Volumes/Backup/report.pdf");
+
+ const [marked] = await pruneMissingRecentFiles([
+ stub({
+ id: "a" as FileId,
+ name: "report.pdf",
+ localFilePath: "/Volumes/Backup/report.pdf",
+ }),
+ ]);
+
+ expect(marked.diskUnavailableReason).toBe("offline");
+ });
+
+ it("clears the mark once the location comes back", async () => {
+ disk.present.add("/Volumes/Backup/report.pdf");
+
+ const [healed] = await pruneMissingRecentFiles([
+ stub({
+ id: "a" as FileId,
+ name: "report.pdf",
+ localFilePath: "/Volumes/Backup/report.pdf",
+ diskUnavailableReason: "offline",
+ }),
+ ]);
+
+ expect(healed.diskUnavailableReason).toBeUndefined();
+ });
+
+ it("does not detach an open file just because disk went quiet", async () => {
+ disk.unreachable.add("/Volumes/Backup/report.pdf");
+ const onOpenFilesDetached = vi.fn();
+
+ await pruneMissingRecentFiles(
+ [
+ stub({
+ id: "a" as FileId,
+ name: "report.pdf",
+ localFilePath: "/Volumes/Backup/report.pdf",
+ }),
+ ],
+ { openFileIds: new Set(["a" as FileId]), onOpenFilesDetached },
+ );
+
+ expect(onOpenFilesDetached).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/editor/src/desktop/services/pruneMissingRecentFiles.ts b/frontend/editor/src/desktop/services/pruneMissingRecentFiles.ts
new file mode 100644
index 0000000000..60ad94d087
--- /dev/null
+++ b/frontend/editor/src/desktop/services/pruneMissingRecentFiles.ts
@@ -0,0 +1,126 @@
+import { StirlingFileStub, FileId } from "@app/types/fileContext";
+import { fileStorage } from "@app/services/fileStorage";
+import {
+ DiskUnavailableReason,
+ desktopFileLinkingSupported,
+ getDiskFileState,
+} from "@app/services/desktopFileLink";
+import {
+ detachedFields,
+ diskAvailabilityFields,
+} from "@app/services/diskFileSync";
+import type {
+ DetachedOpenFile,
+ PruneOptions,
+} from "@core/services/pruneMissingRecentFiles";
+
+export type { DetachedOpenFile, PruneOptions };
+
+/** Reconciles the file list against disk so a file deleted outside the app never shows as available;
+ * the open path re-checks for the delete-after-draw race. No-op off desktop. */
+
+/** True for real local IndexedDB records; ephemeral `server-`/`shared-` stubs have no disk link. */
+export function hasLocalRecord(stub: StirlingFileStub): boolean {
+ return !stub.id.startsWith("server-") && !stub.id.startsWith("shared-");
+}
+
+/** Unedited v1 holds the same bytes as disk, so losing it loses nothing unique.
+ * Non-leaf is excluded: it is the version-history root "revert to original" needs. */
+export function isPristineLocalPassthrough(stub: StirlingFileStub): boolean {
+ return (
+ !stub.isDirty &&
+ stub.isLeaf !== false &&
+ (stub.versionNumber ?? 1) === 1 &&
+ (stub.toolHistory?.length ?? 0) === 0
+ );
+}
+
+/** Local-only stubs with a dead `localFilePath`: pristine passthroughs are deleted, the rest are
+ * detached (old path kept for the UI). Server-backed skipped - the server may hold the only copy. */
+export async function pruneMissingRecentFiles(
+ stubs: StirlingFileStub[],
+ options: PruneOptions = {},
+): Promise<StirlingFileStub[]> {
+ if (!desktopFileLinkingSupported) return stubs;
+
+ const linked = stubs.filter(
+ (stub) =>
+ stub.localFilePath && !stub.remoteStorageId && hasLocalRecord(stub),
+ );
+ if (linked.length === 0) return stubs;
+
+ const states = await Promise.all(
+ linked.map((stub) => getDiskFileState(stub.localFilePath!)),
+ );
+
+ const marks = new Map<FileId, DiskUnavailableReason | undefined>(
+ linked.map((stub, i) => [
+ stub.id,
+ diskAvailabilityFields(states[i]).diskUnavailableReason,
+ ]),
+ );
+
+ const openIds = options.openFileIds;
+ const toDelete: FileId[] = [];
+ const toDetach: StirlingFileStub[] = [];
+ const detachedOpen: DetachedOpenFile[] = [];
+ linked.forEach((stub, i) => {
+ if (states[i].availability !== "gone") return;
+ if (openIds?.has(stub.id)) {
+ toDetach.push(stub);
+ detachedOpen.push({
+ id: stub.id,
+ name: stub.name,
+ path: stub.localFilePath!,
+ });
+ } else if (isPristineLocalPassthrough(stub)) {
+ toDelete.push(stub.id);
+ } else {
+ toDetach.push(stub);
+ }
+ });
+
+ if (detachedOpen.length > 0) {
+ options.onOpenFilesDetached?.(detachedOpen);
+ }
+
+ const remarked = linked.some(
+ (stub) => marks.get(stub.id) !== stub.diskUnavailableReason,
+ );
+ if (toDelete.length === 0 && toDetach.length === 0 && !remarked) return stubs;
+
+ if (toDelete.length > 0) {
+ try {
+ await fileStorage.deleteMultipleStirlingFiles(toDelete);
+ } catch (error) {
+ console.error("[pruneMissingRecentFiles] delete failed:", error);
+ }
+ }
+ if (toDetach.length > 0) {
+ await Promise.all(
+ toDetach.map((stub) =>
+ fileStorage
+ .updateFileMetadata(stub.id, detachedFields(stub.localFilePath))
+ .catch((error) =>
+ console.error("[pruneMissingRecentFiles] detach failed:", error),
+ ),
+ ),
+ );
+ }
+
+ const deleteSet = new Set<FileId>(toDelete);
+ const detachSet = new Map<FileId, string | undefined>(
+ toDetach.map((stub) => [stub.id, stub.localFilePath]),
+ );
+ return stubs
+ .filter((stub) => !deleteSet.has(stub.id))
+ .map((stub) => {
+ if (detachSet.has(stub.id)) {
+ return { ...stub, ...detachedFields(detachSet.get(stub.id)) };
+ }
+ if (!marks.has(stub.id)) return stub;
+ const mark = marks.get(stub.id);
+ if (mark === stub.diskUnavailableReason) return stub;
+ return { ...stub, diskUnavailableReason: mark };
+ });
+}