Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions apps/desktop/src-tauri/src/commands/blocking.rs
Original file line number Diff line number Diff line change
@@ -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<T, F>(operation: &'static str, work: F) -> Result<T, NativeError>
where
T: Send + 'static,
F: FnOnce() -> Result<T, NativeError> + 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}"),
))
}
}
}
9 changes: 6 additions & 3 deletions apps/desktop/src-tauri/src/commands/media.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<tauri::ipc::Response, NativeError> {
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`
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src-tauri/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -35,6 +36,7 @@

pub mod atomic_write;
pub mod backup;
pub(crate) mod blocking;
pub mod clipboard;
pub mod extensions;
pub mod markdown;
Expand Down
68 changes: 37 additions & 31 deletions apps/desktop/src-tauri/src/commands/workspace_entries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
) -> Result<Vec<WorkspaceEntry>, 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
Expand Down
43 changes: 25 additions & 18 deletions apps/desktop/src-tauri/src/commands/workspace_windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<WorkspaceSnapshot, NativeError> {
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(
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src-tauri/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
Expand Down
Loading
Loading