diff --git a/apps/desktop/src-tauri/src/commands/blocking.rs b/apps/desktop/src-tauri/src/commands/blocking.rs new file mode 100644 index 00000000..f1d9f87b --- /dev/null +++ b/apps/desktop/src-tauri/src/commands/blocking.rs @@ -0,0 +1,34 @@ +//! Runs synchronous disk work off the async runtime's worker threads. +//! +//! An `async` Tauri command is polled on an async-runtime worker, and a body +//! that walks a vault or reads a large file holds that worker for every task +//! it was driving. `run` hands the body to the blocking pool — the thread pool +//! built for exactly this — so the worker is released while the filesystem +//! call proceeds, then flattens the join result back into the command's +//! ordinary `Result`. + +use crate::error::NativeError; + +/// Runs `work` on the blocking pool and returns its result unchanged. +/// +/// `operation` names the command, which is the only context a join failure +/// carries: a panicking or cancelled worker surfaces as `native.worker_failed` +/// with the operation in `details` rather than as a hung IPC call or a bare +/// panic string. The work itself owns its errors — they pass through typed. +pub(crate) async fn run(operation: &'static str, work: F) -> Result +where + T: Send + 'static, + F: FnOnce() -> Result + Send + 'static, +{ + match tauri::async_runtime::spawn_blocking(work).await { + Ok(result) => result, + Err(error) => { + eprintln!("[{operation}] blocking task failed: {error}"); + Err(NativeError::with_details( + "native.worker_failed", + "The native operation could not finish.", + format!("{operation}: {error}"), + )) + } + } +} diff --git a/apps/desktop/src-tauri/src/commands/media.rs b/apps/desktop/src-tauri/src/commands/media.rs index df5c0e9a..0cbe6d05 100644 --- a/apps/desktop/src-tauri/src/commands/media.rs +++ b/apps/desktop/src-tauri/src/commands/media.rs @@ -23,12 +23,15 @@ use std::io::Read; pub const MAX_MEDIA_BYTES: u64 = 256 * 1024 * 1024; #[tauri::command] -pub fn read_media_file( +pub async fn read_media_file( root_path: String, relative_path: String, ) -> Result { - read_media_file_bytes(&root_path, &relative_path, MAX_MEDIA_BYTES) - .map(tauri::ipc::Response::new) + crate::commands::blocking::run("workspace.read_media", move || { + read_media_file_bytes(&root_path, &relative_path, MAX_MEDIA_BYTES) + }) + .await + .map(tauri::ipc::Response::new) } /// The command body, split out so tests can drive it without an `AppHandle` diff --git a/apps/desktop/src-tauri/src/commands/mod.rs b/apps/desktop/src-tauri/src/commands/mod.rs index 6d0fb9a7..cebe232b 100644 --- a/apps/desktop/src-tauri/src/commands/mod.rs +++ b/apps/desktop/src-tauri/src/commands/mod.rs @@ -6,6 +6,7 @@ //! Submodules: //! - `atomic_write`: Temp-then-rename file replacement that never deletes the destination first. //! - `backup`: Per-note version safety net — lists the copy a save replaced and restores it. +//! - `blocking`: Runs synchronous disk work on the blocking pool with typed worker errors. //! - `clipboard`: Puts workspace *files* on the OS clipboard so a system file manager can paste them. //! - `workspace`: Vault/workspace window lifecycle, file and directory hierarchy operations. //! - `workspace_known`: The read-only list of workspaces the app knows how to open — recents plus managed vaults. @@ -35,6 +36,7 @@ pub mod atomic_write; pub mod backup; +pub(crate) mod blocking; pub mod clipboard; pub mod extensions; pub mod markdown; diff --git a/apps/desktop/src-tauri/src/commands/workspace_entries.rs b/apps/desktop/src-tauri/src/commands/workspace_entries.rs index 5590fd33..d6013fb2 100644 --- a/apps/desktop/src-tauri/src/commands/workspace_entries.rs +++ b/apps/desktop/src-tauri/src/commands/workspace_entries.rs @@ -35,43 +35,49 @@ pub struct WorkspaceEntry { } #[tauri::command] -pub fn list_workspace_entries( +pub async fn list_workspace_entries( root_path: String, include_hidden: bool, path_prefix: Option, ) -> Result, NativeError> { - let root = resolve_workspace_root(&root_path)?; - // A prefix scopes the walk to one subtree: callers like the journal ask - // for just their folder rather than a listing of the whole vault. - let start = match path_prefix.as_deref().map(str::trim) { - Some("") | None => root.clone(), - Some(prefix) => { - let normalized = normalize_relative_path(prefix)?; - // The same exclusions a full scan applies at every level: a - // hidden or ignored segment can never yield entries the tree - // would show, so a scoped walk under one is empty rather than a - // read the tree hides. - let excluded = normalized.split('/').any(|segment| { - (!include_hidden && is_hidden_name(segment)) || IGNORED_FOLDERS.contains(&segment) - }); - if excluded { - return Ok(Vec::new()); - } - let dir = resolve_workspace_entry_path(&root, prefix)?; - // A prefix naming a folder that does not exist yet is an empty - // listing, not a failure — the same answer a full scan gave when - // nothing under it matched. - if !dir.is_dir() { - return Ok(Vec::new()); + // Resolve the root on the blocking pool too, so queued scans validate the + // filesystem when they run rather than trusting a previously resolved path. + crate::commands::blocking::run("workspace.list_entries", move || { + let root = resolve_workspace_root(&root_path)?; + // A prefix scopes the walk to one subtree: callers like the journal ask + // for just their folder rather than a listing of the whole vault. + let start = match path_prefix.as_deref().map(str::trim) { + Some("") | None => root.clone(), + Some(prefix) => { + let normalized = normalize_relative_path(prefix)?; + // The same exclusions a full scan applies at every level: a + // hidden or ignored segment can never yield entries the tree + // would show, so a scoped walk under one is empty rather than a + // read the tree hides. + let excluded = normalized.split('/').any(|segment| { + (!include_hidden && is_hidden_name(segment)) + || IGNORED_FOLDERS.contains(&segment) + }); + if excluded { + return Ok(Vec::new()); + } + let dir = resolve_workspace_entry_path(&root, prefix)?; + // A prefix naming a folder that does not exist yet is an empty + // listing, not a failure — the same answer a full scan gave when + // nothing under it matched. + if !dir.is_dir() { + return Ok(Vec::new()); + } + dir } - dir - } - }; - let mut entries = Vec::new(); - collect_workspace_entries(&root, &start, &mut entries, include_hidden)?; - entries.sort_by(|left, right| left.relative_path.cmp(&right.relative_path)); + }; + let mut entries = Vec::new(); + collect_workspace_entries(&root, &start, &mut entries, include_hidden)?; + entries.sort_by(|left, right| left.relative_path.cmp(&right.relative_path)); - Ok(entries) + Ok(entries) + }) + .await } /// Creates a workspace file of any type. Unlike `create_markdown_file`, this diff --git a/apps/desktop/src-tauri/src/commands/workspace_windows.rs b/apps/desktop/src-tauri/src/commands/workspace_windows.rs index 7d558f6c..5a7d0bfb 100644 --- a/apps/desktop/src-tauri/src/commands/workspace_windows.rs +++ b/apps/desktop/src-tauri/src/commands/workspace_windows.rs @@ -28,30 +28,37 @@ pub struct WorkspaceSnapshot { } #[tauri::command] -pub fn open_workspace( +pub async fn open_workspace( app: tauri::AppHandle, root_path: String, ) -> Result { - let root = resolve_workspace_root(&root_path)?; + // Everything below — root resolution, the asset-scope grant, and the + // listing — runs when the blocking worker picks it up, keeping the vault + // scan off the async worker and validating the root as it is at run + // time. The grant keeps its original order inside the body. + crate::commands::blocking::run("workspace.open", move || { + let root = resolve_workspace_root(&root_path)?; - // Grant `asset://` reads for this vault only. The static scope in - // tauri.conf.json is empty, so the renderer can reach nothing until a - // workspace is deliberately opened, and then only inside it. This is what - // lets live preview render vault-relative images without handing the - // webview the whole filesystem. - if let Err(error) = app.asset_protocol_scope().allow_directory(&root, true) { - // Not fatal: the workspace still opens, images just fall back to alt - // text. Fail loudly so the cause is visible rather than mysterious. - eprintln!( - "[workspace] failed to grant asset scope for {}: {error}", - root.display() - ); - } + // Grant `asset://` reads for this vault only. The static scope in + // tauri.conf.json is empty, so the renderer can reach nothing until a + // workspace is deliberately opened, and then only inside it. This is what + // lets live preview render vault-relative images without handing the + // webview the whole filesystem. + if let Err(error) = app.asset_protocol_scope().allow_directory(&root, true) { + // Not fatal: the workspace still opens, images just fall back to alt + // text. Fail loudly so the cause is visible rather than mysterious. + eprintln!( + "[workspace] failed to grant asset scope for {}: {error}", + root.display() + ); + } - Ok(WorkspaceSnapshot { - workspace: describe_workspace(&root), - files: list_markdown_file_entries(&root)?, + Ok(WorkspaceSnapshot { + workspace: describe_workspace(&root), + files: list_markdown_file_entries(&root)?, + }) }) + .await } pub(crate) fn create_workspace_window_off_main_thread( diff --git a/apps/desktop/src-tauri/src/tests.rs b/apps/desktop/src-tauri/src/tests.rs index cc56dff2..73bd133b 100644 --- a/apps/desktop/src-tauri/src/tests.rs +++ b/apps/desktop/src-tauri/src/tests.rs @@ -11,6 +11,8 @@ //! - [`settings`] — settings paths, read/write, atomic writes, quarantine, //! write preconditions, theme. //! - [`desktop_state`] — desktop-state merge/version/tabs/workspace views. +//! - [`blocking_commands`] — blocking-pool offload semantics and the async +//! boundary of the read commands that use it. //! - [`workspace_markdown`] — shell status, path normalization, markdown //! detection, workspace entry CRUD, symlink escapes, backup/restore, note //! write preconditions. @@ -24,6 +26,7 @@ //! The workspace-window lifecycle tests live in //! `crate::workspace_window_lifecycle_tests` (sibling module). +mod blocking_commands; mod desktop_state; mod search; mod settings; diff --git a/apps/desktop/src-tauri/src/tests/blocking_commands.rs b/apps/desktop/src-tauri/src/tests/blocking_commands.rs new file mode 100644 index 00000000..c7f5b7a7 --- /dev/null +++ b/apps/desktop/src-tauri/src/tests/blocking_commands.rs @@ -0,0 +1,244 @@ +//! Blocking-pool offload tests: `commands::blocking::run` scheduling and +//! result semantics, plus the async boundary of the commands that run on it. +//! +//! The "removed before first poll" tests pin a contract the sync commands +//! could not express: an `async` command captures its arguments when called +//! but does no disk work until the future is polled, so the filesystem it +//! sees is the one at run time — not the one at call time. + +use std::{ + fs, + pin::pin, + sync::mpsc, + task::{Context, Poll, Waker}, + thread, + time::Duration, +}; + +use tauri::async_runtime::block_on; +use tauri::ipc::{InvokeResponseBody, IpcResponse}; + +use crate::NativeError; +use crate::commands::{blocking::run, media::read_media_file, workspace::*}; + +use super::temp_test_dir; + +/// Only a guard against a wedged test hanging forever — a hung channel would +/// otherwise block `cargo test` until CI's timeout. Not a latency assertion. +const HANG_GUARD: Duration = Duration::from_secs(5); + +/// Polls a pinned future once with a no-op waker: the future must arrange +/// its own rescheduling, which `run` does through the JoinHandle's waker. +fn poll_once(future: &mut std::pin::Pin<&mut impl std::future::Future>) -> Poll { + future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) +} + +#[test] +fn run_dispatches_work_to_a_blocking_pool_thread() { + let caller = thread::current().id(); + let worker = block_on(run("test.thread", move || Ok(thread::current().id()))) + .expect("worker returns its thread id"); + + assert_ne!( + caller, worker, + "disk work must not run on the polling thread" + ); +} + +#[test] +fn run_returns_work_results_unchanged() { + let value = block_on(run("test.value", || Ok(vec![1_u8, 2, 3]))).expect("ok value"); + assert_eq!(value, vec![1, 2, 3]); + + // An ordinary NativeError is the work's own failure — it must reach the + // caller untouched rather than being rewritten as a worker failure. + let expected = NativeError::with_details( + "workspace.open_failed", + "Failed to open this workspace.", + "no such directory", + ); + let returned = block_on(run("test.error", { + let expected = expected.clone(); + move || Err::<(), _>(expected) + })) + .expect_err("typed error passes through"); + assert_eq!(returned, expected); +} + +#[test] +fn run_maps_a_worker_panic_to_worker_failed() { + let error = block_on(run( + "media.panic_test", + move || -> Result<(), NativeError> { + panic!("simulated worker panic"); + }, + )) + .expect_err("a panicking worker is a failure, not a hang"); + + assert_eq!(error.code, "native.worker_failed"); + assert_eq!(error.message, "The native operation could not finish."); + let details = error.details.expect("details name the operation"); + assert!( + details.contains("media.panic_test"), + "details should carry the operation name, got: {details}" + ); +} + +#[test] +fn run_is_pending_while_its_worker_is_held() { + block_on(async { + let (gate_tx, gate_rx) = mpsc::channel::<()>(); + let (started_tx, started_rx) = mpsc::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::>(); + + let mut future = pin!(run("test.held", move || { + started_tx.send(()).expect("worker started"); + // The timeout is a deadlock guard, not a speed target: if the + // sender is dropped without releasing this errors too, so a + // panicking test cannot leave the worker parked forever. + gate_rx.recv_timeout(HANG_GUARD).expect("worker released"); + done_tx.send(Ok("held")).expect("completion is reported"); + Ok("held result") + })); + + // First poll schedules the worker but cannot complete it. + assert!(matches!(poll_once(&mut future), Poll::Pending)); + started_rx.recv_timeout(HANG_GUARD).expect("worker started"); + + // A held worker does not serialize the pool: an independent run + // completes while the first is still parked. The result comes back + // over a channel because awaiting `run` inline here would hang + // forever on a serialization regression instead of failing. + let (parallel_tx, parallel_rx) = mpsc::channel::>(); + tauri::async_runtime::spawn(async move { + parallel_tx + .send(run("test.parallel", || Ok(7_u32)).await) + .expect("parallel result is reported"); + }); + let parallel = parallel_rx + .recv_timeout(HANG_GUARD) + .expect("parallel work completes while the held worker is parked"); + assert_eq!(parallel.expect("parallel work succeeds"), 7); + + gate_tx.send(()).expect("release the held worker"); + assert_eq!(future.await.expect("held worker finishes"), "held result"); + assert_eq!( + done_rx + .recv_timeout(HANG_GUARD) + .expect("held worker reported done"), + Ok("held") + ); + }); +} + +#[test] +fn dropping_the_future_lets_the_worker_finish() { + block_on(async { + let (gate_tx, gate_rx) = mpsc::channel::<()>(); + let (done_tx, done_rx) = mpsc::channel::<()>(); + + { + let mut future = pin!(run("test.detached", move || { + gate_rx.recv_timeout(HANG_GUARD).expect("worker released"); + done_tx.send(()).expect("completion is reported"); + Ok(()) + })); + assert!(matches!(poll_once(&mut future), Poll::Pending)); + // Dropping the future drops the JoinHandle, which detaches rather + // than cancels the spawned work. That is intentional: a caller + // that stops awaiting (window closed, request superseded) must + // not strand or abort a read already on the pool, and no window + // or session owner is needed to reap it. + } + + gate_tx.send(()).expect("release the detached worker"); + done_rx + .recv_timeout(HANG_GUARD) + .expect("detached worker ran to completion"); + }); +} + +#[test] +fn list_workspace_entries_validates_the_root_at_run_time() { + let root = temp_test_dir("async-root-removed"); + let root_path = root.to_string_lossy().to_string(); + let future = list_workspace_entries(root_path, false, None); + // Remove the vault after the future exists but before it is polled: the + // worker must see the disk as it is now, not as it was at call time. + fs::remove_dir_all(&root).expect("root removed before first poll"); + + let error = block_on(future).expect_err("missing root is rejected"); + assert_eq!(error.code, "workspace.open_failed"); +} + +#[test] +fn list_workspace_entries_sees_disk_state_at_run_time() { + let root = temp_test_dir("async-root-created"); + let root_path = root.to_string_lossy().to_string(); + fs::remove_dir_all(&root).expect("fixture starts absent"); + let future = list_workspace_entries(root_path, false, None); + + // Populate the vault only after the future is created. + fs::create_dir_all(root.join("docs")).expect("root recreated"); + fs::write(root.join("docs/note.md"), "# Late note\n").expect("note written"); + + let entries = block_on(future).expect("listing succeeds"); + let paths: Vec<&str> = entries + .iter() + .map(|entry| entry.relative_path.as_str()) + .collect(); + assert!(paths.contains(&"docs")); + assert!(paths.contains(&"docs/note.md")); + + fs::remove_dir_all(&root).expect("fixture cleaned up"); +} + +#[test] +fn read_media_file_validates_the_root_at_run_time() { + let root = temp_test_dir("async-media-removed"); + let root_path = root.to_string_lossy().to_string(); + fs::write(root.join("pixel.png"), [0x89_u8]).expect("media written"); + let future = read_media_file(root_path, "pixel.png".to_string()); + // Remove the vault after the future exists but before it is polled. + fs::remove_dir_all(&root).expect("root removed before first poll"); + + // Response is not Debug, so this cannot use `expect_err`. + let error = block_on(future).err().expect("missing root is rejected"); + assert_eq!(error.code, "workspace.open_failed"); +} + +/// Compile-time guard against `open_workspace` regressing back to a sync +/// handler — its body holds an `AppHandle`, so no runtime instance is made +/// here; the workspace-window lifecycle tests cover the seam. +#[test] +fn open_workspace_command_is_async() { + fn assert_async_command(_command: F) + where + F: Fn(tauri::AppHandle, String) -> Fut, + Fut: std::future::Future>, + { + } + + assert_async_command(open_workspace); +} + +#[test] +fn read_media_file_returns_the_file_as_a_raw_response() { + let root = temp_test_dir("async-media-ok"); + fs::write(root.join("pixel.png"), [0x89_u8, 0x50, 0x4e, 0x47]).expect("media written"); + + let response = block_on(read_media_file( + root.to_string_lossy().to_string(), + "pixel.png".to_string(), + )) + .expect("media read succeeds"); + + match response.body().expect("response has a body") { + InvokeResponseBody::Raw(bytes) => assert_eq!(bytes, vec![0x89, 0x50, 0x4e, 0x47]), + other => panic!("media responses must be raw bytes, got {other:?}"), + } + + fs::remove_dir_all(&root).expect("fixture cleaned up"); +} diff --git a/apps/desktop/src-tauri/src/tests/workspace_markdown.rs b/apps/desktop/src-tauri/src/tests/workspace_markdown.rs index da13a63b..e2a9835c 100644 --- a/apps/desktop/src-tauri/src/tests/workspace_markdown.rs +++ b/apps/desktop/src-tauri/src/tests/workspace_markdown.rs @@ -515,11 +515,11 @@ fn list_workspace_entries_scopes_to_a_path_prefix() { ) .expect("outside note is created"); - let entries = list_workspace_entries( + let entries = tauri::async_runtime::block_on(list_workspace_entries( root.to_string_lossy().to_string(), false, Some("journal".to_string()), - ) + )) .expect("prefixed listing succeeds"); let paths: Vec<&str> = entries @@ -557,11 +557,11 @@ fn list_workspace_entries_missing_prefix_is_an_empty_listing() { ) .expect("note is created"); - let entries = list_workspace_entries( + let entries = tauri::async_runtime::block_on(list_workspace_entries( root.to_string_lossy().to_string(), false, Some("journal".to_string()), - ) + )) .expect("missing prefix is not an error"); assert!(entries.is_empty()); @@ -573,11 +573,11 @@ fn list_workspace_entries_missing_prefix_is_an_empty_listing() { fn list_workspace_entries_rejects_a_prefix_that_escapes() { let root = temp_test_dir("list-escape-prefix"); - let error = list_workspace_entries( + let error = tauri::async_runtime::block_on(list_workspace_entries( root.to_string_lossy().to_string(), false, Some("../".to_string()), - ) + )) .expect_err("escaping prefix is rejected"); assert_eq!(error.code, "workspace.invalid_path"); @@ -597,21 +597,21 @@ fn list_workspace_entries_hidden_prefix_is_an_empty_listing() { // A full scan never descends into `.private`, so a scoped walk under it // must answer empty rather than list what the tree hides. - let entries = list_workspace_entries( + let entries = tauri::async_runtime::block_on(list_workspace_entries( root.to_string_lossy().to_string(), false, Some(".private".to_string()), - ) + )) .expect("hidden prefix is not an error"); assert!(entries.is_empty()); // `include_hidden` lifts the exclusion for the prefix as it does for the // walk's own entries. - let entries = list_workspace_entries( + let entries = tauri::async_runtime::block_on(list_workspace_entries( root.to_string_lossy().to_string(), true, Some(".private".to_string()), - ) + )) .expect("hidden prefix with include_hidden succeeds"); assert!( entries @@ -641,11 +641,11 @@ fn list_workspace_entries_ignored_prefix_is_an_empty_listing() { // Direct hit and a buried one — either way the full scan never reaches // these files. for prefix in ["node_modules", "deep/node_modules/x"] { - let entries = list_workspace_entries( + let entries = tauri::async_runtime::block_on(list_workspace_entries( root.to_string_lossy().to_string(), false, Some(prefix.to_string()), - ) + )) .expect("ignored prefix is not an error"); assert!( entries.is_empty(), diff --git a/apps/desktop/src/workspace/useWorkspaceSession.test.tsx b/apps/desktop/src/workspace/useWorkspaceSession.test.tsx index c7aa8acd..b0a23970 100644 --- a/apps/desktop/src/workspace/useWorkspaceSession.test.tsx +++ b/apps/desktop/src/workspace/useWorkspaceSession.test.tsx @@ -232,6 +232,181 @@ describe("useWorkspaceSession", () => { expect(current().entries.map((item) => item.relative_path)).toEqual(["second.md"]); }); + it("keeps the newest open when the same root returns out of order (A->B->A)", async () => { + const staleOpen = deferred(); + const latestOpen = deferred(); + const latestEntries = deferred(); + const onOpened = vi.fn(); + const newestFile = { + relative_path: "newest.md", + file_name: "newest.md", + parent_path: "", + byte_size: 2, + updated_at: null + }; + const latestSnapshot: NativeWorkspaceSnapshot = { ...snapshot("/first"), files: [newestFile] }; + let opens = 0; + await render( + { + openWorkspace: (rootPath) => { + if (rootPath !== "/first") return Promise.resolve(snapshot(rootPath)); + opens += 1; + return opens === 1 ? staleOpen.promise : latestOpen.promise; + }, + listWorkspaceEntries: (rootPath) => + rootPath === "/first" ? latestEntries.promise : Promise.resolve([entry("other.md")]) + }, + { onOpened } + ); + + let stale: Promise | undefined; + await act(async () => { + stale = current().open("/first"); + }); + await act(async () => { + await current().open("/second"); + }); + + let latest: Promise | undefined; + await act(async () => { + latest = current().open("/first"); + latestOpen.resolve(latestSnapshot); + latestEntries.resolve([entry("newest.md")]); + await latest; + }); + + // The first open for "/first" only finishes now — after a newer open of + // the same root already landed. Its result must not be applied. + await act(async () => { + staleOpen.resolve(snapshot("/first")); + await stale; + }); + + expect(current().rootPath).toBe("/first"); + expect(current().snapshot).toEqual(latestSnapshot); + expect(current().files).toEqual(latestSnapshot.files); + expect(current().entries.map((item) => item.relative_path)).toEqual(["newest.md"]); + // The "/second" switch and the newest "/first" open each announced once; + // the stale open announced nothing. + expect(onOpened).toHaveBeenCalledTimes(2); + expect(onOpened).toHaveBeenNthCalledWith(1, "/second", snapshot("/second")); + expect(onOpened).toHaveBeenNthCalledWith(2, "/first", latestSnapshot); + }); + + it("lets the newest reopen of the same path win", async () => { + const staleOpen = deferred(); + const latestOpen = deferred(); + const latestEntries = deferred(); + const onOpened = vi.fn(); + const latestSnapshot: NativeWorkspaceSnapshot = { + ...snapshot("/vault"), + files: [{ relative_path: "newest.md", file_name: "newest.md", parent_path: "", byte_size: 2, updated_at: null }] + }; + let opens = 0; + await render( + { + openWorkspace: () => { + opens += 1; + return opens === 1 ? staleOpen.promise : latestOpen.promise; + }, + listWorkspaceEntries: () => latestEntries.promise + }, + { onOpened } + ); + + let stale: Promise | undefined; + let latest: Promise | undefined; + await act(async () => { + stale = current().open("/vault"); + }); + await act(async () => { + latest = current().open("/vault"); + latestOpen.resolve(latestSnapshot); + latestEntries.resolve([entry("newest.md")]); + await latest; + }); + await act(async () => { + staleOpen.resolve(snapshot("/vault")); + await stale; + }); + + expect(current().snapshot).toEqual(latestSnapshot); + expect(current().entries.map((item) => item.relative_path)).toEqual(["newest.md"]); + expect(onOpened).toHaveBeenCalledTimes(1); + expect(onOpened).toHaveBeenCalledWith("/vault", latestSnapshot); + }); + + it("ignores a superseded failure that lands after the same root reopened", async () => { + const staleOpen = deferred(); + const latestOpen = deferred(); + const onUnavailable = vi.fn(); + let opens = 0; + await render( + { + openWorkspace: (rootPath) => { + if (rootPath !== "/first") return Promise.resolve(snapshot(rootPath)); + opens += 1; + return opens === 1 ? staleOpen.promise : latestOpen.promise; + } + }, + { onUnavailable } + ); + + let stale: Promise | undefined; + await act(async () => { + stale = current().open("/first"); + }); + await act(async () => { + await current().open("/second"); + }); + await act(async () => { + const latest = current().open("/first"); + latestOpen.resolve(snapshot("/first")); + await latest; + }); + await act(async () => { + staleOpen.reject(new Error("too late")); + await stale; + }); + + expect(current()).toMatchObject({ phase: "ready", rootPath: "/first", error: null }); + expect(current().entries.map((item) => item.relative_path)).toEqual(["first.md"]); + expect(onUnavailable).not.toHaveBeenCalled(); + }); + + it("drops a refresh that straddles an A->B->A switch", async () => { + const refreshListing = deferred(); + let deferRefresh = false; + await render({ + listWorkspaceEntries: (rootPath) => + deferRefresh && rootPath === "/first" + ? refreshListing.promise + : Promise.resolve([entry(`${rootPath.slice(1)}.md`)]) + }); + await act(async () => { + await current().open("/first"); + }); + + deferRefresh = true; + let refreshed: Promise | undefined; + await act(async () => { + refreshed = current().refreshEntries("/first"); + }); + await act(async () => { + await current().open("/second"); + }); + deferRefresh = false; + await act(async () => { + await current().open("/first"); + }); + await act(async () => { + refreshListing.resolve([entry("stale.md")]); + }); + + await expect(refreshed).resolves.toBe(false); + expect(current().entries.map((item) => item.relative_path)).toEqual(["first.md"]); + }); + it("starts a new root from default view settings when its own cannot be read", async () => { vi.mocked(readWorkspaceSettings).mockResolvedValueOnce({ showHidden: true, explorerSort: "name-desc" }); const listWorkspaceEntries = vi.fn(async () => [entry("a.md")]); diff --git a/apps/desktop/src/workspace/useWorkspaceSession.ts b/apps/desktop/src/workspace/useWorkspaceSession.ts index 11b3f6e0..40aff6d8 100644 --- a/apps/desktop/src/workspace/useWorkspaceSession.ts +++ b/apps/desktop/src/workspace/useWorkspaceSession.ts @@ -25,8 +25,9 @@ export interface UseWorkspaceSessionOptions { * per-workspace view settings first (the listing depends on `showHidden`), * then the snapshot, then the entry listing. * - * Every step checks the root token after its `await`, so the last `open` wins - * and an open, listing or failure for a root the window has left is dropped. + * Every step checks the root token and the open generation after its + * `await`, so the last `open` wins even when it reopens the same root — a + * stale A->B->A result or failure is dropped instead of overwriting it. * Any failure gives the root up, the same for a startup restore and an * in-window switch. */ @@ -41,6 +42,9 @@ export function useWorkspaceSession({ const [showHidden, setShowHiddenState] = useState(DEFAULT_WORKSPACE_SETTINGS.showHidden); const [explorerSort, setExplorerSort] = useState(DEFAULT_EXPLORER_SORT); const rootRef = useRef(null); + // Monotonic request identity: each `open` gets the next number, so an + // earlier open of the *same* root is stale too, not only other roots. + const openGeneration = useRef(0); const showHiddenRef = useRef(showHidden); // The latest inputs, read after each `await`. Updated in an effect per the // react-hooks/refs rule. @@ -60,30 +64,33 @@ export function useWorkspaceSession({ setShowHidden(DEFAULT_WORKSPACE_SETTINGS.showHidden); setExplorerSort(DEFAULT_EXPLORER_SORT); } + const generation = ++openGeneration.current; rootRef.current = next; setRootPath(next); dispatch({ type: "open" }); + // Still the open this window wants: same root, and no newer open since. + const isCurrent = () => rootRef.current === next && openGeneration.current === generation; try { // A failed settings read falls back to defaults rather than blocking // the workspace from opening. try { const settings = await latest.current.api.readWorkspaceSettings(next); - if (rootRef.current !== next) return; + if (!isCurrent()) return; setShowHidden(settings.showHidden); // Mocked or older settings documents may carry no order at all. setExplorerSort(settings.explorerSort ?? DEFAULT_EXPLORER_SORT); } catch { - if (rootRef.current !== next) return; + if (!isCurrent()) return; } const snapshot = await latest.current.api.openWorkspace(next); - if (rootRef.current !== next) return; + if (!isCurrent()) return; const entries = await latest.current.api.listWorkspaceEntries(next, showHiddenRef.current); - if (rootRef.current !== next) return; + if (!isCurrent()) return; dispatch({ type: "opened", snapshot, entries }); setFiles(snapshot.files); latest.current.onOpened?.(next, snapshot); } catch (error) { - if (rootRef.current !== next) return; + if (!isCurrent()) return; dispatch({ type: "failed", message: workspaceErrorMessage(error) }); rootRef.current = null; setRootPath(null); @@ -93,8 +100,9 @@ export function useWorkspaceSession({ }, [setShowHidden]); const refreshEntries = useCallback(async (root: string): Promise => { + const generation = openGeneration.current; const entries = await latest.current.api.listWorkspaceEntries(root, showHiddenRef.current); - if (rootRef.current !== root) return false; + if (rootRef.current !== root || openGeneration.current !== generation) return false; dispatch({ type: "listed", entries }); return true; }, []); diff --git a/docs/reviews/2026-10-10/architecture-native-backend-med-hard.md b/docs/reviews/2026-10-10/architecture-native-backend-med-hard.md index 3f3bf8e3..a8ffc936 100644 --- a/docs/reviews/2026-10-10/architecture-native-backend-med-hard.md +++ b/docs/reviews/2026-10-10/architecture-native-backend-med-hard.md @@ -5,7 +5,7 @@ Scope: `apps/desktop/src-tauri` — `lib.rs` setup, `commands/` (workspace*, sea ## Summary — top 5 2. **Close the attach/release race in the background sync bootstrap.** `watch_workspace` acquires watcher interest, then spawns a thread that later calls `registry::attach` (`watcher/lifecycle.rs:132-165`). A window destroyed during bootstrap leaves `adopt()` holding interest for a dead label (`sync/registry.rs:76-80`) — a leaked engine that keeps recording a vault nobody has open, and can resurrect metadata after delete. Same root cause as the known `detach_engine_on_delete` story; fix them together. -3. **All commands are synchronous `fn`s, so heavy work runs on the IPC/main path.** `index_documents` (SQLite batch), `sync_now` (network round trip), `list_workspace_entries` (10k-entry walk) are all `pub fn` (`search.rs:95`, `sync/round.rs:704`, `workspace_entries.rs:38`). The codebase already knows the cost — bootstrap was moved off-thread citing Windows AppHang (`watcher/lifecycle.rs:140-145`) — but the fix was applied only where it hurt first. +3. **Finish moving heavy command work off the IPC/main path.** Revalidation and the first read-only worker fix are recorded in `native-command-io-followup-med-med.md`. Workspace scans and media reads now use blocking workers; search/index, history, and mutation lock paths remain separate work. `sync_now` no longer exists and network rounds are already threaded. 4. **The TS↔Rust command contract is hand-mirrored with no mechanical check.** `app_command_list!` names each command once in Rust (`commands/mod.rs:58`), while `NativeCommandMap` in `commands.ts` re-declares names, args, and results by hand. Arg-name/casing drift fails only at runtime. Either generate bindings (tauri-specta/ts-rs) or add a CI check comparing `APP_COMMAND_PATHS` against the map's keys. 5. **The pending `ipc_hardening` story has the right scope; extend it to the search pool.** Root-is-renderer-chosen (`workspace_paths.rs:65-91`), `csp: null`, and unreleased asset grants are correctly identified. The same root-authority fix would also stop `get_search_connection` creating an index for any existing directory the renderer names (`search.rs:26-41`). @@ -33,13 +33,13 @@ Scope: `apps/desktop/src-tauri` — `lib.rs` setup, `commands/` (workspace*, sea ## 3. Blocking work on synchronous commands -**Current decision.** Every command except `open_workspace_window` is a plain `fn` — Tauri runs those on the main/IPC path, not a worker. The codebase documents the consequence itself: bootstrap was threaded because "on a large vault that takes long enough to stall the Windows message pump and trigger an AppHang" (`watcher/lifecycle.rs:141-145`). Yet `index_documents` writes a SQLite batch (`search.rs:95`), `sync_now` does a full git round trip including fetch/push (`sync/round.rs:704-724`), and `list_workspace_entries` walks up to `MAX_WORKSPACE_ENTRIES` files (`workspace_entries.rs:38`, `workspace_paths.rs:14`) — all synchronously. +**Current decision.** The original examples were partly stale: `sync_now` is gone, network rounds/imports already use background threads, and some command handlers were already async. The first follow-up moves workspace scans and media reads onto the blocking pool. Search command handlers still perform SQLite work synchronously, while history/maintenance and mutation paths include blocking disk work and lock waits. See `native-command-io-followup-med-med.md` for the revalidated command groups. -**Cost.** A multi-second vault walk or a slow git fetch freezes UI for every window, not just the caller's. `sync_now` is the worst offender: network latency is unbounded, and the footer button that triggers it is exactly where a user notices a hang. +**Cost.** Remaining synchronous disk work and lock waits can stall the main command path. This is a source-path finding, not a measured latency result. Moving only an index writer to a worker would still let a synchronous search or rename/delete cleanup block the main thread waiting for its connection mutex. -**Alternative.** Mark I/O commands `async` and run the body via `tauri::async_runtime::spawn_blocking` — `sync/round.rs:379` and `sync/network.rs:348` already have `network_call`/`bounded` wrappers doing this pattern internally for threads; reuse it at the command boundary. Prioritize `sync_now`, `index_documents`, `list_workspace_entries`, `sync_history`, `read_version_diff`. Cheap reads (`read_markdown_file`, settings reads) can stay sync. +**Alternative.** Use async command boundaries plus the shared `commands::blocking::run` helper for blocking bodies. Next handle the search command family together with its synchronous mutation callers, rechecking workspace ownership after yielding. Treat engine/lane lifecycle and mobile last-chance recording separately rather than converting every handler in one pass. -**Effort/risk/payoff.** Med effort, low risk (signatures change, bodies don't), high payoff on Windows and Android especially. +**Effort/risk/payoff.** Medium effort and concurrency risk for the remaining shared-state paths; potential responsiveness payoff on desktop and mobile. ## 4. TS command map is hand-synced with Rust diff --git a/docs/reviews/2026-10-10/native-command-io-followup-med-med.md b/docs/reviews/2026-10-10/native-command-io-followup-med-med.md new file mode 100644 index 00000000..32486483 --- /dev/null +++ b/docs/reviews/2026-10-10/native-command-io-followup-med-med.md @@ -0,0 +1,53 @@ +# Native command I/O follow-up + +Revalidated against `main` at `054406b3`. This is a source-path audit, not a +measured latency benchmark. Scope is the registered command surface in +`apps/desktop/src-tauri/src/commands/mod.rs` and its filesystem, SQLite, sync, +dialog, and lifecycle callees. + +## Corrections to the original audit + +- `sync_now` is no longer a registered command or implementation. Sync network + work runs in `sync/registry.rs::start_round_inner` on a named thread. + Git import similarly starts `thinkbrain-import`; sign-in setup delegates to + the existing background round. Their synchronous preparation still includes + settings/catalog/keychain access. +- Some commands are already async: workspace-window creation and picked-file + dialogs. Async alone does not make blocking code nonblocking: the picked-file + commands still call blocking dialog and file APIs on the async runtime. + +## Priorities and boundaries + +| Area | Current work on the command path | Decision | +|---|---|---| +| `open_workspace`, `list_workspace_entries` | Recursive Markdown/tree scans and metadata reads | First fix implemented: owned inputs, async command, blocking worker; validate paths inside the worker. | +| `read_media_file` | Bounded whole-file read, up to the existing 256 MiB cap | First fix implemented: existing contained/capped read runs in a blocking worker; raw IPC bytes preserved. | +| Search command family | SQLite open/schema, transactions/FTS optimize, queries, and connection-mutex waits | Next focused change: treat reads/writes and synchronous rename/delete index cleanup together. | +| History/conflict/maintenance | History walks/diffs, filesystem comparisons/restores, object traversal/cleanup, engine/lane locks | Separate lifecycle-aware follow-up; do not retain a stale engine across a yield. | +| Markdown/text/backup and workspace CRUD | Reads, atomic writes, backups, recursive rename/delete, mutation locks | Still synchronous; assess together with search cleanup before parallelizing mutation paths. | +| Settings/themes/extensions/known workspaces/sign-in | File reads/writes, theme enumeration/seeding, bounded extension reads, path probes, catalog/keychain access | Lower-priority I/O remains; preserve document preconditions, lock ordering, and platform behavior. | +| Watcher and app backgrounding | OS watcher registration/release and last-chance settled-note recording; bootstrap/network work already threaded | Keep lifecycle ordering intact. Mobile suspension makes a blanket fire-and-forget conversion unsafe. | +| Capabilities/window-root/quarantine list/clipboard | State/capability answers and platform clipboard APIs | Do not blanket-convert these; platform-affine APIs need their own review. | + +## First-fix invariants + +- No root, path, connection, or engine is resolved before the worker yield and + then trusted later. The read-only scan bodies keep their existing path + validation, traversal limits, exclusions, sorting, and error codes. +- No new session/index/engine ownership is introduced. A dropped command future + need not cancel a blocking read; it must not create persistent holdings. +- The renderer checks a monotonic open generation *and* the root after each + `await` in `useWorkspaceSession`, so a stale result or failure is rejected + even when the newest open targets the same root (A->B->A). Root identity + alone was not enough: out-of-order worker completions make a late same-path + result practical. +- Worker join/panic failures become logged, typed native errors; ordinary + domain errors pass through unchanged. + +## Remaining action + +Keep `async_io_commands` in progress after the first fix. Next audit/fix the +whole search lock surface, including `workspace_paths::remove_search_index_entry` +and managed-workspace deletion. A synchronous caller waiting on a worker-held +SQLite mutex can still block the main thread, and a late index open must not +recreate deleted metadata or repool a released workspace. diff --git a/plans/other_tasks/pending-async_io_commands-med-med.md b/plans/other_tasks/pending-async_io_commands-med-med.md deleted file mode 100644 index 1a742875..00000000 --- a/plans/other_tasks/pending-async_io_commands-med-med.md +++ /dev/null @@ -1,16 +0,0 @@ -# Story: Move blocking I/O commands off the sync IPC path - -All Tauri commands are synchronous `fn`s; `index_documents`, `sync_now` -(network I/O), `list_workspace_entries` on large vaults block the IPC/main -path. The codebase already threaded the sync bootstrap specifically to dodge -a Windows AppHang — the same hazard applies to every heavy command -(`docs/reviews/2026-10-10/architecture-native-backend-med-hard.md` #3). - -## Acceptance - -- [ ] Audit commands for filesystem/network work; convert the heavy ones to - `async` + `spawn_blocking` (or background-thread + event, where a - progress stream already exists). -- [ ] `sync_now` and index/build commands no longer run on the main path. -- [ ] No new races: anything touching per-workspace state re-checks after - the yield. diff --git a/plans/other_tasks/wip-async_io_commands-med-med.md b/plans/other_tasks/wip-async_io_commands-med-med.md new file mode 100644 index 00000000..e49a70b4 --- /dev/null +++ b/plans/other_tasks/wip-async_io_commands-med-med.md @@ -0,0 +1,21 @@ +# Story: Move blocking I/O commands off the sync IPC path + +Revalidated on `main` at `054406b3`: `sync_now` is gone and network rounds/imports +are already threaded. Workspace scans, media reads, SQLite operations, and other +filesystem work still need attention. See +`docs/reviews/2026-10-10/native-command-io-followup-med-med.md`. + +## Acceptance + +- [x] Revalidate the registered command surface and background worker paths. +- [x] Move read-only workspace scans and media reads to blocking workers, + preserving validation, output, errors, and stale-result handling. +- [ ] Move search/index work off the main path, including synchronous callers + waiting on the same connection locks. +- [ ] Address remaining heavy history/mutation/dialog work in focused changes. +- [ ] No new races: resolve mutable workspace state after yielding and preserve + lifecycle/lock ordering. + +First-fix validation: focused Rust scheduling/path/result tests, unchanged +`useWorkspaceSession` stale-result tests, and `pnpm qa` pass. No live native +window or emulator run is claimed for this change.