#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Fix files not being selected properly when loading in some states (#8885)
James Brunton2762c84885a8
diff --git a/frontend/src/editor/core/components/fileEditor/FileEditor.tsx b/frontend/src/editor/core/components/fileEditor/FileEditor.tsxindex 3e7cb27502..a47c89795f 100644--- a/frontend/src/editor/core/components/fileEditor/FileEditor.tsx+++ b/frontend/src/editor/core/components/fileEditor/FileEditor.tsx@@ -264,7 +264,9 @@ const FileEditor = ({);if (result.success && result.extractedStubs.length > 0) {- await fileActions.addStirlingFileStubs(result.extractedStubs);+ await fileActions.addStirlingFileStubs(result.extractedStubs, {+ selectFiles: true,+ });removeFiles([fileId], false);diff --git a/frontend/src/editor/core/components/filesPage/FileManagerView.tsx b/frontend/src/editor/core/components/filesPage/FileManagerView.tsxindex e8a0609593..852b1be35d 100644--- a/frontend/src/editor/core/components/filesPage/FileManagerView.tsx+++ b/frontend/src/editor/core/components/filesPage/FileManagerView.tsx@@ -660,11 +660,12 @@ export default function FileManagerView() {);// Server-only stubs have no bytes in IDB; download + ingest first.- const materialized = await materializeServerStubs(toOpen, {- addFiles: fileActions.addFilesWithOptions,- updateStub: fileActions.updateStirlingFileStub,- });- if (materialized.length !== toOpen.length) {+ const { stubs: materialized, successfulSourceCount } =+ await materializeServerStubs(toOpen, {+ addFiles: fileActions.addFilesWithOptions,+ updateStub: fileActions.updateStirlingFileStub,+ });+ if (successfulSourceCount !== toOpen.length) {// Refresh successful imports even when another file fails.await refresh();return;@@ -672,7 +673,7 @@ export default function FileManagerView() {if (materialized.length > 0) {await fileActions.addStirlingFileStubs(materialized, {- selectFiles: false,+ selectFiles: true,});}@@ -896,11 +897,11 @@ export default function FileManagerView() {/** Cloud-only rows hold no bytes; pull them local before acting on them. */const localCopyOf = useCallback(async (file: StirlingFileStub): Promise<StirlingFileStub | null> => {- const [materialized] = await materializeServerStubs([file], {+ const { stubs } = await materializeServerStubs([file], {addFiles: fileActions.addFilesWithOptions,updateStub: fileActions.updateStirlingFileStub,});- return materialized ?? null;+ return stubs[0] ?? null;},[fileActions],);diff --git a/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx b/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsxindex f39fb26bca..4455d33169 100644--- a/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx+++ b/frontend/src/editor/core/components/filesPage/VersionHistoryModal.tsx@@ -76,7 +76,7 @@ export function VersionHistoryModal({.map((id) => stubById(id)).filter((s): s is StirlingFileStub => Boolean(s));if (stubs.length === 0) return;- void fileActions.addStirlingFileStubs(stubs);+ void fileActions.addStirlingFileStubs(stubs, { selectFiles: true });navActions.setWorkbench("fileEditor");onClose();},diff --git a/frontend/src/editor/core/components/shared/FileSidebar.tsx b/frontend/src/editor/core/components/shared/FileSidebar.tsxindex 69760d54e3..205ece747d 100644--- a/frontend/src/editor/core/components/shared/FileSidebar.tsx+++ b/frontend/src/editor/core/components/shared/FileSidebar.tsx@@ -903,14 +903,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(navActions.setWorkbench("fileEditor");}- await fileActions.addStirlingFileStubs([stub]);-- if (staysOnAdd) {- fileActions.setSelectedFiles([- ...state.ui.selectedFileIds,- stub.id,- ]);- } else {+ await fileActions.addStirlingFileStubs([stub], { selectFiles: true });++ if (!staysOnAdd) {if (workbenchCount === 0) {navActions.setWorkbench("viewer");} else {@@ -924,7 +919,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(lostFileIds,t,state.files.ids,- state.ui.selectedFileIds,fileActions,navActions,currentWorkbench,@@ -964,7 +958,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(if (state.files.ids.length > 0 && currentWorkbench === "viewer") {navActions.setWorkbench("fileEditor");}- await fileActions.addStirlingFileStubs([stub]);+ await fileActions.addStirlingFileStubs([stub], {+ selectFiles: true,+ });}// Route through pendingViewFileId so both setActiveFileIndex + setWorkbench fire together.diff --git a/frontend/src/editor/core/contexts/FileContext.tsx b/frontend/src/editor/core/contexts/FileContext.tsxindex 6336269903..6fd60d333c 100644--- a/frontend/src/editor/core/contexts/FileContext.tsx+++ b/frontend/src/editor/core/contexts/FileContext.tsx@@ -478,11 +478,11 @@ function FileContextInner({}, []);const selectFiles = (stirlingFiles: StirlingFile[]) => {- const currentSelection = stateRef.current.ui.selectedFileIds;- const newFileIds = stirlingFiles.map((stirlingFile) => stirlingFile.fileId);dispatch({- type: "SET_SELECTED_FILES",- payload: { fileIds: [...currentSelection, ...newFileIds] },+ type: "ADD_SELECTED_FILES",+ payload: {+ fileIds: stirlingFiles.map((stirlingFile) => stirlingFile.fileId),+ },});};diff --git a/frontend/src/editor/core/contexts/FilesModalContext.tsx b/frontend/src/editor/core/contexts/FilesModalContext.tsxindex 491ed628b5..a73f96dba3 100644--- a/frontend/src/editor/core/contexts/FilesModalContext.tsx+++ b/frontend/src/editor/core/contexts/FilesModalContext.tsx@@ -16,10 +16,10 @@ import {import { StirlingFileStub } from "@editor/types/fileContext";import type { FileId } from "@editor/types/file";import { fileStorage } from "@editor/services/fileStorage";+import { importShareBundle } from "@editor/services/shareBundleImportService";import apiClient from "@editor/services/apiClient";import {extractLatestFilesFromBundle,- getShareBundleEntryRootId,isZipBundle,loadShareBundleEntries,parseContentDispositionFilename,@@ -96,72 +96,29 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({? await loadShareBundleEntries(blob): null;if (bundle) {- const { manifest, rootOrder, sortedEntries, files } = bundle;-- const stirlingFiles = await actions.addFilesWithOptions(files, {- selectFiles: false,- autoUnzip: false,- skipAutoUnzip: false,- allowDuplicates: true,- });-- const idMap = new Map<string, FileId>();- for (let i = 0; i < stirlingFiles.length; i += 1) {- idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);- }-- const rootIdMap = new Map<string, FileId>();- for (const rootLogicalId of rootOrder) {- const mappedId = idMap.get(rootLogicalId);- if (mappedId) {- rootIdMap.set(rootLogicalId, mappedId);- }- }-const remoteUpdatedAt = remoteStorageUpdatedAt ?? Date.now();- for (const entry of sortedEntries) {- const newId = idMap.get(entry.logicalId);- if (!newId) continue;- const parentId = entry.parentLogicalId- ? idMap.get(entry.parentLogicalId)- : undefined;- const rootId =- rootIdMap.get(getShareBundleEntryRootId(manifest, entry)) ||- idMap.get(manifest.rootLogicalId) ||- newId;- const updates = {- versionNumber: entry.versionNumber,- originalFileId: rootId,- parentFileId: parentId,- toolHistory: entry.toolHistory,- isLeaf: entry.isLeaf,+ const currentFiles = await importShareBundle(+ bundle,+ {+ addFiles: (files) =>+ actions.addFilesWithOptions(files, {+ selectFiles: false,+ autoUnzip: false,+ skipAutoUnzip: false,+ allowDuplicates: true,+ }),+ updateStub: actions.updateStirlingFileStub,+ },+ {remoteStorageId,remoteStorageUpdatedAt: remoteUpdatedAt,remoteOwnerUsername,remoteOwnedByCurrentUser,remoteSharedViaLink,remoteShareToken,- };- actions.updateStirlingFileStub(newId, updates);- await fileStorage.updateFileMetadata(newId, updates);- }-- const selectedIds: FileId[] = [];- for (const rootId of rootOrder) {- const rootEntries = sortedEntries.filter(- (entry) => getShareBundleEntryRootId(manifest, entry) === rootId,- );- const latestEntry = rootEntries[rootEntries.length - 1];- if (!latestEntry) {- continue;- }- const latestId = idMap.get(latestEntry.logicalId);- if (latestId) {- selectedIds.push(latestId);- }- }-- return selectedIds;+ },+ );+ return currentFiles.map(({ file }) => file.fileId);}const file = new File([blob], filename, {diff --git a/frontend/src/editor/core/contexts/file/FileReducer.test.ts b/frontend/src/editor/core/contexts/file/FileReducer.test.tsindex b08811ff2c..bba1cb3eb9 100644--- a/frontend/src/editor/core/contexts/file/FileReducer.test.ts+++ b/frontend/src/editor/core/contexts/file/FileReducer.test.ts@@ -340,3 +340,35 @@ describe("fileContextReducer — REMOVE_FILES", () => {expect(next.ui.selectedFileIds).toEqual([]);});});++describe("fileContextReducer — ADD_SELECTED_FILES", () => {+ it("merges new selections without duplicating existing ones", () => {+ const start = {+ ...stateWith([stub("a"), stub("b")]),+ ui: {+ ...initialFileContextState.ui,+ selectedFileIds: ["a" as FileId],+ },+ };+ const next = fileContextReducer(start, {+ type: "ADD_SELECTED_FILES",+ payload: { fileIds: ["a" as FileId, "b" as FileId, "b" as FileId] },+ });+ expect(next.ui.selectedFileIds).toEqual(["a", "b"]);+ });++ it("does not let existing duplicates mask a new selection", () => {+ const start = {+ ...stateWith([stub("a"), stub("b")]),+ ui: {+ ...initialFileContextState.ui,+ selectedFileIds: ["a" as FileId, "a" as FileId],+ },+ };+ const next = fileContextReducer(start, {+ type: "ADD_SELECTED_FILES",+ payload: { fileIds: ["b" as FileId] },+ });+ expect(next.ui.selectedFileIds).toEqual(["a", "b"]);+ });+});diff --git a/frontend/src/editor/core/contexts/file/FileReducer.ts b/frontend/src/editor/core/contexts/file/FileReducer.tsindex 4690dd19d6..c28fa3a7ee 100644--- a/frontend/src/editor/core/contexts/file/FileReducer.ts+++ b/frontend/src/editor/core/contexts/file/FileReducer.ts@@ -275,6 +275,26 @@ export function fileContextReducer(};}+ case "ADD_SELECTED_FILES": {+ const { fileIds } = action.payload;+ const selectedFileIds = Array.from(+ new Set([...state.ui.selectedFileIds, ...fileIds]),+ );+ const selectionUnchanged =+ selectedFileIds.length === state.ui.selectedFileIds.length &&+ selectedFileIds.every(+ (fileId, index) => fileId === state.ui.selectedFileIds[index],+ );+ if (selectionUnchanged) return state;+ return {+ ...state,+ ui: {+ ...state.ui,+ selectedFileIds,+ },+ };+ }+case "SET_SELECTED_PAGES": {const { pageNumbers } = action.payload;return {diff --git a/frontend/src/editor/core/contexts/file/selectFiles.dedupe.test.tsx b/frontend/src/editor/core/contexts/file/selectFiles.dedupe.test.tsxnew file mode 100644index 0000000000..77fe9397e8--- /dev/null+++ b/frontend/src/editor/core/contexts/file/selectFiles.dedupe.test.tsx@@ -0,0 +1,83 @@+import { describe, expect, it, vi } from "vitest";+import { act, render } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { FileContextProvider } from "@editor/contexts/FileContext";+import {+ useFileActions,+ useFileSelection,+} from "@editor/contexts/file/fileHooks";+import type {+ FileContextActions,+ StirlingFileStub,+} from "@editor/types/fileContext";+import type { FileId } from "@editor/types/file";++// Selection updates can land in one React batch, so each add must merge in the+// reducer instead of replacing selections read from an earlier render.++vi.mock("@editor/services/fileStorage", async () => {+ const { createStirlingFile } = await import("@editor/types/fileContext");+ return {+ onRecordUnreadable: () => () => {},+ fileStorage: {+ init: vi.fn().mockResolvedValue(undefined),+ getAllStirlingFileStubs: vi.fn().mockResolvedValue([]),+ getStirlingFile: vi.fn(async (id: FileId) =>+ createStirlingFile(+ new File(["%PDF-1.7"], `${id}.pdf`, { type: "application/pdf" }),+ id,+ ),+ ),+ },+ };+});+vi.mock("@editor/utils/thumbnailUtils", () => ({+ generateThumbnailPairWithMetadata: () => new Promise(() => {}),+}));++function stub(id: string): StirlingFileStub {+ return {+ id: id as FileId,+ name: `${id}.pdf`,+ type: "application/pdf",+ size: 8,+ lastModified: 0,+ } as StirlingFileStub;+}++const FIRST = stub("a");+const SECOND = stub("b");++let actions: FileContextActions | null = null;+let selectedFileIds: FileId[] = [];++function Controller() {+ actions = useFileActions().actions;+ selectedFileIds = useFileSelection().selectedFileIds;+ return null;+}++describe("selecting added files", () => {+ it("merges back-to-back additions and lists an open file once", async () => {+ render(+ <MantineProvider>+ <FileContextProvider enableUrlSync={false}>+ <Controller />+ </FileContextProvider>+ </MantineProvider>,+ );++ await act(async () => {+ await Promise.all([+ actions?.addStirlingFileStubs([FIRST], { selectFiles: true }),+ actions?.addStirlingFileStubs([SECOND], { selectFiles: true }),+ ]);+ });+ expect(selectedFileIds).toEqual([FIRST.id, SECOND.id]);++ await act(async () => {+ await actions?.addStirlingFileStubs([FIRST], { selectFiles: true });+ });+ expect(selectedFileIds).toEqual([FIRST.id, SECOND.id]);+ });+});diff --git a/frontend/src/editor/core/services/fileSyncService.materialize.test.ts b/frontend/src/editor/core/services/fileSyncService.materialize.test.tsnew file mode 100644index 0000000000..963061653a--- /dev/null+++ b/frontend/src/editor/core/services/fileSyncService.materialize.test.ts@@ -0,0 +1,150 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { materializeServerStubs } from "@editor/services/fileSyncService";+import { createStirlingFile } from "@editor/types/fileContext";+import type { StirlingFile, StirlingFileStub } from "@editor/types/fileContext";+import type { FileId } from "@editor/types/file";++const mocks = vi.hoisted(() => ({+ apiGet: vi.fn(),+ loadShareBundleEntries: vi.fn(),+ updateFileMetadata: vi.fn(),+}));++vi.mock("@editor/services/apiClient", () => ({+ default: { get: mocks.apiGet },+}));++vi.mock("@editor/services/fileStorage", () => ({+ fileStorage: { updateFileMetadata: mocks.updateFileMetadata },+}));++vi.mock("@editor/components/toast", () => ({ alert: vi.fn() }));++vi.mock("@editor/services/shareBundleUtils", () => ({+ getShareBundleEntryRootId: (+ manifest: { rootLogicalId: string },+ entry: { rootLogicalId?: string },+ ) => entry.rootLogicalId || manifest.rootLogicalId,+ isZipBundle: () => true,+ loadShareBundleEntries: mocks.loadShareBundleEntries,+ parseContentDispositionFilename: () => null,+}));++function ingestedFile(id: string, name: string): StirlingFile {+ return createStirlingFile(+ new File([id], name, {+ type: "application/pdf",+ lastModified: 100,+ }),+ id as FileId,+ );+}++describe("materializeServerStubs", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.apiGet.mockResolvedValue({+ data: new Blob(["bundle"], { type: "application/zip" }),+ headers: { "content-type": "application/zip" },+ });+ });++ it("returns the current file from every root in a server bundle", async () => {+ const entries = [+ {+ logicalId: "root-a",+ rootLogicalId: "root-a",+ versionNumber: 1,+ name: "a-v1.pdf",+ type: "application/pdf",+ size: 1,+ lastModified: 1,+ filePath: "files/a-v1.pdf",+ isLeaf: false,+ },+ {+ logicalId: "a-v2",+ rootLogicalId: "root-a",+ parentLogicalId: "root-a",+ versionNumber: 2,+ name: "a-v2.pdf",+ type: "application/pdf",+ size: 1,+ lastModified: 2,+ filePath: "files/a-v2.pdf",+ isLeaf: true,+ },+ {+ logicalId: "root-b",+ rootLogicalId: "root-b",+ versionNumber: 1,+ name: "b.pdf",+ type: "application/pdf",+ size: 1,+ lastModified: 1,+ filePath: "files/b.pdf",+ isLeaf: true,+ },+ ];+ const bundleFiles = entries.map(+ (entry) =>+ new File([entry.logicalId], entry.name, {+ type: entry.type,+ lastModified: entry.lastModified,+ }),+ );+ mocks.loadShareBundleEntries.mockResolvedValue({+ manifest: {+ schemaVersion: 1,+ rootLogicalId: "root-a",+ rootLogicalIds: ["root-a", "root-b"],+ createdAt: 1,+ entries,+ },+ rootOrder: ["root-a", "root-b"],+ sortedEntries: entries,+ files: bundleFiles,+ });++ const ingested = [+ ingestedFile("local-a-v1", "a-v1.pdf"),+ ingestedFile("local-a-v2", "a-v2.pdf"),+ ingestedFile("local-b", "b.pdf"),+ ];+ const addFiles = vi.fn().mockResolvedValue(ingested);+ const updateStub = vi.fn();+ const source: StirlingFileStub = {+ id: "server-9" as FileId,+ originalFileId: "server-9",+ name: "shared-files.zip",+ type: "application/zip",+ size: 10,+ lastModified: 1,+ versionNumber: 1,+ isLeaf: true,+ remoteStorageId: 9,+ };++ const result = await materializeServerStubs([source], {+ addFiles,+ updateStub,+ });++ expect(result.successfulSourceCount).toBe(1);+ expect(result.stubs.map((stub) => stub.id)).toEqual([+ "local-a-v2",+ "local-b",+ ]);+ expect(result.stubs.map((stub) => stub.originalFileId)).toEqual([+ "local-a-v1",+ "local-b",+ ]);+ expect(result.stubs.map((stub) => stub.name)).toEqual([+ "a-v2.pdf",+ "b.pdf",+ ]);+ expect(updateStub).toHaveBeenCalledTimes(3);+ expect(mocks.updateFileMetadata).toHaveBeenCalledTimes(3);+ });+});diff --git a/frontend/src/editor/core/services/fileSyncService.ts b/frontend/src/editor/core/services/fileSyncService.tsindex 837deb1582..946bb094e0 100644--- a/frontend/src/editor/core/services/fileSyncService.ts+++ b/frontend/src/editor/core/services/fileSyncService.ts@@ -13,6 +13,7 @@ import { StirlingFileStub, StirlingFile } from "@editor/types/fileContext";import { FileId } from "@editor/types/fileContext";import { FolderId, parseFolderId } from "@editor/types/folder";import { virtualFolderStorage } from "@editor/services/virtualFolderStorage";+import { importShareBundle } from "@editor/services/shareBundleImportService";import {isZipBundle,loadShareBundleEntries,@@ -402,14 +403,19 @@ export async function reconcileServerFiles(/*** Download bytes for any server-only stubs (id starts with "server-") and- * ingest them into IDB. Returns a stub list where the server-only entries- * are replaced with proper local stubs that point to the freshly-cached- * IDB rows. Local stubs are passed through untouched.+ * ingest them into IDB. Returns local stubs for every current file produced+ * by the inputs, plus the number of source stubs that materialized. Local+ * stubs are passed through untouched.** Pass `addFiles` (from FileContext.addFilesWithOptions) and* `updateStub` (from FileContext.updateStirlingFileStub) so this util* stays React-free; the caller provides the wiring.*/+export interface MaterializedServerStubsResult {+ stubs: StirlingFileStub[];+ successfulSourceCount: number;+}+export async function materializeServerStubs(stubs: StirlingFileStub[],helpers: {@@ -425,8 +431,9 @@ export async function materializeServerStubs() => Promise<StirlingFile[]>;updateStub: (id: FileId, updates: Partial<StirlingFileStub>) => void;},-): Promise<StirlingFileStub[]> {+): Promise<MaterializedServerStubsResult> {const out: StirlingFileStub[] = [];+ let successfulSourceCount = 0;// Collect per-stub failures so we can surface ONE summarized toast at the// end instead of N popups (or worse, silently dropping files from the grid// with zero user signal as the previous code did).@@ -442,6 +449,7 @@ export async function materializeServerStubs(typeof stub.remoteShareToken === "string";if (!isServerStub && !isSharedStub) {out.push(stub);+ successfulSourceCount += 1;continue;}try {@@ -481,20 +489,6 @@ export async function materializeServerStubs(const bundle = isZipBundle(contentType, filename)? await loadShareBundleEntries(blob).catch(() => null): null;- const files: File[] = bundle- ? bundle.files- : [new File([blob], filename, { type: contentType || blob.type })];-- const ingested = await helpers.addFiles(files, {- selectFiles: false,- autoUnzip: false,- skipAutoUnzip: true,- allowDuplicates: true,- skipUploadTracking: true,- });- if (ingested.length === 0) continue;- const primary = ingested[ingested.length - 1];- const newId = primary.fileId;const remoteUpdates = {// The ingest above made a new local file, which starts in no folder. Without// carrying membership across, materialising a file to open it moves it to the@@ -509,9 +503,65 @@ export async function materializeServerStubs(remoteHasShareLinks: stub.remoteHasShareLinks,remoteShareToken: isSharedStub ? stub.remoteShareToken : undefined,};- helpers.updateStub(newId, remoteUpdates);- await fileStorage.updateFileMetadata(newId, remoteUpdates);- out.push({ ...stub, ...remoteUpdates, id: newId, originalFileId: newId });++ if (bundle) {+ const currentFiles = await importShareBundle(+ bundle,+ {+ addFiles: (files) =>+ helpers.addFiles(files, {+ selectFiles: false,+ autoUnzip: false,+ skipAutoUnzip: true,+ allowDuplicates: true,+ skipUploadTracking: true,+ }),+ updateStub: helpers.updateStub,+ },+ remoteUpdates,+ );+ if (currentFiles.length === 0) continue;+ for (const { file, updates } of currentFiles) {+ out.push({+ ...stub,+ id: file.fileId,+ name: file.name,+ type: file.type,+ size: file.size,+ lastModified: file.lastModified,+ quickKey: file.quickKey,+ ...updates,+ });+ }+ } else {+ const ingested = await helpers.addFiles(+ [new File([blob], filename, { type: contentType || blob.type })],+ {+ selectFiles: false,+ autoUnzip: false,+ skipAutoUnzip: true,+ allowDuplicates: true,+ skipUploadTracking: true,+ },+ );+ if (ingested.length === 0) continue;+ const primary = ingested[ingested.length - 1];+ const newId = primary.fileId;+ helpers.updateStub(newId, remoteUpdates);+ await fileStorage.updateFileMetadata(newId, remoteUpdates);+ out.push({+ ...stub,+ ...remoteUpdates,+ id: newId,+ name: primary.name,+ type: primary.type,+ size: primary.size,+ lastModified: primary.lastModified,+ quickKey: primary.quickKey,+ originalFileId: newId,+ });+ }+ successfulSourceCount += 1;} catch (err) {console.warn("[fileSyncService] failed to materialize server stub", err);const status = (err as { response?: { status?: number } })?.response@@ -538,7 +588,10 @@ export async function materializeServerStubs(bodyText = i18n.t("fileSync.openFailed.singleWithStatus",`Couldn't open "{{name}}" (HTTP {{status}}).`,- { name: first.name, status: first.status },+ {+ name: first.name,+ status: first.status,+ },);} else {bodyText = i18n.t(@@ -559,5 +612,5 @@ export async function materializeServerStubs(durationMs: 5000,});}- return out;+ return { stubs: out, successfulSourceCount };}diff --git a/frontend/src/editor/core/services/shareBundleImportService.ts b/frontend/src/editor/core/services/shareBundleImportService.tsnew file mode 100644index 0000000000..23d4773b6c--- /dev/null+++ b/frontend/src/editor/core/services/shareBundleImportService.ts@@ -0,0 +1,77 @@+import { fileStorage } from "@editor/services/fileStorage";+import {+ getShareBundleEntryRootId,+ type LoadedShareBundle,+} from "@editor/services/shareBundleUtils";+import type { FileId } from "@editor/types/file";+import type { StirlingFile, StirlingFileStub } from "@editor/types/fileContext";++interface ShareBundleImportHelpers {+ addFiles: (files: File[]) => Promise<StirlingFile[]>;+ updateStub: (id: FileId, updates: Partial<StirlingFileStub>) => void;+ isCancelled?: () => boolean;+}++export interface ImportedShareBundleFile {+ file: StirlingFile;+ updates: Partial<StirlingFileStub>;+}++/** Ingests every bundle version and returns the current file for each root. */+export async function importShareBundle(+ bundle: LoadedShareBundle,+ helpers: ShareBundleImportHelpers,+ additionalUpdates: Partial<StirlingFileStub> = {},+): Promise<ImportedShareBundleFile[]> {+ const ingested = await helpers.addFiles(bundle.files);+ if (helpers.isCancelled?.()) return [];++ const ingestedByLogicalId = new Map(+ bundle.sortedEntries.flatMap((entry, index) => {+ const file = ingested[index];+ return file ? [[entry.logicalId, file] as const] : [];+ }),+ );+ const rootFileIds = new Map(+ bundle.rootOrder.flatMap((rootLogicalId) => {+ const file = ingestedByLogicalId.get(rootLogicalId);+ return file ? [[rootLogicalId, file.fileId] as const] : [];+ }),+ );+ const updatesByLogicalId = new Map<string, Partial<StirlingFileStub>>();+ const currentEntryByRoot = new Map<+ string,+ LoadedShareBundle["sortedEntries"][number]+ >();++ for (const entry of bundle.sortedEntries) {+ const file = ingestedByLogicalId.get(entry.logicalId);+ if (!file) continue;+ const rootLogicalId = getShareBundleEntryRootId(bundle.manifest, entry);+ const updates: Partial<StirlingFileStub> = {+ ...additionalUpdates,+ versionNumber: entry.versionNumber,+ originalFileId:+ rootFileIds.get(rootLogicalId) ??+ ingestedByLogicalId.get(bundle.manifest.rootLogicalId)?.fileId ??+ file.fileId,+ parentFileId: entry.parentLogicalId+ ? ingestedByLogicalId.get(entry.parentLogicalId)?.fileId+ : undefined,+ toolHistory: entry.toolHistory,+ isLeaf: entry.isLeaf,+ };+ updatesByLogicalId.set(entry.logicalId, updates);+ currentEntryByRoot.set(rootLogicalId, entry);+ helpers.updateStub(file.fileId, updates);+ await fileStorage.updateFileMetadata(file.fileId, updates);+ }++ return bundle.rootOrder.flatMap((rootLogicalId) => {+ const currentEntry = currentEntryByRoot.get(rootLogicalId);+ if (!currentEntry) return [];+ const file = ingestedByLogicalId.get(currentEntry.logicalId);+ const updates = updatesByLogicalId.get(currentEntry.logicalId);+ return file && updates ? [{ file, updates }] : [];+ });+}diff --git a/frontend/src/editor/core/services/shareBundleUtils.ts b/frontend/src/editor/core/services/shareBundleUtils.tsindex 11be8886c7..43b2f68d0e 100644--- a/frontend/src/editor/core/services/shareBundleUtils.ts+++ b/frontend/src/editor/core/services/shareBundleUtils.ts@@ -108,12 +108,16 @@ function loadJSZip(): Promise<typeof JSZipClass> {return jsZipPromise;}-export async function loadShareBundleEntries(blob: Blob): Promise<{+export interface LoadedShareBundle {manifest: ShareBundleManifest;rootOrder: string[];sortedEntries: ShareBundleManifest["entries"];files: File[];-} | null> {+}++export async function loadShareBundleEntries(+ blob: Blob,+): Promise<LoadedShareBundle | null> {const JSZip = await loadJSZip();const zip = await JSZip.loadAsync(blob);const manifestEntry = zip.file(MANIFEST_FILENAME);diff --git a/frontend/src/editor/core/tests/stubbed/workbench-save-selection.spec.ts b/frontend/src/editor/core/tests/stubbed/workbench-save-selection.spec.tsnew file mode 100644index 0000000000..b4f8fa958b--- /dev/null+++ b/frontend/src/editor/core/tests/stubbed/workbench-save-selection.spec.ts@@ -0,0 +1,83 @@+import { test, expect } from "@editor/tests/helpers/stub-test-base";+import type { Locator, Page } from "@playwright/test";+import path from "path";+import {+ openRecents,+ switchView,+ uploadFiles,+} from "@editor/tests/helpers/ui-helpers";++// Active Files has no selection UI, so its hidden selection must cover every+// open file: Save acts on the selection whenever there is one.++test.use({ filesViewMode: "grid" });++const FIXTURES_DIR = path.join(import.meta.dirname, "../test-fixtures");+const STORED = "sample.pdf";+const UPLOADED = "multi-page-sample.pdf";++function row(page: Page, name: string): Locator {+ return page.locator(".file-sidebar-file-item").filter({ hasText: name });+}++const IN_WORKBENCH = /(^|\s)selected(\s|$)/;++async function closeIntoLibrary(page: Page, name: string): Promise<void> {+ await uploadFiles(page, path.join(FIXTURES_DIR, name));+ await row(page, name).locator(".file-sidebar-file-name").click();+ await expect(row(page, name)).not.toHaveClass(IN_WORKBENCH);+}++// Browser multi-download policies differ, so record what Save hands the+// browser rather than whether the browser accepts every file.+async function recordDownloads(page: Page): Promise<() => Promise<string[]>> {+ await page.evaluate(() => {+ const names: string[] = [];+ Reflect.set(window, "__downloadNames", names);+ const click = HTMLAnchorElement.prototype.click;+ HTMLAnchorElement.prototype.click = function (this: HTMLAnchorElement) {+ if (this.download) names.push(this.download);+ click.call(this);+ };+ });+ return () =>+ page.evaluate(() =>+ [...(Reflect.get(window, "__downloadNames") as string[])].sort(),+ );+}++const reopenStored: Record<string, (page: Page) => Promise<void>> = {+ "its sidebar row": (page) =>+ row(page, STORED).locator(".file-sidebar-file-name").click(),+ "its sidebar eye button": async (page) => {+ await row(page, STORED).hover();+ await row(page, STORED).locator(".file-sidebar-eye-btn").click();+ },+ "the file library": async (page) => {+ await openRecents(page);+ await page+ .locator(".files-page-card")+ .filter({ hasText: STORED })+ .dblclick();+ await expect(page).not.toHaveURL(/\/files/);+ },+};++for (const [via, reopen] of Object.entries(reopenStored)) {+ test(`Save covers a stored file reopened from ${via} and an uploaded one`, async ({+ page,+ }) => {+ await closeIntoLibrary(page, STORED);++ await reopen(page);+ await expect(row(page, STORED)).toHaveClass(IN_WORKBENCH);+ await uploadFiles(page, path.join(FIXTURES_DIR, UPLOADED));+ await expect(row(page, UPLOADED)).toHaveClass(IN_WORKBENCH);++ await switchView(page, "Active Files");+ const downloads = await recordDownloads(page);+ await page.getByRole("button", { name: /^Download (All|Files)$/ }).click();++ await expect.poll(downloads).toEqual([UPLOADED, STORED].sort());+ });+}diff --git a/frontend/src/editor/core/types/fileContext.ts b/frontend/src/editor/core/types/fileContext.tsindex 4a68be476f..6286f0a964 100644--- a/frontend/src/editor/core/types/fileContext.ts+++ b/frontend/src/editor/core/types/fileContext.ts@@ -384,6 +384,7 @@ export type FileContextAction =// UI actions| { type: "SET_SELECTED_FILES"; payload: { fileIds: FileId[] } }+ | { type: "ADD_SELECTED_FILES"; payload: { fileIds: FileId[] } }| { type: "SET_SELECTED_PAGES"; payload: { pageNumbers: number[] } }| { type: "CLEAR_SELECTIONS" }| {diff --git a/frontend/src/editor/desktop/hooks/useOpenWindowFiles.ts b/frontend/src/editor/desktop/hooks/useOpenWindowFiles.tsindex 3377da02d8..0ad921007a 100644--- a/frontend/src/editor/desktop/hooks/useOpenWindowFiles.ts+++ b/frontend/src/editor/desktop/hooks/useOpenWindowFiles.ts@@ -43,7 +43,7 @@ export function useOpenWindowFiles() {}// Download + ingest any server-only stubs first; local stubs pass through.- const materialized = await materializeServerStubs(stubs, {+ const { stubs: materialized } = await materializeServerStubs(stubs, {addFiles: actions.addFilesWithOptions,updateStub: actions.updateStirlingFileStub,});diff --git a/frontend/src/editor/proprietary/components/notifications/notificationActions.test.tsx b/frontend/src/editor/proprietary/components/notifications/notificationActions.test.tsxindex 16dcb45ace..eac6aa23b8 100644--- a/frontend/src/editor/proprietary/components/notifications/notificationActions.test.tsx+++ b/frontend/src/editor/proprietary/components/notifications/notificationActions.test.tsx@@ -207,7 +207,9 @@ describe("useNotificationActions", () => {it("opens the failed tool on the failed document alone, in the viewer", async () => {await registry().OPEN_IN_TOOL?.run(context());- expect(addStirlingFileStubs).toHaveBeenCalledWith([h.stub]);+ expect(addStirlingFileStubs).toHaveBeenCalledWith([h.stub], {+ selectFiles: true,+ });expect(setActiveFileId).toHaveBeenCalledWith("f-1");// The viewer scopes the tool to this one file. Any other view would hand it the whole// workbench, so a retry on one failed document would re-run across every open file.@@ -278,7 +280,9 @@ describe("useNotificationActions", () => {await registry().VIEW_FILE?.run(context());// Selecting alone shows nothing: the workbench holds neither the file nor the viewer yet.- expect(addStirlingFileStubs).toHaveBeenCalledWith([h.stub]);+ expect(addStirlingFileStubs).toHaveBeenCalledWith([h.stub], {+ selectFiles: true,+ });expect(setActiveFileId).toHaveBeenCalledWith("f-1");expect(setWorkbench).toHaveBeenCalledWith("viewer");});diff --git a/frontend/src/editor/proprietary/components/notifications/notificationActions.ts b/frontend/src/editor/proprietary/components/notifications/notificationActions.tsindex dd531573a0..e47b9b7f3a 100644--- a/frontend/src/editor/proprietary/components/notifications/notificationActions.ts+++ b/frontend/src/editor/proprietary/components/notifications/notificationActions.ts@@ -114,7 +114,9 @@ export function useNotificationActions(): ClientActionRegistry {.getState().files.ids.some((id) => (id as string) === fileId);if (!alreadyOpen) {- await fileContext.actions.addStirlingFileStubs([stub]);+ await fileContext.actions.addStirlingFileStubs([stub], {+ selectFiles: true,+ });}viewer.setActiveFileId(fileId);// The viewer is what scopes a tool to one document; every other view hands it all of them.diff --git a/frontend/src/editor/proprietary/routes/ShareLinkLoader.tsx b/frontend/src/editor/proprietary/routes/ShareLinkLoader.tsxindex 731f4773b2..135672d600 100644--- a/frontend/src/editor/proprietary/routes/ShareLinkLoader.tsx+++ b/frontend/src/editor/proprietary/routes/ShareLinkLoader.tsx@@ -8,11 +8,10 @@ import { useFileActions } from "@editor/contexts/FileContext";import { useNavigationActions } from "@editor/contexts/NavigationContext";import { alert } from "@editor/components/toast";import type { StirlingFile } from "@editor/types/fileContext";-import type { FileId } from "@editor/types/file";import { fileStorage } from "@editor/services/fileStorage";+import { importShareBundle } from "@editor/services/shareBundleImportService";import { EDITOR_BASENAME } from "@editor/routes/editorBasename";import {- getShareBundleEntryRootId,isZipBundle,loadShareBundleEntries,parseContentDispositionFilename,@@ -96,39 +95,20 @@ export default function ShareLinkLoader({ token }: ShareLinkLoaderProps) {if (isZipBundle(contentTypeValue, filename)) {const bundle = await loadShareBundleEntries(blob);if (bundle) {- const { manifest, rootOrder, sortedEntries, files } = bundle;- const stirlingFiles = await actions.addFilesWithOptions(files, {- selectFiles: false,- autoUnzip: false,- skipAutoUnzip: false,- allowDuplicates: true,- });- if (signal.aborted) return;-- const idMap = new Map<string, FileId>();- for (let i = 0; i < stirlingFiles.length; i += 1) {- idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);- }-- const rootIdMap = new Map<string, FileId>();- for (const rootLogicalId of rootOrder) {- const mappedId = idMap.get(rootLogicalId);- if (mappedId) {- rootIdMap.set(rootLogicalId, mappedId);- }- }- for (let i = 0; i < sortedEntries.length; i += 1) {- const entry = sortedEntries[i];- const newId = idMap.get(entry.logicalId);- if (!newId) continue;- const parentId = entry.parentLogicalId- ? idMap.get(entry.parentLogicalId)- : undefined;- const rootId =- rootIdMap.get(getShareBundleEntryRootId(manifest, entry)) ||- idMap.get(manifest.rootLogicalId) ||- newId;- const sharedUpdates = {+ const currentFiles = await importShareBundle(+ bundle,+ {+ addFiles: (files) =>+ actions.addFilesWithOptions(files, {+ selectFiles: false,+ autoUnzip: false,+ skipAutoUnzip: false,+ allowDuplicates: true,+ }),+ updateStub: actions.updateStirlingFileStub,+ isCancelled: () => signal.aborted,+ },+ {remoteStorageId: shareMetadata?.fileId,remoteOwnerUsername: shareMetadata?.owner ?? undefined,remoteOwnedByCurrentUser: false,@@ -136,40 +116,11 @@ export default function ShareLinkLoader({ token }: ShareLinkLoaderProps) {remoteSharedViaLink: true,remoteHasShareLinks: false,remoteShareToken: shareMetadata?.shareToken || normalizedToken,- };- actions.updateStirlingFileStub(newId, {- versionNumber: entry.versionNumber,- originalFileId: rootId,- parentFileId: parentId,- toolHistory: entry.toolHistory,- isLeaf: entry.isLeaf,- ...sharedUpdates,- });- await fileStorage.updateFileMetadata(newId, {- versionNumber: entry.versionNumber,- originalFileId: rootId,- parentFileId: parentId,- toolHistory: entry.toolHistory,- isLeaf: entry.isLeaf,- ...sharedUpdates,- });- }+ },+ );+ if (signal.aborted) return;- const selectedIds: FileId[] = [];- for (const rootId of rootOrder) {- const rootEntries = sortedEntries.filter(- (entry) =>- getShareBundleEntryRootId(manifest, entry) === rootId,- );- const latestEntry = rootEntries[rootEntries.length - 1];- if (!latestEntry) {- continue;- }- const latestId = idMap.get(latestEntry.logicalId);- if (latestId) {- selectedIds.push(latestId);- }- }+ const selectedIds = currentFiles.map(({ file }) => file.fileId);if (selectedIds.length > 0) {actions.setSelectedFiles(selectedIds);}diff --git a/frontend/src/editor/proprietary/services/shareLinkImport.ts b/frontend/src/editor/proprietary/services/shareLinkImport.tsindex 8badcbfeea..889f033e6f 100644--- a/frontend/src/editor/proprietary/services/shareLinkImport.ts+++ b/frontend/src/editor/proprietary/services/shareLinkImport.ts@@ -3,8 +3,8 @@ import { fileStorage } from "@editor/services/fileStorage";import type { FileId } from "@editor/types/file";import type { StirlingFile } from "@editor/types/fileContext";import type { FileContextActions } from "@editor/types/fileContext";+import { importShareBundle } from "@editor/services/shareBundleImportService";import {- getShareBundleEntryRootId,isZipBundle,loadShareBundleEntries,parseContentDispositionFilename,@@ -68,27 +68,6 @@ export async function importShareLinkToWorkbench(if (isZipBundle(contentTypeValue, filename)) {const bundle = await loadShareBundleEntries(blob);if (bundle) {- const { manifest, rootOrder, sortedEntries, files } = bundle;- const stirlingFiles = await actions.addFilesWithOptions(files, {- selectFiles: false,- autoUnzip: false,- skipAutoUnzip: false,- allowDuplicates: true,- });-- const idMap = new Map<string, FileId>();- for (let i = 0; i < stirlingFiles.length; i += 1) {- idMap.set(sortedEntries[i].logicalId, stirlingFiles[i].fileId);- }-- const rootIdMap = new Map<string, FileId>();- for (const rootLogicalId of rootOrder) {- const mappedId = idMap.get(rootLogicalId);- if (mappedId) {- rootIdMap.set(rootLogicalId, mappedId);- }- }-const sharedUpdates = {remoteStorageId: shareMetadata?.fileId,remoteOwnerUsername: shareMetadata?.owner ?? undefined,@@ -98,45 +77,21 @@ export async function importShareLinkToWorkbench(remoteHasShareLinks: false,remoteShareToken: shareMetadata?.shareToken || token,};-- for (const entry of sortedEntries) {- const newId = idMap.get(entry.logicalId);- if (!newId) continue;- const parentId = entry.parentLogicalId- ? idMap.get(entry.parentLogicalId)- : undefined;- const rootId =- rootIdMap.get(getShareBundleEntryRootId(manifest, entry)) ||- idMap.get(manifest.rootLogicalId) ||- newId;- const updates = {- versionNumber: entry.versionNumber,- originalFileId: rootId,- parentFileId: parentId,- toolHistory: entry.toolHistory,- isLeaf: entry.isLeaf,- ...sharedUpdates,- };- actions.updateStirlingFileStub(newId, updates);- await fileStorage.updateFileMetadata(newId, updates);- }-- const selectedIds: FileId[] = [];- for (const rootId of rootOrder) {- const rootEntries = sortedEntries.filter(- (entry) => getShareBundleEntryRootId(manifest, entry) === rootId,- );- const latestEntry = rootEntries[rootEntries.length - 1];- if (!latestEntry) {- continue;- }- const latestId = idMap.get(latestEntry.logicalId);- if (latestId) {- selectedIds.push(latestId);- }- }-- return selectedIds;+ const currentFiles = await importShareBundle(+ bundle,+ {+ addFiles: (files) =>+ actions.addFilesWithOptions(files, {+ selectFiles: false,+ autoUnzip: false,+ skipAutoUnzip: false,+ allowDuplicates: true,+ }),+ updateStub: actions.updateStirlingFileStub,+ },+ sharedUpdates,+ );+ return currentFiles.map(({ file }) => file.fileId);}}