Skip to content

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

Fix toast spam on desktop and file linking (#8029)

James Brunton51e0f383c87a
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index b3cae278c9..5d9a86668e 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -83,7 +83,10 @@ jobs:
# releases (v2.0.0 / v2.5.0 / v2.10.0) and verifies admin login still
# works after Hibernate's ddl-auto=update migrates the schema. Gated on
# the `project` filter so doc-only PRs skip this ~5-minute job.
- if: needs.files-changed.outputs.project == 'true'
+ if: |
+ !cancelled() &&
+ needs.files-changed.outputs.project == 'true' &&
+ contains(fromJSON('["success", "skipped"]'), needs.gradle-cache-prime.result)
needs: [files-changed, gradle-cache-prime]
permissions:
contents: read
@@ -128,7 +131,10 @@ jobs:
secrets: inherit
playwright-e2e-live:
- if: needs.files-changed.outputs.frontend == 'true'
+ if: |
+ !cancelled() &&
+ needs.files-changed.outputs.frontend == 'true' &&
+ contains(fromJSON('["success", "skipped"]'), needs.gradle-cache-prime.result)
needs: [files-changed, gradle-cache-prime]
permissions:
contents: read
@@ -136,7 +142,10 @@ jobs:
secrets: inherit
playwright-e2e-enterprise:
- if: needs.files-changed.outputs.proprietary == 'true'
+ if: |
+ !cancelled() &&
+ needs.files-changed.outputs.proprietary == 'true' &&
+ contains(fromJSON('["success", "skipped"]'), needs.gradle-cache-prime.result)
needs: [files-changed, gradle-cache-prime]
permissions:
contents: read
@@ -154,7 +163,10 @@ jobs:
secrets: inherit
docker-compose-tests:
- if: needs.files-changed.outputs.project == 'true'
+ if: |
+ !cancelled() &&
+ needs.files-changed.outputs.project == 'true' &&
+ contains(fromJSON('["success", "skipped"]'), needs.gradle-cache-prime.result)
needs: [files-changed, gradle-cache-prime]
permissions:
actions: write
@@ -192,7 +204,10 @@ jobs:
dockerfiles-changed: ${{ needs.files-changed.outputs.dockerfiles }}
tauri-build:
- if: needs.files-changed.outputs.tauri == 'true'
+ if: |
+ !cancelled() &&
+ needs.files-changed.outputs.tauri == 'true' &&
+ contains(fromJSON('["success", "skipped"]'), needs.gradle-cache-prime.result)
needs: [files-changed, gradle-cache-prime]
permissions:
contents: read
@@ -224,7 +239,10 @@ jobs:
# generators, generated files, generation tasks) rather than the broad
# frontend filter, so a CSS-only PR does not pay for a backend build.
generated-models:
- if: needs.files-changed.outputs.generated-models == 'true'
+ if: |
+ !cancelled() &&
+ needs.files-changed.outputs.generated-models == 'true' &&
+ contains(fromJSON('["success", "skipped"]'), needs.gradle-cache-prime.result)
needs: [files-changed, gradle-cache-prime]
permissions:
contents: read
diff --git a/.taskfiles/desktop.yml b/.taskfiles/desktop.yml
index 555e252a4e..bee37fa019 100644
--- a/.taskfiles/desktop.yml
+++ b/.taskfiles/desktop.yml
@@ -49,7 +49,8 @@ tasks:
ignore_error: true
dir: editor
cmds:
- - npx tauri dev --no-watch
+ # Dev HTTP uses the packaged app origin instead of the Vite origin; keep this out of builds.
+ - npx tauri dev --no-watch --features tauri-plugin-http/unsafe-headers
build:
desc: "Build Tauri desktop app (production)"
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index e78620e065..68cdf0a3bb 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -4500,6 +4500,8 @@ openFromComputer = "Open from computer"
openSettings = "Open settings"
other = "Other"
recent = "Recent"
+uploadFailedBody = "Could not add the selected files."
+uploadFailedTitle = "Upload failed"
viewAll = "View all {{count}} files"
[fileSidebar.fileItem]
diff --git a/frontend/editor/src-tauri/Cargo.toml b/frontend/editor/src-tauri/Cargo.toml
index f8582f4f94..083dbe2be8 100644
--- a/frontend/editor/src-tauri/Cargo.toml
+++ b/frontend/editor/src-tauri/Cargo.toml
@@ -52,7 +52,7 @@ rand = "0.10"
core-foundation = "0.10"
core-services = "1.0"
objc2 = "0.6.4"
-objc2-app-kit = { version = "0.3.2", features = ["NSPrintInfo", "NSPrintOperation"] }
+objc2-app-kit = { version = "0.3.2", features = ["NSPrintInfo", "NSPrintOperation", "NSPasteboard", "NSDragging"] }
objc2-foundation = { version = "0.3.2", features = ["NSObject", "NSString", "NSURL"] }
objc2-pdf-kit = { version = "0.3.2", features = ["PDFDocument", "objc2-app-kit"] }
diff --git a/frontend/editor/src-tauri/src/commands/file_drop.rs b/frontend/editor/src-tauri/src/commands/file_drop.rs
new file mode 100644
index 0000000000..4645930f3d
--- /dev/null
+++ b/frontend/editor/src-tauri/src/commands/file_drop.rs
@@ -0,0 +1,258 @@
+use serde::Deserialize;
+use std::sync::Mutex;
+
+// Real filesystem paths of the most recent OS file drop, recorded natively by the
+// performDragOperation: swizzle (see macos_capture) before WebKit fires the DOM
+// drop. resolve_dropped_file_paths consumes them to link the matching DOM files;
+// the async resolve can't read the drag pasteboard itself, as the drag session has
+// ended by the time it runs.
+static DRAG_SNAPSHOT: Mutex<Vec<std::path::PathBuf>> = Mutex::new(Vec::new());
+
+fn snapshot() -> std::sync::MutexGuard<'static, Vec<std::path::PathBuf>> {
+ DRAG_SNAPSHOT
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DroppedFile {
+ name: String,
+ size: u64,
+ last_modified: u64,
+}
+
+fn matching_paths(files: &[DroppedFile], paths: Vec<std::path::PathBuf>) -> Vec<Option<String>> {
+ files
+ .iter()
+ .map(|file| {
+ let mut matches = paths.iter().filter(|path| {
+ if path.file_name().and_then(|name| name.to_str()) != Some(file.name.as_str()) {
+ return false;
+ }
+ let Ok(metadata) = path.metadata() else {
+ return false;
+ };
+ let modified_ms = metadata
+ .modified()
+ .ok()
+ .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
+ .map(|time| time.as_millis() as u64);
+ metadata.is_file()
+ && metadata.len() == file.size
+ && modified_ms.is_some_and(|ms| ms / 1000 == file.last_modified / 1000)
+ });
+ let path = matches.next()?;
+ // Identical names/metadata in two folders cannot safely identify a save target.
+ if matches.next().is_some() {
+ return None;
+ }
+ path.to_str().map(String::from)
+ })
+ .collect()
+}
+
+/// Resolves the webview's DOM files against the real paths captured from the last
+/// OS drop. Unknown or ambiguous files stay unlinked rather than taking an unsafe
+/// save target.
+#[tauri::command]
+pub fn resolve_dropped_file_paths(files: Vec<DroppedFile>) -> Vec<Option<String>> {
+ // Consume the snapshot: a later drop that captures no paths must not reuse a
+ // stale one, and a second window must not resolve against this drop's paths.
+ matching_paths(&files, std::mem::take(&mut *snapshot()))
+}
+
+/// Starts capturing OS file-drop paths for this webview so resolve_dropped_file_paths
+/// can hand them to the matching DOM files. No-op off macOS (Windows resolves the
+/// DOM File directly through WebView2's AdditionalObjects bridge).
+#[cfg(target_os = "macos")]
+pub fn install_drag_path_capture(webview: *mut std::ffi::c_void) {
+ macos_capture::install(webview);
+}
+
+#[cfg(not(target_os = "macos"))]
+pub fn install_drag_path_capture(_webview: *mut std::ffi::c_void) {}
+
+/// Frontend startup calls this so the capture is installed on the live WKWebView
+/// (webview creation lifecycle hooks proved unreliable). Idempotent; no-op off macOS.
+#[cfg(target_os = "macos")]
+#[tauri::command]
+pub fn install_drag_capture(webview: tauri::WebviewWindow) {
+ if let Err(error) = webview.with_webview(|platform| install_drag_path_capture(platform.inner()))
+ {
+ log::warn!("Could not install drag-path capture: {error}");
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+#[tauri::command]
+pub fn install_drag_capture() {}
+
+// Tauri keeps dragDropEnabled=false so the webview's own HTML5 drag-and-drop
+// (in-page reordering, the drop zones) keeps working; that also means wry never
+// reports the dropped paths to us. wry's WryWebView still overrides
+// performDragOperation: and reads those paths off the dragging pasteboard before
+// forwarding the drop on to WebKit, so we swizzle that method to record the same
+// paths and then call straight through.
+#[cfg(target_os = "macos")]
+mod macos_capture {
+ use super::snapshot;
+ use objc2::runtime::{AnyObject, Bool, Imp, ProtocolObject, Sel};
+ use objc2::sel;
+ use objc2_app_kit::NSDraggingInfo;
+ use objc2_foundation::{NSArray, NSString};
+ use std::ffi::c_void;
+ use std::path::PathBuf;
+ use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering};
+
+ static ORIGINAL: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
+
+ // NSFilenamesPboardType is the legacy pasteboard type, but it is what wry reads
+ // and it yields plain path strings; NSPasteboardTypeFileURL can hand back an
+ // unresolvable file-reference URL for the same drop.
+ #[allow(deprecated)]
+ fn dragged_filenames(info: &ProtocolObject<dyn NSDraggingInfo>) -> Vec<PathBuf> {
+ use objc2_app_kit::NSFilenamesPboardType;
+ let pasteboard = info.draggingPasteboard();
+ let filenames_type = unsafe { NSFilenamesPboardType };
+ let types = NSArray::arrayWithObject(filenames_type);
+ if pasteboard.availableTypeFromArray(&types).is_none() {
+ return Vec::new();
+ }
+ let Some(list) = pasteboard.propertyListForType(filenames_type) else {
+ return Vec::new();
+ };
+ let Ok(list) = list.downcast::<NSArray>() else {
+ return Vec::new();
+ };
+ (0..list.count())
+ .filter_map(|index| {
+ list.objectAtIndex(index)
+ .downcast::<NSString>()
+ .ok()
+ .map(|name| PathBuf::from(name.to_string()))
+ })
+ .collect()
+ }
+
+ unsafe extern "C-unwind" fn perform_drag_operation(
+ this: *mut AnyObject,
+ cmd: Sel,
+ sender: *mut AnyObject,
+ ) -> Bool {
+ if let Some(info) = (sender as *const ProtocolObject<dyn NSDraggingInfo>).as_ref() {
+ // Always replace, so a path-less drag (e.g. an in-page reorder) clears
+ // any prior paths instead of leaving them for the next resolve.
+ *snapshot() = dragged_filenames(info);
+ }
+ // Set before the swizzle is installed, so it is never null when reached.
+ let original: unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> Bool =
+ std::mem::transmute(ORIGINAL.load(Ordering::Acquire));
+ original(this, cmd, sender)
+ }
+
+ pub fn install(webview: *mut c_void) {
+ static INSTALLED: AtomicBool = AtomicBool::new(false);
+ if INSTALLED.load(Ordering::SeqCst) {
+ return;
+ }
+ let Some(object) = (unsafe { (webview as *const AnyObject).as_ref() }) else {
+ return;
+ };
+ // The instance's runtime class is a dynamic NSKVONotifying_* subclass
+ // (AppKit installs a KVO observer on the webview). performDragOperation:
+ // is defined on wry's own WryWebView class, so walk up to it and swizzle
+ // there; the KVO subclass inherits the replaced implementation.
+ let mut class = object.class();
+ while class.name().to_string_lossy().contains("NSKVONotifying")
+ || !class.name().to_string_lossy().contains("WryWebView")
+ {
+ let Some(parent) = class.superclass() else {
+ return;
+ };
+ class = parent;
+ }
+ let selector = sel!(performDragOperation:);
+ let Some(method) = class.instance_method(selector) else {
+ return;
+ };
+ // wry's WryWebView overrides performDragOperation:; if a future wry stops
+ // doing so this reads as WKWebView's inherited method and we skip it,
+ // rather than swizzling every WKWebView in the process.
+ let inherited = class
+ .superclass()
+ .and_then(|parent| parent.instance_method(selector))
+ .is_some_and(|parent_method| std::ptr::eq(parent_method, method));
+ if inherited {
+ return;
+ }
+ ORIGINAL.store(method.implementation() as *mut c_void, Ordering::Release);
+ let replacement: Imp = unsafe {
+ std::mem::transmute(
+ perform_drag_operation
+ as unsafe extern "C-unwind" fn(*mut AnyObject, Sel, *mut AnyObject) -> Bool,
+ )
+ };
+ unsafe { method.set_implementation(replacement) };
+ INSTALLED.store(true, Ordering::SeqCst);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn links_only_a_unique_matching_file() {
+ let directory = std::env::temp_dir().join(format!("stirling-drop-{}", std::process::id()));
+ std::fs::create_dir_all(directory.join("other")).unwrap();
+ let path = directory.join("report.pdf");
+ std::fs::write(&path, b"pdf").unwrap();
+ let modified = path.metadata().unwrap().modified().unwrap();
+ let last_modified = modified
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_millis() as u64;
+ let file = DroppedFile {
+ name: "report.pdf".into(),
+ size: 3,
+ last_modified,
+ };
+ assert_eq!(
+ matching_paths(&[file], vec![path.clone()]),
+ vec![Some(path.to_str().unwrap().into())]
+ );
+
+ let copy = directory.join("other/report.pdf");
+ std::fs::copy(&path, &copy).unwrap();
+ std::fs::OpenOptions::new()
+ .write(true)
+ .open(&copy)
+ .unwrap()
+ .set_modified(modified)
+ .unwrap();
+ let file = DroppedFile {
+ name: "report.pdf".into(),
+ size: 3,
+ last_modified,
+ };
+ assert_eq!(
+ matching_paths(&[file], vec![path.clone(), copy]),
+ vec![None]
+ );
+
+ for (name, size, time) in [
+ ("other.pdf", 3, last_modified),
+ ("report.pdf", 4, last_modified),
+ ("report.pdf", 3, 0),
+ ] {
+ let file = DroppedFile {
+ name: name.into(),
+ size,
+ last_modified: time,
+ };
+ assert_eq!(matching_paths(&[file], vec![path.clone()]), vec![None]);
+ }
+ std::fs::remove_dir_all(directory).unwrap();
+ }
+}
diff --git a/frontend/editor/src-tauri/src/commands/mod.rs b/frontend/editor/src-tauri/src/commands/mod.rs
index e8ae386b48..5e2da45176 100644
--- a/frontend/editor/src-tauri/src/commands/mod.rs
+++ b/frontend/editor/src-tauri/src/commands/mod.rs
@@ -1,5 +1,6 @@
pub mod backend;
pub mod files;
+pub mod file_drop;
pub mod connection;
pub mod auth;
pub mod default_app;
diff --git a/frontend/editor/src-tauri/src/directory_drop.rs b/frontend/editor/src-tauri/src/directory_drop.rs
index 6dfc114390..c6fbcc9a1c 100644
--- a/frontend/editor/src-tauri/src/directory_drop.rs
+++ b/frontend/editor/src-tauri/src/directory_drop.rs
@@ -1,4 +1,4 @@
-/// Resolves dropped DOM folders on Windows while leaving HTML drag-and-drop enabled.
+/// Resolves dropped DOM files and folders on Windows without intercepting HTML drag-and-drop.
pub fn init() -> tauri::plugin::TauriPlugin<tauri::Wry> {
tauri::plugin::Builder::new("directory-drop")
.on_webview_ready(|_webview| {
@@ -55,6 +55,34 @@ mod windows {
}
}
+ fn file_paths(args: &ICoreWebView2WebMessageReceivedEventArgs) -> Vec<Option<String>> {
+ unsafe {
+ let Ok(args) = args.cast::<ICoreWebView2WebMessageReceivedEventArgs2>() else {
+ return Vec::new();
+ };
+ let Ok(objects) = args.AdditionalObjects() else {
+ return Vec::new();
+ };
+ let mut count = 0;
+ if objects.Count(&mut count).is_err() {
+ return Vec::new();
+ }
+ (0..count)
+ .map(|index| {
+ let file = objects
+ .GetValueAtIndex(index)
+ .ok()?
+ .cast::<ICoreWebView2File>()
+ .ok()?;
+ let mut path = PWSTR::null();
+ file.Path(&mut path).ok()?;
+ let path = take_pwstr(path);
+ std::path::Path::new(&path).is_file().then_some(path)
+ })
+ .collect()
+ }
+ }
+
pub(super) fn attach(webview: tauri::webview::PlatformWebview) -> webview2_core::Result<()> {
// COM callbacks run on the WebView2 UI thread; the webview owns the registered handler.
unsafe {
@@ -73,7 +101,11 @@ mod windows {
else {
return Ok(());
};
- if request.kind != "stirling-folder-drop" || request.request_id.len() > 64 {
+ if !matches!(
+ request.kind.as_str(),
+ "stirling-folder-drop" | "stirling-file-drop"
+ ) || request.request_id.len() > 64
+ {
return Ok(());
}
let mut source = PWSTR::null();
@@ -88,11 +120,19 @@ mod windows {
if !allowed {
return Ok(());
}
- let response = serde_json::json!({
- "type": "stirling-folder-drop-result",
- "requestId": request.request_id,
- "path": directory_path(&args),
- });
+ let response = if request.kind == "stirling-file-drop" {
+ serde_json::json!({
+ "type": "stirling-file-drop-result",
+ "requestId": request.request_id,
+ "paths": file_paths(&args),
+ })
+ } else {
+ serde_json::json!({
+ "type": "stirling-folder-drop-result",
+ "requestId": request.request_id,
+ "path": directory_path(&args),
+ })
+ };
sender.PostWebMessageAsJson(&HSTRING::from(response.to_string()))?;
Ok(())
})),
diff --git a/frontend/editor/src-tauri/src/lib.rs b/frontend/editor/src-tauri/src/lib.rs
index b0794ec7e8..8e410cc084 100644
--- a/frontend/editor/src-tauri/src/lib.rs
+++ b/frontend/editor/src-tauri/src/lib.rs
@@ -216,6 +216,8 @@ pub fn run() {
start_backend,
get_backend_port,
get_opened_files,
+ commands::file_drop::resolve_dropped_file_paths,
+ commands::file_drop::install_drag_capture,
pop_opened_files,
clear_opened_files,
file_disk_state,
diff --git a/frontend/editor/src/cloud/hooks/useWallet.ts b/frontend/editor/src/cloud/hooks/useWallet.ts
index 38b80ac05a..c432917502 100644
--- a/frontend/editor/src/cloud/hooks/useWallet.ts
+++ b/frontend/editor/src/cloud/hooks/useWallet.ts
@@ -259,7 +259,9 @@ export function useWallet(enabled = true): UseWalletResult {
}
try {
- const res = await apiClient.get<Wallet>("/api/v1/payg/wallet");
+ const res = await apiClient.get<Wallet>("/api/v1/payg/wallet", {
+ suppressErrorToast: true,
+ });
if (cancelled || reqId !== latestReqId.current) return;
setWallet((prev) => reuseIfEqual(prev, res.data));
// Fresh data retires any earlier failure, including one a silent poll
diff --git a/frontend/editor/src/core/api/signing.ts b/frontend/editor/src/core/api/signing.ts
index c58fad8aac..d17009d203 100644
--- a/frontend/editor/src/core/api/signing.ts
+++ b/frontend/editor/src/core/api/signing.ts
@@ -9,13 +9,16 @@ export interface SigningSessions {
mySessions: SessionSummary[];
}
-/** The two lists the signing UI always needs together. */
+/** Reads both signing lists without global toasts; the caller owns error reporting. */
export async function fetchSigningSessions(): Promise<SigningSessions> {
const [requests, sessions] = await Promise.all([
apiClient.get<SignRequestSummary[]>(
"/api/v1/security/cert-sign/sign-requests",
+ { suppressErrorToast: true },
),
- apiClient.get<SessionSummary[]>("/api/v1/security/cert-sign/sessions"),
+ apiClient.get<SessionSummary[]>("/api/v1/security/cert-sign/sessions", {
+ suppressErrorToast: true,
+ }),
]);
return { signRequests: requests.data, mySessions: sessions.data };
}
diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
index 939efb222f..ca1d136646 100644
--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx
@@ -34,6 +34,7 @@ import { useOpenFolder } from "@app/components/filesPage/useOpenFolder";
import { useFileActions } from "@app/contexts/file/fileHooks";
import { useAllFiles } from "@app/contexts/FileContext";
import { useFileHandler } from "@app/hooks/useFileHandler";
+import { openFilesFromDisk } from "@app/services/openFilesFromDisk";
import { useServerFolderBlock } from "@app/hooks/useServerFolderBlock";
import {
useNavigationActions,
@@ -959,14 +960,27 @@ export default function FileManagerView() {
[addFiles, currentFolderId, currentTab, folders, moveFilesTo, refresh, t],
);
+ const reportUploadError = useCallback(
+ (err: unknown) =>
+ folders.setError(
+ err instanceof Error
+ ? t("filesPage.error.uploadFilesFailedDetail", {
+ message: err.message,
+ defaultValue: `Could not upload files: ${err.message}`,
+ })
+ : t("filesPage.error.uploadFilesFailed", "Could not upload files."),
+ ),
+ [folders, t],
+ );
+
const onFileInputChange = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const list = Array.from(e.target.files ?? []);
e.target.value = "";
if (list.length === 0) return;
- await handleNativeUpload(list);
+ await handleNativeUpload(list).catch(reportUploadError);
},
- [handleNativeUpload],
+ [handleNativeUpload, reportUploadError],
);
// ─── add to workspace ───────────────────────────────────────────────────
@@ -1090,19 +1104,7 @@ export default function FileManagerView() {
setIsDraggingExternal(false);
const dropped = Array.from(e.dataTransfer?.files ?? []);
if (dropped.length > 0) {
- handleNativeUpload(dropped).catch((err) =>
- folders.setError(
- err instanceof Error
- ? t("filesPage.error.uploadFilesFailedDetail", {
- message: err.message,
- defaultValue: `Could not upload files: ${err.message}`,
- })
- : t(
- "filesPage.error.uploadFilesFailed",
- "Could not upload files.",
- ),
- ),
- );
+ handleNativeUpload(dropped).catch(reportUploadError);
}
};
node.addEventListener("dragenter", onEnter);
@@ -1115,7 +1117,7 @@ export default function FileManagerView() {
node.removeEventListener("dragleave", onLeave);
node.removeEventListener("drop", onDrop);
};
- }, [handleNativeUpload]);
+ }, [handleNativeUpload, reportUploadError]);
// ─── close / exit ───────────────────────────────────────────────────────
const handleClose = useCallback(() => {
@@ -1388,7 +1390,16 @@ export default function FileManagerView() {
// Stable identities, here and for the controls built below: the bar re-registers
// whenever what it was given changes, so a value rebuilt per render turns that into
// an endless register -> render -> register loop.
- const openFilePicker = useCallback(() => fileInputRef.current?.click(), []);
+ const openFilePicker = useCallback(async () => {
+ try {
+ const files = await openFilesFromDisk({
+ onFallbackOpen: () => fileInputRef.current?.click(),
+ });
+ await handleNativeUpload(files);
+ } catch (err) {
+ reportUploadError(err);
+ }
+ }, [handleNativeUpload, reportUploadError]);
const newFolderControl = useMemo(
() => (
@@ -1928,7 +1939,7 @@ export default function FileManagerView() {
// handlers the corner header buttons use so behaviour
// (disabled tooltips, native file picker, dialog) is
// identical regardless of where the user clicks from.
- onEmptyUpload={() => fileInputRef.current?.click()}
+ onEmptyUpload={openFilePicker}
emptyNewFolderControl={
<NewFolderButton
label={t("filesPage.newFolder", "New folder")}
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index 96ad7313c4..64bea49ec1 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -22,6 +22,7 @@ import {
} from "@app/contexts/NavigationContext";
import { useViewer } from "@app/contexts/ViewerContext";
import { useFileHandler } from "@app/hooks/useFileHandler";
+import { openFilesFromDisk } from "@app/services/openFilesFromDisk";
import { useAccountIdentity } from "@app/hooks/useAccountIdentity";
import { useFreeCreditsSummary } from "@app/hooks/useFreeCreditsSummary";
import { useOpenPlan } from "@app/hooks/useOpenPlan";
@@ -801,11 +802,33 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
[ingestFiles],
);
+ const openNativeFilePicker = useCallback(() => {
+ void openFilesFromDisk({
+ onFallbackOpen: () => nativeFileInputRef.current?.click(),
+ })
+ .then(ingestFiles)
+ .catch((err) => {
+ console.error("[FileSidebar] Native file pick failed", err);
+ alert({
+ alertType: "error",
+ title: t("fileSidebar.uploadFailedTitle", "Upload failed"),
+ body:
+ err instanceof Error
+ ? err.message
+ : t(
+ "fileSidebar.uploadFailedBody",
+ "Could not add the selected files.",
+ ),
+ isPersistentPopup: false,
+ });
+ });
+ }, [ingestFiles, t]);
+
useEffect(() => {
if (!onRegisterOpenFromComputer) return;
- onRegisterOpenFromComputer(() => nativeFileInputRef.current?.click());
+ onRegisterOpenFromComputer(openNativeFilePicker);
return () => onRegisterOpenFromComputer(null);
- }, [onRegisterOpenFromComputer]);
+ }, [onRegisterOpenFromComputer, openNativeFilePicker]);
// Native OS file drop onto the sidebar - mirrors the workbench drop zone.
// Only react to OS file drags ("Files" type); internal element drags (e.g.
@@ -1105,7 +1128,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
variant="quiet"
className="file-sidebar-section-btn file-sidebar-section-btn-add"
data-testid="pdf-library-add-files"
- onClick={() => nativeFileInputRef.current?.click()}
+ onClick={openNativeFilePicker}
title={t("fileSidebar.addFiles", "Add files")}
aria-label={t("fileSidebar.addFiles", "Add files")}
>
diff --git a/frontend/editor/src/core/contexts/file/fileActions.ts b/frontend/editor/src/core/contexts/file/fileActions.ts
index 4744758b84..55a0ca9d96 100644
--- a/frontend/editor/src/core/contexts/file/fileActions.ts
+++ b/frontend/editor/src/core/contexts/file/fileActions.ts
@@ -512,7 +512,7 @@ export async function addFiles(
}
}
- Object.assign(fileStub, await sourceLinkForNewFile(quickKey));
+ Object.assign(fileStub, await sourceLinkForNewFile(file));
// Store insertion position if provided
if (options.insertAfterPageId !== undefined) {
diff --git a/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts b/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts
index 6eeac53b9c..3db0decfc1 100644
--- a/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts
+++ b/frontend/editor/src/core/contexts/file/storedFileReconciler.test.ts
@@ -37,6 +37,8 @@ describe("reconciling a record with no source", () => {
});
it("leaves a newly added file unlinked", async () => {
- await expect(sourceLinkForNewFile("k")).resolves.toEqual({});
+ await expect(
+ sourceLinkForNewFile(new File(["pdf"], "a.pdf")),
+ ).resolves.toEqual({});
});
});
diff --git a/frontend/editor/src/core/contexts/file/storedFileReconciler.ts b/frontend/editor/src/core/contexts/file/storedFileReconciler.ts
index 845bdcc802..ba6aec7064 100644
--- a/frontend/editor/src/core/contexts/file/storedFileReconciler.ts
+++ b/frontend/editor/src/core/contexts/file/storedFileReconciler.ts
@@ -52,11 +52,10 @@ export function inheritedSourceLink(
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. */
+/** Fields recording the source a newly added file was read from.
+ * Empty where files have no source outside the app. */
export async function sourceLinkForNewFile(
- _quickKey: string,
+ _file: File,
): Promise<Partial<StirlingFileStub>> {
return {};
}
diff --git a/frontend/editor/src/core/services/fileDialogService.ts b/frontend/editor/src/core/services/fileDialogService.ts
index 9dbcc79a53..bda3ca1ab5 100644
--- a/frontend/editor/src/core/services/fileDialogService.ts
+++ b/frontend/editor/src/core/services/fileDialogService.ts
@@ -15,6 +15,9 @@ export interface FileDialogOptions {
}>;
}
+/** Whether cancelling the picker should finish instead of opening a browser fallback. */
+export const hasNativeFileDialog = false;
+
/**
* Open native file dialog and read selected files
* Core stub - returns empty array (no native dialog in web)
diff --git a/frontend/editor/src/core/services/notifications.ts b/frontend/editor/src/core/services/notifications.ts
index 0f7bf44a10..70d86e676f 100644
--- a/frontend/editor/src/core/services/notifications.ts
+++ b/frontend/editor/src/core/services/notifications.ts
@@ -72,6 +72,7 @@ export async function fetchNotifications(
try {
const response = await apiClient.get<NotificationsResponse>(
`${NOTIFICATIONS_PATH}?limit=${limit}`,
+ { suppressErrorToast: true },
);
return {
notifications: response?.data?.notifications ?? [],
@@ -90,6 +91,8 @@ export async function reportNotificationResolved(
try {
await apiClient.post(
`${NOTIFICATIONS_PATH}/${encodeURIComponent(notificationId)}/resolved`,
+ undefined,
+ { suppressErrorToast: true },
);
return true;
} catch {
diff --git a/frontend/editor/src/core/services/openFilesFromDisk.ts b/frontend/editor/src/core/services/openFilesFromDisk.ts
index c1536da0de..ea455d2394 100644
--- a/frontend/editor/src/core/services/openFilesFromDisk.ts
+++ b/frontend/editor/src/core/services/openFilesFromDisk.ts
@@ -1,4 +1,7 @@
-import { openFileDialog } from "@app/services/fileDialogService";
+import {
+ hasNativeFileDialog,
+ openFileDialog,
+} from "@app/services/fileDialogService";
import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
import { getDocumentFileDialogFilter } from "@app/utils/fileDialogUtils";
@@ -20,12 +23,12 @@ export async function openFilesFromDisk(
});
if (filesWithPaths.length > 0) {
- for (const { quickKey, path } of filesWithPaths) {
- pendingFilePathMappings.set(quickKey, path);
+ for (const { file, path } of filesWithPaths) {
+ pendingFilePathMappings.set(file, path);
}
return filesWithPaths.map((entry) => entry.file);
}
- options.onFallbackOpen?.();
+ if (!hasNativeFileDialog) options.onFallbackOpen?.();
return [];
}
diff --git a/frontend/editor/src/core/services/pendingFilePathMappings.ts b/frontend/editor/src/core/services/pendingFilePathMappings.ts
index d123ebe2b6..9c8a6fa8d2 100644
--- a/frontend/editor/src/core/services/pendingFilePathMappings.ts
+++ b/frontend/editor/src/core/services/pendingFilePathMappings.ts
@@ -1,3 +1,5 @@
-// Module-level storage for file path mappings (quickKey -> localFilePath)
-// Used to pass file paths from Tauri file dialog to FileManagerContext
-export const pendingFilePathMappings = new Map<string, string>();
+/** Import provenance follows the File instance: metadata keys can collide across folders. */
+export const pendingFilePathMappings = new WeakMap<
+ File,
+ string | Promise<string | undefined>
+>();
diff --git a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
index 5d94211f67..648cecb496 100644
--- a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
+++ b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
@@ -69,9 +69,27 @@ export async function installTauri(page: Page) {
return id;
},
unregisterListener() {},
- async invoke(cmd: string, args: any = {}) {
+ async invoke(cmd: string, args: any = {}, options: any = {}) {
w.__invoked.push(cmd);
switch (cmd) {
+ case "plugin:dialog|open":
+ return w.__pickedPaths ?? null;
+ case "plugin:dialog|save":
+ throw new Error(
+ "Unexpected Save As: the imported file must keep its disk path",
+ );
+ case "resolve_dropped_file_paths":
+ return w.__droppedPaths ?? [];
+ case "plugin:fs|write_file": {
+ const path = decodeURIComponent(options.headers.path);
+ w.__writtenPaths = [...(w.__writtenPaths ?? []), path];
+ w.__disk[path] = {
+ bytes: Array.from(args),
+ modifiedMs: Date.now(),
+ };
+ w.__saveDisk();
+ return null;
+ }
case "file_disk_state":
return stat(args.path);
case "plugin:fs|read_file": {
@@ -126,7 +144,11 @@ export async function installTauri(page: Page) {
case "get_backend_port":
return 8080;
- case "pop_opened_files":
+ case "pop_opened_files": {
+ const paths = w.__openedPaths ?? [];
+ w.__openedPaths = [];
+ return paths;
+ }
case "get_opened_files":
case "pop_window_file_ids":
return [];
diff --git a/frontend/editor/src/core/tests/stubbed/disk-link-imports.spec.ts b/frontend/editor/src/core/tests/stubbed/disk-link-imports.spec.ts
new file mode 100644
index 0000000000..d23eeb4de9
--- /dev/null
+++ b/frontend/editor/src/core/tests/stubbed/disk-link-imports.spec.ts
@@ -0,0 +1,140 @@
+import fs from "node:fs";
+import path from "node:path";
+import type { Page } from "@playwright/test";
+import { test, expect } from "@app/tests/helpers/stub-test-base";
+import {
+ installTauri,
+ dismissModals,
+ setDisk,
+} from "@app/tests/helpers/tauriDiskStub";
+
+const PATH = "C:/Docs/report.pdf";
+const BYTES = Array.from(
+ fs.readFileSync(
+ path.resolve("src/core/tests/test-fixtures/annotation-text-sample.pdf"),
+ ),
+);
+const MTIME = 1_700_000_000_000;
+
+test.use({ autoGoto: false });
+
+async function storedLinks(page: Page) {
+ return page.evaluate(
+ () =>
+ new Promise<unknown[]>((resolve, reject) => {
+ const request = indexedDB.open("stirling-pdf-files");
+ request.onsuccess = () => {
+ const db = request.result;
+ if (!db.objectStoreNames.contains("files")) {
+ db.close();
+ resolve([]);
+ return;
+ }
+ const read = db.transaction("files").objectStore("files").getAll();
+ read.onsuccess = () => {
+ resolve(
+ read.result.map(({ name, localFilePath, diskSyncedSize }) => ({
+ name,
+ localFilePath,
+ diskSyncedSize,
+ })),
+ );
+ db.close();
+ };
+ read.onerror = () => {
+ db.close();
+ reject(read.error);
+ };
+ };
+ request.onerror = () => reject(request.error);
+ }),
+ );
+}
+
+async function expectLinked(page: Page) {
+ await expect
+ .poll(() => storedLinks(page))
+ .toEqual([
+ { name: "report.pdf", localFilePath: PATH, diskSyncedSize: BYTES.length },
+ ]);
+}
+
+test.beforeEach(async ({ page }) => {
+ await installTauri(page);
+ await page.goto("/editor");
+ await dismissModals(page);
+ await setDisk(page, { [PATH]: { bytes: BYTES, modifiedMs: MTIME } });
+ await page.evaluate((path) => {
+ Object.assign(window, { __pickedPaths: [path], __droppedPaths: [path] });
+ }, PATH);
+});
+
+test("the sidebar native picker keeps its path after reload and saves in place", async ({
+ page,
+}) => {
+ await page.getByTestId("files-button").click();
+ await expectLinked(page);
+ await expect(page.locator(".file-sidebar-file-item")).toHaveCount(1);
+ await page.reload();
+ await dismissModals(page);
+ await expectLinked(page);
+ await expect(page.locator(".file-sidebar-file-item")).toHaveCount(1);
+ await page.locator(".file-sidebar-file-item").click();
+ await expect(page.locator('[data-page-index="0"]').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ await page.keyboard.press("Control+s");
+ await expect
+ .poll(() => page.evaluate(() => Reflect.get(window, "__writtenPaths")))
+ .toEqual([PATH]);
+});
+
+test("the Files page upload uses the native picker", async ({ page }) => {
+ await page.getByTestId("my-files-button").click();
+ await page
+ .getByRole("button", { name: "Upload files", exact: true })
+ .first()
+ .click();
+ await expectLinked(page);
+});
+
+test("the sidebar add button uses the native picker", async ({ page }) => {
+ await page.getByTestId("pdf-library-add-files").click();
+ await expectLinked(page);
+});
+
+test("a Finder-open event stores the link during import", async ({ page }) => {
+ await page.evaluate((path) => {
+ Reflect.set(window, "__openedPaths", [path]);
+ const callbacks = Reflect.get(window, "__callbacks");
+ const listeners = Reflect.get(window, "__listeners");
+ callbacks[listeners["files-changed"]]({
+ event: "files-changed",
+ payload: null,
+ });
+ }, PATH);
+ await expectLinked(page);
+});
+
+test("an HTML file drop imports the native path", async ({ page }) => {
+ await page.locator(".file-sidebar").evaluate(
+ (node, { bytes, mtime }) => {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.items.add(
+ new File([new Uint8Array(bytes)], "report.pdf", {
+ type: "application/pdf",
+ lastModified: mtime,
+ }),
+ );
+ node.dispatchEvent(
+ new DragEvent("drop", {
+ bubbles: true,
+ cancelable: true,
+ dataTransfer,
+ }),
+ );
+ },
+ { bytes: BYTES, mtime: MTIME },
+ );
+ await expectLinked(page);
+});
diff --git a/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.ts b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.ts
new file mode 100644
index 0000000000..f561303ec3
--- /dev/null
+++ b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.test.ts
@@ -0,0 +1,79 @@
+import { act, renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useNotificationsAvailable } from "@app/components/notifications/useNotificationsAvailable";
+import {
+ connectionModeService,
+ type ConnectionConfig,
+ type ConnectionMode,
+} from "@app/services/connectionModeService";
+
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCurrentMode: vi.fn(),
+ subscribeToModeChanges: vi.fn(),
+ },
+}));
+
+describe("desktop notification availability", () => {
+ let notify: (cfg: ConnectionConfig) => void;
+ const unsubscribe = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(connectionModeService.subscribeToModeChanges).mockImplementation(
+ (listener) => {
+ notify = listener;
+ return unsubscribe;
+ },
+ );
+ });
+
+ it.each(["local", "saas", "selfhosted"] as const)(
+ "waits for the mode, then enables notifications only for a server (%s)",
+ async (mode) => {
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(mode);
+ const { result, unmount } = renderHook(() => useNotificationsAvailable());
+ expect(result.current).toBe(false);
+ await act(async () => {});
+ expect(result.current).toBe(mode !== "local");
+ unmount();
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("a late initial mode cannot restart polling after switching to local", async () => {
+ let resolveMode: (mode: ConnectionMode) => void = () => {};
+ vi.mocked(connectionModeService.getCurrentMode).mockReturnValue(
+ new Promise((resolve) => {
+ resolveMode = resolve;
+ }),
+ );
+ const { result } = renderHook(() => useNotificationsAvailable());
+ await act(async () => {
+ notify({
+ mode: "local",
+ server_config: null,
+ lock_connection_mode: false,
+ });
+ resolveMode("saas");
+ });
+ expect(result.current).toBe(false);
+
+ await act(async () => {
+ notify({
+ mode: "saas",
+ server_config: null,
+ lock_connection_mode: false,
+ });
+ });
+ expect(result.current).toBe(true);
+ await act(async () => {
+ notify({
+ mode: "local",
+ server_config: null,
+ lock_connection_mode: false,
+ });
+ });
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.ts b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.ts
new file mode 100644
index 0000000000..9ecc2c30cb
--- /dev/null
+++ b/frontend/editor/src/desktop/components/notifications/useNotificationsAvailable.ts
@@ -0,0 +1,24 @@
+import { useEffect, useState } from "react";
+import { connectionModeService } from "@app/services/connectionModeService";
+
+/** The bundled backend has no notification API; wait for the mode before polling. */
+export function useNotificationsAvailable(): boolean {
+ const [available, setAvailable] = useState(false);
+
+ useEffect(() => {
+ let current = true;
+ void connectionModeService.getCurrentMode().then((mode) => {
+ if (current) setAvailable(mode !== "local");
+ });
+ const unsubscribe = connectionModeService.subscribeToModeChanges((cfg) => {
+ current = false;
+ setAvailable(cfg.mode !== "local");
+ });
+ return () => {
+ current = false;
+ unsubscribe();
+ };
+ }, []);
+
+ return available;
+}
diff --git a/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts
index 811268c8e6..2dd5f3c282 100644
--- a/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts
+++ b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.test.ts
@@ -28,6 +28,7 @@ import {
} from "@app/contexts/file/storedFileReconciler";
const PATH = "C:/docs/report.pdf";
+let file: File;
const stub = (over: Partial<StirlingFileStub> = {}): StirlingFileStub =>
({
@@ -43,7 +44,7 @@ const stub = (over: Partial<StirlingFileStub> = {}): StirlingFileStub =>
beforeEach(() => {
vi.clearAllMocks();
- pendingFilePathMappings.clear();
+ file = new File(["pdf"], "report.pdf", { lastModified: 5000 });
getDiskFileState.mockResolvedValue({
availability: "present",
size: 100,
@@ -99,29 +100,29 @@ describe("inheritedSourceLink", () => {
describe("sourceLinkForNewFile", () => {
it("links a file the open dialog registered, and baselines it", async () => {
- pendingFilePathMappings.set("k", PATH);
- await expect(sourceLinkForNewFile("k")).resolves.toEqual({
+ pendingFilePathMappings.set(file, PATH);
+ await expect(sourceLinkForNewFile(file)).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);
+ const copy = new File(["pdf"], "report.pdf", { lastModified: 5000 });
+ await expect(sourceLinkForNewFile(copy)).resolves.toEqual({});
});
it("links without a baseline when disk cannot be read right now", async () => {
- pendingFilePathMappings.set("k", PATH);
+ pendingFilePathMappings.set(file, PATH);
getDiskFileState.mockResolvedValue({
availability: "unavailable",
reason: "permission",
});
- await expect(sourceLinkForNewFile("k")).resolves.toEqual({
+ await expect(sourceLinkForNewFile(file)).resolves.toEqual({
localFilePath: PATH,
});
});
it("leaves a file that came from nowhere unlinked", async () => {
- await expect(sourceLinkForNewFile("unknown")).resolves.toEqual({});
+ await expect(sourceLinkForNewFile(file)).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
index fa48a50ab8..089bdbbac4 100644
--- a/frontend/editor/src/desktop/contexts/file/storedFileReconciler.ts
+++ b/frontend/editor/src/desktop/contexts/file/storedFileReconciler.ts
@@ -21,7 +21,7 @@ import {
getDiskFileState,
type PresentDiskFileState,
} from "@app/services/desktopFileLink";
-import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
+import { sourcePathForFile } from "@app/services/fileImportPaths";
import { isPristineLocalPassthrough } from "@app/services/pruneMissingRecentFiles";
import {
cancelDiskConflict,
@@ -115,11 +115,10 @@ export function inheritedSourceLink(
}
export async function sourceLinkForNewFile(
- quickKey: string,
+ file: File,
): Promise<Partial<StirlingFileStub>> {
- const localFilePath = pendingFilePathMappings.get(quickKey);
+ const localFilePath = await sourcePathForFile(file);
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);
diff --git a/frontend/editor/src/desktop/hooks/useAppInitialization.ts b/frontend/editor/src/desktop/hooks/useAppInitialization.ts
index b5df4e26ff..0f2f97b3b0 100644
--- a/frontend/editor/src/desktop/hooks/useAppInitialization.ts
+++ b/frontend/editor/src/desktop/hooks/useAppInitialization.ts
@@ -1,9 +1,10 @@
import { useEffect, useState } from "react";
+import { invoke } from "@tauri-apps/api/core";
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";
+import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
+import { captureDroppedFilePaths } from "@app/services/fileImportPaths";
/**
* App initialization hook
@@ -12,8 +13,15 @@ import { getDiskFileState } from "@app/services/desktopFileLink";
* - Handles files opened with the app (adds directly to FileContext)
*/
export function useAppInitialization(): void {
+ useEffect(captureDroppedFilePaths, []);
+ // macOS captures dropped paths via a native swizzle installed against the live
+ // webview; no-op on other platforms.
+ useEffect(() => {
+ void invoke("install_drag_capture").catch(() => {});
+ }, []);
+
// Get file management actions
- const { addFiles, updateStirlingFileStub } = useFileManagement();
+ const { addFiles } = useFileManagement();
// Handle files opened with app (Tauri mode)
const {
@@ -51,12 +59,8 @@ export function useAppInitialization(): void {
);
console.log("[Desktop] Loaded file:", fileData.fileName);
-
- return {
- file,
- filePath,
- quickKey: createQuickKey(file),
- };
+ pendingFilePathMappings.set(file, filePath);
+ return file;
} catch (error) {
console.error(
"[Desktop] Failed to load file:",
@@ -67,38 +71,10 @@ export function useAppInitialization(): void {
}
}),
)
- ).filter(
- (
- entry,
- ): entry is { file: File; filePath: string; quickKey: string } =>
- Boolean(entry),
- );
+ ).filter((file): file is File => Boolean(file));
if (loadedFiles.length > 0) {
- const filesArray = loadedFiles.map((entry) => entry.file);
- const quickKeyToPath = new Map(
- loadedFiles.map((entry) => [entry.quickKey, entry.filePath]),
- );
-
- const addedFiles = await addFiles(filesArray, { selectFiles: true });
- // 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,
- }
- : {}),
- });
- }),
- );
+ await addFiles(loadedFiles, { selectFiles: true });
console.log(
`[Desktop] ${loadedFiles.length} opened file(s) added to FileContext`,
@@ -110,13 +86,7 @@ export function useAppInitialization(): void {
};
loadOpenedFiles();
- }, [
- openedFilePaths,
- openedFileLoading,
- addFiles,
- updateStirlingFileStub,
- consumeOpenedFilePaths,
- ]);
+ }, [openedFilePaths, openedFileLoading, addFiles, consumeOpenedFilePaths]);
}
export function useSetupCompletion(): (completed: boolean) => void {
diff --git a/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.test.ts b/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.test.ts
index e85806c3c8..473674dab9 100644
--- a/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.test.ts
+++ b/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.test.ts
@@ -59,4 +59,24 @@ describe("useConfirmedSaaSMode", () => {
await act(async () => notify?.({ mode: "saas" }));
expect(result.current).toBe(true);
});
+
+ it("ignores a stale initial SaaS read after switching to local", async () => {
+ let resolveMode: (mode: string) => void = () => {};
+ getCurrentModeMock.mockReturnValue(
+ new Promise<string>((resolve) => {
+ resolveMode = resolve;
+ }),
+ );
+ let notify: (cfg: { mode: string }) => void = () => {};
+ subscribeToModeChangesMock.mockImplementation((listener) => {
+ notify = listener;
+ return () => {};
+ });
+ const { result } = renderHook(() => useConfirmedSaaSMode());
+ await act(async () => {
+ notify({ mode: "local" });
+ resolveMode("saas");
+ });
+ expect(result.current).toBe(false);
+ });
});
diff --git a/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts b/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts
index bdff432824..4a67ec4023 100644
--- a/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts
+++ b/frontend/editor/src/desktop/hooks/useConfirmedSaaSMode.ts
@@ -18,12 +18,18 @@ export function useConfirmedSaaSMode(): boolean {
const [isSaaSMode, setIsSaaSMode] = useState(false);
useEffect(() => {
- void connectionModeService
- .getCurrentMode()
- .then((mode) => setIsSaaSMode(mode === "saas"));
- return connectionModeService.subscribeToModeChanges((cfg) =>
- setIsSaaSMode(cfg.mode === "saas"),
- );
+ let current = true;
+ void connectionModeService.getCurrentMode().then((mode) => {
+ if (current) setIsSaaSMode(mode === "saas");
+ });
+ const unsubscribe = connectionModeService.subscribeToModeChanges((cfg) => {
+ current = false;
+ setIsSaaSMode(cfg.mode === "saas");
+ });
+ return () => {
+ current = false;
+ unsubscribe();
+ };
}, []);
return isSaaSMode;
diff --git a/frontend/editor/src/desktop/hooks/useWallet.ts b/frontend/editor/src/desktop/hooks/useWallet.ts
index 10f8ea101c..767470b3ef 100644
--- a/frontend/editor/src/desktop/hooks/useWallet.ts
+++ b/frontend/editor/src/desktop/hooks/useWallet.ts
@@ -1,5 +1,5 @@
import { useWallet as useCloudWallet } from "@cloud/hooks/useWallet";
-import { useSaaSMode } from "@app/hooks/useSaaSMode";
+import { useConfirmedSaaSMode } from "@app/hooks/useConfirmedSaaSMode";
export type {
UseWalletResult,
@@ -13,6 +13,6 @@ export type {
/** Local and self-hosted backends do not provide cloud billing. */
export function useWallet(enabled = true) {
- const saasMode = useSaaSMode();
+ const saasMode = useConfirmedSaaSMode();
return useCloudWallet(enabled && saasMode);
}
diff --git a/frontend/editor/src/desktop/services/apiClientSetup.test.ts b/frontend/editor/src/desktop/services/apiClientSetup.test.ts
index 66f8abbd88..79816f24b3 100644
--- a/frontend/editor/src/desktop/services/apiClientSetup.test.ts
+++ b/frontend/editor/src/desktop/services/apiClientSetup.test.ts
@@ -136,7 +136,7 @@ describe("desktop apiClientSetup - 403 handling", () => {
expect(alert).not.toHaveBeenCalled();
});
- test("a 403 from the local backend still surfaces", async () => {
+ test("leaves permission toasts to the HTTP error handler", async () => {
const { client, handlers } = makeMockClient();
setupApiInterceptors(client as unknown as AxiosInstance);
@@ -145,7 +145,7 @@ describe("desktop apiClientSetup - 403 handling", () => {
config: { url: "/api/v1/general/merge-pdfs" },
});
- expect(alert).toHaveBeenCalledTimes(1);
+ expect(alert).not.toHaveBeenCalled();
});
});
diff --git a/frontend/editor/src/desktop/services/apiClientSetup.ts b/frontend/editor/src/desktop/services/apiClientSetup.ts
index 5670210e77..b8693764ff 100644
--- a/frontend/editor/src/desktop/services/apiClientSetup.ts
+++ b/frontend/editor/src/desktop/services/apiClientSetup.ts
@@ -270,23 +270,6 @@ export function setupApiInterceptors(client: AxiosInstance): void {
);
}
- // Handle 403 Forbidden - unauthorized access. Skipped only where the caller opted
- // out per request: a fire-and-forget refusal is a normal answer, not news.
- if (
- error.response?.status === 403 &&
- !originalRequest.suppressErrorToast
- ) {
- alert({
- alertType: "error",
- title: i18n.t("auth.accessDenied", "Access Denied"),
- body: i18n.t(
- "auth.insufficientPermissions",
- "You do not have permission to perform this action.",
- ),
- isPersistentPopup: false,
- });
- }
-
return Promise.reject(error);
},
);
diff --git a/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts b/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts
new file mode 100644
index 0000000000..2a8feba9fb
--- /dev/null
+++ b/frontend/editor/src/desktop/services/backgroundRequestErrors.test.ts
@@ -0,0 +1,188 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { fetch } from "@tauri-apps/plugin-http";
+import apiClient from "@app/services/apiClient";
+import {
+ fetchNotifications,
+ reportNotificationResolved,
+} from "@app/services/notifications";
+import { fetchSigningSessions } from "@app/api/signing";
+import {
+ fetchMountedFiles,
+ fetchProcessingFolderRuns,
+} from "@app/services/processingFolderApi";
+import { alert } from "@app/components/toast";
+import { operationRouter } from "@app/services/operationRouter";
+import { allowConsole } from "@app/tests/failOnConsole";
+import { useWallet } from "@app/hooks/useWallet";
+import { connectionModeService } from "@app/services/connectionModeService";
+
+vi.mock("@tauri-apps/plugin-http", () => ({ fetch: vi.fn() }));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+vi.mock("@app/services/apiClientConfig", () => ({ getApiBaseUrl: () => "" }));
+vi.mock("@app/services/tauriLocalProxy", () => ({
+ shouldUseFastLocalTransport: () => false,
+}));
+vi.mock("@app/services/localFolderContents", () => ({ readDiskFile: vi.fn() }));
+vi.mock("@app/services/billing", () => ({ createPortalSession: vi.fn() }));
+vi.mock("@app/platform/openExternal", () => ({ openExternal: vi.fn() }));
+vi.mock("@app/hooks/walletDevPreview", () => ({
+ getWalletDevPreview: () => null,
+}));
+vi.mock("@app/auth/session", () => ({
+ getAccessToken: async () => "test-token",
+}));
+vi.mock("@app/services/authService", () => ({
+ authService: {
+ awaitRefreshIfInProgress: async () => {},
+ },
+}));
+vi.mock("@app/services/connectionModeService", () => ({
+ connectionModeService: {
+ getCurrentMode: vi.fn(),
+ subscribeToModeChanges: vi.fn(() => () => {}),
+ },
+}));
+vi.mock("@app/services/tauriBackendService", () => ({
+ tauriBackendService: {
+ isOnline: true,
+ getBackendStatus: () => "healthy",
+ getBackendPort: () => 8080,
+ },
+}));
+vi.mock("@app/services/operationRouter", () => ({
+ operationRouter: {
+ isSelfHostedMode: async () => false,
+ isSaaSMode: async () => true,
+ getBaseUrl: vi.fn(),
+ shouldSkipBackendReadyCheck: async () => true,
+ },
+}));
+vi.mock("@app/constants/connection", () => ({
+ STIRLING_SAAS_URL: "https://saas.test",
+ STIRLING_SAAS_BACKEND_API_URL: "https://api.saas.test",
+}));
+vi.mock("@app/i18n", () => ({
+ default: { t: (_key: string, fallback: string) => fallback },
+}));
+
+function failRequest(status: number): void {
+ vi.mocked(fetch).mockImplementation(
+ async () =>
+ new Response(JSON.stringify({ message: "Server unavailable" }), {
+ status,
+ }),
+ );
+}
+
+describe("desktop background requests through the HTTP interceptors", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(operationRouter.getBaseUrl).mockResolvedValue(
+ "https://api.saas.test",
+ );
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue("saas");
+ allowConsole.error(/\[TauriHttpClient\]/);
+ allowConsole.error(/\[saasErrorInterceptor\]/);
+ });
+ afterEach(() => vi.useRealTimers());
+
+ it.each(["local", "selfhosted"] as const)(
+ "does not fetch or poll the cloud wallet in %s mode",
+ async (mode) => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ vi.mocked(connectionModeService.getCurrentMode).mockResolvedValue(mode);
+ const { result } = renderHook(() => useWallet());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(90_000);
+ });
+ expect(fetch).not.toHaveBeenCalled();
+ expect(result.current.wallet).toBeNull();
+ expect(result.current.loading).toBe(false);
+ },
+ );
+
+ it("wallet polling exposes the load error without repeated global toasts", async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ allowConsole.warn(/\[useWallet\] fetch failed/);
+ failRequest(500);
+ const { result } = renderHook(() => useWallet());
+ await waitFor(() => expect(result.current.error).not.toBeNull());
+ const initialRequests = vi.mocked(fetch).mock.calls.length;
+ for (let poll = 0; poll < 3; poll++) {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+ }
+ expect(fetch).toHaveBeenCalledTimes(initialRequests + 3);
+ expect(alert).not.toHaveBeenCalled();
+ });
+
+ it.each([403, 404, 500])(
+ "notification polling and resolution stay quiet on HTTP %s",
+ async (status) => {
+ failRequest(status);
+
+ for (let poll = 0; poll < 3; poll++) {
+ expect((await fetchNotifications()).notifications).toEqual([]);
+ }
+ expect(await reportNotificationResolved("failure:123")).toBe(false);
+
+ expect(fetch).toHaveBeenCalledTimes(4);
+ expect(alert).not.toHaveBeenCalled();
+ },
+ );
+
+ it("lets the signing hook report a failure without per-request toasts", async () => {
+ failRequest(500);
+ await expect(fetchSigningSessions()).rejects.toMatchObject({
+ response: { status: 500 },
+ });
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(alert).not.toHaveBeenCalled();
+ });
+
+ it("notification polls stay quiet when the server cannot be reached", async () => {
+ vi.mocked(fetch).mockRejectedValue(new TypeError("Failed to fetch"));
+ await fetchNotifications();
+ await fetchNotifications();
+ expect(alert).not.toHaveBeenCalled();
+ });
+
+ it("processing-folder progress polls reject without a toast", async () => {
+ failRequest(503);
+ for (const poll of [fetchMountedFiles, fetchProcessingFolderRuns]) {
+ await expect(poll("folder-1")).rejects.toMatchObject({
+ response: { status: 503 },
+ });
+ }
+ expect(alert).not.toHaveBeenCalled();
+ });
+
+ it.each(["http://127.0.0.1:8080", "https://api.saas.test"])(
+ "a user action refused by %s produces one permission toast",
+ async (baseUrl) => {
+ vi.mocked(operationRouter.getBaseUrl).mockResolvedValue(baseUrl);
+ failRequest(403);
+ await expect(
+ apiClient.post("/api/v1/general/merge-pdfs"),
+ ).rejects.toMatchObject({
+ response: { status: 403 },
+ });
+ expect(alert).toHaveBeenCalledTimes(1);
+ expect(alert).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Access Denied" }),
+ );
+ },
+ );
+
+ it("still reports a failed user-requested operation", async () => {
+ failRequest(500);
+ await expect(
+ apiClient.post("/api/v1/general/merge-pdfs"),
+ ).rejects.toMatchObject({
+ response: { status: 500 },
+ });
+ expect(alert).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/editor/src/desktop/services/fileDialogService.ts b/frontend/editor/src/desktop/services/fileDialogService.ts
index 67a4fb13c3..2e579707fd 100644
--- a/frontend/editor/src/desktop/services/fileDialogService.ts
+++ b/frontend/editor/src/desktop/services/fileDialogService.ts
@@ -8,6 +8,9 @@ import { getDocumentFileDialogFilter } from "@app/utils/fileDialogUtils";
export type { FileWithPath, FileDialogOptions };
+/** Whether cancelling the picker should finish instead of opening a browser fallback. */
+export const hasNativeFileDialog = true;
+
/**
* Open native file dialog and read selected files (Desktop/Tauri only)
*/
diff --git a/frontend/editor/src/desktop/services/fileImportPaths.test.ts b/frontend/editor/src/desktop/services/fileImportPaths.test.ts
new file mode 100644
index 0000000000..0487a4bffc
--- /dev/null
+++ b/frontend/editor/src/desktop/services/fileImportPaths.test.ts
@@ -0,0 +1,235 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { FileContextState, FileId } from "@app/types/fileContext";
+
+const { invoke, open, readFile, storeStirlingFile } = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ open: vi.fn(),
+ readFile: vi.fn(),
+ storeStirlingFile: vi.fn(),
+}));
+vi.mock("@tauri-apps/api/core", () => ({ invoke, isTauri: () => true }));
+vi.mock("@tauri-apps/plugin-dialog", () => ({ open }));
+vi.mock("@tauri-apps/plugin-fs", () => ({ readFile }));
+vi.mock("@app/services/localFolderStorage", () => ({
+ directoryKey: (path: string) => path,
+ localFolderStorage: {
+ getAllFolders: async () => [{ directory: "/Downloads" }],
+ },
+}));
+vi.mock("@core/services/localFolderStorage", () => ({
+ directoryKey: (path: string) => path,
+ localFolderStorage: {
+ getAllFolders: async () => [{ directory: "/Downloads" }],
+ },
+}));
+vi.mock("@app/services/fileStorage", () => ({
+ fileStorage: { storeStirlingFile, updateThumbnail: vi.fn() },
+}));
+vi.mock("@app/utils/thumbnailUtils", () => ({
+ generateThumbnailPairWithMetadata: vi.fn(),
+}));
+vi.mock("@app/services/fileAnalyzer", () => ({
+ FileAnalyzer: { isPDFUserPasswordProtected: async () => false },
+}));
+vi.mock("@app/components/toast", () => ({ alert: vi.fn() }));
+
+import { addFiles } from "@app/contexts/file/fileActions";
+import { openFilesFromDisk } from "@app/services/openFilesFromDisk";
+import { readDiskFile } from "@app/services/localFolderContents";
+import { captureDroppedFilePaths } from "@app/services/fileImportPaths";
+
+const PATH = "/Downloads/report.pdf";
+const BYTES = new Uint8Array([37, 80, 68, 70]);
+let stopCapturingDrops: () => void;
+
+function dropFiles(files: File[]) {
+ const event = new Event("drop", { bubbles: true });
+ Object.defineProperty(event, "dataTransfer", { value: { files } });
+ document.dispatchEvent(event);
+}
+
+async function importFiles(files: File[]) {
+ const state = {
+ files: { ids: [], byId: {} },
+ pinnedFiles: new Set(),
+ ui: { selectedFileIds: [], selectedPageNumbers: [] },
+ } as unknown as FileContextState;
+ const dispatch = vi.fn();
+ await addFiles(
+ {
+ files,
+ skipMetadataHydration: true,
+ skipUploadTracking: true,
+ skipWorkspaceDispatch: true,
+ },
+ { current: state },
+ { current: new Map<FileId, File>() },
+ dispatch,
+ {} as never,
+ true,
+ );
+ return storeStirlingFile.mock.calls.map(([, stub]) => stub);
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ stopCapturingDrops = captureDroppedFilePaths();
+ open.mockResolvedValue([PATH]);
+ readFile.mockResolvedValue(BYTES);
+ storeStirlingFile.mockResolvedValue(undefined);
+ invoke.mockImplementation(async (command: string) => {
+ if (command === "resolve_dropped_file_paths") return [PATH];
+ if (command === "file_disk_state")
+ return { availability: "present", size: BYTES.length, modifiedMs: 5000 };
+ throw new Error(`Unexpected command: ${command}`);
+ });
+});
+
+afterEach(() => {
+ stopCapturingDrops();
+ vi.unstubAllGlobals();
+});
+
+describe("desktop imports retain a save target on the initial stored record", () => {
+ it("persists a native picker selection with its path and baseline", async () => {
+ const files = await openFilesFromDisk();
+ expect(await importFiles(files)).toEqual([
+ expect.objectContaining({
+ localFilePath: PATH,
+ diskSyncedSize: BYTES.length,
+ diskSyncedModifiedMs: 5000,
+ }),
+ ]);
+ });
+
+ it("keeps the mounted-folder path during an unopened magic-trick import", async () => {
+ const file = await readDiskFile({
+ path: PATH,
+ name: "report.pdf",
+ sizeBytes: BYTES.length,
+ lastModified: 5000,
+ });
+ expect(file).not.toBeNull();
+ expect(await importFiles([file!])).toEqual([
+ expect.objectContaining({
+ localFilePath: PATH,
+ diskSyncedModifiedMs: 5000,
+ }),
+ ]);
+ });
+
+ it("persists the resolved path of a dropped file", async () => {
+ const file = new File([BYTES], "report.pdf", {
+ type: "application/pdf",
+ lastModified: 5000,
+ });
+ dropFiles([file]);
+ expect(await importFiles([file])).toEqual([
+ expect.objectContaining({ localFilePath: PATH }),
+ ]);
+ expect(invoke).toHaveBeenCalledWith("resolve_dropped_file_paths", {
+ files: [{ name: "report.pdf", size: BYTES.length, lastModified: 5000 }],
+ });
+ });
+
+ it("does not give an unrelated upload the path of a same-metadata file", async () => {
+ const original = new File([BYTES], "report.pdf", { lastModified: 5000 });
+ const copy = new File([BYTES], "report.pdf", { lastModified: 5000 });
+ dropFiles([original]);
+ const [stub] = await importFiles([copy]);
+ expect(stub.localFilePath).toBeUndefined();
+ expect(
+ invoke.mock.calls.filter(
+ ([command]) => command === "resolve_dropped_file_paths",
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("waits for captured drop paths before persisting through addFiles", async () => {
+ let resolvePaths!: (paths: string[]) => void;
+ const paths = new Promise<string[]>((resolve) => {
+ resolvePaths = resolve;
+ });
+ invoke.mockImplementation(async (command: string) => {
+ if (command === "resolve_dropped_file_paths") return paths;
+ return { availability: "present", size: BYTES.length, modifiedMs: 5000 };
+ });
+ const file = new File([BYTES], "report.pdf");
+ dropFiles([file]);
+ const importing = importFiles([file]);
+ expect(storeStirlingFile).not.toHaveBeenCalled();
+ resolvePaths([PATH]);
+ expect(await importing).toEqual([
+ expect.objectContaining({ localFilePath: PATH }),
+ ]);
+ });
+
+ it("removes the global drop listener during app cleanup", async () => {
+ stopCapturingDrops();
+ const file = new File([BYTES], "report.pdf");
+ dropFiles([file]);
+ const [stub] = await importFiles([file]);
+ expect(stub.localFilePath).toBeUndefined();
+ expect(invoke).not.toHaveBeenCalled();
+ });
+
+ it("does not open a pathless browser picker after native cancellation", async () => {
+ open.mockResolvedValue(null);
+ const onFallbackOpen = vi.fn();
+ expect(await openFilesFromDisk({ onFallbackOpen })).toEqual([]);
+ expect(onFallbackOpen).not.toHaveBeenCalled();
+ });
+
+ it("imports unresolved drops without inventing a save target", async () => {
+ invoke.mockRejectedValue(new Error("No native path available"));
+ const file = new File([BYTES], "report.pdf");
+ dropFiles([file]);
+ const [stub] = await importFiles([file]);
+ expect(stub.localFilePath).toBeUndefined();
+ });
+
+ it("uses WebView2's actual DOM file paths on Windows", async () => {
+ vi.stubGlobal("crypto", {
+ ...crypto,
+ randomUUID: () => "file-drop-request",
+ });
+ let listener: ((event: MessageEvent) => void) | undefined;
+ const removeEventListener = vi.fn();
+ const postMessageWithAdditionalObjects = vi.fn(
+ (message: string, files: File[]) => {
+ const request = JSON.parse(message);
+ expect(files).toHaveLength(1);
+ listener?.(
+ new MessageEvent("message", {
+ data: {
+ type: "stirling-file-drop-result",
+ requestId: request.requestId,
+ paths: [PATH],
+ },
+ }),
+ );
+ },
+ );
+ vi.stubGlobal("chrome", {
+ webview: {
+ postMessageWithAdditionalObjects,
+ addEventListener: (
+ _type: string,
+ handler: (event: MessageEvent) => void,
+ ) => {
+ listener = handler;
+ },
+ removeEventListener,
+ },
+ });
+ const file = new File([BYTES], "report.pdf");
+ expect(await importFiles([file])).toEqual([
+ expect.objectContaining({ localFilePath: PATH }),
+ ]);
+ expect(removeEventListener).toHaveBeenCalledWith("message", listener);
+ expect(invoke).not.toHaveBeenCalledWith(
+ "resolve_dropped_file_paths",
+ expect.anything(),
+ );
+ });
+});
diff --git a/frontend/editor/src/desktop/services/fileImportPaths.ts b/frontend/editor/src/desktop/services/fileImportPaths.ts
new file mode 100644
index 0000000000..9d906cb774
--- /dev/null
+++ b/frontend/editor/src/desktop/services/fileImportPaths.ts
@@ -0,0 +1,102 @@
+import { invoke } from "@tauri-apps/api/core";
+import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
+
+interface FileDropBridge {
+ postMessageWithAdditionalObjects(message: string, objects: File[]): void;
+ addEventListener(
+ type: "message",
+ listener: (event: MessageEvent) => void,
+ ): void;
+ removeEventListener(
+ type: "message",
+ listener: (event: MessageEvent) => void,
+ ): void;
+}
+
+function resolveWindowsPaths(
+ bridge: FileDropBridge,
+ files: File[],
+): Promise<(string | null)[]> {
+ return new Promise((resolve) => {
+ const requestId = crypto.randomUUID();
+ const finish = (paths: (string | null)[]) => {
+ window.clearTimeout(timeout);
+ bridge.removeEventListener("message", onMessage);
+ resolve(paths);
+ };
+ const onMessage = (event: MessageEvent) => {
+ const response = event.data;
+ if (
+ response?.type !== "stirling-file-drop-result" ||
+ response.requestId !== requestId
+ )
+ return;
+ finish(Array.isArray(response.paths) ? response.paths : []);
+ };
+ const timeout = window.setTimeout(() => finish([]), 5000);
+ bridge.addEventListener("message", onMessage);
+ try {
+ bridge.postMessageWithAdditionalObjects(
+ JSON.stringify({ type: "stirling-file-drop", requestId }),
+ files,
+ );
+ } catch {
+ finish([]);
+ }
+ });
+}
+
+function fileDropBridge(): FileDropBridge | undefined {
+ return (window as Window & { chrome?: { webview?: FileDropBridge } }).chrome
+ ?.webview;
+}
+
+function resolveDroppedPaths(files: File[]): Promise<(string | null)[]> {
+ const bridge = fileDropBridge();
+ return (
+ bridge?.postMessageWithAdditionalObjects
+ ? resolveWindowsPaths(bridge, files)
+ : invoke<(string | null)[]>("resolve_dropped_file_paths", {
+ files: files.map(({ name, size, lastModified }) => ({
+ name,
+ size,
+ lastModified,
+ })),
+ })
+ ).catch(() => []);
+}
+
+/** Captures drop provenance before UI handlers run. Cleanup removes the app-wide listener. */
+export function captureDroppedFilePaths(): () => void {
+ const onDrop = (event: DragEvent) => {
+ const files = Array.from(event.dataTransfer?.files ?? []);
+ if (files.length === 0) return;
+ // Read the drag pasteboard now; addFiles may wait on ZIP extraction or another import.
+ const paths = resolveDroppedPaths(files);
+ files.forEach((file, index) => {
+ pendingFilePathMappings.set(
+ file,
+ paths.then((paths) => paths[index] || undefined),
+ );
+ });
+ };
+ document.addEventListener("drop", onDrop, true);
+ return () => document.removeEventListener("drop", onDrop, true);
+}
+
+/** Returns the original path for this File only; generated files have no disk source. */
+export async function sourcePathForFile(
+ file: File,
+): Promise<string | undefined> {
+ if (pendingFilePathMappings.has(file))
+ return pendingFilePathMappings.get(file);
+ const bridge = fileDropBridge();
+ if (!bridge?.postMessageWithAdditionalObjects) return undefined;
+ // Chromium's FileSystemHandle can supply a new File instance after drop capture.
+ // WebView2 resolves that File's native backing; synthetic Files return no path.
+ const path = resolveWindowsPaths(bridge, [file])
+ .then((paths) => paths[0] || undefined)
+ .catch(() => undefined);
+ pendingFilePathMappings.set(file, path);
+ return path;
+}
diff --git a/frontend/editor/src/desktop/services/httpErrorHandler.ts b/frontend/editor/src/desktop/services/httpErrorHandler.ts
index e084101f25..69e479844c 100644
--- a/frontend/editor/src/desktop/services/httpErrorHandler.ts
+++ b/frontend/editor/src/desktop/services/httpErrorHandler.ts
@@ -5,12 +5,13 @@ import {
handlePaygError,
} from "@app/services/paygErrorInterceptor";
import { OPEN_SIGN_IN_EVENT } from "@app/constants/signInEvents";
+import { alert } from "@app/components/toast";
+import i18n from "@app/i18n";
/**
- * Desktop override of handleHttpError.
- * In desktop builds, 401 errors must never navigate to /login — the legacy web
- * login page must not appear. Instead, open the SignInModal for re-authentication.
- * All other error handling delegates to the core implementation.
+ * Desktop authentication uses token refresh and the sign-in modal, so 401s must
+ * never reach core's web login redirect. Permission failures are reported once
+ * here; remaining errors delegate to core.
*/
export async function handleHttpError(error: unknown): Promise<boolean> {
const status = isAxiosError(error) ? error.response?.status : undefined;
@@ -48,5 +49,22 @@ export async function handleHttpError(error: unknown): Promise<boolean> {
return true; // Suppress toast
}
+ if (isAxiosError(error) && error.config?.suppressErrorToast === true) {
+ return false;
+ }
+
+ if (status === 403) {
+ alert({
+ alertType: "error",
+ title: i18n.t("auth.accessDenied", "Access Denied"),
+ body: i18n.t(
+ "auth.insufficientPermissions",
+ "You do not have permission to perform this action.",
+ ),
+ isPersistentPopup: false,
+ });
+ return true;
+ }
+
return coreHandleHttpError(error);
}
diff --git a/frontend/editor/src/desktop/services/localFolderContents.ts b/frontend/editor/src/desktop/services/localFolderContents.ts
index eabb22d3cc..c1dde96284 100644
--- a/frontend/editor/src/desktop/services/localFolderContents.ts
+++ b/frontend/editor/src/desktop/services/localFolderContents.ts
@@ -18,6 +18,7 @@ import type {
DiskListing,
ListDirectoryOptions,
} from "@core/services/localFolderContents";
+import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
export type { DiskDirEntry, DiskFileEntry, DiskListing, ListDirectoryOptions };
/**
@@ -140,10 +141,12 @@ export async function readDiskFile(entry: DiskFileEntry): Promise<File | null> {
if (!canListDirectory) return null;
if (!(await isWithinMount(entry.path))) return null;
const bytes = await readFile(entry.path);
- return new File([new Uint8Array(bytes)], entry.name, {
+ const file = new File([new Uint8Array(bytes)], entry.name, {
type: mimeForName(entry.name),
lastModified: entry.lastModified || undefined,
});
+ pendingFilePathMappings.set(file, entry.path);
+ return file;
}
/** How many "(n)" suffixes to try before conceding the directory is hostile. */
diff --git a/frontend/editor/src/desktop/services/tauriHttpClient.test.ts b/frontend/editor/src/desktop/services/tauriHttpClient.test.ts
index ae59d7e919..ea20b22b7e 100644
--- a/frontend/editor/src/desktop/services/tauriHttpClient.test.ts
+++ b/frontend/editor/src/desktop/services/tauriHttpClient.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, test, vi, beforeEach } from "vitest";
+import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
// Regression: a caller-set "Content-Type: multipart/form-data" (no boundary) on a
// FormData POST must NOT reach the server, or Jetty rejects it with
@@ -25,6 +25,45 @@ function lastFetchHeaders(): Record<string, string> {
return (opts.headers ?? {}) as Record<string, string>;
}
+describe("tauriHttpClient — native request origin", () => {
+ beforeEach(() => {
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue(okJson());
+ });
+
+ afterEach(() => vi.unstubAllEnvs());
+
+ test.each([true, false])(
+ "preserves auth and overrides Origin only in dev (DEV=%s)",
+ async (dev) => {
+ vi.stubEnv("DEV", dev);
+
+ const client = create({
+ baseURL: "https://api.test",
+ headers: { "X-Browser-Id": "desktop-test" },
+ });
+
+ await client.get("/api/v1/policies", {
+ headers: { Authorization: "Bearer test-token" },
+ withCredentials: true,
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://api.test/api/v1/policies",
+ expect.objectContaining({
+ method: "GET",
+ credentials: "include",
+ headers: {
+ ...(dev ? { Origin: "tauri://localhost" } : {}),
+ "X-Browser-Id": "desktop-test",
+ Authorization: "Bearer test-token",
+ },
+ }),
+ );
+ },
+ );
+});
+
describe("tauriHttpClient — Content-Type handling", () => {
beforeEach(() => {
fetchMock.mockReset();
diff --git a/frontend/editor/src/desktop/services/tauriHttpClient.ts b/frontend/editor/src/desktop/services/tauriHttpClient.ts
index ae226685cb..90fade621c 100644
--- a/frontend/editor/src/desktop/services/tauriHttpClient.ts
+++ b/frontend/editor/src/desktop/services/tauriHttpClient.ts
@@ -253,7 +253,11 @@ class TauriHttpClient {
};
} = {
method,
- headers,
+ // The dev webview has a Vite origin; cloud CORS accepts the packaged app origin.
+ // task desktop:dev alone enables the plugin feature needed to override Origin.
+ headers: import.meta.env.DEV
+ ? { Origin: "tauri://localhost", ...headers }
+ : headers,
body,
credentials,
...(finalConfig.signal ? { signal: finalConfig.signal } : {}),
diff --git a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx
index 8d03245307..5c46eba55b 100644
--- a/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx
+++ b/frontend/editor/src/proprietary/components/policies/DownloadsProcessingWizard.tsx
@@ -94,7 +94,9 @@ export function DownloadsProcessingWizard({
setFound({ directory, entries: pdfs });
// Warm the AI engine while the user reads the offer, so the first escalation pays no
// cold start. Best-effort.
- void apiClient.get("/api/v1/ai/health").catch(() => {});
+ void apiClient
+ .get("/api/v1/ai/health", { suppressErrorToast: true })
+ .catch(() => {});
})();
return () => {
diff --git a/frontend/editor/src/proprietary/services/processingFolderApi.ts b/frontend/editor/src/proprietary/services/processingFolderApi.ts
index 2289ca5b7c..1963008728 100644
--- a/frontend/editor/src/proprietary/services/processingFolderApi.ts
+++ b/frontend/editor/src/proprietary/services/processingFolderApi.ts
@@ -118,7 +118,7 @@ export interface ProcessingFolderRun {
stepCount?: number;
}
-/** Runs belonging to a processing folder, newest first — drives the progress display. */
+/** Newest runs first. Poll failures reject without global toasts. */
export async function fetchProcessingFolderRuns(
policyId: string,
): Promise<ProcessingFolderRun[]> {
@@ -126,7 +126,10 @@ export async function fetchProcessingFolderRuns(
// against a backend that ignores the parameter.
const res = await apiClient.get<
(ProcessingFolderRun & { policyId?: string })[]
- >("/api/v1/policies/runs", { params: { policyId } });
+ >("/api/v1/policies/runs", {
+ params: { policyId },
+ suppressErrorToast: true,
+ });
return (res.data ?? []).filter((run) => run.policyId === policyId);
}
@@ -176,9 +179,11 @@ export interface MountedFile {
hasOriginal?: boolean;
}
+/** Reads file progress for polling; failures reject without global toasts. */
export async function fetchMountedFiles(id: string): Promise<MountedFile[]> {
const res = await apiClient.get<MountedFile[]>(
`/api/v1/processing-folders/${id}/files`,
+ { suppressErrorToast: true },
);
return res.data ?? [];
}
diff --git a/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx b/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx
index b72eac67f8..e6c1a1ee11 100644
--- a/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx
+++ b/frontend/editor/src/saas/hooks/useWallet.poll.test.tsx
@@ -155,4 +155,36 @@ describe("useWallet — keeping the figures fresh", () => {
await waitFor(() => expect(get.mock.calls.length).toBe(afterMount + 1));
visibility.mockRestore();
});
+
+ it("stops a disabled reader and discards its in-flight wallet response", async () => {
+ const { result, rerender } = renderHook(
+ ({ enabled }) => useWallet(enabled),
+ { initialProps: { enabled: false } },
+ );
+ expect(get).not.toHaveBeenCalled();
+
+ rerender({ enabled: true });
+ await waitFor(() => expect(result.current.wallet).not.toBeNull());
+
+ let finishPoll: (value: ReturnType<typeof walletWith>) => void = () => {};
+ get.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishPoll = resolve;
+ }),
+ );
+ await act(async () => {
+ vi.advanceTimersByTime(30_000);
+ });
+ expect(get).toHaveBeenCalledTimes(2);
+
+ rerender({ enabled: false });
+ await act(async () => {
+ finishPoll(walletWith(480));
+ vi.advanceTimersByTime(90_000);
+ });
+ expect(get).toHaveBeenCalledTimes(2);
+ expect(result.current.wallet).toBeNull();
+ expect(result.current.loading).toBe(false);
+ expect(result.current.error).toBeNull();
+ });
});