Skip to content

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

Fix startup views and desktop session restoration (#8309)

Reece Browne90d4c9b2f880
diff --git a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx
index bdea80405b..5980980b80 100644
--- a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx
+++ b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.test.tsx
@@ -3,6 +3,7 @@ import { render, waitFor, act } from "@testing-library/react";
const mocks = vi.hoisted(() => ({
getLeafStirlingFileStubs: vi.fn(),
+ getStirlingFileStub: vi.fn(),
alert: vi.fn(),
setActiveFileId: vi.fn(),
restoreWorkbench: vi.fn(),
@@ -11,12 +12,19 @@ const mocks = vi.hoisted(() => ({
authLoading: false,
pathname: "/editor",
activeFileId: null as string | null,
+ launchFilesPending: false,
}));
vi.mock("@app/services/fileStorage", () => ({
- fileStorage: { getLeafStirlingFileStubs: mocks.getLeafStirlingFileStubs },
+ fileStorage: {
+ getLeafStirlingFileStubs: mocks.getLeafStirlingFileStubs,
+ getStirlingFileStub: mocks.getStirlingFileStub,
+ },
}));
vi.mock("@app/components/toast", () => ({ alert: mocks.alert }));
+vi.mock("@app/services/launchFiles", () => ({
+ launchFilesPending: async () => mocks.launchFilesPending,
+}));
vi.mock("@app/contexts/NavigationContext", () => ({
useNavigationState: () => ({ workbench: mocks.workbench }),
useNavigationActions: () => ({
@@ -120,11 +128,13 @@ beforeEach(() => {
vi.clearAllMocks();
actions.addStirlingFileStubs.mockResolvedValue([]);
mocks.getLeafStirlingFileStubs.mockResolvedValue([]);
+ mocks.getStirlingFileStub.mockResolvedValue(null);
mocks.workbench = "viewer";
mocks.authUser = null;
mocks.authLoading = false;
mocks.pathname = "/editor";
mocks.activeFileId = null;
+ mocks.launchFilesPending = false;
});
afterEach(() => vi.useRealTimers());
@@ -159,15 +169,154 @@ describe("restore", () => {
expect(mocks.alert).not.toHaveBeenCalled();
});
- it("does not touch a workbench that already holds files", async () => {
+ it("adds saved files alongside files that are already open", async () => {
sessionStorage.setItem(
SESSION_KEY,
JSON.stringify({ v: 2, fileIds: ["root-a"], selectedFileIds: [] }),
);
+ mocks.getStirlingFileStub.mockResolvedValue(stub("root-a", "root-a"));
mount(makeStore([stub("already-open", "already-open")]));
+ await act(async () => {});
+ expect(actions.addStirlingFileStubs).toHaveBeenCalledWith([
+ stub("root-a", "root-a"),
+ ]);
+ expect(actions.setSelectedFiles).not.toHaveBeenCalled();
+ expect(mocks.setActiveFileId).not.toHaveBeenCalled();
+ expect(mocks.restoreWorkbench).not.toHaveBeenCalled();
+ });
+
+ it("reads unversioned files directly instead of scanning the whole library", async () => {
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({ v: 2, fileIds: ["root-a"], selectedFileIds: [] }),
+ );
+ mocks.getStirlingFileStub.mockResolvedValue(stub("root-a", "root-a"));
+
+ mount(makeStore());
+
+ await waitFor(() =>
+ expect(actions.addStirlingFileStubs).toHaveBeenCalled(),
+ );
+ expect(
+ actions.addStirlingFileStubs.mock.calls[0][0].map(
+ (s: StirlingFileStub) => s.id,
+ ),
+ ).toEqual(["root-a"]);
+ expect(mocks.getLeafStirlingFileStubs).not.toHaveBeenCalled();
+ });
+
+ it("scans for the current leaf once a recorded file has been versioned", async () => {
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({ v: 2, fileIds: ["root-a"], selectedFileIds: [] }),
+ );
+ mocks.getStirlingFileStub.mockResolvedValue({
+ ...stub("root-a", "root-a"),
+ isLeaf: false,
+ });
+ mocks.getLeafStirlingFileStubs.mockResolvedValue([
+ stub("a-v2", "root-a", 2),
+ ]);
+
+ mount(makeStore());
+
+ await waitFor(() =>
+ expect(actions.addStirlingFileStubs).toHaveBeenCalled(),
+ );
+ expect(
+ actions.addStirlingFileStubs.mock.calls[0][0].map(
+ (s: StirlingFileStub) => s.id,
+ ),
+ ).toEqual(["a-v2"]);
+ });
+
+ it("restores saved files while leaving the view to launch files still loading", async () => {
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({
+ v: 2,
+ fileIds: ["root-a"],
+ selectedFileIds: ["root-a"],
+ activeFileId: "root-a",
+ workbench: "fileEditor",
+ }),
+ );
+ mocks.getLeafStirlingFileStubs.mockResolvedValue([
+ stub("root-a", "root-a"),
+ ]);
+ mocks.launchFilesPending = true;
+
+ mount(makeStore());
+
+ await act(async () => {});
+ expect(actions.addStirlingFileStubs).toHaveBeenCalledWith([
+ stub("root-a", "root-a"),
+ ]);
+ expect(actions.setSelectedFiles).not.toHaveBeenCalled();
+ expect(mocks.setActiveFileId).not.toHaveBeenCalled();
+ expect(mocks.restoreWorkbench).not.toHaveBeenCalled();
+ });
+
+ it.each(["lookup", "addition"])(
+ "does not replace launch selection or view when files arrive during %s",
+ async (phase) => {
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({
+ v: 2,
+ fileIds: ["root-a"],
+ selectedFileIds: ["root-a"],
+ activeFileId: "root-a",
+ workbench: "fileEditor",
+ }),
+ );
+ const store = makeStore();
+ const arrive = () => {
+ store.state.files.ids = ["launched" as never];
+ store.state.files.byId = { launched: stub("launched", "launched") };
+ store.state.ui.selectedFileIds = ["launched"];
+ store.notify();
+ };
+ mocks.getStirlingFileStub.mockImplementation(async () => {
+ if (phase === "lookup") arrive();
+ return stub("root-a", "root-a");
+ });
+ actions.addStirlingFileStubs.mockImplementation(async () => {
+ if (phase === "addition") arrive();
+ return [];
+ });
+
+ mount(store);
+ await act(async () => {});
+
+ expect(actions.addStirlingFileStubs).toHaveBeenCalledWith([
+ stub("root-a", "root-a"),
+ ]);
+ expect(actions.setSelectedFiles).not.toHaveBeenCalled();
+ expect(mocks.setActiveFileId).not.toHaveBeenCalled();
+ expect(mocks.restoreWorkbench).not.toHaveBeenCalled();
+ expect(store.state.ui.selectedFileIds).toEqual(["launched"]);
+ },
+ );
+
+ it("does not reopen another version of a file already in the workbench", async () => {
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({ v: 2, fileIds: ["root-a"], selectedFileIds: [] }),
+ );
+ mocks.getStirlingFileStub.mockResolvedValue({
+ ...stub("root-a", "root-a"),
+ isLeaf: false,
+ });
+ mocks.getLeafStirlingFileStubs.mockResolvedValue([
+ stub("a-v3", "root-a", 3),
+ ]);
+ mount(makeStore([stub("a-v2", "root-a", 2)]));
+
await act(async () => {});
expect(actions.addStirlingFileStubs).not.toHaveBeenCalled();
+ expect(mocks.alert).not.toHaveBeenCalled();
});
it("restores what still exists and says how much is gone", async () => {
@@ -404,6 +553,76 @@ describe("on the login screen", () => {
});
describe("writer", () => {
+ it("keeps the saved session when launch intake never opens a file", async () => {
+ vi.useFakeTimers();
+ const saved = JSON.stringify({
+ v: 2,
+ fileIds: ["root-a"],
+ selectedFileIds: [],
+ });
+ sessionStorage.setItem(SESSION_KEY, saved);
+ mocks.launchFilesPending = true;
+ const store = makeStore();
+ const { unmount } = mount(store);
+ await act(async () => {});
+ mocks.launchFilesPending = false;
+ act(() => store.notify());
+ await act(async () => vi.advanceTimersByTimeAsync(300));
+ unmount();
+
+ expect(sessionStorage.getItem(SESSION_KEY)).toBe(saved);
+ });
+
+ it("records launched files and an intentional close after intake succeeds", async () => {
+ vi.useFakeTimers();
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({ v: 2, fileIds: ["root-a"], selectedFileIds: [] }),
+ );
+ mocks.launchFilesPending = true;
+ const store = makeStore();
+ const { unmount } = mount(store);
+ await act(async () => {});
+
+ store.state.files.ids = ["launched" as never];
+ store.state.files.byId = { launched: stub("launched", "launched") };
+ act(() => store.notify());
+ await act(async () => vi.advanceTimersByTimeAsync(300));
+ expect(JSON.parse(sessionStorage.getItem(SESSION_KEY)!).fileIds).toEqual([
+ "launched",
+ ]);
+
+ store.state.files.ids = [];
+ store.state.files.byId = {};
+ act(() => store.notify());
+ unmount();
+ expect(JSON.parse(sessionStorage.getItem(SESSION_KEY)!).fileIds).toEqual(
+ [],
+ );
+ });
+
+ it("records a launch file closed before the debounced write as an empty session", async () => {
+ sessionStorage.setItem(
+ SESSION_KEY,
+ JSON.stringify({ v: 2, fileIds: ["root-a"], selectedFileIds: [] }),
+ );
+ mocks.launchFilesPending = true;
+ const store = makeStore();
+ const { unmount } = mount(store);
+ await act(async () => {});
+
+ store.state.files.ids = ["launched" as never];
+ store.state.files.byId = { launched: stub("launched", "launched") };
+ act(() => store.notify());
+ store.state.files.ids = [];
+ store.state.files.byId = {};
+ act(() => store.notify());
+ unmount();
+ expect(JSON.parse(sessionStorage.getItem(SESSION_KEY)!).fileIds).toEqual(
+ [],
+ );
+ });
+
it("mirrors the open files and selection as original ids, debounced", async () => {
vi.useFakeTimers();
const store = makeStore();
diff --git a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx
index 425aa6340d..b17382b007 100644
--- a/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx
+++ b/frontend/editor/src/core/components/session/WorkbenchSessionPersistence.tsx
@@ -1,5 +1,5 @@
// The editor/processor shell switch unmounts every editor provider, and a reload starts from nothing:
-// this mirrors the workbench into sessionStorage and refills an empty one from that record on mount.
+// this mirrors the workbench into sessionStorage and reopens its files alongside incoming files.
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -18,6 +18,7 @@ import { isAuthRoute } from "@app/constants/routes";
import { fileStorage } from "@app/services/fileStorage";
import { alert } from "@app/components/toast";
import { WORKBENCH_SESSION_RESTORE } from "@app/constants/featureFlags";
+import { launchFilesPending } from "@app/services/launchFiles";
import {
beginRestoredView,
clearWorkbenchSession,
@@ -50,6 +51,23 @@ function leafByOriginalId(
return map;
}
+/**
+ * The current leaf for each original id. A file never versioned is its own leaf, so point reads
+ * settle the usual case; scanning every stored file - seconds on a large library - is kept for
+ * when one of them has been versioned or is gone.
+ */
+async function currentLeaves(
+ originalIds: string[],
+): Promise<Map<string, StirlingFileStub>> {
+ const direct = await Promise.all(
+ originalIds.map((id) => fileStorage.getStirlingFileStub(id as FileId)),
+ );
+ if (direct.every((stub) => stub && stub.isLeaf !== false)) {
+ return new Map(originalIds.map((id, i) => [id, direct[i]!]));
+ }
+ return leafByOriginalId(await fileStorage.getLeafStirlingFileStubs());
+}
+
/** How long to wait for the NEXT file to hydrate before giving up on holding the view. Restarted on
* each arrival, so a slow device with large documents keeps the view as long as it makes progress. */
const SETTLE_TIMEOUT_MS = 5000;
@@ -146,6 +164,8 @@ export function WorkbenchSessionPersistence() {
const restoreStarted = useRef(false);
// Until the restore has run, this mount's empty state is not the truth to record.
const restoreSettled = useRef(false);
+ // Failed launch intake must leave the previous recovery record available on the next reload.
+ const awaitingLaunchedFile = useRef(false);
// Published so a build's restore setting is legible without reading the bundle.
useEffect(() => {
@@ -159,6 +179,8 @@ export function WorkbenchSessionPersistence() {
// A known identity whose fingerprint has not landed yet: wait, do not stamp it as nobody's.
if (userId != null && owner == null) return;
const state = store.getState();
+ if (awaitingLaunchedFile.current && state.files.ids.length === 0) return;
+ awaitingLaunchedFile.current = false;
const toOriginal = (id: FileId): string | null => {
const stub = state.files.byId[id];
return stub ? originalIdOf(stub) : null;
@@ -187,6 +209,8 @@ export function WorkbenchSessionPersistence() {
resumeWorkbenchSession();
let timer: ReturnType<typeof setTimeout> | undefined;
const unsubscribe = store.subscribe(() => {
+ if (store.getState().files.ids.length > 0)
+ awaitingLaunchedFile.current = false;
clearTimeout(timer);
timer = setTimeout(() => writeRef.current(), WRITE_DEBOUNCE_MS);
});
@@ -212,8 +236,7 @@ export function WorkbenchSessionPersistence() {
!WORKBENCH_SESSION_RESTORE ||
!store ||
!saved ||
- saved.fileIds.length === 0 ||
- store.getState().files.ids.length > 0;
+ saved.fileIds.length === 0;
if (nothingToDo) {
restoreSettled.current = true;
return;
@@ -229,44 +252,65 @@ export function WorkbenchSessionPersistence() {
restoreSettled.current = true;
return;
}
+ const pending = await launchFilesPending();
+ awaitingLaunchedFile.current =
+ pending && store.getState().files.ids.length === 0;
// Held while the files land: they are added one at a time, and each landing re-runs the
// default-view heuristic, which must not overwrite the recorded view mid-restore.
let held: number | null = null;
try {
// Resolve each id to its CURRENT leaf: a policy or another tab may have versioned it since.
- const leaves = leafByOriginalId(
- await fileStorage.getLeafStirlingFileStubs(),
- );
+ const leaves = await currentLeaves(saved.fileIds);
const stubs = saved.fileIds
.map((id) => leaves.get(id))
.filter((stub): stub is StirlingFileStub => stub !== undefined);
+ const openOriginalIds = new Set(
+ Object.values(store.getState().files.byId).map(originalIdOf),
+ );
+ const toRestore = stubs.filter(
+ (stub) => !openOriginalIds.has(originalIdOf(stub)),
+ );
- if (stubs.length > 0) {
+ if (toRestore.length > 0) {
+ const canRestorePresentation =
+ !(await launchFilesPending()) &&
+ store.getState().files.ids.length === 0;
const view =
- !pathOwnsView && isSeedableView(saved.workbench)
+ canRestorePresentation &&
+ !pathOwnsView &&
+ isSeedableView(saved.workbench)
? saved.workbench
: null;
if (view) held = beginRestoredView();
// The same entry point My Files uses, so a restored file is governed by the same rules as
// any other file entering the workbench - including whether a policy has already run on it.
- await actions.addStirlingFileStubs(stubs);
- const selected = saved.selectedFileIds
- .map((id) => leaves.get(id)?.id)
- .filter((id): id is FileId => id !== undefined);
- if (selected.length > 0) actions.setSelectedFiles(selected);
- // After the files land: the viewer drops an active id it cannot find.
- const active = saved.activeFileId
- ? leaves.get(saved.activeFileId)?.id
- : undefined;
- if (active) setActiveFileId(active);
- if (view && held !== null) {
- reopenView(store, navigationActions.restoreWorkbench, {
- view,
- fileCount: stubs.length,
- token: held,
- });
- held = null; // reopenView owns the release from here.
+ await actions.addStirlingFileStubs(toRestore);
+ const restoredIds = new Set(toRestore.map((stub) => stub.id));
+ // File intake can begin during either storage lookup or insertion. Keep its selection
+ // and view, while still reopening the saved files alongside it.
+ if (
+ canRestorePresentation &&
+ !(await launchFilesPending()) &&
+ store.getState().files.ids.every((id) => restoredIds.has(id))
+ ) {
+ const selected = saved.selectedFileIds
+ .map((id) => leaves.get(id)?.id)
+ .filter((id): id is FileId => id !== undefined);
+ if (selected.length > 0) actions.setSelectedFiles(selected);
+ // After the files land: the viewer drops an active id it cannot find.
+ const active = saved.activeFileId
+ ? leaves.get(saved.activeFileId)?.id
+ : undefined;
+ if (active) setActiveFileId(active);
+ if (view && held !== null) {
+ reopenView(store, navigationActions.restoreWorkbench, {
+ view,
+ fileCount: toRestore.length,
+ token: held,
+ });
+ held = null; // reopenView owns the release from here.
+ }
}
}
diff --git a/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx b/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx
index e83c4344c4..e3349664d1 100644
--- a/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx
+++ b/frontend/editor/src/core/components/shared/NavigationWarningModal.tsx
@@ -1,4 +1,5 @@
import { useRef, useEffect } from "react";
+import { flushSync } from "react-dom";
import { useNavigationGuard } from "@app/contexts/NavigationContext";
import { UnsavedChangesDialog } from "@app/components/shared/UnsavedChangesDialog";
@@ -25,8 +26,11 @@ const NavigationWarningModal = () => {
const finishAndNavigate = () => {
const nav = pendingNavigationRef.current;
- setHasUnsavedChanges(false);
- cancelNavigation();
+ // Compound navigation can invoke more guards; they must see the resolved edits.
+ flushSync(() => {
+ setHasUnsavedChanges(false);
+ cancelNavigation();
+ });
if (nav) {
nav();
}
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
index d0f783dfce..a3d42f80d6 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavHostBridge.tsx
@@ -21,6 +21,7 @@ export interface QuickNavHostBridgeProps {
onSetReaderMode?: (on: boolean) => void;
requestNavigation?: (go: () => void) => void;
onGoToDefaultState?: () => void;
+ onGoToStartupView?: () => void;
onSelectTool?: (toolId: ToolId) => void;
activeTool?: ToolId | null;
onShowFileLibrary?: () => void;
@@ -42,6 +43,7 @@ export function QuickNavHostBridge({
onShowFileLibrary,
onCreateProcessingFolder,
onGoToDefaultState,
+ onGoToStartupView,
toolReasons,
onOpenFromComputer,
}: QuickNavHostBridgeProps) {
@@ -78,6 +80,7 @@ export function QuickNavHostBridge({
showFileLibrary: onShowFileLibrary,
createProcessingFolder: onCreateProcessingFolder,
goToDefaultState: onGoToDefaultState,
+ goToStartupView: onGoToStartupView,
openFromComputer: onOpenFromComputer,
toggleNotifications: () => setNotificationsOpen((open) => !open),
onBrandFlourish: brandFlourish.trigger,
diff --git a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
index f8919f6b49..a243823b70 100644
--- a/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
+++ b/frontend/editor/src/core/components/shared/quickNav/QuickNavRailHost.tsx
@@ -54,6 +54,13 @@ export function QuickNavRailHost() {
else navigate(inPortal ? PORTAL_BASENAME : EDITOR_BASENAME);
};
+ // The brand goes where the app launches; the Editor entry stays in the editor.
+ const goToStartupView = () => {
+ const start = host?.actions.current?.goToStartupView;
+ if (start) start();
+ else returnHome();
+ };
+
// Guarded where the app supplies a guard, so leaving mid-edit still prompts.
const guarded = (leave: () => void) => {
const guard = host?.actions.current?.requestNavigation;
@@ -249,7 +256,7 @@ export function QuickNavRailHost() {
return (
<QuickNavRailContainer
groups={[surfaces, within]}
- onReturnHome={returnHome}
+ onReturnHome={() => guarded(goToStartupView)}
identity={host?.identity ?? null}
onOpenAccount={openAccount}
// The avatar stands for the whole page, not just its own section.
diff --git a/frontend/editor/src/core/contexts/FileContext.tsx b/frontend/editor/src/core/contexts/FileContext.tsx
index 75701be435..74b0418d44 100644
--- a/frontend/editor/src/core/contexts/FileContext.tsx
+++ b/frontend/editor/src/core/contexts/FileContext.tsx
@@ -75,8 +75,6 @@ import { processResponse } from "@app/utils/toolResponseProcessor";
import { ToolOperation } from "@app/types/file";
import { handlePasswordError } from "@app/utils/toolErrorHandler";
-const DEBUG = process.env.NODE_ENV === "development";
-
// Inner provider component that has access to IndexedDB
function FileContextInner({
children,
@@ -775,12 +773,15 @@ function FileContextInner({
// loadFromPersistence();
// }, [enablePersistence, indexedDB]);
- // Cleanup on unmount
+ const mountedRef = useRef(false);
useEffect(() => {
+ mountedRef.current = true;
return () => {
- if (DEBUG)
- console.log("FileContext unmounting - cleaning up all resources");
- lifecycleManager.destroy();
+ mountedRef.current = false;
+ // StrictMode can replay effects after files hydrate; only an actual unmount owns cleanup.
+ queueMicrotask(() => {
+ if (!mountedRef.current) lifecycleManager.destroy();
+ });
};
}, [lifecycleManager]);
diff --git a/frontend/editor/src/core/contexts/NavigationContext.tsx b/frontend/editor/src/core/contexts/NavigationContext.tsx
index 85c51f7701..d1ebe3391e 100644
--- a/frontend/editor/src/core/contexts/NavigationContext.tsx
+++ b/frontend/editor/src/core/contexts/NavigationContext.tsx
@@ -323,11 +323,14 @@ export const NavigationProvider: React.FC<{
const requestNavigation = useCallback(
(navigationFn: () => void) => {
- if (!state.hasUnsavedChanges) {
+ const hasUnsavedChanges =
+ unsavedChangesCheckerRef.current?.() || state.hasUnsavedChanges;
+ if (!hasUnsavedChanges) {
navigationFn();
return;
}
+ dispatch({ type: "SET_UNSAVED_CHANGES", payload: { hasChanges: true } });
dispatch({ type: "SET_PENDING_NAVIGATION", payload: { navigationFn } });
dispatch({ type: "SHOW_NAVIGATION_WARNING", payload: { show: true } });
},
diff --git a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
index b9a6eca1b0..5dbab6f6e2 100644
--- a/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
+++ b/frontend/editor/src/core/contexts/QuickNavHostContext.tsx
@@ -42,6 +42,8 @@ export interface QuickNavHostActions {
createProcessingFolder?: () => void;
toggleNotifications?: () => void;
goToDefaultState?: () => void;
+ /** The view the user chose to launch into, where that differs from the default state. */
+ goToStartupView?: () => void;
requestNavigation?: (go: () => void) => void;
openFromComputer?: () => void;
/**
diff --git a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
index 0fa0555d17..524eba1f6b 100644
--- a/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
+++ b/frontend/editor/src/core/contexts/ToolWorkflowContext.tsx
@@ -405,17 +405,24 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
// editor's home, never what a deep link to a tool shows. Without this, a
// "Reader" preference rewrote every /<tool> link to /read.
const path = stripBasePath(window.location.pathname);
- if (path !== "/" && path !== EDITOR_BASENAME) {
+ // A reload is not a launch: it keeps whichever view the user had open.
+ const navigation = performance.getEntriesByType?.("navigation")[0] as
+ | PerformanceNavigationTiming
+ | undefined;
+ if (
+ navigation?.type === "reload" ||
+ (path !== "/" && path !== EDITOR_BASENAME)
+ ) {
hasAppliedStartupView.current = true;
return;
}
const startupView = preferences.defaultStartupView;
if (startupView === "read") {
+ // Reading is a surface, not a tool: selecting the Read tool as well would
+ // disagree with the reader's address, and the URL sync would close both.
hasAppliedStartupView.current = true;
- startupSelectedToolRef.current = "read";
markReaderModeFromPreference();
setReaderMode(true);
- actions.setSelectedTool("read");
} else if (startupView === "automate") {
hasAppliedStartupView.current = true;
startupSelectedToolRef.current = "automate";
@@ -583,10 +590,17 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
return filterToolRegistryByQuery(toolRegistry, state.searchQuery);
}, [toolRegistry, state.searchQuery]);
+ // An address naming no tool clears the tool, not reading: the reader's own path
+ // decides that, and /reader names no tool either.
+ const clearToolFromAddress = useCallback(() => {
+ setLeftPanelView("toolPicker");
+ actions.setSelectedTool(null);
+ }, [setLeftPanelView, actions.setSelectedTool]);
+
useNavigationUrlSync(
navigationState.selectedTool,
handleToolSelect,
- handleBackToTools,
+ clearToolFromAddress,
allTools,
true,
startupSelectedToolRef,
diff --git a/frontend/editor/src/core/contexts/file/providerCleanup.test.tsx b/frontend/editor/src/core/contexts/file/providerCleanup.test.tsx
new file mode 100644
index 0000000000..50c3e1f1cc
--- /dev/null
+++ b/frontend/editor/src/core/contexts/file/providerCleanup.test.tsx
@@ -0,0 +1,43 @@
+import "fake-indexeddb/auto";
+import { StrictMode, useEffect, useRef } from "react";
+import { act, render } from "@testing-library/react";
+import { MantineProvider } from "@mantine/core";
+import { expect, it, vi } from "vitest";
+import { FileContextProvider, useFileActions } from "@app/contexts/FileContext";
+
+function OwnedResource({ url }: { url: string }) {
+ const { actions } = useFileActions();
+ const registered = useRef(false);
+ useEffect(() => {
+ if (registered.current) return;
+ registered.current = true;
+ actions.trackBlobUrl(url);
+ }, [actions, url]);
+ return null;
+}
+
+it("keeps owned resources through effect replay and releases them on unmount", async () => {
+ const url = "blob:owned-file-resource";
+ const revoke = vi.spyOn(URL, "revokeObjectURL");
+ try {
+ const { unmount } = render(
+ <StrictMode>
+ <MantineProvider>
+ <FileContextProvider>
+ <OwnedResource url={url} />
+ </FileContextProvider>
+ </MantineProvider>
+ </StrictMode>,
+ );
+ await act(async () => {});
+ expect(revoke).not.toHaveBeenCalledWith(url);
+
+ unmount();
+ await act(async () => {});
+ expect(
+ revoke.mock.calls.filter(([revoked]) => revoked === url),
+ ).toHaveLength(1);
+ } finally {
+ revoke.mockRestore();
+ }
+});
diff --git a/frontend/editor/src/core/pages/HomePage.startupView.test.tsx b/frontend/editor/src/core/pages/HomePage.startupView.test.tsx
new file mode 100644
index 0000000000..93b1d32113
--- /dev/null
+++ b/frontend/editor/src/core/pages/HomePage.startupView.test.tsx
@@ -0,0 +1,251 @@
+import "fake-indexeddb/auto";
+import { useState } from "react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter, useLocation, useNavigate } from "react-router-dom";
+import { MantineProvider } from "@mantine/core";
+import { AppProviders } from "@app/components/AppProviders";
+import HomePage from "@app/pages/HomePage";
+import SettingsPage from "@app/pages/SettingsPage";
+import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
+import {
+ useNavigationActions,
+ useNavigationState,
+} from "@app/contexts/NavigationContext";
+import NavigationWarningModal from "@app/components/shared/NavigationWarningModal";
+import { QuickNavHostProvider } from "@app/contexts/QuickNavHostContext";
+import { QuickNavRailHost } from "@app/components/shared/quickNav/QuickNavRailHost";
+import { allowConsole } from "@app/tests/failOnConsole";
+import type { ToolId } from "@app/types/toolId";
+
+vi.mock("@app/hooks/useDocumentMeta", () => ({ useDocumentMeta: () => {} }));
+// Document and tool panels are outside the navigation contract; loading them
+// under coverage can time out before the real pages and providers settle.
+vi.mock("@app/components/layout/Workbench", () => ({ default: () => null }));
+vi.mock("@app/components/tools/RightSidebar", () => ({ default: () => null }));
+vi.mock("@app/components/FileManager", () => ({ default: () => null }));
+
+const seen = { pathname: "", readerMode: false };
+let showPage: () => void = () => {};
+let backToTools: () => void = () => {};
+let selectTool: (id: ToolId) => void = () => {};
+let goBack: () => void = () => {};
+let goToSettings: () => void = () => {};
+let setReaderMode: (on: boolean) => void = () => {};
+let navigation: ReturnType<typeof useNavigationState>;
+let navigationActions: ReturnType<typeof useNavigationActions>["actions"];
+
+function Probe() {
+ seen.pathname = useLocation().pathname;
+ const navigate = useNavigate();
+ const workflow = useToolWorkflow();
+ navigation = useNavigationState();
+ navigationActions = useNavigationActions().actions;
+ seen.readerMode = workflow.readerMode;
+ backToTools = workflow.handleBackToTools;
+ selectTool = workflow.handleToolSelect;
+ setReaderMode = workflow.setReaderMode;
+ goBack = () => navigate(-1);
+ goToSettings = () => navigate("/settings/general");
+ return null;
+}
+
+// Holds the page back behind already-mounted providers, as the desktop shell
+// does until its auth check settles.
+function Page({ late }: { late: boolean }) {
+ const [shown, setShown] = useState(!late);
+ const { pathname } = useLocation();
+ showPage = () => setShown(true);
+ return (
+ <>
+ <Probe />
+ <NavigationWarningModal />
+ {shown &&
+ (pathname.startsWith("/settings") ? <SettingsPage /> : <HomePage />)}
+ </>
+ );
+}
+
+function renderApp(late = false) {
+ render(
+ <MemoryRouter initialEntries={["/"]}>
+ <MantineProvider>
+ <QuickNavHostProvider>
+ <QuickNavRailHost />
+ <AppProviders
+ appConfigProviderProps={{
+ initialConfig: {},
+ bootstrapMode: "non-blocking",
+ autoFetch: false,
+ }}
+ >
+ <Page late={late} />
+ </AppProviders>
+ </QuickNavHostProvider>
+ </MantineProvider>
+ </MemoryRouter>,
+ );
+}
+
+async function expectSettledInReader() {
+ await waitFor(() => expect(seen.pathname).toBe("/reader"));
+ // Settled there, not just passing through on the way back to the editor.
+ await act(() => new Promise((r) => setTimeout(r, 1000)));
+ expect(seen).toEqual({ pathname: "/reader", readerMode: true });
+}
+
+describe("default startup view: Reader", () => {
+ beforeEach(() => {
+ // The full provider tree settles asynchronously outside act().
+ allowConsole.error(/not wrapped in act/);
+ localStorage.clear();
+ localStorage.setItem(
+ "stirlingpdf_preferences",
+ JSON.stringify({ defaultStartupView: "read" }),
+ );
+ });
+
+ it.each([
+ ["with the providers", false],
+ ["after the providers", true],
+ ])(
+ "opens reading when the page mounts %s",
+ async (_label, late) => {
+ renderApp(late);
+ if (late) {
+ await waitFor(() => expect(seen.readerMode).toBe(true));
+ act(() => showPage());
+ }
+ await expectSettledInReader();
+ },
+ 15000,
+ );
+
+ it("keeps the editor on a reload", async () => {
+ const navigation = vi
+ .spyOn(performance, "getEntriesByType")
+ .mockReturnValue([{ type: "reload" } as PerformanceNavigationTiming]);
+ try {
+ renderApp();
+ await act(() => new Promise((r) => setTimeout(r, 1500)));
+ expect(seen).toEqual({ pathname: "/", readerMode: false });
+ } finally {
+ navigation.mockRestore();
+ }
+ }, 15000);
+
+ it("returns to reading from the brand mark", async () => {
+ renderApp();
+ await expectSettledInReader();
+ act(() => backToTools());
+ await waitFor(() =>
+ expect(seen).toEqual({ pathname: "/", readerMode: false }),
+ );
+ fireEvent.click(document.querySelector(".quick-nav-brand-button")!);
+ await expectSettledInReader();
+ }, 15000);
+
+ it("returns to reading from a selected tool and Back reopens that tool", async () => {
+ renderApp();
+ await expectSettledInReader();
+ act(() => selectTool("compress"));
+ await waitFor(() =>
+ expect(seen).toEqual({ pathname: "/compress", readerMode: false }),
+ );
+
+ fireEvent.click(document.querySelector(".quick-nav-brand-button")!);
+ await expectSettledInReader();
+
+ act(() => goBack());
+ await waitFor(() =>
+ expect(seen).toEqual({ pathname: "/compress", readerMode: false }),
+ );
+ }, 15000);
+
+ it("returns from settings to reading with one brand click", async () => {
+ renderApp();
+ await expectSettledInReader();
+ act(() => backToTools());
+ await waitFor(() => expect(seen.readerMode).toBe(false));
+ act(() => goToSettings());
+ await waitFor(() => expect(seen.pathname).toBe("/settings/general"));
+
+ fireEvent.click(document.querySelector(".quick-nav-brand-button")!);
+ await expectSettledInReader();
+ }, 15000);
+
+ it("opens reading from the rail while a tool is open", async () => {
+ renderApp();
+ await expectSettledInReader();
+ act(() => selectTool("compress"));
+ await waitFor(() =>
+ expect(seen).toEqual({ pathname: "/compress", readerMode: false }),
+ );
+
+ act(() => setReaderMode(true));
+ await expectSettledInReader();
+ }, 15000);
+
+ it.each([
+ ["cancel", "state"],
+ ["discard", "state"],
+ ["cancel", "checker"],
+ ["discard", "checker"],
+ ])(
+ "waits for the unsaved-changes decision from the brand mark: %s (%s)",
+ async (decision, dirtySource) => {
+ renderApp();
+ await expectSettledInReader();
+ act(() => selectTool("multiTool"));
+ await waitFor(() => {
+ expect(seen).toEqual({ pathname: "/multi-tool", readerMode: false });
+ expect(navigation.workbench).toBe("pageEditor");
+ });
+ if (dirtySource === "checker") {
+ let dirty = true;
+ act(() => {
+ navigationActions.registerUnsavedChangesChecker(() => dirty);
+ navigationActions.registerNavigationWarningHandlers({
+ onDiscardAndContinue: async () => {
+ dirty = false;
+ },
+ });
+ });
+ } else {
+ act(() => navigationActions.setHasUnsavedChanges(true));
+ }
+
+ fireEvent.click(document.querySelector(".quick-nav-brand-button")!);
+ await waitFor(() => expect(navigation.showNavigationWarning).toBe(true));
+ expect(seen).toEqual({ pathname: "/multi-tool", readerMode: false });
+ expect(navigation.selectedTool).toBe("multiTool");
+ expect(navigation.workbench).toBe("pageEditor");
+
+ if (decision === "cancel") {
+ fireEvent.click(screen.getByRole("button", { name: "keepWorking" }));
+ await waitFor(() =>
+ expect(navigation.showNavigationWarning).toBe(false),
+ );
+ expect(seen).toEqual({ pathname: "/multi-tool", readerMode: false });
+ expect(navigation.selectedTool).toBe("multiTool");
+ expect(navigation.workbench).toBe("pageEditor");
+ expect(navigation.hasUnsavedChanges).toBe(true);
+ } else {
+ fireEvent.click(screen.getByTestId("unsaved-discard"));
+ await expectSettledInReader();
+ expect(navigation.workbench).toBe("viewer");
+ expect(navigation.selectedTool).toBeNull();
+ expect(navigation.hasUnsavedChanges).toBe(false);
+ expect(navigation.showNavigationWarning).toBe(false);
+ expect(navigation.pendingNavigation).toBeNull();
+ }
+ },
+ 15000,
+ );
+});
diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsx
index 4c35262e32..76e808601e 100644
--- a/frontend/editor/src/core/pages/HomePage.tsx
+++ b/frontend/editor/src/core/pages/HomePage.tsx
@@ -1,5 +1,6 @@
import {
forwardRef,
+ startTransition,
useCallback,
useEffect,
useMemo,
@@ -48,6 +49,7 @@ import { PolicyAutoRunController } from "@app/components/policies/PolicyAutoRunC
import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
import type { QuickNavToolReasons } from "@app/contexts/QuickNavHostContext";
+import { usePreferences } from "@app/contexts/PreferencesContext";
import {
getToolDisabledReason,
getDisabledLabel,
@@ -194,6 +196,26 @@ export default function HomePage() {
actions.setWorkbench(getDefaultWorkbenchForFileCount(activeFiles.length));
}, [handleBackToTools, actions, activeFiles.length]);
+ const { preferences } = usePreferences();
+ const goToStartupView = useCallback(() => {
+ // The router transitions its updates; the tool reset must see the same destination.
+ startTransition(() => {
+ goToDefaultState();
+ if (preferences.defaultStartupView === "read") {
+ if (location.pathname !== READER_PATH) navigate(READER_PATH);
+ setReaderMode(true);
+ } else if (preferences.defaultStartupView === "automate")
+ handleToolSelect("automate");
+ });
+ }, [
+ goToDefaultState,
+ preferences.defaultStartupView,
+ location.pathname,
+ navigate,
+ setReaderMode,
+ handleToolSelect,
+ ]);
+
// Reconcile route and workspace only on transitions, or the old route can undo a view change.
const derivedFromPath = actions.viewDerivedFromPathRef;
useEffect(() => {
@@ -235,10 +257,23 @@ export default function HomePage() {
const readerDerivedFromPath = useRef<string | null>(null);
useEffect(() => {
if (readerDerivedFromPath.current === location.pathname) return;
+ const isMount = readerDerivedFromPath.current === null;
readerDerivedFromPath.current = location.pathname;
const onReadPath = location.pathname.startsWith(READER_PATH);
+ // The startup-view preference can open reading before this page mounts (the
+ // desktop shell holds the page back until its auth check settles). Reading is
+ // then the cause and the path follows it, rather than the path closing it.
+ if (
+ isMount &&
+ readerMode &&
+ !onReadPath &&
+ consumeReaderModeFromPreference()
+ ) {
+ navigate(READER_PATH, { replace: true });
+ return;
+ }
if (onReadPath !== readerMode) setReaderMode(onReadPath);
- }, [location.pathname, readerMode, setReaderMode]);
+ }, [location.pathname, readerMode, setReaderMode, navigate]);
// The wings animate off their own edge, so the unmount waits out the leave rather
// than happening with it. The rails' stylesheets take them out of flow while it
@@ -552,6 +587,7 @@ export default function HomePage() {
fileLibrary={navigationState.workbench === "myFiles"}
onSetReaderMode={setReaderMode}
onGoToDefaultState={goToDefaultState}
+ onGoToStartupView={goToStartupView}
onSelectTool={handleToolSelect}
activeTool={selectedToolKey}
onShowFileLibrary={() => actions.setWorkbench("myFiles")}
diff --git a/frontend/editor/src/core/pages/SettingsPage.tsx b/frontend/editor/src/core/pages/SettingsPage.tsx
index 6f1ccb2ce6..6276c7070f 100644
--- a/frontend/editor/src/core/pages/SettingsPage.tsx
+++ b/frontend/editor/src/core/pages/SettingsPage.tsx
@@ -29,6 +29,8 @@ import {
} from "@app/contexts/UnsavedChangesContext";
import { QuickNavHostBridge } from "@app/components/shared/quickNav/QuickNavHostBridge";
import { EDITOR_BASENAME } from "@app/routes/editorBasename";
+import { READER_PATH } from "@app/routes/readerRoute";
+import { usePreferences } from "@app/contexts/PreferencesContext";
import { stripBasePath } from "@app/constants/app";
import { takeSettingsOrigin } from "@app/utils/settingsNavigation";
import { Z_INDEX_OVER_CONFIG_MODAL } from "@app/styles/zIndex";
@@ -52,6 +54,17 @@ const SettingsPageInner: React.FC = () => {
const isMobile = useIsMobile();
const licenseAlert = useLicenseAlert();
const { confirmIfDirty } = useUnsavedChanges();
+ const { preferences } = usePreferences();
+ const goToStartupView = () => {
+ const view = preferences.defaultStartupView;
+ navigate(
+ view === "read"
+ ? READER_PATH
+ : view === "automate"
+ ? "/automate"
+ : EDITOR_BASENAME,
+ );
+ };
// The same bar as the editor and the processor, so search is one thing
// everywhere; settings results deep-link straight back into this page.
const searchScopes = useEditorSearchScopes();
@@ -191,7 +204,10 @@ const SettingsPageInner: React.FC = () => {
return (
<div className="settings-page" data-tour="settings-modal">
- <QuickNavHostBridge requestNavigation={requestNavigation} />
+ <QuickNavHostBridge
+ requestNavigation={requestNavigation}
+ onGoToStartupView={goToStartupView}
+ />
<aside
className={`settings-page__nav modal-nav ${isMobile ? "mobile" : ""}`}
diff --git a/frontend/editor/src/core/services/launchFiles.ts b/frontend/editor/src/core/services/launchFiles.ts
new file mode 100644
index 0000000000..84a63c8e6e
--- /dev/null
+++ b/frontend/editor/src/core/services/launchFiles.ts
@@ -0,0 +1,8 @@
+/**
+ * Whether files the OS handed this window ("open with") are still on their way in.
+ * Session restoration can reopen files, but must leave incoming files' selection and view alone.
+ * Only the desktop app is launched with files.
+ */
+export async function launchFilesPending(): Promise<boolean> {
+ return false;
+}
diff --git a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
index 5bf5076c8d..c62574498a 100644
--- a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
+++ b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts
@@ -138,7 +138,7 @@ export async function installTauri(page: Page) {
case "plugin:event|listen":
w.__listeners[args.event] = args.handler;
- return Object.keys(w.__listeners).length;
+ return args.handler;
case "plugin:event|unlisten":
return null;
@@ -174,8 +174,8 @@ export async function installTauri(page: Page) {
// `unlisten()` goes through this object, not __TAURI_INTERNALS__.
w.__TAURI_EVENT_PLUGIN_INTERNALS__ = {
- unregisterListener(event: string) {
- delete w.__listeners[event];
+ unregisterListener(event: string, eventId: number) {
+ if (w.__listeners[event] === eventId) delete w.__listeners[event];
},
};
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
index d23eeb4de9..a6b47db7c4 100644
--- a/frontend/editor/src/core/tests/stubbed/disk-link-imports.spec.ts
+++ b/frontend/editor/src/core/tests/stubbed/disk-link-imports.spec.ts
@@ -79,7 +79,6 @@ test("the sidebar native picker keeps its path after reload and saves in place",
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,
});
@@ -116,6 +115,67 @@ test("a Finder-open event stores the link during import", async ({ page }) => {
await expectLinked(page);
});
+for (const timing of ["reload", "running"] as const) {
+ test(`an OS-opened file joins existing files when ${timing}`, async ({
+ page,
+ }) => {
+ await page.getByTestId("files-button").click();
+ await expectLinked(page);
+ await expect(
+ page.getByRole("button", { name: "Close viewer", exact: true }),
+ ).toHaveCount(1);
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ JSON.parse(
+ sessionStorage.getItem("stirling.workbench.session") ?? "{}",
+ ).fileIds?.length,
+ ),
+ )
+ .toBe(1);
+
+ const incomingPath = "C:/Docs/incoming.pdf";
+ await setDisk(page, {
+ [PATH]: { bytes: BYTES, modifiedMs: MTIME },
+ [incomingPath]: { bytes: BYTES, modifiedMs: MTIME },
+ });
+ if (timing === "reload") {
+ await page.addInitScript(
+ (path) => Reflect.set(window, "__openedPaths", [path]),
+ incomingPath,
+ );
+ await page.reload();
+ await dismissModals(page);
+ } else {
+ 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,
+ });
+ }, incomingPath);
+ }
+
+ await expect(page.locator(".file-sidebar-file-item")).toHaveCount(2);
+ await expect(page.locator(".file-sidebar-file-item.selected")).toHaveCount(
+ 2,
+ );
+ await expect
+ .poll(() =>
+ page.evaluate(
+ () =>
+ JSON.parse(
+ sessionStorage.getItem("stirling.workbench.session") ?? "{}",
+ ).fileIds?.length,
+ ),
+ )
+ .toBe(2);
+ });
+}
+
test("an HTML file drop imports the native path", async ({ page }) => {
await page.locator(".file-sidebar").evaluate(
(node, { bytes, mtime }) => {
diff --git a/frontend/editor/src/desktop/components/session/WorkbenchSessionPersistence.tsx b/frontend/editor/src/desktop/components/session/WorkbenchSessionPersistence.tsx
deleted file mode 100644
index 2957ac3735..0000000000
--- a/frontend/editor/src/desktop/components/session/WorkbenchSessionPersistence.tsx
+++ /dev/null
@@ -1,4 +0,0 @@
-// Stub: desktop opens OS-launched files on boot; a session restore would collide with that.
-export function WorkbenchSessionPersistence() {
- return null;
-}
diff --git a/frontend/editor/src/desktop/hooks/useAppInitialization.ts b/frontend/editor/src/desktop/hooks/useAppInitialization.ts
index 0f2f97b3b0..e96be1cf4a 100644
--- a/frontend/editor/src/desktop/hooks/useAppInitialization.ts
+++ b/frontend/editor/src/desktop/hooks/useAppInitialization.ts
@@ -5,6 +5,7 @@ import { fileOpenService } from "@app/services/fileOpenService";
import { useFileManagement } from "@app/contexts/file/fileHooks";
import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";
import { captureDroppedFilePaths } from "@app/services/fileImportPaths";
+import { endLoadingLaunchFiles } from "@app/services/launchFiles";
/**
* App initialization hook
@@ -82,6 +83,8 @@ export function useAppInitialization(): void {
}
} catch (error) {
console.error("[Desktop] Failed to load opened files:", error);
+ } finally {
+ endLoadingLaunchFiles();
}
};
diff --git a/frontend/editor/src/desktop/hooks/useOpenedFile.test.tsx b/frontend/editor/src/desktop/hooks/useOpenedFile.test.tsx
new file mode 100644
index 0000000000..0a399a24df
--- /dev/null
+++ b/frontend/editor/src/desktop/hooks/useOpenedFile.test.tsx
@@ -0,0 +1,123 @@
+import { StrictMode } from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ getOpenedFiles: vi.fn<() => Promise<string[]>>(),
+ listen: vi.fn<() => Promise<() => void>>(),
+ beginLoading: vi.fn(),
+ endLoading: vi.fn(),
+}));
+
+vi.mock("@app/services/fileOpenService", () => ({
+ fileOpenService: { getOpenedFiles: mocks.getOpenedFiles },
+}));
+vi.mock("@tauri-apps/api/webviewWindow", () => ({
+ getCurrentWebviewWindow: () => ({ label: "main", listen: mocks.listen }),
+}));
+vi.mock("@app/services/launchFiles", () => ({
+ trackLaunchFilePop: <T,>(pop: Promise<T>) => pop,
+ beginLoadingLaunchFiles: mocks.beginLoading,
+ endLoadingLaunchFiles: mocks.endLoading,
+}));
+
+import { useOpenedFile } from "@app/hooks/useOpenedFile";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => (resolve = r));
+ return { promise, resolve };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getOpenedFiles.mockResolvedValue([]);
+ mocks.listen.mockResolvedValue(vi.fn());
+});
+
+describe("launch-file consumer lifetime", () => {
+ it("does not register files returned after the consumer unmounts", async () => {
+ const pop = deferred<string[]>();
+ mocks.getOpenedFiles.mockReturnValue(pop.promise);
+ const { unmount } = renderHook(useOpenedFile);
+ await waitFor(() => expect(mocks.getOpenedFiles).toHaveBeenCalledOnce());
+
+ unmount();
+ await act(async () => pop.resolve(["C:/late.pdf"]));
+
+ expect(mocks.beginLoading).not.toHaveBeenCalled();
+ expect(mocks.endLoading).not.toHaveBeenCalled();
+ });
+
+ it("releases an unconsumed batch when the consumer unmounts", async () => {
+ mocks.getOpenedFiles.mockResolvedValue(["C:/pending.pdf"]);
+ const { result, unmount } = renderHook(useOpenedFile);
+ await waitFor(() =>
+ expect(result.current.openedFilePaths).toEqual(["C:/pending.pdf"]),
+ );
+
+ unmount();
+
+ expect(mocks.beginLoading).toHaveBeenCalledOnce();
+ expect(mocks.endLoading).toHaveBeenCalledOnce();
+ });
+
+ it("leaves a consumed batch tracked until the loader finishes", async () => {
+ mocks.getOpenedFiles.mockResolvedValue(["C:/loading.pdf"]);
+ const { result, unmount } = renderHook(useOpenedFile);
+ await waitFor(() =>
+ expect(result.current.openedFilePaths).toEqual(["C:/loading.pdf"]),
+ );
+
+ act(() =>
+ expect(result.current.consumeOpenedFilePaths()).toEqual([
+ "C:/loading.pdf",
+ ]),
+ );
+ unmount();
+
+ expect(mocks.beginLoading).toHaveBeenCalledOnce();
+ expect(mocks.endLoading).not.toHaveBeenCalled();
+ });
+
+ it("releases a cleared batch only once", async () => {
+ mocks.getOpenedFiles.mockResolvedValue(["C:/cleared.pdf"]);
+ const { result, unmount } = renderHook(useOpenedFile);
+ await waitFor(() =>
+ expect(result.current.openedFilePaths).toEqual(["C:/cleared.pdf"]),
+ );
+
+ act(() => result.current.clearOpenedFilePaths());
+ unmount();
+
+ expect(mocks.endLoading).toHaveBeenCalledOnce();
+ });
+
+ it("removes an event listener that finishes registering after unmount", async () => {
+ const listener = deferred<() => void>();
+ const unlisten = vi.fn();
+ mocks.listen.mockReturnValue(listener.promise);
+ const { unmount } = renderHook(useOpenedFile);
+
+ unmount();
+ await act(async () => listener.resolve(unlisten));
+
+ expect(unlisten).toHaveBeenCalledOnce();
+ });
+
+ it("keeps launch files available through StrictMode effect replay", async () => {
+ mocks.getOpenedFiles
+ .mockResolvedValueOnce(["C:/launch.pdf"])
+ .mockResolvedValue([]);
+ const { result, unmount } = renderHook(useOpenedFile, {
+ wrapper: StrictMode,
+ });
+
+ await waitFor(() =>
+ expect(result.current.openedFilePaths).toEqual(["C:/launch.pdf"]),
+ );
+ expect(mocks.beginLoading).toHaveBeenCalledOnce();
+ unmount();
+ expect(mocks.endLoading).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/editor/src/desktop/hooks/useOpenedFile.ts b/frontend/editor/src/desktop/hooks/useOpenedFile.ts
index 1e2ddc7e64..0ebfb1b997 100644
--- a/frontend/editor/src/desktop/hooks/useOpenedFile.ts
+++ b/frontend/editor/src/desktop/hooks/useOpenedFile.ts
@@ -1,6 +1,11 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { fileOpenService } from "@app/services/fileOpenService";
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
+import {
+ beginLoadingLaunchFiles,
+ endLoadingLaunchFiles,
+ trackLaunchFilePop,
+} from "@app/services/launchFiles";
export function useOpenedFile() {
const [openedFilePaths, setOpenedFilePaths] = useState<string[]>([]);
@@ -8,6 +13,7 @@ export function useOpenedFile() {
const openedFilePathsRef = useRef<string[]>([]);
const clearOpenedFilePaths = useCallback(() => {
+ if (openedFilePathsRef.current.length > 0) endLoadingLaunchFiles();
openedFilePathsRef.current = [];
setOpenedFilePaths([]);
}, []);
@@ -20,11 +26,17 @@ export function useOpenedFile() {
}, []);
useEffect(() => {
- // Function to read and process files from storage
+ let disposed = false;
const readFilesFromStorage = async () => {
+ // StrictMode replays setup before this resumes; a discarded setup must not drain the queue.
+ await Promise.resolve();
+ if (disposed) return;
console.log("πŸ” Reading files from storage...");
try {
- const filePaths = await fileOpenService.getOpenedFiles();
+ const filePaths = await trackLaunchFilePop(
+ fileOpenService.getOpenedFiles(),
+ );
+ if (disposed) return;
console.log("πŸ” fileOpenService.getOpenedFiles() returned:", filePaths);
if (filePaths.length > 0) {
@@ -32,13 +44,16 @@ export function useOpenedFile() {
`βœ… Found ${filePaths.length} file(s) in storage:`,
filePaths,
);
+ // A batch replaced before it was consumed is never loaded.
+ if (openedFilePathsRef.current.length > 0) endLoadingLaunchFiles();
+ beginLoadingLaunchFiles();
openedFilePathsRef.current = filePaths;
setOpenedFilePaths(filePaths);
}
} catch (error) {
console.error("❌ Failed to read files from storage:", error);
} finally {
- setLoading(false);
+ if (!disposed) setLoading(false);
}
};
@@ -58,10 +73,16 @@ export function useOpenedFile() {
await readFilesFromStorage();
})
.then((unlistenFn) => {
- unlisten = unlistenFn;
+ if (disposed) unlistenFn();
+ else unlisten = unlistenFn;
});
return () => {
+ disposed = true;
+ if (openedFilePathsRef.current.length > 0) {
+ endLoadingLaunchFiles();
+ openedFilePathsRef.current = [];
+ }
if (unlisten) unlisten();
};
}, []);
diff --git a/frontend/editor/src/desktop/services/diskFileSync.test.ts b/frontend/editor/src/desktop/services/diskFileSync.test.ts
index 4fdd4efb35..539ea69235 100644
--- a/frontend/editor/src/desktop/services/diskFileSync.test.ts
+++ b/frontend/editor/src/desktop/services/diskFileSync.test.ts
@@ -204,6 +204,21 @@ describe("syncLinkedFileFromDisk", () => {
expect(result.status).toBe("conflict");
});
+ it("keeps a recorded conflict after the live editor state is lost on reload", async () => {
+ diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
+ const result = await syncLinkedFileFromDisk(
+ stub({ isDirty: false, diskConflictAt: 8000 }),
+ );
+ expect(result.status).toBe("conflict");
+ });
+
+ it("keeps a recorded conflict when disk metadata matches the saved baseline", async () => {
+ const result = await syncLinkedFileFromDisk(
+ stub({ isDirty: false, diskConflictAt: 8000 }),
+ );
+ expect(result.status).toBe("conflict");
+ });
+
it("keeps an open editor's edits, which no stub flag records", async () => {
// A page editor, annotation or redaction session is dirty long before any
// version exists to set isDirty, so disk must not simply win.
@@ -217,7 +232,7 @@ describe("syncLinkedFileFromDisk", () => {
// are the only bytes that version has.
diskState.state = { availability: "present", size: 3, modifiedMs: 9000 };
const result = await syncLinkedFileFromDisk(
- stub({ isLeaf: false, versionNumber: 1 }),
+ stub({ isLeaf: false, versionNumber: 1, diskConflictAt: 8000 }),
);
expect(result.status).toBe("superseded");
});
diff --git a/frontend/editor/src/desktop/services/diskFileSync.ts b/frontend/editor/src/desktop/services/diskFileSync.ts
index 11fdbd364f..c8a850fdc2 100644
--- a/frontend/editor/src/desktop/services/diskFileSync.ts
+++ b/frontend/editor/src/desktop/services/diskFileSync.ts
@@ -138,6 +138,9 @@ export async function syncLinkedFileFromDisk(
if (state.availability === "unavailable") {
return { status: "unavailable", reason: state.reason };
}
+ // Matching disk metadata does not resolve a recorded conflict after reload.
+ if (stub.isLeaf !== false && stub.diskConflictAt)
+ return { status: "conflict" };
if (!hasDiskChanged(stub, state)) return { status: "unchanged" };
// Deliberately below the missing and unavailable checks: a superseded version
// still wants its link state reported, it just must never be replaced.
diff --git a/frontend/editor/src/desktop/services/launchFiles.test.ts b/frontend/editor/src/desktop/services/launchFiles.test.ts
new file mode 100644
index 0000000000..ed49a98792
--- /dev/null
+++ b/frontend/editor/src/desktop/services/launchFiles.test.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const queue = vi.hoisted(() => ({ files: [] as string[] }));
+vi.mock("@tauri-apps/api/core", () => ({
+ invoke: vi.fn(async (command: string) =>
+ command === "get_opened_files" ? queue.files : undefined,
+ ),
+}));
+
+import {
+ beginLoadingLaunchFiles,
+ endLoadingLaunchFiles,
+ launchFilesPending,
+ trackLaunchFilePop,
+} from "@app/services/launchFiles";
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => (resolve = r));
+ return { promise, resolve };
+}
+
+describe("launchFilesPending", () => {
+ beforeEach(() => {
+ queue.files = [];
+ });
+
+ it("waits out a pop that comes back empty rather than yielding to it", async () => {
+ const pop = deferred<string[]>();
+ void trackLaunchFilePop(pop.promise);
+ const pending = launchFilesPending();
+ pop.resolve([]);
+ expect(await pending).toBe(false);
+ });
+
+ it("yields while popped files are still loading", async () => {
+ const pop = deferred<string[]>();
+ void trackLaunchFilePop(pop.promise).then((files) => {
+ if (files.length > 0) beginLoadingLaunchFiles();
+ });
+ const pending = launchFilesPending();
+ pop.resolve(["C:/doc.pdf"]);
+ expect(await pending).toBe(true);
+ endLoadingLaunchFiles();
+ expect(await launchFilesPending()).toBe(false);
+ });
+
+ it("yields to files still on the queue", async () => {
+ queue.files = ["C:/doc.pdf"];
+ expect(await launchFilesPending()).toBe(true);
+ });
+});
diff --git a/frontend/editor/src/desktop/services/launchFiles.ts b/frontend/editor/src/desktop/services/launchFiles.ts
new file mode 100644
index 0000000000..406b541d98
--- /dev/null
+++ b/frontend/editor/src/desktop/services/launchFiles.ts
@@ -0,0 +1,39 @@
+import { invoke } from "@tauri-apps/api/core";
+
+// Pops of the launch queue still awaiting their answer: until one comes back,
+// nothing says whether it carried files.
+const pops = new Set<Promise<unknown>>();
+// Batches popped with files that have not reached the workbench yet.
+let loading = 0;
+
+/** Registers a pop of the launch queue, so a restore waits to see what it carries. */
+export function trackLaunchFilePop<T>(pop: Promise<T>): Promise<T> {
+ pops.add(pop);
+ void pop.finally(() => pops.delete(pop)).catch(() => {});
+ return pop;
+}
+
+/** A pop came back with files; they are now on their way into the workbench. */
+export function beginLoadingLaunchFiles(): void {
+ loading++;
+}
+
+/** Those files reached the workbench, failed to, or were superseded. */
+export function endLoadingLaunchFiles(): void {
+ loading = Math.max(0, loading - 1);
+}
+
+/**
+ * Whether files the OS handed this app ("open with") are on their way in.
+ * Session restoration can reopen files, but must leave incoming files' selection and view alone.
+ */
+export async function launchFilesPending(): Promise<boolean> {
+ await Promise.allSettled([...pops]);
+ if (loading > 0) return true;
+ try {
+ // A peek: popping here would take the files from the window they are for.
+ return (await invoke<string[]>("get_opened_files")).length > 0;
+ } catch {
+ return false;
+ }
+}