#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
Rebuild Add files around the file library (#8060)
Reece Brownef4d9383bba4a
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 7245893e57..12dd45fc83 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -195,9 +195,6 @@ title = "What it does"[AddAttachmentsRequest.tooltip.header]title = "About Add Attachments"-[addFileCard]-upload = "Upload"-[addImage]applySignatures = "Apply Images"header = "Add images to PDFs"@@ -4264,9 +4261,6 @@ subtitle = "Import bookmarks, build hierarchies, and apply the outline without cdescription = "Select the Edit Table of Contents tool to load its workspace."title = "Open the tool to start editing"-[emptyFilesState]-upload = "Upload"-[encryptedPdfUnlock]description = "This PDF is password protected. Enter the password so you can continue working with it."emptyResponse = "Password removal did not produce a file."@@ -4347,107 +4341,66 @@ closeFile = "Close file"addFiles = "Add Files"[fileManager]-active = "Active"addToUpload = "Add to Upload"-changesNotUploaded = "Changes not uploaded"clearAll = "Clear All"clearSelection = "Clear"-closeAllFiles = "Close all files"-closeFile = "Close File"-cloudFile = "Cloud file"-copyCreated = "Copy saved to this device."-copyFailed = "Could not create a copy."delete = "Delete"deleteAll = "Delete All"-deleteSelected = "Delete Files"-deselectAll = "Uncheck All"-details = "File Details"download = "Download"downloadSelected = "Download Files"-dropFilesHere = "Drop files here"-fileFormat = "Format"-fileHistory = "File History"-fileName = "Name"-fileSize = "Size"filesSelected = "files"filesStored = "files stored"-fileVersion = "Version"-filterAll = "All"-filterLocal = "Local"-filterSharedByMe = "Shared by me"-filterSharedWithMe = "Shared with me"-googleDrive = "Google Drive"-googleDriveNotAvailable = "Google Drive integration not available"-googleDriveShort = "Drive"-hideHistory = "Hide History"-lastModified = "Last Modified"-lastSynced = "Last synced"-leaveShare = "Remove from my list"-leaveShareFailed = "Could not remove the shared file."-leaveShareSuccess = "Removed from your shared list."loadingFiles = "Loading files..."-localOnly = "Local only"-makeCopy = "Make a copy"-mobileShort = "Mobile"-mobileUpload = "Mobile Upload"-mobileUploadNotAvailable = "Mobile upload not enabled"-moreOptions = "More options"-nextFile = "Next file"noFiles = "No files available"noFilesFound = "No files found matching your search"-noRecentFiles = "No recent files found"-openFile = "Open File"-openFiles = "Open Files"openInFileEditor = "Open in File Editor"openInPageEditor = "Open in Page Editor"-owner = "Owner"-ownerUnknown = "Unknown"-previousFile = "Previous file"-recent = "Recent"-removeBoth = "Remove from both"-removeFilePrompt = "This file is saved on this device and on your server. Where would you like to remove it from?"-removeFileTitle = "Remove file"-removeLocalOnly = "This device only"-removeServerFailed = "Could not remove the file from the server."-removeServerOnly = "Server only"-removeServerOnlyPrompt = "This file is stored only on your server. Would you like to remove it from the server?"-removeServerSuccess = "Removed from server."-removeSharedPrompt = "This file is shared with you. You can remove it from this device or your shared list."-removeSharedServerOnlyBlockedPrompt = "This file is shared with you and stored only on the server."-removeSharedServerOnlyPrompt = "This file is shared with you and stored only on the server. Remove it from your list?"-restore = "Restore"saveSelected = "Save Files"searchFiles = "Search files..."-selectAll = "Check All"-selectedCount = "{{count}} checked"share = "Share"shared = "Shared"-sharedByYou = "Shared by you"sharedEditNoticeBody = "You do not have edit rights to the server version of this file. Any edits you make will be saved as a local copy."sharedEditNoticeConfirm = "Got it"sharedEditNoticeTitle = "Read-only server copy"sharedWithYou = "Shared with you"-shareSelected = "Share Files"-sharing = "Sharing"showAll = "Show All"-showHistory = "Show History"sortBy = "Sort files"sortByDate = "Sort by Date"sortByName = "Sort by Name"sortBySize = "Sort by Size"storage = "Storage"-storageState = "Storage"storageUsed = "Storage used"-synced = "Synced"title = "Upload PDF Files"-toolChain = "Tools Applied"unsupported = "Unsupported"unzip = "Unzip"updateOnServer = "Update on Server"-uploadSelected = "Upload Files"uploadToServer = "Upload to Server"versionHistory = "Version history"+[filePicker]+add_one = "Add {{count}} file"+add_other = "Add {{count}} files"+addHere = "Add here"+adding = "Adding files…"+chooseDestination = "Choose a folder, or add here."+dropHint = "Choose the files you want to work with."+dropTitle = "Drop files here, or click to browse"+emptyZip = "No files could be extracted from this ZIP."+error = "Could not add these files. Please try again."+errorTitle = "Couldn't add files"+filesUnavailable = "Could not add: {{names}}"+fileUnavailable = "{{name}} is no longer available."+folderPath = "Folder path"+fromComputer = "From your computer"+fromPhone = "From your phone"+limit = "Choose up to {{count}} files."+selectedLimit = "{{count}} of {{limit}} selected"+selectVersion = "Select version {{version}}"+sources = "File sources"+subtitle = "Choose from your library or add something new."+title = "Add files"+unsupported = "This file type isn't supported by the selected tool."+[files]addFiles = "Add files"created = "Created"@@ -4533,9 +4486,13 @@ save = "Rename"title = "Rename file"[filesPage]+addedToLibrary = "Added to Stirling library"+addingToLibrary = "Adding to Stirling library…"+addToLibrary = "Add to Stirling library…"+addToLibraryFailed = "Some files could not be added"addToWorkspace = "Add to workspace"addToWorkspaceCount = "Add {{count}} to workspace"-allFiles = "All files"+allFiles = "Stirling library"back = "Back"backToFolder = "Back to {{folder}}"backToMyFiles = "Back to File library"@@ -4563,7 +4520,7 @@ deleteFolderContents_one = "Also delete {{count}} file inside the folder"deleteFolderContents_other = "Also delete {{count}} files inside the folder"deleteFolderContentsWarning = "Files will be permanently removed and cannot be recovered."deleteFolderError = "Could not delete the folder. Try again."-deleteFolderKeepHint = "Files inside will be moved to All files."+deleteFolderKeepHint = "Files inside will be moved to Stirling library."deleteFolderTitle = "Delete folder?"deselectAll = "Clear selection"details = "Details"@@ -4574,7 +4531,7 @@ download = "Download"downloadAll = "Download all"downloadVersion = "Download this version"dropOverlay = "Drop files to upload"-dropOverlaySub = "Files land in Local. Organize them into folders any time."+dropOverlaySub = "Files appear in Recents. Organize them into folders any time."dropOverlaySubFolder = "They'll be added to this folder."duplicate = "Duplicate"file = "File"@@ -4588,7 +4545,6 @@ folderSettings = "Folder settings"inPath = "in {{path}}"inWorkspace = "Open"inWorkspaceAria = "Already in workspace"-loading = "Loading…"localFolderManagedByDisk = "This folder is managed by its directory on disk."moveAcrossKindsBlocked = "These folders live in different places, so one can't go inside the other."moveIntoMountCloudSkipped_one = "{{count}} server file stayed in your files. It lives on the server, not on this disk."@@ -4602,11 +4558,12 @@ moveSkippedRemote_other = "{{count}} files couldn't be moved on the server (no pmoveTo = "Move to…"newFolder = "New folder"newFolderStorageDisabled = "Server folder storage isn't enabled."-newFolderTabUnavailable = "Switch to All or Cloud to create folders."+newFolderTabUnavailable = "Switch to Stirling library to create folders."offlineNoFolderEdits = "Server folder sync unavailable - folder changes are disabled. Check sign-in and storage configuration."open = "Open"openVersionInWorkspace = "Open in workspace"originFilter = "Filter by source"+recentFiles = "Recents"refresh = "Refresh"refreshNeedsConnection = "Sign in to refresh from the server."remove = "Delete"@@ -4620,6 +4577,7 @@ saveToServer = "Save to server"saveToServerDisabledHint = "Saving to the server isn't enabled on this server. Ask your admin to enable it."selectAll = "Select all"selectedCount = "{{count}} selected"+selectedFile = "{{name}}, selected"selectFile = "Select file {{name}}"serverFolderNeedsConnection = "Sign in to Stirling Cloud or connect a self-hosted server to use server folders."shareDisabledHint = "File sharing isn't enabled on this server. Ask your admin to enable it."@@ -4652,6 +4610,7 @@ title = "Appearance"useColour = "Use color {{c}}"[filesPage.column]+added = "Added"modified = "Modified"name = "Name"size = "Size"@@ -4803,9 +4762,10 @@ serverHint = "Synced to your account, available wherever you sign in."all = "All sources"cloud = "Cloud"cloudHint = "Stored on the Stirling server"+diskFileHint = "Stored on your computer"diskHint = "A file in the mounted folder on your disk"local = "Local"-localHint = "Only stored in this browser"+localHint = "Not backed up"shared = "Shared"sharedHint = "Shared with you via link"@@ -4834,9 +4794,9 @@ back = "Back"cancel = "Cancel"[filesPage.search]-clear = "Clear filter"-label = "Filter files by name"-placeholder = "Filter files…"+clear = "Clear search"+label = "Search filenames"+placeholder = "Search filenames…"[filesPage.sort]label = "Sort files"@@ -4852,9 +4812,6 @@ client = "Folder sync failed."network = "Could not reach the server."server = "Server error during folder sync."-[filesPage.tabName]-local = "Local"-[filesPage.treeMenu]actions = "Folder actions for {{name}}"delete = "Delete folder"@@ -10394,7 +10351,7 @@ server = "Server storage"serverAction = "Or add a new folder to your server"settings = "Adjust settings"signInRequired = "Sign in to set up folder processing"-title = "Set up folder processing"+title = "Process a folder"useExisting = "Use existing folder"viewLabels = "View classification labels"@@ -12036,7 +11993,6 @@ commenterHint = "Commenting is coming soon."copied = "Link copied to clipboard"copy = "Copy"copyFailed = "Copy failed"-copyLink = "Copy share link"createdAt = "Created"description = "Create a share link for this file. Signed-in users with the link can access it."download = "Download"diff --git a/frontend/editor/src/core/components/FileManager.tsx b/frontend/editor/src/core/components/FileManager.tsxindex 6361d9d4a8..ad3899457a 100644--- a/frontend/editor/src/core/components/FileManager.tsx+++ b/frontend/editor/src/core/components/FileManager.tsx@@ -1,255 +1,31 @@-import React, { useState, useCallback, useEffect, useMemo } from "react";-import { Modal } from "@mantine/core";-import { Dropzone } from "@mantine/dropzone";-import { StirlingFileStub } from "@app/types/fileContext";-import type { FileId } from "@app/types/file";-import { useFileManager } from "@app/hooks/useFileManager";+import { useState } from "react";import { useFilesModalContext } from "@app/contexts/FilesModalContext";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import MobileLayout from "@app/components/fileManager/MobileLayout";-import DesktopLayout from "@app/components/fileManager/DesktopLayout";-import DragOverlay from "@app/components/fileManager/DragOverlay";-import { FileManagerProvider } from "@app/contexts/FileManagerContext";-import { Z_INDEX_FILE_MANAGER_MODAL } from "@app/styles/zIndex";-import {- isGoogleDriveConfigured,- extractGoogleDriveBackendConfig,-} from "@app/services/googleDrivePickerService";-import { loadScript } from "@app/utils/scriptLoader";-import { useAllFiles } from "@app/contexts/FileContext";-import { useFileActions } from "@app/contexts/file/fileHooks";+import { LibraryFilePicker } from "@app/components/filesPage/LibraryFilePicker";+import { LibraryPickerModal } from "@app/components/filesPage/LibraryPickerModal";-/**- * Structural prop: anything that exposes an optional `supportedFormats`- * string array. Both `Tool` (from `@app/types/tool`) and `ToolRegistryEntry`- * (from `@app/data/toolsTaxonomy`) satisfy this, so callers can pass either- * without an `as any` cast.- */interface FileManagerProps {selectedTool?: { supportedFormats?: string[] } | null;}-const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {- const {- isFilesModalOpen,- closeFilesModal,- onFileUpload,- onRecentFileSelect,- maxSelectable,- } = useFilesModalContext();- const { config } = useAppConfig();- const [recentFiles, setRecentFiles] = useState<StirlingFileStub[]>([]);- const [isDragging, setIsDragging] = useState(false);- const [isMobile, setIsMobile] = useState(false);-- const { loadRecentFiles, handleRemoveFile, loading } = useFileManager();- const { actions: fileActions } = useFileActions();-- // Get active file IDs from FileContext to show which files are already loaded- const { fileIds: activeFileIds } = useAllFiles();-- // File management handlers- const isFileSupported = useCallback(- (fileName: string) => {- if (!selectedTool?.supportedFormats) return true;- const extension = fileName.split(".").pop()?.toLowerCase();- return selectedTool.supportedFormats.includes(extension || "");- },- [selectedTool?.supportedFormats],- );-- const refreshRecentFiles = useCallback(async () => {- const files = await loadRecentFiles();- setRecentFiles(files);- }, [loadRecentFiles]);-- const handleRecentFilesSelected = useCallback(- async (files: StirlingFileStub[]) => {- try {- // Use StirlingFileStubs directly - preserves all metadata!- onRecentFileSelect(files);- } catch (error) {- console.error("Failed to process selected files:", error);- }- },- [onRecentFileSelect],- );-- const handleNewFileUpload = useCallback(- async (files: File[]) => {- if (files.length > 0) {- try {- // Files will get IDs assigned through onFilesSelect -> FileContext addFiles- onFileUpload(files);- await refreshRecentFiles();- } catch (error) {- console.error("Failed to process dropped files:", error);- }- }- },- [onFileUpload, refreshRecentFiles],- );-- const handleRemoveFileByIndex = useCallback(- async (index: number) => {- await handleRemoveFile(- index,- recentFiles,- setRecentFiles,- (fileId) => {- fileActions.removeFiles([fileId], false);- },- refreshRecentFiles,- );- },- [handleRemoveFile, recentFiles, fileActions, refreshRecentFiles],- );-- const handleBulkRemove = useCallback((fileIds: FileId[]) => {- const idSet = new Set(fileIds as string[]);- setRecentFiles((prev) => prev.filter((f) => !idSet.has(f.id as string)));- }, []);-- useEffect(() => {- const checkMobile = () => setIsMobile(window.innerWidth < 1030);- checkMobile();- window.addEventListener("resize", checkMobile);- return () => window.removeEventListener("resize", checkMobile);- }, []);-- useEffect(() => {- if (isFilesModalOpen) {- refreshRecentFiles();- } else {- // Reset state when modal is closed- setIsDragging(false);- }- }, [isFilesModalOpen, refreshRecentFiles]);-- // Cleanup any blob URLs when component unmounts- useEffect(() => {- return () => {- // StoredFileMetadata doesn't have blob URLs, so no cleanup needed- // Blob URLs are managed by FileContext and tool operations- console.log(- "FileManager unmounting - FileContext handles blob URL cleanup",- );- };- }, []);-- // Preload Google Drive scripts if configured- // Use useMemo to only track Google Drive config changes, not all config updates- const googleDriveBackendConfig = useMemo(- () => extractGoogleDriveBackendConfig(config),- [- config?.googleDriveEnabled,- config?.googleDriveClientId,- config?.googleDriveApiKey,- config?.googleDriveAppId,- ],- );-- useEffect(() => {- if (isGoogleDriveConfigured(googleDriveBackendConfig)) {- // Load scripts in parallel without blocking- Promise.all([- loadScript({- src: "https://apis.google.com/js/api.js",- id: "gapi-script",- async: true,- defer: true,- }),- loadScript({- src: "https://accounts.google.com/gsi/client",- id: "gis-script",- async: true,- defer: true,- }),- ]).catch((error) => {- console.warn("Failed to preload Google Drive scripts:", error);- });- }- }, [googleDriveBackendConfig]);-- // Modal size constants for consistent scaling- const modalHeight = "80vh";- const modalWidth = isMobile ? "100%" : "80vw";- const modalMaxWidth = isMobile ? "100%" : "1200px";- const modalMaxHeight = "1200px";- const modalMinWidth = isMobile ? "320px" : "800px";-+/** Unmounting discards tentative selections; file ingestion remains owned by FilesModalContext. */+export default function FileManager({ selectedTool }: FileManagerProps) {+ const { isFilesModalOpen, closeFilesModal } = useFilesModalContext();+ const [busy, setBusy] = useState(false);+ const [externalPickerOpen, setExternalPickerOpen] = useState(false);return (- <Modal+ <LibraryPickerModalopened={isFilesModalOpen}onClose={closeFilesModal}- size={isMobile ? "100%" : "auto"}- centered- radius="md"- className="overflow-hidden p-0"- withCloseButton={false}- zIndex={Z_INDEX_FILE_MANAGER_MODAL}- styles={{- content: {- position: "relative",- margin: isMobile ? "1rem" : "2rem",- },- body: { padding: 0 },- header: { display: "none" },- }}+ busy={busy}+ externalPickerOpen={externalPickerOpen}>- <div- data-tour="files-modal"- style={{- position: "relative",- height: modalHeight,- width: modalWidth,- maxWidth: modalMaxWidth,- maxHeight: modalMaxHeight,- minWidth: modalMinWidth,- margin: "0 auto",- overflow: "hidden",- }}- >- <Dropzone- onDrop={handleNewFileUpload}- onDragEnter={() => setIsDragging(true)}- onDragLeave={() => setIsDragging(false)}- multiple={true}- activateOnClick={false}- style={{- height: "100%",- width: "100%",- border: "none",- borderRadius: "var(--radius-md)",- backgroundColor: "var(--c-bg)",- }}- styles={{- inner: { pointerEvents: "all" },- }}- >- <FileManagerProvider- recentFiles={recentFiles}- onRecentFilesSelected={handleRecentFilesSelected}- onNewFilesSelect={handleNewFileUpload}- onClose={closeFilesModal}- isFileSupported={isFileSupported}- isOpen={isFilesModalOpen}- maxSelectable={maxSelectable}- onFileRemove={handleRemoveFileByIndex}- onBulkRemove={handleBulkRemove}- modalHeight={modalHeight}- refreshRecentFiles={refreshRecentFiles}- isLoading={loading}- activeFileIds={activeFileIds}- >- {isMobile ? <MobileLayout /> : <DesktopLayout />}- </FileManagerProvider>- </Dropzone>-- <DragOverlay isVisible={isDragging} />- </div>- </Modal>+ {isFilesModalOpen && (+ <LibraryFilePicker+ supportedFormats={selectedTool?.supportedFormats}+ onBusyChange={setBusy}+ onExternalPickerChange={setExternalPickerOpen}+ />+ )}+ </LibraryPickerModal>);-};--export default FileManager;+}diff --git a/frontend/editor/src/core/components/fileEditor/AddFileCard.tsx b/frontend/editor/src/core/components/fileEditor/AddFileCard.tsxindex 8138e4b895..696b47cd02 100644--- a/frontend/editor/src/core/components/fileEditor/AddFileCard.tsx+++ b/frontend/editor/src/core/components/fileEditor/AddFileCard.tsx@@ -1,4 +1,4 @@-import React, { useRef, useState } from "react";+import React from "react";import { Group } from "@mantine/core";import { Button } from "@app/ui/Button";import { useTranslation } from "react-i18next";@@ -6,191 +6,77 @@ import { useFilesModalContext } from "@app/contexts/FilesModalContext";import { Wordmark } from "@app/components/shared/Wordmark";import styles from "@app/components/fileEditor/FileEditor.module.css";import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";-import { openFilesFromDisk } from "@app/services/openFilesFromDisk";-import { Icon } from "@app/ui/Icon";-interface AddFileCardProps {- onFileSelect: (files: File[]) => void;- accept?: string;- multiple?: boolean;-}-const AddFileCard = ({- onFileSelect,- accept,- multiple = true,-}: AddFileCardProps) => {+const AddFileCard = () => {const { t } = useTranslation();- const fileInputRef = useRef<HTMLInputElement>(null);const { openFilesModal } = useFilesModalContext();- const [isUploadHover, setIsUploadHover] = useState(false);const terminology = useFileActionTerminology();- const icons = useFileActionIcons();const handleCardClick = () => {openFilesModal();};- const handleNativeUploadClick = async (e: React.MouseEvent) => {- e.stopPropagation();- const files = await openFilesFromDisk({- multiple,- onFallbackOpen: () => fileInputRef.current?.click(),- });- if (files.length > 0) {- onFileSelect(files);- }- };-const handleOpenFilesModal = (e: React.MouseEvent) => {e.stopPropagation();openFilesModal();};- const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {- const files = Array.from(event.target.files || []);- if (files.length > 0) {- onFileSelect(files);- }- // Reset input so same files can be selected again- event.target.value = "";- };-return (- <>- <input- ref={fileInputRef}- type="file"- accept={accept}- multiple={multiple}- onChange={handleFileChange}- style={{ display: "none" }}- />-- <div- className={`${styles.addFileCard} select-none flex flex-col transition-all relative cursor-pointer`}- tabIndex={0}- role="button"- aria-label={t("fileEditor.addFiles", "Add files")}- onClick={handleCardClick}- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- handleCardClick();- }- }}- >- {/* Main content area */}- <div className={styles.addFileContent}>- {/* Stirling PDF Branding */}- <Group gap="xs" align="center">- <Wordmark- alt="Stirling PDF"- muted- style={{ height: "2.2rem", width: "auto" }}- />- </Group>+ <div+ className={`${styles.addFileCard} select-none flex flex-col transition-all relative cursor-pointer`}+ tabIndex={0}+ role="button"+ aria-label={t("fileEditor.addFiles", "Add files")}+ onClick={handleCardClick}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ handleCardClick();+ }+ }}+ >+ <div className={styles.addFileContent}>+ <Group gap="xs" align="center">+ <Wordmark+ alt="Stirling PDF"+ muted+ style={{ height: "2.2rem", width: "auto" }}+ />+ </Group>- {/* Add Files + Native Upload Buttons - styled like LandingPage */}- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "center",- gap: "0.6rem",- width: "100%",- marginTop: "0.8rem",- marginBottom: "0.8rem",- }}- onMouseLeave={() => setIsUploadHover(false)}- >- {!isUploadHover && (- <Button- variant="tertiary"- style={{- backgroundColor: "var(--landing-button-bg)",- color: "var(--c-accent-fg)",- border: "1px solid var(--landing-button-border)",- borderRadius: "2rem",- height: "38px",- paddingLeft: "1rem",- paddingRight: "1rem",- width: "calc(100% - 58px - 0.6rem)",- display: "flex",- alignItems: "center",- justifyContent: "center",- transition: "width .5s ease, padding .5s ease",- }}- onClick={handleOpenFilesModal}- onMouseEnter={() => setIsUploadHover(false)}- >- <Icon- name="plus"- size="1.5rem"- className="text-[var(--c-primary)]"- />- <span>{t("landing.addFiles", "Add Files")}</span>- </Button>- )}- <Button- variant="tertiary"- aria-label={t("addFileCard.upload", "Upload")}- title={terminology.uploadFromComputer}- style={{- backgroundColor: "var(--landing-button-bg)",- color: "var(--c-accent-fg)",- border: "1px solid var(--landing-button-border)",- borderRadius: "1rem",- height: "38px",- width: isUploadHover ? "100%" : "58px",- minWidth: "58px",- paddingLeft: isUploadHover ? "1rem" : 0,- paddingRight: isUploadHover ? "1rem" : 0,- display: "flex",- alignItems: "center",- justifyContent: "center",- transition: "width .5s ease, padding .5s ease",- overflow: "hidden",- }}- onClick={handleNativeUploadClick}- onMouseEnter={() => setIsUploadHover(true)}- >- <Icon- name={icons.upload}- size="1.25rem"- style={{ color: "var(--c-accent-text)", flexShrink: 0 }}- />- {isUploadHover && (- <span- style={{- marginLeft: ".5rem",- whiteSpace: "nowrap",- overflow: "hidden",- textOverflow: "ellipsis",- minWidth: 0,- }}- >- {terminology.uploadFromComputer}- </span>- )}- </Button>- </div>+ <Button+ variant="tertiary"+ style={{+ backgroundColor: "var(--landing-button-bg)",+ color: "var(--c-accent-fg)",+ border: "1px solid var(--landing-button-border)",+ borderRadius: "2rem",+ height: "38px",+ paddingLeft: "1rem",+ paddingRight: "1rem",+ width: "100%",+ marginTop: "0.8rem",+ marginBottom: "0.8rem",+ }}+ onClick={handleOpenFilesModal}+ >+ <Icon name="plus" size="1.5rem" className="text-[var(--c-primary)]" />+ <span>{terminology.addFiles}</span>+ </Button>- {/* Instruction Text */}- <span- style={{- fontSize: ".8rem",- textAlign: "center",- marginTop: "0.5rem",- color: "var(--c-text-muted)",- }}- >- {terminology.dropFilesHere}- </span>- </div>+ <span+ style={{+ fontSize: ".8rem",+ textAlign: "center",+ marginTop: "0.5rem",+ color: "var(--c-text-muted)",+ }}+ >+ {terminology.dropFilesHere}+ </span></div>- </>+ </div>);};diff --git a/frontend/editor/src/core/components/fileEditor/FileEditor.tsx b/frontend/editor/src/core/components/fileEditor/FileEditor.tsxindex edf132ba8a..eeee41a1f0 100644--- a/frontend/editor/src/core/components/fileEditor/FileEditor.tsx+++ b/frontend/editor/src/core/components/fileEditor/FileEditor.tsx@@ -20,6 +20,7 @@ import { alert } from "@app/components/toast";import { downloadFileWithPolicy as downloadFile } from "@app/services/exportWithPolicy";import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";import { usePolicyFileBadges } from "@app/hooks/usePolicyFileBadges";+import { useDropzoneFiles } from "@app/hooks/useDropzoneFiles";import type { FileItemPolicyRef } from "@app/components/shared/PolicyBadges";const EMPTY_POLICIES: FileItemPolicyRef[] = [];@@ -37,7 +38,6 @@ const FileEditor = ({}: FileEditorProps) => {const policyFileBadges = usePolicyFileBadges();- // Utility function to check if a file extension is supportedconst isFileSupported = useCallback((fileName: string): boolean => {const extension = detectFileExtension(fileName);@@ -46,36 +46,29 @@ const FileEditor = ({[supportedExtensions],);- // Use optimized FileContext hooksconst { state, selectors } = useFileState();const { addFiles, removeFiles, reorderFiles } = useFileManagement();const { actions: fileActions } = useFileActions();const { selectedFileIds, setSelectedFiles } = useFileSelection();- // Extract needed values from state (memoized to prevent infinite loops)const activeStirlingFileStubs = useMemo(() => selectors.getStirlingFileStubs(),[state.files.byId, state.files.ids],);- // Always-current refs so callbacks can read the latest stubs/selection without- // closing over them as deps — prevents every callback from regenerating whenever- // any stub changes (e.g. thumbnail load), which would bust React.memo on every thumbnail.+ // Stable callbacks read current stubs and selection without invalidating memoized thumbnails.const stubsRef = useRef(activeStirlingFileStubs);stubsRef.current = activeStirlingFileStubs;const selectedFileIdsRef = useRef(selectedFileIds);selectedFileIdsRef.current = selectedFileIds;- // Get navigation actionsconst { actions: navActions } = useNavigationActions();- // Get viewer context for setting active file index and IDconst { setActiveFileIndex, setActiveFileId } = useViewer();const [_status, _setStatus] = useState<string | null>(null);const [_error, _setError] = useState<string | null>(null);- // Toast helpersconst showStatus = useCallback((message: string,@@ -99,32 +92,23 @@ const FileEditor = ({});}, []);- // Current tool (for enforcing maxFiles limits)const { selectedTool } = useToolWorkflow();- // Compute effective max allowed files based on the active tool and modeconst maxAllowed = useMemo<number>(() => {const rawMax = selectedTool?.maxFiles;return !toolMode || rawMax == null || rawMax < 0 ? Infinity : rawMax;}, [selectedTool?.maxFiles, toolMode]);+ const getDropzoneFiles = useDropzoneFiles();const [showFilePickerModal, setShowFilePickerModal] = useState(false);- // Process uploaded files using context- // ZIP extraction is now handled automatically in FileContext based on user preferencesconst handleFileUpload = useCallback(async (uploadedFiles: File[]) => {_setError(null);try {if (uploadedFiles.length > 0) {- // FileContext will automatically handle ZIP extraction based on user preferences- // - Respects autoUnzip setting- // - Respects autoUnzipFileLimit- // - HTML ZIPs stay intact- // - Non-ZIP files pass through unchangedawait addFiles(uploadedFiles, { selectFiles: true });- // After auto-selection, enforce maxAllowed if neededif (Number.isFinite(maxAllowed)) {const nowSelectedIds = selectors.getSelectedStirlingFileStubs()@@ -145,19 +129,16 @@ const FileEditor = ({[addFiles, showStatus, showError, selectors, maxAllowed, setSelectedFiles],);- // Enforce maxAllowed when tool changes or when an external action sets too many selected filesuseEffect(() => {if (Number.isFinite(maxAllowed) && selectedFileIds.length > maxAllowed) {setSelectedFiles(selectedFileIds.slice(-maxAllowed));}}, [maxAllowed, selectedFileIds, setSelectedFiles]);- // File reordering handler for drag and dropconst handleReorderFiles = useCallback((sourceFileId: FileId, targetFileId: FileId, selectedFileIds: FileId[]) => {const currentIds = stubsRef.current.map((r) => r.id);- // Find indicesconst sourceIndex = currentIds.findIndex((id) => id === sourceFileId);const targetIndex = currentIds.findIndex((id) => id === targetFileId);@@ -166,13 +147,11 @@ const FileEditor = ({return;}- // Handle multi-file selection reorderingconst filesToMove =selectedFileIds.length > 1? selectedFileIds.filter((id) => currentIds.includes(id)): [sourceFileId];- // Create new orderconst newOrder = [...currentIds];// Remove files to move from their current positions (in reverse order to maintain indices)@@ -184,31 +163,19 @@ const FileEditor = ({newOrder.splice(index, 1);});- // Calculate insertion index after removalslet insertIndex = newOrder.findIndex((id) => id === targetFileId);if (insertIndex !== -1) {- // Determine if moving forward or backwardconst isMovingForward = sourceIndex < targetIndex;if (isMovingForward) {- // Moving forward: insert after targetinsertIndex += 1;- } else {- // Moving backward: insert before target (insertIndex already correct)}} else {- // Target was moved, insert at endinsertIndex = newOrder.length;}- // Insert files at the calculated positionnewOrder.splice(insertIndex, 0, ...filesToMove);- // Animate the reorder using the View Transitions API where available.- // Each FileEditorThumbnail carries a stable `view-transition-name`, so- // the browser snapshots each card before and after the DOM reorder and- // interpolates the positions automatically. `flushSync` forces React to- // apply the reorderFiles dispatch synchronously inside the transition- // callback so the BEFORE/AFTER snapshots capture the correct frames.+ // flushSync commits the reorder inside the view transition so its snapshots capture both layouts.const applyReorder = () => reorderFiles(newOrder);const docWithViewTransition = document as Document & {startViewTransition?: (cb: () => void) => unknown;@@ -221,14 +188,12 @@ const FileEditor = ({applyReorder();}- // Update statusconst moveCount = filesToMove.length;showStatus(`${moveCount > 1 ? `${moveCount} files` : "File"} reordered`);},[reorderFiles, showStatus],);- // File operations using contextconst handleCloseFile = useCallback((fileId: FileId) => {const record = stubsRef.current.find((r) => r.id === fileId);@@ -266,7 +231,6 @@ const FileEditor = ({isDirty: record.isDirty,savedPath: result.savedPath,});- // Mark file as clean after successful save to diskif (result.savedPath) {console.log("[FileEditor] Marking file as clean:", fileId);fileActions.updateStirlingFileStub(fileId, {@@ -290,17 +254,14 @@ const FileEditor = ({const file = record ? selectors.getFile(record.id) : null;if (record && file) {try {- // Extract and store files using shared service methodconst result = await zipFileService.extractAndStoreFilesWithHistory(file,record,);if (result.success && result.extractedStubs.length > 0) {- // Add extracted file stubs to FileContextawait fileActions.addStirlingFileStubs(result.extractedStubs);- // Remove the original ZIP fileremoveFiles([fileId], false);alert({@@ -348,8 +309,6 @@ const FileEditor = ({if (selectedFiles.length === 0) return;try {- // Use FileContext to handle loading stored files- // The files are already in FileContext, just need to add them to active filesshowStatus(`Loaded ${selectedFiles.length} files from storage`);} catch (err) {console.error("Error loading files from storage:", err);@@ -360,6 +319,8 @@ const FileEditor = ({return (<DropzoneonDrop={handleFileUpload}+ useFsAccessApi={false}+ getFilesFromEvent={getDropzoneFiles}multiple={true}maxSize={2 * 1024 * 1024 * 1024}style={{@@ -376,7 +337,7 @@ const FileEditor = ({<Box p="md">{activeStirlingFileStubs.length === 0 ? (<Center h="60vh">- <AddFileCard onFileSelect={handleFileUpload} />+ <AddFileCard /></Center>) : (<div@@ -388,12 +349,8 @@ const FileEditor = ({pointerEvents: "auto",}}>- {/* Add File Card - only show when files exist */}{activeStirlingFileStubs.length > 0 && (- <AddFileCard- key="add-file-card"- onFileSelect={handleFileUpload}- />+ <AddFileCard key="add-file-card" />)}{activeStirlingFileStubs.map((record, index) => {@@ -418,7 +375,6 @@ const FileEditor = ({)}</Box>- {/* File Picker Modal */}<FilePickerModalopened={showFilePickerModal}onClose={() => setShowFilePickerModal(false)}diff --git a/frontend/editor/src/core/components/fileManager/CompactFileDetails.stories.tsx b/frontend/editor/src/core/components/fileManager/CompactFileDetails.stories.tsxdeleted file mode 100644index 760b4b7781..0000000000--- a/frontend/editor/src/core/components/fileManager/CompactFileDetails.stories.tsx+++ /dev/null@@ -1,68 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import CompactFileDetails from "@app/components/fileManager/CompactFileDetails";-import type { StirlingFileStub } from "@app/types/fileContext";-import type { FileId } from "@app/types/file";--const buildFileStub = (- overrides: Partial<StirlingFileStub> = {},-): StirlingFileStub => ({- id: "file-1" as FileId,- name: "report.pdf",- type: "application/pdf",- size: 1024 * 512,- lastModified: 0,- isLeaf: true,- originalFileId: "file-1",- versionNumber: 1,- ...overrides,-});--const meta = {- title: "FileManager/CompactFileDetails",- component: CompactFileDetails,- args: {- onPrevious: () => {},- onNext: () => {},- onOpenFiles: () => {},- },-} satisfies Meta<typeof CompactFileDetails>;-export default meta;--type Story = StoryObj<typeof meta>;--export const Default: Story = {- args: {- currentFile: buildFileStub(),- thumbnail: null,- selectedFiles: [buildFileStub()],- currentFileIndex: 0,- numberOfFiles: 1,- isAnimating: false,- },-};--export const MultipleFiles: Story = {- args: {- currentFile: buildFileStub({ name: "invoice-final.pdf", versionNumber: 2 }),- thumbnail: null,- selectedFiles: [- buildFileStub({ id: "file-1" as FileId, name: "invoice-final.pdf" }),- buildFileStub({ id: "file-2" as FileId, name: "receipt.pdf" }),- buildFileStub({ id: "file-3" as FileId, name: "statement.pdf" }),- ],- currentFileIndex: 1,- numberOfFiles: 3,- isAnimating: false,- },-};--export const NoFileLoaded: Story = {- args: {- currentFile: null,- thumbnail: null,- selectedFiles: [],- currentFileIndex: 0,- numberOfFiles: 0,- isAnimating: false,- },-};diff --git a/frontend/editor/src/core/components/fileManager/CompactFileDetails.tsx b/frontend/editor/src/core/components/fileManager/CompactFileDetails.tsxdeleted file mode 100644index d99512593a..0000000000--- a/frontend/editor/src/core/components/fileManager/CompactFileDetails.tsx+++ /dev/null@@ -1,173 +0,0 @@-import React from "react";-import { Stack, Box, Text, Center } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { ActionIcon } from "@app/ui/ActionIcon";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import { getFileSize } from "@app/utils/fileUtils";-import { toolOperationLabel } from "@app/utils/toolOperationLabel";-import { StirlingFileStub } from "@app/types/fileContext";-import { PrivateContent } from "@app/components/shared/PrivateContent";--interface CompactFileDetailsProps {- currentFile: StirlingFileStub | null;- thumbnail: string | null;- selectedFiles: StirlingFileStub[];- currentFileIndex: number;- numberOfFiles: number;- isAnimating: boolean;- onPrevious: () => void;- onNext: () => void;- onOpenFiles: () => void;- canCloseAll?: boolean;-}--const CompactFileDetails: React.FC<CompactFileDetailsProps> = ({- currentFile,- thumbnail,- selectedFiles,- currentFileIndex,- numberOfFiles,- isAnimating,- onPrevious,- onNext,- onOpenFiles,- canCloseAll = false,-}) => {- const { t } = useTranslation();- const hasSelection = selectedFiles.length > 0;- const hasMultipleFiles = numberOfFiles > 1;- const showOwner = Boolean(- currentFile &&- (currentFile.remoteOwnedByCurrentUser === false ||- currentFile.remoteSharedViaLink),- );- const ownerLabel = currentFile- ? currentFile.remoteOwnerUsername ||- t("fileManager.ownerUnknown", "Unknown")- : "";-- return (- <Stack gap="xs" style={{ height: "100%" }}>- {/* Compact mobile layout */}- <Box style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>- {/* Small preview */}- <Box- style={{- width: "7.5rem",- height: "9.375rem",- flexShrink: 0,- position: "relative",- display: "flex",- alignItems: "center",- justifyContent: "center",- }}- >- {currentFile && thumbnail ? (- <PrivateContent>- <img- src={thumbnail}- alt={currentFile.name}- style={{- maxWidth: "100%",- maxHeight: "100%",- objectFit: "contain",- borderRadius: "0.25rem",- boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)",- }}- />- </PrivateContent>- ) : currentFile ? (- <Center- style={{- width: "100%",- height: "100%",- backgroundColor: "var(--mantine-color-gray-1)",- borderRadius: 4,- }}- >- <Icon- name="file-pdf"- size={20}- style={{ color: "var(--mantine-color-gray-6)" }}- />- </Center>- ) : null}- </Box>-- {/* File info */}- <Box style={{ flex: 1, minWidth: 0 }}>- <Text size="sm" fw={500} truncate>- <PrivateContent>- {currentFile ? currentFile.name : "No file loaded"}- </PrivateContent>- </Text>- <Text size="xs" c="dimmed">- {currentFile ? getFileSize(currentFile) : ""}- {selectedFiles.length > 1 && ` • ${selectedFiles.length} files`}- {currentFile && ` • v${currentFile.versionNumber || 1}`}- </Text>- {hasMultipleFiles && (- <Text size="xs" c="var(--c-accent-text)">- {currentFileIndex + 1} of {selectedFiles.length}- </Text>- )}- {/* Compact tool chain for mobile */}- {currentFile?.toolHistory && currentFile.toolHistory.length > 0 && (- <Text size="xs" c="dimmed">- {currentFile.toolHistory- .map((tool) => toolOperationLabel(tool, t))- .join(" → ")}- </Text>- )}- {currentFile && showOwner && (- <Text size="xs" c="dimmed">- {t("fileManager.owner", "Owner")}: {ownerLabel}- </Text>- )}- </Box>-- {/* Navigation arrows for multiple files */}- {hasMultipleFiles && (- <Box style={{ display: "flex", gap: "0.25rem" }}>- <ActionIcon- variant="tertiary"- size="sm"- onClick={onPrevious}- disabled={isAnimating}- aria-label={t("fileManager.previousFile", "Previous file")}- >- <Icon name="chevron-left" size={16} />- </ActionIcon>- <ActionIcon- variant="tertiary"- size="sm"- onClick={onNext}- disabled={isAnimating}- aria-label={t("fileManager.nextFile", "Next file")}- >- <Icon name="chevron-right" size={16} />- </ActionIcon>- </Box>- )}- </Box>-- {/* Action Button */}- <Button- size="sm"- accent="neutral"- onClick={onOpenFiles}- disabled={!hasSelection && !canCloseAll}- fullWidth- >- {canCloseAll- ? t("fileManager.closeAllFiles", "Close all files")- : selectedFiles.length > 1- ? t("fileManager.openFiles", `Open ${selectedFiles.length} Files`)- : t("fileManager.openFile", "Open File")}- </Button>- </Stack>- );-};--export default CompactFileDetails;diff --git a/frontend/editor/src/core/components/fileManager/DesktopLayout.tsx b/frontend/editor/src/core/components/fileManager/DesktopLayout.tsxdeleted file mode 100644index dc203ab756..0000000000--- a/frontend/editor/src/core/components/fileManager/DesktopLayout.tsx+++ /dev/null@@ -1,124 +0,0 @@-import React from "react";-import { Grid } from "@mantine/core";-import FileSourceButtons from "@app/components/fileManager/FileSourceButtons";-import FileDetails from "@app/components/fileManager/FileDetails";-import SearchInput from "@app/components/fileManager/SearchInput";-import FileListArea from "@app/components/fileManager/FileListArea";-import FileActions from "@app/components/fileManager/FileActions";-import HiddenFileInput from "@app/components/fileManager/HiddenFileInput";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";--const DesktopLayout: React.FC = () => {- const { activeSource, recentFiles, modalHeight } = useFileManagerContext();-- return (- <Grid- gutter="xs"- h="100%"- grow={false}- style={{ flexWrap: "nowrap", minWidth: 0 }}- >- {/* Column 1: File Sources */}- <Grid.Col- span="content"- p="lg"- style={{- minWidth: "13.625rem",- width: "13.625rem",- flexShrink: 0,- height: "100%",- }}- data-tour="file-sources"- >- <FileSourceButtons />- </Grid.Col>-- {/* Column 2: File List */}- <Grid.Col- span="auto"- style={{- display: "flex",- flexDirection: "column",- height: "100%",- minHeight: 0,- minWidth: 0,- flex: "1 1 0px",- }}- >- <div- style={{- flex: 1,- display: "flex",- flexDirection: "column",- backgroundColor: "var(--c-surface)",- border: "1px solid var(--mantine-color-gray-2)",- boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",- overflow: "hidden",- }}- >- {activeSource === "recent" && (- <>- <div- style={{- flexShrink: 0,- borderBottom: "1px solid var(--mantine-color-gray-3)",- }}- >- <SearchInput />- </div>- <div- style={{- flexShrink: 0,- borderBottom: "1px solid var(--mantine-color-gray-3)",- }}- >- <FileActions />- </div>- </>- )}-- <div style={{ flex: 1, minHeight: 0, overflow: "hidden" }}>- <FileListArea- scrollAreaHeight={- activeSource === "recent" && recentFiles.length > 0- ? `calc(${modalHeight} - 7rem)`- : "100%"- }- scrollAreaStyle={{- height:- activeSource === "recent" && recentFiles.length > 0- ? `calc(${modalHeight} - 7rem)`- : "100%",- backgroundColor: "transparent",- border: "none",- borderRadius: 0,- }}- />- </div>- </div>- </Grid.Col>-- {/* Column 3: File Details */}- <Grid.Col- p="xl"- span="content"- style={{- minWidth: "25rem",- width: "25rem",- flexShrink: 0,- height: "100%",- maxWidth: "18rem",- }}- >- <div style={{ height: "100%", overflow: "hidden" }}>- <FileDetails />- </div>- </Grid.Col>-- {/* Hidden file input for local file selection */}- <HiddenFileInput />- </Grid>- );-};--export default DesktopLayout;diff --git a/frontend/editor/src/core/components/fileManager/DragOverlay.stories.tsx b/frontend/editor/src/core/components/fileManager/DragOverlay.stories.tsxdeleted file mode 100644index a047cd9e94..0000000000--- a/frontend/editor/src/core/components/fileManager/DragOverlay.stories.tsx+++ /dev/null@@ -1,30 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import DragOverlay from "@app/components/fileManager/DragOverlay";--const meta = {- title: "FileManager/DragOverlay",- component: DragOverlay,- parameters: { layout: "fullscreen" },-} satisfies Meta<typeof DragOverlay>;-export default meta;--type Story = StoryObj<typeof meta>;--export const Default: Story = {- args: {- isVisible: true,- },- decorators: [- (Story) => (- <div style={{ position: "relative", height: "20rem" }}>- <Story />- </div>- ),- ],-};--export const Hidden: Story = {- args: {- isVisible: false,- },-};diff --git a/frontend/editor/src/core/components/fileManager/DragOverlay.tsx b/frontend/editor/src/core/components/fileManager/DragOverlay.tsxdeleted file mode 100644index 13fff23de2..0000000000--- a/frontend/editor/src/core/components/fileManager/DragOverlay.tsx+++ /dev/null@@ -1,50 +0,0 @@-import React from "react";-import { Stack, Text } from "@mantine/core";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";--interface DragOverlayProps {- isVisible: boolean;-}--const DragOverlay: React.FC<DragOverlayProps> = ({ isVisible }) => {- const { t } = useTranslation();-- if (!isVisible) return null;-- return (- <div- style={{- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0,- // The prompt below is the drop affordance on its own. Tinting the whole- // region and ringing it in dashed accent reads as a second, competing- // surface, so the overlay stays transparent.- borderRadius: "1.875rem",- display: "flex",- alignItems: "center",- justifyContent: "center",- zIndex: 1000,- pointerEvents: "none",- }}- >- <Stack align="center" gap="md">- {/* Muted ink rather than the accent shade: it has to read on whatever- the overlay happens to sit on, in either scheme. */}- <Icon- name="file-up"- size={"4rem"}- style={{ color: "var(--c-text-muted)" }}- />- <Text size="xl" fw={500} c="var(--c-text-muted)">- {t("fileManager.dropFilesHere", "Drop files here to upload")}- </Text>- </Stack>- </div>- );-};--export default DragOverlay;diff --git a/frontend/editor/src/core/components/fileManager/EmptyFilesState.tsx b/frontend/editor/src/core/components/fileManager/EmptyFilesState.tsxdeleted file mode 100644index ad7691066b..0000000000--- a/frontend/editor/src/core/components/fileManager/EmptyFilesState.tsx+++ /dev/null@@ -1,128 +0,0 @@-import React, { useState } from "react";-import { Group, Text, Stack } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";-import { Wordmark } from "@app/components/shared/Wordmark";-import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";--const EmptyFilesState: React.FC = () => {- const { t } = useTranslation();- const { onLocalFileClick } = useFileManagerContext();- const [isUploadHover, setIsUploadHover] = useState(false);- const terminology = useFileActionTerminology();- const icons = useFileActionIcons();-- const handleUploadClick = () => {- onLocalFileClick();- };-- return (- <div- style={{- height: "100%",- width: "100%",- display: "flex",- alignItems: "center",- justifyContent: "center",- padding: "2rem",- }}- >- {/* Container */}- <div- style={{- backgroundColor: "transparent",- padding: "3rem 2rem",- display: "flex",- flexDirection: "column",- alignItems: "center",- justifyContent: "center",- gap: "1.5rem",- minWidth: "20rem",- maxWidth: "28rem",- width: "100%",- }}- >- {/* No Recent Files Message */}- <Stack align="center" gap="sm">- <Icon- name="rotate-ccw-clock"- size={"3rem"}- style={{ color: "var(--mantine-color-gray-5)" }}- />- <Text c="dimmed" ta="center" size="lg">- {t("fileManager.noRecentFiles", "No recent files")}- </Text>- </Stack>-- {/* Stirling PDF Logo */}- <Group gap="xs" align="center">- <Wordmark- alt="Stirling PDF"- muted- style={{ height: "2.2rem", width: "auto" }}- />- </Group>-- {/* Upload Button */}- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "center",- width: "100%",- marginTop: "0.5rem",- marginBottom: "0.5rem",- }}- onMouseLeave={() => setIsUploadHover(false)}- >- <Button- variant="tertiary"- aria-label={t("emptyFilesState.upload", "Upload")}- style={{- backgroundColor: "var(--c-bg)",- color: "var(--c-accent-fg)",- border: "1px solid var(--landing-button-border)",- borderRadius: isUploadHover ? "2rem" : "1rem",- height: "38px",- width: isUploadHover ? "100%" : "58px",- minWidth: "58px",- paddingLeft: isUploadHover ? "1rem" : 0,- paddingRight: isUploadHover ? "1rem" : 0,- display: "flex",- alignItems: "center",- justifyContent: "center",- transition:- "width .5s ease, padding .5s ease, border-radius .5s ease",- }}- onClick={handleUploadClick}- onMouseEnter={() => setIsUploadHover(true)}- >- <Icon- name={icons.upload}- size="1.25rem"- style={{ color: "var(--c-accent-text)" }}- />- {isUploadHover && (- <span style={{ marginLeft: ".5rem" }}>- {terminology.uploadFromComputer}- </span>- )}- </Button>- </div>-- {/* Instruction Text */}- <span- className="text-[var(--c-primary)]"- style={{ fontSize: ".8rem", textAlign: "center" }}- >- {terminology.dropFilesHere}- </span>- </div>- </div>- );-};--export default EmptyFilesState;diff --git a/frontend/editor/src/core/components/fileManager/FileActions.tsx b/frontend/editor/src/core/components/fileManager/FileActions.tsxdeleted file mode 100644index eb383c6386..0000000000--- a/frontend/editor/src/core/components/fileManager/FileActions.tsx+++ /dev/null@@ -1,244 +0,0 @@-import React, { useEffect } from "react";-import { Group, Text, Tooltip } from "@mantine/core";-import { ActionIcon } from "@app/ui/ActionIcon";-import { SegmentedControl } from "@app/ui/SegmentedControl";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";-import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import BulkUploadToServerModal from "@app/components/shared/BulkUploadToServerModal";-import BulkShareModal from "@app/components/shared/BulkShareModal";--const FileActions: React.FC = () => {- const { t } = useTranslation();- const terminology = useFileActionTerminology();- const icons = useFileActionIcons();- const { config } = useAppConfig();- const [showBulkUploadModal, setShowBulkUploadModal] = React.useState(false);- const [showBulkShareModal, setShowBulkShareModal] = React.useState(false);- const {- recentFiles,- selectedFileIds,- selectedFiles,- filteredFiles,- onSelectAll,- onDeleteSelected,- onDownloadSelected,- refreshRecentFiles,- storageFilter,- onStorageFilterChange,- } = useFileManagerContext();- const uploadEnabled = config?.storageEnabled === true;- const sharingEnabled =- uploadEnabled && config?.storageSharingEnabled === true;- const shareLinksEnabled =- sharingEnabled && config?.storageShareLinksEnabled === true;- const showStorageFilter = uploadEnabled;- const storageFilterOptions = sharingEnabled- ? [- { value: "all", label: t("fileManager.filterAll", "All") },- { value: "local", label: t("fileManager.filterLocal", "Local") },- {- value: "sharedWithMe",- label: t("fileManager.filterSharedWithMe", "Shared with me"),- },- {- value: "sharedByMe",- label: t("fileManager.filterSharedByMe", "Shared by me"),- },- ]- : [- { value: "all", label: t("fileManager.filterAll", "All") },- { value: "local", label: t("fileManager.filterLocal", "Local") },- ];- useEffect(() => {- if (- !sharingEnabled &&- (storageFilter === "sharedWithMe" || storageFilter === "sharedByMe")- ) {- onStorageFilterChange("all");- }- }, [sharingEnabled, storageFilter, onStorageFilterChange]);- const hasSelection = selectedFileIds.length > 0;- const hasOnlyOwnedSelection = selectedFiles.every(- (file) => file.remoteOwnedByCurrentUser !== false,- );- const hasDownloadAccess = selectedFiles.every((file) => {- const role = (- file.remoteOwnedByCurrentUser !== false- ? "editor"- : (file.remoteAccessRole ?? "viewer")- ).toLowerCase();- return role === "editor" || role === "commenter" || role === "viewer";- });- const canBulkUpload = uploadEnabled && hasSelection && hasOnlyOwnedSelection;- const canBulkShare =- shareLinksEnabled && hasSelection && hasOnlyOwnedSelection;-- const handleSelectAll = () => {- onSelectAll();- };-- const handleDeleteSelected = () => {- if (selectedFileIds.length > 0) {- onDeleteSelected();- }- };-- const handleDownloadSelected = () => {- if (selectedFileIds.length > 0) {- onDownloadSelected();- }- };-- // Only show actions if there are files- if (recentFiles.length === 0) {- return null;- }-- const allFilesSelected =- filteredFiles.length > 0 && selectedFileIds.length === filteredFiles.length;-- return (- <div- style={{- padding: "0.75rem 1rem",- backgroundColor: "var(--mantine-color-gray-1)",- display: "flex",- alignItems: "center",- justifyContent: "space-between",- minHeight: "3rem",- position: "relative",- }}- >- {/* Left: Select All + Filter */}- <Group gap="xs">- <Tooltip- label={- allFilesSelected- ? t("fileManager.deselectAll", "Deselect All")- : t("fileManager.selectAll", "Select All")- }- >- <ActionIcon- variant="secondary"- size="sm"- onClick={handleSelectAll}- disabled={filteredFiles.length === 0}- aria-label={- allFilesSelected- ? t("fileManager.deselectAll", "Deselect All")- : t("fileManager.selectAll", "Select All")- }- >- <Icon name="select-all" size={"1rem"} />- </ActionIcon>- </Tooltip>- {showStorageFilter && (- <SegmentedControl- size="sm"- value={storageFilter}- onChange={(value) =>- onStorageFilterChange(- value as "all" | "local" | "sharedWithMe" | "sharedByMe",- )- }- options={storageFilterOptions}- />- )}- </Group>-- {/* Center: Selected count */}- <div- style={{- position: "absolute",- left: "50%",- transform: "translateX(-50%)",- }}- >- {hasSelection && (- <Text size="sm" c="dimmed" fw={500}>- {t("fileManager.selectedCount", "{{count}} selected", {- count: selectedFileIds.length,- })}- </Text>- )}- </div>-- {/* Right: Delete and Download */}- <Group gap="xs">- {uploadEnabled && (- <Tooltip label={t("fileManager.uploadSelected", "Upload Selected")}>- <ActionIcon- variant="secondary"- size="sm"- onClick={() => setShowBulkUploadModal(true)}- disabled={!canBulkUpload}- aria-label={t("fileManager.uploadSelected", "Upload Selected")}- >- <Icon name="cloud-upload" size={"1rem"} />- </ActionIcon>- </Tooltip>- )}- {shareLinksEnabled && (- <Tooltip label={t("fileManager.shareSelected", "Share Selected")}>- <ActionIcon- variant="secondary"- size="sm"- onClick={() => setShowBulkShareModal(true)}- disabled={!canBulkShare}- aria-label={t("fileManager.shareSelected", "Share Selected")}- >- <Icon name="link" size={"1rem"} />- </ActionIcon>- </Tooltip>- )}- <Tooltip label={t("fileManager.deleteSelected", "Delete Selected")}>- <ActionIcon- variant="secondary"- size="sm"- accent="danger"- onClick={handleDeleteSelected}- disabled={!hasSelection}- aria-label={t("fileManager.deleteSelected", "Delete Selected")}- >- <Icon name="trash" size={"1rem"} />- </ActionIcon>- </Tooltip>-- <Tooltip label={terminology.downloadSelected}>- <ActionIcon- variant="secondary"- size="sm"- onClick={handleDownloadSelected}- disabled={!hasSelection || !hasDownloadAccess}- aria-label={terminology.downloadSelected}- >- <Icon name={icons.download} size="1rem" />- </ActionIcon>- </Tooltip>- </Group>-- {uploadEnabled && (- <BulkUploadToServerModal- opened={showBulkUploadModal}- onClose={() => setShowBulkUploadModal(false)}- files={selectedFiles}- onUploaded={refreshRecentFiles}- />- )}- {shareLinksEnabled && (- <BulkShareModal- opened={showBulkShareModal}- onClose={() => setShowBulkShareModal(false)}- files={selectedFiles}- onShared={refreshRecentFiles}- />- )}- </div>- );-};--export default FileActions;diff --git a/frontend/editor/src/core/components/fileManager/FileDetails.stories.tsx b/frontend/editor/src/core/components/fileManager/FileDetails.stories.tsxdeleted file mode 100644index 38ba423deb..0000000000--- a/frontend/editor/src/core/components/fileManager/FileDetails.stories.tsx+++ /dev/null@@ -1,73 +0,0 @@-import type { ReactElement } from "react";-import type { Meta, StoryObj } from "@storybook/react-vite";-import FileDetails from "@app/components/fileManager/FileDetails";-import { FileContextProvider } from "@app/contexts/FileContext";-import { FileManagerProvider } from "@app/contexts/FileManagerContext";-import type { StirlingFileStub } from "@app/types/fileContext";-import type { FileId } from "@app/types/file";--const mockFile: StirlingFileStub = {- id: "story-file-1" as FileId,- name: "quarterly-report.pdf",- type: "application/pdf",- size: 2_400_000,- lastModified: Date.now(),- isLeaf: true,- originalFileId: "story-file-1",- versionNumber: 1,- // Set so useIndexedDBThumbnail short-circuits on the stored thumbnail- // instead of trying to read file bytes out of IndexedDB.- thumbnailUrl:- "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='160'%3E%3Crect width='120' height='160' fill='%23e9ecef'/%3E%3C/svg%3E",-};--/**- * FileDetails reads from FileManagerContext, which itself needs FileContext- * (for useFileActions/useFileManagement) and IndexedDBContext (pulled in by- * FileContextProvider) further up the tree — neither is part of the shared- * preview decorators, so both are stood up here with static mock data.- */-function withFileManager(activeFileIds: FileId[]) {- return (Story: () => ReactElement) => (- <FileContextProvider>- <FileManagerProvider- recentFiles={[mockFile]}- onRecentFilesSelected={() => {}}- onNewFilesSelect={() => {}}- onClose={() => {}}- isFileSupported={() => true}- isOpen- onFileRemove={() => {}}- modalHeight="600px"- refreshRecentFiles={async () => {}}- isLoading={false}- activeFileIds={activeFileIds}- >- <Story />- </FileManagerProvider>- </FileContextProvider>- );-}--const meta = {- title: "FileManager/FileDetails",- component: FileDetails,-} satisfies Meta<typeof FileDetails>;-export default meta;--type Story = StoryObj<typeof meta>;--export const Default: Story = {- decorators: [withFileManager([mockFile.id])],-};--export const Empty: Story = {- decorators: [withFileManager([])],-};--export const Compact: Story = {- args: {- compact: true,- },- decorators: [withFileManager([mockFile.id])],-};diff --git a/frontend/editor/src/core/components/fileManager/FileDetails.tsx b/frontend/editor/src/core/components/fileManager/FileDetails.tsxdeleted file mode 100644index 3fd116b75e..0000000000--- a/frontend/editor/src/core/components/fileManager/FileDetails.tsx+++ /dev/null@@ -1,127 +0,0 @@-import React, { useEffect, useState } from "react";-import { Stack, Box } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { useTranslation } from "react-i18next";-import { useIndexedDBThumbnail } from "@app/hooks/useIndexedDBThumbnail";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";-import FilePreview from "@app/components/shared/FilePreview";-import FileInfoCard from "@app/components/fileManager/FileInfoCard";-import CompactFileDetails from "@app/components/fileManager/CompactFileDetails";--interface FileDetailsProps {- compact?: boolean;-}--const FileDetails: React.FC<FileDetailsProps> = ({ compact = false }) => {- const { selectedFiles, onOpenFiles, modalHeight, activeFileIds } =- useFileManagerContext();- const { t } = useTranslation();- const [currentFileIndex, setCurrentFileIndex] = useState(0);- const [isAnimating, setIsAnimating] = useState(false);-- // Get the currently displayed file- const currentFile =- selectedFiles.length > 0 ? selectedFiles[currentFileIndex] : null;- const hasSelection = selectedFiles.length > 0;- const hasActiveFiles = activeFileIds.length > 0;- // Enable "Close all files" when nothing is checked but files are open in workbench- const canCloseAll = !hasSelection && hasActiveFiles;-- // Use IndexedDB hook for the current file- const { thumbnail: currentThumbnail } = useIndexedDBThumbnail(currentFile);-- // Get thumbnail for current file- const getCurrentThumbnail = () => {- return currentThumbnail;- };-- const handlePrevious = () => {- if (isAnimating) return;- setIsAnimating(true);- setTimeout(() => {- setCurrentFileIndex((prev) =>- prev > 0 ? prev - 1 : selectedFiles.length - 1,- );- setIsAnimating(false);- }, 150);- };-- const handleNext = () => {- if (isAnimating) return;- setIsAnimating(true);- setTimeout(() => {- setCurrentFileIndex((prev) =>- prev < selectedFiles.length - 1 ? prev + 1 : 0,- );- setIsAnimating(false);- }, 150);- };-- // Reset index when selection changes- useEffect(() => {- if (currentFileIndex >= selectedFiles.length) {- setCurrentFileIndex(0);- }- }, [selectedFiles.length, currentFileIndex]);-- if (compact) {- return (- <CompactFileDetails- currentFile={currentFile}- thumbnail={getCurrentThumbnail()}- selectedFiles={selectedFiles}- currentFileIndex={currentFileIndex}- numberOfFiles={selectedFiles.length}- isAnimating={isAnimating}- onPrevious={handlePrevious}- onNext={handleNext}- onOpenFiles={onOpenFiles}- canCloseAll={canCloseAll}- />- );- }-- return (- <Stack gap="lg" h={`calc(${modalHeight} - 2rem)`} justify="flex-start">- {/* Section 1: Thumbnail Preview */}- <Box- style={{- width: "100%",- height: "min(35vh, 280px)",- textAlign: "center",- flexShrink: 0,- }}- >- <FilePreview- file={currentFile}- thumbnail={getCurrentThumbnail()}- showStacking={true}- showNavigation={true}- totalFiles={selectedFiles.length}- isAnimating={isAnimating}- onPrevious={handlePrevious}- onNext={handleNext}- />- </Box>-- {/* Section 2: File Details */}- <FileInfoCard currentFile={currentFile} modalHeight={modalHeight} />-- <Button- size="md"- accent="neutral"- onClick={onOpenFiles}- disabled={!hasSelection && !canCloseAll}- fullWidth- >- {canCloseAll- ? t("fileManager.closeAllFiles", "Close all files")- : selectedFiles.length > 1- ? t("fileManager.openFiles", `Open ${selectedFiles.length} Files`)- : t("fileManager.openFile", "Open File")}- </Button>- </Stack>- );-};--export default FileDetails;diff --git a/frontend/editor/src/core/components/fileManager/FileHistoryGroup.tsx b/frontend/editor/src/core/components/fileManager/FileHistoryGroup.tsxdeleted file mode 100644index a405bd37a5..0000000000--- a/frontend/editor/src/core/components/fileManager/FileHistoryGroup.tsx+++ /dev/null@@ -1,65 +0,0 @@-import React from "react";-import { Box, Text, Collapse, Group } from "@mantine/core";-import { useTranslation } from "react-i18next";-import { StirlingFileStub } from "@app/types/fileContext";-import FileListItem from "@app/components/fileManager/FileListItem";--interface FileHistoryGroupProps {- leafFile: StirlingFileStub;- historyFiles: StirlingFileStub[];- isExpanded: boolean;- onDownloadSingle: (file: StirlingFileStub) => void;- onFileDoubleClick: (file: StirlingFileStub) => void;- onHistoryFileRemove: (file: StirlingFileStub) => void;-}--const FileHistoryGroup: React.FC<FileHistoryGroupProps> = ({- leafFile,- historyFiles,- isExpanded,- onDownloadSingle,- onFileDoubleClick,- onHistoryFileRemove,-}) => {- const { t } = useTranslation();-- // Sort history files by version number (oldest first, excluding the current leaf file)- const sortedHistory = historyFiles- .filter((file) => file.id !== leafFile.id) // Exclude the leaf file itself- .sort((a, b) => (b.versionNumber || 1) - (a.versionNumber || 1));-- if (!isExpanded || sortedHistory.length === 0) {- return null;- }-- return (- <Collapse in={isExpanded}>- <Box ml="md" mt="xs" mb="sm">- <Group align="center" mb="sm">- <Text size="xs" fw={600} c="dimmed">- {t("fileManager.fileHistory", "File History")} (- {sortedHistory.length})- </Text>- </Group>-- <Box ml="md">- {sortedHistory.map((historyFile) => (- <FileListItem- key={`history-${historyFile.id}-${historyFile.versionNumber || 1}`}- file={historyFile}- isSelected={false} // History files are not selectable- onSelect={() => {}} // No selection for history files- onRemove={() => onHistoryFileRemove(historyFile)} // Remove specific history file- onDownload={() => onDownloadSingle(historyFile)}- onDoubleClick={() => onFileDoubleClick(historyFile)}- isHistoryFile={true} // This enables "Add to Recents" in menu- isLatestVersion={false} // History files are never latest- />- ))}- </Box>- </Box>- </Collapse>- );-};--export default FileHistoryGroup;diff --git a/frontend/editor/src/core/components/fileManager/FileInfoCard.tsx b/frontend/editor/src/core/components/fileManager/FileInfoCard.tsxdeleted file mode 100644index 4f94155d4e..0000000000--- a/frontend/editor/src/core/components/fileManager/FileInfoCard.tsx+++ /dev/null@@ -1,314 +0,0 @@-import React, { useMemo, useState } from "react";-import {- Stack,- Card,- Box,- Text,- Badge,- Group,- Divider,- ScrollArea,-} from "@mantine/core";-import { Button } from "@app/ui/Button";-import { useTranslation } from "react-i18next";-import { detectFileExtension, getFileSize } from "@app/utils/fileUtils";-import { StirlingFileStub } from "@app/types/fileContext";-import ToolChain from "@app/components/shared/ToolChain";-import { PrivateContent } from "@app/components/shared/PrivateContent";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";-import ShareManagementModal from "@app/components/shared/ShareManagementModal";-import { useAppConfig } from "@app/contexts/AppConfigContext";--interface FileInfoCardProps {- currentFile: StirlingFileStub | null;- modalHeight: string;-}--const FileInfoCard: React.FC<FileInfoCardProps> = ({- currentFile,- modalHeight,-}) => {- const { t } = useTranslation();- const { config } = useAppConfig();- const { onMakeCopy } = useFileManagerContext();- const [showShareManageModal, setShowShareManageModal] = useState(false);- const isSharedWithYou = useMemo(() => {- if (!currentFile) return false;- return (- currentFile.remoteOwnedByCurrentUser === false ||- currentFile.remoteSharedViaLink- );- }, [currentFile]);- const isOwnedRemote = useMemo(() => {- if (!currentFile) return false;- return (- Boolean(currentFile.remoteStorageId) &&- currentFile.remoteOwnedByCurrentUser !== false- );- }, [currentFile]);- const localUpdatedAt =- currentFile?.createdAt ?? currentFile?.lastModified ?? 0;- const remoteUpdatedAt = currentFile?.remoteStorageUpdatedAt ?? 0;- const isUploaded = Boolean(currentFile?.remoteStorageId);- const isUpToDate = isUploaded && remoteUpdatedAt >= localUpdatedAt;- const isOutOfSync = isUploaded && !isUpToDate && isOwnedRemote;- const isLocalOnly =- !currentFile?.remoteStorageId && !currentFile?.remoteSharedViaLink;- const isSharedByYou = useMemo(() => {- if (!currentFile) return false;- return isOwnedRemote && Boolean(currentFile.remoteHasShareLinks);- }, [currentFile, isOwnedRemote]);- const uploadEnabled = config?.storageEnabled === true;- const sharingEnabled =- uploadEnabled && config?.storageSharingEnabled === true;- const ownerLabel = useMemo(() => {- if (!currentFile) return "";- if (currentFile.remoteOwnerUsername) {- return currentFile.remoteOwnerUsername;- }- return t("fileManager.ownerUnknown", "Unknown");- }, [currentFile, t]);- const lastSyncedLabel = useMemo(() => {- if (!currentFile?.remoteStorageUpdatedAt) return "";- return new Date(currentFile.remoteStorageUpdatedAt).toLocaleString();- }, [currentFile?.remoteStorageUpdatedAt]);-- return (- <Card- withBorder- p={0}- mah={`calc(${modalHeight} * 0.45)`}- style={{- overflow: "hidden",- flexShrink: 1,- display: "flex",- flexDirection: "column",- }}- >- <Box- p="sm"- style={{- background: "var(--c-surface-raised)",- borderTopLeftRadius: "var(--mantine-radius-md)",- borderTopRightRadius: "var(--mantine-radius-md)",- flexShrink: 0,- }}- >- <Text size="sm" fw={500} ta="center">- {t("fileManager.details", "File Details")}- </Text>- </Box>- {/* The viewport is focusable and named so keyboard users can scroll the- detail list once it overflows. */}- <ScrollArea- style={{ flex: 1, minHeight: 0 }}- p="md"- viewportProps={{- tabIndex: 0,- role: "group",- "aria-label": t("fileManager.details", "File Details"),- }}- >- <Stack gap="sm">- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- <PrivateContent>- {t("fileManager.fileName", "Name")}- </PrivateContent>- </Text>- <Text- size="sm"- fw={500}- style={{ maxWidth: "60%", textAlign: "right" }}- truncate- >- {currentFile ? currentFile.name : ""}- </Text>- </Group>- <Divider />-- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.fileFormat", "Format")}- </Text>- {currentFile ? (- <Badge size="sm" variant="light">- {detectFileExtension(currentFile.name).toUpperCase()}- </Badge>- ) : (- <Text size="sm" fw={500}></Text>- )}- </Group>- <Divider />-- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.fileSize", "Size")}- </Text>- <Text size="sm" fw={500}>- {currentFile ? getFileSize(currentFile) : ""}- </Text>- </Group>- <Divider />-- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.lastModified", "Last modified")}- </Text>- <Text size="sm" fw={500}>- {currentFile- ? new Date(currentFile.lastModified).toLocaleDateString()- : ""}- </Text>- </Group>- <Divider />-- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.fileVersion", "Version")}- </Text>- {currentFile && (- <Badge- size="sm"- variant="light"- color={currentFile?.versionNumber ? "blue" : "gray"}- >- v{currentFile ? currentFile.versionNumber || 1 : ""}- </Badge>- )}- </Group>- {sharingEnabled && isSharedWithYou && (- <>- <Divider />- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.owner", "Owner")}- </Text>- <Group gap="xs">- <Text size="sm" fw={500}>- {ownerLabel}- </Text>- <Badge size="xs" variant="light" color="grape">- {t("fileManager.sharedWithYou", "Shared with you")}- </Badge>- </Group>- </Group>- </>- )}-- {/* Tool Chain Display */}- {currentFile?.toolHistory && currentFile.toolHistory.length > 0 && (- <>- <Divider />- <Box py="xs">- <Text size="xs" c="dimmed" mb="xs">- {t("fileManager.toolChain", "Tools Applied")}- </Text>- <ToolChain- toolChain={currentFile.toolHistory}- displayStyle="badges"- size="xs"- />- </Box>- </>- )}-- {currentFile && isSharedWithYou && (- <>- <Divider />- <Button- size="sm"- variant="secondary"- onClick={() => onMakeCopy(currentFile)}- fullWidth- >- {t("fileManager.makeCopy", "Make a copy")}- </Button>- </>- )}-- {currentFile && isOwnedRemote && (- <>- <Divider />- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.cloudFile", "Cloud file")}- </Text>- {uploadEnabled && isOutOfSync ? (- <Badge size="xs" variant="light" color="yellow">- {t(- "fileManager.changesNotUploaded",- "Changes not uploaded",- )}- </Badge>- ) : uploadEnabled ? (- <Badge size="xs" variant="light" color="teal">- {t("fileManager.synced", "Synced")}- </Badge>- ) : null}- </Group>- {lastSyncedLabel && (- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.lastSynced", "Last synced")}- </Text>- <Text size="sm" fw={500}>- {lastSyncedLabel}- </Text>- </Group>- )}- {isSharedByYou && sharingEnabled && (- <>- <Divider />- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.sharing", "Sharing")}- </Text>- <Badge size="xs" variant="light" color="blue">- {t("fileManager.sharedByYou", "Shared by you")}- </Badge>- </Group>- <Button- size="sm"- variant="secondary"- onClick={() => setShowShareManageModal(true)}- fullWidth- >- {t("storageShare.manage", "Manage sharing")}- </Button>- </>- )}- </>- )}- {currentFile && isLocalOnly && (- <>- <Divider />- <Group justify="space-between" py="xs">- <Text size="sm" c="dimmed">- {t("fileManager.storageState", "Storage")}- </Text>- <Badge- size="xs"- variant="default"- c="dimmed"- style={{ opacity: 0.75 }}- >- {t("fileManager.localOnly", "Local only")}- </Badge>- </Group>- </>- )}- </Stack>- </ScrollArea>- {currentFile && isOwnedRemote && isSharedByYou && sharingEnabled && (- <ShareManagementModal- opened={showShareManageModal}- onClose={() => setShowShareManageModal(false)}- file={currentFile}- />- )}- </Card>- );-};--export default FileInfoCard;diff --git a/frontend/editor/src/core/components/fileManager/FileListArea.tsx b/frontend/editor/src/core/components/fileManager/FileListArea.tsxdeleted file mode 100644index 110bb6bea4..0000000000--- a/frontend/editor/src/core/components/fileManager/FileListArea.tsx+++ /dev/null@@ -1,113 +0,0 @@-import React from "react";-import { Center, ScrollArea, Text, Stack } from "@mantine/core";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import FileListItem from "@app/components/fileManager/FileListItem";-import FileHistoryGroup from "@app/components/fileManager/FileHistoryGroup";-import EmptyFilesState from "@app/components/fileManager/EmptyFilesState";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";--interface FileListAreaProps {- scrollAreaHeight: string;- scrollAreaStyle?: React.CSSProperties;-}--const FileListArea: React.FC<FileListAreaProps> = ({- scrollAreaHeight,- scrollAreaStyle = {},-}) => {- const {- activeSource,- recentFiles,- filteredFiles,- selectedFilesSet,- expandedFileIds,- loadedHistoryFiles,- onFileSelect,- onFileRemove,- onHistoryFileRemove,- onFileDoubleClick,- onDownloadSingle,- isLoading,- activeFileIds,- } = useFileManagerContext();- const { t } = useTranslation();-- if (activeSource === "recent") {- return (- <ScrollArea- h={scrollAreaHeight}- style={{- ...scrollAreaStyle,- }}- type="always"- scrollbarSize={8}- >- <Stack gap={0}>- {recentFiles.length === 0 && !isLoading ? (- <EmptyFilesState />- ) : recentFiles.length === 0 && isLoading ? (- <Center style={{ height: "12.5rem" }}>- <Text c="dimmed" ta="center">- {t("fileManager.loadingFiles", "Loading files...")}- </Text>- </Center>- ) : (- filteredFiles.map((file, index) => {- // All files in filteredFiles are now leaf files only- const historyFiles = loadedHistoryFiles.get(file.id) || [];- const isExpanded = expandedFileIds.has(file.id);- const isActive = activeFileIds.includes(file.id);-- return (- <React.Fragment key={file.id}>- <FileListItem- file={file}- isSelected={selectedFilesSet.has(file.id)}- onSelect={(shiftKey) => onFileSelect(file, index, shiftKey)}- onRemove={() => onFileRemove(index)}- onDownload={() => onDownloadSingle(file)}- onDoubleClick={() => onFileDoubleClick(file)}- isHistoryFile={false} // All files here are leaf files- isLatestVersion={true} // All files here are the latest versions- isActive={isActive}- />-- <FileHistoryGroup- leafFile={file}- historyFiles={historyFiles}- isExpanded={isExpanded}- onDownloadSingle={onDownloadSingle}- onFileDoubleClick={onFileDoubleClick}- onHistoryFileRemove={onHistoryFileRemove}- />- </React.Fragment>- );- })- )}- </Stack>- </ScrollArea>- );- }-- // Google Drive placeholder- return (- <Center style={{ height: "12.5rem" }}>- <Stack align="center" gap="sm">- <Icon- name="cloud"- size={"3rem"}- style={{ color: "var(--mantine-color-gray-5)" }}- />- <Text c="dimmed" ta="center">- {t(- "fileManager.googleDriveNotAvailable",- "Google Drive integration coming soon",- )}- </Text>- </Stack>- </Center>- );-};--export default FileListArea;diff --git a/frontend/editor/src/core/components/fileManager/FileListItem.tsx b/frontend/editor/src/core/components/fileManager/FileListItem.tsxdeleted file mode 100644index c8c2964068..0000000000--- a/frontend/editor/src/core/components/fileManager/FileListItem.tsx+++ /dev/null@@ -1,502 +0,0 @@-import React, { useCallback, useMemo, useState } from "react";-import {- Group,- Box,- Text,- Checkbox,- Divider,- Menu,- Badge,-} from "@mantine/core";-import { ActionIcon } from "@app/ui/ActionIcon";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import { getFileSize, getFileDate } from "@app/utils/fileUtils";-import { FileId, StirlingFileStub } from "@app/types/fileContext";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";-import { zipFileService } from "@app/services/zipFileService";-import ToolChain from "@app/components/shared/ToolChain";-import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@app/styles/zIndex";-import { PrivateContent } from "@app/components/shared/PrivateContent";-import { useFileManagement } from "@app/contexts/FileContext";-import UploadToServerModal from "@app/components/shared/UploadToServerModal";-import ShareFileModal from "@app/components/shared/ShareFileModal";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import ShareManagementModal from "@app/components/shared/ShareManagementModal";-import apiClient from "@app/services/apiClient";-import { absoluteWithBasePath } from "@app/constants/app";-import { alert } from "@app/components/toast";--interface FileListItemProps {- file: StirlingFileStub;- isSelected: boolean;- onSelect: (shiftKey?: boolean) => void;- onRemove: () => void;- onDownload?: () => void;- onDoubleClick?: () => void;- isLast?: boolean;- isHistoryFile?: boolean; // Whether this is a history file (indented)- isLatestVersion?: boolean; // Whether this is the latest version (shows chevron)- isActive?: boolean; // Whether this file is currently loaded in FileContext-}--const FileListItem: React.FC<FileListItemProps> = ({- file,- isSelected,- onSelect,- onRemove,- onDownload,- onDoubleClick,- isHistoryFile = false,- isLatestVersion = false,- isActive = false,-}) => {- const [isHovered, setIsHovered] = useState(false);- const [isMenuOpen, setIsMenuOpen] = useState(false);- const [showUploadModal, setShowUploadModal] = useState(false);- const [showShareModal, setShowShareModal] = useState(false);- const [showShareManageModal, setShowShareManageModal] = useState(false);- const { t } = useTranslation();- const { config } = useAppConfig();- const {- expandedFileIds,- onToggleExpansion,- onUnzipFile,- refreshRecentFiles,- } = useFileManagerContext();- const { removeFiles } = useFileManagement();-- // Check if this is a ZIP file- const isZipFile = zipFileService.isZipFileStub(file);-- // Check file extension- const extLower = (- file.name?.match(/\.([a-z0-9]+)$/i)?.[1] || ""- ).toLowerCase();- const isCBZ = extLower === "cbz";- const isCBR = extLower === "cbr";-- // Keep item in hovered state if menu is open- const shouldShowHovered = isHovered || isMenuOpen;-- // Get version information for this file- const leafFileId = (- isLatestVersion ? file.id : file.originalFileId || file.id- ) as FileId;- const hasVersionHistory = (file.versionNumber || 1) > 1; // Show history for any processed file (v2+)- const currentVersion = file.versionNumber || 1; // Display original files as v1- const isExpanded = expandedFileIds.has(leafFileId);- const uploadEnabled = config?.storageEnabled === true;- const sharingEnabled =- uploadEnabled && config?.storageSharingEnabled === true;- const shareLinksEnabled =- sharingEnabled && config?.storageShareLinksEnabled === true;- const isOwnedOrLocal = file.remoteOwnedByCurrentUser !== false;- const isSharedWithYou =- sharingEnabled &&- (file.remoteOwnedByCurrentUser === false || file.remoteSharedViaLink);- const localUpdatedAt = file.createdAt ?? file.lastModified ?? 0;- const remoteUpdatedAt = file.remoteStorageUpdatedAt ?? 0;- const isUploaded = Boolean(file.remoteStorageId);- const isUpToDate = isUploaded && remoteUpdatedAt >= localUpdatedAt;- const isOutOfSync = isUploaded && !isUpToDate && isOwnedOrLocal;- const isLocalOnly = !file.remoteStorageId && !file.remoteSharedViaLink;- const accessRole = (- isOwnedOrLocal ? "editor" : (file.remoteAccessRole ?? "viewer")- ).toLowerCase();- const hasReadAccess =- isOwnedOrLocal ||- accessRole === "editor" ||- accessRole === "commenter" ||- accessRole === "viewer";- const canUpload =- uploadEnabled &&- isOwnedOrLocal &&- isLatestVersion &&- (!isUploaded || !isUpToDate);- const canShare = shareLinksEnabled && isOwnedOrLocal && isLatestVersion;- const canManageShare =- sharingEnabled && isOwnedOrLocal && Boolean(file.remoteStorageId);- const canCopyShareLink =- shareLinksEnabled &&- Boolean(file.remoteHasShareLinks) &&- Boolean(file.remoteStorageId);- const canDownloadFile = Boolean(onDownload) && hasReadAccess;-- const shareBaseUrl = useMemo(() => {- const frontendUrl = (config?.frontendUrl || "").trim();- if (frontendUrl) {- const normalized = frontendUrl.endsWith("/")- ? frontendUrl.slice(0, -1)- : frontendUrl;- return `${normalized}/share/`;- }- return absoluteWithBasePath("/share/");- }, [config?.frontendUrl]);-- const handleCopyShareLink = useCallback(async () => {- if (!file.remoteStorageId) return;- try {- const response = await apiClient.get<{- shareLinks?: Array<{ token?: string }>;- }>(`/api/v1/storage/files/${file.remoteStorageId}`, {- suppressErrorToast: true,- });- const links = response.data?.shareLinks ?? [];- const token = links[links.length - 1]?.token;- if (!token) {- alert({- alertType: "warning",- title: t("storageShare.noLinks", "No active share links yet."),- expandable: false,- durationMs: 2500,- });- return;- }- await navigator.clipboard.writeText(`${shareBaseUrl}${token}`);- alert({- alertType: "success",- title: t("storageShare.copied", "Link copied to clipboard"),- expandable: false,- durationMs: 2000,- });- } catch (error) {- console.error("Failed to copy share link:", error);- alert({- alertType: "warning",- title: t("storageShare.copyFailed", "Copy failed"),- expandable: false,- durationMs: 2500,- });- }- }, [file.remoteStorageId, shareBaseUrl, t]);-- return (- <>- <Box- p="sm"- style={{- cursor: isHistoryFile ? "default" : "pointer",- backgroundColor:- isSelected || shouldShowHovered- ? "var(--mantine-color-gray-1)"- : "var(--c-surface)",- opacity: 1,- transition: "background-color 0.15s ease",- userSelect: "none",- WebkitUserSelect: "none",- MozUserSelect: "none",- msUserSelect: "none",- paddingLeft: isHistoryFile ? "2rem" : "0.75rem", // Indent history files- borderLeft: isHistoryFile- ? "3px solid var(--mantine-color-blue-4)"- : "none", // Visual indicator for history- }}- onClick={isHistoryFile ? undefined : (e) => onSelect(e.shiftKey)}- onDoubleClick={onDoubleClick}- onMouseEnter={() => setIsHovered(true)}- onMouseLeave={() => setIsHovered(false)}- >- <Group gap="sm">- {!isHistoryFile && (- <Box>- {/* Checkbox for regular files only */}- <Checkbox- checked={isSelected}- onChange={() => {}} // Handled by parent onClick- size="sm"- pl="sm"- pr="xs"- styles={{- input: {- cursor: "pointer",- },- }}- />- </Box>- )}-- <Box style={{ flex: 1, minWidth: 0 }}>- <Group gap="xs" align="center">- <Text size="sm" fw={500} truncate style={{ flex: 1 }}>- <PrivateContent>{file.name}</PrivateContent>- </Text>- {isActive && (- <Badge- size="xs"- variant="light"- style={{- backgroundColor: "var(--file-active-badge-bg)",- color: "var(--file-active-badge-fg)",- border: "1px solid var(--file-active-badge-border)",- }}- >- {t("fileManager.active", "Active")}- </Badge>- )}- <Badge size="xs" variant="light" color={"blue"}>- v{currentVersion}- </Badge>- {sharingEnabled && isSharedWithYou ? (- <Badge size="xs" variant="light" color="grape">- {t("fileManager.sharedWithYou", "Shared with you")}- </Badge>- ) : null}- {sharingEnabled &&- isSharedWithYou &&- accessRole &&- accessRole !== "editor" ? (- <Badge size="xs" variant="light" color="gray">- {accessRole === "commenter"- ? t("storageShare.roleCommenter", "Commenter")- : t("storageShare.roleViewer", "Viewer")}- </Badge>- ) : isLocalOnly ? (- <Badge- size="xs"- variant="default"- c="dimmed"- style={{ opacity: 0.75 }}- >- {t("fileManager.localOnly", "Local only")}- </Badge>- ) : uploadEnabled && isOutOfSync ? (- <Badge- size="xs"- variant="light"- color="yellow"- leftSection={<Icon name="cloud-upload" size={12} />}- >- {t("fileManager.changesNotUploaded", "Changes not uploaded")}- </Badge>- ) : uploadEnabled && isUploaded ? (- <Badge- size="xs"- variant="light"- color="teal"- leftSection={<Icon name="cloud-check" size={12} />}- >- {t("fileManager.synced", "Synced")}- </Badge>- ) : null}- {sharingEnabled &&- file.remoteOwnedByCurrentUser !== false &&- file.remoteHasShareLinks && (- <Badge size="xs" variant="light" color="blue">- {t("fileManager.sharedByYou", "Shared by you")}- </Badge>- )}- </Group>- <Group gap="xs" align="center">- <Text size="xs" c="dimmed">- {getFileSize(file)} • {getFileDate(file)}- </Text>-- {/* Tool chain for processed files */}- {file.toolHistory && file.toolHistory.length > 0 && (- <ToolChain- toolChain={file.toolHistory}- maxWidth={"150px"}- displayStyle="text"- size="xs"- />- )}- </Group>- </Box>-- {/* Three dots menu - fades in/out on hover */}- <Menu- position="bottom-end"- withinPortal- onOpen={() => setIsMenuOpen(true)}- onClose={() => setIsMenuOpen(false)}- zIndex={Z_INDEX_OVER_FILE_MANAGER_MODAL}- >- <Menu.Target>- <ActionIcon- variant="tertiary"- accent="neutral"- size="md"- onClick={(e) => e.stopPropagation()}- aria-label={t("fileManager.moreOptions", "More options")}- style={{- opacity: shouldShowHovered ? 1 : 0,- transform: shouldShowHovered ? "scale(1)" : "scale(0.8)",- transition: "opacity 0.3s ease, transform 0.3s ease",- pointerEvents: shouldShowHovered ? "auto" : "none",- }}- >- <Icon name="ellipsis-vertical" size={20} />- </ActionIcon>- </Menu.Target>-- <Menu.Dropdown>- {/* Close file option for active files */}- {isActive && (- <>- <Menu.Item- leftSection={<Icon name="x" size={16} />}- onClick={(e) => {- e.stopPropagation();- removeFiles([file.id]);- }}- >- {t("fileManager.closeFile", "Close File")}- </Menu.Item>- <Menu.Divider />- </>- )}-- {canDownloadFile && (- <Menu.Item- leftSection={<Icon name="download" size={16} />}- onClick={(e) => {- e.stopPropagation();- onDownload?.();- }}- >- {t("fileManager.download", "Download")}- </Menu.Item>- )}-- {canUpload && (- <Menu.Item- leftSection={<Icon name="cloud-upload" size={16} />}- onClick={(e) => {- e.stopPropagation();- setShowUploadModal(true);- }}- >- {isUploaded- ? t("fileManager.updateOnServer", "Update on Server")- : t("fileManager.uploadToServer", "Upload to Server")}- </Menu.Item>- )}-- {canShare && (- <Menu.Item- leftSection={<Icon name="link" size={16} />}- onClick={(e) => {- e.stopPropagation();- setShowShareModal(true);- }}- >- {t("fileManager.share", "Share")}- </Menu.Item>- )}-- {canCopyShareLink && (- <Menu.Item- leftSection={<Icon name="link" size={16} />}- onClick={(e) => {- e.stopPropagation();- void handleCopyShareLink();- }}- >- {t("storageShare.copyLink", "Copy share link")}- </Menu.Item>- )}-- {canManageShare && (- <Menu.Item- leftSection={<Icon name="link" size={16} />}- onClick={(e) => {- e.stopPropagation();- setShowShareManageModal(true);- }}- >- {t("storageShare.manage", "Manage sharing")}- </Menu.Item>- )}-- {/* Show/Hide History option for latest version files */}- {isLatestVersion && hasVersionHistory && (- <>- <Menu.Item- leftSection={<Icon name="rotate-ccw-clock" size={16} />}- onClick={(e) => {- e.stopPropagation();- onToggleExpansion(leafFileId);- }}- >- {isExpanded- ? t("fileManager.hideHistory", "Hide History")- : t("fileManager.showHistory", "Show History")}- </Menu.Item>- <Menu.Divider />- </>- )}-- {/* Restore option for history files */}- {isHistoryFile && (- <>- <Menu.Item- leftSection={<Icon name="rotate-ccw-clock" size={16} />}- onClick={(e) => {- e.stopPropagation();- }}- >- {t("fileManager.restore", "Restore")}- </Menu.Item>- <Menu.Divider />- </>- )}-- {/* Unzip option for ZIP files */}- {isZipFile && !isHistoryFile && !isCBZ && !isCBR && (- <>- <Menu.Item- leftSection={<Icon name="archive-restore" size={16} />}- onClick={(e) => {- e.stopPropagation();- onUnzipFile(file);- }}- >- {t("fileManager.unzip", "Unzip")}- </Menu.Item>- <Menu.Divider />- </>- )}-- <Menu.Item- leftSection={<Icon name="trash" size={16} />}- onClick={(e) => {- e.stopPropagation();- onRemove();- }}- >- {t("fileManager.delete", "Delete")}- </Menu.Item>- </Menu.Dropdown>- </Menu>- </Group>- </Box>- {<Divider color="var(--mantine-color-gray-3)" />}- {canUpload && (- <UploadToServerModal- opened={showUploadModal}- onClose={() => setShowUploadModal(false)}- file={file}- onUploaded={refreshRecentFiles}- />- )}- {canShare && (- <ShareFileModal- opened={showShareModal}- onClose={() => setShowShareModal(false)}- file={file}- onUploaded={refreshRecentFiles}- />- )}- {canManageShare && (- <ShareManagementModal- opened={showShareManageModal}- onClose={() => setShowShareManageModal(false)}- file={file}- />- )}- </>- );-};--export default FileListItem;diff --git a/frontend/editor/src/core/components/fileManager/FileSourceButtons.tsx b/frontend/editor/src/core/components/fileManager/FileSourceButtons.tsxdeleted file mode 100644index 368a8a1ca2..0000000000--- a/frontend/editor/src/core/components/fileManager/FileSourceButtons.tsx+++ /dev/null@@ -1,192 +0,0 @@-import React, { useState } from "react";-import { Stack, Text, Group } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";-import { useGoogleDrivePicker } from "@app/hooks/useGoogleDrivePicker";-import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";-import { useAppConfig } from "@app/contexts/AppConfigContext";-import { useIsMobile } from "@app/hooks/useIsMobile";-import MobileUploadModal from "@app/components/shared/MobileUploadModal";--interface FileSourceButtonsProps {- horizontal?: boolean;-}--const FileSourceButtons: React.FC<FileSourceButtonsProps> = ({- horizontal = false,-}) => {- const {- activeSource,- onSourceChange,- onLocalFileClick,- onGoogleDriveSelect,- onNewFilesSelect,- } = useFileManagerContext();- const { t } = useTranslation();- const { isEnabled: isGoogleDriveEnabled, openPicker: openGoogleDrivePicker } =- useGoogleDrivePicker();- const terminology = useFileActionTerminology();- const icons = useFileActionIcons();- const [mobileUploadModalOpen, setMobileUploadModalOpen] = useState(false);- const { config } = useAppConfig();- const isMobile = useIsMobile();- const isMobileUploadEnabled = config?.enableMobileScanner && !isMobile;-- const handleGoogleDriveClick = async () => {- try {- const files = await openGoogleDrivePicker({ multiple: true });- if (files.length > 0) {- onGoogleDriveSelect(files);- }- } catch (error) {- console.error("Failed to pick files from Google Drive:", error);- }- };-- const handleMobileUploadClick = () => {- setMobileUploadModalOpen(true);- };-- const handleFilesReceivedFromMobile = (files: File[]) => {- if (files.length > 0) {- onNewFilesSelect(files);- }- };-- // Determine visibility of Google Drive button- const shouldHideGoogleDrive =- !isGoogleDriveEnabled && config?.hideDisabledToolsGoogleDrive;-- // Determine visibility of Mobile QR Scanner button- const shouldHideMobileQR =- !isMobileUploadEnabled && config?.hideDisabledToolsMobileQRScanner;- // Shared Button has no `xs`; map the old horizontal `xs` to `sm`.- const buttonSize = "sm" as const;- const buttonJustify = horizontal ? "center" : "start";- const buttons = (- <>- <Button- variant={activeSource === "recent" ? "primary" : "tertiary"}- accent="neutral"- leftSection={<Icon name="rotate-ccw-clock" />}- justify={buttonJustify}- onClick={() => onSourceChange("recent")}- fullWidth={!horizontal}- size={buttonSize}- >- {t("fileManager.recent", "Recent")}- </Button>-- <Button- variant="tertiary"- accent="neutral"- leftSection={<Icon name={icons.upload} />}- justify={buttonJustify}- onClick={onLocalFileClick}- fullWidth={!horizontal}- size={buttonSize}- >- {horizontal ? terminology.upload : terminology.uploadFiles}- </Button>-- {!shouldHideGoogleDrive && (- <Button- variant="tertiary"- accent="neutral"- leftSection={- <Icon- name="googledrive"- size={18}- colorless={!isGoogleDriveEnabled}- />- }- justify={buttonJustify}- onClick={handleGoogleDriveClick}- fullWidth={!horizontal}- size={buttonSize}- disabled={!isGoogleDriveEnabled}- title={- !isGoogleDriveEnabled- ? t(- "fileManager.googleDriveNotAvailable",- "Google Drive integration not available",- )- : undefined- }- >- {horizontal- ? t("fileManager.googleDriveShort", "Drive")- : t("fileManager.googleDrive", "Google Drive")}- </Button>- )}-- {!shouldHideMobileQR && (- <Button- variant="tertiary"- accent="neutral"- leftSection={<Icon name="monitor-smartphone" />}- justify={buttonJustify}- onClick={handleMobileUploadClick}- fullWidth={!horizontal}- size={buttonSize}- disabled={!isMobileUploadEnabled}- title={- !isMobileUploadEnabled- ? t(- "fileManager.mobileUploadNotAvailable",- "Mobile upload not available",- )- : undefined- }- >- {horizontal- ? t("fileManager.mobileShort", "Mobile")- : t("fileManager.mobileUpload", "Mobile Upload")}- </Button>- )}- </>- );-- if (horizontal) {- return (- <>- <Group gap="xs" justify="center" style={{ width: "100%" }}>- {buttons}- </Group>- <MobileUploadModal- opened={mobileUploadModalOpen}- onClose={() => setMobileUploadModalOpen(false)}- onFilesReceived={handleFilesReceivedFromMobile}- />- </>- );- }-- return (- <>- <Stack gap="xs" style={{ height: "100%" }}>- <Text- size="sm"- pt="sm"- fw={500}- c="dimmed"- mb="xs"- style={{ paddingLeft: "1rem" }}- >- {t("fileSidebar.myFiles", "File library")}- </Text>- {buttons}- </Stack>- <MobileUploadModal- opened={mobileUploadModalOpen}- onClose={() => setMobileUploadModalOpen(false)}- onFilesReceived={handleFilesReceivedFromMobile}- />- </>- );-};--export default FileSourceButtons;diff --git a/frontend/editor/src/core/components/fileManager/HiddenFileInput.tsx b/frontend/editor/src/core/components/fileManager/HiddenFileInput.tsxdeleted file mode 100644index fce23187cd..0000000000--- a/frontend/editor/src/core/components/fileManager/HiddenFileInput.tsx+++ /dev/null@@ -1,19 +0,0 @@-import React from "react";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";--const HiddenFileInput: React.FC = () => {- const { fileInputRef, onFileInputChange } = useFileManagerContext();-- return (- <input- ref={fileInputRef}- type="file"- multiple={true}- onChange={onFileInputChange}- style={{ display: "none" }}- data-testid="file-input"- />- );-};--export default HiddenFileInput;diff --git a/frontend/editor/src/core/components/fileManager/MobileLayout.tsx b/frontend/editor/src/core/components/fileManager/MobileLayout.tsxdeleted file mode 100644index 9cc8c6ed99..0000000000--- a/frontend/editor/src/core/components/fileManager/MobileLayout.tsx+++ /dev/null@@ -1,99 +0,0 @@-import React from "react";-import { Box } from "@mantine/core";-import FileSourceButtons from "@app/components/fileManager/FileSourceButtons";-import FileDetails from "@app/components/fileManager/FileDetails";-import SearchInput from "@app/components/fileManager/SearchInput";-import FileListArea from "@app/components/fileManager/FileListArea";-import FileActions from "@app/components/fileManager/FileActions";-import HiddenFileInput from "@app/components/fileManager/HiddenFileInput";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";--const MobileLayout: React.FC = () => {- const { activeSource, selectedFiles, modalHeight } = useFileManagerContext();-- // Calculate the height more accurately based on actual content- const calculateFileListHeight = () => {- // Base modal height minus padding and gaps- const baseHeight = `calc(${modalHeight} - 2rem)`; // Account for Stack padding-- // Estimate heights of fixed components- const fileSourceHeight = "3rem"; // FileSourceButtons height- const fileDetailsHeight = selectedFiles.length > 0 ? "10rem" : "8rem"; // FileDetails compact height- const fileActionsHeight = activeSource === "recent" ? "3rem" : "0rem"; // FileActions height (now at bottom)- const searchHeight = activeSource === "recent" ? "3rem" : "0rem"; // SearchInput height- const gapHeight = activeSource === "recent" ? "3.75rem" : "2rem"; // Stack gaps-- return `calc(${baseHeight} - ${fileSourceHeight} - ${fileDetailsHeight} - ${fileActionsHeight} - ${searchHeight} - ${gapHeight})`;- };-- return (- <Box- h="100%"- p="sm"- style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}- >- {/* Section 1: File Sources - Fixed at top */}- <Box style={{ flexShrink: 0 }}>- <FileSourceButtons horizontal={true} />- </Box>-- <Box style={{ flexShrink: 0 }}>- <FileDetails compact={true} />- </Box>-- {/* Section 3 & 4: Search Bar + File List - Unified background extending to modal edge */}- <Box- style={{- flex: 1,- display: "flex",- flexDirection: "column",- backgroundColor: "var(--c-surface)",- borderRadius: "0.5rem",- border: "1px solid var(--mantine-color-gray-2)",- overflow: "hidden",- minHeight: 0,- }}- >- {activeSource === "recent" && (- <>- <Box- style={{- flexShrink: 0,- borderBottom: "1px solid var(--mantine-color-gray-2)",- }}- >- <SearchInput />- </Box>- <Box- style={{- flexShrink: 0,- borderBottom: "1px solid var(--mantine-color-gray-2)",- }}- >- <FileActions />- </Box>- </>- )}-- <Box style={{ flex: 1, minHeight: 0 }}>- <FileListArea- scrollAreaHeight={calculateFileListHeight()}- scrollAreaStyle={{- height: calculateFileListHeight(),- maxHeight: "60vh",- minHeight: "9.375rem",- backgroundColor: "transparent",- border: "none",- borderRadius: 0,- }}- />- </Box>- </Box>-- {/* Hidden file input for local file selection */}- <HiddenFileInput />- </Box>- );-};--export default MobileLayout;diff --git a/frontend/editor/src/core/components/fileManager/SearchInput.tsx b/frontend/editor/src/core/components/fileManager/SearchInput.tsxdeleted file mode 100644index c6d369088a..0000000000--- a/frontend/editor/src/core/components/fileManager/SearchInput.tsx+++ /dev/null@@ -1,32 +0,0 @@-import React from "react";-import { TextInput } from "@mantine/core";-import { Icon } from "@app/ui/Icon";-import { useTranslation } from "react-i18next";-import { useFileManagerContext } from "@app/contexts/FileManagerContext";--interface SearchInputProps {- style?: React.CSSProperties;-}--const SearchInput: React.FC<SearchInputProps> = ({ style }) => {- const { t } = useTranslation();- const { searchTerm, onSearchChange } = useFileManagerContext();-- return (- <TextInput- placeholder={t("fileManager.searchFiles", "Search files...")}- leftSection={<Icon name="search" />}- value={searchTerm}- onChange={(e) => onSearchChange(e.target.value)}- style={{ padding: "0.5rem", ...style }}- styles={{- input: {- border: "none",- backgroundColor: "transparent",- },- }}- />- );-};--export default SearchInput;diff --git a/frontend/editor/src/core/components/filesPage/AddToLibraryModal.test.tsx b/frontend/editor/src/core/components/filesPage/AddToLibraryModal.test.tsxnew file mode 100644index 0000000000..521f1d04d6--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/AddToLibraryModal.test.tsx@@ -0,0 +1,89 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { MantineProvider } from "@mantine/core";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { AddToLibraryModal } from "@app/components/filesPage/AddToLibraryModal";+import type { StirlingFileStub } from "@app/types/fileContext";++const state = vi.hoisted(() => ({+ move: vi.fn(),+ alert: vi.fn(),+ dismiss: vi.fn(),+}));+vi.mock("@app/contexts/FilesPageContext", () => ({+ useFilesPage: () => ({ moveFilesTo: state.move }),+}));+vi.mock("@app/components/toast", () => ({+ alert: state.alert,+ dismissToast: state.dismiss,+}));+vi.mock("@app/components/filesPage/LibraryFilePicker", () => ({+ LibraryFilePicker: ({+ destination,+ }: {+ destination: { onConfirm: (id: null) => void };+ }) => <button onClick={() => destination.onConfirm(null)}>Add here</button>,+}));++describe("library destination confirmation", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ state.alert.mockReturnValue("progress");+ });++ it("closes immediately while the upload continues, then dismisses progress", async () => {+ let finishUpload!: () => void;+ state.move.mockReturnValue(+ new Promise<void>((resolve) => {+ finishUpload = resolve;+ }),+ );+ const close = vi.fn();+ render(+ <MantineProvider>+ <AddToLibraryModal+ files={[{ id: "one" } as StirlingFileStub]}+ onClose={close}+ />+ </MantineProvider>,+ );+ await userEvent.click(screen.getByRole("button", { name: "Add here" }));+ expect(close).toHaveBeenCalledOnce();+ expect(state.move).toHaveBeenCalledWith(["one"], null, {+ uploadToRoot: true,+ });+ expect(close.mock.invocationCallOrder[0]).toBeLessThan(+ state.move.mock.invocationCallOrder[0],+ );+ expect(state.dismiss).not.toHaveBeenCalled();+ await act(async () => finishUpload());+ await waitFor(() => expect(state.dismiss).toHaveBeenCalledWith("progress"));+ expect(state.alert).toHaveBeenLastCalledWith(+ expect.objectContaining({ alertType: "success" }),+ );+ });++ it("reports failed files outside the dismissed picker", async () => {+ state.move.mockRejectedValue(new Error("Missing.pdf: File unavailable"));+ const close = vi.fn();+ render(+ <MantineProvider>+ <AddToLibraryModal+ files={[{ id: "one" } as StirlingFileStub]}+ onClose={close}+ />+ </MantineProvider>,+ );+ await userEvent.click(screen.getByRole("button", { name: "Add here" }));+ await waitFor(() =>+ expect(state.alert).toHaveBeenLastCalledWith(+ expect.objectContaining({+ alertType: "error",+ body: "Missing.pdf: File unavailable",+ }),+ ),+ );+ expect(close).toHaveBeenCalledOnce();+ expect(state.dismiss).toHaveBeenCalledWith("progress");+ });+});diff --git a/frontend/editor/src/core/components/filesPage/AddToLibraryModal.tsx b/frontend/editor/src/core/components/filesPage/AddToLibraryModal.tsxnew file mode 100644index 0000000000..2a2778320f--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/AddToLibraryModal.tsx@@ -0,0 +1,63 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { LibraryPickerModal } from "@app/components/filesPage/LibraryPickerModal";+import { LibraryFilePicker } from "@app/components/filesPage/LibraryFilePicker";+import { useFilesPage } from "@app/contexts/FilesPageContext";+import { alert, dismissToast } from "@app/components/toast";+import type { StirlingFileStub } from "@app/types/fileContext";+import type { FolderId } from "@app/types/folder";++/** Uploads continue after dismissal, without changing the underlying library navigation. */+export function AddToLibraryModal({+ files,+ onClose,+}: {+ files: StirlingFileStub[];+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const { moveFilesTo } = useFilesPage();+ const [busy, setBusy] = useState(false);+ const add = async (folderId: FolderId | null) => {+ const ids = files.map((file) => file.id);+ onClose();+ const progress = alert({+ title: t("filesPage.addingToLibrary", "Adding to Stirling library…"),+ isPersistentPopup: true,+ expandable: false,+ });+ try {+ await moveFilesTo(ids, folderId, { uploadToRoot: true });+ alert({+ alertType: "success",+ title: t("filesPage.addedToLibrary", "Added to Stirling library"),+ expandable: false,+ });+ } catch (cause) {+ alert({+ alertType: "error",+ title: t(+ "filesPage.addToLibraryFailed",+ "Some files could not be added",+ ),+ body: cause instanceof Error ? cause.message : String(cause),+ isPersistentPopup: true,+ });+ } finally {+ dismissToast(progress);+ }+ };+ return (+ <LibraryPickerModal opened={files.length > 0} onClose={onClose} busy={busy}>+ <LibraryFilePicker+ onBusyChange={setBusy}+ onExternalPickerChange={() => {}}+ destination={{+ fileCount: files.length,+ onClose,+ onConfirm: (folderId) => void add(folderId),+ }}+ />+ </LibraryPickerModal>+ );+}diff --git a/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsx b/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsxindex c7cf3a196c..a1be8fe507 100644--- a/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsx+++ b/frontend/editor/src/core/components/filesPage/DeleteFolderDialog.tsx@@ -85,7 +85,7 @@ export function DeleteFolderDialog({): t("filesPage.deleteFolderKeepHint",- "Files inside will be moved to All files.",+ "Files inside will be moved to Stirling library.",)}</Text>)}diff --git a/frontend/editor/src/core/components/filesPage/FileDetailsActions.tsx b/frontend/editor/src/core/components/filesPage/FileDetailsActions.tsxindex a46fc71d3a..b85dc5b181 100644--- a/frontend/editor/src/core/components/filesPage/FileDetailsActions.tsx+++ b/frontend/editor/src/core/components/filesPage/FileDetailsActions.tsx@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";+import { isBrowserOnlyFile } from "@app/components/filesPage/fileOrigin";import { FileId } from "@app/types/file";import { StirlingFileStub } from "@app/types/fileContext";@@ -11,7 +12,7 @@ export interface FileDetailsActionsProps {/** The only selected file, or null for a multi-selection. */single: StirlingFileStub | null;fileCount: number;- /** Selected files with no server copy yet; empty hides Save to server. */+ /** Selected files with no server copy yet; empty hides Add to library. */localOnlyFiles: StirlingFileStub[];sharingEnabled: boolean;downloading: boolean;@@ -20,7 +21,7 @@ export interface FileDetailsActionsProps {onMove: (fileIds: FileId[]) => void;onRemove: (fileIds: FileId[]) => void;onSaveToServer?: (files: StirlingFileStub[]) => void;- /** When set, Save to server renders disabled with this tooltip (storage off). */+ /** Keeps Add to library visible but disabled, with this explanation as a tooltip. */saveToServerDisabledReason?: string | null;onShare: () => void;}@@ -28,10 +29,6 @@ export interface FileDetailsActionsProps {const ICON_SIZE = 20;const MENU_ICON_SIZE = "1.1rem";-/**- * The details panel's action row: one primary CTA, download, and everything- * else behind an overflow menu.- */export function FileDetailsActions({selectedFileIds,single,@@ -59,6 +56,10 @@ export function FileDetailsActions({? t("filesPage.download", "Download"): t("filesPage.downloadAll", "Download all");const showSaveToServer = Boolean(onSaveToServer) && localOnlyFiles.length > 0;+ const browserOnlyIds = new Set(+ localOnlyFiles.filter(isBrowserOnlyFile).map((file) => file.id),+ );+ const movableIds = selectedFileIds.filter((id) => !browserOnlyIds.has(id));const saveToServerDisabled = Boolean(saveToServerDisabledReason);return (@@ -73,7 +74,7 @@ export function FileDetailsActions({</Button><Tooltip label={downloadLabel} withinPortal><ActionIcon- variant="secondary"+ variant="tertiary"loading={downloading}onClick={onDownload}aria-label={downloadLabel}@@ -84,16 +85,14 @@ export function FileDetailsActions({<Menu shadow="md" width={230} position="top-end" withinPortal><Menu.Target><ActionIcon- variant="secondary"+ variant="tertiary"aria-label={t("filesPage.bulkActions", "Actions")}><Icon name="ellipsis-vertical" size={ICON_SIZE} /></ActionIcon></Menu.Target><Menu.Dropdown>- {/* Share is single-file only. When sharing is disabled in server- config (storage.sharing.enabled=false) the item stays listed but- disabled, so the feature is discoverable rather than absent. */}+ {/* Keep sharing discoverable when server settings disable it. */}{single && (<Tooltiplabel={t(@@ -114,12 +113,14 @@ export function FileDetailsActions({</Menu.Item></Tooltip>)}- <Menu.Item- leftSection={<Icon name="folder-input" size={MENU_ICON_SIZE} />}- onClick={() => onMove(selectedFileIds)}- >- {t("filesPage.moveTo", "Move to…")}- </Menu.Item>+ {movableIds.length > 0 && (+ <Menu.Item+ leftSection={<Icon name="folder-input" size={MENU_ICON_SIZE} />}+ onClick={() => onMove(movableIds)}+ >+ {t("filesPage.moveTo", "Move to…")}+ </Menu.Item>+ )}{showSaveToServer && (<Tooltiplabel={saveToServerDisabledReason}@@ -135,7 +136,7 @@ export function FileDetailsActions({disabled={saveToServerDisabled}onClick={() => onSaveToServer?.(localOnlyFiles)}>- {t("filesPage.saveToServer", "Save to server")}+ {t("filesPage.addToLibrary", "Add to Stirling library…")}</Menu.Item></Tooltip>)}diff --git a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsxindex 883e2fa8ba..76306785ea 100644--- a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx+++ b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.stories.tsx@@ -42,7 +42,7 @@ export const Default: Story = {args: {selectedFileIds: [singleFile.id],fileMap,- currentFolder: null,+ foldersById: new Map(),onClose: () => {},onAddToWorkspace: () => {},onMove: () => {},@@ -53,7 +53,8 @@ export const Default: Story = {export const InFolder: Story = {args: {...Default.args,- currentFolder: folder,+ foldersById: new Map([[folder.id, folder]]),+ fileMap: new Map([[singleFile.id, { ...singleFile, folderId: folder.id }]]),},};@@ -71,7 +72,7 @@ export const MultiSelect: Story = {[fileA.id, fileA],[fileB.id, fileB],]),- currentFolder: null,+ foldersById: new Map(),onClose: () => {},onAddToWorkspace: () => {},onMove: () => {},diff --git a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsxindex 05c186265b..64a0b8f84d 100644--- a/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx+++ b/frontend/editor/src/core/components/filesPage/FileDetailsPanel.tsx@@ -1,11 +1,11 @@-import React, { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { Badge, Tooltip } from "@mantine/core";import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";import { FileId } from "@app/types/file";-import { FolderRecord } from "@app/types/folder";+import type { FolderId, FolderRecord } from "@app/types/folder";import { StirlingFileStub } from "@app/types/fileContext";import { formatFileSize, getFileDate } from "@app/utils/fileUtils";import {@@ -23,30 +23,33 @@ import {DetailField,} from "@app/components/filesPage/VersionTimeline";import { FileDetailsActions } from "@app/components/filesPage/FileDetailsActions";+import { getFileOrigin } from "@app/components/filesPage/fileOrigin";import "@app/components/filesPage/FilesPage.css";interface FileDetailsPanelProps {+ /** Picker hosts choose a version without exposing workspace or library mutations. */+ onPickVersion?: (file: StirlingFileStub) => void;selectedFileIds: FileId[];fileMap: Map<FileId, StirlingFileStub>;- currentFolder: FolderRecord | null;+ foldersById: ReadonlyMap<FolderId, FolderRecord>;onClose: () => void;- onAddToWorkspace: (fileIds: FileId[]) => void;- onMove: (fileIds: FileId[]) => void;- onRemove: (fileIds: FileId[]) => void;- /** Save to server; only shown when at least one selected file is local-only. */+ onAddToWorkspace?: (fileIds: FileId[]) => void;+ onMove?: (fileIds: FileId[]) => void;+ onRemove?: (fileIds: FileId[]) => void;+ /** Receives selected files without a server copy; omitting it hides Add to library. */onSaveToServer?: (files: StirlingFileStub[]) => void;- /** When set, Save to server renders disabled with this tooltip (storage off). */+ /** Keeps Add to library visible but disabled, with this explanation as a tooltip. */saveToServerDisabledReason?: string | null;- /** On small screens, show a compact "Version journey" button instead of the- * full inline timeline (which opens onOpenVersionHistory). */+ /** Replaces the inline version timeline with a button that invokes onOpenVersionHistory. */compactVersions?: boolean;onOpenVersionHistory?: () => void;}export function FileDetailsPanel({+ onPickVersion,selectedFileIds,fileMap,- currentFolder,+ foldersById,onClose,onAddToWorkspace,onMove,@@ -66,21 +69,16 @@ export function FileDetailsPanel({[selectedFileIds, fileMap],);- // Hooks must run before any early return.const [downloading, setDownloading] = useState(false);const [shareModalOpen, setShareModalOpen] = useState(false);- // Metadata (size/type/dates) is collapsed by default so the panel stays- // short and the action buttons keep their pinned footer in view.+ // Collapsed metadata leaves room for the preview and footer actions.const [fieldsOpen, setFieldsOpen] = useState(false);- // Version journey is collapsed by default so the panel stays short.const [versionsOpen, setVersionsOpen] = useState(false);- // Document classification read from PDF metadata, plus its (collapsed) section.- // Stored as label ids; resolve to display names via the seam.const [classification, setClassification] = useState<string[] | null>(null);const [classificationOpen, setClassificationOpen] = useState(false);const classificationEnabled = useClassificationEnabled();+ // Stored classification values are IDs; display names depend on the active locale.const labelName = useLabelName();- // Version chain for the selected file; empty for v1 or multi-select.const [versionChain, setVersionChain] = useState<StirlingFileStub[]>([]);const singleFileForChain = files.length === 1 ? files[0] : null;useEffect(() => {@@ -105,11 +103,6 @@ export function FileDetailsPanel({};}, [singleFileForChain]);- // Show the file's classification labels: the stub's cached copy when present- // (free — no byte load), else read the PDF metadata via the shared service.- // Gated on classification being enabled (SaaS + AI): off-feature we never read- // the metadata or show the section, so a PDF that happens to carry the- // StirlingPDFClassification key never reveals the feature in a build without it.useEffect(() => {setClassification(null);if (!classificationEnabled) return;@@ -133,9 +126,11 @@ export function FileDetailsPanel({}const single = files.length === 1 ? files[0] : null;+ const selectedFolder = single?.folderId+ ? foldersById.get(single.folderId)+ : undefined;const totalSize = files.reduce((sum, f) => sum + f.size, 0);const ext = single ? (single.name.split(".").pop() ?? "").toUpperCase() : "";- // Files still needing a server upload; drives Save-to-server visibility.const localOnlyFiles = files.filter((f) => f.remoteStorageId == null);const handleDownload = async () => {@@ -210,10 +205,7 @@ export function FileDetailsPanel({<h3 style={{ margin: 0, wordBreak: "break-word", flex: 1 }}>{single.name}</h3>- {ext && (- // Custom span; Mantine Badge default rendered invisible in dark mode.- <span className="files-page-details-ext-tag">{ext}</span>- )}+ {ext && <span className="files-page-details-ext-tag">{ext}</span>}{(single.versionNumber ?? 1) > 1 && (<Badge size="sm" color="blue">v{single.versionNumber}@@ -262,9 +254,11 @@ export function FileDetailsPanel({<DetailFieldlabel={t("filesPage.field.folder", "Folder")}value={- currentFolder- ? currentFolder.name- : t("filesPage.allFiles", "All files")+ selectedFolder+ ? selectedFolder.name+ : !single.folderId && getFileOrigin(single) === "local"+ ? t("filesPage.recentFiles", "Recents")+ : t("filesPage.allFiles", "Stirling library")}/></div>@@ -321,19 +315,11 @@ export function FileDetailsPanel({)}</>)}- {/* Version journey. Each tool run writes a new StirlingFile- with the same `originalFileId` and an incremented- `versionNumber`, so the chain reconstructs the edit- timeline. The previous file manager exposed this and the- refactored one had silently dropped it; this revival also- shows WHICH tool was added at each step (the delta from- the prior version) so the user can read the journey- top-to-bottom. Long chains (> 6) collapse the middle. */}{versionChain.length > 1 &&(compactVersions && onOpenVersionHistory ? (<ButtonleftSection={<Icon name="rotate-ccw-clock" size={20} />}- variant="secondary"+ variant="tertiary"onClick={onOpenVersionHistory}>{t(@@ -371,6 +357,7 @@ export function FileDetailsPanel({</Button>{versionsOpen && (<VersionTimeline+ onPickVersion={onPickVersion}chain={versionChain}currentId={single.id}onAddToWorkspace={onAddToWorkspace}@@ -395,23 +382,24 @@ export function FileDetailsPanel({)}</div>- <FileDetailsActions- selectedFileIds={selectedFileIds}- single={single}- fileCount={files.length}- localOnlyFiles={localOnlyFiles}- sharingEnabled={sharingEnabled}- downloading={downloading}- onDownload={handleDownload}- onAddToWorkspace={onAddToWorkspace}- onMove={onMove}- onRemove={onRemove}- onSaveToServer={onSaveToServer}- saveToServerDisabledReason={saveToServerDisabledReason}- onShare={() => setShareModalOpen(true)}- />- {/* Single panel-level mount; gated on sharingEnabled. */}- {single && sharingEnabled && (+ {onAddToWorkspace && onMove && onRemove && (+ <FileDetailsActions+ selectedFileIds={selectedFileIds}+ single={single}+ fileCount={files.length}+ localOnlyFiles={localOnlyFiles}+ sharingEnabled={sharingEnabled}+ downloading={downloading}+ onDownload={handleDownload}+ onAddToWorkspace={onAddToWorkspace}+ onMove={onMove}+ onRemove={onRemove}+ onSaveToServer={onSaveToServer}+ saveToServerDisabledReason={saveToServerDisabledReason}+ onShare={() => setShareModalOpen(true)}+ />+ )}+ {single && sharingEnabled && !onPickVersion && (<ShareManagementModalopened={shareModalOpen}onClose={() => setShareModalOpen(false)}diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.accessibility.test.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.accessibility.test.tsxnew file mode 100644index 0000000000..db717174fa--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/FileGrid.accessibility.test.tsx@@ -0,0 +1,113 @@+import type { ComponentProps } from "react";+import { render, screen, within } from "@testing-library/react";+import { MantineProvider } from "@mantine/core";+import { describe, expect, it, vi } from "vitest";+import { FileGrid } from "@app/components/filesPage/FileGrid";+import { FileContextProvider } from "@app/contexts/FileContext";+import { createNewStirlingFileStub } from "@app/types/fileContext";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback: string, values?: Record<string, string>) => {+ if (key === "filesPage.file") return "Fichier";+ if (key === "filesPage.selectedFile")+ return `${values?.name}, sélectionné`;+ return fallback ?? key;+ },+ }),+}));+vi.mock("@app/hooks/useLazyThumbnail", () => ({+ useLazyThumbnail: () => undefined,+ useDiskThumbnail: () => undefined,+}));++const stored = createNewStirlingFileStub(new File(["text"], "README"));+const disk = {+ path: "/documents/README",+ name: "README",+ sizeBytes: 4,+ lastModified: 0,+};+const props: ComponentProps<typeof FileGrid> = {+ entries: [{ kind: "file", file: stored }],+ selectedFileIds: new Set(),+ viewMode: "grid",+ onSelectFile: () => {},+ onOpenFolder: () => {},+ onOpenFile: () => {},+ onMoveFiles: () => {},+ onMoveFolder: () => {},+ onRenameFolder: () => {},+ onDeleteFolder: () => {},+ onChangeFolderAppearance: () => {},+ onRemoveFiles: () => {},+ onPromptMoveFiles: () => {},+};++function grid(overrides: Partial<ComponentProps<typeof FileGrid>>) {+ return (+ <MantineProvider>+ <FileContextProvider>+ <FileGrid {...props} {...overrides} />+ </FileContextProvider>+ </MantineProvider>+ );+}++describe("file library accessibility", () => {+ it("announces a single selected card without changing its list semantics", () => {+ const view = render(grid({}));+ expect(+ screen.getByRole("listitem", { name: "README" }),+ ).not.toHaveAttribute("aria-selected");++ view.rerender(grid({ selectedFileIds: new Set([stored.id]) }));+ const selected = screen.getByRole("listitem", {+ name: "README, sélectionné",+ });+ expect(selected).not.toHaveAttribute("aria-selected");+ expect(within(selected).queryByRole("checkbox")).not.toBeInTheDocument();++ view.rerender(grid({}));+ expect(screen.getByRole("listitem", { name: "README" })).toBeVisible();+ });++ it("announces native picker selection through its label and checkbox", () => {+ render(+ grid({+ entries: [{ kind: "diskFile", disk }],+ picker: {+ isEligible: () => true,+ selectionDisabled: false,+ disabledReason: () => undefined,+ selectedDiskPaths: new Set([disk.path]),+ onSelectDiskFile: () => {},+ onSetDiskSelection: () => {},+ onUnzipFile: () => {},+ },+ }),+ );+ const card = screen.getByRole("listitem", { name: "README, sélectionné" });+ expect(card).not.toHaveAttribute("aria-selected");+ expect(within(card).getByRole("checkbox")).toBeChecked();+ });++ it.each([+ ["grid", "file"],+ ["grid", "diskFile"],+ ["list", "file"],+ ["list", "diskFile"],+ ] as const)(+ "translates the extensionless fallback in %s for %s entries",+ (viewMode, kind) => {+ render(+ grid({+ viewMode,+ entries: [kind === "file" ? { kind, file: stored } : { kind, disk }],+ }),+ );+ expect(screen.getByText("Fichier")).toBeVisible();+ expect(screen.queryByText("FILE")).not.toBeInTheDocument();+ },+ );+});diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsxindex 2822b6b31d..d6ee7e9536 100644--- a/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx+++ b/frontend/editor/src/core/components/filesPage/FileGrid.stories.tsx@@ -91,6 +91,38 @@ type Story = StoryObj<typeof meta>;export const Default: Story = {};+export const SingleSelection: Story = {+ args: {+ selectedFileIds: new Set([localFile.id]),+ },+};++export const NativeFilePicker: Story = {+ args: {+ entries: [+ {+ kind: "diskFile",+ disk: {+ path: "/documents/README",+ name: "README",+ sizeBytes: 1000,+ lastModified: 0,+ },+ },+ ...fileEntries,+ ],+ picker: {+ isEligible: () => true,+ selectionDisabled: false,+ disabledReason: () => undefined,+ selectedDiskPaths: new Set(["/documents/README"]),+ onSelectDiskFile: () => {},+ onSetDiskSelection: () => {},+ onUnzipFile: () => {},+ },+ },+};+export const ListMode: Story = {args: {viewMode: "list",diff --git a/frontend/editor/src/core/components/filesPage/FileGrid.tsx b/frontend/editor/src/core/components/filesPage/FileGrid.tsxindex b26f22d7a2..54007833bd 100644--- a/frontend/editor/src/core/components/filesPage/FileGrid.tsx+++ b/frontend/editor/src/core/components/filesPage/FileGrid.tsx@@ -22,14 +22,22 @@ import {rowHeightPx,} from "@app/components/filesPage/useVirtualFileRows";import { StirlingFileStub } from "@app/types/fileContext";-import { formatFileSize, getFileDate } from "@app/utils/fileUtils";+import {+ detectFileExtension,+ formatFileSize,+ getFileDate,+} from "@app/utils/fileUtils";import {FILES_PAGE_DRAG_TYPE,parseFilesPageDragPayload,serialiseFilesPageDragPayload,} from "@app/components/filesPage/dragDrop";import { useDropTarget } from "@app/components/filesPage/useDropTarget";-import { getFileOrigin } from "@app/components/filesPage/fileOrigin";+import {+ getFileOrigin,+ isBrowserOnlyFile,+} from "@app/components/filesPage/fileOrigin";+import { libraryFileDate } from "@app/components/filesPage/libraryFileDate";import { FileOriginBadge } from "@app/components/filesPage/FileOriginBadge";import { FolderProcessingTag } from "@app/components/filesPage/FolderProcessingTag";import { FolderOriginBadge } from "@app/components/filesPage/FolderOriginBadge";@@ -49,16 +57,16 @@ import { OpenInNewWindowMenuItem } from "@app/components/filesPage/OpenInNewWindexport type FilesPageViewMode = "grid" | "list";-/** A disk file's place in its working folder's pipeline, when one is attached. */+/** A file's place in its working folder's pipeline, when one is attached. */export type DiskFileState = "done" | "processing" | "failed" | "waiting";export interface FilesPageEntry {kind: "folder" | "file" | "diskFile";folder?: FolderRecord;- /** Number of files inside this folder (folder entries only). */+folderFileCount?: number;file?: StirlingFileStub;- /** A file read straight off a mounted directory (kind "diskFile"). */+disk?: DiskFileEntry;/** The file's processing state; absent on a folder with no pipeline. */diskState?: DiskFileState;@@ -69,20 +77,33 @@ export interface FilesPageEntry {parentPath?: string;}+/** Picker mode hides library mutations; opening a file confirms its selection. */+export interface FileGridPicker {+ foldersOnly?: boolean;+ /** Format and processing eligibility only; capacity and busy state must not change the selection count. */+ isEligible: (entry: FilesPageEntry) => boolean;+ selectionDisabled: boolean;+ disabledReason: (entry: FilesPageEntry) => string | undefined;+ selectedDiskPaths: ReadonlySet<string>;+ onSelectDiskFile: (entry: DiskFileEntry, shift: boolean) => void;+ onSetDiskSelection: (entries: DiskFileEntry[]) => void;+ onUnzipFile: (file: StirlingFileStub) => void;+}+interface FileGridProps {+ picker?: FileGridPicker;entries: FilesPageEntry[];selectedFileIds: Set<FileId>;- /** Ids of files loaded in the active workspace. */+activeWorkspaceFileIds?: Set<string>;viewMode: FilesPageViewMode;onSelectFile: (id: FileId, shiftKey: boolean, ctrlKey: boolean) => void;- /** Replace the entire selection set. */+onSetSelection?: (ids: Set<FileId>) => void;onOpenFolder: (id: FolderId) => void;- /** "Add to workspace". */onOpenFile: (file: StirlingFileStub) => void;onOpenDiskFile?: (entry: DiskFileEntry) => void;- /** Open the processing-setup dialog for a folder (create or edit). */+onStartProcessing?: (folder: FolderRecord) => void;/** Retry one failed file, by its name in the open folder. */onRetryFile?: (name: string) => void;@@ -90,38 +111,38 @@ interface FileGridProps {onRevertFile?: (name: string) => void;/** Ask to restore every original in a folder; the confirm dialog lives upstream. */onRequestRevertAll?: (folder: FolderRecord) => void;- onMoveFiles: (+ onMoveFiles?: (fileIds: FileId[],targetFolderId: FolderId | null,) => void | Promise<void>;- onMoveFolder: (+ onMoveFolder?: (folderId: FolderId,newParentId: FolderId | null,) => void | Promise<void>;- onRenameFolder: (folder: FolderRecord) => void;- onDeleteFolder: (folder: FolderRecord) => void;- onChangeFolderAppearance: (+ onRenameFolder?: (folder: FolderRecord) => void;+ onDeleteFolder?: (folder: FolderRecord) => void;+ onChangeFolderAppearance?: (folderId: FolderId,appearance: { color?: string; icon?: string | null },) => void;- onRemoveFiles: (fileIds: FileId[]) => void;- onPromptMoveFiles: (fileIds: FileId[]) => void;- /** Per-file Save to server; hidden when file already has remoteStorageId. */+ onRemoveFiles?: (fileIds: FileId[]) => void;+ onPromptMoveFiles?: (fileIds: FileId[]) => void;+ /** Per-file library upload; hidden when file already has remoteStorageId. */onSaveToServer?: (file: StirlingFileStub) => void;/** Open the version-history modal for a file (only when it has >1 version). */onVersionHistory?: (file: StirlingFileStub) => void;- /** Download a copy (desktop: save a copy). */+onDownloadFile?: (file: StirlingFileStub) => void;- /** Open the rename dialog for a file. */+onRenameFile?: (file: StirlingFileStub) => void;- /** Save a second copy of the file into the library. */+onDuplicateFile?: (file: StirlingFileStub) => void;- /** When set, the Save to server item renders disabled with this tooltip. */+ /** When set, the library upload item renders disabled with this tooltip. */saveToServerDisabledReason?: string | null;/** When supplied the list-view column headers become sortable. */sortMode?: FilesPageSortMode;onChangeSortMode?: (mode: FilesPageSortMode) => void;- /** Drives the empty-state copy. */+currentTab?: "all" | "cloud" | "recent" | "shared" | "sharedByMe";/** A filter is applied; an empty result then means "no matches", not "no files". */searchActive?: boolean;@@ -129,34 +150,15 @@ interface FileGridProps {serverReachable?: boolean;/** Empty-state CTA handlers; if absent the matching button hides. */onEmptyUpload?: () => void;- /** The New-folder control for the empty state, built by the page that owns the- * destinations. Passed in rather than rebuilt here so the empty state and the- * header cannot offer different things. */+ /** Reuse the host's folder control so header and empty-state destinations agree. */emptyNewFolderControl?: React.ReactNode;- /** Non-null disables the New folder CTA with this reason as tooltip. */- newFolderDisabledReason?: string | null;- /**- * Where a failed drop reports its message. A prop rather than the folder- * context so the grid renders without a FolderProvider (its tests do), and- * so no item needs a context subscription that memoization would then fight.- */+ /** Report failures through the host; per-row context subscriptions defeat memoization. */onActionError?: (message: string) => void;- /**- * What acts on the current selection, built by the page that owns the- * handlers. Rendered in the list's column header, which grid view lacks.- */- selectionActions?: React.ReactNode;}/**- * One stable dispatch object shared by every card and row. The grid's- * callback props change identity on every parent render, and per-item- * closures would too — either defeats React.memo and turns each selection- * click or landed thumbnail into a full-list re-render. Items call these- * with their own id/record instead; the ref always sees the current props,- * so behavior stays live while identity stays fixed. Selection-aware- * behavior (drag payloads, multi-move) lives here too, so items never hold- * the selection Set — whose identity changes on every click — as a prop.+ * Stable callbacks read current props through refs so selection changes do not rerender every row.+ * Keep selection-aware actions here: passing the selection Set to each row defeats React.memo.*/interface FileGridActions {selectFile: (id: FileId, shiftKey: boolean, ctrlKey: boolean) => void;@@ -167,7 +169,7 @@ interface FileGridActions {retryFile: (name: string) => void;revertFile: (name: string) => void;requestRevertAll: (folder: FolderRecord) => void;- /** Surface a failed folder action's reason the way a failed drop's is. */+reportError: (err: unknown, label: string) => void;renameFolder: (folder: FolderRecord) => void;deleteFolder: (folder: FolderRecord) => void;@@ -175,11 +177,7 @@ interface FileGridActions {folderId: FolderId,appearance: { color?: string; icon?: string | null },) => void;- /**- * Failures surface here, not in the item: the memoized folder items would- * otherwise each need the folder context for its error banner, and one- * context subscription inside an item undoes what the memo buys.- */+dropFilesOnFolder: (fileIds: FileId[], target: FolderId) => void;dropFolderOnFolder: (folderId: FolderId, target: FolderId) => void;removeFile: (id: FileId) => void;@@ -192,6 +190,8 @@ interface FileGridActions {downloadFile: (file: StirlingFileStub) => void;renameFile: (file: StirlingFileStub) => void;duplicateFile: (file: StirlingFileStub) => void;+ selectDiskFile: (entry: DiskFileEntry, shift: boolean) => void;+ unzipFile: (file: StirlingFileStub) => void;}export function FileGrid(props: FileGridProps & { loading?: boolean }) {@@ -211,11 +211,9 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {const { t } = useTranslation();const translateRef = useRef(t);translateRef.current = t;- // One subscription for the whole grid: every row calling the badge hook- // would rebuild the full badge map per row on any file or run change. The- // hook keeps per-file array identity stable across rebuilds, so memoized- // items re-render only when their own badges change.+ // One badge subscription avoids rebuilding the full map per row.const policyBadges = usePolicyFileBadges();+ const processingBlock = useServerProcessingBlock();const actions = useMemo<FileGridActions>(() => {const reportDrop = (err: unknown, label: string) => {console.error(`[FileGrid] ${label}`, err);@@ -234,6 +232,9 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {);};return {+ selectDiskFile: (entry, shift) =>+ latest.current.picker?.onSelectDiskFile(entry, shift),+ unzipFile: (file) => latest.current.picker?.onUnzipFile(file),selectFile: (id, shiftKey, ctrlKey) =>latest.current.onSelectFile(id, shiftKey, ctrlKey),openFolder: (id) => latest.current.onOpenFolder(id),@@ -244,24 +245,24 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {revertFile: (name) => latest.current.onRevertFile?.(name),requestRevertAll: (folder) => latest.current.onRequestRevertAll?.(folder),reportError: (err, label) => reportDrop(err, label),- renameFolder: (folder) => latest.current.onRenameFolder(folder),- deleteFolder: (folder) => latest.current.onDeleteFolder(folder),+ renameFolder: (folder) => latest.current.onRenameFolder?.(folder),+ deleteFolder: (folder) => latest.current.onDeleteFolder?.(folder),changeFolderAppearance: (folderId, appearance) =>- latest.current.onChangeFolderAppearance(folderId, appearance),+ latest.current.onChangeFolderAppearance?.(folderId, appearance),dropFilesOnFolder: (fileIds, target) => {- Promise.resolve(latest.current.onMoveFiles(fileIds, target)).catch(+ Promise.resolve(latest.current.onMoveFiles?.(fileIds, target)).catch((err) => reportDrop(err, "move files into folder"),);},dropFolderOnFolder: (folderId, target) => {- Promise.resolve(latest.current.onMoveFolder(folderId, target)).catch(+ Promise.resolve(latest.current.onMoveFolder?.(folderId, target)).catch((err) => reportDrop(err, "move folder"),);},- removeFile: (id) => latest.current.onRemoveFiles([id]),+ removeFile: (id) => latest.current.onRemoveFiles?.([id]),requestMoveFile: (id) => {const selected = latest.current.selectedFileIds;- latest.current.onPromptMoveFiles(+ latest.current.onPromptMoveFiles?.(selected.has(id) ? Array.from(selected) : [id],);},@@ -284,8 +285,8 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {return <SkeletonGrid viewMode={viewMode} />;}- if (entries.length === 0) {- const emptyState = (+ const emptyState =+ entries.length === 0 ? (<EmptyStatetab={currentTab}searchActive={searchActive}@@ -293,31 +294,31 @@ export function FileGrid(props: FileGridProps & { loading?: boolean }) {onUpload={onEmptyUpload}newFolderControl={emptyNewFolderControl}/>- );- // When a filter empties the list view, keep the column headers in place and- // show the no-results message beneath them, rather than replacing the whole- // table. Grid view (cards, no headers) just shows the empty state.- if (viewMode === "list" && searchActive) {- return (- <>- <ListView {...props} actions={actions} policyBadges={policyBadges} />- {emptyState}- </>- );- }- return emptyState;- }+ ) : null;- if (viewMode === "list") {+ if (viewMode === "list" && (entries.length > 0 || searchActive)) {return (- <ListView {...props} actions={actions} policyBadges={policyBadges} />+ <ListView+ {...props}+ actions={actions}+ policyBadges={policyBadges}+ processingBlock={processingBlock}+ emptyState={emptyState}+ />);}- return <GridView {...props} actions={actions} policyBadges={policyBadges} />;+ if (emptyState) return emptyState;+ return (+ <GridView+ {...props}+ actions={actions}+ policyBadges={policyBadges}+ processingBlock={processingBlock}+ />+ );}function SkeletonGrid({ viewMode }: { viewMode: FilesPageViewMode }) {- // Six placeholders mirroring the card layout while IDB resolves.const placeholders = Array.from({ length: 6 });if (viewMode === "list") {return (@@ -369,7 +370,6 @@ function SkeletonGrid({ viewMode }: { viewMode: FilesPageViewMode }) {}interface EmptyStateProps {- /** Drives copy + iconography. */tab?: "all" | "cloud" | "recent" | "shared" | "sharedByMe";/** When true the empty list is the result of a filter, not a bare folder. */searchActive?: boolean;@@ -390,8 +390,6 @@ function EmptyState({}: EmptyStateProps) {const { t } = useTranslation();- // A filter with no matches isn't an empty folder - say so, and skip the- // upload / new-folder CTAs since clearing the filter is the way out.if (searchActive) {return (<div className="files-page-empty">@@ -461,7 +459,7 @@ function EmptyState({};}})();- // Recent/Shared tabs are read-only filters; Local is cloud-only for folders.+const readOnlyTab =tab === "recent" || tab === "shared" || tab === "sharedByMe";const showUpload = Boolean(onUpload) && !readOnlyTab;@@ -492,7 +490,15 @@ function EmptyState({);}+type FileGridLayoutProps = FileGridProps & {+ actions: FileGridActions;+ policyBadges: Map<string, FileItemPolicyRef[]>;+ processingBlock: string | null;+};+function GridView({+ picker,+ currentTab,entries,selectedFileIds,activeWorkspaceFileIds,@@ -505,16 +511,15 @@ function GridView({serverReachable,actions,policyBadges,-}: FileGridProps & {- actions: FileGridActions;- policyBadges: Map<string, FileItemPolicyRef[]>;-}) {+ processingBlock,+}: FileGridLayoutProps) {const { range, padTop, padBottom, setContainer } = useVirtualFileRows(entries.length,rowHeightPx(true),true,);return (+ // Cards contain menus and checkboxes; retain list semantics and name selected cards explicitly.<div className="files-page-grid" role="list" ref={setContainer}>{padTop > 0 && (<div@@ -528,10 +533,12 @@ function GridView({return (<FolderCardkey={`folder-${entry.folder.id}`}+ selectionOnly={Boolean(picker)}folder={entry.folder}fileCount={entry.folderFileCount ?? 0}parentPath={entry.parentPath}serverReachable={serverReachable ?? false}+ processingBlock={processingBlock}actions={actions}/>);@@ -540,6 +547,9 @@ function GridView({return (<DiskFileCardkey={`disk-${entry.disk.path}`}+ selectionOnly={Boolean(picker)}+ isSelected={picker?.selectedDiskPaths.has(entry.disk.path)}+ disabledReason={picker?.disabledReason(entry)}entry={entry.disk}state={entry.diskState}locked={entry.processingLocked ?? false}@@ -552,7 +562,11 @@ function GridView({return (<FileCardkey={`file-${entry.file.id}`}+ selectionOnly={Boolean(picker)}+ disabledReason={picker?.disabledReason(entry)}+ folderPicker={picker?.foldersOnly}file={entry.file}+ date={libraryFileDate(entry.file, currentTab)}parentPath={entry.parentPath}processingState={entry.diskState}locked={entry.processingLocked ?? false}@@ -560,7 +574,10 @@ function GridView({isInWorkspace={activeWorkspaceFileIds?.has(entry.file.id) ?? false}- multiSelectActive={selectedFileIds.size >= 2}+ multiSelectActive={+ !picker?.foldersOnly &&+ (Boolean(picker) || selectedFileIds.size >= 2)+ }downloadAvailable={Boolean(onDownloadFile)}renameAvailable={Boolean(onRenameFile)}duplicateAvailable={Boolean(onDuplicateFile)}@@ -585,26 +602,29 @@ function GridView({);}-interface FolderCardProps {+interface FolderItemProps {+ selectionOnly?: boolean;folder: FolderRecord;fileCount: number;- /** Subtitle for search results outside current folder. */+parentPath?: string;serverReachable: boolean;+ processingBlock: string | null;actions: FileGridActions;}const FolderCard = React.memo(function FolderCard({+ selectionOnly,folder,fileCount,parentPath,serverReachable,+ processingBlock,actions,-}: FolderCardProps) {+}: FolderItemProps) {const { t } = useTranslation();const onOpen = () => actions.openFolder(folder.id);- // Only a server folder can go offline: the other kinds take their name, look and- // lifetime from elsewhere, so their edit items are hidden rather than disabled.+ // Mounted folders are managed on disk; only server folders can be offline.const kind = folderKind(folder);const {stateFor: processingStateFor,@@ -615,8 +635,7 @@ const FolderCard = React.memo(function FolderCard({listFiles: listProcessingFiles,} = useProcessingFolders();const processing = processingStateFor(folder);- // Each action surfaces its own failure the way a failed drop does; the- // backend's reason (invalid pipeline, storage disabled) is the useful part.+const resumeProcessing = (label: string) =>Promise.resolve(enableProcessing(folder)).catch((err) =>actions.reportError(err, label),@@ -634,7 +653,6 @@ const FolderCard = React.memo(function FolderCard({actions.reportError(err, label),);const editsDisabled = kind === "server" && !serverReachable;- const processingBlock = useServerProcessingBlock();const editsHidden = kind === "local";const offlineHint = t("filesPage.offlineNoFolderEdits",@@ -658,7 +676,7 @@ const FolderCard = React.memo(function FolderCard({<divrole="listitem"tabIndex={0}- draggable+ draggable={!selectionOnly}onDragStart={(e) => {e.dataTransfer.setData(FILES_PAGE_DRAG_TYPE,@@ -669,15 +687,15 @@ const FolderCard = React.memo(function FolderCard({);e.dataTransfer.effectAllowed = "move";}}- {...dropHandlers}+ {...(selectionOnly ? {} : dropHandlers)}className={`files-page-card is-folder${isDropTarget ? " is-drop-target" : ""}`}- onDoubleClick={onOpen}+ onClick={onOpen}onContextMenu={(e) => {e.preventDefault();kebabRef.current?.click();}}onKeyDown={(e) => {- if (e.key === "Enter") onOpen();+ if (e.target === e.currentTarget && e.key === "Enter") onOpen();}}><div@@ -725,56 +743,60 @@ const FolderCard = React.memo(function FolderCard({}))}</div>- {processing && (+ {processing && !selectionOnly && (<ProcessingFolderStatsrecordId={processing.id}listFiles={listProcessingFiles}/>)}</div>- <div className="files-page-card-actions">- <FolderMenu- folder={folder}- processing={processing}- continuous={kind === "virtual"}- isMount={editsHidden}- canUnmount={folder.parentFolderId === null}- editsDisabled={editsDisabled}- editsDisabledHint={offlineHint}- processingBlock={processingBlock}- variant="kebab"- triggerRef={kebabRef}- onOpen={onOpen}- onStartProcessing={() => actions.startProcessing(folder)}- onRunProcessing={() => void runProcessing("process folder now")}- onStopProcessing={() =>- void stopProcessing("pause processing folder")- }- onResumeProcessing={() => void resumeProcessing("resume processing")}- onRemoveProcessing={() =>- void removeProcessing("remove processing folder")- }- onEditProcessing={() => actions.startProcessing(folder)}- onRevertAll={- kind === "local"- ? () => actions.requestRevertAll(folder)- : undefined- }- onRename={() => actions.renameFolder(folder)}- onChangeAppearance={(appearance) =>- actions.changeFolderAppearance(folder.id, appearance)- }- onDelete={() => actions.deleteFolder(folder)}- />+ <div+ className="files-page-card-actions"+ onClick={(e) => e.stopPropagation()}+ >+ {!selectionOnly && (+ <FolderMenu+ folder={folder}+ processing={processing}+ continuous={kind === "virtual"}+ isMount={editsHidden}+ canUnmount={folder.parentFolderId === null}+ editsDisabled={editsDisabled}+ editsDisabledHint={offlineHint}+ processingBlock={processingBlock}+ variant="kebab"+ triggerRef={kebabRef}+ onOpen={onOpen}+ onStartProcessing={() => actions.startProcessing(folder)}+ onRunProcessing={() => void runProcessing("process folder now")}+ onStopProcessing={() =>+ void stopProcessing("pause processing folder")+ }+ onResumeProcessing={() =>+ void resumeProcessing("resume processing")+ }+ onRemoveProcessing={() =>+ void removeProcessing("remove processing folder")+ }+ onEditProcessing={() => actions.startProcessing(folder)}+ onRevertAll={+ kind === "local"+ ? () => actions.requestRevertAll(folder)+ : undefined+ }+ onRename={() => actions.renameFolder(folder)}+ onChangeAppearance={(appearance) =>+ actions.changeFolderAppearance(folder.id, appearance)+ }+ onDelete={() => actions.deleteFolder(folder)}+ />+ )}</div></div>);});-/**- * A working folder's live per-state counts. The row variant clips, so the states- * worth acting on come first and the title repeats the whole breakdown.- */+/** Put actionable states first because narrow rows clip the breakdown. */function ProcessingFolderStats({recordId,listFiles,@@ -815,7 +837,6 @@ function ProcessingFolderStats({);}-/** Why the file cannot be opened: being replaced now, or waiting its turn to be. */function useLockedHint(state?: DiskFileState): string {const { t } = useTranslation();return state === "processing"@@ -829,7 +850,6 @@ function useLockedHint(state?: DiskFileState): string {);}-/** A file's pipeline state chip; a failed state adds an inline retry. */function FileStateBadge({state,onRetry,@@ -872,8 +892,7 @@ function FileStateBadge({title={retryHint}aria-label={`${failed}: ${retryHint}`}>- {/* Both labels share one grid cell, so the chip is as wide as the wider- of them and swapping on hover moves nothing around it. */}+ {/* Reserve both labels' widths to prevent a hover layout shift. */}<span className="files-page-state-retry-rest" aria-hidden="true">{failed}</span>@@ -894,26 +913,25 @@ function FileStateBadge({/** Stable empty value so badge-less rows keep identical props across renders. */const NO_BADGES: FileItemPolicyRef[] = [];-/** Per-file actions. Shared verbatim by the grid card and the list row, and- * kept in step with the file sidebar's kebab so both surfaces offer the same. */interface FileActionsMenuProps {+ selectionOnly?: boolean;file: StirlingFileStub;triggerRef: React.RefObject<HTMLButtonElement | null>;locked?: boolean;- /** Download / rename / duplicate menu items offered. */downloadAvailable: boolean;renameAvailable: boolean;duplicateAvailable: boolean;- /** Kebab Save to server offered; only fires when file is local-only. */+saveToServerAvailable: boolean;- /** Version-history menu item offered; shown only when file has >1 version. */+versionHistoryAvailable: boolean;- /** When set, the kebab Save to server is disabled with this tooltip. */+saveToServerDisabledReason?: string | null;actions: FileGridActions;}function FileActionsMenu({+ selectionOnly,file,triggerRef,locked = false,@@ -932,6 +950,24 @@ function FileActionsMenu({saveToServerAvailable && file.remoteStorageId == null;const showVersionHistory =versionHistoryAvailable && (file.versionNumber ?? 1) > 1;+ if (selectionOnly) {+ if (!file.name.toLowerCase().endsWith(".zip")) return null;+ return (+ <Tooltip label={t("fileManager.unzip", "Unzip")} withinPortal>+ <ActionIcon+ variant="tertiary"+ aria-label={t("fileManager.unzip", "Unzip")}+ onClick={(event) => {+ event.stopPropagation();+ actions.unzipFile(file);+ }}+ >+ <Icon name="archive-restore" size={20} />+ </ActionIcon>+ </Tooltip>+ );+ }+return (<Menu shadow="md" position="bottom-end" withinPortal width={220}><Menu.Target>@@ -958,16 +994,18 @@ function FileActionsMenu({{t("filesPage.addToWorkspace", "Add to workspace")}</Menu.Item><OpenInNewWindowMenuItem file={file} disabled={locked} />- <Menu.Item- leftSection={<Icon name="folder-input" size={20} />}- onClick={(e) => {- e.stopPropagation();- actions.requestMoveFile(file.id);- }}- data-testid="file-menu-move-to"- >- {t("filesPage.moveTo", "Move to…")}- </Menu.Item>+ {!isBrowserOnlyFile(file) && (+ <Menu.Item+ leftSection={<Icon name="folder-input" size={20} />}+ onClick={(e) => {+ e.stopPropagation();+ actions.requestMoveFile(file.id);+ }}+ data-testid="file-menu-move-to"+ >+ {t("filesPage.moveTo", "Move to…")}+ </Menu.Item>+ )}{(downloadAvailable || renameAvailable || duplicateAvailable) && (<Menu.Divider />@@ -1010,8 +1048,7 @@ function FileActionsMenu({)}{(showSaveToServer || showVersionHistory) && <Menu.Divider />}- {/* Per-file Save to server; shown for local-only files. When- storage is off it stays visible but disabled with a tooltip. */}+{showSaveToServer && (<Tooltiplabel={saveToServerDisabledReason}@@ -1034,7 +1071,7 @@ function FileActionsMenu({: undefined}>- {t("filesPage.saveToServer", "Save to server")}+ {t("filesPage.addToLibrary", "Add to Stirling library…")}</Menu.Item></Tooltip>)}@@ -1067,22 +1104,26 @@ function FileActionsMenu({}interface FileCardProps {+ date: number;+ folderPicker?: boolean;+ selectionOnly?: boolean;+ disabledReason?: string;file: StirlingFileStub;isSelected: boolean;isInWorkspace: boolean;- /** Subtitle for search results outside current folder. */+parentPath?: string;- /** Shows the checkbox once 2+ files are selected. */+multiSelectActive: boolean;- /** Download / rename / duplicate menu items offered. */+downloadAvailable: boolean;renameAvailable: boolean;duplicateAvailable: boolean;- /** Kebab Save to server offered; only fires when file is local-only. */+saveToServerAvailable: boolean;- /** Version-history menu item offered; shown only when file has >1 version. */+versionHistoryAvailable: boolean;- /** When set, the kebab Save to server is disabled with this tooltip. */+saveToServerDisabledReason?: string | null;badges: FileItemPolicyRef[];processingState?: DiskFileState;@@ -1092,6 +1133,10 @@ interface FileCardProps {}const FileCard = React.memo(function FileCard({+ date,+ folderPicker,+ selectionOnly,+ disabledReason,file,parentPath,isSelected,@@ -1112,19 +1157,17 @@ const FileCard = React.memo(function FileCard({const lockedHint = useLockedHint(processingState);const cardRef = useRef<HTMLDivElement>(null);const fileSize = useMemo(() => formatFileSize(file.size), [file.size]);- const fileDate = useMemo(- () => getFileDate({ lastModified: file.lastModified }),- [file.lastModified],- );+ const fileDate = useMemo(() => getFileDate({ lastModified: date }), [date]);const onClick = useCallback((e: React.MouseEvent) =>+ !disabledReason &&actions.selectFile(file.id, e.shiftKey, e.metaKey || e.ctrlKey),- [actions, file.id],+ [actions, file.id, disabledReason],);const onDoubleClick = useCallback(() => {- if (!locked) actions.openFile(file);- }, [locked, actions, file]);+ if (!locked && !disabledReason) actions.openFile(file);+ }, [actions, file, disabledReason, locked]);const handleDragStart = useCallback((e: React.DragEvent<HTMLDivElement>) => {@@ -1137,7 +1180,7 @@ const FileCard = React.memo(function FileCard({[actions, file.id],);- const extension = file.name.split(".").pop()?.toUpperCase() ?? "";+ const extension = detectFileExtension(file.name).toUpperCase();const isPdf = extension === "PDF";const resolvedThumbnail = useLazyThumbnail(file.id,@@ -1149,7 +1192,7 @@ const FileCard = React.memo(function FileCard({const handleContextMenu = useCallback((e: React.MouseEvent) => {e.preventDefault();- // Right-click on unselected card selects first, then opens menu.+if (!isSelected) onClick(e);kebabRef.current?.click();},@@ -1160,17 +1203,29 @@ const FileCard = React.memo(function FileCard({<divref={cardRef}role="listitem"+ aria-label={+ isSelected+ ? t("filesPage.selectedFile", "{{name}}, selected", {+ name: file.name,+ })+ : file.name+ }tabIndex={0}- draggable+ draggable={!selectionOnly}+ aria-disabled={Boolean(disabledReason)}onDragStart={handleDragStart}onClick={onClick}onDoubleClick={onDoubleClick}onContextMenu={handleContextMenu}onKeyDown={(e) => {+ if (e.key === " " && selectionOnly) {+ e.preventDefault();+ if (!disabledReason) actions.selectFile(file.id, e.shiftKey, true);+ }if (e.key === "Enter") onDoubleClick();}}className={`files-page-card${isSelected ? " is-selected" : ""}${isInWorkspace ? " is-in-workspace" : ""}${locked ? " is-locked" : ""}`}- title={locked ? lockedHint : undefined}+ title={disabledReason ?? (locked ? lockedHint : undefined)}>{isInWorkspace && (<span@@ -1181,17 +1236,13 @@ const FileCard = React.memo(function FileCard({{t("filesPage.inWorkspace", "Open")}</span>)}- {/* Checkbox only renders once the user is explicitly in multi-select- mode (2+ files chosen via Ctrl/Shift-click, or one file then- another). For single-select the highlight border on the card is- the only state indicator - avoids the always-on-checkbox- visual noise and matches the file-explorer model. */}+{multiSelectActive && (<div className="files-page-card-selector"><Checkbox+ disabled={Boolean(disabledReason)}checked={isSelected}onClick={(e) => {- // Ctrl-click semantics: toggle this file in/out of the selection.e.stopPropagation();actions.selectFile(file.id, false, true);}}@@ -1215,16 +1266,22 @@ const FileCard = React.memo(function FileCard({) : (<Icon name="file" size={"2rem"} />)}- <span>{extension || "FILE"}</span>+ <span>{extension || t("filesPage.file", "File")}</span></div>)}<div className="files-page-card-origin">- <FileOriginBadge origin={getFileOrigin(file)} compact />+ <FileOriginBadge+ origin={getFileOrigin(file)}+ onDisk={Boolean(file.localFilePath)}+ compact+ /><DiskLinkBadge file={file} compact /></div><FileStateBadgestate={processingState}- onRetry={() => actions.retryFile(file.name)}+ onRetry={+ selectionOnly ? undefined : () => actions.retryFile(file.name)+ }/></div><div className="files-page-card-body">@@ -1246,29 +1303,34 @@ const FileCard = React.memo(function FileCard({</div></div><div className="files-page-card-actions">- <FileActionsMenu- file={file}- triggerRef={kebabRef}- locked={locked}- downloadAvailable={downloadAvailable}- renameAvailable={renameAvailable}- duplicateAvailable={duplicateAvailable}- saveToServerAvailable={saveToServerAvailable}- versionHistoryAvailable={versionHistoryAvailable}- saveToServerDisabledReason={saveToServerDisabledReason}- actions={actions}- />+ {!folderPicker && (+ <FileActionsMenu+ selectionOnly={selectionOnly}+ file={file}+ triggerRef={kebabRef}+ locked={locked}+ downloadAvailable={downloadAvailable}+ renameAvailable={renameAvailable}+ duplicateAvailable={duplicateAvailable}+ saveToServerAvailable={saveToServerAvailable}+ versionHistoryAvailable={versionHistoryAvailable}+ saveToServerDisabledReason={saveToServerDisabledReason}+ actions={actions}+ />+ )}</div></div>);});+/** Grid rows must own cells: wrap checkboxes, sort controls and menus in gridcell/columnheader elements. */function ListView({+ picker,+ currentTab,entries,selectedFileIds,activeWorkspaceFileIds,onSetSelection,- selectionActions,onSaveToServer,onVersionHistory,onDownloadFile,@@ -1280,31 +1342,28 @@ function ListView({serverReachable,actions,policyBadges,-}: FileGridProps & {- sortMode?: FilesPageSortMode;- onChangeSortMode?: (next: FilesPageSortMode) => void;- actions: FileGridActions;- policyBadges: Map<string, FileItemPolicyRef[]>;-}) {+ processingBlock,+ emptyState,+}: FileGridLayoutProps & { emptyState?: React.ReactNode }) {const { t } = useTranslation();- // Tri-state header checkbox state - computed from current entries.- const visibleFileIds = useMemo(- () =>- entries- .filter(- (e): e is FilesPageEntry & { file: StirlingFileStub } =>- e.kind === "file" && !!e.file,- )- .map((e) => e.file.id),- [entries],+ // Reaching a pick limit leaves the header mixed while other eligible files remain unselected.+ const selectableEntries = entries.filter(+ (entry) => !picker || picker.isEligible(entry),+ );+ const visibleFileIds = selectableEntries.flatMap((entry) =>+ entry.file ? [entry.file.id] : [],);- const allSelected =- visibleFileIds.length > 0 &&- visibleFileIds.every((id) => selectedFileIds.has(id));- const someSelected =- !allSelected && visibleFileIds.some((id) => selectedFileIds.has(id));- const selecting = Boolean(selectionActions) && selectedFileIds.size > 0;+ const visibleDiskFiles = picker+ ? selectableEntries.flatMap((entry) => (entry.disk ? [entry.disk] : []))+ : [];+ const visibleCount = visibleFileIds.length + visibleDiskFiles.length;+ const selectedCount =+ visibleFileIds.filter((id) => selectedFileIds.has(id)).length ++ visibleDiskFiles.filter((disk) => picker?.selectedDiskPaths.has(disk.path))+ .length;+ const allSelected = visibleCount > 0 && selectedCount === visibleCount;+ const someSelected = selectedCount > 0 && !allSelected;const sortIndicator = (asc: FilesPageSortMode, desc: FilesPageSortMode) => {if (sortMode === asc) return " ↑";@@ -1336,21 +1395,31 @@ function ListView({);return (<div className="files-page-list" role="grid" ref={setContainer}>- {/* Each direct child is a columnheader: a role="row" may only own cells, so- the sort controls and the select-all box have to sit inside one. */}- <div- className={`files-page-list-row is-header${selecting ? " is-selecting" : ""}`}- role="row"- >- {onSetSelection && visibleFileIds.length > 0 ? (+ <div className="files-page-list-row is-header" role="row">+ {onSetSelection && visibleCount > 0 ? (<span role="columnheader"><Checkboxchecked={allSelected}indeterminate={someSelected}- onChange={() => {- onSetSelection(- allSelected ? new Set() : new Set(visibleFileIds),- );+ disabled={picker?.selectionDisabled}+ onChange={(event) => {+ // A click clears the native mixed state even when the pick limit prevents a selection change.+ event.currentTarget.indeterminate = someSelected;+ if (picker) {+ const next = new Set(selectedFileIds);+ for (const id of visibleFileIds) {+ if (allSelected) next.delete(id);+ else next.add(id);+ }+ onSetSelection(next);+ picker.onSetDiskSelection(+ allSelected ? [] : visibleDiskFiles,+ );+ } else {+ onSetSelection(+ allSelected ? new Set() : new Set(visibleFileIds),+ );+ }}}aria-label={allSelected@@ -1362,44 +1431,33 @@ function ListView({) : (<span aria-hidden="true" />)}- {selecting ? (- <span role="columnheader" className="files-page-list-selection-bar">- <span className="files-page-list-selection-count">- {t("filesPage.selectedCount", "{{count}} selected", {- count: selectedFileIds.size,- })}- </span>- {selectionActions}+ <span role="columnheader">+ <span {...headerProps("name-asc", "name-desc")}>+ {t("filesPage.column.name", "Name")}+ {sortIndicator("name-asc", "name-desc")}+ </span>+ </span>+ <span role="columnheader">{t("filesPage.column.type", "Type")}</span>+ <span role="columnheader">+ <span {...headerProps("size-asc", "size-desc")}>+ {t("filesPage.column.size", "Size")}+ {sortIndicator("size-asc", "size-desc")}+ </span>+ </span>+ <span role="columnheader">+ <span {...headerProps("modified-asc", "modified-desc")}>+ {currentTab === "recent"+ ? t("filesPage.column.added", "Added")+ : t("filesPage.column.modified", "Modified")}+ {sortIndicator("modified-asc", "modified-desc")}+ </span>+ </span>+ {!picker && (+ <span role="columnheader">+ {t("filesPage.column.status", "Status")}</span>- ) : (- <>- <span role="columnheader">- <span {...headerProps("name-asc", "name-desc")}>- {t("filesPage.column.name", "Name")}- {sortIndicator("name-asc", "name-desc")}- </span>- </span>- <span role="columnheader">- {t("filesPage.column.type", "Type")}- </span>- <span role="columnheader">- <span {...headerProps("size-asc", "size-desc")}>- {t("filesPage.column.size", "Size")}- {sortIndicator("size-asc", "size-desc")}- </span>- </span>- <span role="columnheader">- <span {...headerProps("modified-asc", "modified-desc")}>- {t("filesPage.column.modified", "Modified")}- {sortIndicator("modified-asc", "modified-desc")}- </span>- </span>- <span role="columnheader">- {t("filesPage.column.status", "Status")}- </span>- <span aria-hidden="true" />- </>)}+ <span aria-hidden="true" /></div>{padTop > 0 && (<div@@ -1408,15 +1466,22 @@ function ListView({style={{ height: padTop }}/>)}+ {emptyState && (+ <div role="row">+ <div role="gridcell">{emptyState}</div>+ </div>+ )}{entries.slice(range.start, range.end).map((entry) => {if (entry.kind === "folder" && entry.folder) {return (<FolderRowkey={`folder-${entry.folder.id}`}+ selectionOnly={Boolean(picker)}folder={entry.folder}fileCount={entry.folderFileCount ?? 0}parentPath={entry.parentPath}serverReachable={serverReachable ?? false}+ processingBlock={processingBlock}actions={actions}/>);@@ -1425,6 +1490,9 @@ function ListView({return (<DiskFileRowkey={`disk-${entry.disk.path}`}+ selectionOnly={Boolean(picker)}+ isSelected={picker?.selectedDiskPaths.has(entry.disk.path)}+ disabledReason={picker?.disabledReason(entry)}entry={entry.disk}state={entry.diskState}locked={entry.processingLocked ?? false}@@ -1437,7 +1505,11 @@ function ListView({return (<FileRowkey={`file-${entry.file.id}`}+ selectionOnly={Boolean(picker)}+ disabledReason={picker?.disabledReason(entry)}+ folderPicker={picker?.foldersOnly}file={entry.file}+ date={libraryFileDate(entry.file, currentTab)}parentPath={entry.parentPath}processingState={entry.diskState}locked={entry.processingLocked ?? false}@@ -1445,7 +1517,10 @@ function ListView({isInWorkspace={activeWorkspaceFileIds?.has(entry.file.id) ?? false}- multiSelectActive={selectedFileIds.size >= 2}+ multiSelectActive={+ !picker?.foldersOnly &&+ (Boolean(picker) || selectedFileIds.size >= 2)+ }downloadAvailable={Boolean(onDownloadFile)}renameAvailable={Boolean(onRenameFile)}duplicateAvailable={Boolean(onDuplicateFile)}@@ -1470,24 +1545,18 @@ function ListView({);}-interface FolderRowProps {- folder: FolderRecord;- fileCount: number;- parentPath?: string;- serverReachable: boolean;- actions: FileGridActions;-}-const FolderRow = React.memo(function FolderRow({+ selectionOnly,folder,fileCount,parentPath,serverReachable,+ processingBlock,actions,-}: FolderRowProps) {+}: FolderItemProps) {const { t } = useTranslation();const onOpen = () => actions.openFolder(folder.id);- // Kinds gate the edit items, as in FolderCard.+const kind = folderKind(folder);const {stateFor: processingStateFor,@@ -1498,8 +1567,7 @@ const FolderRow = React.memo(function FolderRow({listFiles: listProcessingFiles,} = useProcessingFolders();const processing = processingStateFor(folder);- // Each action surfaces its own failure the way a failed drop does; the- // backend's reason (invalid pipeline, storage disabled) is the useful part.+const resumeProcessing = (label: string) =>Promise.resolve(enableProcessing(folder)).catch((err) =>actions.reportError(err, label),@@ -1517,7 +1585,6 @@ const FolderRow = React.memo(function FolderRow({actions.reportError(err, label),);const editsDisabled = kind === "server" && !serverReachable;- const processingBlock = useServerProcessingBlock();const editsHidden = kind === "local";const offlineHint = t("filesPage.offlineNoFolderEdits",@@ -1541,7 +1608,7 @@ const FolderRow = React.memo(function FolderRow({<divrole="row"tabIndex={0}- draggable+ draggable={!selectionOnly}onDragStart={(e) => {e.dataTransfer.setData(FILES_PAGE_DRAG_TYPE,@@ -1552,20 +1619,19 @@ const FolderRow = React.memo(function FolderRow({);e.dataTransfer.effectAllowed = "move";}}- {...dropHandlers}- onDoubleClick={onOpen}+ {...(selectionOnly ? {} : dropHandlers)}+ onClick={onOpen}onContextMenu={(e) => {e.preventDefault();kebabRef.current?.click();}}onKeyDown={(e) => {- if (e.key === "Enter") onOpen();+ if (e.target === e.currentTarget && e.key === "Enter") onOpen();}}className={`files-page-list-row${isDropTarget ? " is-drop-target" : ""}`}><span aria-hidden="true" />- {/* Each direct child is a gridcell: a role="row" may only own cells, so the- actions menu has to sit inside one. */}+<spanrole="gridcell"style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}@@ -1621,70 +1687,80 @@ const FolderRow = React.memo(function FolderRow({<span role="gridcell">{getFileDate({ lastModified: folder.updatedAt })}</span>- <span role="gridcell" className="files-page-list-status">- {processing && (- <ProcessingFolderStats- recordId={processing.id}- listFiles={listProcessingFiles}- variant="row"+ {!selectionOnly && (+ <span role="gridcell" className="files-page-list-status">+ {processing && (+ <ProcessingFolderStats+ recordId={processing.id}+ listFiles={listProcessingFiles}+ variant="row"+ />+ )}+ </span>+ )}+ <span role="gridcell" onClick={(e) => e.stopPropagation()}>+ {!selectionOnly && (+ <FolderMenu+ folder={folder}+ processing={processing}+ continuous={kind === "virtual"}+ isMount={editsHidden}+ canUnmount={folder.parentFolderId === null}+ editsDisabled={editsDisabled}+ editsDisabledHint={offlineHint}+ processingBlock={processingBlock}+ variant="kebab"+ triggerRef={kebabRef}+ onOpen={onOpen}+ onStartProcessing={() => actions.startProcessing(folder)}+ onRunProcessing={() => void runProcessing("process folder now")}+ onStopProcessing={() =>+ void stopProcessing("pause processing folder")+ }+ onResumeProcessing={() =>+ void resumeProcessing("resume processing")+ }+ onRemoveProcessing={() =>+ void removeProcessing("remove processing folder")+ }+ onEditProcessing={() => actions.startProcessing(folder)}+ onRevertAll={+ kind === "local"+ ? () => actions.requestRevertAll(folder)+ : undefined+ }+ onRename={() => actions.renameFolder(folder)}+ onChangeAppearance={(appearance) =>+ actions.changeFolderAppearance(folder.id, appearance)+ }+ onDelete={() => actions.deleteFolder(folder)}/>)}</span>- <span role="gridcell">- <FolderMenu- folder={folder}- processing={processing}- continuous={kind === "virtual"}- isMount={editsHidden}- canUnmount={folder.parentFolderId === null}- editsDisabled={editsDisabled}- editsDisabledHint={offlineHint}- processingBlock={processingBlock}- variant="kebab"- triggerRef={kebabRef}- onOpen={onOpen}- onStartProcessing={() => actions.startProcessing(folder)}- onRunProcessing={() => void runProcessing("process folder now")}- onStopProcessing={() =>- void stopProcessing("pause processing folder")- }- onResumeProcessing={() => void resumeProcessing("resume processing")}- onRemoveProcessing={() =>- void removeProcessing("remove processing folder")- }- onEditProcessing={() => actions.startProcessing(folder)}- onRevertAll={- kind === "local"- ? () => actions.requestRevertAll(folder)- : undefined- }- onRename={() => actions.renameFolder(folder)}- onChangeAppearance={(appearance) =>- actions.changeFolderAppearance(folder.id, appearance)- }- onDelete={() => actions.deleteFolder(folder)}- />- </span></div>);});interface FileRowProps {+ date: number;+ folderPicker?: boolean;+ selectionOnly?: boolean;+ disabledReason?: string;file: StirlingFileStub;isSelected: boolean;isInWorkspace: boolean;parentPath?: string;- /** Shows the checkbox once 2+ files are selected. */+multiSelectActive: boolean;- /** Download / rename / duplicate menu items offered. */+downloadAvailable: boolean;renameAvailable: boolean;duplicateAvailable: boolean;- /** Kebab Save to server offered; only fires when file is local-only. */+saveToServerAvailable: boolean;- /** Version-history menu item offered; shown only when file has >1 version. */+versionHistoryAvailable: boolean;- /** When set, the kebab Save to server is disabled with this tooltip. */+saveToServerDisabledReason?: string | null;badges: FileItemPolicyRef[];processingState?: DiskFileState;@@ -1694,6 +1770,10 @@ interface FileRowProps {}const FileRow = React.memo(function FileRow({+ date,+ folderPicker,+ selectionOnly,+ disabledReason,file,isSelected,isInWorkspace,@@ -1714,27 +1794,26 @@ const FileRow = React.memo(function FileRow({const lockedHint = useLockedHint(processingState);const kebabRef = useRef<HTMLButtonElement>(null);const fileSize = useMemo(() => formatFileSize(file.size), [file.size]);- const fileDate = useMemo(- () => getFileDate({ lastModified: file.lastModified }),- [file.lastModified],- );- const ext = (file.name.split(".").pop() ?? "").toUpperCase();+ const fileDate = useMemo(() => getFileDate({ lastModified: date }), [date]);+ const ext = detectFileExtension(file.name).toUpperCase();const resolvedThumbnail = useLazyThumbnail(file.id,file.size,file.thumbnailUrl,);const onClick = (e: React.MouseEvent) =>+ !disabledReason &&actions.selectFile(file.id, e.shiftKey, e.metaKey || e.ctrlKey);const onOpen = () => {- if (!locked) actions.openFile(file);+ if (!locked && !disabledReason) actions.openFile(file);};return (<divrole="row"aria-selected={isSelected}tabIndex={0}- draggable+ draggable={!selectionOnly}+ aria-disabled={Boolean(disabledReason)}onDragStart={(e) => {e.dataTransfer.setData(FILES_PAGE_DRAG_TYPE,@@ -1750,23 +1829,21 @@ const FileRow = React.memo(function FileRow({kebabRef.current?.click();}}onKeyDown={(e) => {+ if (e.key === " " && selectionOnly) {+ e.preventDefault();+ if (!disabledReason) actions.selectFile(file.id, e.shiftKey, true);+ }if (e.key === "Enter") onOpen();}}className={`files-page-list-row${isSelected ? " is-selected" : ""}${isInWorkspace ? " is-in-workspace" : ""}${locked ? " is-locked" : ""}`}- title={locked ? lockedHint : undefined}+ title={disabledReason ?? (locked ? lockedHint : undefined)}>- {/* Each direct child is a gridcell: a role="row" may only own cells, so the- checkbox and the actions menu have to sit inside one.-- The checkbox only shows in multi-select mode (see FileCard). When it is- hidden the first grid column collapses, but the row's CSS grid keeps the- columns aligned via the named template, so no empty cell shows. */}{multiSelectActive ? (<span role="gridcell"><Checkbox+ disabled={Boolean(disabledReason)}checked={isSelected}onClick={(e) => {- // Toggle this file in/out of the selection without modifier keys.e.stopPropagation();actions.selectFile(file.id, false, true);}}@@ -1779,7 +1856,6 @@ const FileRow = React.memo(function FileRow({/></span>) : (- // Empty cell preserves grid column alignment.<span aria-hidden="true" />)}<span@@ -1791,9 +1867,7 @@ const FileRow = React.memo(function FileRow({minWidth: 0,}}>- {/* Fixed slot: the fallback and the thumbnail are different sizes, and a- thumbnail arrives after first paint, so sizing to the content would- leave the names ragged and then shift them as each one landed. */}+ {/* Reserve thumbnail width so names do not shift when images load. */}<span className="files-page-list-thumb">{resolvedThumbnail ? (<img@@ -1833,7 +1907,11 @@ const FileRow = React.memo(function FileRow({</span>)}</span>- <FileOriginBadge origin={getFileOrigin(file)} compact />+ <FileOriginBadge+ origin={getFileOrigin(file)}+ onDisk={Boolean(file.localFilePath)}+ compact+ /><DiskLinkBadge file={file} compact /><PolicyBadgeRow policies={badges} />{isInWorkspace && (@@ -1846,44 +1924,50 @@ const FileRow = React.memo(function FileRow({<span role="gridcell">{ext || t("filesPage.file", "File")}</span><span role="gridcell">{fileSize}</span><span role="gridcell">{fileDate}</span>- <span role="gridcell" className="files-page-list-status">- <FileStateBadge- state={processingState}- onRetry={() => actions.retryFile(file.name)}- />- </span>+ {!selectionOnly && (+ <span role="gridcell" className="files-page-list-status">+ <FileStateBadge+ state={processingState}+ onRetry={() => actions.retryFile(file.name)}+ />+ </span>+ )}<span role="gridcell">- <FileActionsMenu- file={file}- triggerRef={kebabRef}- locked={locked}- downloadAvailable={downloadAvailable}- renameAvailable={renameAvailable}- duplicateAvailable={duplicateAvailable}- saveToServerAvailable={saveToServerAvailable}- versionHistoryAvailable={versionHistoryAvailable}- saveToServerDisabledReason={saveToServerDisabledReason}- actions={actions}- />+ {!folderPicker && (+ <FileActionsMenu+ selectionOnly={selectionOnly}+ file={file}+ triggerRef={kebabRef}+ locked={locked}+ downloadAvailable={downloadAvailable}+ renameAvailable={renameAvailable}+ duplicateAvailable={duplicateAvailable}+ saveToServerAvailable={saveToServerAvailable}+ versionHistoryAvailable={versionHistoryAvailable}+ saveToServerDisabledReason={saveToServerDisabledReason}+ actions={actions}+ />+ )}</span></div>);});-// Re-export root constant for caller convenienceexport { ROOT_FOLDER_ID };-/**- * No stub behind it, so no selection, move, rename or delete: the disk owns the- * file and the only affordance is adding it to the workspace.- */const DiskFileCard = React.memo(function DiskFileCard({+ selectionOnly,+ isSelected,+ disabledReason,entry,state,- locked = false,+ locked: processingLocked = false,hasOriginal,actions,}: {+ selectionOnly?: boolean;+ isSelected?: boolean;+ disabledReason?: string;entry: DiskFileEntry;state?: DiskFileState;/** The folder still owes this file a run; see FilesPageEntry.processingLocked. */@@ -1891,27 +1975,58 @@ const DiskFileCard = React.memo(function DiskFileCard({hasOriginal?: boolean;actions: FileGridActions;}) {+ const locked = processingLocked || Boolean(disabledReason);const onOpen = () => {if (!locked) actions.openDiskFile(entry);};const { t } = useTranslation();const lockedHint = useLockedHint(state);const thumbnail = useDiskThumbnail(entry);- const extension = entry.name.includes(".")- ? entry.name.split(".").pop()!.toUpperCase()- : "";+ const extension = detectFileExtension(entry.name).toUpperCase();const isPdf = extension === "PDF";return (<div- className={`files-page-card${locked ? " is-locked" : ""}`}+ className={`files-page-card${locked ? " is-locked" : ""}${isSelected ? " is-selected" : ""}`}role="listitem"tabIndex={0}+ aria-label={+ isSelected+ ? t("filesPage.selectedFile", "{{name}}, selected", {+ name: entry.name,+ })+ : entry.name+ }+ aria-disabled={locked}+ onClick={(event) => {+ if (selectionOnly && !locked)+ actions.selectDiskFile(entry, event.shiftKey);+ }}onDoubleClick={onOpen}onKeyDown={(e) => {+ if (e.key === " " && selectionOnly) {+ e.preventDefault();+ if (!locked) actions.selectDiskFile(entry, e.shiftKey);+ }if (e.key === "Enter") onOpen();}}- title={locked ? lockedHint : entry.path}+ title={disabledReason ?? (processingLocked ? lockedHint : entry.path)}>+ {selectionOnly && (+ <div className="files-page-card-selector">+ <Checkbox+ checked={Boolean(isSelected)}+ disabled={locked}+ onClick={(event) => {+ event.stopPropagation();+ actions.selectDiskFile(entry, event.shiftKey);+ }}+ onChange={() => {}}+ aria-label={t("filesPage.selectFile", "Select file {{name}}", {+ name: entry.name,+ })}+ />+ </div>+ )}<div className="files-page-card-thumb">{thumbnail ? (<img src={thumbnail} alt="" draggable={false} />@@ -1922,12 +2037,13 @@ const DiskFileCard = React.memo(function DiskFileCard({) : (<Icon name="file" size={"2rem"} />)}- <span>{extension || "FILE"}</span>+ <span>{extension || t("filesPage.file", "File")}</span></div>)}<div className="files-page-card-origin"><FileOriginBadgeorigin="local"+ onDisktooltip={t("filesPage.origin.diskHint","A file in the mounted folder on your disk",@@ -1937,7 +2053,9 @@ const DiskFileCard = React.memo(function DiskFileCard({</div><FileStateBadgestate={state}- onRetry={() => actions.retryFile(entry.name)}+ onRetry={+ selectionOnly ? undefined : () => actions.retryFile(entry.name)+ }/></div><div className="files-page-card-body">@@ -1951,53 +2069,60 @@ const DiskFileCard = React.memo(function DiskFileCard({</div></div><div className="files-page-card-actions">- <Menu shadow="md" position="bottom-end" withinPortal>- <Menu.Target>- <ActionIcon- size="sm"- onClick={(e) => e.stopPropagation()}- aria-label={t("filesPage.fileMenu", "File actions")}- >- <Icon name="ellipsis-vertical" size={20} />- </ActionIcon>- </Menu.Target>- <Menu.Dropdown>- <Menu.Item- disabled={locked}- leftSection={<Icon name="external-link" size={20} />}- onClick={(e) => {- e.stopPropagation();- onOpen();- }}- >- {t("filesPage.addToWorkspace", "Add to workspace")}- </Menu.Item>- {hasOriginal && (+ {!selectionOnly && (+ <Menu shadow="md" position="bottom-end" withinPortal>+ <Menu.Target>+ <ActionIcon+ size="sm"+ onClick={(e) => e.stopPropagation()}+ aria-label={t("filesPage.fileMenu", "File actions")}+ >+ <Icon name="ellipsis-vertical" size={20} />+ </ActionIcon>+ </Menu.Target>+ <Menu.Dropdown><Menu.Item- leftSection={<Icon name="rotate-ccw-clock" size={20} />}+ disabled={locked}+ leftSection={<Icon name="external-link" size={20} />}onClick={(e) => {e.stopPropagation();- actions.revertFile(entry.name);+ onOpen();}}>- {t("filesPage.processing.restore", "Restore original")}+ {t("filesPage.addToWorkspace", "Add to workspace")}</Menu.Item>- )}- </Menu.Dropdown>- </Menu>+ {hasOriginal && (+ <Menu.Item+ leftSection={<Icon name="rotate-ccw-clock" size={20} />}+ onClick={(e) => {+ e.stopPropagation();+ actions.revertFile(entry.name);+ }}+ >+ {t("filesPage.processing.restore", "Restore original")}+ </Menu.Item>+ )}+ </Menu.Dropdown>+ </Menu>+ )}</div></div>);});-/** List-view sibling of {@link DiskFileCard}; same single affordance. */const DiskFileRow = React.memo(function DiskFileRow({+ selectionOnly,+ isSelected,+ disabledReason,entry,state,- locked = false,+ locked: processingLocked = false,hasOriginal,actions,}: {+ selectionOnly?: boolean;+ isSelected?: boolean;+ disabledReason?: string;entry: DiskFileEntry;state?: DiskFileState;/** The folder still owes this file a run; see FilesPageEntry.processingLocked. */@@ -2005,27 +2130,51 @@ const DiskFileRow = React.memo(function DiskFileRow({hasOriginal?: boolean;actions: FileGridActions;}) {+ const locked = processingLocked || Boolean(disabledReason);const onOpen = () => {if (!locked) actions.openDiskFile(entry);};const { t } = useTranslation();const lockedHint = useLockedHint(state);const thumbnail = useDiskThumbnail(entry);- const ext = entry.name.includes(".")- ? entry.name.split(".").pop()!.toUpperCase()- : "";+ const ext = detectFileExtension(entry.name).toUpperCase();return (<divrole="row"tabIndex={0}- className={`files-page-list-row${locked ? " is-locked" : ""}`}+ aria-selected={isSelected}+ aria-disabled={locked}+ onClick={(event) => {+ if (selectionOnly && !locked)+ actions.selectDiskFile(entry, event.shiftKey);+ }}+ className={`files-page-list-row${locked ? " is-locked" : ""}${isSelected ? " is-selected" : ""}`}onDoubleClick={onOpen}onKeyDown={(e) => {+ if (e.key === " " && selectionOnly) {+ e.preventDefault();+ if (!locked) actions.selectDiskFile(entry, e.shiftKey);+ }if (e.key === "Enter") onOpen();}}- title={locked ? lockedHint : entry.path}+ title={disabledReason ?? (processingLocked ? lockedHint : entry.path)}>- <span aria-hidden="true" />+ <span role="gridcell">+ {selectionOnly && (+ <Checkbox+ checked={Boolean(isSelected)}+ disabled={locked}+ onClick={(event) => {+ event.stopPropagation();+ actions.selectDiskFile(entry, event.shiftKey);+ }}+ onChange={() => {}}+ aria-label={t("filesPage.selectFile", "Select file {{name}}", {+ name: entry.name,+ })}+ />+ )}+ </span><spanrole="gridcell"style={{@@ -2056,6 +2205,7 @@ const DiskFileRow = React.memo(function DiskFileRow({</span><FileOriginBadgeorigin="local"+ onDisktooltip={t("filesPage.origin.diskHint","A file in the mounted folder on your disk",@@ -2068,42 +2218,46 @@ const DiskFileRow = React.memo(function DiskFileRow({<span role="gridcell">{getFileDate({ lastModified: entry.lastModified })}</span>- <span role="gridcell" className="files-page-list-status">- <FileStateBadge- state={state}- onRetry={() => actions.retryFile(entry.name)}- />- </span>+ {!selectionOnly && (+ <span role="gridcell" className="files-page-list-status">+ <FileStateBadge+ state={state}+ onRetry={() => actions.retryFile(entry.name)}+ />+ </span>+ )}<span role="gridcell">- <Menu shadow="md" position="bottom-end" withinPortal>- <Menu.Target>- <ActionIcon- variant="tertiary"- size="sm"- onClick={(e) => e.stopPropagation()}- aria-label={t("filesPage.fileMenu", "File actions")}- >- <Icon name="ellipsis-vertical" size={20} />- </ActionIcon>- </Menu.Target>- <Menu.Dropdown>- <Menu.Item- disabled={locked}- leftSection={<Icon name="external-link" size={20} />}- onClick={onOpen}- >- {t("filesPage.addToWorkspace", "Add to workspace")}- </Menu.Item>- {hasOriginal && (+ {!selectionOnly && (+ <Menu shadow="md" position="bottom-end" withinPortal>+ <Menu.Target>+ <ActionIcon+ variant="tertiary"+ size="sm"+ onClick={(e) => e.stopPropagation()}+ aria-label={t("filesPage.fileMenu", "File actions")}+ >+ <Icon name="ellipsis-vertical" size={20} />+ </ActionIcon>+ </Menu.Target>+ <Menu.Dropdown><Menu.Item- leftSection={<Icon name="rotate-ccw-clock" size={20} />}- onClick={() => actions.revertFile(entry.name)}+ disabled={locked}+ leftSection={<Icon name="external-link" size={20} />}+ onClick={onOpen}>- {t("filesPage.processing.restore", "Restore original")}+ {t("filesPage.addToWorkspace", "Add to workspace")}</Menu.Item>- )}- </Menu.Dropdown>- </Menu>+ {hasOriginal && (+ <Menu.Item+ leftSection={<Icon name="rotate-ccw-clock" size={20} />}+ onClick={() => actions.revertFile(entry.name)}+ >+ {t("filesPage.processing.restore", "Restore original")}+ </Menu.Item>+ )}+ </Menu.Dropdown>+ </Menu>+ )}</span></div>);diff --git a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx b/frontend/editor/src/core/components/filesPage/FileManagerView.tsxindex d304a3d383..f55e55a569 100644--- a/frontend/editor/src/core/components/filesPage/FileManagerView.tsx+++ b/frontend/editor/src/core/components/filesPage/FileManagerView.tsx@@ -6,26 +6,14 @@ import React, {useRef,useState,} from "react";-import { useQuery, useQueryClient } from "@tanstack/react-query";import { useTranslation } from "react-i18next";import { useLocation, useNavigate } from "react-router-dom";-import {- Drawer,- Menu,- MultiSelect,- Select,- TextInput,- Tooltip,-} from "@mantine/core";-import { qk } from "@app/query/keys";+import { Drawer, Menu, Tooltip } from "@mantine/core";import { ActionIcon } from "@app/ui/ActionIcon";-import { SegmentedControl } from "@app/ui/SegmentedControl";import { useMediaQuery } from "@mantine/hooks";import { FilesToolbarBulkMenu } from "@app/components/filesPage/FilesToolbarBulkMenu";import { FilesToolbarCount } from "@app/components/filesPage/FilesToolbarCount";-import { FilesToolbarFilterMenu } from "@app/components/filesPage/FilesToolbarFilterMenu";import { FolderMenu } from "@app/components/filesPage/FolderMenu";-import { FilesToolbarSortMenu } from "@app/components/filesPage/FilesToolbarSortMenu";import { NewFolderButton } from "@app/components/filesPage/NewFolderButton";import { useFileLibraryWorkbenchBarButtons } from "@app/components/filesPage/useFileLibraryWorkbenchBarButtons";@@ -36,25 +24,24 @@ import { useOpenFolder } from "@app/components/filesPage/useOpenFolder";import { useFileActions } from "@app/contexts/file/fileHooks";import { useAllFiles } from "@app/contexts/FileContext";import { useFileHandler } from "@app/hooks/useFileHandler";+import { useDropzoneFiles } from "@app/hooks/useDropzoneFiles";import { openFilesFromDisk } from "@app/services/openFilesFromDisk";-import { useServerFolderBlock } from "@app/hooks/useServerFolderBlock";import {useNavigationActions,useNavigationGuard,} from "@app/contexts/NavigationContext";import { useViewer } from "@app/contexts/ViewerContext";-import {- FILES_PAGE_VIEW_MODES,- FilesPageOriginFilter,- FilesPageSortMode,- useFilesPage,-} from "@app/contexts/FilesPageContext";-import { getFileOrigin } from "@app/components/filesPage/fileOrigin";+import { useFilesPage } from "@app/contexts/FilesPageContext";+import { useLibraryFiles } from "@app/components/filesPage/useLibraryFiles";+import { useFolderFileStates } from "@app/components/filesPage/useFolderFileStates";+import { useDiskFolder } from "@app/components/filesPage/useDiskFolder";+import { LibraryToolbar } from "@app/components/filesPage/LibraryToolbar";+import { LibraryTabs } from "@app/components/filesPage/LibraryTabs";+import { useLibraryScrollPosition } from "@app/components/filesPage/useLibraryScrollPosition";import { FileId } from "@app/types/file";import { StirlingFileStub } from "@app/types/fileContext";import {- FolderBreadcrumbEntry,FolderId,FolderRecord,ROOT_FOLDER_ID,@@ -66,10 +53,7 @@ import {FilesPageEntry,type DiskFileState,} from "@app/components/filesPage/FileGrid";-import {- useProcessingFolders,- type MountedFileState,-} from "@app/hooks/useProcessingFolders";+import { useProcessingFolders } from "@app/hooks/useProcessingFolders";import { FolderProcessingSetup } from "@app/components/policies/FolderProcessingSetup";import { useServerProcessingBlock } from "@app/hooks/useServerProcessingBlock";import { useConnectedServer } from "@app/hooks/useConnectedServer";@@ -77,27 +61,22 @@ import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled"import { FolderSweepWall } from "@app/components/policies/SweepRunWall";import { RestoreOriginalsDialog } from "@app/components/filesPage/RestoreOriginalsDialog";import { FileDetailsPanel } from "@app/components/filesPage/FileDetailsPanel";-import BulkUploadToServerModal from "@app/components/shared/BulkUploadToServerModal";+import { AddToLibraryModal } from "@app/components/filesPage/AddToLibraryModal";+import { isBrowserOnlyFile } from "@app/components/filesPage/fileOrigin";import { useAppConfig } from "@app/contexts/AppConfigContext";import { canPickDirectory } from "@app/services/directoryPicker";-import {- diskFolderId,- isDiskFolderId,- pickFolderColor,-} from "@app/types/folder";+import { isDiskFolderId } from "@app/types/folder";import { useNewFolderFlow } from "@app/hooks/useNewFolderFlow";import { useLibraryRefresh } from "@app/hooks/useLibraryRefresh";-import { writeIntoMount } from "@app/services/mountWrites";+import { useLibraryUpload } from "@app/components/filesPage/useLibraryUpload";import {- canListDirectory,- listDirectory,readDiskFile,type DiskFileEntry,} from "@app/services/localFolderContents";import { useIsMobile } from "@app/hooks/useIsMobile";import { MoveToFolderDialog } from "@app/components/filesPage/MoveToFolderDialog";import { FolderNameDialog } from "@app/components/filesPage/FolderNameDialog";-import { getFolderPath } from "@app/utils/folderPath";+import { libraryEntries } from "@app/components/filesPage/libraryEntries";import { DeleteFolderDialog } from "@app/components/filesPage/DeleteFolderDialog";import { DeleteFilesDialog } from "@app/components/filesPage/DeleteFilesDialog";import { VersionHistoryModal } from "@app/components/filesPage/VersionHistoryModal";@@ -119,24 +98,22 @@ export default function FileManagerView() {const navigate = useNavigate();const location = useLocation();const openFolder = useOpenFolder();+ const folderDropHandlers = useFolderDropHandlers();- // Hide Shared tab when storageSharingEnabled is false.const { sharingEnabled } = useSharingEnabled();- // ≤800px hosts the details panel in a button-triggered Drawer.const isCompactDetailsViewport = useMediaQuery("(max-width: 800px)") ?? false;- // Phones get a full-screen drawer; tablets get a smaller one.+const useFullScreenDrawer = useMediaQuery("(max-width: 640px)") ?? false;const [mobileDetailsOpen, setMobileDetailsOpen] = useState(false);- // Save-to-server modal target. Bulk button uses local-only selection;- // per-file kebab uses [file]. Targets root; folder placement is via drop.const [saveToServerTarget, setSaveToServerTarget] = useState<StirlingFileStub[] | null>(null);- // Version-history modal target (opened from the card kebab).+const [versionHistoryFile, setVersionHistoryFile] =useState<StirlingFileStub | null>(null);const folders = useFolders();+ const setFolderError = folders.setError;const { actions: fileActions } = useFileActions();const { fileIds: activeWorkspaceFileIds, fileStubs: activeWorkspaceFiles } =useAllFiles();@@ -147,16 +124,11 @@ export default function FileManagerView() {const { addFiles } = useFileHandler();const { config: appConfig } = useAppConfig();const isMobile = useIsMobile();- // Guests (anonymous sessions) have no server-side storage, so every cloud- // action is account-only. Rather than let the click fire a guaranteed 401- // (which surfaced as an error toast), we disable the control and explain why- // on hover - the same affordance the storage-disabled / wrong-tab gates use.+ // Guests cannot use server storage; explain the disabled control before a request fails.const { isAnonymous } = useAuth();const signInRequiredReason = isAnonymous? t("filesPage.signInRequired", "Sign in to use cloud storage."): null;- // Refresh pulls from the server. True on web (server-backed); on desktop it tracks the- // signed-in connection, so the control falls inert with an explanation until connected.const connectedServer = useConnectedServer();const refreshDisabledReason =signInRequiredReason ??@@ -166,10 +138,6 @@ export default function FileManagerView() {"filesPage.refreshNeedsConnection","Sign in to refresh from the server.",));- // Server storage gate; mirrors ConfigController's storageEnabled- // (enableLogin && storage.isEnabled). When off, Save-to-server stays- // visible but disabled with an explanatory tooltip (discoverability beats- // hiding - mirrors the New folder / Manage sharing gates in this view).const uploadEnabled = appConfig?.storageEnabled === true;const saveToServerDisabledReason: string | null =signInRequiredReason ??@@ -226,7 +194,6 @@ export default function FileManagerView() {setFolderAppearance,} = filesPage;- // Resolve queued delete ids into stubs for the DeleteFilesDialog.const deleteDialogFiles = useMemo(() =>deleteDialogFileIds@@ -240,8 +207,6 @@ export default function FileManagerView() {const foldersById = folders.foldersById;const currentFolderId = folders.currentFolderId;- // The path selects the folder - see useOpenFolder - and this applies it, on arrival,- // on a deep link, and on back/forward alike. Re-runs as the folder map fills in.useEffect(() => {const match = location.pathname.match(/^\/files\/([^/]+)/);const param = match?.[1] ?? null;@@ -258,9 +223,7 @@ export default function FileManagerView() {setCurrentFolderId(param as FolderId);return;}- // Not known yet is not the same as not real: folders load asynchronously, and a- // mount's subdirectories arrive with the listing that finds them. Falling back to- // the root waits until the map can no longer turn up the folder named here.+ // Wait for folder loading and mount discovery before rejecting an unknown folder ID.if (!folders.loading) {setCurrentFolderId(ROOT_FOLDER_ID);}@@ -272,7 +235,6 @@ export default function FileManagerView() {folders.loading,]);- // Bounce off any share-related tab when sharing isn't enabled.useEffect(() => {if (!sharingEnabled &&@@ -282,185 +244,6 @@ export default function FileManagerView() {}}, [sharingEnabled, currentTab, setCurrentTab]);- // ─── visible items (current folder + sort + search) ─────────────────────-- /** currentFolderId + all descendants. Includes `null` when at root. */- const subtreeFolderIds = useMemo(() => {- const set = new Set<FolderId | null>();- set.add(currentFolderId);- const childMap = new Map<FolderId | null, FolderId[]>();- for (const f of folders.folders) {- const list = childMap.get(f.parentFolderId) ?? [];- list.push(f.id);- childMap.set(f.parentFolderId, list);- }- // Iterative DFS to avoid stack overflow on deep chains.- const stack: (FolderId | null)[] = [currentFolderId];- while (stack.length > 0) {- const cur = stack.pop()!;- for (const childId of childMap.get(cur) ?? []) {- if (set.has(childId)) continue;- set.add(childId);- stack.push(childId);- }- }- return set;- }, [folders.folders, currentFolderId]);-- const visibleFolders = useMemo(() => {- // Folders only appear in cloud-rooted tabs.- if (- currentTab === "recent" ||- currentTab === "shared" ||- currentTab === "sharedByMe"- ) {- return [];- }- const lc = search.toLowerCase();- const matched = folders.folders.filter((f) => {- // The Cloud tab is the server's view: browser folders and mounts aren't on it.- if (currentTab === "cloud" && folderKind(f) !== "server") return false;- // A folder answers to the source filter the way its files would: a server- // folder is cloud, a browser folder and a mount are both local.- if (originFilter !== "all") {- const folderOrigin = folderKind(f) === "server" ? "cloud" : "local";- if (folderOrigin !== originFilter) return false;- }- if (search) {- // Subtree-wide name match; exclude the current folder itself.- return (- f.id !== currentFolderId &&- subtreeFolderIds.has(f.parentFolderId) &&- f.name.toLowerCase().includes(lc)- );- }- // Direct children only.- return f.parentFolderId === currentFolderId;- });- return matched.sort((a, b) =>- a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),- );- }, [- folders.folders,- currentFolderId,- search,- currentTab,- subtreeFolderIds,- originFilter,- ]);-- // Files in current folder, pre-filter. Drives the type-filter dropdown.- const filesInCurrentFolder = useMemo(() => {- // Tab overrides folder navigation for Local/Recent/Shared.- switch (currentTab) {- case "cloud":- // Cloud bucket; search widens to subtree, else direct-folder match.- return allFiles.filter((f) => {- if (f.remoteStorageId == null) return false;- if (search) return subtreeFolderIds.has(f.folderId ?? null);- return (f.folderId ?? null) === (currentFolderId ?? null);- });- case "recent": {- // Last 50 modified across local + cloud, folder context ignored.- const sorted = [...allFiles].sort(- (a, b) => (b.lastModified ?? 0) - (a.lastModified ?? 0),- );- return sorted.slice(0, 50);- }- case "shared":- return allFiles.filter((f) => f.remoteOwnedByCurrentUser === false);- case "sharedByMe":- // Files I own that I've shared in any way - either with a public link- // or with a specific user. (Previously split across two visually- // identical tabs; merged here so the same idea lives in one place.)- return allFiles.filter(- (f) =>- f.remoteOwnedByCurrentUser !== false &&- (f.remoteHasShareLinks === true || f.remoteHasUserShares === true),- );- case "all":- default:- // Search widens to the subtree.- // Files with a dangling folderId (folder deleted, or stale local IDB- // row) fall back to root so they aren't permanently invisible.- return allFiles.filter((f) => {- const rawFolder = f.folderId ?? null;- const effectiveFolder =- rawFolder !== null && !foldersById.has(rawFolder)- ? null- : rawFolder;- if (search) return subtreeFolderIds.has(effectiveFolder);- return effectiveFolder === (currentFolderId ?? null);- });- }- }, [- allFiles,- currentFolderId,- currentTab,- search,- subtreeFolderIds,- foldersById,- ]);-- const availableTypes = useMemo(() => {- const set = new Set<string>();- for (const f of filesInCurrentFolder) {- const ext = (f.name.split(".").pop() ?? "").toUpperCase();- if (ext) set.add(ext);- }- return Array.from(set).sort();- }, [filesInCurrentFolder]);-- // Drop any active type filters that no longer appear in this folder- // (e.g. when the user navigates between folders).- useEffect(() => {- if (typeFilter.length === 0) return;- const stillValid = typeFilter.filter((t) => availableTypes.includes(t));- if (stillValid.length !== typeFilter.length) {- setTypeFilter(stillValid);- }- }, [availableTypes, typeFilter, setTypeFilter]);-- const visibleFiles = useMemo(() => {- const filtered = filesInCurrentFolder- .filter((f) =>- search ? f.name.toLowerCase().includes(search.toLowerCase()) : true,- )- .filter((f) =>- originFilter === "all" ? true : getFileOrigin(f) === originFilter,- )- .filter((f) => {- if (typeFilter.length === 0) return true;- const ext = (f.name.split(".").pop() ?? "").toUpperCase();- return typeFilter.includes(ext);- });- const sorted = [...filtered];- sorted.sort((a, b) => {- switch (sortMode) {- case "name-asc":- return a.name.localeCompare(b.name);- case "name-desc":- return b.name.localeCompare(a.name);- case "modified-asc":- return (a.lastModified ?? 0) - (b.lastModified ?? 0);- case "size-desc":- return (b.size ?? 0) - (a.size ?? 0);- case "size-asc":- return (a.size ?? 0) - (b.size ?? 0);- case "modified-desc":- default:- return (b.lastModified ?? 0) - (a.lastModified ?? 0);- }- });- return sorted;- }, [filesInCurrentFolder, search, sortMode, originFilter, typeFilter]);-- const pathForFolderId = useCallback(- (folderId: FolderId | null | undefined) =>- getFolderPath(folderId, foldersById),- [foldersById],- );-const currentFolder = currentFolderId? folders.foldersById.get(currentFolderId): undefined;@@ -473,87 +256,24 @@ export default function FileManagerView() {folderKind(currentFolder) === "server" &&!folders.serverReachable,);- const { setError: setFolderError, registerDiskSubfolders } = folders;- const [diskEntries, setDiskEntries] = useState<DiskFileEntry[]>([]);- const [diskLoading, setDiskLoading] = useState(false);- // Bumped when this view writes into the directory, so the listing re-reads.- const { diskRevision, bumpDiskRevision } = filesPage;- useEffect(() => {- if (!currentLocalDirectory || !canListDirectory) {- // Same array when it is already empty: a refresh outside a mount re-runs this- // and a fresh one would re-render every reader of the listing for nothing.- setDiskEntries((prev) => (prev.length > 0 ? [] : prev));- // Leaving a mount mid-listing cancels the in-flight reset, so clear the- // flag here or the skeleton covers every folder for the rest of the session.- setDiskLoading(false);- return;- }- let cancelled = false;- // The directory is the disk's and anything can write to it, so poll while open and let- // outside changes appear on their own; only a changed listing re-renders.- const load = async (background: boolean) => {- if (!background) setDiskLoading(true);- try {- const listed = await listDirectory(currentLocalDirectory);- if (cancelled) return;- const files = listed?.files ?? [];- setDiskEntries((prev) =>- listingSignature(prev) === listingSignature(files) ? prev : files,- );- if (currentFolderId !== null) {- registerDiskSubfolders(- currentFolderId,- (listed?.directories ?? []).map((dir) => ({- id: diskFolderId(dir.path),- kind: "local" as const,- name: dir.name,- parentFolderId: currentFolderId,- directory: dir.path,- color: pickFolderColor(dir.name),- createdAt: 0,- updatedAt: 0,- })),- );- }- } catch (err) {- console.warn("[FileManagerView] disk listing failed", err);- // Background ticks stay quiet: a transient lock (a sync client holding- // the directory) would otherwise pop an error banner every few seconds.- if (!cancelled && !background) {- setDiskEntries([]);- setFolderError(- err instanceof Error- ? t("filesPage.error.readFolderFailedDetail", {- message: err.message,- defaultValue: `Could not read the folder: ${err.message}`,- })- : t(- "filesPage.error.readFolderFailed",- "Could not read the folder.",- ),- );- }- } finally {- if (!cancelled && !background) setDiskLoading(false);- }- };- void load(false);- const timer = setInterval(() => void load(true), 4000);- return () => {- cancelled = true;- clearInterval(timer);- };- // The stable setter, not the context: its identity changes on every folder- // mutation, including the setError above, so a failing listing would re-trigger.- }, [+ const { diskRevision } = filesPage;+ const { diskEntries, diskLoading } = useDiskFolder(currentLocalDirectory,currentFolderId,- registerDiskSubfolders,- setFolderError,diskRevision,- t,- ]);+ folders.setError,+ );+ const { visibleFolders, visibleFiles, availableTypes } = useLibraryFiles({+ allFiles,+ currentFolderId,+ currentTab,+ search,+ sortMode,+ originFilter,+ typeFilter,+ diskEntries: currentLocalDirectory ? diskEntries : undefined,+ });const openDiskFile = useCallback(async (entry: DiskFileEntry) => {try {@@ -581,8 +301,6 @@ export default function FileManagerView() {[addFiles, navActions, navigate, folders, t],);- // A working folder lists its real contents; each file wears its pipeline state and a state- // filter narrows the listing. Files the pipeline never claims carry no state at all.const processingApi = useProcessingFolders();const processingEnabled = usePoliciesEnabled();const currentProcessing = currentFolder@@ -592,68 +310,17 @@ export default function FileManagerView() {? currentProcessing?.outputDirectory: undefined;const processingRecordId = currentProcessing?.id;- // The state layer applies inside any working folder: a mount's directory listing or a- // server folder's stored files, both joined to the same ledger behind listFiles.const processingView = Boolean(processingRecordId && (outputDirectory || !currentLocalDirectory),);- const { listFiles, retryFile, revertFile } = processingApi;- const queryClient = useQueryClient();- const processingFilesKey = qk.processingFolderFiles(processingRecordId ?? "");- // Per-file state from the backend's ledger: processing in place leaves no output folder to- // infer it from. Polled while the folder is open so badges follow the sweep live, and the- // poll stands down with the tab rather than asking every 3s into a background window.+ const { retryFile, revertFile } = processingApi;const {- data: processingFiles,- dataUpdatedAt: processingFilesUpdatedAt,- errorUpdatedAt: processingFilesErrorAt,- status: processingFilesStatus,- } = useQuery({- queryKey: processingFilesKey,- queryFn: () => listFiles(processingRecordId!),- enabled: processingView && Boolean(processingRecordId),- refetchInterval: PROCESSING_FILES_POLL_MS,- retry: false,- });-- const activeProcessingKey = processingView ? (processingRecordId ?? "") : "";- const [processingPollFailures, setProcessingPollFailures] = useState({- key: "",- count: 0,- });- const processingPollEvent = useRef({ key: "", updatedAt: 0 });- useEffect(() => {- const key = activeProcessingKey;- if (processingPollEvent.current.key !== key) {- processingPollEvent.current = { key, updatedAt: 0 };- setProcessingPollFailures({ key, count: 0 });- }- if (!key) return;-- const updatedAt =- processingFilesStatus === "error"- ? processingFilesErrorAt- : processingFilesUpdatedAt;- if (!updatedAt || updatedAt <= processingPollEvent.current.updatedAt)- return;-- processingPollEvent.current.updatedAt = updatedAt;- setProcessingPollFailures((failures) => ({- key,- count:- processingFilesStatus === "error"- ? (failures.key === key ? failures.count : 0) + 1- : 0,- }));- }, [- activeProcessingKey,- processingFilesErrorAt,- processingFilesStatus,- processingFilesUpdatedAt,- ]);- const processingStatesUnavailable =- processingPollFailures.key === activeProcessingKey &&- processingPollFailures.count >= PROCESSING_FILES_FAILURE_LIMIT;+ fileStates,+ revertables,+ patchProcessingFile,+ processingLockedFor,+ processingStatesUnavailable,+ } = useFolderFileStates(processingRecordId, processingView);useEffect(() => {if (!processingStatesUnavailable) return;setFolderError(@@ -664,39 +331,9 @@ export default function FileManagerView() {);}, [processingStatesUnavailable, setFolderError, t]);- // Stable empties for a folder with no processing: a fresh Map/Set is never- // Object.is equal, so returning one would re-render every reader for nothing.- const fileStates = useMemo(- () =>- processingFiles- ? new Map(processingFiles.map((f) => [f.name, f.state]))- : EMPTY_FILE_STATES,- [processingFiles],- );- // Files whose pre-processing original is archived and can be restored.- const revertables = useMemo(- () =>- processingFiles- ? new Set(- processingFiles.filter((f) => f.hasOriginal).map((f) => f.name),- )- : EMPTY_REVERTABLES,- [processingFiles],- );- /** Shows a just-made change ahead of the next poll. */- const patchProcessingFile = useCallback(- (name: string, patch: Partial<MountedFileState>) =>- queryClient.setQueryData<MountedFileState[]>(- processingFilesKey,- (prev) =>- prev?.map((f) => (f.name === name ? { ...f, ...patch } : f)) ?? prev,- ),- [queryClient, processingFilesKey],- );-const [processingSetupFolder, setProcessingSetupFolder] =useState<FolderRecord | null>(null);- // Restores wait on a confirmation, since they also pause the folder.+ // Restoring originals also pauses the folder, so it requires confirmation.const [revertConfirmName, setRevertConfirmName] = useState<string | null>(null,);@@ -707,15 +344,6 @@ export default function FileManagerView() {const [diskStateFilter, setDiskStateFilter] = useState<DiskFileState | "all">("all",);- const processingLockedFor = useCallback(- (key: string): boolean => {- if (!processingView || processingStatesUnavailable) return false;- const state = fileStates.get(key);- return state !== "done" && state !== "failed";- },- [processingView, processingStatesUnavailable, fileStates],- );-const processingLockedFileIds = useMemo(() =>new Set(@@ -766,7 +394,7 @@ export default function FileManagerView() {(name: string): DiskFileState | undefined => fileStates.get(name),[fileStates],);- // Counts for the filter chips, from the same states the badges wear.+const stateCounts = useMemo(() => {const counts: Record<DiskFileState, number> = {done: 0,@@ -804,8 +432,6 @@ export default function FileManagerView() {if (!processingRecordId) return;void revertFile(processingRecordId, name).then(() =>- // Reflect the restore ahead of the next poll; the original is gone, so- // the row stops offering one.patchProcessingFile(name, { state: "waiting", hasOriginal: false }),).catch((err) =>@@ -823,7 +449,7 @@ export default function FileManagerView() {),);},- [processingRecordId, revertFile, folders, t],+ [processingRecordId, revertFile, folders, t, patchProcessingFile],);const revertAllInFolder = useCallback((folder: FolderRecord) => {@@ -855,8 +481,7 @@ export default function FileManagerView() {},[processingApi, folders, t],);- // The open folder's own actions: everything its card kebab offers from the- // listing outside must be reachable from inside the folder too.+const runFolderAction = useCallback((action: (folder: FolderRecord) => Promise<void>, label: string) => {if (!currentFolder) return;@@ -878,106 +503,68 @@ export default function FileManagerView() {[currentFolder, folders, t],);- const entries = useMemo<FilesPageEntry[]>(() => {- // When searching, items may come from anywhere in the subtree, so we- // expose a "parentPath" subtitle whenever the item's parent differs from- // currentFolderId. When no search is active, every item is in the- // current folder by definition and the subtitle is suppressed.- const inSearch = search.length > 0;- // Inside a mount the listing is the directory; storage rows don't apply.- if (currentLocalDirectory) {- const needle = search.toLowerCase();- const compare: Record<- string,- (a: DiskFileEntry, b: DiskFileEntry) => number- > = {- "name-asc": (a, b) => a.name.localeCompare(b.name),- "name-desc": (a, b) => b.name.localeCompare(a.name),- "size-asc": (a, b) => a.sizeBytes - b.sizeBytes,- "size-desc": (a, b) => b.sizeBytes - a.sizeBytes,- "modified-asc": (a, b) => a.lastModified - b.lastModified,- "modified-desc": (a, b) => b.lastModified - a.lastModified,- };- const toDiskEntries = (list: DiskFileEntry[]) =>- list- .filter((disk) => !needle || disk.name.toLowerCase().includes(needle))- .sort(compare[filesPage.sortMode] ?? compare["modified-desc"]!)- .map<FilesPageEntry>((disk) => ({- kind: "diskFile",- disk,- diskState: outputDirectory ? diskStateFor(disk.name) : undefined,- processingLocked:- Boolean(outputDirectory) && processingLockedFor(disk.name),- hasOriginal: outputDirectory- ? revertables.has(disk.name)- : undefined,- }))- .filter(- (entry) =>- diskStateFilter === "all" ||- entry.diskState === undefined ||- entry.diskState === diskStateFilter,- );- return [- ...visibleFolders.map<FilesPageEntry>((folder) => ({- kind: "folder",- folder,- folderFileCount: 0,- })),- ...toDiskEntries(diskEntries),- ];- }- return [- ...visibleFolders.map<FilesPageEntry>((folder) => ({- kind: "folder",- folder,- folderFileCount: filesPage.fileCountsByFolder.get(folder.id) ?? 0,- parentPath:- inSearch && folder.parentFolderId !== currentFolderId- ? pathForFolderId(folder.parentFolderId) || undefined- : undefined,- })),- ...visibleFiles- .map<FilesPageEntry>((file) => ({- kind: "file",- file,- diskState:- processingView &&- (file.folderId ?? null) === (currentFolderId ?? null)- ? diskStateFor(file.name)- : undefined,- processingLocked: processingLockedFileIds.has(file.id),- parentPath:- inSearch && (file.folderId ?? null) !== (currentFolderId ?? null)- ? pathForFolderId(file.folderId ?? null) || undefined- : undefined,- }))+ const entries = useMemo<FilesPageEntry[]>(+ () =>+ libraryEntries({+ visibleFolders,+ visibleFiles,+ currentFolderId,+ foldersById,+ fileCountsByFolder: filesPage.fileCountsByFolder,+ search,+ sortMode,+ originFilter,+ typeFilter,+ diskEntries: currentLocalDirectory ? diskEntries : undefined,+ })+ .map((entry) => {+ const name = entry.disk?.name ?? entry.file?.name;+ const stateVisible = entry.disk+ ? Boolean(outputDirectory)+ : processingView &&+ (entry.file?.folderId ?? null) === (currentFolderId ?? null);+ return {+ ...entry,+ diskState: name && stateVisible ? diskStateFor(name) : undefined,+ processingLocked: entry.disk+ ? Boolean(outputDirectory) && processingLockedFor(entry.disk.name)+ : Boolean(+ entry.file && processingLockedFileIds.has(entry.file.id),+ ),+ hasOriginal:+ entry.disk && outputDirectory+ ? revertables.has(entry.disk.name)+ : undefined,+ };+ }).filter((entry) =>diskStateFilter === "all" ||entry.diskState === undefined ||entry.diskState === diskStateFilter,),- ];- }, [- visibleFolders,- visibleFiles,- filesPage.fileCountsByFolder,- search,- currentFolderId,- currentLocalDirectory,- diskEntries,- outputDirectory,- processingView,- processingLockedFileIds,- diskStateFor,- revertables,- diskStateFilter,- filesPage.sortMode,- pathForFolderId,- ]);+ [+ visibleFolders,+ visibleFiles,+ currentFolderId,+ foldersById,+ filesPage.fileCountsByFolder,+ search,+ sortMode,+ originFilter,+ typeFilter,+ currentLocalDirectory,+ diskEntries,+ outputDirectory,+ processingView,+ processingLockedFor,+ processingLockedFileIds,+ diskStateFor,+ revertables,+ diskStateFilter,+ ],+ );- // ─── selection ──────────────────────────────────────────────────────────const lastClickedFileRef = useRef<FileId | null>(null);const handleSelectFile = useCallback((fileId: FileId, shift: boolean, ctrl: boolean) => {@@ -996,21 +583,11 @@ export default function FileManagerView() {return next;}}- // Once the user has 2+ files selected they're explicitly in- // multi-select mode (they checked a box, or shift-range'd, or- // ctrl-clicked) - in that mode plain clicks toggle add/remove- // instead of collapsing the whole selection back to one file.- // This is the Google Drive pattern: the "selection mode" sticks- // until the user explicitly exits via the X clear button or by- // clicking the empty background of the grid.const inMultiSelectMode = prev.size >= 2;if (ctrl || inMultiSelectMode) {if (next.has(fileId)) next.delete(fileId);else next.add(fileId);} else {- // 0 or 1 selected: plain click replaces (Finder/Explorer- // behaviour). Clicking the already-only-selected file- // deselects it, so single-file selection still toggles.const isSoleSelection = prev.size === 1 && prev.has(fileId);next.clear();if (!isSoleSelection) next.add(fileId);@@ -1022,11 +599,8 @@ export default function FileManagerView() {[visibleFiles, setSelectedFileIds],);- // Background click on the content area clears the selection.const handleContentBackgroundClick = useCallback((e: React.MouseEvent<HTMLDivElement>) => {- // Only react when the click target is the scroll container itself- // (not a card, row, or drop overlay).if (e.target === e.currentTarget) {clearSelection();}@@ -1034,60 +608,11 @@ export default function FileManagerView() {[clearSelection],);- // ─── upload (drag-from-desktop or button) ───────────────────────────────const fileInputRef = useRef<HTMLInputElement>(null);const [isDraggingExternal, setIsDraggingExternal] = useState(false);- const handleNativeUpload = useCallback(- async (files: File[]) => {- if (files.length === 0) return;- // skipWorkspaceDispatch: the user is in the file manager, not opening- // files for work. Persist to IDB so the file appears in the grid (via- // FilesPageContext's independent IDB scan) but DON'T pollute workspace- // state - otherwise the file pops up the next time the user navigates- // to /viewer or /tools, which reads as "auto-opened" and surprised- // people every time. The grid will repaint via refresh() below.- // Files uploaded while standing in a folder belong in that folder.- const target =- currentTab === "all" || currentTab === "cloud" ? currentFolderId : null;- const targetFolder = target ? folders.foldersById.get(target) : undefined;- if (targetFolder && folderKind(targetFolder) === "local") {- const { failedCount } = await writeIntoMount(- targetFolder.directory,- files.map((file) => ({ name: file.name, bytes: async () => file })),- );- if (failedCount > 0) {- folders.setError(- t("filesPage.moveIntoMountFailed", {- count: failedCount,- defaultValue:- "{{count}} file(s) could not be written into the folder.",- }),- );- }- bumpDiskRevision();- return;- }- // Everywhere else membership is set with the stub rather than by a move that- // could fail after. For a server folder it stays local until the save lands.- const added = await addFiles(files, {- selectFiles: false,- skipWorkspaceDispatch: true,- ...(target ? { folderId: target as string } : {}),- });- const fileIds = added.map((f) => f.fileId);- if (- target !== null &&- fileIds.length > 0 &&- targetFolder &&- folderKind(targetFolder) === "server"- ) {- await moveFilesTo(fileIds, target);- }- await refresh();- },- [addFiles, currentFolderId, currentTab, folders, moveFilesTo, refresh, t],- );+ const handleNativeUpload = useLibraryUpload();+ const getDropzoneFiles = useDropzoneFiles();const reportUploadError = useCallback((err: unknown) =>@@ -1112,7 +637,6 @@ export default function FileManagerView() {[handleNativeUpload, reportUploadError],);- // ─── add to workspace ───────────────────────────────────────────────────const openFilesInWorkbench = useCallback(async (fileIds: FileId[]) => {const stubs = fileIds@@ -1123,9 +647,7 @@ export default function FileManagerView() {const proceed = async () => {clearFilesPageReturnRoute();- // Already in the workspace: nothing to fetch or add, so just go to it. Sending- // it through materialize and add again has no reason to succeed - the bytes- // are already spoken for.+ // Open workspace files directly; their bytes need no further materialization.const alreadyOpen = stubs.filter((stub) =>activeWorkspaceFileIdSet.has(stub.id as string),);@@ -1139,8 +661,7 @@ export default function FileManagerView() {updateStub: fileActions.updateStirlingFileStub,});if (materialized.length !== toOpen.length) {- // At least one server download failed; refresh so the grid- // reflects any successful ingests and the user can retry.+ // Refresh successful imports even when another file fails.await refresh();return;}@@ -1151,7 +672,6 @@ export default function FileManagerView() {});}- // Every file the user asked for, whether it arrived now or was already there.const opened = [...alreadyOpen, ...materialized];if (opened.length === 1) {setActiveFileId(opened[0].id);@@ -1189,7 +709,6 @@ export default function FileManagerView() {const handleOpenFile = useCallback((file: StirlingFileStub) => {- // Double-click commits to workspace.void handleAddToWorkspace([file.id]);},[handleAddToWorkspace],@@ -1203,8 +722,14 @@ export default function FileManagerView() {[openFolder, clearSelection],);- // ─── full-page drag-and-drop for OS uploads ─────────────────────────────const dropZoneRef = useRef<HTMLDivElement>(null);+ const dropQueue = useRef<Promise<void>>(Promise.resolve());+ const onScrollCapture = useLibraryScrollPosition(+ dropZoneRef,+ `${currentTab}:${currentFolderId}:${viewMode}`,+ loading || diskLoading,+ entries.length,+ );useEffect(() => {const node = dropZoneRef.current;if (!node) return;@@ -1234,10 +759,15 @@ export default function FileManagerView() {e.preventDefault();counter = 0;setIsDraggingExternal(false);- const dropped = Array.from(e.dataTransfer?.files ?? []);- if (dropped.length > 0) {- handleNativeUpload(dropped).catch(reportUploadError);- }+ // Capture drop entries while the event is live; import batches in order without losing later drops.+ const files = getDropzoneFiles(e);+ dropQueue.current = dropQueue.current+ .then(async () =>+ handleNativeUpload(+ (await files).filter((item) => item instanceof File),+ ),+ )+ .catch(reportUploadError);};node.addEventListener("dragenter", onEnter);node.addEventListener("dragover", onOver);@@ -1249,17 +779,14 @@ export default function FileManagerView() {node.removeEventListener("dragleave", onLeave);node.removeEventListener("drop", onDrop);};- }, [handleNativeUpload, reportUploadError]);+ }, [getDropzoneFiles, handleNativeUpload, reportUploadError]);- // ─── close / exit ───────────────────────────────────────────────────────const handleClose = useCallback(() => {// Drop the return-route hint so the workbench doesn't show a stale back.clearFilesPageReturnRoute();navigate(EDITOR_BASENAME);}, [navigate]);- // ─── keyboard shortcuts ─────────────────────────────────────────────────- // Focus the super-search input (stable id), used by the "/" shortcut.const focusSearch = useCallback(() => {(document.getElementById("super-search-input") as HTMLInputElement | null@@ -1274,14 +801,12 @@ export default function FileManagerView() {active.tagName === "TEXTAREA" ||active.isContentEditable);- // Cmd/Ctrl + A - select every visible file in the current folder.if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "a" && !inInput) {e.preventDefault();setSelectedFileIds(new Set(visibleFiles.map((f) => f.id)));return;}- // Delete / Backspace - remove selected files.if ((e.key === "Delete" || e.key === "Backspace") &&!inInput &&@@ -1289,7 +814,7 @@ export default function FileManagerView() {) {e.preventDefault();removeFiles(Array.from(selectedFileIds)).catch((err) =>- folders.setError(+ setFolderError(err instanceof Error? t("filesPage.error.removeFilesFailedDetail", {message: err.message,@@ -1304,7 +829,6 @@ export default function FileManagerView() {return;}- // "/" focuses the search field.if (e.key === "/" && !inInput) {e.preventDefault();focusSearch();@@ -1319,6 +843,8 @@ export default function FileManagerView() {removeFiles,setSelectedFileIds,focusSearch,+ setFolderError,+ t,]);useEffect(() => {@@ -1337,7 +863,7 @@ export default function FileManagerView() {for (const overlay of overlays) {if ((overlay as HTMLElement).offsetWidth > 0) return;}- // Esc-once cancels selection before closing the workbench.+if (selectedFileIds.size > 0) {clearSelection();return;@@ -1348,7 +874,6 @@ export default function FileManagerView() {return () => window.removeEventListener("keydown", onKey);}, [handleClose, selectedFileIds, clearSelection]);- // ─── remove via context wrapper (clears selection state too) ────────────const handleRemoveFiles = useCallback(async (fileIds: FileId[]) => {await removeFiles(fileIds);@@ -1356,9 +881,6 @@ export default function FileManagerView() {[removeFiles],);- // ─── per-file kebab: download / rename / duplicate ───────────────────────- // Same actions the file sidebar's kebab offers, so both surfaces match.-/** Cloud-only rows hold no bytes; pull them local before acting on them. */const localCopyOf = useCallback(async (file: StirlingFileStub): Promise<StirlingFileStub | null> => {@@ -1442,20 +964,14 @@ export default function FileManagerView() {[renameTarget, localCopyOf, fileActions, refresh, t],);- // ─── derived UI bits ────────────────────────────────────────────────────- const currentFolderRecord = currentFolderId- ? (foldersById.get(currentFolderId) ?? null)- : null;const totalCount = entries.length;const selectedFiles = useMemo(- () => Array.from(selectedFileIds),- [selectedFileIds],+ () => Array.from(selectedFileIds).filter((id) => fileMap.has(id)),+ [selectedFileIds, fileMap],);- // A phone with files selected shows a contextual selection bar instead of the- // full toolbar - five bulk buttons plus filters cannot fit the width.+ // On phones, selection actions and filters compete for width.const mobileSelection = isMobile && selectedFiles.length > 0;- // Local-only subset of selection; drives Save-to-server visibility.const localOnlySelectedStubs = useMemo(() =>selectedFiles@@ -1466,62 +982,22 @@ export default function FileManagerView() {),[selectedFiles, fileMap],);+ const movableSelectedFiles = selectedFiles.filter((id) => {+ const file = fileMap.get(id);+ return file && !isBrowserOnlyFile(file);+ });- // Per-destination availability for the New-folder menu; the reason renders as the- // disabled item's caption.- const serverFolderDisabledReason = useServerFolderBlock() ?? undefined;-- // Why folder processing has no server to run on, or null. The controls that open- // the setup dialog carry it as their disabled reason.const processingBlock = useServerProcessingBlock();- const { addLocalFolder } = useNewFolderFlow();+ const {+ addLocalFolder,+ createFolderHereBlockedReason: newFolderDisabledReason,+ serverFolderBlock: serverFolderDisabledReason,+ } = useNewFolderFlow();- // null = New folder actionable; string = disabled tooltip reason.const { refreshing, refresh: handleRefresh } = useLibraryRefresh();- const newFolderDisabledReason: string | null = useMemo(() => {- // Only All/Cloud render folders, so creating one elsewhere would look inert.- if (- currentTab === "recent" ||- currentTab === "shared" ||- currentTab === "sharedByMe"- ) {- return t(- "filesPage.newFolderTabUnavailable",- "Switch to All or Cloud to create folders.",- );- }- // A subfolder inherits kind server, so the blockers gate the button rather- // than letting the dialog open and fail at submit.- if (- currentFolder &&- folderKind(currentFolder) === "server" &&- serverFolderDisabledReason- ) {- return serverFolderDisabledReason;- }- // The web root creates on the server or not at all.- if (- folders.currentFolderId === null &&- !canPickDirectory &&- serverFolderDisabledReason- ) {- return serverFolderDisabledReason;- }- return null;- }, [- currentTab,- currentLocalDirectory,- currentFolder,- folders.currentFolderId,- serverFolderDisabledReason,- t,- ]);-- // Stable identities, here and for the controls built below: the bar re-registers- // whenever what it was given changes, so a value rebuilt per render turns that into- // an endless register -> render -> register loop.+ // The workbench bar re-registers changed values; stable identities prevent a render loop.const openFilePicker = useCallback(async () => {try {const files = await openFilesFromDisk({@@ -1555,14 +1031,6 @@ export default function FileManagerView() {openNewFolderDialog,],);- // Reads the trail from context, so it takes no props to change. Only the- // folder-rooted tabs have a trail to show: the rest list files by predicate.- const path = useMemo(- () =>- currentTab === "all" || currentTab === "cloud" ? <Breadcrumbs /> : null,- [currentTab],- );-const libraryActions = useMemo(() => (<>@@ -1605,15 +1073,12 @@ export default function FileManagerView() {],);- // The file sidebar carries these on desktop. Mobile has no sidebar to put them- // in, so there they go in the bar - the only chrome its layout shows.+ // Mobile has no sidebar, so its library actions live in the workbench bar.useFileLibraryWorkbenchBarButtons({- path: isMobile ? path : null,+ path: null,actions: isMobile ? libraryActions : null,});- // One instance for whichever surface the view mode uses, so the two cannot- // drift apart.const bulkActionsMenu =selectedFiles.length > 0 ? (<FilesToolbarBulkMenu@@ -1630,14 +1095,22 @@ export default function FileManagerView() {? () => setMobileDetailsOpen(true): undefined}- onMove={() => promptMoveFiles(selectedFiles)}+ onMove={+ movableSelectedFiles.length > 0+ ? () => promptMoveFiles(movableSelectedFiles)+ : undefined+ }onRemove={() => handleRemoveFiles(selectedFiles)}onClearSelection={() => clearSelection()}/>) : null;return (- <div className="files-page" ref={dropZoneRef}>+ <div+ className="files-page"+ ref={dropZoneRef}+ onScrollCapture={onScrollCapture}+ ><inputref={fileInputRef}type="file"@@ -1675,27 +1148,27 @@ export default function FileManagerView() {</div>)}- {/* No offline banner: when the folder API is unreachable the user- still sees their cached local files (the IDB read survives), and- folder-mutation controls are individually disabled with their own- tooltips. Banner removed per UX feedback. */}-<div className="files-page-body"><main className="files-page-main">- {/* The folder trail gets its own row above the toolbar. On mobile the- shared bar above carries it instead, so this row stays empty. */}- <div className="files-page-tabs-row">- {!isMobile && path && (- <div className="files-page-tabs-path">{path}</div>- )}- </div>+ <LibraryTabs+ currentTab={currentTab}+ sharingEnabled={sharingEnabled}+ onChange={setCurrentTab}+ onOpenRoot={() => openFolder(ROOT_FOLDER_ID)}+ rootDropHandlers={folderDropHandlers(ROOT_FOLDER_ID)}+ breadcrumbs={<Breadcrumbs />}+ /><div className="files-page-toolbar"><FilesToolbarCount- loading={loading}totalCount={totalCount}selectedCount={selectedFiles.length}/>+ {bulkActionsMenu && (+ <div className="files-page-selection-actions">+ {bulkActionsMenu}+ </div>+ )}{currentFolder && !mobileSelection && processingEnabled && (<div className="files-page-folder-actions"><FolderMenu@@ -1766,221 +1239,27 @@ export default function FileManagerView() {<div className="files-page-toolbar-actions">{!mobileSelection && (<>- {isMobile ? (- /* Side by side these need ~480px and were truncating to- stubs like "All sour"; collapsed they read in full. */- <>- <FilesToolbarFilterMenu- originFilter={originFilter}- onOriginChange={setOriginFilter}- availableTypes={availableTypes}- typeFilter={typeFilter}- onTypeChange={setTypeFilter}- search={search}- onSearchChange={setSearch}- />- <FilesToolbarSortMenu- value={sortMode}- onChange={setSortMode}- />- </>- ) : (- <>- <Select- size="xs"- value={originFilter}- onChange={(value) =>- value &&- setOriginFilter(value as FilesPageOriginFilter)- }- data={[- {- value: "all",- label: t("filesPage.origin.all", "All sources"),- },- {- value: "local",- label: t("filesPage.origin.local", "Local"),- },- {- value: "cloud",- label: t("filesPage.origin.cloud", "Cloud"),- },- {- value: "shared-with-me",- label: t("filesPage.origin.shared", "Shared"),- },- ]}- style={{ width: 140 }}- aria-label={t(- "filesPage.originFilter",- "Filter by source",- )}- />- {availableTypes.length > 1 && (- <MultiSelect- size="xs"- value={typeFilter}- onChange={setTypeFilter}- data={availableTypes.map((ext) => ({- value: ext,- label: ext,- }))}- placeholder={- typeFilter.length === 0- ? t("filesPage.typeFilter.allTypes", "All types")- : undefined- }- clearable- hidePickedOptions- searchable={false}- style={{ width: 160 }}- aria-label={t(- "filesPage.typeFilter.label",- "Filter by type",- )}- />- )}- <TextInput- size="xs"- value={search}- onChange={(e) => setSearch(e.currentTarget.value)}- placeholder={t(- "filesPage.search.placeholder",- "Filter files…",- )}- leftSection={<Icon name="search" size={"1rem"} />}- rightSection={- search ? (- <ActionIcon- variant="tertiary"- size="sm"- onClick={() => setSearch("")}- aria-label={t(- "filesPage.search.clear",- "Clear filter",- )}- >- <Icon name="x" size={"0.9rem"} />- </ActionIcon>- ) : null- }- aria-label={t(- "filesPage.search.label",- "Filter files by name",- )}- style={{ width: 180 }}- />- <Select- size="xs"- value={sortMode}- onChange={(value) =>- value && setSortMode(value as FilesPageSortMode)- }- data={[- {- value: "modified-desc",- label: t(- "filesPage.sort.modifiedDesc",- "Recent first",- ),- },- {- value: "modified-asc",- label: t(- "filesPage.sort.modifiedAsc",- "Oldest first",- ),- },- {- value: "name-asc",- label: t("filesPage.sort.nameAsc", "Name A→Z"),- },- {- value: "name-desc",- label: t("filesPage.sort.nameDesc", "Name Z→A"),- },- {- value: "size-desc",- label: t(- "filesPage.sort.sizeDesc",- "Largest first",- ),- },- {- value: "size-asc",- label: t(- "filesPage.sort.sizeAsc",- "Smallest first",- ),- },- ]}- style={{ width: 160 }}- />- </>- )}- <span- className="files-page-toolbar-divider"- aria-hidden="true"- />- <SegmentedControl- size="sm"- value={viewMode}- onChange={(v) => {- // Mantine only emits values declared in `data[].value`, but- // narrow defensively so a future third option can't silently- // bypass the FilesPageViewMode contract. Derived from the- // `as const` tuple so adding a mode anywhere in the code- // base automatically widens the guard here.- if (- !(FILES_PAGE_VIEW_MODES as readonly string[]).includes(- v,- )- )- return;- setViewMode(v);- }}- aria-label={t("filesPage.viewMode.label", "View mode")}- options={[- {- value: "grid",- label: (- <span- className="files-page-view-toggle-icon"- title={t("filesPage.viewMode.grid", "Grid view")}- >- <Icon name="layout-grid" size={20} />- <span className="files-page-sr-only">- {t("filesPage.viewMode.grid", "Grid view")}- </span>- </span>- ),- },- {- value: "list",- label: (- <span- className="files-page-view-toggle-icon"- title={t("filesPage.viewMode.list", "List view")}- >- <Icon name="list" size={20} />- <span className="files-page-sr-only">- {t("filesPage.viewMode.list", "List view")}- </span>- </span>- ),- },- ]}+ <LibraryToolbar+ isMobile={isMobile}+ availableTypes={availableTypes}+ originFilter={originFilter}+ setOriginFilter={setOriginFilter}+ typeFilter={typeFilter}+ setTypeFilter={setTypeFilter}+ search={search}+ setSearch={setSearch}+ sortMode={sortMode}+ setSortMode={setSortMode}+ viewMode={viewMode}+ setViewMode={setViewMode}/></>)}</div></div>- {/* Always rendered: a row that only exists once something is selected- would push the listing down under the pointer mid-double-click. */}- <div className="files-page-above-table">- {processingView && (+ {processingView && (+ <div className="files-page-above-table"><div className="files-page-state-filters">{(["all", "done", "processing", "failed", "waiting"] as const@@ -2003,13 +1282,8 @@ export default function FileManagerView() {</button>))}</div>- )}- {viewMode === "grid" && bulkActionsMenu && (- <div className="files-page-toolbar-actions files-page-selection-actions">- {bulkActionsMenu}- </div>- )}- </div>+ </div>+ )}<divclassName="files-page-content"@@ -2026,9 +1300,6 @@ export default function FileManagerView() {selectedFileIds={selectedFileIds}activeWorkspaceFileIds={activeWorkspaceFileIdSet}viewMode={viewMode}- selectionActions={- viewMode === "list" ? bulkActionsMenu : undefined- }sortMode={sortMode}onChangeSortMode={setSortMode}onSelectFile={handleSelectFile}@@ -2062,17 +1333,20 @@ export default function FileManagerView() {);}}onRemoveFiles={handleRemoveFiles}- onPromptMoveFiles={promptMoveFiles}+ onPromptMoveFiles={(ids) =>+ promptMoveFiles(+ ids.filter((id) => {+ const file = fileMap.get(id);+ return file && !isBrowserOnlyFile(file);+ }),+ )+ }onSaveToServer={(file) => setSaveToServerTarget([file])}onVersionHistory={(file) => setVersionHistoryFile(file)}onDownloadFile={handleDownloadFile}onRenameFile={setRenameTarget}onDuplicateFile={handleDuplicateFile}saveToServerDisabledReason={saveToServerDisabledReason}- // Center-of-grid CTAs when the empty state shows - same- // handlers the corner header buttons use so behaviour- // (disabled tooltips, native file picker, dialog) is- // identical regardless of where the user clicks from.onEmptyUpload={openFilePicker}emptyNewFolderControl={<NewFolderButton@@ -2096,11 +1370,6 @@ export default function FileManagerView() {{t("filesPage.dropOverlay", "Drop files to upload")}</span><span className="files-page-drop-overlay-sub">- {/* Behavior contract: per handleNativeUpload above, files- dropped inside a folder on the All/Cloud views are- placed into it — a mount takes them onto the disk- itself. Other tabs land drops in Local, so the copy- must match. */}{(currentTab === "all" || currentTab === "cloud") &¤tFolderId !== null? t(@@ -2109,7 +1378,7 @@ export default function FileManagerView() {): t("filesPage.dropOverlaySub",- "Files land in Local. Organise them into folders any time.",+ "Files appear in Recents. Organize them into folders any time.",)}</span></div>@@ -2117,12 +1386,11 @@ export default function FileManagerView() {</div></main>- {/* Inline aside on desktop. */}{selectedFiles.length > 0 && !isCompactDetailsViewport && (<FileDetailsPanelselectedFileIds={selectedFiles}fileMap={fileMap}- currentFolder={currentFolderRecord}+ foldersById={foldersById}onClose={() => clearSelection()}onAddToWorkspace={handleAddToWorkspace}onMove={promptMoveFiles}@@ -2152,7 +1420,6 @@ export default function FileManagerView() {/>)}- {/* Drawer hosts the details panel on ≤800px viewports. */}{isCompactDetailsViewport && (<Draweropened={mobileDetailsOpen && selectedFiles.length === 1}@@ -2167,7 +1434,7 @@ export default function FileManagerView() {<FileDetailsPanelselectedFileIds={selectedFiles}fileMap={fileMap}- currentFolder={currentFolderRecord}+ foldersById={foldersById}onClose={() => setMobileDetailsOpen(false)}onAddToWorkspace={handleAddToWorkspace}onMove={promptMoveFiles}@@ -2190,8 +1457,7 @@ export default function FileManagerView() {<MoveToFolderDialogopened={moveDialog.open}onClose={closeMoveDialog}- // Files can go anywhere, but a folder moves only within its own kind and- // never into a mount - a directory's subfolders are the filesystem's.+ // Folders stay within their storage kind; mounted directories cannot receive library subfolders.folders={folders.folders.filter((candidate) => {if (!moveDialog.folderId) return true;if (folderKind(candidate) === "local") return false;@@ -2207,9 +1473,9 @@ export default function FileManagerView() {await moveFolderTo(moveDialog.folderId, target);}}}- // Inline-create folder; gated on serverReachable.+onCreateFolder={- folders.serverReachable+ serverFolderDisabledReason === null? (name, parentFolderId) =>folders.createFolder(name, parentFolderId): undefined@@ -2260,7 +1526,6 @@ export default function FileManagerView() {}}/>- {/* Cloud-aware delete; offers local/cloud/both when a file lives in both. */}<DeleteFilesDialogopened={deleteDialogOpen}files={deleteDialogFiles}@@ -2268,7 +1533,6 @@ export default function FileManagerView() {onConfirm={confirmRemoveFiles}/>- {/* Rename (opened from the card kebab). */}<RenameFileDialogopened={Boolean(renameTarget)}fileName={renameTarget?.name ?? ""}@@ -2276,7 +1540,6 @@ export default function FileManagerView() {onSubmit={handleConfirmRename}/>- {/* Version journey in a modal (opened from the card kebab). */}<VersionHistoryModalopened={Boolean(versionHistoryFile)}onClose={() => setVersionHistoryFile(null)}@@ -2284,42 +1547,19 @@ export default function FileManagerView() {onChanged={refresh}/>- {/* Save-to-server modal; keyed on target so updates don't retarget. */}- <BulkUploadToServerModal+ <AddToLibraryModalkey={`save-${(saveToServerTarget ?? []).map((s) => s.id).join(",")}`}- opened={Boolean(saveToServerTarget && saveToServerTarget.length > 0)}onClose={() => setSaveToServerTarget(null)}files={saveToServerTarget ?? []}- onUploaded={refresh}/></div>);}-/**- * A cheap identity for a directory listing, so a background re-read only re-renders the- * grid when something actually changed on disk.- */-/** How often a working folder's per-file states re-read while it is open. */-const PROCESSING_FILES_POLL_MS = 3000;-const PROCESSING_FILES_FAILURE_LIMIT = 3;-const EMPTY_FILE_STATES: ReadonlyMap<string, DiskFileState> = new Map();-const EMPTY_REVERTABLES: ReadonlySet<string> = new Set();--function listingSignature(- files: { path: string; sizeBytes: number; lastModified: number }[],-): string {- return files- .map((file) => `${file.path}|${file.sizeBytes}|${file.lastModified}`)- .join("\n");-}--function Breadcrumbs() {+function useFolderDropHandlers() {const { t } = useTranslation();const folders = useFolders();const filesPage = useFilesPage();- const openFolder = useOpenFolder();- const trail = folders.breadcrumbs;const reportFailure = (err: unknown, detailKey: string, plainKey: string) => {folders.setError(@@ -2332,8 +1572,7 @@ function Breadcrumbs() {);};- /** A crumb is a drop target for the folder it names. */- const dropHandlers = (target: FolderBreadcrumbEntry) => ({+ return (folderId: FolderId | null) => ({onDragOver: (e: React.DragEvent) => {if (e.dataTransfer.types.includes(FILES_PAGE_DRAG_TYPE)) {e.preventDefault();@@ -2345,9 +1584,7 @@ function Breadcrumbs() {const payload = parseFilesPageDragPayload(e.dataTransfer);if (!payload) return;if (payload.kind === "files") {- // Through moveFilesTo so the revision bumps and the grid refreshes, and a- // rejection reaches the banner rather than only the console.- void filesPage.moveFilesTo(payload.fileIds, target.id).catch((err) => {+ void filesPage.moveFilesTo(payload.fileIds, folderId).catch((err) => {console.error("[breadcrumb] drop failed", err);reportFailure(err,@@ -2356,26 +1593,31 @@ function Breadcrumbs() {);});} else if (payload.kind === "folder") {- // Through moveFolderTo so the client-side cycle guard fires before the- // server call: dropping an ancestor on a descendant crumb has its own- // message, not the generic banner.- void filesPage- .moveFolderTo(payload.folderId, target.id)- .catch((err) => {- console.error("[breadcrumb] folder drop failed", err);- reportFailure(- err,- "filesPage.error.moveFolderFailedDetail",- "filesPage.error.moveFolderFailed",- );- });+ // Use the shared move action so ancestor drops report the cycle guard's reason.+ void filesPage.moveFolderTo(payload.folderId, folderId).catch((err) => {+ console.error("[breadcrumb] folder drop failed", err);+ reportFailure(+ err,+ "filesPage.error.moveFolderFailedDetail",+ "filesPage.error.moveFolderFailed",+ );+ });}},});+}- // Two crumbs at most. Everything above them, the root included, moves into the- // overflow menu: a deep trail otherwise grows the bar it sits in, and the folder- // you are actually in is the one that scrolls out of sight.+function Breadcrumbs() {+ const { t } = useTranslation();+ const folders = useFolders();+ const openFolder = useOpenFolder();+ const dropHandlers = useFolderDropHandlers();+ const trail = folders.breadcrumbs.filter(+ (entry) => entry.id !== ROOT_FOLDER_ID,+ );+ if (trail.length === 0) return null;++ // Collapse ancestors so the current folder stays visible in deep paths.const VISIBLE = 2;const split = Math.max(0, trail.length - VISIBLE);const hidden = trail.slice(0, split);@@ -2386,6 +1628,12 @@ function Breadcrumbs() {className="files-page-breadcrumbs"aria-label={t("filesPage.breadcrumbs", "Folder path")}>+ <Icon+ name="chevron-right"+ size={20}+ className="files-page-breadcrumb-sep"+ aria-hidden="true"+ />{hidden.length > 0 && (<><Menu shadow="md" position="bottom-start" withinPortal>@@ -2430,7 +1678,7 @@ function Breadcrumbs() {className={`files-page-breadcrumb${isLast ? " is-current" : ""}`}title={entry.name}onClick={() => openFolder(entry.id)}- {...dropHandlers(entry)}+ {...dropHandlers(entry.id)}>{entry.name}</button>diff --git a/frontend/editor/src/core/components/filesPage/FileOriginBadge.tsx b/frontend/editor/src/core/components/filesPage/FileOriginBadge.tsxindex 078ed1810e..3085401d61 100644--- a/frontend/editor/src/core/components/filesPage/FileOriginBadge.tsx+++ b/frontend/editor/src/core/components/filesPage/FileOriginBadge.tsx@@ -6,6 +6,7 @@ import { FileOrigin } from "@app/components/filesPage/fileOrigin";interface FileOriginBadgeProps {origin: FileOrigin;+ onDisk?: boolean;/** Compact (icon-only) vs full (icon + text). */compact?: boolean;tooltip?: string;@@ -41,6 +42,7 @@ const styles = {export function FileOriginBadge({origin,+ onDisk = false,compact = false,tooltip,}: FileOriginBadgeProps) {@@ -69,12 +71,13 @@ export function FileOriginBadge({default:return {label: t("filesPage.origin.local", "Local"),- icon: <Icon name="monitor" size={"0.85rem"} />,- style: styles.local,- tooltip: t(- "filesPage.origin.localHint",- "Only stored in this browser",+ icon: (+ <Icon name={onDisk ? "monitor" : "cloud-off"} size={"0.85rem"} />),+ style: styles.local,+ tooltip: onDisk+ ? t("filesPage.origin.diskFileHint", "Stored on your computer")+ : t("filesPage.origin.localHint", "Not backed up"),};}})();diff --git a/frontend/editor/src/core/components/filesPage/FilenameSearch.tsx b/frontend/editor/src/core/components/filesPage/FilenameSearch.tsxnew file mode 100644index 0000000000..1dcce2f659--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/FilenameSearch.tsx@@ -0,0 +1,85 @@+import { Popover, TextInput } from "@mantine/core";+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Icon } from "@app/ui/Icon";++/** The host owns the query so it survives switching between list and grid views. */+export function FilenameSearch({+ value,+ onChange,+ zIndex,+}: {+ value: string;+ onChange: (value: string) => void;+ zIndex?: number;+}) {+ const { t } = useTranslation();+ const inputRef = useRef<HTMLInputElement>(null);+ const [opened, setOpened] = useState(false);+ const label = t("filesPage.search.label", "Search filenames");+ const active = value.trim().length > 0;+ return (+ <Popover+ opened={opened}+ onChange={setOpened}+ closeOnEscape={false}+ width={260}+ position="bottom-end"+ shadow="md"+ withinPortal+ zIndex={zIndex}+ trapFocus+ returnFocus+ >+ <Popover.Target>+ <ActionIcon+ variant={active ? "secondary" : "tertiary"}+ size="sm"+ aria-label={label}+ title={active ? `${label}: ${value}` : label}+ className="files-page-toolbar-icon-btn"+ onClick={() => setOpened((current) => !current)}+ >+ <Icon name="search" size="1.1rem" />+ </ActionIcon>+ </Popover.Target>+ <Popover.Dropdown+ aria-label={label}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ // The library also handles Escape to leave the page.+ event.stopPropagation();+ setOpened(false);+ }+ }}+ >+ <TextInput+ ref={inputRef}+ data-autofocus+ size="sm"+ value={value}+ onChange={(event) => onChange(event.currentTarget.value)}+ placeholder={t("filesPage.search.placeholder", "Search filenames…")}+ aria-label={label}+ leftSection={<Icon name="search" size="1rem" />}+ rightSection={+ value ? (+ <ActionIcon+ variant="tertiary"+ size="sm"+ onClick={() => {+ onChange("");+ inputRef.current?.focus();+ }}+ aria-label={t("filesPage.search.clear", "Clear search")}+ >+ <Icon name="x" size="0.9rem" />+ </ActionIcon>+ ) : null+ }+ />+ </Popover.Dropdown>+ </Popover>+ );+}diff --git a/frontend/editor/src/core/components/filesPage/FilesPage.css b/frontend/editor/src/core/components/filesPage/FilesPage.cssindex ad1a1dc7b3..0cc108a5c1 100644--- a/frontend/editor/src/core/components/filesPage/FilesPage.css+++ b/frontend/editor/src/core/components/filesPage/FilesPage.css@@ -8,27 +8,34 @@overflow: hidden;}-/* The library's own row. The shared bar above carries only what every view has,- so the folder path sits here instead. */-.files-page-tabs-row {+.files-page-navigation {display: flex;align-items: center;- gap: 0.5rem;- min-width: 0;+ gap: 0.75rem;+ padding: 0.5rem 1.25rem;+ border-block: 1px solid var(--c-border-subtle);+ overflow-x: auto;+ flex-shrink: 0;}-.files-page-tabs-path {- flex: 1;- min-width: 0;+.files-page-view-tabs {display: flex;align-items: center;- overflow: hidden;+ gap: 0.75rem;+ flex-shrink: 0;}-/* The folder path. Sized and coloured like the bar's own controls, since on mobile- that is where it renders. Fixed height and no wrapping: a deep trail would- otherwise push its row taller, so depth is handled by showing fewer crumbs - see- the overflow menu. */+.files-page-view-tabs > .files-page-breadcrumbs {+ flex: 1;+}++@media (max-width: 768px) {+ .files-page-navigation {+ padding-inline: 0.75rem;+ }+}++/* A fixed height keeps deep folder paths from pushing the file list down. */.files-page-breadcrumbs {display: flex;align-items: center;@@ -67,7 +74,6 @@color: var(--c-text);}-/* The parents that don't fit, root included. */.files-page-breadcrumb-overflow {flex-shrink: 0;}@@ -105,10 +111,6 @@flex-shrink: 0;flex-wrap: wrap;min-height: 3rem;- /* Safety net - the content should always fit thanks to the shrink rules on- `.files-page-toolbar-actions` below, but if a future addition ever breaks- that, this stops the action group bleeding into sibling areas (notably the- details panel on the right). */overflow-x: hidden;}@@ -118,7 +120,6 @@font-weight: 500;}-/* Upload + New folder at the start of the toolbar. */.files-page-toolbar-create {display: inline-flex;align-items: center;@@ -137,31 +138,25 @@justify-content: flex-end;flex-wrap: wrap;gap: 0.5rem;- /* Allow this container to shrink below its intrinsic content width so it- wraps inside the toolbar rather than bursting out of it (it would bleed- under the right-hand details panel). */min-width: 0;}-/* The filter, search and sort controls are text: shrinking them renders- "All sources" as "All s". They keep their declared width and the group- above wraps to a second line when the toolbar runs out of room. */.files-page-toolbar-actions > .mantine-Select-root,.files-page-toolbar-actions > .mantine-MultiSelect-root,.files-page-toolbar-actions > .mantine-TextInput-root {flex-shrink: 0;}-/* The menu triggers in the toolbar - selection actions, folder settings. Tighter- on the chevron side than the label side so the caret sits against the edge- rather than floating in its own margin. */.files-page-toolbar-bulk-trigger {padding-left: 0.75rem;padding-right: 0.5rem;flex-shrink: 0;}-/* Pin the view toggle: never let it clip off the right. flex-shrink:0- keeps its width fixed; the rest of the row shrinks around it. */++.files-page-selection-actions {+ flex-shrink: 0;+}+.files-page-toolbar-actions .mantine-SegmentedControl-root {flex-shrink: 0;}@@ -173,10 +168,7 @@margin: 0 0.15rem;}-/* SegmentedControl in the toolbar uses icon-only options; this centers the- MUI icon inside Mantine's `.mantine-SegmentedControl-innerLabel` (which- defaults to `display: inline` and baseline-aligns its children, leaving- the icon visually pinned to the top of the label box). */+/* Mantine's inline label otherwise aligns icons to the text baseline. */.files-page-view-toggle-icon {display: inline-flex;align-items: center;@@ -185,10 +177,6 @@vertical-align: middle;}-/* Visually-hidden text that screen readers still announce. Lets us put- localised labels next to icon-only buttons (SegmentedControl options,- icon-only action rows) without growing the visible UI. Standard- "sr-only" / "visually-hidden" recipe. */.files-page-sr-only {position: absolute;width: 1px;@@ -203,13 +191,25 @@.files-page-content {flex: 1 1 auto;+ min-width: 0;+ min-height: 0;overflow: auto;- padding: 1.25rem;+ padding: 0.5rem 1.25rem 1.25rem;position: relative;scrollbar-width: thin;scrollbar-color: var(--c-border-subtle) transparent;}+.files-page-above-table + .files-page-content {+ padding-top: 0;+}++.files-page-content:has(> .files-page-list) {+ display: flex;+ flex-direction: column;+ overflow: hidden;+}+.files-page-content::-webkit-scrollbar {width: 0.5rem;height: 0.5rem;@@ -250,9 +250,7 @@gap: 1rem;}-/* Stands in for the rows outside the rendered window, so the scrollbar reflects the- whole folder. Spans every column: in the grid a spacer sharing a row with cards- would be laid out beside them instead of above. */+/* Spacers span every column so virtual rows reserve vertical space in both layouts. */.files-page-virtual-pad {grid-column: 1 / -1;pointer-events: none;@@ -261,35 +259,31 @@.files-page-list {display: flex;flex-direction: column;+ flex: 1 1 auto;+ min-height: 0;border: 1px solid var(--c-border-subtle);border-radius: 0.6rem;- /* Scrolls sideways once the rows hit their floors - see the narrow step- below. Still clips vertically, so rows stay inside the rounded corners. */- overflow-x: auto;- overflow-y: hidden;+ overflow: auto;+ scrollbar-width: thin;+ scrollbar-color: var(--c-border-subtle) transparent;background: var(--c-surface);}+.files-page-list > * {+ flex-shrink: 0;+}+.files-page-list-row {display: grid;- /* No column is ever dropped, so every track carries a floor: denied its width- a value wraps and the row grows, a timestamp into three lines. Type floors- for "Processing folder" and status for two chips ("1 Failed 12 Ready"),- the widest those cells hold; name floors widest, being what stays on screen- when the row is wider than the list.-- Floors are lengths, never max-content: each row is its own grid, so a track- measuring its own text lands a few pixels off its neighbours and the- columns drift apart while scrolled. */+ /* Keep fixed column floors across independent row grids; intrinsic widths misalign rows. */grid-template-columns:2.25rem minmax(17rem, 3fr) minmax(7.5rem, 1fr) minmax(4.5rem, 1fr)minmax(9.5rem, 1.5fr) minmax(8rem, 11rem) 2.5rem;- /* The sum of those floors: a flex item will not grow to its own content, so- without this the tracks overflow a box that never grew and nothing scrolls. */+ /* Match the column floors so the list owns horizontal overflow. */min-width: 56rem;gap: 0.5rem;align-items: center;- /* Same offscreen skip as .files-page-card. */+content-visibility: auto;contain-intrinsic-size: auto 3rem;padding: 0.5rem 0.75rem;@@ -304,6 +298,10 @@}.files-page-list-row.is-header {+ position: sticky;+ top: 0;+ z-index: 1;+ content-visibility: visible;background: var(--c-bg-raised);color: var(--c-text-subtle);text-transform: uppercase;@@ -311,39 +309,10 @@letter-spacing: 0.05em;cursor: default;user-select: none;- /* Tall enough for the selection bar's button, so swapping the column labels- for it leaves the rows below where they were. A header that grows on the- first click moves the row under the pointer mid-double-click. */min-height: 3rem;}-/* Selecting replaces the column labels with what acts on the selection: they- have nothing to sort while a selection is the subject. The select-all box- keeps its track so it does not jump. */-.files-page-list-row.is-header.is-selecting {- grid-template-columns: 2.25rem minmax(0, 1fr);- background: color-mix(in srgb, var(--c-primary) 10%, var(--c-bg-raised));- color: var(--c-text);- text-transform: none;- letter-spacing: normal;-}--.files-page-list-selection-bar {- display: flex;- align-items: center;- gap: 0.6rem;- min-width: 0;-}--.files-page-list-selection-count {- font-size: 0.85rem;- font-weight: 600;- white-space: nowrap;-}-.files-page-list-row.is-header [data-sortable="true"] {- /* Block so the hit area and hover tint fill the columnheader cell that wraps- it, rather than hugging the label text. */display: block;cursor: pointer;padding: 0.2rem 0.4rem;@@ -358,6 +327,7 @@background: var(--c-hover);color: var(--c-text);}+.files-page-list-row:not(.is-header):hover,.files-page-list-row.is-selected {background: var(--c-hover);@@ -372,9 +342,7 @@position: relative;display: flex;flex-direction: column;- /* Offscreen cards skip layout and paint — a 500-entry folder only pays- for the rows in view. The intrinsic size stands in for unrendered- cards so the scrollbar doesn't jump (auto: measured size once seen). */+ /* Reserve unrendered card height to avoid scrollbar jumps. */content-visibility: auto;contain-intrinsic-size: auto 13rem;background: var(--c-surface);@@ -471,8 +439,6 @@letter-spacing: -0.005em;}-/* Values wrap as whole units onto their own lines rather than breaking- mid-value ("239.26 / KB") around a stranded separator. */.files-page-card-meta {font-size: 0.76rem;color: var(--c-text-subtle);@@ -491,8 +457,6 @@display: none;}-/* Marks a folder that runs a pipeline over anything added to it. Replaces the- item count so a processing folder reads as a different kind of thing. */.files-page-processing-tag {display: inline-flex;align-items: center;@@ -520,9 +484,6 @@background: currentColor;}-/* Per-file processing state on a working folder's listing. The badge names the- state; a not-yet-processed file is also inert (no open, no menu) until its- result exists, and reads that way. */.files-page-state-badge {display: inline-flex;align-items: center;@@ -536,8 +497,7 @@color: var(--c-text-muted);}-/* Cards only: a row is a grid whose nearest positioned ancestor is the scrolling- area, so the same rule would take the badge out of the row entirely. */+/* Rows have no positioned ancestor of their own; badge overlays apply only to cards. */.files-page-card .files-page-state-badge {position: absolute;top: 6px;@@ -572,7 +532,6 @@display: none;}-/* The open folder's own actions, inline beside the items count. */.files-page-folder-actions {display: flex;align-items: center;@@ -582,22 +541,14 @@border-left: 1px solid var(--c-border-subtle);}-/* The strip between the toolbar and the listing: state chips on the left, and- in grid view the selection's actions on the right, list view having a column- header to hold them. They sit here rather than in the toolbar because a- toolbar that reflows on selection moves every row under it, which breaks- double-click-to-open. Side padding matches the toolbar so the chips line up- with the count above them. */.files-page-above-table {display: flex;align-items: center;gap: 0.6rem;- /* Same space empty as full, so filling it moves nothing below. */- min-height: 2.5rem;+ min-height: 2rem;padding: 0 1.25rem;}-/* State filter chips above a working folder's listing. */.files-page-state-filters {display: flex;align-items: center;@@ -623,7 +574,6 @@background: var(--c-primary-subtle, var(--c-surface));}-/* Count on a filter chip ("Failed 3"). */.files-page-state-count {margin-left: 0.3rem;font-variant-numeric: tabular-nums;@@ -631,9 +581,7 @@}/* Retry on a failed file's badge; must stay clickable inside an inert card. */-/* The failed chip is the retry control: hovering it swaps its label for the- action. Both labels occupy one grid cell so the chip keeps the width of the- wider of them and the row's other cells never shift. */+/* Stack both labels to reserve their width and prevent hover layout shifts. */.files-page-state-retry {display: inline-grid;font: inherit;@@ -664,7 +612,6 @@visibility: visible;}-/* A working folder's per-state counts, one dotted chip per non-zero state. */.files-page-folder-stats {display: flex;flex-wrap: wrap;@@ -672,8 +619,7 @@margin-top: 0.3rem;}-/* The row's height is fixed, so the breakdown stays on the one line the status- cell gives it and clips rather than wrapping. */+/* Virtualized rows require a fixed height, so status text must not wrap. */.files-page-folder-stats.is-row {margin-top: 0;flex-wrap: nowrap;@@ -681,8 +627,7 @@min-width: 0;}-/* One width whatever the row has to show, so every name in the column starts at- the same x and none of them move when a thumbnail resolves. */+/* Reserve thumbnail width so file names do not shift when images load. */.files-page-list-thumb {display: inline-flex;align-items: center;@@ -699,8 +644,6 @@border-radius: 0.25rem;}-/* The state has a column of its own: beside the name it outgrows the cell and- runs under the actions. */.files-page-list-status {display: flex;align-items: center;@@ -738,8 +681,6 @@background: var(--c-danger, var(--c-text));}-/* Parent-folder breadcrumb shown on cards/rows during recursive search so- the user can tell which folder each hit lives in without navigating. */.files-page-card-path {font-size: 0.72rem;color: var(--c-text-subtle);@@ -759,8 +700,7 @@pointer-events: none;}-/* Reveal on hover, on focus-within (keyboard navigation), and when the card is selected.- :focus-within is what makes the checkbox + kebab discoverable without a pointer device. */+/* Focus must expose the same controls as pointer hover. */.files-page-card:hover .files-page-card-selector,.files-page-card:focus-within .files-page-card-selector,.files-page-card.is-selected .files-page-card-selector {@@ -768,8 +708,6 @@pointer-events: auto;}-/* Style the Mantine checkbox so it reads as a soft pill rather than a- bare form control. */.files-page-card-selector :where(.mantine-Checkbox-input) {background: var(--c-surface);border-color: var(--c-border-subtle);@@ -785,10 +723,7 @@z-index: 4;}-/* Make the kebab a high-contrast pill that works on dark thumbnails,- white PDFs, and any background underneath.- Use stronger specificity + !important to win over Mantine's- variant=filled inline styles. */+/* Override Mantine's inline variant styles for contrast on arbitrary thumbnails. */.files-page-card .files-page-card-actions button.mantine-ActionIcon-root {background-color: var(--c-surface-raised, var(--c-surface)) !important;color: var(--c-text) !important;@@ -801,8 +736,6 @@background-color: var(--c-hover) !important;}-/* Row-view kebab: same high-contrast treatment so it's readable- against selected (tinted) and in-workspace rows. */.files-page-list-row .mantine-ActionIcon-root[aria-label$="actions"] {color: var(--c-text-muted);}@@ -816,17 +749,13 @@position: absolute;bottom: 0.4rem;left: 0.4rem;- /* The overlay itself stays transparent to the card's clicks and drags, but- the badge inside must catch hover or its tooltip can never open. */+ /* Pass clicks through the overlay while allowing the badge tooltip to receive hover. */pointer-events: none;}.files-page-card-origin > * {pointer-events: auto;}-/* "Open" badge - file is currently loaded in the active workspace.- Solid pill with white text so it reads against any thumbnail- (white PDFs, dark covers, photos). */.files-page-card-open-badge {position: absolute;top: 0.5rem;@@ -1034,7 +963,6 @@line-height: 1.5;}-/* Empty-state CTA row; stacks on phones. */.files-page-empty-actions {display: flex;flex-wrap: wrap;@@ -1061,10 +989,6 @@}.files-page-details-header {- /* Tight vertical padding so the "DETAILS" label hugs the body content- below it - it's a quiet section header, not a banner, and the old- ~16px top + 18px body padding wasted nearly two character heights- of vertical space before the user saw the file thumbnail. */padding: 0.35rem 1.1rem;display: flex;align-items: center;@@ -1081,12 +1005,7 @@}.files-page-details-body {- /* Smaller top padding to pair with the tightened header above. Side- and bottom padding stays at 1.1rem so the content still breathes- against the panel edges. */padding: 0.3rem 1.1rem 1.1rem;- /* Grow to fill the panel and scroll internally so the action footer below- stays pinned and visible regardless of how tall the content gets. */flex: 1;min-height: 0;overflow-y: auto;@@ -1095,7 +1014,6 @@gap: 0.65rem;}-/* Pinned action footer - always visible so the buttons never scroll off. */.files-page-details-actions {flex-shrink: 0;display: flex;@@ -1112,14 +1030,11 @@gap: 0.4rem;}-/* The panel is narrow enough that "Add {{count}} to workspace" wraps to two- lines. ActionIcon is square by default, so without this the icons keep their- own height and the row stops sharing a baseline. */+/* Match icon-button height to action labels that wrap. */.files-page-details-actions-row .mantine-ActionIcon-root {height: auto;}-/* Collapsible "File info" header (size/type/dates). */.files-page-details-collapse-toggle {display: flex;align-items: center;@@ -1144,9 +1059,7 @@}.files-page-details-thumb {- /* Compact fixed height (was a tall 4:3 box that dominated the panel and- pushed the action buttons off the bottom). */- height: 6.5rem;+ height: clamp(15rem, 40vh, 25rem);background: var(--c-surface);border: 1px solid var(--c-border-subtle);border-radius: 0.6rem;@@ -1155,11 +1068,7 @@justify-content: center;overflow: hidden;box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);- /* Inside an overflow-y:auto flex column, `aspect-ratio` alone doesn't- guarantee intrinsic height - flex-shrink:1 (default) can squash the- thumb to a 2px sliver when the column gets cramped (notably after- tightening the body padding above). Pin shrink so the thumb keeps- its 4:3 box. */+ /* Scroll the details body instead of squashing the preview. */flex-shrink: 0;}@@ -1220,9 +1129,6 @@color: var(--c-text-subtle);}-/* Filename chip next to the title - "PDF", "DOCX", etc.- Mantine's <Badge variant="default"> rendered effectively invisible- in dark mode; project CSS vars track the active color scheme. */.files-page-details-ext-tag {display: inline-flex;align-items: center;@@ -1238,13 +1144,6 @@line-height: 1.2;}-/* Vertical timeline of version history.- Each row has a left rail (dot + connector) and a body (summary + meta- + expandable detail). The rail visually threads versions together- like a commit graph; clicking a row's summary toggles its expanded- detail (cumulative tool chain, full meta). Long chains (> 6) collapse- the middle behind a "Show N earlier versions" button. */-/* Version Timeline styling */.files-page-details-version-timeline {display: flex;flex-direction: column;@@ -1543,25 +1442,15 @@}@media (max-width: 800px) {- /* Details panel visibility is controlled by JSX (conditional Drawer) at this- width, not CSS: blanket-hiding .files-page-details would also hide it when it- lives inside the Drawer's portaled overlay tree. */+ /* JSX controls drawer visibility; hiding this class would also hide the portalled panel. */.files-page-content {- padding: 0.75rem;+ padding: 0.5rem 0.75rem 0.75rem;}}-/* Below this width the toolbar holds the count, the filter and sort triggers- and the view toggle in the room the details panel used to leave it. What- follows tightens their spacing and collapses the controls that can afford to- lose their labels. */@media (max-width: 1024px) {.files-page-toolbar {- /* nowrap so the count shares a row with the filter and sort triggers and- the view toggle. Runs to the app's own mobile breakpoint: stopping at- 900px left 901-1024px wrapping to two rows, and that band is where the- mobile layout renders. Scrolls rather than clips, so nothing the row- cannot fit ends up unreachable behind its edge. */+ /* Scroll narrow toolbars so overflow controls remain reachable. */flex-wrap: nowrap;gap: 0.35rem;padding: 0.35rem 0.5rem;@@ -1573,26 +1462,20 @@display: none;}.files-page-toolbar-info {- /* The toolbar's only status text. Pinned, because against nowrap- siblings it lost every shrink round and rendered as "3 i". */+ /* Keep the item count readable beside fixed-width controls. */flex-shrink: 0;min-width: 0;white-space: nowrap;}- /* Filter and sort collapse to icon triggers here (see FilesToolbar*Menu);- they are the whole control, so they never shrink. */+.files-page-toolbar-icon-btn {flex-shrink: 0;}- /* The desktop inset cost the state chips a chip's worth of room and wrapped- the last one onto a second line. */.files-page-above-table {padding: 0 0.5rem;}- /* The gear alone: its label and caret cost more width here than the two- filter controls beside it. */.files-page-folder-actions .files-page-toolbar-bulk-trigger {padding-left: 0.4rem;padding-right: 0.4rem;@@ -1616,22 +1499,14 @@}.files-page-toolbar-actions .mantine-Select-root,.files-page-toolbar-actions .mantine-Select-input {- /* Mantine Select defaults to ~12rem which is huge for narrow widths.- The inline `style={{ width: 140|160 }}` on the Selects gets- overridden here so they actually shrink. */+ /* Override inline control widths to fit narrow toolbars. */min-width: 0;max-width: 7.5rem;width: auto !important;}}-/* ── Mobile (≤640px) ────────────────────────────────────────────────- Tighten the chrome so the file manager fits inside the mobile workspace- slide: the slide-rail's bottom tab bar already carries the navigation, and- uploads have the centre drop overlay. */-@media (max-width: 640px) {- /* Grid: single column on very narrow phones; two columns from ~440px */.files-page-grid {grid-template-columns: repeat(auto-fill, minmax(9rem, 1fr));gap: 0.75rem;@@ -1642,19 +1517,12 @@}@media (max-width: 420px) {- /* Don't force 1fr - auto-fill with the 9rem floor already keeps two cards- per row on a 360px phone, which feels right for one-handed taps. The- real fix at this width is the list view, which had 6 columns that wouldn't- fit at all. */.files-page-grid {grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));gap: 0.5rem;}}-/* Honour user preference for reduced motion (WCAG 2.3.3). Disables the- open-badge pulse, drop-overlay pulse + scale, and the card hover lift -- keeps focus rings and selection borders so state is still visible. */@media (prefers-reduced-motion: reduce) {.files-page-card-open-dot,.files-page-drop-overlay {@@ -1675,9 +1543,7 @@}}-/* A disabled destination still has to be read - its caption carries the reason - and- Mantine's disabled colour drops below comfortable contrast in dark mode. Selector- stands on the item's own class because the dropdown renders in a portal. */+/* Keep disabled reasons readable; the menu is portalled outside its trigger's subtree. */.files-page-new-folder-option[data-disabled] {color: var(--c-text-muted) !important;opacity: 1;diff --git a/frontend/editor/src/core/components/filesPage/FilesToolbarBulkMenu.tsx b/frontend/editor/src/core/components/filesPage/FilesToolbarBulkMenu.tsxindex f5ecf89aa2..723208dd54 100644--- a/frontend/editor/src/core/components/filesPage/FilesToolbarBulkMenu.tsx+++ b/frontend/editor/src/core/components/filesPage/FilesToolbarBulkMenu.tsx@@ -6,21 +6,16 @@ import { Button } from "@app/ui/Button";interface FilesToolbarBulkMenuProps {selectedCount: number;onAddToWorkspace: () => void;- /** Local-only files in the selection; omit when there are none to upload. */+ /** Omit when the selection has no files to upload. */onSaveToServer?: () => void;- /** Set when storage is off - the item stays listed but disabled. */+ /** Keeps Add to library visible but disabled. */saveToServerDisabledReason?: string;onShowDetails?: () => void;- onMove: () => void;+ onMove?: () => void;onRemove: () => void;onClearSelection: () => void;}-/**- * Everything that acts on the current selection, behind one trigger. A strip of- * five buttons only fits the widest viewports, and shrinking it to icons costs- * every label; one menu reads the same at any width.- */export function FilesToolbarBulkMenu({selectedCount,onAddToWorkspace,@@ -45,7 +40,8 @@ export function FilesToolbarBulkMenu({<Menu.Target><Buttonsize="sm"- variant="secondary"+ variant="tertiary"+ shape="pill"className="files-page-toolbar-bulk-trigger"rightSection={<Icon name="chevron-down" size={"1.1rem"} />}aria-label={t("filesPage.bulkActions", "Actions")}@@ -66,7 +62,7 @@ export function FilesToolbarBulkMenu({disabled={Boolean(saveToServerDisabledReason)}onClick={onSaveToServer}>- {t("filesPage.saveToServer", "Save to server")}+ {t("filesPage.addToLibrary", "Add to Stirling library…")}</Menu.Item>)}{onShowDetails && (@@ -77,12 +73,14 @@ export function FilesToolbarBulkMenu({{t("filesPage.showDetails", "Show details")}</Menu.Item>)}- <Menu.Item- leftSection={<Icon name="folder-input" size={"1.1rem"} />}- onClick={onMove}- >- {t("filesPage.moveTo", "Move to…")}- </Menu.Item>+ {onMove && (+ <Menu.Item+ leftSection={<Icon name="folder-input" size={"1.1rem"} />}+ onClick={onMove}+ >+ {t("filesPage.moveTo", "Move to…")}+ </Menu.Item>+ )}<Menu.ItemleftSection={<Icon name="x" size={"1.1rem"} />}onClick={onClearSelection}diff --git a/frontend/editor/src/core/components/filesPage/FilesToolbarCount.tsx b/frontend/editor/src/core/components/filesPage/FilesToolbarCount.tsxindex 09f9658124..d04e62603f 100644--- a/frontend/editor/src/core/components/filesPage/FilesToolbarCount.tsx+++ b/frontend/editor/src/core/components/filesPage/FilesToolbarCount.tsx@@ -1,14 +1,11 @@import { useTranslation } from "react-i18next";interface FilesToolbarCountProps {- loading: boolean;totalCount: number;selectedCount: number;}-/** Status text at the head of the files toolbar. */export function FilesToolbarCount({- loading,totalCount,selectedCount,}: FilesToolbarCountProps) {@@ -20,9 +17,7 @@ export function FilesToolbarCount({return (<span className="files-page-toolbar-info">- {loading- ? t("filesPage.loading", "Loading…")- : t("filesPage.summary", "{{count}} items", { count: totalCount })}+ {t("filesPage.summary", "{{count}} items", { count: totalCount })}{selectedCount > 0 && <span> · {selected}</span>}</span>);diff --git a/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsx b/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsxindex 9f54cf3364..93b7262529 100644--- a/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsx+++ b/frontend/editor/src/core/components/filesPage/FilesToolbarFilterMenu.tsx@@ -1,4 +1,4 @@-import { MultiSelect, Popover, Select, Stack, TextInput } from "@mantine/core";+import { MultiSelect, Popover, Select, Stack } from "@mantine/core";import { useTranslation } from "react-i18next";import { Icon } from "@app/ui/Icon";import { ActionIcon } from "@app/ui/ActionIcon";@@ -12,41 +12,36 @@ interface FilesToolbarFilterMenuProps {availableTypes: string[];typeFilter: string[];onTypeChange: (value: string[]) => void;- search: string;- onSearchChange: (value: string) => void;+ zIndex?: number;}-/**- * Source, type and name filters collapsed behind one icon. Side by side these- * three need ~480px, so on narrow viewports they were each truncated to- * unreadable stubs ("All sour"). In the popover they get their full width back,- * and a dot on the trigger keeps an active filter discoverable while hidden.- */export function FilesToolbarFilterMenu({originFilter,onOriginChange,availableTypes,typeFilter,onTypeChange,- search,- onSearchChange,+ zIndex,}: FilesToolbarFilterMenuProps) {const { t } = useTranslation();const activeCount =- (originFilter !== "all" ? 1 : 0) +- (typeFilter.length > 0 ? 1 : 0) +- (search.trim() !== "" ? 1 : 0);+ (originFilter !== "all" ? 1 : 0) + (typeFilter.length > 0 ? 1 : 0);const label = t("filesPage.filters.label", "Filters");const clearAll = () => {onOriginChange("all");onTypeChange([]);- onSearchChange("");};return (- <Popover width={260} position="bottom-end" shadow="md" withinPortal>+ <Popover+ width={260}+ position="bottom-end"+ shadow="md"+ withinPortal+ zIndex={zIndex}+ ><Popover.Target><div><Tooltip@@ -76,26 +71,6 @@ export function FilesToolbarFilterMenu({</Popover.Target><Popover.Dropdown><Stack gap="xs">- <TextInput- size="xs"- value={search}- onChange={(e) => onSearchChange(e.currentTarget.value)}- placeholder={t("filesPage.search.placeholder", "Filter files…")}- leftSection={<Icon name="search" size={"1rem"} />}- rightSection={- search ? (- <ActionIcon- variant="tertiary"- size="sm"- onClick={() => onSearchChange("")}- aria-label={t("filesPage.search.clear", "Clear filter")}- >- <Icon name="x" size={"0.9rem"} />- </ActionIcon>- ) : null- }- aria-label={t("filesPage.search.label", "Filter files by name")}- /><Selectsize="xs"value={originFilter}@@ -114,7 +89,7 @@ export function FilesToolbarFilterMenu({label={t("filesPage.originFilter", "Filter by source")}comboboxProps={{ withinPortal: false }}/>- {availableTypes.length > 1 && (+ {(availableTypes.length > 1 || typeFilter.length > 0) && (<MultiSelectsize="xs"value={typeFilter}diff --git a/frontend/editor/src/core/components/filesPage/FilesToolbarSortMenu.tsx b/frontend/editor/src/core/components/filesPage/FilesToolbarSortMenu.tsxindex c69a1619bb..4a548340d2 100644--- a/frontend/editor/src/core/components/filesPage/FilesToolbarSortMenu.tsx+++ b/frontend/editor/src/core/components/filesPage/FilesToolbarSortMenu.tsx@@ -8,17 +8,13 @@ import type { FilesPageSortMode } from "@app/contexts/FilesPageContext";interface FilesToolbarSortMenuProps {value: FilesPageSortMode;onChange: (mode: FilesPageSortMode) => void;+ zIndex?: number;}-/**- * Sort control collapsed to a single icon. The desktop Select needs 160px and- * still truncated its longest label ("Recent first" → "Recent fi") once the- * toolbar got tight, so on narrow viewports the options move into a menu where- * they have room to read in full.- */export function FilesToolbarSortMenu({value,onChange,+ zIndex,}: FilesToolbarSortMenuProps) {const { t } = useTranslation();@@ -44,7 +40,13 @@ export function FilesToolbarSortMenu({const current = options.find((o) => o.value === value)?.label ?? "";return (- <Menu shadow="md" width={200} position="bottom-end" withinPortal>+ <Menu+ shadow="md"+ width={200}+ position="bottom-end"+ withinPortal+ zIndex={zIndex}+ ><Menu.Target><div><Tooltip content={`${label} · ${current}`} position="bottom">diff --git a/frontend/editor/src/core/components/filesPage/FolderMenu.tsx b/frontend/editor/src/core/components/filesPage/FolderMenu.tsxindex 7c61d1a629..2fbf5d8c5b 100644--- a/frontend/editor/src/core/components/filesPage/FolderMenu.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderMenu.tsx@@ -19,22 +19,15 @@ import { Button } from "@app/ui/Button";interface FolderMenuProps {folder: FolderRecord;processing: ProcessingFolderState | undefined;- /**- * A folder whose engine picks up arrivals on its own, where an explicit- * "retry failed" has nothing to act on.- */+ /** Arrival-driven engine with no explicit retry-failed action. */continuous: boolean;- /**- * A mounted disk directory. The disk owns its name, colour and existence, so- * the rename, appearance and delete entries do not apply to it.- */+ /** Disk-owned folders cannot be renamed, recoloured or deleted here. */isMount: boolean;/** Mount roots can be unmounted; a subdirectory below one cannot. */canUnmount: boolean;editsDisabled: boolean;editsDisabledHint?: string;- /** Why processing cannot run, or null. Gates the processing entries alone: a- * build with no server behind it can still rename and recolour a folder. */+ /** Disables only processing actions; library edits remain available. */processingBlock?: string | null;onStartProcessing: () => void;onRunProcessing: () => void;@@ -57,11 +50,6 @@ interface FolderMenuProps {triggerRef?: React.Ref<HTMLButtonElement>;}-/**- * Everything that acts on one folder, behind a single trigger. The folder you- * are inside and every folder in a row open this same menu; only the trigger- * and the Open entry differ.- */export function FolderMenu({folder,processing,@@ -112,7 +100,8 @@ export function FolderMenu({<Buttonref={triggerRef}size="sm"- variant="secondary"+ variant="tertiary"+ shape="pill"className="files-page-toolbar-bulk-trigger"leftSection={<SettingsIcon sx={{ fontSize: "1.1rem" }} />}rightSection={<ExpandMoreIcon sx={{ fontSize: "1.1rem" }} />}diff --git a/frontend/editor/src/core/components/filesPage/FolderNameDialog.tsx b/frontend/editor/src/core/components/filesPage/FolderNameDialog.tsxindex c8324f38bd..293d53da62 100644--- a/frontend/editor/src/core/components/filesPage/FolderNameDialog.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderNameDialog.tsx@@ -11,6 +11,7 @@ interface FolderNameDialogProps {submitLabel: string;onClose: () => void;onSubmit: (name: string) => void | Promise<void>;+ zIndex?: number;}export function FolderNameDialog({@@ -20,6 +21,7 @@ export function FolderNameDialog({submitLabel,onClose,onSubmit,+ zIndex,}: FolderNameDialogProps) {const { t } = useTranslation();const [value, setValue] = useState(initialName);@@ -43,9 +45,6 @@ export function FolderNameDialog({await onSubmit(name);onClose();} catch (err) {- // Keep dialog open so the user can retry. Closing on error was a- // silent failure (the dialog vanished, but the folder was never- // created - user thinks success, sees no folder).setError(err instanceof Error? err.message@@ -65,6 +64,7 @@ export function FolderNameDialog({onClose={onClose}title={title}centered+ zIndex={zIndex}size="sm"keepMountedtransitionProps={{ duration: 0 }}diff --git a/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsx b/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsxindex a3c1106ab9..78088d3366 100644--- a/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderOriginBadge.tsx@@ -24,6 +24,7 @@ export function FolderOriginBadge({ folder }: { folder: FolderRecord }) {return (<FileOriginBadgeorigin={kind === "server" ? "cloud" : "local"}+ onDisk={kind === "local"}tooltip={tooltip}compact/>diff --git a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.css b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.cssindex cc1f118564..3de9c035e2 100644--- a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.css+++ b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.css@@ -1,7 +1,3 @@-/* Folder tree rows. They sit in the file sidebar's Folders section, so they take the- same row height, padding and muted icon treatment as .file-sidebar-action-row, and- the same hover pill rather than an accent bar. */-.files-page-tree-list {display: flex;flex-direction: column;@@ -12,9 +8,9 @@display: flex;align-items: center;height: 32px;- padding: 0 14px;+ padding: 0 8px;border-radius: 4px;- margin: 0 8px;+ margin: 0;cursor: pointer;user-select: none;color: var(--c-text-muted);@@ -46,40 +42,26 @@justify-content: center;width: 16px;height: 16px;+ margin-inline-start: 4px;color: var(--c-text-subtle);flex-shrink: 0;}-.files-page-tree-toggle svg {- font-size: 16px !important;-}--.files-page-tree-spacer {- display: inline-block;- width: 16px;- height: 16px;- flex-shrink: 0;-}-.files-page-tree-icon {display: inline-flex;align-items: center;justify-content: center;flex-shrink: 0;color: var(--c-text-subtle);- margin-left: 8px;- font-size: 18px;-}--.files-page-tree-icon svg {- font-size: 18px !important;+ width: 18px;+ height: 18px;}.files-page-tree-name {flex: 1;min-width: 0;display: flex;- white-space: nowrap;+ white-space: pre;overflow: hidden;text-overflow: ellipsis;margin-left: 12px;@@ -90,7 +72,6 @@.files-page-tree-name-head {overflow: hidden;text-overflow: ellipsis;- white-space: nowrap;}.files-page-tree-name-tail {diff --git a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.stories.tsx b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.stories.tsxindex e06bf42685..790fdfd59b 100644--- a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.stories.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.stories.tsx@@ -6,14 +6,7 @@ import { FolderProvider } from "@app/contexts/FolderContext";import { FilesPageProvider } from "@app/contexts/FilesPageContext";import { ROOT_FOLDER_ID } from "@app/types/folder";-/**- * FolderTreeSidebar reads the folder tree and active tab from FolderContext /- * FilesPageContext, neither of which is part of the shared preview- * decorators. Both providers also pull in IndexedDBContext (via- * FileContextProvider) further up the tree, so all three are stood up here.- * No folders are seeded into IndexedDB, so the tree renders with just the- * pinned "All files" / "Local" rows - an accurate empty state.- */+/** Folder and library providers need IndexedDB; no seeded folders leaves only the pinned views. */function withFolderContexts(Story: () => React.JSX.Element) {return (<FileContextProvider>diff --git a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsxindex 4858216ceb..02c67305e2 100644--- a/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx+++ b/frontend/editor/src/core/components/filesPage/FolderTreeSidebar.tsx@@ -1,4 +1,4 @@-import React, { useCallback, useMemo, useState } from "react";+import React, { useCallback, useState } from "react";import { useTranslation } from "react-i18next";import { Menu } from "@mantine/core";import { ActionIcon } from "@app/ui/ActionIcon";@@ -24,13 +24,7 @@ import { useDropTarget } from "@app/components/filesPage/useDropTarget";import "@app/components/filesPage/FolderTreeSidebar.css";import { useOpenFolder } from "@app/components/filesPage/useOpenFolder";-/**- * Hard cap on folder-tree render depth. The backend already enforces an- * application-level depth limit via cycle detection + folder-count cap,- * and React's render stack handles ~50 nested components comfortably,- * so this is purely defensive against a corrupted IDB cache producing- * a chain deeper than the server would allow.- */+/** Bound recursion to protect rendering from corrupted folder hierarchies. */const MAX_TREE_DEPTH = 50;interface FolderTreeSidebarProps {@@ -38,26 +32,14 @@ interface FolderTreeSidebarProps {onRequestNewFolder: (parentId: FolderId | null) => void;onRenameFolder: (folder: FolderRecord) => void;onDeleteFolder: (folder: FolderRecord) => void;- /**- * Move the *dragged* files (from the drop payload) into the target folder.- * Earlier signature took only the folder id and the parent then used the- * current selection - which silently moved the wrong files whenever the- * user dragged something that wasn't in the selection.- */+ /** Move the IDs from the drag payload, which can differ from the current selection. */onMoveFilesIntoFolder: (folderId: FolderId | null,fileIds: FileId[],) => Promise<void> | void;}-// A list, not a surface: the section around it owns the heading, and root-level-// folder mutations belong there too - they need a serverReachable gate that a bare-// list has no way to apply.-/**- * A name that gives way in the middle when the row is too narrow for it, keeping both- * ends readable - folder names tend to differ at the end, where a plain end-ellipsis- * would cut. The split is fixed; the CSS decides whether the head actually elides.- */+/** Preserve both ends because folder names often differ only at the end. */function MiddleTruncated({text,className,@@ -89,13 +71,8 @@ export function FolderTreeSidebar({const { t } = useTranslation();const { tree, currentFolderId } = useFolders();const openFolder = useOpenFolder();- const {- currentTab,- setCurrentTab,- moveFolderTo,- originFilter,- setOriginFilter,- } = useFilesPage();+ const { currentTab, setCurrentTab, moveFolderTo, setOriginFilter } =+ useFilesPage();return (<div@@ -103,6 +80,10 @@ export function FolderTreeSidebar({role="tree"aria-label={t("filesPage.tree", "Folders")}>+ <RecentRow+ isActive={currentTab === "recent"}+ onSelect={() => setCurrentTab("recent")}+ /><RootRowfileCount={fileCounts.get(ROOT_FOLDER_ID) ?? 0}isActive={@@ -110,39 +91,24 @@ export function FolderTreeSidebar({(currentTab === "all" || currentTab === "cloud")}onSelect={() => {- // Picking the root re-enters the cloud bucket - also switch out- // of any virtual tab so the user lands somewhere consistent.- if (currentTab !== "all" && currentTab !== "cloud") {- setCurrentTab("all");- }openFolder(ROOT_FOLDER_ID);+ setOriginFilter("all");}}onDropFiles={(fileIds) =>onMoveFilesIntoFolder(ROOT_FOLDER_ID, fileIds)}/>- <LocalRow- isActive={originFilter === "local"}- onSelect={() => setOriginFilter("local")}- />{tree.map((node) => (<TreeNodeRowkey={node.folder.id}node={node}fileCounts={fileCounts}currentFolderId={currentFolderId}- // Same dance as RootRow: clicking a cloud folder must drop the- // virtual-tab highlight (Local/Recent/Shared), otherwise the row- // AND the tab both look "active" simultaneously.onSelect={(id) => {- if (currentTab !== "all" && currentTab !== "cloud") {- setCurrentTab("all");- }openFolder(id);+ setOriginFilter("all");}}onMoveFolder={async (folderId, newParentId) => {- // Route through filesPage.moveFolderTo so the cycle case- // surfaces an error banner instead of silently no-op'ing.await moveFolderTo(folderId, newParentId);}}onMoveFiles={onMoveFilesIntoFolder}@@ -203,29 +169,23 @@ function RootRow({ fileCount, isActive, onSelect, onDropFiles }: RootRowProps) {}}{...handlers}>- <span className="files-page-tree-spacer" /><span className="files-page-tree-icon">- <Icon name="house" size={20} />+ <Icon name="house" size={18} /></span><span className="files-page-tree-name">- {t("filesPage.allFiles", "All files")}+ {t("filesPage.allFiles", "Stirling library")}</span><span className="files-page-tree-count">{fileCount}</span></div>);}-interface LocalRowProps {+interface RecentRowProps {isActive: boolean;onSelect: () => void;}-/**- * Sets the source filter to local, and nothing else: it narrows whatever view you- * are in rather than being a place of its own. Not a drop target and no count- * badge - a local file has no folder to be counted under.- */-function LocalRow({ isActive, onSelect }: LocalRowProps) {+function RecentRow({ isActive, onSelect }: RecentRowProps) {const { t } = useTranslation();return (<div@@ -241,12 +201,11 @@ function LocalRow({ isActive, onSelect }: LocalRowProps) {}}}>- <span className="files-page-tree-spacer" /><span className="files-page-tree-icon">- <Icon name="tablet-smartphone" size={20} />+ <Icon name="clock" size={18} /></span><span className="files-page-tree-name">- {t("filesPage.tabName.local", "Local")}+ {t("filesPage.recentFiles", "Recents")}</span></div>);@@ -283,9 +242,7 @@ function TreeNodeRow({}: TreeNodeRowProps) {const { t } = useTranslation();const { serverReachable, setError } = useFolders();- // Server folders need the server; a virtual folder is browser-owned and a- // local one is managed by its directory, so its edit items disable with a- // kind-specific hint instead of a wrong "offline" excuse.+const kind = folderKind(node.folder);const editsDisabled =kind === "local" || (kind === "server" && !serverReachable);@@ -296,17 +253,11 @@ function TreeNodeRow({);const [open, setOpen] = useState(true);- // Only highlight the folder row when we're actually in a cloud-rooted- // view. Otherwise (Local/Recent/Shared tabs) it'd compete with the tab- // highlight and confuse the user about "where they are".+ // Filter tabs own the active highlight even when a folder remains remembered.const isActive =currentFolderId === node.folder.id &&(currentTab === "all" || currentTab === "cloud");const hasChildren = node.children.length > 0;- const indent = useMemo(- () => ({ paddingLeft: `${14 + node.depth * 16}px` }),- [node.depth],- );const { handlers: dropHandlers, isOver: isDropTarget } = useDropTarget({dragType: FILES_PAGE_DRAG_TYPE,@@ -314,10 +265,6 @@ function TreeNodeRow({const payload = parseFilesPageDragPayload(e.dataTransfer);if (!payload) return;if (payload.kind === "files") {- // Use payload.fileIds - not the current selection - so dragging a- // non-selected file moves *that* file. Surface failures via the- // shared error banner rather than letting them become unhandled- // rejections that only the dev console sees.Promise.resolve(onMoveFiles(node.folder.id, payload.fileIds)).catch((err) => {console.error("[TreeNodeRow] file drop failed", err);@@ -376,7 +323,7 @@ function TreeNodeRow({aria-expanded={hasChildren ? open : undefined}tabIndex={0}draggable- style={indent}+ style={{ paddingInlineStart: 8 + node.depth * 16 }}className={`files-page-tree-node${isActive ? " is-active" : ""}${isDropTarget ? " is-drop-target" : ""}`}@@ -386,8 +333,6 @@ function TreeNodeRow({setOpen((o) => !o);}}onContextMenu={(e) => {- // Open the action menu on right-click rather than a native- // window.prompt (unstyled, untranslatable, unusable on mobile).e.preventDefault();setMenuOpen(true);}}@@ -404,7 +349,14 @@ function TreeNodeRow({{...dropHandlers}onDragStart={handleDragStart}>- {hasChildren ? (+ <span className="files-page-tree-icon">+ <FolderThumbnail color={node.folder.color} size="tree" />+ </span>+ <MiddleTruncated+ className="files-page-tree-name"+ text={node.folder.name}+ />+ {hasChildren && (<spanclassName="files-page-tree-toggle"aria-hidden="true"@@ -414,21 +366,12 @@ function TreeNodeRow({}}>{open ? (- <Icon name="chevron-down" size={20} />+ <Icon name="chevron-down" size={16} />) : (- <Icon name="chevron-right" size={20} />+ <Icon name="chevron-right" size={16} />)}</span>- ) : (- <span className="files-page-tree-spacer" />)}- <span className="files-page-tree-icon">- <FolderThumbnail color={node.folder.color} size="tree" />- </span>- <MiddleTruncated- className="files-page-tree-name"- text={node.folder.name}- /><span className="files-page-tree-count">{fileCounts.get(node.folder.id) ?? 0}</span>@@ -500,10 +443,7 @@ function TreeNodeRow({{t("filesPage.treeMenu.newSubfolder", "New subfolder")}</Menu.Item><Menu.Divider />- {/* Every kind can be removed except a mount's subdirectory, which- is the disk's — the app never deletes directories. A mount- root's removal deletes the record and nothing on disk, so only- the server kind's reachability gate applies. */}+ {/* Removing a mount detaches its record; filesystem directories are never deleted here. */}{(kind !== "local" || node.folder.parentFolderId === null) && (<Menu.Itemcolor="red"@@ -528,11 +468,6 @@ function TreeNodeRow({</Menu></div>{open &&- // Cap render recursion at MAX_TREE_DEPTH to guarantee a finite- // call stack even if a future bug (or a hand-edited IDB cache)- // produces a folder chain deeper than the server enforces. Any- // realistic user tree stays well under this; the cap exists so- // the renderer fails closed rather than blowing the JS stack.node.depth < MAX_TREE_DEPTH &&node.children.map((child) => (<TreeNodeRowdiff --git a/frontend/editor/src/core/components/filesPage/LibraryFilePicker.css b/frontend/editor/src/core/components/filesPage/LibraryFilePicker.cssnew file mode 100644index 0000000000..406b64da47--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryFilePicker.css@@ -0,0 +1,117 @@+.library-file-picker {+ height: min(84dvh, 900px);+}+.library-picker-header,+.library-picker-imports,+.library-picker-controls,+.library-picker-footer,+.library-picker-footer-actions,+.library-picker-selection,+.library-picker-crumb {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}+.library-picker-header,+.library-picker-footer {+ justify-content: space-between;+ padding: 1rem 1.25rem;+ flex-shrink: 0;+}+.library-picker-header h2 {+ margin: 0 0 0.25rem;+ font-size: 1.25rem;+}+.library-picker-imports {+ padding: 0 1.25rem 1rem;+ flex-wrap: wrap;+}+.library-picker-controls {+ padding: 0.75rem 1.25rem;+ justify-content: space-between;+ flex-wrap: wrap;+}+.library-picker-controls .files-page-toolbar-actions {+ flex-wrap: wrap;+}+.library-picker-crumb {+ min-width: 0;+}+.library-picker-dropzone {+ flex: 1;+ min-width: 0;+ min-height: 0;+ padding: 0;+ border: 0;+ border-radius: 0;+ background: var(--c-bg);+}+.library-picker-dropzone .files-page-content {+ height: 100%;+}+.library-file-picker .files-page-list-row {+ grid-template-columns:+ 2.25rem minmax(17rem, 3fr) minmax(7.5rem, 1fr) minmax(4.5rem, 1fr)+ minmax(9.5rem, 1.5fr) 2.5rem;+ min-width: 47.5rem;+}+.library-picker-footer {+ border-top: 1px solid var(--c-border-subtle);+ background: var(--c-surface);+}+.library-picker-selection {+ min-width: 0;+ flex-wrap: wrap;+}+.library-picker-empty {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 1rem;+ min-height: 200px;+ width: 100%;+ height: 100%;+ border: none;+ border-radius: var(--radius-md);+ background: var(--c-primary-subtle);+ color: var(--c-text);+ cursor: pointer;+ padding: 2rem;+}+.library-picker-empty:hover {+ background: var(--c-hover);+}+.library-picker-empty > svg {+ color: var(--c-accent-fg);+}+.library-picker-empty > span {+ color: var(--c-text-muted);+}+.library-file-picker [aria-disabled="true"] {+ opacity: 0.5;+}+.library-file-picker .files-page-details {+ width: 280px;+ flex: 0 0 280px;+}+@media (max-width: 640px) {+ .library-file-picker {+ height: 100dvh;+ }+ .library-picker-header,+ .library-picker-footer,+ .library-picker-controls {+ padding: 0.75rem;+ }+ .library-picker-imports {+ padding-inline: 0.75rem;+ gap: 0.25rem;+ }+ .library-picker-footer {+ flex-wrap: wrap;+ }+ .library-picker-footer-actions {+ margin-left: auto;+ }+}diff --git a/frontend/editor/src/core/components/filesPage/LibraryFilePicker.test.tsx b/frontend/editor/src/core/components/filesPage/LibraryFilePicker.test.tsxnew file mode 100644index 0000000000..9e69a2288d--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryFilePicker.test.tsx@@ -0,0 +1,1089 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { MantineProvider } from "@mantine/core";+import { QueryClientProvider } from "@tanstack/react-query";+import { createAppQueryClient } from "@app/query/queryClient";+import { LibraryFilePicker } from "@app/components/filesPage/LibraryFilePicker";+import type { StirlingFileStub } from "@app/types/fileContext";+import type { FolderRecord } from "@app/types/folder";+import type { DiskFileEntry } from "@app/services/localFolderContents";+import type { ProcessingFolderState } from "@app/hooks/useProcessingFolders";+import { allowConsole } from "@app/tests/failOnConsole";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (+ key: string,+ fallback?: string | Record<string, unknown>,+ values?: Record<string, unknown>,+ ) => {+ const options = typeof fallback === "object" ? fallback : values;+ const text =+ typeof fallback === "string"+ ? fallback+ : String(options?.defaultValue ?? key);+ return text.replace(/\{\{(\w+)\}\}/g, (_, name: string) =>+ String(options?.[name] ?? ""),+ );+ },+ }),+}));++const state = vi.hoisted(() => ({+ files: [] as StirlingFileStub[],+ folders: [] as FolderRecord[],+ diskFiles: [] as DiskFileEntry[],+ selected: vi.fn().mockResolvedValue(undefined),+ close: vi.fn(),+ alert: vi.fn(),+ moveFolder: vi.fn(),+ createFolder: vi.fn(),+ listDirectory: vi.fn(),+ readDiskFile: vi.fn(),+ extractAllFiles: vi.fn(),+ registerDiskSubfolders: vi.fn(),+ maxSelectable: null as number | null,+ viewMode: "list" as "list" | "grid",+ storageEnabled: false,+ driveError: null as string | null,+ clearDriveError: vi.fn(),+ processingRecord: undefined as ProcessingFolderState | undefined,+ listProcessingFiles: vi.fn(),+}));++vi.mock("@app/contexts/FilesPageContext", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/contexts/FilesPageContext")>()),+ useFilesPage: () => ({+ allFiles: state.files,+ fileMap: new Map(state.files.map((file) => [file.id, file])),+ fileCountsByFolder: new Map(),+ loading: false,+ diskRevision: 0,+ viewMode: state.viewMode,+ setViewMode: vi.fn(),+ }),+}));+vi.mock("@app/contexts/FolderContext", () => ({+ useFolders: () => ({+ folders: state.folders,+ foldersById: new Map(state.folders.map((folder) => [folder.id, folder])),+ currentFolderId: "behind-the-modal",+ setCurrentFolderId: state.moveFolder,+ registerDiskSubfolders: state.registerDiskSubfolders,+ createFolder: state.createFolder,+ }),+}));+vi.mock("@app/contexts/FilesModalContext", () => ({+ useFilesModalContext: () => ({+ closeFilesModal: state.close,+ onRecentFileSelect: state.selected,+ maxSelectable: state.maxSelectable,+ loadFiles: vi.fn(),+ }),+}));+vi.mock("@app/contexts/FileContext", () => ({+ useAllFiles: () => ({ fileIds: [] }),+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: { storageEnabled: state.storageEnabled } }),+}));+vi.mock("@app/hooks/useSharingEnabled", () => ({+ useSharingEnabled: () => ({ sharingEnabled: false }),+}));+vi.mock("@app/hooks/useGoogleDrivePicker", () => ({+ useGoogleDrivePicker: () => ({+ isEnabled: false,+ error: state.driveError,+ clearError: state.clearDriveError,+ }),+}));+vi.mock("@app/hooks/useIsMobile", () => ({ useIsMobile: () => false }));+vi.mock("@app/hooks/usePolicyFileBadges", () => ({+ usePolicyFileBadges: () => new Map(),+}));+vi.mock("@app/hooks/useProcessingFolders", () => ({+ useProcessingFolders: () => ({+ stateFor: () => state.processingRecord,+ listFiles: state.listProcessingFiles,+ }),+}));+vi.mock("@app/hooks/useServerProcessingBlock", () => ({+ useServerProcessingBlock: () => null,+}));+vi.mock("@app/hooks/useLazyThumbnail", () => ({+ useLazyThumbnail: () => undefined,+ useDiskThumbnail: () => undefined,+}));+vi.mock("@app/components/shared/MobileUploadModal", () => ({+ default: () => null,+}));+vi.mock("@app/components/toast", () => ({ alert: state.alert }));+vi.mock("@app/services/localFolderContents", () => ({+ canListDirectory: true,+ listDirectory: state.listDirectory,+ readDiskFile: state.readDiskFile,+}));+vi.mock("@app/services/zipFileService", () => ({+ zipFileService: { extractAllFiles: state.extractAllFiles },+}));+vi.mock("@app/services/fileStorage", () => ({+ fileStorage: { getHistoryChainStubs: vi.fn().mockResolvedValue([]) },+}));++const file = (id: string, name: string, folderId: string | null = null) =>+ ({+ id,+ name,+ folderId,+ type: "application/pdf",+ size: 100,+ lastModified: 1,+ originalFileId: id,+ isLeaf: true,+ versionNumber: 1,+ }) as StirlingFileStub;+const folder = (id: string, name: string, extra = {}) =>+ ({+ id,+ name,+ kind: "virtual",+ parentFolderId: null,+ color: "blue",+ createdAt: 0,+ updatedAt: 0,+ ...extra,+ }) as FolderRecord;+const show = (+ supportedFormats?: string[],+ destination?: Parameters<typeof LibraryFilePicker>[0]["destination"],+) => {+ const client = createAppQueryClient();+ return render(+ <MantineProvider env="test">+ <LibraryFilePicker+ supportedFormats={supportedFormats}+ destination={destination}+ onBusyChange={vi.fn()}+ onExternalPickerChange={vi.fn()}+ />+ </MantineProvider>,+ {+ wrapper: ({ children }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ ),+ },+ );+};++beforeEach(() => {+ vi.clearAllMocks();+ HTMLElement.prototype.scrollIntoView = vi.fn();+ state.files = [file("one", "One.pdf"), file("two", "Two.pdf")];+ state.folders = [];+ state.diskFiles = [];+ state.maxSelectable = null;+ state.viewMode = "list";+ state.storageEnabled = false;+ state.driveError = null;+ state.processingRecord = undefined;+ state.listProcessingFiles.mockResolvedValue([]);+ state.clearDriveError.mockImplementation(() => {+ state.driveError = null;+ });+ state.listDirectory.mockImplementation(async () => ({+ files: state.diskFiles,+ directories: [],+ }));+ state.readDiskFile.mockImplementation(+ async (entry: DiskFileEntry) => new File(["PDF"], entry.name),+ );+});++describe("library file picker", () => {+ it.each(["list", "grid"] as const)(+ "keeps queued files out of selection in %s view while completed files remain available",+ async (viewMode) => {+ state.viewMode = viewMode;+ state.folders = [folder("processing", "Processing", { kind: "server" })];+ const queued = {+ ...file("queued", "Queued.pdf", "processing"),+ remoteStorageId: 1,+ };+ const done = {+ ...file("done", "Done.pdf", "processing"),+ remoteStorageId: 2,+ };+ state.files = [queued, done];+ state.processingRecord = { id: "processing-record", enabled: true };+ state.listProcessingFiles.mockResolvedValue([+ { name: queued.name, state: "waiting" },+ { name: done.name, state: "done" },+ ]);+ const user = userEvent.setup();+ show();+ await user.click(+ screen.getByRole("button", { name: "Stirling library" }),+ );+ await user.click(screen.getByText("Processing"));+ await waitFor(() => expect(state.listProcessingFiles).toHaveBeenCalled());+ const queuedItem = screen+ .getByText(queued.name)+ .closest('[role="row"], [role="listitem"]')!;+ await waitFor(() =>+ expect(queuedItem).toHaveAttribute("aria-disabled", "true"),+ );+ await user.dblClick(screen.getByText(queued.name));+ expect(state.selected).not.toHaveBeenCalled();+ await user.click(screen.getByText(done.name));+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([done], []);+ },+ );++ it.each(["list", "grid"] as const)(+ "sorts Recents by date added and displays that date in %s view",+ async (viewMode) => {+ state.viewMode = viewMode;+ const newlyAdded = {+ ...file("new", "New.pdf"),+ createdAt: Date.parse("2026-09-22T10:00:00Z"),+ lastModified: Date.parse("2000-01-01T10:00:00Z"),+ remoteStorageId: 1,+ };+ const olderUpload = {+ ...file("old", "Old.pdf"),+ createdAt: Date.parse("2026-09-01T10:00:00Z"),+ lastModified: Date.parse("2026-09-20T10:00:00Z"),+ remoteStorageId: 2,+ };+ state.files = [olderUpload, newlyAdded];+ const user = userEvent.setup();+ show();++ const fileOrder = () =>+ screen.getAllByText(/^(New|Old)\.pdf$/).map((node) => node.textContent);+ expect(fileOrder()).toEqual(["New.pdf", "Old.pdf"]);+ expect(+ screen.getByText(new Date(newlyAdded.createdAt).toLocaleString()),+ ).toBeVisible();+ expect(+ screen.queryByText(new Date(newlyAdded.lastModified).toLocaleString()),+ ).not.toBeInTheDocument();+ if (viewMode === "list")+ expect(+ screen.getByRole("columnheader", { name: /Added/ }),+ ).toBeVisible();++ await user.click(+ screen.getByRole("button", { name: "Sort files: Recent first" }),+ );+ await user.click(screen.getByRole("menuitem", { name: "Oldest first" }));+ expect(fileOrder()).toEqual(["Old.pdf", "New.pdf"]);++ await user.click(+ screen.getByRole("button", { name: "Stirling library" }),+ );+ expect(fileOrder()).toEqual(["Old.pdf", "New.pdf"]);+ expect(+ screen.getByText(new Date(newlyAdded.lastModified).toLocaleString()),+ ).toBeVisible();+ if (viewMode === "list")+ expect(+ screen.getByRole("columnheader", { name: /Modified/ }),+ ).toBeVisible();+ },+ );++ it("browses server destinations without selecting files or changing the page behind it", async () => {+ const invoices = folder("invoices", "Invoices", { kind: "server" });+ state.folders = [+ invoices,+ folder("browser", "Browser folder"),+ folder("disk", "Disk folder", { kind: "local" }),+ ];+ state.files = [{ ...file("cloud", "Existing.zip"), remoteStorageId: 1 }];+ const onConfirm = vi.fn();+ const user = userEvent.setup();+ show(undefined, { fileCount: 2, onClose: vi.fn(), onConfirm });++ expect(+ screen.queryByRole("button", { name: "Recents" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("Browser folder")).not.toBeInTheDocument();+ expect(screen.queryByText("Disk folder")).not.toBeInTheDocument();+ expect(screen.getByText("Existing.zip")).toBeVisible();+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Unzip" }),+ ).not.toBeInTheDocument();+ await user.dblClick(screen.getByText("Existing.zip"));+ expect(state.selected).not.toHaveBeenCalled();+ await user.click(screen.getByText("Invoices"));+ await user.click(screen.getByRole("button", { name: "Add here" }));+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(invoices.id);+ expect(state.moveFolder).not.toHaveBeenCalled();+ });++ it("accepts an empty server library root as the destination", async () => {+ state.files = [];+ const onConfirm = vi.fn();+ show(undefined, { fileCount: 1, onClose: vi.fn(), onConfirm });+ await userEvent.click(screen.getByRole("button", { name: "Add here" }));+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(null);+ });++ it("creates a server folder and selects it without navigating the library page", async () => {+ const created = folder("new", "New destination", { kind: "server" });+ state.createFolder.mockImplementation(async () => {+ state.folders = [created];+ return created;+ });+ const onConfirm = vi.fn();+ const user = userEvent.setup();+ show(undefined, { fileCount: 1, onClose: vi.fn(), onConfirm });+ await user.click(screen.getByRole("button", { name: "New folder" }));+ await user.type(+ screen.getByRole("textbox", { name: "Folder name" }),+ created.name,+ );+ await user.click(screen.getByRole("button", { name: "Create" }));+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );+ await user.click(screen.getByRole("button", { name: "Add here" }));+ expect(state.createFolder).toHaveBeenCalledWith(+ created.name,+ null,+ "server",+ );+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(created.id);+ expect(state.moveFolder).not.toHaveBeenCalled();+ });++ it("dismisses a Drive error without losing selected files", async () => {+ state.driveError = "Drive access denied";+ const user = userEvent.setup();+ const view = show();+ await user.click(screen.getByText("One.pdf"));+ const alert = screen.getByRole("alert");+ expect(alert).toHaveTextContent("Drive access denied");+ await user.click(within(alert).getByRole("button"));+ expect(state.clearDriveError).toHaveBeenCalledOnce();+ view.rerender(+ <MantineProvider env="test">+ <LibraryFilePicker+ onBusyChange={vi.fn()}+ onExternalPickerChange={vi.fn()}+ />+ </MantineProvider>,+ );+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith(+ [state.files[0]],+ [],+ );+ });++ it("shows the selected file's folder when browsing Recents", async () => {+ state.folders = [folder("invoices", "Invoices")];+ state.files = [file("filed", "Filed.pdf", "invoices")];+ const user = userEvent.setup();+ show();++ await user.click(screen.getByText("Filed.pdf"));+ await user.click(screen.getByRole("button", { name: "Details" }));+ const details = within(+ screen.getByRole("complementary", { name: "Details" }),+ );+ await user.click(details.getByRole("button", { name: "File info" }));++ expect(details.getByText("Invoices")).toBeVisible();+ });++ it.each(["list", "grid"] as const)(+ "keeps the %s selection when switching between the library and Recents",+ async (viewMode) => {+ state.viewMode = viewMode;+ const local = state.files[0];+ const server = { ...file("server", "Server.pdf"), remoteStorageId: 1 };+ state.files = [local, server];+ const user = userEvent.setup();+ show();+ await user.click(screen.getByText("One.pdf"));+ await user.click(+ screen.getByRole("button", {+ name: "Stirling library",+ pressed: false,+ }),+ );+ if (viewMode === "list") {+ await user.click(screen.getByRole("checkbox", { name: "Select all" }));+ } else {+ await user.click(screen.getByText("Server.pdf"));+ }+ const listing = screen.getByRole(viewMode === "list" ? "grid" : "list");+ expect(within(listing).queryByText("Recents")).not.toBeInTheDocument();+ await user.click(+ screen.getByRole("button", { name: "Recents", pressed: false }),+ );+ expect(screen.getByText("One.pdf")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Add 2 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith(+ [local, server],+ [],+ );+ },+ );++ it("keeps loose local files in Recent while root shows folders and server files", async () => {+ state.folders = [folder("folder", "Invoices")];+ const local = state.files[0];+ const organised = file("organised", "Filed.pdf", "folder");+ const orphan = file("orphan", "Unfiled.pdf", "missing-folder");+ const server = { ...file("server", "Server.pdf"), remoteStorageId: 1 };+ state.files = [local, organised, orphan, server];+ const user = userEvent.setup();+ show();+ expect(screen.getByText("One.pdf")).toBeInTheDocument();+ expect(screen.getByText("Unfiled.pdf")).toBeInTheDocument();+ await user.click(screen.getByText("One.pdf"));+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: false }),+ );+ expect(screen.queryByText("One.pdf")).not.toBeInTheDocument();+ expect(screen.queryByText("Unfiled.pdf")).not.toBeInTheDocument();+ expect(screen.getByText("Server.pdf")).toBeInTheDocument();+ await user.click(screen.getByText("Invoices"));+ expect(screen.getByText("Filed.pdf")).toBeInTheDocument();+ await user.click(+ screen.getByRole("button", { name: "Recents", pressed: false }),+ );+ expect(screen.getByText("One.pdf")).toBeInTheDocument();+ expect(screen.getByText("Unfiled.pdf")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([local], []);+ });++ it("closes immediately for a batch and reports import failures after unmounting", async () => {+ let rejectImport!: (error: Error) => void;+ state.selected.mockReturnValueOnce(+ new Promise<void>((_, reject) => {+ rejectImport = reject;+ }),+ );+ const user = userEvent.setup();+ const view = show();+ const uploads = Array.from(+ { length: 40 },+ (_, i) => new File(["PDF"], `Upload${i}.pdf`),+ );+ fireEvent.change(view.container.querySelector('input[type="file"]')!, {+ target: { files: uploads },+ });+ await user.click(screen.getByRole("button", { name: "Add 40 files" }));+ expect(state.close).toHaveBeenCalledTimes(1);+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], uploads);+ view.unmount();+ await act(async () => rejectImport(new Error("Storage is full.")));+ expect(state.alert).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ alertType: "error",+ body: "Storage is full.",+ }),+ );+ expect(state.close).toHaveBeenCalledTimes(1);+ });++ it("filters staged imports out of Cloud without losing their selection", async () => {+ const serverFile = { ...file("server", "Server.pdf"), remoteStorageId: 1 };+ state.files.push(serverFile);+ const user = userEvent.setup();+ const view = show();+ const uploads = [+ new File(["PDF"], "New.pdf"),+ new File(["PDF"], "Other.pdf"),+ ];+ fireEvent.change(view.container.querySelector('input[type="file"]')!, {+ target: { files: uploads },+ });+ await user.click(screen.getByRole("textbox", { name: "Filter by source" }));+ await user.click(await screen.findByRole("option", { name: "Cloud" }));+ expect(screen.getByText("Server.pdf")).toBeInTheDocument();+ expect(screen.queryByText("One.pdf")).not.toBeInTheDocument();+ expect(screen.queryByText("New.pdf")).not.toBeInTheDocument();+ expect(screen.queryByText("Other.pdf")).not.toBeInTheDocument();+ await user.click(screen.getByText("Server.pdf"));+ await user.click(screen.getByRole("button", { name: "Add 3 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledExactlyOnceWith(+ [serverFile],+ uploads,+ ),+ );+ });++ it("keeps server files reachable with the source filter while browsing folders", async () => {+ state.storageEnabled = true;+ state.folders = [+ folder("browser", "Browser folder"),+ folder("server-folder", "Server folder", { kind: "server" }),+ ];+ state.files = [+ { ...file("root", "Root.pdf"), remoteStorageId: 1 },+ {+ ...file("missing", "Missing folder.pdf", "missing-folder"),+ remoteStorageId: 2,+ },+ {+ ...file("browser-file", "Browser folder copy.pdf", "browser"),+ remoteStorageId: 3,+ },+ { ...file("nested", "Nested.pdf", "server-folder"), remoteStorageId: 4 },+ ];+ const user = userEvent.setup();+ const view = show();+ expect(+ screen.queryByRole("button", { name: "Cloud" }),+ ).not.toBeInTheDocument();+ fireEvent.change(view.container.querySelector('input[type="file"]')!, {+ target: { files: [new File(["PDF"], "New.pdf")] },+ });+ await user.click(+ screen.getAllByRole("button", { name: "Stirling library" })[0],+ );+ await user.click(screen.getByRole("textbox", { name: "Filter by source" }));+ await user.click(await screen.findByRole("option", { name: "Cloud" }));+ expect(screen.getByText("Root.pdf")).toBeInTheDocument();+ expect(screen.getByText("Missing folder.pdf")).toBeInTheDocument();+ expect(screen.getByText("Browser folder copy.pdf")).toBeInTheDocument();+ expect(screen.queryByText("New.pdf")).not.toBeInTheDocument();+ expect(screen.queryByText("Nested.pdf")).not.toBeInTheDocument();+ await user.click(screen.getByText("Server folder"));+ expect(screen.getByText("Nested.pdf")).toBeInTheDocument();+ expect(screen.queryByText("New.pdf")).not.toBeInTheDocument();+ expect(+ screen.getByRole("textbox", { name: "Filter by source" }),+ ).toHaveValue("Cloud");+ });++ it("shows a readable error when a dropped file cannot be read", async () => {+ const view = show();+ fireEvent.drop(view.container.querySelector(".library-picker-dropzone")!, {+ dataTransfer: {+ items: [{ kind: "file", getAsFile: () => null }],+ types: ["Files"],+ },+ });+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Could not read a dropped file.",+ );+ expect(state.selected).not.toHaveBeenCalled();+ });++ it("stages readable files from a partial drop and names the failure", async () => {+ const user = userEvent.setup();+ const view = show();+ const file = new File(["PDF"], "Dropped.pdf");+ fireEvent.drop(view.container.querySelector(".library-picker-dropzone")!, {+ dataTransfer: {+ items: [+ { kind: "file", getAsFile: () => null },+ { kind: "file", getAsFile: () => file },+ ],+ types: ["Files"],+ },+ });+ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Could not read a dropped file.",+ );+ expect(await screen.findByText("Dropped.pdf")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], [file]);+ });++ it("keeps stored selections and readable disk files when another disk file disappears", async () => {+ allowConsole.error(/Could not read selected disk file/);+ state.folders = [+ folder("mount", "Documents", {+ kind: "local",+ directory: "C:/Documents",+ }),+ ];+ state.diskFiles = ["Missing.pdf", "Readable.pdf"].map((name) => ({+ path: `C:/Documents/${name}`,+ name,+ sizeBytes: 100,+ lastModified: 1,+ }));+ const readable = new File(["PDF"], "Readable.pdf");+ state.readDiskFile.mockImplementation(async (entry: DiskFileEntry) =>+ entry.name === "Missing.pdf" ? null : readable,+ );+ const user = userEvent.setup();+ show();+ await user.click(screen.getByText("One.pdf"));+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: false }),+ );+ await user.click(screen.getByText("Documents"));+ await user.click(await screen.findByText("Missing.pdf"));+ await user.click(screen.getByText("Readable.pdf"));+ await user.click(screen.getByRole("button", { name: "Add 3 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledExactlyOnceWith(+ [state.files[0]],+ [readable],+ ),+ );+ expect(state.close).toHaveBeenCalledOnce();+ expect(state.alert).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ body: "Missing.pdf is no longer available." }),+ );+ });++ it("stages dropped files when the browser denies file-system handle access", async () => {+ vi.stubGlobal("isSecureContext", true);+ try {+ const user = userEvent.setup();+ const view = show();+ const dropped = new File(["PDF"], "Dropped.pdf", {+ type: "application/pdf",+ });+ const getFile = vi+ .fn()+ .mockRejectedValue(+ new DOMException("File-system access denied", "NotAllowedError"),+ );+ const getAsFileSystemHandle = vi.fn().mockResolvedValue({ getFile });+ const dataTransfer = {+ files: [dropped],+ items: [+ {+ kind: "file",+ type: dropped.type,+ getAsFile: () => dropped,+ getAsFileSystemHandle,+ },+ ],+ types: ["Files"],+ };+ fireEvent.drop(+ view.container.querySelector(".library-picker-dropzone")!,+ {+ dataTransfer,+ },+ );+ expect(await screen.findByText("Dropped.pdf")).toBeInTheDocument();+ expect(getAsFileSystemHandle).not.toHaveBeenCalled();+ expect(state.selected).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], [dropped]),+ );+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("extracts ZIP contents into a tentative selection before importing", async () => {+ const extracted = new File(["PDF"], "Extracted.pdf", {+ type: "application/pdf",+ });+ state.extractAllFiles.mockResolvedValue({+ success: true,+ extractedFiles: [extracted],+ errors: [],+ });+ const user = userEvent.setup();+ const view = show(["pdf"]);+ const archive = new File(["zip"], "Archive.zip", {+ type: "application/zip",+ });+ fireEvent.change(view.container.querySelector('input[type="file"]')!, {+ target: { files: [archive] },+ });+ await user.click(screen.getByRole("button", { name: "Unzip" }));+ expect(await screen.findByText("Extracted.pdf")).toBeInTheDocument();+ expect(state.selected).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], [extracted]),+ );+ });+ it("restores each tab's folder and filters while keeping the cross-folder selection", async () => {+ state.folders = [folder("folder", "Invoices")];+ state.files[1] = file("two", "Two.pdf", "folder");+ const user = userEvent.setup();+ show();+ await user.click(screen.getByRole("button", { name: "Search filenames" }));+ await user.type(+ screen.getByRole("textbox", { name: "Search filenames" }),+ "One",+ );+ await user.click(screen.getByRole("textbox", { name: "Filter by source" }));+ await user.click(await screen.findByRole("option", { name: "Local" }));+ await user.click(screen.getByText("One.pdf"));+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: false }),+ );+ await user.click(screen.getByText("Invoices"));+ await user.click(screen.getByRole("button", { name: "Search filenames" }));+ await user.type(+ screen.getByRole("textbox", { name: "Search filenames" }),+ "Two",+ );+ await user.click(+ screen.getByRole("button", { name: "Recents", pressed: false }),+ );+ await user.click(screen.getByRole("button", { name: "Search filenames" }));+ expect(+ screen.getByRole("textbox", { name: "Search filenames" }),+ ).toHaveValue("One");+ expect(+ screen.getByRole("textbox", { name: "Filter by source" }),+ ).toHaveValue("Local");+ expect(screen.getByText("One.pdf")).toBeInTheDocument();+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: false }),+ );+ await user.click(screen.getByRole("button", { name: "Search filenames" }));+ expect(+ screen.getByRole("textbox", { name: "Search filenames" }),+ ).toHaveValue("Two");+ expect(+ screen.getByRole("textbox", { name: "Filter by source" }),+ ).toHaveValue("All sources");+ expect(+ screen.getByRole("button", { name: "Invoices" }),+ ).toBeInTheDocument();+ await user.click(screen.getByText("Two.pdf"));+ await user.click(screen.getByRole("button", { name: "Add 2 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledWith(state.files, []),+ );+ expect(state.moveFolder).not.toHaveBeenCalled();+ expect(screen.queryByLabelText("File actions")).not.toBeInTheDocument();+ });++ it("keeps the header partially selected when the selection limit leaves eligible files unselected", async () => {+ state.maxSelectable = 2;+ state.files = Array.from({ length: 10 }, (_, i) =>+ file(`file-${i}`, `File ${i}.pdf`),+ );+ const user = userEvent.setup();+ show(["pdf"]);++ await user.click(screen.getByText("File 0.pdf"));+ await user.click(screen.getByText("File 1.pdf"));++ const header = screen.getByRole("checkbox", { name: "Select all" });+ expect(header).toBePartiallyChecked();+ expect(header).not.toBeChecked();+ expect(screen.getByRole("button", { name: "Add 2 files" })).toBeEnabled();+ await user.click(header);+ expect(header).toBePartiallyChecked();+ await user.click(screen.getByRole("button", { name: "Add 2 files" }));+ expect(state.selected).toHaveBeenCalledWith(state.files.slice(0, 2), []);+ });++ it("counts only format-eligible files for a fully selected header", async () => {+ state.files.push(file("text", "Notes.txt"));+ const user = userEvent.setup();+ show(["pdf"]);+ await user.click(screen.getByRole("checkbox", { name: "Select all" }));+ expect(+ screen.getByRole("checkbox", { name: "Clear selection" }),+ ).toBeChecked();+ expect(screen.getByRole("button", { name: "Add 2 files" })).toBeEnabled();+ });++ it("enforces type restrictions and the selection limit when selecting all", async () => {+ state.maxSelectable = 1;+ state.files.push(file("text", "Notes.txt"));+ const user = userEvent.setup();+ show(["pdf"]);+ expect(+ screen.getByText("Notes.txt").closest('[role="row"]'),+ ).toHaveAttribute("aria-disabled", "true");+ await user.click(screen.getByLabelText("Select all"));+ await user.click(screen.getByText("Two.pdf"));+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledWith([state.files[1]], []),+ );+ });++ it("stages imports until confirmation and discards them on cancellation", async () => {+ const user = userEvent.setup();+ const view = show();+ const upload = new File(["PDF"], "New.pdf", { type: "application/pdf" });+ fireEvent.change(view.container.querySelector('input[type="file"]')!, {+ target: { files: [upload] },+ });+ expect(screen.getByText("New.pdf")).toBeInTheDocument();+ expect(state.selected).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Cancel" }));+ expect(state.close).toHaveBeenCalled();+ expect(state.selected).not.toHaveBeenCalled();+ view.unmount();+ show();+ expect(screen.queryByText("New.pdf")).not.toBeInTheDocument();+ });++ it("submits a mixture of imports and library files once", async () => {+ const user = userEvent.setup();+ const view = show();+ const upload = new File(["PDF"], "New.pdf", { type: "application/pdf" });+ await user.click(screen.getByText("One.pdf"));+ fireEvent.change(view.container.querySelector('input[type="file"]')!, {+ target: { files: [upload] },+ });+ await user.click(screen.getByRole("button", { name: "Add 2 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledExactlyOnceWith(+ [state.files[0]],+ [upload],+ ),+ );+ });++ it("stages each file once across duplicate entries and repeated imports", async () => {+ const user = userEvent.setup();+ const view = show();+ const upload = new File(["PDF"], "Duplicate.pdf", { lastModified: 123 });+ const duplicate = new File(["PDF"], "Duplicate.pdf", { lastModified: 123 });+ const input = view.container.querySelector('input[type="file"]')!;+ fireEvent.change(input, { target: { files: [upload, duplicate] } });+ const { pendingFilePathMappings } =+ await import("@app/services/pendingFilePathMappings");+ pendingFilePathMappings.set(duplicate, "C:/Documents/Duplicate.pdf");+ fireEvent.change(input, { target: { files: [duplicate] } });++ expect(pendingFilePathMappings.has(duplicate)).toBe(false);+ expect(screen.getAllByText("Duplicate.pdf")).toHaveLength(1);+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], [upload]);+ });++ it("preserves a pending native path when staged files reach the editor", async () => {+ const user = userEvent.setup();+ const view = show();+ const upload = new File(["PDF"], "Native.pdf");+ const { pendingFilePathMappings } =+ await import("@app/services/pendingFilePathMappings");+ const path = Promise.resolve("C:/Documents/Native.pdf");+ pendingFilePathMappings.set(upload, path);+ const input = view.container.querySelector('input[type="file"]')!;+ fireEvent.change(input, { target: { files: [upload] } });+ fireEvent.change(input, { target: { files: [upload] } });++ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], [upload]);+ expect(pendingFilePathMappings.get(upload)).toBe(path);+ });++ it("clears native selections from multiple folders in the selected-only view", async () => {+ state.folders = ["A", "B"].map((name) =>+ folder(name, name, { kind: "local", directory: `C:/${name}` }),+ );+ state.listDirectory.mockImplementation(async (directory: string) => ({+ files: [+ {+ path: `${directory}/File.pdf`,+ name: `${directory.slice(-1)}.pdf`,+ sizeBytes: 100,+ lastModified: 1,+ },+ ],+ directories: [],+ }));+ const user = userEvent.setup();+ show();+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: false }),+ );+ await user.click(screen.getByText("A", { exact: true }));+ await user.click(await screen.findByText("A.pdf"));+ expect(+ screen.getAllByRole("button", { name: "Stirling library" }),+ ).toHaveLength(1);+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: true }),+ );+ await user.click(screen.getByText("B", { exact: true }));+ await user.click(await screen.findByText("B.pdf"));+ await user.click(screen.getByRole("button", { name: "2 selected" }));+ await user.click(screen.getByRole("checkbox", { name: "Clear selection" }));+ expect(screen.getByRole("button", { name: "Add 0 files" })).toBeDisabled();+ });++ it("closes before native reads finish and imports them after unmounting with their disk paths", async () => {+ state.folders = [+ folder("mount", "Documents", {+ kind: "local",+ directory: "C:/Documents",+ }),+ ];+ state.diskFiles = [+ {+ path: "C:/Documents/Disk.pdf",+ name: "Disk.pdf",+ sizeBytes: 100,+ lastModified: 1,+ },+ ];+ let finishRead!: (file: File) => void;+ state.readDiskFile.mockReturnValueOnce(+ new Promise<File>((resolve) => {+ finishRead = resolve;+ }),+ );+ const user = userEvent.setup();+ const view = show();+ await user.click(+ screen.getByRole("button", { name: "Stirling library", pressed: false }),+ );+ await user.click(screen.getByText("Documents"));+ await user.click(await screen.findByText("Disk.pdf"));+ expect(state.readDiskFile).not.toHaveBeenCalled();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.close).toHaveBeenCalledTimes(1);+ expect(state.selected).not.toHaveBeenCalled();+ view.unmount();+ const diskFile = new File(["PDF"], "Disk.pdf");+ await act(async () => finishRead(diskFile));+ await waitFor(() => expect(state.selected).toHaveBeenCalled());+ expect(state.selected).toHaveBeenCalledExactlyOnceWith([], [diskFile]);+ expect(state.readDiskFile).toHaveBeenCalledWith(state.diskFiles[0]);+ const { pendingFilePathMappings } =+ await import("@app/services/pendingFilePathMappings");+ const imported = state.selected.mock.calls[0][1][0];+ expect(pendingFilePathMappings.get(imported)).toBe("C:/Documents/Disk.pdf");+ });++ it("keeps more than 50 files accessible in Recent and filters older files", async () => {+ state.files = Array.from({ length: 60 }, (_, i) => ({+ ...file(`f${i}`, `File${i}.pdf`),+ lastModified: 60 - i,+ }));+ const user = userEvent.setup();+ show();+ expect(screen.getByText("File59.pdf")).toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Search filenames" }));+ await user.type(+ screen.getByRole("textbox", { name: "Search filenames" }),+ "File59",+ );+ expect(await screen.findByText("File59.pdf")).toBeInTheDocument();+ expect(screen.queryByText("File0.pdf")).not.toBeInTheDocument();+ });++ it("keeps dropdown search focused through no matches and preserves its query and selection", async () => {+ const user = userEvent.setup();+ show();+ await user.click(screen.getByText("One.pdf"));+ const trigger = screen.getByRole("button", { name: "Search filenames" });+ expect(+ screen.queryByRole("textbox", { name: "Search filenames" }),+ ).not.toBeInTheDocument();+ await user.click(trigger);+ const search = screen.getByRole("textbox", {+ name: "Search filenames",+ });+ await waitFor(() => expect(search).toHaveFocus());+ await user.type(search, "missing file");+ expect(search).toHaveFocus();+ expect(search).toHaveValue("missing file");+ expect(screen.queryByText("One.pdf")).not.toBeInTheDocument();+ await user.clear(search);+ expect(search).toHaveFocus();+ expect(screen.getByText("One.pdf")).toBeInTheDocument();+ await user.type(search, "Two");+ const onPageKeyDown = vi.fn();+ window.addEventListener("keydown", onPageKeyDown);+ try {+ await user.keyboard("{Escape}");+ expect(onPageKeyDown).not.toHaveBeenCalled();+ } finally {+ window.removeEventListener("keydown", onPageKeyDown);+ }+ await waitFor(() => expect(trigger).toHaveFocus());+ expect(+ screen.queryByRole("textbox", { name: "Search filenames" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("One.pdf")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Name" }));+ await user.click(trigger);+ expect(+ screen.getByRole("textbox", { name: "Search filenames" }),+ ).toHaveValue("Two");+ await user.click(screen.getByRole("button", { name: "Clear search" }));+ expect(+ screen.getByRole("textbox", { name: "Search filenames" }),+ ).toHaveFocus();+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ expect(state.selected).toHaveBeenCalledExactlyOnceWith(+ [state.files[0]],+ [],+ );+ });++ it("keeps the search when switching layouts and sorts through the compact menu", async () => {+ const user = userEvent.setup();+ const view = show();+ await user.click(screen.getByRole("button", { name: "Search filenames" }));+ await user.type(+ screen.getByRole("textbox", { name: "Search filenames" }),+ "One",+ );+ state.viewMode = "grid";+ view.rerender(+ <MantineProvider env="test">+ <LibraryFilePicker+ onBusyChange={vi.fn()}+ onExternalPickerChange={vi.fn()}+ />+ </MantineProvider>,+ );+ expect(+ screen.getByRole("textbox", { name: "Search filenames" }),+ ).toHaveValue("One");+ expect(screen.queryByText("Two.pdf")).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Clear search" }));+ await user.click(+ screen.getByRole("button", { name: "Sort files: Recent first" }),+ );+ await user.click(screen.getByRole("menuitem", { name: "Name Z→A" }));+ const cards = screen.getAllByRole("listitem");+ expect(cards[0]).toHaveTextContent("Two.pdf");+ expect(cards[1]).toHaveTextContent("One.pdf");+ expect(+ screen.getByRole("button", { name: "Sort files: Name Z→A" }),+ ).toBeInTheDocument();+ });++ it("uses the shared grid with keyboard selection and no management menus", async () => {+ state.viewMode = "grid";+ const user = userEvent.setup();+ show();+ const card = screen+ .getByText("One.pdf")+ .closest('[role="listitem"]') as HTMLElement;+ act(() => card.focus());+ await user.keyboard(" ");+ await user.click(screen.getByRole("button", { name: "Add 1 files" }));+ await waitFor(() =>+ expect(state.selected).toHaveBeenCalledWith([state.files[0]], []),+ );+ expect(screen.queryByLabelText("File actions")).not.toBeInTheDocument();+ });+});diff --git a/frontend/editor/src/core/components/filesPage/LibraryFilePicker.tsx b/frontend/editor/src/core/components/filesPage/LibraryFilePicker.tsxnew file mode 100644index 0000000000..29c5035e1f--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryFilePicker.tsx@@ -0,0 +1,970 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Alert, Drawer, Text } from "@mantine/core";+import { Dropzone } from "@mantine/dropzone";+import { useMediaQuery } from "@mantine/hooks";+import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";+import { Icon } from "@app/ui/Icon";+import { alert } from "@app/components/toast";+import { useFilesModalContext } from "@app/contexts/FilesModalContext";+import { useFilesPage } from "@app/contexts/FilesPageContext";+import { useFolders } from "@app/contexts/FolderContext";+import { useAllFiles } from "@app/contexts/FileContext";+import { useAppConfig } from "@app/contexts/AppConfigContext";+import { useSharingEnabled } from "@app/hooks/useSharingEnabled";+import { useGoogleDrivePicker } from "@app/hooks/useGoogleDrivePicker";+import { useProcessingFolders } from "@app/hooks/useProcessingFolders";+import { useFolderFileStates } from "@app/components/filesPage/useFolderFileStates";+import { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";+import { createQuickKey } from "@app/types/fileContext";+import { useIsMobile } from "@app/hooks/useIsMobile";+import {+ FileGrid,+ type FilesPageEntry,+} from "@app/components/filesPage/FileGrid";+import { LibraryToolbar } from "@app/components/filesPage/LibraryToolbar";+import { LibraryTabs } from "@app/components/filesPage/LibraryTabs";+import { FolderNameDialog } from "@app/components/filesPage/FolderNameDialog";+import { useLibraryViewState } from "@app/components/filesPage/useLibraryViewState";+import { useLibraryScrollPosition } from "@app/components/filesPage/useLibraryScrollPosition";+import { FileDetailsPanel } from "@app/components/filesPage/FileDetailsPanel";+import { libraryEntries } from "@app/components/filesPage/libraryEntries";+import { useLibraryFiles } from "@app/components/filesPage/useLibraryFiles";+import { useDiskFolder } from "@app/components/filesPage/useDiskFolder";+import {+ addPickerItems,+ pickerKey,+ supportsPickerFile,+ type PickerItem,+} from "@app/components/filesPage/pickerSelection";+import MobileUploadModal from "@app/components/shared/MobileUploadModal";+import { openFilesFromDisk } from "@app/services/openFilesFromDisk";+import { readDiskFile } from "@app/services/localFolderContents";+import { zipFileService } from "@app/services/zipFileService";+import {+ createNewStirlingFileStub,+ type StirlingFileStub,+} from "@app/types/fileContext";+import type { FileId } from "@app/types/file";+import { folderKind, type FolderId } from "@app/types/folder";+import { getFolderChain } from "@app/utils/folderPath";+import { useDropzoneFiles } from "@app/hooks/useDropzoneFiles";+import {+ Z_INDEX_FILE_MANAGER_MODAL,+ Z_INDEX_OVER_FILE_MANAGER_MODAL,+} from "@app/styles/zIndex";+import "@app/components/filesPage/FilesPage.css";+import "@app/components/filesPage/LibraryFilePicker.css";++interface Props {+ supportedFormats?: string[];+ onBusyChange: (busy: boolean) => void;+ onExternalPickerChange: (open: boolean) => void;+ /** Destination mode shows server storage; files provide context and cannot be selected. */+ destination?: {+ fileCount: number;+ onClose: () => void;+ onConfirm: (folderId: FolderId | null) => void;+ };+}++/** Shares the library's data and browser; navigation and uncommitted selections belong to this modal. */+export function LibraryFilePicker({+ supportedFormats,+ onBusyChange,+ onExternalPickerChange,+ destination,+}: Props) {+ const { t } = useTranslation();+ const { closeFilesModal, onRecentFileSelect, maxSelectable, loadFiles } =+ useFilesModalContext();+ const library = useFilesPage();+ const close = destination?.onClose ?? closeFilesModal;+ const folders = useFolders();+ const { fileIds: activeFileIds } = useAllFiles();+ const activeWorkspaceFileIds = useMemo(+ () => new Set<string>(activeFileIds),+ [activeFileIds],+ );+ const { config } = useAppConfig();+ const { sharingEnabled } = useSharingEnabled();+ const drive = useGoogleDrivePicker();+ const isPhone = useIsMobile();+ const compact = useMediaQuery("(max-width: 1000px)") ?? false;+ const {+ currentFolderId,+ setCurrentFolderId,+ currentTab,+ setCurrentTab,+ search,+ setSearch,+ sortMode,+ setSortMode,+ originFilter,+ setOriginFilter,+ typeFilter,+ setTypeFilter,+ } = useLibraryViewState(destination ? "all" : "recent");+ const browserRef = useRef<HTMLDivElement>(null);+ const [selection, setSelection] = useState<Map<string, PickerItem>>(+ () => new Map(),+ );+ const [uploads, setUploads] = useState<+ Map<FileId, Extract<PickerItem, { kind: "upload" }>>+ >(() => new Map());+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const busyRef = useRef(false);+ const [mobileUploadOpen, setMobileUploadOpen] = useState(false);+ const [showSelected, setShowSelected] = useState(false);+ const [detailsOpen, setDetailsOpen] = useState(false);+ const [dragging, setDragging] = useState(false);+ const [creatingFolder, setCreatingFolder] = useState(false);+ const fileInput = useRef<HTMLInputElement>(null);+ const lastSelected = useRef<string | null>(null);+ const currentFolder = currentFolderId+ ? folders.foldersById.get(currentFolderId)+ : undefined;+ const directory =+ currentFolder && folderKind(currentFolder) === "local"+ ? currentFolder.directory+ : undefined;+ const { diskEntries, diskLoading } = useDiskFolder(+ directory,+ currentFolderId,+ library.diskRevision,+ setError,+ );+ const processing = useProcessingFolders();+ const processingRecord = currentFolder+ ? processing.stateFor(currentFolder)+ : undefined;+ const { fileStates, processingLockedFor, processingStatesUnavailable } =+ useFolderFileStates(processingRecord?.id, Boolean(processingRecord));+ useEffect(() => {+ if (!processingStatesUnavailable) return;+ setError(+ t(+ "filesPage.error.processingStatusUnavailable",+ "Could not refresh processing status. File locks have been released until the connection recovers.",+ ),+ );+ }, [processingStatesUnavailable, t]);+ const uploadStubs = useMemo(+ () => Array.from(uploads.values(), (item) => item.stub),+ [uploads],+ );+ const { visibleFiles, visibleFolders, availableTypes } = useLibraryFiles({+ allFiles: library.allFiles,+ stagedFiles: uploadStubs,+ currentFolderId,+ currentTab,+ search,+ sortMode,+ originFilter: destination ? "cloud" : originFilter,+ typeFilter,+ diskEntries: directory ? diskEntries : undefined,+ });+ const fileMap = useMemo(+ () =>+ new Map([+ ...library.fileMap,+ ...uploadStubs.map((stub) => [stub.id, stub] as const),+ ...Array.from(selection.values()).flatMap((item) =>+ item.kind === "disk" ? [] : [[item.stub.id, item.stub] as const],+ ),+ ]),+ [library.fileMap, uploadStubs, selection],+ );+ const selectedFileIds = useMemo(+ () =>+ new Set(+ Array.from(selection.values()).flatMap((item) =>+ item.kind === "disk" ? [] : [item.stub.id],+ ),+ ),+ [selection],+ );+ const selectedDiskPaths = useMemo(+ () =>+ new Set(+ Array.from(selection.values()).flatMap((item) =>+ item.kind === "disk" ? [item.entry.path] : [],+ ),+ ),+ [selection],+ );++ const browserEntries = useMemo<FilesPageEntry[]>(+ () => [+ ...visibleFiles+ .filter((stub) => uploads.has(stub.id))+ .map<FilesPageEntry>((file) => ({ kind: "file", file })),+ ...libraryEntries({+ visibleFolders,+ visibleFiles: visibleFiles.filter((stub) => !uploads.has(stub.id)),+ currentFolderId,+ foldersById: folders.foldersById,+ fileCountsByFolder: library.fileCountsByFolder,+ search,+ sortMode,+ originFilter,+ typeFilter,+ diskEntries: directory ? diskEntries : undefined,+ }).map((entry) => {+ const name = entry.disk?.name ?? entry.file?.name;+ const inCurrentFolder =+ Boolean(entry.disk) || entry.file?.folderId === currentFolderId;+ return {+ ...entry,+ diskState: inCurrentFolder && name ? fileStates.get(name) : undefined,+ processingLocked: Boolean(+ inCurrentFolder && name && processingLockedFor(name),+ ),+ };+ }),+ ],+ [+ uploads,+ visibleFolders,+ visibleFiles,+ currentFolderId,+ folders.foldersById,+ library.fileCountsByFolder,+ search,+ sortMode,+ originFilter,+ typeFilter,+ directory,+ diskEntries,+ fileStates,+ processingLockedFor,+ ],+ );++ const entries = showSelected+ ? Array.from(selection.values()).map<FilesPageEntry>((item) =>+ item.kind === "disk"+ ? { kind: "diskFile", disk: item.entry }+ : { kind: "file", file: item.stub },+ )+ : browserEntries;++ const itemForEntry = useCallback(+ (entry: FilesPageEntry): PickerItem | null => {+ if (entry.disk) return { kind: "disk", entry: entry.disk };+ if (entry.file)+ return (+ uploads.get(entry.file.id) ?? { kind: "stored", stub: entry.file }+ );+ return null;+ },+ [uploads],+ );++ const selectItem = (item: PickerItem, shift = false) => {+ if (busyRef.current || destination) return;+ const key = pickerKey(item);+ const visible = entries.find((entry) => {+ const candidate = itemForEntry(entry);+ return candidate && pickerKey(candidate) === key;+ });+ if (visible?.processingLocked) return;+ const anchor = lastSelected.current;+ setSelection((previous) => {+ if (shift && anchor) {+ const candidates = entries+ .filter((entry) => !entry.processingLocked)+ .flatMap((entry) => {+ const candidate = itemForEntry(entry);+ return candidate ? [candidate] : [];+ });+ const from = candidates.findIndex(+ (candidate) => pickerKey(candidate) === anchor,+ );+ const to = candidates.findIndex(+ (candidate) => pickerKey(candidate) === key,+ );+ if (from >= 0 && to >= 0)+ return addPickerItems(+ previous,+ candidates.slice(Math.min(from, to), Math.max(from, to) + 1),+ maxSelectable,+ supportedFormats,+ );+ }+ if (previous.has(key)) {+ const next = new Map(previous);+ next.delete(key);+ return next;+ }+ return addPickerItems(previous, [item], maxSelectable, supportedFormats);+ });+ lastSelected.current = key;+ };++ const eligibilityReason = (entry: FilesPageEntry) => {+ if (destination && entry.kind !== "folder")+ return t("filePicker.chooseDestination", "Choose a folder, or add here.");+ const item = itemForEntry(entry);+ if (!item) return undefined;+ if (entry.processingLocked)+ return entry.diskState === "processing"+ ? t(+ "filesPage.diskState.processingHint",+ "Processing - available when it finishes",+ )+ : t(+ "filesPage.diskState.waitingHint",+ "Queued for processing - available when its folder has run it",+ );+ const name = item.kind === "disk" ? item.entry.name : item.stub.name;+ if (!supportsPickerFile(name, supportedFormats))+ return t(+ "filePicker.unsupported",+ "This file type isn't supported by the selected tool.",+ );+ return undefined;+ };++ const disabledReason = (entry: FilesPageEntry) => {+ const reason = eligibilityReason(entry);+ if (reason) return reason;+ const item = itemForEntry(entry);+ if (!item) return undefined;+ if (busy) return t("filePicker.adding", "Adding files…");+ if (+ maxSelectable !== null &&+ maxSelectable !== 1 &&+ selection.size >= maxSelectable &&+ !selection.has(pickerKey(item))+ )+ return t("filePicker.limit", "Choose up to {{count}} files.", {+ count: maxSelectable,+ });+ return undefined;+ };++ const errorMessage = (cause: unknown) =>+ cause instanceof Error+ ? cause.message+ : t("filePicker.error", "Could not add these files. Please try again.");+ const reportError = (cause: unknown) => setError(errorMessage(cause));+ const getDropzoneFiles = useDropzoneFiles((cause) => {+ setDragging(false);+ reportError(cause);+ });+ const run = async (operation: () => Promise<void>) => {+ if (busyRef.current) return;+ busyRef.current = true;+ setBusy(true);+ onBusyChange(true);+ setError(null);+ try {+ await operation();+ } catch (cause) {+ reportError(cause);+ } finally {+ busyRef.current = false;+ setBusy(false);+ onBusyChange(false);+ }+ };++ const stageFiles = (files: File[]) => {+ if (busyRef.current || destination) return;+ const uploadsByKey = new Map(+ Array.from(uploads.values(), (item) => [createQuickKey(item.file), item]),+ );+ const newItems = files.map((file) => {+ const key = createQuickKey(file);+ const existing = uploadsByKey.get(key);+ if (existing) {+ if (existing.file !== file) pendingFilePathMappings.delete(file);+ return existing;+ }+ // Deferred native paths stay attached to the File until editor ingestion.+ const localFilePath = pendingFilePathMappings.get(file);+ const stub = createNewStirlingFileStub(file);+ if (typeof localFilePath === "string") stub.localFilePath = localFilePath;+ const item = { kind: "upload" as const, file, stub };+ uploadsByKey.set(key, item);+ return item;+ });+ setUploads(+ (previous) =>+ new Map([+ ...previous,+ ...newItems.map((item) => [item.stub.id, item] as const),+ ]),+ );+ setSelection((previous) =>+ addPickerItems(previous, newItems, maxSelectable, supportedFormats),+ );+ if (files.some((file) => !supportsPickerFile(file.name, supportedFormats)))+ setError(+ t(+ "filePicker.unsupported",+ "This file type isn't supported by the selected tool.",+ ),+ );+ };++ const pickFromComputer = async () => {+ try {+ stageFiles(+ await openFilesFromDisk({+ multiple: maxSelectable !== 1,+ onFallbackOpen: () => fileInput.current?.click(),+ }),+ );+ } catch (cause) {+ reportError(cause);+ }+ };++ const confirm = async (items = Array.from(selection.values())) => {+ if (busyRef.current || destination) return;+ const eligible = Array.from(+ addPickerItems(+ new Map(),+ items,+ maxSelectable,+ supportedFormats,+ ).values(),+ );+ if (!eligible.length) return;+ busyRef.current = true;+ closeFilesModal();+ const errors: string[] = [];+ try {+ const stored: StirlingFileStub[] = [];+ const incoming: File[] = [];+ for (const item of eligible) {+ if (item.kind === "stored")+ stored.push(library.fileMap.get(item.stub.id) ?? item.stub);+ else if (item.kind === "upload") {+ incoming.push(item.file);+ } else {+ try {+ const file = await readDiskFile(item.entry);+ if (!file) throw new Error("File unavailable");+ pendingFilePathMappings.set(file, item.entry.path);+ incoming.push(file);+ } catch (cause) {+ console.error(+ "Could not read selected disk file",+ item.entry.path,+ cause,+ );+ errors.push(+ t(+ "filePicker.fileUnavailable",+ "{{name}} is no longer available.",+ { name: item.entry.name },+ ),+ );+ }+ }+ }+ if (stored.length || incoming.length)+ await onRecentFileSelect(stored, incoming);+ } catch (cause) {+ errors.push(errorMessage(cause));+ }+ if (errors.length) {+ alert({+ alertType: "error",+ title: t("filePicker.errorTitle", "Couldn't add files"),+ body: errors.join("\n"),+ expandable: false,+ durationMs: 5000,+ });+ }+ };++ const unzip = (stub: StirlingFileStub) =>+ run(async () => {+ const upload = uploads.get(stub.id);+ const [file] = upload ? [upload.file] : await loadFiles([stub]);+ if (!file)+ throw new Error(+ t("filePicker.fileUnavailable", "{{name}} is no longer available.", {+ name: stub.name,+ }),+ );+ const result = await zipFileService.extractAllFiles(file);+ if (!result.success)+ throw new Error(+ result.errors.join("\n") ||+ t(+ "filePicker.emptyZip",+ "No files could be extracted from this ZIP.",+ ),+ );+ const extracted = result.extractedFiles.map((file) => ({+ kind: "upload" as const,+ file,+ stub: createNewStirlingFileStub(file),+ }));+ setUploads(+ (previous) =>+ new Map([+ ...previous,+ ...extracted.map((item) => [item.stub.id, item] as const),+ ]),+ );+ setSelection((previous) => {+ const next = new Map(previous);+ next.delete(pickerKey({ kind: "stored", stub }));+ return addPickerItems(next, extracted, maxSelectable, supportedFormats);+ });+ if (result.errors.length) setError(result.errors.join("\n"));+ });++ const openFolder = (id: FolderId | null) => {+ setShowSelected(false);+ setCurrentTab("all");+ setCurrentFolderId(id);+ setSearch("");+ lastSelected.current = null;+ };+ const onScrollCapture = useLibraryScrollPosition(+ browserRef,+ `${currentTab}:${currentFolderId}:${library.viewMode}:${showSelected}`,+ library.loading || diskLoading,+ entries.length,+ );+ const details = (+ <FileDetailsPanel+ selectedFileIds={[...selectedFileIds]}+ fileMap={fileMap}+ foldersById={folders.foldersById}+ onClose={() => setDetailsOpen(false)}+ onPickVersion={(stub) => selectItem({ kind: "stored", stub })}+ />+ );++ return (+ <div+ ref={browserRef}+ onScrollCapture={onScrollCapture}+ className="files-page library-file-picker"+ data-tour="files-modal"+ >+ <header className="library-picker-header">+ <div>+ <h2>+ {destination+ ? t("filesPage.addToLibrary", "Add to Stirling library…")+ : t("filePicker.title", "Add files")}+ </h2>+ <Text size="sm" c="dimmed">+ {destination+ ? t(+ "filePicker.chooseDestination",+ "Choose a folder, or add here.",+ )+ : t(+ "filePicker.subtitle",+ "Choose from your library or add something new.",+ )}+ </Text>+ </div>+ <ActionIcon+ variant="tertiary"+ disabled={busy}+ onClick={close}+ aria-label={t("close", "Close")}+ >+ <Icon name="x" />+ </ActionIcon>+ </header>+ {!destination && (+ <div className="library-picker-imports" data-tour="file-sources">+ <Button+ variant="tertiary"+ disabled={busy}+ leftSection={<Icon name="file-up" />}+ onClick={() => void pickFromComputer()}+ >+ {t("filePicker.fromComputer", "From your computer")}+ </Button>+ {drive.isEnabled && (+ <Button+ variant="tertiary"+ disabled={busy}+ loading={drive.isLoading}+ leftSection={<Icon name="googledrive" />}+ onClick={() => {+ onExternalPickerChange(true);+ void drive+ .openPicker({ multiple: maxSelectable !== 1 })+ .then(stageFiles)+ .catch(reportError)+ .finally(() => onExternalPickerChange(false));+ }}+ >+ Google Drive+ </Button>+ )}+ {config?.enableMobileScanner && !isPhone && (+ <Button+ variant="tertiary"+ disabled={busy}+ leftSection={<Icon name="qr-code" />}+ onClick={() => setMobileUploadOpen(true)}+ >+ {t("filePicker.fromPhone", "From your phone")}+ </Button>+ )}+ <input+ ref={fileInput}+ type="file"+ hidden+ multiple={maxSelectable !== 1}+ accept={supportedFormats+ ?.map((format) => `.${format.replace(/^\./, "")}`)+ .join(",")}+ onChange={(event) => {+ stageFiles(Array.from(event.target.files ?? []));+ event.target.value = "";+ }}+ />+ </div>+ )}+ {(error || (!destination && drive.error)) && (+ <Alert+ title={t("filePicker.errorTitle", "Couldn't add files")}+ withCloseButton+ onClose={() => {+ setError(null);+ drive.clearError();+ }}+ role="alert"+ >+ {error ?? drive.error}+ </Alert>+ )}+ <LibraryTabs+ libraryOnly={Boolean(destination)}+ currentTab={currentTab}+ sharingEnabled={sharingEnabled}+ onOpenRoot={() => openFolder(null)}+ onChange={(tab) => {+ setShowSelected(false);+ setCurrentTab(tab);+ }}+ breadcrumbs={+ currentFolderId !== null && (+ <nav+ className="files-page-breadcrumbs"+ aria-label={t("filePicker.folderPath", "Folder path")}+ >+ {getFolderChain(currentFolderId, folders.foldersById).map(+ (folder) => (+ <span className="library-picker-crumb" key={folder.id}>+ <Icon name="chevron-right" size={14} />+ <button+ className="files-page-breadcrumb"+ onClick={() => openFolder(folder.id)}+ >+ {folder.name}+ </button>+ </span>+ ),+ )}+ </nav>+ )+ }+ />+ <div className="library-picker-controls">+ {destination && (+ <Button+ variant="tertiary"+ leftSection={<Icon name="folder-plus" />}+ onClick={() => setCreatingFolder(true)}+ >+ {t("filesPage.newFolder", "New folder")}+ </Button>+ )}+ <div className="files-page-toolbar-actions">+ <LibraryToolbar+ hideFilters={Boolean(destination)}+ dropdownZIndex={Z_INDEX_OVER_FILE_MANAGER_MODAL}+ isMobile={compact}+ availableTypes={availableTypes}+ originFilter={originFilter}+ setOriginFilter={setOriginFilter}+ typeFilter={typeFilter}+ setTypeFilter={setTypeFilter}+ search={search}+ setSearch={setSearch}+ sortMode={sortMode}+ setSortMode={setSortMode}+ viewMode={library.viewMode}+ setViewMode={library.setViewMode}+ />+ </div>+ </div>+ <div className="files-page-body">+ <Dropzone+ className="library-picker-dropzone"+ disabled={busy}+ activateOnDrag={!destination}+ activateOnClick={false}+ useFsAccessApi={false}+ getFilesFromEvent={getDropzoneFiles}+ onDrop={(files) => {+ setDragging(false);+ stageFiles(files);+ }}+ onDragEnter={() => setDragging(true)}+ onDragLeave={() => setDragging(false)}+ onReject={() => {+ setDragging(false);+ setError(+ t(+ "filePicker.error",+ "Could not add these files. Please try again.",+ ),+ );+ }}+ styles={{ inner: { pointerEvents: "all", height: "100%" } }}+ >+ <div className="files-page-content" data-tour="recent-files">+ {!destination &&+ !entries.length &&+ !library.loading &&+ !diskLoading &&+ !search &&+ !typeFilter.length &&+ originFilter === "all" ? (+ <button+ className="library-picker-empty"+ onClick={() => void pickFromComputer()}+ disabled={busy}+ >+ <Icon name="files" size={48} />+ <strong>+ {t(+ "filePicker.dropTitle",+ "Drop files here, or click to browse",+ )}+ </strong>+ <span>+ {t(+ "filePicker.dropHint",+ "Choose the files you want to work with.",+ )}+ </span>+ </button>+ ) : (+ <FileGrid+ entries={entries}+ loading={library.loading || diskLoading}+ selectedFileIds={selectedFileIds}+ activeWorkspaceFileIds={activeWorkspaceFileIds}+ viewMode={library.viewMode}+ currentTab={currentTab}+ searchActive={Boolean(+ search || typeFilter.length || originFilter !== "all",+ )}+ sortMode={sortMode}+ onChangeSortMode={setSortMode}+ onOpenFolder={openFolder}+ onSelectFile={(id, shift) => {+ const stub = fileMap.get(id);+ if (stub)+ selectItem(+ uploads.get(id) ?? { kind: "stored", stub },+ shift,+ );+ }}+ onOpenFile={(stub) =>+ void confirm([+ uploads.get(stub.id) ?? { kind: "stored", stub },+ ])+ }+ onOpenDiskFile={(entry) =>+ void confirm([{ kind: "disk", entry }])+ }+ onSetSelection={(ids) =>+ setSelection((previous) => {+ const next = new Map(previous);+ for (const [key, item] of next)+ if (item.kind !== "disk" && !ids.has(item.stub.id))+ next.delete(key);+ return addPickerItems(+ next,+ [...ids].flatMap((id) => {+ const stub = fileMap.get(id);+ return stub+ ? [+ uploads.get(id) ?? {+ kind: "stored" as const,+ stub,+ },+ ]+ : [];+ }),+ maxSelectable,+ supportedFormats,+ );+ })+ }+ picker={{+ foldersOnly: Boolean(destination),+ isEligible: (entry) => !eligibilityReason(entry),+ selectionDisabled: busy,+ disabledReason,+ selectedDiskPaths,+ onSelectDiskFile: (entry, shift) =>+ selectItem({ kind: "disk", entry }, shift),+ onSetDiskSelection: (disks) =>+ setSelection((previous) => {+ const next = new Map(previous);+ for (const entry of entries)+ if (entry.disk)+ next.delete(+ pickerKey({ kind: "disk", entry: entry.disk }),+ );+ return addPickerItems(+ next,+ disks.map((entry) => ({ kind: "disk", entry })),+ maxSelectable,+ supportedFormats,+ );+ }),+ onUnzipFile: (stub) => void unzip(stub),+ }}+ />+ )}+ {dragging && (+ <div className="files-page-drop-overlay">+ <Icon name="file-up" size={40} />+ <span>+ {t(+ "filePicker.dropTitle",+ "Drop files here, or click to browse",+ )}+ </span>+ </div>+ )}+ </div>+ </Dropzone>+ {detailsOpen && selectedFileIds.size > 0 && !compact && details}+ </div>+ <footer className="library-picker-footer">+ {destination ? (+ <Text size="sm" c="dimmed">+ {t("filesPage.selectedCount", "{{count}} selected", {+ count: destination.fileCount,+ })}+ </Text>+ ) : (+ <div className="library-picker-selection">+ <Button+ size="sm"+ variant="tertiary"+ onClick={() => setShowSelected((value) => !value)}+ aria-pressed={showSelected}+ disabled={!selection.size && !showSelected}+ >+ {maxSelectable+ ? t(+ "filePicker.selectedLimit",+ "{{count}} of {{limit}} selected",+ { count: selection.size, limit: maxSelectable },+ )+ : t("filesPage.selectedCount", "{{count}} selected", {+ count: selection.size,+ })}+ </Button>+ {selection.size > 0 && (+ <Button+ size="sm"+ variant="tertiary"+ disabled={busy}+ onClick={() => setSelection(new Map())}+ >+ {t("filesPage.deselectAll", "Clear selection")}+ </Button>+ )}+ {selectedFileIds.size > 0 && (+ <ActionIcon+ variant="tertiary"+ onClick={() => setDetailsOpen((open) => !open)}+ aria-label={t("filesPage.details", "Details")}+ >+ <Icon name="info" size={20} />+ </ActionIcon>+ )}+ </div>+ )}+ <div className="library-picker-footer-actions">+ <Button fat variant="tertiary" disabled={busy} onClick={close}>+ {t("cancel", "Cancel")}+ </Button>+ {destination ? (+ <Button+ onClick={() => {+ if (busyRef.current) return;+ busyRef.current = true;+ destination.onConfirm(currentFolderId);+ }}+ >+ {t("filePicker.addHere", "Add here")}+ </Button>+ ) : (+ <Button+ fat+ disabled={!selection.size}+ loading={busy}+ onClick={() => void confirm()}+ >+ {t("filePicker.add", "Add {{count}} files", {+ count: selection.size,+ })}+ </Button>+ )}+ </div>+ </footer>+ {destination && (+ <FolderNameDialog+ opened={creatingFolder}+ title={t("filesPage.newFolder", "New folder")}+ submitLabel={t("filesPage.create", "Create")}+ zIndex={Z_INDEX_OVER_FILE_MANAGER_MODAL}+ onClose={() => setCreatingFolder(false)}+ onSubmit={async (name) => {+ const created = await folders.createFolder(+ name,+ currentFolderId,+ "server",+ );+ openFolder(created.id);+ }}+ />+ )}+ <Drawer+ opened={compact && detailsOpen && selectedFileIds.size > 0}+ onClose={() => setDetailsOpen(false)}+ position="right"+ title={t("filesPage.details", "Details")}+ zIndex={Z_INDEX_FILE_MANAGER_MODAL + 1}+ >+ {details}+ </Drawer>+ <MobileUploadModal+ opened={mobileUploadOpen}+ onClose={() => setMobileUploadOpen(false)}+ onFilesReceived={(files) => {+ stageFiles(files);+ setMobileUploadOpen(false);+ }}+ />+ </div>+ );+}diff --git a/frontend/editor/src/core/components/filesPage/LibraryPickerModal.tsx b/frontend/editor/src/core/components/filesPage/LibraryPickerModal.tsxnew file mode 100644index 0000000000..6168ef8e66--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryPickerModal.tsx@@ -0,0 +1,41 @@+import type { ReactNode } from "react";+import { Modal } from "@mantine/core";+import { useMediaQuery } from "@mantine/hooks";+import { Z_INDEX_FILE_MANAGER_MODAL } from "@app/styles/zIndex";++/** Unmounts tentative picker state on close; external pickers temporarily own focus. */+export function LibraryPickerModal({+ opened,+ onClose,+ busy = false,+ externalPickerOpen = false,+ children,+}: {+ opened: boolean;+ onClose: () => void;+ busy?: boolean;+ externalPickerOpen?: boolean;+ children: ReactNode;+}) {+ const mobile = useMediaQuery("(max-width: 640px)") ?? false;+ return (+ <Modal+ opened={opened}+ onClose={() => {+ if (!busy) onClose();+ }}+ fullScreen={mobile}+ size="min(1280px, 94vw)"+ centered+ withCloseButton={false}+ padding={0}+ radius="md"+ zIndex={Z_INDEX_FILE_MANAGER_MODAL}+ trapFocus={!externalPickerOpen}+ closeOnEscape={!busy && !externalPickerOpen}+ closeOnClickOutside={!busy && !externalPickerOpen}+ >+ {opened && children}+ </Modal>+ );+}diff --git a/frontend/editor/src/core/components/filesPage/LibraryTabs.tsx b/frontend/editor/src/core/components/filesPage/LibraryTabs.tsxnew file mode 100644index 0000000000..d89e7d5fcb--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryTabs.tsx@@ -0,0 +1,68 @@+import { Fragment, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { Button, type ButtonProps } from "@app/ui/Button";+import type { FilesPageTab } from "@app/contexts/FilesPageContext";++/** Shared view navigation; each host owns its remembered browsing state. */+export function LibraryTabs({+ currentTab,+ onChange,+ onOpenRoot,+ rootDropHandlers,+ sharingEnabled,+ breadcrumbs,+ libraryOnly = false,+}: {+ currentTab: FilesPageTab;+ onChange: (tab: FilesPageTab) => void;+ /** The active library tab returns to root; switching tabs restores the remembered folder. */+ onOpenRoot: () => void;+ rootDropHandlers?: Pick<ButtonProps, "onDragOver" | "onDrop">;+ sharingEnabled: boolean;+ breadcrumbs?: ReactNode;+ libraryOnly?: boolean;+}) {+ const { t } = useTranslation();+ const tabs: { id: FilesPageTab; label: string }[] = [+ { id: "recent", label: t("filesPage.recentFiles", "Recents") },+ { id: "all", label: t("filesPage.allFiles", "Stirling library") },+ ...(sharingEnabled+ ? [+ {+ id: "shared" as const,+ label: t("fileManager.sharedWithYou", "Shared with you"),+ },+ ]+ : []),+ ];+ return (+ <div className="files-page-navigation">+ <nav+ className="files-page-view-tabs"+ aria-label={t("filePicker.sources", "File sources")}+ >+ {tabs+ .filter((tab) => !libraryOnly || tab.id === "all")+ .map((tab) => (+ <Fragment key={tab.id}>+ <Button+ variant={currentTab === tab.id ? "primary" : "tertiary"}+ shape="pill"+ size="sm"+ aria-pressed={currentTab === tab.id}+ onClick={() =>+ tab.id === "all" && currentTab === "all"+ ? onOpenRoot()+ : onChange(tab.id)+ }+ {...(tab.id === "all" ? rootDropHandlers : undefined)}+ >+ {tab.label}+ </Button>+ {tab.id === "all" && currentTab === "all" && breadcrumbs}+ </Fragment>+ ))}+ </nav>+ </div>+ );+}diff --git a/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx b/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsxnew file mode 100644index 0000000000..3c9b3a9922--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/LibraryToolbar.tsx@@ -0,0 +1,168 @@+import { MultiSelect, Select } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { Icon } from "@app/ui/Icon";+import { SegmentedControl } from "@app/ui/SegmentedControl";+import { FilesToolbarFilterMenu } from "@app/components/filesPage/FilesToolbarFilterMenu";+import { FilesToolbarSortMenu } from "@app/components/filesPage/FilesToolbarSortMenu";+import { FilenameSearch } from "@app/components/filesPage/FilenameSearch";+import {+ FILES_PAGE_VIEW_MODES,+ type FilesPageOriginFilter,+ type FilesPageSortMode,+ type FilesPageViewMode,+} from "@app/contexts/FilesPageContext";+import type { LibraryFilters } from "@app/components/filesPage/useLibraryFiles";++type Props = Pick<+ LibraryFilters,+ "search" | "sortMode" | "originFilter" | "typeFilter"+> & {+ isMobile: boolean;+ availableTypes: string[];+ setSearch: (value: string) => void;+ setSortMode: (value: FilesPageSortMode) => void;+ setOriginFilter: (value: FilesPageOriginFilter) => void;+ setTypeFilter: (value: string[]) => void;+ viewMode: FilesPageViewMode;+ setViewMode: (value: FilesPageViewMode) => void;+ /** Popovers are portalled; modal hosts must place them above their overlay. */+ dropdownZIndex?: number;+ hideFilters?: boolean;+};++export function LibraryToolbar({+ isMobile,+ availableTypes,+ originFilter,+ setOriginFilter,+ typeFilter,+ setTypeFilter,+ search,+ setSearch,+ sortMode,+ setSortMode,+ viewMode,+ setViewMode,+ dropdownZIndex,+ hideFilters = false,+}: Props) {+ const { t } = useTranslation();+ return (+ <>+ {!hideFilters &&+ (isMobile ? (+ <FilesToolbarFilterMenu+ zIndex={dropdownZIndex}+ originFilter={originFilter}+ onOriginChange={setOriginFilter}+ availableTypes={availableTypes}+ typeFilter={typeFilter}+ onTypeChange={setTypeFilter}+ />+ ) : (+ <>+ <Select+ comboboxProps={{ zIndex: dropdownZIndex }}+ size="xs"+ value={originFilter}+ onChange={(value) =>+ value && setOriginFilter(value as FilesPageOriginFilter)+ }+ data={[+ {+ value: "all",+ label: t("filesPage.origin.all", "All sources"),+ },+ {+ value: "local",+ label: t("filesPage.origin.local", "Local"),+ },+ {+ value: "cloud",+ label: t("filesPage.origin.cloud", "Cloud"),+ },+ {+ value: "shared-with-me",+ label: t("filesPage.origin.shared", "Shared"),+ },+ ]}+ style={{ width: 140 }}+ aria-label={t("filesPage.originFilter", "Filter by source")}+ />+ {(availableTypes.length > 1 || typeFilter.length > 0) && (+ <MultiSelect+ comboboxProps={{ zIndex: dropdownZIndex }}+ size="xs"+ value={typeFilter}+ onChange={setTypeFilter}+ data={availableTypes.map((ext) => ({+ value: ext,+ label: ext,+ }))}+ placeholder={+ typeFilter.length === 0+ ? t("filesPage.typeFilter.allTypes", "All types")+ : undefined+ }+ clearable+ hidePickedOptions+ searchable={false}+ style={{ width: 160 }}+ aria-label={t("filesPage.typeFilter.label", "Filter by type")}+ />+ )}+ </>+ ))}+ <FilenameSearch+ value={search}+ onChange={setSearch}+ zIndex={dropdownZIndex}+ />+ <FilesToolbarSortMenu+ value={sortMode}+ onChange={setSortMode}+ zIndex={dropdownZIndex}+ />+ <span className="files-page-toolbar-divider" aria-hidden="true" />+ <SegmentedControl+ size="sm"+ value={viewMode}+ onChange={(v) => {+ if (!(FILES_PAGE_VIEW_MODES as readonly string[]).includes(v)) return;+ setViewMode(v as FilesPageViewMode);+ }}+ aria-label={t("filesPage.viewMode.label", "View mode")}+ options={[+ {+ value: "grid",+ label: (+ <span+ className="files-page-view-toggle-icon"+ title={t("filesPage.viewMode.grid", "Grid view")}+ >+ <Icon name="layout-grid" size={20} />+ <span className="files-page-sr-only">+ {t("filesPage.viewMode.grid", "Grid view")}+ </span>+ </span>+ ),+ },+ {+ value: "list",+ label: (+ <span+ className="files-page-view-toggle-icon"+ title={t("filesPage.viewMode.list", "List view")}+ >+ <Icon name="list" size={20} />+ <span className="files-page-sr-only">+ {t("filesPage.viewMode.list", "List view")}+ </span>+ </span>+ ),+ },+ ]}+ />+ </>+ );+}diff --git a/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.test.tsx b/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.test.tsxnew file mode 100644index 0000000000..f1d10c0c6d--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.test.tsx@@ -0,0 +1,90 @@+import { describe, expect, it, vi } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { MantineProvider } from "@mantine/core";+import { MoveToFolderDialog } from "@app/components/filesPage/MoveToFolderDialog";+import { createFolderId, type FolderRecord } from "@app/types/folder";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),+}));++const folder: FolderRecord = {+ id: createFolderId(),+ name: "Documents",+ parentFolderId: null,+ createdAt: 0,+ updatedAt: 0,+};++function show(+ options: {+ onConfirm?: (id: FolderRecord["id"] | null) => Promise<void>;+ onCreateFolder?: (+ name: string,+ parentId: FolderRecord["id"] | null,+ ) => Promise<FolderRecord>;+ } = {},+) {+ const onConfirm = options.onConfirm ?? vi.fn().mockResolvedValue(undefined);+ const onClose = vi.fn();+ render(+ <MantineProvider env="test">+ <MoveToFolderDialog+ opened+ folders={[folder]}+ onClose={onClose}+ {...options}+ onConfirm={onConfirm}+ />+ </MantineProvider>,+ );+ return { onConfirm, onClose };+}++describe("MoveToFolderDialog", () => {+ it("moves files to the selected folder and closes on success", async () => {+ const user = userEvent.setup();+ const { onConfirm, onClose } = show();++ await user.click(screen.getByRole("button", { name: "Documents" }));+ await user.click(screen.getByRole("button", { name: "Move here" }));+ expect(onConfirm).toHaveBeenCalledWith(folder.id);+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ });++ it("allows moving a file to the root", async () => {+ const { onConfirm } = show();+ await userEvent.click(screen.getByRole("button", { name: "Move here" }));+ expect(onConfirm).toHaveBeenCalledWith(null);+ });++ it("selects a newly created folder as the destination", async () => {+ const user = userEvent.setup();+ const created = { ...folder, id: createFolderId(), name: "Invoices" };+ const onCreateFolder = vi.fn().mockResolvedValue(created);+ const { onConfirm } = show({ onCreateFolder });++ await user.click(screen.getByTestId("move-dialog-create-folder-toggle"));+ await user.type(screen.getByLabelText("New folder name"), "Invoices");+ await user.click(screen.getByRole("button", { name: "Create" }));+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Move here" })).toBeEnabled(),+ );+ await user.click(screen.getByRole("button", { name: "Move here" }));++ expect(onCreateFolder).toHaveBeenCalledWith("Invoices", null);+ expect(onConfirm).toHaveBeenCalledWith(created.id);+ });++ it("keeps the destination picker open when moving fails", async () => {+ const user = userEvent.setup();+ const { onClose } = show({+ onConfirm: vi.fn().mockRejectedValue(new Error("Upload failed")),+ });+ await user.click(screen.getByRole("button", { name: "Documents" }));+ await user.click(screen.getByRole("button", { name: "Move here" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Upload failed");+ expect(onClose).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.tsx b/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.tsxindex b6e474a3ec..c2b6442f52 100644--- a/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.tsx+++ b/frontend/editor/src/core/components/filesPage/MoveToFolderDialog.tsx@@ -42,12 +42,10 @@ export function MoveToFolderDialog({const [target, setTarget] = useState<FolderId | null>(initialFolderId);const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);- // Inline create-folder state; revealed by the toggle.const [creatingFolder, setCreatingFolder] = useState(false);const [newFolderName, setNewFolderName] = useState("");const [creating, setCreating] = useState(false);- // Reset when reopening with a new initial.React.useEffect(() => {if (opened) {setTarget(initialFolderId);@@ -59,7 +57,6 @@ export function MoveToFolderDialog({}}, [opened, initialFolderId]);- /** Single-pass build of parent index, depths, and blocked descendants. */const { depthById, blocked, treeOrder } = useMemo(() => {const byParent = new Map<FolderId | null, FolderRecord[]>();for (const folder of folders) {@@ -73,7 +70,6 @@ export function MoveToFolderDialog({);}- // Pre-order DFS; truncates past MAX_TREE_DEPTH to prevent stack overflow.const MAX_TREE_DEPTH = 50;const order: FolderRecord[] = [];const depths = new Map<FolderId, number>();@@ -129,7 +125,7 @@ export function MoveToFolderDialog({}}><FolderPick- label={t("filesPage.allFiles", "All files")}+ label={t("filesPage.allFiles", "Stirling library")}isActive={target === ROOT_FOLDER_ID}disabled={false}depth={0}@@ -148,7 +144,6 @@ export function MoveToFolderDialog({/>))}</div>- {/* Inline Create new folder; new folder becomes the move target. */}{onCreateFolder &&(() => {const trimmedName = newFolderName.trim();@@ -159,7 +154,6 @@ export function MoveToFolderDialog({try {const created = await onCreateFolder(trimmedName,- // ROOT becomes null parent.target === ROOT_FOLDER_ID ? null : target,);setTarget(created.id);@@ -216,7 +210,6 @@ export function MoveToFolderDialog({>{t("filesPage.moveDialog.newFolderCreate", "Create")}</Button>- {/* X collapses the inline create row only. */}<Tooltiplabel={t("filesPage.moveDialog.newFolderCancel", "Discard")}withinPortal@@ -270,6 +263,7 @@ export function MoveToFolderDialog({</Button><Buttonloading={submitting}+ disabled={creating || (target !== null && blocked.has(target))}onClick={async () => {setSubmitting(true);setError(null);diff --git a/frontend/editor/src/core/components/filesPage/VersionTimeline.tsx b/frontend/editor/src/core/components/filesPage/VersionTimeline.tsxindex eeb3c627ff..8645633bd8 100644--- a/frontend/editor/src/core/components/filesPage/VersionTimeline.tsx+++ b/frontend/editor/src/core/components/filesPage/VersionTimeline.tsx@@ -10,7 +10,6 @@ import { StirlingFileStub } from "@app/types/fileContext";import { formatFileSize, getFileDate } from "@app/utils/fileUtils";import { downloadFileFromStorage } from "@app/utils/downloadUtils";-/** Small label/value row with crisp flex alignment and colon separation. */export function DetailField({label,value,@@ -48,7 +47,6 @@ export function DetailField({);}-/** Tool that produced `version` from `prior`; null for v1. */function deltaToolFor(version: StirlingFileStub,prior: StirlingFileStub | null,@@ -59,24 +57,22 @@ function deltaToolFor(return curr[priorLen] ?? null;}-/** The operation's own label when it has one, else its translated tool name. */function ToolLabel({ operation }: { operation: ToolOperation }) {const { t } = useTranslation();return <span>{toolOperationLabel(operation, t)}</span>;}export interface VersionTimelineProps {- /** Chain sorted oldest-first. */+ onPickVersion?: (file: StirlingFileStub) => void;chain: StirlingFileStub[];- /** Currently selected version. */currentId: FileId;- onAddToWorkspace: (fileIds: FileId[]) => void;- onRemove: (fileIds: FileId[]) => void;+ onAddToWorkspace?: (fileIds: FileId[]) => void;+ onRemove?: (fileIds: FileId[]) => void;hideHeader?: boolean;}-/** Clean, spacious version timeline with minimal clutter. */export function VersionTimeline({+ onPickVersion,chain,currentId,onAddToWorkspace,@@ -86,7 +82,6 @@ export function VersionTimeline({const { t } = useTranslation();const [showAllCollapsed, setShowAllCollapsed] = useState(false);- // Newest-first ordering.const ordered = useMemo(() =>[...chain].sort(@@ -95,7 +90,6 @@ export function VersionTimeline({[chain],);- // Index by versionNumber for prior-version lookup.const byVersionNumber = useMemo(() => {const map = new Map<number, StirlingFileStub>();for (const v of chain) {@@ -104,7 +98,6 @@ export function VersionTimeline({return map;}, [chain]);- // Collapse middle when long: 3 newest + ellipsis + 2 oldest.const COLLAPSE_THRESHOLD = 6;const collapsible = ordered.length > COLLAPSE_THRESHOLD;type Row =@@ -199,7 +192,6 @@ export function VersionTimeline({)}</div><div className="files-page-details-version-timeline-body">- {/* Header row: Version Badge, Action Title + Menu */}<divstyle={{display: "flex",@@ -244,7 +236,20 @@ export function VersionTimeline({</Text></Group>- {!isActive && (+ {onPickVersion && (+ <ActionIcon+ variant="tertiary"+ aria-label={t(+ "filePicker.selectVersion",+ "Select version {{version}}",+ { version: v.versionNumber },+ )}+ onClick={() => onPickVersion(v)}+ >+ <Icon name="plus" size={20} />+ </ActionIcon>+ )}+ {!isActive && !onPickVersion && (<Menu position="bottom-end" withinPortal shadow="md"><Menu.Target><ActionIcon@@ -262,7 +267,7 @@ export function VersionTimeline({<Menu.Dropdown><Menu.ItemleftSection={<Icon name="external-link" size={20} />}- onClick={() => onAddToWorkspace([v.id])}+ onClick={() => onAddToWorkspace?.([v.id])}>{t("filesPage.openVersionInWorkspace",@@ -284,7 +289,7 @@ export function VersionTimeline({<Menu.Itemcolor="red"leftSection={<Icon name="trash" size={20} />}- onClick={() => onRemove([v.id])}+ onClick={() => onRemove?.([v.id])}>{t("filesPage.removeVersion", "Remove this version")}</Menu.Item>@@ -293,7 +298,6 @@ export function VersionTimeline({)}</div>- {/* Quiet Meta Line: File Size · Date */}<Text size="xs" c="dimmed" style={{ marginTop: "0.15rem" }}>{formatFileSize(v.size)}{v.lastModified && (@@ -301,7 +305,6 @@ export function VersionTimeline({)}</Text>- {/* Show filename ONLY if original upload or if name changed */}{(isOriginal || nameChanged) && (<Textsize="xs"diff --git a/frontend/editor/src/core/components/filesPage/fileOrigin.test.ts b/frontend/editor/src/core/components/filesPage/fileOrigin.test.tsnew file mode 100644index 0000000000..0157fc7513--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/fileOrigin.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";+import { isUnfiledLocalFile } from "@app/components/filesPage/fileOrigin";+import type { StirlingFileStub } from "@app/types/fileContext";+import { createFolderId, type FolderRecord } from "@app/types/folder";++describe("isUnfiledLocalFile", () => {+ const folderId = createFolderId();+ const folders = new Map([[folderId, { id: folderId } as FolderRecord]]);++ it.each([+ ["loose browser copy", {}, true],+ ["browser copy in an existing folder", { folderId }, false],+ [+ "browser copy whose folder was removed",+ { folderId: createFolderId() },+ true,+ ],+ ["server file at the library root", { remoteStorageId: 42 }, false],+ ["shared file", { remoteOwnedByCurrentUser: false }, false],+ ["file opened through a share link", { remoteSharedViaLink: true }, false],+ ])("identifies a %s", (_name, metadata, expected) => {+ expect(isUnfiledLocalFile(metadata as StirlingFileStub, folders)).toBe(+ expected,+ );+ });+});diff --git a/frontend/editor/src/core/components/filesPage/fileOrigin.ts b/frontend/editor/src/core/components/filesPage/fileOrigin.tsindex 273e370053..f98dc0e0cc 100644--- a/frontend/editor/src/core/components/filesPage/fileOrigin.ts+++ b/frontend/editor/src/core/components/filesPage/fileOrigin.ts@@ -1,16 +1,14 @@-/**- * Classifies where a stored file lives. The UI uses this to badge each file- * (Local vs Cloud) and to drive the origin filter chip.- *- * - "local" - only in the browser's IndexedDB- * - "cloud" - also exists on the server (uploaded), still owned by the user- * - "shared-with-me" - opened from a share link / not owned by current user- */-import { StirlingFileStub } from "@app/types/fileContext";+import type { FolderId, FolderRecord } from "@app/types/folder";export type FileOrigin = "local" | "cloud" | "shared-with-me";+/** Browser-only files have neither a server copy nor a link to a file on disk. */+export function isBrowserOnlyFile(file: StirlingFileStub): boolean {+ return getFileOrigin(file) === "local" && !file.localFilePath;+}++/** Local includes browser and disk copies without server storage; shared access takes precedence. */export function getFileOrigin(file: StirlingFileStub): FileOrigin {if (file.remoteSharedViaLink || file.remoteOwnedByCurrentUser === false) {return "shared-with-me";@@ -20,3 +18,14 @@ export function getFileOrigin(file: StirlingFileStub): FileOrigin {}return "local";}++/** Local files without a known folder are hidden from Stirling library but remain in Recents. */+export function isUnfiledLocalFile(+ file: StirlingFileStub,+ foldersById: ReadonlyMap<FolderId, FolderRecord>,+): boolean {+ return (+ getFileOrigin(file) === "local" &&+ (!file.folderId || !foldersById.has(file.folderId))+ );+}diff --git a/frontend/editor/src/core/components/filesPage/libraryEntries.ts b/frontend/editor/src/core/components/filesPage/libraryEntries.tsnew file mode 100644index 0000000000..aede64c79f--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/libraryEntries.ts@@ -0,0 +1,77 @@+import type { FilesPageEntry } from "@app/components/filesPage/FileGrid";+import type {+ FilesPageSortMode,+ FilesPageOriginFilter,+} from "@app/contexts/FilesPageContext";+import type { DiskFileEntry } from "@app/services/localFolderContents";+import type { StirlingFileStub } from "@app/types/fileContext";+import type { FolderId, FolderRecord } from "@app/types/folder";+import { getFolderPath } from "@app/utils/folderPath";++interface Options {+ visibleFiles: StirlingFileStub[];+ visibleFolders: FolderRecord[];+ currentFolderId: FolderId | null;+ foldersById: ReadonlyMap<FolderId, FolderRecord>;+ fileCountsByFolder: ReadonlyMap<FolderId | null, number>;+ search: string;+ sortMode: FilesPageSortMode;+ originFilter: FilesPageOriginFilter;+ typeFilter: string[];+ diskEntries?: DiskFileEntry[];+}++/** diskEntries replaces visibleFiles for mounts; folders always precede files. */+export function libraryEntries({+ visibleFiles,+ visibleFolders,+ currentFolderId,+ foldersById,+ fileCountsByFolder,+ search,+ sortMode,+ diskEntries,+ originFilter,+ typeFilter,+}: Options): FilesPageEntry[] {+ const parentPath = (id: FolderId | null | undefined) =>+ search && (id ?? null) !== currentFolderId+ ? getFolderPath(id, foldersById) || undefined+ : undefined;+ const folders: FilesPageEntry[] = visibleFolders.map((folder) => ({+ kind: "folder",+ folder,+ folderFileCount: diskEntries ? 0 : (fileCountsByFolder.get(folder.id) ?? 0),+ parentPath: parentPath(folder.parentFolderId),+ }));+ const files: FilesPageEntry[] =+ diskEntries !== undefined+ ? diskEntries+ .filter(+ (disk) =>+ (originFilter === "all" || originFilter === "local") &&+ disk.name.toLowerCase().includes(search.toLowerCase()),+ )+ .filter(+ (disk) =>+ !typeFilter.length ||+ typeFilter.includes(+ disk.name.split(".").pop()?.toUpperCase() ?? "",+ ),+ )+ .sort((a, b) => {+ const direction = sortMode.endsWith("asc") ? 1 : -1;+ if (sortMode.startsWith("name"))+ return direction * a.name.localeCompare(b.name);+ if (sortMode.startsWith("size"))+ return direction * (a.sizeBytes - b.sizeBytes);+ return direction * (a.lastModified - b.lastModified);+ })+ .map((disk) => ({ kind: "diskFile", disk }))+ : visibleFiles.map((file) => ({+ kind: "file",+ file,+ parentPath: parentPath(file.folderId),+ }));+ return [...folders, ...files];+}diff --git a/frontend/editor/src/core/components/filesPage/libraryFileDate.ts b/frontend/editor/src/core/components/filesPage/libraryFileDate.tsnew file mode 100644index 0000000000..090263c2c0--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/libraryFileDate.ts@@ -0,0 +1,10 @@+import type { FilesPageTab } from "@app/contexts/FilesPageContext";+import type { StirlingFileStub } from "@app/types/fileContext";++/** Recents uses the ingestion date; an unknown date sorts before known dates in ascending order. */+export function libraryFileDate(+ file: Pick<StirlingFileStub, "createdAt" | "lastModified">,+ tab?: FilesPageTab,+): number {+ return (tab === "recent" ? file.createdAt : file.lastModified) ?? 0;+}diff --git a/frontend/editor/src/core/components/filesPage/pickerSelection.ts b/frontend/editor/src/core/components/filesPage/pickerSelection.tsnew file mode 100644index 0000000000..c97962881a--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/pickerSelection.ts@@ -0,0 +1,43 @@+import type { DiskFileEntry } from "@app/services/localFolderContents";+import type { StirlingFileStub } from "@app/types/fileContext";++export type PickerItem =+ | { kind: "stored"; stub: StirlingFileStub }+ | { kind: "upload"; stub: StirlingFileStub; file: File }+ | { kind: "disk"; entry: DiskFileEntry };++/** Disk paths and stored IDs occupy separate namespaces in a cross-folder selection. */+export function pickerKey(item: PickerItem): string {+ return item.kind === "disk"+ ? `disk:${item.entry.path}`+ : `file:${item.stub.id}`;+}++/** Format restrictions apply equally to imports, native files and stored files. */+export function supportsPickerFile(name: string, formats?: string[]): boolean {+ if (!formats) return true;+ const extension = name.split(".").pop()?.toLowerCase() ?? "";+ return formats.some(+ (format) => format.toLowerCase().replace(/^\./, "") === extension,+ );+}++/** Appends eligible items without dropping earlier choices; a limit of one replaces the choice. */+export function addPickerItems(+ selection: ReadonlyMap<string, PickerItem>,+ items: PickerItem[],+ limit: number | null,+ formats?: string[],+): Map<string, PickerItem> {+ const next = new Map(selection);+ for (const item of items) {+ const name = item.kind === "disk" ? item.entry.name : item.stub.name;+ if (!supportsPickerFile(name, formats)) continue;+ const key = pickerKey(item);+ if (limit === 1 && !next.has(key)) next.clear();+ if (limit !== null && next.size >= limit && !next.has(key)) break;+ next.set(key, item);+ if (limit === 1) break;+ }+ return next;+}diff --git a/frontend/editor/src/core/components/filesPage/useDiskFolder.ts b/frontend/editor/src/core/components/filesPage/useDiskFolder.tsnew file mode 100644index 0000000000..60cb92240f--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useDiskFolder.ts@@ -0,0 +1,102 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { useFolders } from "@app/contexts/FolderContext";+import {+ diskFolderId,+ pickFolderColor,+ type FolderId,+} from "@app/types/folder";+import {+ canListDirectory,+ listDirectory,+ type DiskFileEntry,+} from "@app/services/localFolderContents";++/** Reads mounted directories and ignores obsolete replies after navigation. */+export function useDiskFolder(+ currentLocalDirectory: string | undefined,+ currentFolderId: FolderId | null,+ diskRevision: number,+ setFolderError: (message: string) => void,+) {+ const { t } = useTranslation();+ const { registerDiskSubfolders } = useFolders();+ const [diskEntries, setDiskEntries] = useState<DiskFileEntry[]>([]);+ const [diskLoading, setDiskLoading] = useState(false);++ useEffect(() => {+ if (!currentLocalDirectory || !canListDirectory) {+ setDiskEntries((prev) => (prev.length > 0 ? [] : prev));+ setDiskLoading(false);+ return;+ }+ let cancelled = false;+ const load = async (background: boolean) => {+ if (!background) setDiskLoading(true);+ try {+ const listed = await listDirectory(currentLocalDirectory);+ if (cancelled) return;+ const files = listed?.files ?? [];+ setDiskEntries((prev) =>+ listingSignature(prev) === listingSignature(files) ? prev : files,+ );+ if (currentFolderId !== null) {+ registerDiskSubfolders(+ currentFolderId,+ (listed?.directories ?? []).map((dir) => ({+ id: diskFolderId(dir.path),+ kind: "local" as const,+ name: dir.name,+ parentFolderId: currentFolderId,+ directory: dir.path,+ color: pickFolderColor(dir.name),+ createdAt: 0,+ updatedAt: 0,+ })),+ );+ }+ } catch (err) {+ console.warn("[useDiskFolder] disk listing failed", err);+ if (!cancelled && !background) {+ setDiskEntries([]);+ setFolderError(+ err instanceof Error+ ? t("filesPage.error.readFolderFailedDetail", {+ message: err.message,+ defaultValue: `Could not read the folder: ${err.message}`,+ })+ : t(+ "filesPage.error.readFolderFailed",+ "Could not read the folder.",+ ),+ );+ }+ } finally {+ if (!cancelled && !background) setDiskLoading(false);+ }+ };+ void load(false);+ const timer = setInterval(() => void load(true), 4000);+ return () => {+ cancelled = true;+ clearInterval(timer);+ };+ }, [+ currentLocalDirectory,+ currentFolderId,+ registerDiskSubfolders,+ setFolderError,+ diskRevision,+ t,+ ]);++ return { diskEntries, diskLoading };+}++function listingSignature(+ files: { path: string; sizeBytes: number; lastModified: number }[],+): string {+ return files+ .map((file) => `${file.path}|${file.sizeBytes}|${file.lastModified}`)+ .join("\n");+}diff --git a/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsx b/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsxnew file mode 100644index 0000000000..96d2e55958--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useFolderFileStates.test.tsx@@ -0,0 +1,178 @@+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, test, vi } from "vitest";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClientProvider } from "@tanstack/react-query";+import { createAppQueryClient } from "@app/query/queryClient";+import { useFolderFileStates } from "@app/components/filesPage/useFolderFileStates";+import type { MountedFileState } from "@app/hooks/useProcessingFolders";+import {+ resetTabVisibility,+ setTabHidden,+} from "@app/tests/utils/tabVisibility";++const { listFiles } = vi.hoisted(() => ({+ listFiles: vi.fn<() => Promise<MountedFileState[]>>(),+}));++vi.mock("@app/hooks/useProcessingFolders", () => ({+ useProcessingFolders: () => ({ listFiles }),+}));++function queryWrapper() {+ const client = createAppQueryClient();+ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={client}>{children}</QueryClientProvider>+ );+}++beforeEach(() => {+ listFiles+ .mockReset()+ .mockResolvedValue([+ { name: "report.pdf", state: "done", hasOriginal: true },+ ]);+});++afterEach(() => {+ cleanup();+ resetTabVisibility();+ vi.useRealTimers();+});++test("library and picker share a read and immediately reflect a restore", async () => {+ const { result } = renderHook(+ () => ({+ library: useFolderFileStates("folder", true),+ picker: useFolderFileStates("folder", true),+ }),+ { wrapper: queryWrapper() },+ );+ await waitFor(() =>+ expect(result.current.picker.fileStates.get("report.pdf")).toBe("done"),+ );+ expect(listFiles).toHaveBeenCalledOnce();+ expect(result.current.library.revertables.has("report.pdf")).toBe(true);++ act(() =>+ result.current.library.patchProcessingFile("report.pdf", {+ state: "waiting",+ hasOriginal: false,+ }),+ );++ await waitFor(() =>+ expect(result.current.picker.fileStates.get("report.pdf")).toBe("waiting"),+ );+ expect(result.current.library.fileStates.get("report.pdf")).toBe("waiting");+ expect(result.current.picker.revertables.has("report.pdf")).toBe(false);+ expect(listFiles).toHaveBeenCalledOnce();+});++test("polling pauses while hidden and resumes when visible", async () => {+ vi.useFakeTimers();+ renderHook(() => useFolderFileStates("folder", true), {+ wrapper: queryWrapper(),+ });+ await act(async () => vi.advanceTimersByTimeAsync(1));+ expect(listFiles).toHaveBeenCalledOnce();++ await act(async () => {+ setTabHidden(true);+ await vi.advanceTimersByTimeAsync(30_000);+ });+ expect(listFiles).toHaveBeenCalledOnce();++ await act(async () => {+ setTabHidden(false);+ await vi.advanceTimersByTimeAsync(3001);+ });+ expect(listFiles).toHaveBeenCalledTimes(2);+});++test("a late reply cannot replace the newly opened folder's states", async () => {+ let finishPrevious!: (files: MountedFileState[]) => void;+ listFiles.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishPrevious = resolve;+ }),+ );+ const { result, rerender } = renderHook(+ (recordId) => useFolderFileStates(recordId, true),+ { initialProps: "previous", wrapper: queryWrapper() },+ );+ await waitFor(() => expect(listFiles).toHaveBeenCalledOnce());+ rerender("current");+ await waitFor(() =>+ expect(result.current.fileStates.get("report.pdf")).toBe("done"),+ );++ await act(async () => {+ finishPrevious([{ name: "old.pdf", state: "failed" }]);+ });+ expect(result.current.fileStates.get("report.pdf")).toBe("done");+ expect(result.current.fileStates.has("old.pdf")).toBe(false);+});++function show() {+ return renderHook(({ id, enabled }) => useFolderFileStates(id, enabled), {+ initialProps: { id: "folder-one", enabled: true },+ wrapper: queryWrapper(),+ });+}++describe("processing file locks", () => {+ beforeEach(() => vi.useFakeTimers());+ it("locks unlisted, queued and processing files until a terminal state arrives", async () => {+ listFiles.mockResolvedValue([+ { name: "queued.pdf", state: "waiting" },+ { name: "active.pdf", state: "processing" },+ { name: "done.pdf", state: "done" },+ { name: "failed.pdf", state: "failed" },+ ]);+ const { result } = show();+ expect(result.current.processingLockedFor("new.pdf")).toBe(true);+ await act(async () => vi.advanceTimersByTimeAsync(1));+ expect(result.current.processingLockedFor("queued.pdf")).toBe(true);+ expect(result.current.processingLockedFor("active.pdf")).toBe(true);+ expect(result.current.processingLockedFor("done.pdf")).toBe(false);+ expect(result.current.processingLockedFor("failed.pdf")).toBe(false);++ listFiles.mockResolvedValue([{ name: "queued.pdf", state: "done" }]);+ await act(async () => vi.advanceTimersByTimeAsync(3001));+ expect(result.current.processingLockedFor("queued.pdf")).toBe(false);+ });++ it("releases locks after three failed polls and restores them when polling recovers", async () => {+ listFiles.mockRejectedValue(new Error("Server unavailable"));+ const { result } = show();+ await act(async () => vi.advanceTimersByTimeAsync(1));+ expect(result.current.processingLockedFor("queued.pdf")).toBe(true);+ await act(async () => vi.advanceTimersByTimeAsync(3001));+ expect(result.current.processingLockedFor("queued.pdf")).toBe(true);+ await act(async () => vi.advanceTimersByTimeAsync(3001));+ expect(listFiles).toHaveBeenCalledTimes(3);+ expect(result.current.processingStatesUnavailable).toBe(true);+ expect(result.current.processingLockedFor("queued.pdf")).toBe(false);++ listFiles.mockResolvedValue([{ name: "queued.pdf", state: "waiting" }]);+ await act(async () => vi.advanceTimersByTimeAsync(3001));+ expect(result.current.processingStatesUnavailable).toBe(false);+ expect(result.current.processingLockedFor("queued.pdf")).toBe(true);+ });++ it("does not carry failed polls into another folder or lock an inactive view", async () => {+ listFiles.mockRejectedValue(new Error("Server unavailable"));+ const { result, rerender } = show();+ await act(async () => vi.advanceTimersByTimeAsync(6003));+ expect(result.current.processingStatesUnavailable).toBe(true);++ rerender({ id: "folder-two", enabled: true });+ await act(async () => vi.advanceTimersByTimeAsync(1));+ expect(result.current.processingStatesUnavailable).toBe(false);+ expect(result.current.processingLockedFor("new.pdf")).toBe(true);++ rerender({ id: "folder-two", enabled: false });+ expect(result.current.processingLockedFor("new.pdf")).toBe(false);+ });+});diff --git a/frontend/editor/src/core/components/filesPage/useFolderFileStates.ts b/frontend/editor/src/core/components/filesPage/useFolderFileStates.tsnew file mode 100644index 0000000000..3868cb8847--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useFolderFileStates.ts@@ -0,0 +1,124 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import type { DiskFileState } from "@app/components/filesPage/FileGrid";+import {+ useProcessingFolders,+ type MountedFileState,+} from "@app/hooks/useProcessingFolders";+import { qk } from "@app/query/keys";++const PROCESSING_FILES_POLL_MS = 3000;+const PROCESSING_FILES_FAILURE_LIMIT = 3;+const EMPTY_FILE_STATES: ReadonlyMap<string, DiskFileState> = new Map();+const EMPTY_REVERTABLES: ReadonlySet<string> = new Set();++/**+ * Shares processing states between library views; polling pauses while the browser tab is hidden.+ * Files stay locked until done or failed; three failed polls release locks until status recovers.+ */+export function useFolderFileStates(+ processingRecordId: string | undefined,+ enabled: boolean,+) {+ const { listFiles } = useProcessingFolders();+ const queryClient = useQueryClient();+ const processingFilesKey = qk.processingFolderFiles(processingRecordId ?? "");+ const {+ data: processingFiles,+ dataUpdatedAt: processingFilesUpdatedAt,+ errorUpdatedAt: processingFilesErrorAt,+ status: processingFilesStatus,+ } = useQuery({+ queryKey: processingFilesKey,+ queryFn: () => listFiles(processingRecordId!),+ enabled: enabled && Boolean(processingRecordId),+ refetchInterval: PROCESSING_FILES_POLL_MS,+ retry: false,+ });++ const activeProcessingKey = enabled ? (processingRecordId ?? "") : "";+ const [processingPollFailures, setProcessingPollFailures] = useState({+ key: "",+ count: 0,+ });+ const processingPollEvent = useRef({ key: "", updatedAt: 0 });+ useEffect(() => {+ const key = activeProcessingKey;+ if (processingPollEvent.current.key !== key) {+ processingPollEvent.current = { key, updatedAt: 0 };+ setProcessingPollFailures({ key, count: 0 });+ }+ if (!key) return;++ const updatedAt =+ processingFilesStatus === "error"+ ? processingFilesErrorAt+ : processingFilesUpdatedAt;+ if (!updatedAt || updatedAt <= processingPollEvent.current.updatedAt)+ return;++ processingPollEvent.current.updatedAt = updatedAt;+ setProcessingPollFailures((failures) => ({+ key,+ count:+ processingFilesStatus === "error"+ ? (failures.key === key ? failures.count : 0) + 1+ : 0,+ }));+ }, [+ activeProcessingKey,+ processingFilesErrorAt,+ processingFilesStatus,+ processingFilesUpdatedAt,+ ]);+ const processingStatesUnavailable =+ processingPollFailures.key === activeProcessingKey &&+ processingPollFailures.count >= PROCESSING_FILES_FAILURE_LIMIT;++ const fileStates = useMemo(+ () =>+ processingFiles+ ? new Map(processingFiles.map((file) => [file.name, file.state]))+ : EMPTY_FILE_STATES,+ [processingFiles],+ );+ const revertables = useMemo(+ () =>+ processingFiles+ ? new Set(+ processingFiles+ .filter((file) => file.hasOriginal)+ .map((file) => file.name),+ )+ : EMPTY_REVERTABLES,+ [processingFiles],+ );+ const patchProcessingFile = useCallback(+ (name: string, patch: Partial<MountedFileState>) =>+ queryClient.setQueryData<MountedFileState[]>(+ processingFilesKey,+ (previous) =>+ previous?.map((file) =>+ file.name === name ? { ...file, ...patch } : file,+ ),+ ),+ [queryClient, processingFilesKey],+ );++ const processingLockedFor = useCallback(+ (name: string): boolean => {+ if (!activeProcessingKey || processingStatesUnavailable) return false;+ const state = fileStates.get(name);+ return state !== "done" && state !== "failed";+ },+ [activeProcessingKey, processingStatesUnavailable, fileStates],+ );++ return {+ fileStates,+ revertables,+ patchProcessingFile,+ processingLockedFor,+ processingStatesUnavailable,+ };+}diff --git a/frontend/editor/src/core/components/filesPage/useLibraryFiles.ts b/frontend/editor/src/core/components/filesPage/useLibraryFiles.tsnew file mode 100644index 0000000000..e1c5e0468e--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useLibraryFiles.ts@@ -0,0 +1,196 @@+import { useMemo } from "react";+import { useFolders } from "@app/contexts/FolderContext";+import type {+ FilesPageOriginFilter,+ FilesPageSortMode,+ FilesPageTab,+} from "@app/contexts/FilesPageContext";+import type { StirlingFileStub } from "@app/types/fileContext";+import { FolderId, folderKind } from "@app/types/folder";+import type { DiskFileEntry } from "@app/services/localFolderContents";+import { libraryFileDate } from "@app/components/filesPage/libraryFileDate";+import {+ getFileOrigin,+ isUnfiledLocalFile,+} from "@app/components/filesPage/fileOrigin";++export interface LibraryFilters {+ currentFolderId: FolderId | null;+ currentTab: FilesPageTab;+ search: string;+ sortMode: FilesPageSortMode;+ originFilter: FilesPageOriginFilter;+ typeFilter: string[];+}++/** Shares folder scoping, filtering and ordering without owning navigation or selection. */+export function useLibraryFiles({+ allFiles,+ currentFolderId,+ currentTab,+ search,+ sortMode,+ originFilter,+ typeFilter,+ diskEntries,+ stagedFiles,+}: LibraryFilters & {+ allFiles: StirlingFileStub[];+ diskEntries?: DiskFileEntry[];+ /** Uncommitted imports follow library and Recents filters without belonging to a stored folder. */+ stagedFiles?: StirlingFileStub[];+}) {+ const { folders: folderRecords, foldersById } = useFolders();+ const subtreeFolderIds = useMemo(() => {+ const set = new Set<FolderId | null>();+ set.add(currentFolderId);+ const childMap = new Map<FolderId | null, FolderId[]>();+ for (const f of folderRecords) {+ const list = childMap.get(f.parentFolderId) ?? [];+ list.push(f.id);+ childMap.set(f.parentFolderId, list);+ }+ const stack: (FolderId | null)[] = [currentFolderId];+ while (stack.length > 0) {+ const cur = stack.pop()!;+ for (const childId of childMap.get(cur) ?? []) {+ if (set.has(childId)) continue;+ set.add(childId);+ stack.push(childId);+ }+ }+ return set;+ }, [folderRecords, currentFolderId]);++ const visibleFolders = useMemo(() => {+ if (+ currentTab === "recent" ||+ currentTab === "shared" ||+ currentTab === "sharedByMe"+ ) {+ return [];+ }+ const lc = search.toLowerCase();+ const matched = folderRecords.filter((f) => {+ if (currentTab === "cloud" && folderKind(f) !== "server") return false;+ if (originFilter !== "all") {+ const folderOrigin = folderKind(f) === "server" ? "cloud" : "local";+ if (folderOrigin !== originFilter) return false;+ }+ if (search) {+ return (+ f.id !== currentFolderId &&+ subtreeFolderIds.has(f.parentFolderId) &&+ f.name.toLowerCase().includes(lc)+ );+ }+ return f.parentFolderId === currentFolderId;+ });+ return matched.sort((a, b) =>+ a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),+ );+ }, [+ folderRecords,+ currentFolderId,+ search,+ currentTab,+ subtreeFolderIds,+ originFilter,+ ]);+ const filesInCurrentFolder = useMemo(() => {+ switch (currentTab) {+ case "cloud":+ case "all":+ return allFiles.filter((f) => {+ if (currentTab === "cloud" && f.remoteStorageId == null) return false;+ const folder = f.folderId ? foldersById.get(f.folderId) : undefined;+ if (isUnfiledLocalFile(f, foldersById)) return false;+ const effectiveFolder =+ folder &&+ ((currentTab !== "cloud" && originFilter !== "cloud") ||+ folderKind(folder) === "server")+ ? folder.id+ : null;+ if (search) return subtreeFolderIds.has(effectiveFolder);+ return effectiveFolder === currentFolderId;+ });+ case "recent":+ return allFiles;+ case "shared":+ return allFiles.filter((f) => f.remoteOwnedByCurrentUser === false);+ case "sharedByMe":+ return allFiles.filter(+ (f) =>+ f.remoteOwnedByCurrentUser !== false &&+ (f.remoteHasShareLinks === true || f.remoteHasUserShares === true),+ );+ }+ }, [+ allFiles,+ currentFolderId,+ currentTab,+ originFilter,+ search,+ subtreeFolderIds,+ foldersById,+ ]);++ const stagedInScope =+ currentTab === "all" || currentTab === "recent" ? stagedFiles : undefined;+ const filesInScope = useMemo(+ () =>+ stagedInScope+ ? [...stagedInScope, ...filesInCurrentFolder]+ : filesInCurrentFolder,+ [stagedInScope, filesInCurrentFolder],+ );++ const availableTypes = useMemo(() => {+ const set = new Set(typeFilter);+ for (const f of diskEntries+ ? [...diskEntries, ...(stagedInScope ?? [])]+ : filesInScope) {+ const ext = (f.name.split(".").pop() ?? "").toUpperCase();+ if (ext) set.add(ext);+ }+ return Array.from(set).sort();+ }, [filesInScope, diskEntries, stagedInScope, typeFilter]);++ const visibleFiles = useMemo(() => {+ const filtered = filesInScope+ .filter((f) =>+ search ? f.name.toLowerCase().includes(search.toLowerCase()) : true,+ )+ .filter((f) =>+ originFilter === "all" ? true : getFileOrigin(f) === originFilter,+ )+ .filter((f) => {+ if (typeFilter.length === 0) return true;+ const ext = (f.name.split(".").pop() ?? "").toUpperCase();+ return typeFilter.includes(ext);+ });+ return filtered.sort((a, b) => {+ switch (sortMode) {+ case "name-asc":+ return a.name.localeCompare(b.name);+ case "name-desc":+ return b.name.localeCompare(a.name);+ case "modified-asc":+ return (+ libraryFileDate(a, currentTab) - libraryFileDate(b, currentTab)+ );+ case "size-desc":+ return (b.size ?? 0) - (a.size ?? 0);+ case "size-asc":+ return (a.size ?? 0) - (b.size ?? 0);+ case "modified-desc":+ default:+ return (+ libraryFileDate(b, currentTab) - libraryFileDate(a, currentTab)+ );+ }+ });+ }, [filesInScope, search, sortMode, originFilter, typeFilter, currentTab]);++ return { visibleFolders, visibleFiles, availableTypes };+}diff --git a/frontend/editor/src/core/components/filesPage/useLibraryScrollPosition.ts b/frontend/editor/src/core/components/filesPage/useLibraryScrollPosition.tsnew file mode 100644index 0000000000..10e6520694--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useLibraryScrollPosition.ts@@ -0,0 +1,56 @@+import {+ useCallback,+ useLayoutEffect,+ useRef,+ type RefObject,+ type UIEvent,+} from "react";++/** Restores list/grid scroll after a view's rows load; positions belong to this mounted host. */+export function useLibraryScrollPosition(+ root: RefObject<HTMLDivElement | null>,+ viewKey: string,+ loading: boolean,+ entryCount: number,+) {+ const positions = useRef(new Map<string, { top: number; left: number }>());+ const restoring = useRef(false);+ useLayoutEffect(() => {+ if (loading) return;+ const container = root.current;+ const scroller =+ container?.querySelector<HTMLElement>(".files-page-list") ??+ container?.querySelector<HTMLElement>(".files-page-content");+ if (!scroller) return;+ const position = positions.current.get(viewKey) ?? { top: 0, left: 0 };+ const restore = () => {+ scroller.scrollTop = position.top;+ scroller.scrollLeft = position.left;+ };+ restoring.current = true;+ restore();+ // Virtual rows need a frame to measure their new scroll container.+ const frame = requestAnimationFrame(() => {+ restore();+ restoring.current = false;+ });+ return () => cancelAnimationFrame(frame);+ }, [root, viewKey, loading, entryCount]);+ return useCallback(+ (event: UIEvent<HTMLDivElement>) => {+ const target = event.target;+ if (+ restoring.current ||+ loading ||+ !(target instanceof HTMLElement) ||+ !target.matches(".files-page-list, .files-page-content")+ )+ return;+ positions.current.set(viewKey, {+ top: target.scrollTop,+ left: target.scrollLeft,+ });+ },+ [viewKey, loading],+ );+}diff --git a/frontend/editor/src/core/components/filesPage/useLibraryUpload.test.ts b/frontend/editor/src/core/components/filesPage/useLibraryUpload.test.tsnew file mode 100644index 0000000000..b498825981--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useLibraryUpload.test.ts@@ -0,0 +1,134 @@+import { renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useLibraryUpload } from "@app/components/filesPage/useLibraryUpload";+import type { FolderId, FolderRecord } from "@app/types/folder";++const mocks = vi.hoisted(() => ({+ addFiles: vi.fn(),+ writeIntoMount: vi.fn(),+ folders: {+ currentFolderId: null as FolderId | null,+ foldersById: new Map<FolderId, FolderRecord>(),+ setError: vi.fn(),+ },+ library: {+ currentTab: "all",+ moveFilesTo: vi.fn(),+ refresh: vi.fn(),+ bumpDiskRevision: vi.fn(),+ setCurrentTab: vi.fn(),+ setOriginFilter: vi.fn(),+ setSearch: vi.fn(),+ },+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@app/contexts/FolderContext", () => ({+ useFolders: () => mocks.folders,+}));+vi.mock("@app/contexts/FilesPageContext", () => ({+ useFilesPage: () => mocks.library,+}));+vi.mock("@app/hooks/useFileHandler", () => ({+ useFileHandler: () => ({ addFiles: mocks.addFiles }),+}));+vi.mock("@app/services/mountWrites", () => ({+ writeIntoMount: mocks.writeIntoMount,+}));++const folderId = "folder" as FolderId;+const files = [new File(["pdf"], "document.pdf", { type: "application/pdf" })];++function openFolder(kind: FolderRecord["kind"]) {+ mocks.folders.currentFolderId = folderId;+ mocks.folders.foldersById.set(folderId, {+ id: folderId,+ kind,+ name: "Documents",+ parentFolderId: null,+ directory: "/documents",+ createdAt: 0,+ updatedAt: 0,+ });+}++describe("library imports", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.folders.currentFolderId = null;+ mocks.folders.foldersById.clear();+ mocks.library.currentTab = "all";+ mocks.addFiles.mockResolvedValue([{ fileId: "file" }]);+ mocks.writeIntoMount.mockResolvedValue({ failedCount: 0 });+ });++ it("keeps root imports local, opens Recent, and leaves the editor untouched", async () => {+ const { result } = renderHook(() => useLibraryUpload());+ await result.current(files);++ expect(mocks.addFiles).toHaveBeenCalledWith(files, {+ selectFiles: false,+ skipWorkspaceDispatch: true,+ });+ expect(mocks.library.moveFilesTo).not.toHaveBeenCalled();+ expect(mocks.library.refresh).toHaveBeenCalledOnce();+ expect(mocks.library.setCurrentTab).toHaveBeenCalledWith("recent");+ expect(mocks.library.setOriginFilter).toHaveBeenCalledWith("all");+ expect(mocks.library.setSearch).toHaveBeenCalledWith("");+ });++ it("saves imports to the open server folder without changing views", async () => {+ openFolder("server");+ const { result } = renderHook(() => useLibraryUpload());+ await result.current(files);++ expect(mocks.addFiles).toHaveBeenCalledWith(files, {+ selectFiles: false,+ skipWorkspaceDispatch: true,+ folderId,+ });+ expect(mocks.library.moveFilesTo).toHaveBeenCalledWith(["file"], folderId);+ expect(mocks.library.setCurrentTab).not.toHaveBeenCalled();+ });++ it("does not send virtual-folder imports to the server", async () => {+ openFolder("virtual");+ const { result } = renderHook(() => useLibraryUpload());+ await result.current(files);++ expect(mocks.addFiles).toHaveBeenCalledWith(+ files,+ expect.objectContaining({ folderId }),+ );+ expect(mocks.library.moveFilesTo).not.toHaveBeenCalled();+ });++ it("writes to mounted folders and refreshes their disk listing", async () => {+ openFolder("local");+ const { result } = renderHook(() => useLibraryUpload());+ await result.current(files);++ const [directory, entries] = mocks.writeIntoMount.mock.calls[0];+ expect(directory).toBe("/documents");+ expect(entries[0].name).toBe("document.pdf");+ expect(await entries[0].bytes()).toBe(files[0]);+ expect(mocks.library.bumpDiskRevision).toHaveBeenCalledOnce();+ expect(mocks.addFiles).not.toHaveBeenCalled();+ expect(mocks.library.moveFilesTo).not.toHaveBeenCalled();+ });++ it("ignores a remembered folder when importing from Recent", async () => {+ openFolder("server");+ mocks.library.currentTab = "recent";+ const { result } = renderHook(() => useLibraryUpload());+ await result.current(files);++ expect(mocks.addFiles).toHaveBeenCalledWith(+ files,+ expect.not.objectContaining({ folderId }),+ );+ expect(mocks.library.moveFilesTo).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/components/filesPage/useLibraryUpload.ts b/frontend/editor/src/core/components/filesPage/useLibraryUpload.tsnew file mode 100644index 0000000000..75909e25c1--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useLibraryUpload.ts@@ -0,0 +1,84 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { useFolders } from "@app/contexts/FolderContext";+import { useFilesPage } from "@app/contexts/FilesPageContext";+import { useFileHandler } from "@app/hooks/useFileHandler";+import { writeIntoMount } from "@app/services/mountWrites";+import { folderKind } from "@app/types/folder";++/** Imports into the current folder without opening the editor; root imports appear in Recents. */+export function useLibraryUpload() {+ const { t } = useTranslation();+ const folders = useFolders();+ const { currentFolderId } = folders;+ const { addFiles } = useFileHandler();+ const {+ currentTab,+ moveFilesTo,+ refresh,+ bumpDiskRevision,+ setCurrentTab,+ setOriginFilter,+ setSearch,+ } = useFilesPage();++ return useCallback(+ async (files: File[]) => {+ if (files.length === 0) return;+ const target =+ currentTab === "all" || currentTab === "cloud" ? currentFolderId : null;+ const targetFolder = target ? folders.foldersById.get(target) : undefined;+ if (targetFolder && folderKind(targetFolder) === "local") {+ const { failedCount } = await writeIntoMount(+ targetFolder.directory,+ files.map((file) => ({ name: file.name, bytes: async () => file })),+ );+ if (failedCount > 0) {+ folders.setError(+ t("filesPage.moveIntoMountFailed", {+ count: failedCount,+ defaultValue:+ "{{count}} file(s) could not be written into the folder.",+ }),+ );+ }+ bumpDiskRevision();+ return;+ }+ // Keep folder membership if the server upload fails, so the local copy stays reachable.+ const added = await addFiles(files, {+ selectFiles: false,+ skipWorkspaceDispatch: true,+ ...(target ? { folderId: target } : {}),+ });+ const fileIds = added.map((f) => f.fileId);+ if (+ target !== null &&+ fileIds.length > 0 &&+ targetFolder &&+ folderKind(targetFolder) === "server"+ ) {+ await moveFilesTo(fileIds, target);+ }+ await refresh();+ if (target === null && fileIds.length > 0) {+ setCurrentTab("recent");+ setOriginFilter("all");+ setSearch("");+ }+ },+ [+ addFiles,+ currentFolderId,+ currentTab,+ folders,+ moveFilesTo,+ refresh,+ bumpDiskRevision,+ setCurrentTab,+ setOriginFilter,+ setSearch,+ t,+ ],+ );+}diff --git a/frontend/editor/src/core/components/filesPage/useLibraryViewState.test.ts b/frontend/editor/src/core/components/filesPage/useLibraryViewState.test.tsnew file mode 100644index 0000000000..bef6eba454--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useLibraryViewState.test.ts@@ -0,0 +1,82 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { useLibraryViewState } from "@app/components/filesPage/useLibraryViewState";+import type { FolderId } from "@app/types/folder";+import type { FileId } from "@app/types/file";+import type { FilesPageTab } from "@app/contexts/FilesPageContext";++describe("library view memory", () => {+ it("keeps a pending destination's filter updates separate from the visible routed tab", () => {+ const { result, rerender } = renderHook(+ ({ tab }: { tab: FilesPageTab }) => useLibraryViewState("all", tab),+ { initialProps: { tab: "all" as FilesPageTab } },+ );+ act(() => {+ result.current.setSearch("invoice");+ result.current.setCurrentTab("recent");+ result.current.setSearch("draft");+ });+ expect(result.current.currentTab).toBe("all");+ expect(result.current.search).toBe("invoice");+ rerender({ tab: "recent" });+ expect(result.current.currentTab).toBe("recent");+ expect(result.current.search).toBe("draft");+ });++ it("restores folder, filters, ordering and selection independently for each tab", () => {+ const { result } = renderHook(() => useLibraryViewState("all"));+ const folder = "invoices" as FolderId;+ const file = "invoice" as FileId;+ act(() => {+ result.current.setCurrentFolderId(folder);+ result.current.setSearch("invoice");+ result.current.setSortMode("name-desc");+ result.current.setOriginFilter("cloud");+ result.current.setTypeFilter(["PDF"]);+ result.current.setSelectedFileIds(new Set([file]));+ result.current.setCurrentTab("recent");+ result.current.setSearch("notes");+ result.current.setOriginFilter("local");+ });+ expect(result.current.currentFolderId).toBeNull();+ expect(result.current.selectedFileIds.size).toBe(0);+ act(() => result.current.setCurrentTab("all"));+ expect(result.current).toMatchObject({+ currentFolderId: folder,+ search: "invoice",+ sortMode: "name-desc",+ originFilter: "cloud",+ typeFilter: ["PDF"],+ selectedFileIds: new Set([file]),+ });+ act(() => result.current.setCurrentTab("recent"));+ expect(result.current).toMatchObject({+ search: "notes",+ originFilter: "local",+ });+ });++ it("keeps selection when restoring the same folder but clears it when navigating to another", () => {+ const { result } = renderHook(() => useLibraryViewState("all"));+ act(() => {+ result.current.setCurrentFolderId("invoices" as FolderId);+ result.current.setSelectedFileIds(new Set(["invoice" as FileId]));+ result.current.setCurrentFolderId("invoices" as FolderId);+ });+ expect(result.current.selectedFileIds.size).toBe(1);+ act(() => result.current.setCurrentFolderId(null));+ expect(result.current.selectedFileIds.size).toBe(0);+ });++ it("keeps separate hosts independent and makes reselecting the active tab a no-op", () => {+ const picker = renderHook(() => useLibraryViewState("recent"));+ const library = renderHook(() => useLibraryViewState("all"));+ act(() => {+ picker.result.current.setSearch("draft");+ picker.result.current.setCurrentTab("recent");+ });+ expect(picker.result.current.search).toBe("draft");+ expect(library.result.current.search).toBe("");+ expect(library.result.current.currentTab).toBe("all");+ });+});diff --git a/frontend/editor/src/core/components/filesPage/useLibraryViewState.ts b/frontend/editor/src/core/components/filesPage/useLibraryViewState.tsnew file mode 100644index 0000000000..870465e377--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useLibraryViewState.ts@@ -0,0 +1,129 @@+import { useCallback, useState, type SetStateAction } from "react";+import type {+ FilesPageOriginFilter,+ FilesPageSortMode,+ FilesPageTab,+} from "@app/contexts/FilesPageContext";+import type { FileId } from "@app/types/file";+import type { FolderId } from "@app/types/folder";++interface LibraryView {+ currentFolderId: FolderId | null;+ search: string;+ sortMode: FilesPageSortMode;+ originFilter: FilesPageOriginFilter;+ typeFilter: string[];+ selectedFileIds: Set<FileId>;+}++const createView = (): LibraryView => ({+ currentFolderId: null,+ search: "",+ sortMode: "modified-desc",+ originFilter: "all",+ typeFilter: [],+ selectedFileIds: new Set(),+});++/** Remembers each tab for this host's lifetime. A controlled tab keeps routing authoritative during pending navigation. */+export function useLibraryViewState(+ initialTab: FilesPageTab,+ controlledTab?: FilesPageTab,+) {+ const [state, setState] = useState(() => ({+ currentTab: initialTab,+ views: { [initialTab]: createView() } as Partial<+ Record<FilesPageTab, LibraryView>+ >,+ }));+ const update = useCallback((change: (view: LibraryView) => LibraryView) => {+ setState((previous) => {+ const view = previous.views[previous.currentTab]!;+ const next = change(view);+ return next === view+ ? previous+ : {+ ...previous,+ views: { ...previous.views, [previous.currentTab]: next },+ };+ });+ }, []);+ const setCurrentTab = useCallback((currentTab: FilesPageTab) => {+ setState((previous) =>+ previous.currentTab === currentTab+ ? previous+ : {+ currentTab,+ views: {+ ...previous.views,+ [currentTab]: previous.views[currentTab] ?? createView(),+ },+ },+ );+ }, []);+ if (controlledTab !== undefined && state.currentTab !== controlledTab) {+ setCurrentTab(controlledTab);+ }+ const folderForTab = useCallback(+ (tab: FilesPageTab) => state.views[tab]?.currentFolderId ?? null,+ [state.views],+ );+ const setCurrentFolderId = useCallback(+ (currentFolderId: FolderId | null) => {+ update((view) =>+ view.currentFolderId === currentFolderId+ ? view+ : {+ ...view,+ currentFolderId,+ selectedFileIds: new Set(),+ },+ );+ },+ [update],+ );+ const setSearch = useCallback(+ (search: string) => update((view) => ({ ...view, search })),+ [update],+ );+ const setSortMode = useCallback(+ (sortMode: FilesPageSortMode) => update((view) => ({ ...view, sortMode })),+ [update],+ );+ const setOriginFilter = useCallback(+ (originFilter: FilesPageOriginFilter) =>+ update((view) => ({ ...view, originFilter })),+ [update],+ );+ const setTypeFilter = useCallback(+ (typeFilter: string[]) => update((view) => ({ ...view, typeFilter })),+ [update],+ );+ const setSelectedFileIds = useCallback(+ (value: SetStateAction<Set<FileId>>) => {+ update((view) => ({+ ...view,+ selectedFileIds:+ typeof value === "function" ? value(view.selectedFileIds) : value,+ }));+ },+ [update],+ );+ const clearSelection = useCallback(+ () => setSelectedFileIds(new Set()),+ [setSelectedFileIds],+ );+ return {+ ...state.views[state.currentTab]!,+ currentTab: state.currentTab,+ setCurrentTab,+ folderForTab,+ setCurrentFolderId,+ setSearch,+ setSortMode,+ setOriginFilter,+ setTypeFilter,+ setSelectedFileIds,+ clearSelection,+ };+}diff --git a/frontend/editor/src/core/components/filesPage/useOpenFolder.ts b/frontend/editor/src/core/components/filesPage/useOpenFolder.tsindex 7da1feee54..451be99d99 100644--- a/frontend/editor/src/core/components/filesPage/useOpenFolder.ts+++ b/frontend/editor/src/core/components/filesPage/useOpenFolder.ts@@ -1,20 +1,7 @@-import { useCallback } from "react";-import { useNavigate } from "react-router-dom";-+import { useFilesPage } from "@app/contexts/FilesPageContext";import type { FolderId } from "@app/types/folder";-/**- * Open a folder by putting it in the URL, which is what selects it: the library reads- * its current folder back out of the path. Selecting the folder state directly leaves- * the path to an effect that cannot tell such a selection from one the path itself- * made, which is why this is the only way in.- */+/** Opens Stirling library at this folder; the URL drives selection and browser history. */export function useOpenFolder(): (id: FolderId | null) => void {- const navigate = useNavigate();- return useCallback(- (id: FolderId | null) => {- navigate(id === null ? "/files" : `/files/${id}`);- },- [navigate],- );+ return useFilesPage().openFolder;}diff --git a/frontend/editor/src/core/components/filesPage/useRoutedLibraryViewState.test.tsx b/frontend/editor/src/core/components/filesPage/useRoutedLibraryViewState.test.tsxnew file mode 100644index 0000000000..2f416fd7a0--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useRoutedLibraryViewState.test.tsx@@ -0,0 +1,175 @@+import type { ReactNode } from "react";+import { act, render, renderHook } from "@testing-library/react";+import {+ MemoryRouter,+ NavigationType,+ Router,+ useLocation,+ useNavigate,+} from "react-router-dom";+import { describe, expect, it, vi } from "vitest";+import { useRoutedLibraryViewState } from "@app/components/filesPage/useRoutedLibraryViewState";+import type { FileId } from "@app/types/file";+import type { FolderId } from "@app/types/folder";++function setup(initialEntries: string[]) {+ return renderHook(+ () => ({+ ...useRoutedLibraryViewState(),+ location: useLocation(),+ navigate: useNavigate(),+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) => (+ <MemoryRouter initialEntries={initialEntries}>{children}</MemoryRouter>+ ),+ },+ );+}++describe("library browser history", () => {+ it("restores the view when Back cancels a tab transition before its URL commits", () => {+ const navigator = {+ createHref: () => "",+ go: vi.fn(),+ push: vi.fn(),+ replace: vi.fn(),+ };+ let library!: ReturnType<typeof useRoutedLibraryViewState>;+ function Library() {+ library = useRoutedLibraryViewState();+ return null;+ }+ const { rerender } = render(+ <Router+ location="/files/invoices"+ navigationType={NavigationType.Push}+ navigator={navigator}+ >+ <Library />+ </Router>,+ );+ act(() => library.setCurrentTab("recent"));+ expect(library.currentTab).toBe("all");+ expect(navigator.push).toHaveBeenCalledOnce();++ rerender(+ <Router+ location="/files/invoices"+ navigationType={NavigationType.Pop}+ navigator={navigator}+ >+ <Library />+ </Router>,+ );+ expect(library.currentTab).toBe("all");+ expect(library.currentFolderId).toBe("invoices");+ });++ it("opens Recents from a direct link and restores it with Back and Forward", () => {+ const { result } = setup(["/files?view=recent"]);+ expect(result.current.currentTab).toBe("recent");++ act(() => result.current.setCurrentTab("all"));+ expect(result.current.location.search).toBe("");+ expect(result.current.currentTab).toBe("all");++ act(() => result.current.navigate(-1));+ expect(result.current.location.search).toBe("?view=recent");+ expect(result.current.currentTab).toBe("recent");++ act(() => result.current.navigate(1));+ expect(result.current.currentTab).toBe("all");+ });++ it("remembers each tab's filters and selection when history returns to a folder", () => {+ const { result } = setup(["/files/invoices"]);+ const selected = new Set(["invoice" as FileId]);+ act(() => {+ result.current.setSearch("invoice");+ result.current.setSelectedFileIds(selected);+ result.current.setCurrentTab("recent");+ result.current.setSearch("notes");+ result.current.setOriginFilter("local");+ });+ expect(result.current.location.pathname).toBe("/files");+ expect(result.current.location.search).toBe("?view=recent");+ expect(result.current.search).toBe("notes");++ act(() => result.current.navigate(-1));+ expect(result.current).toMatchObject({+ currentTab: "all",+ currentFolderId: "invoices",+ search: "invoice",+ selectedFileIds: selected,+ });++ act(() => result.current.navigate(1));+ expect(result.current).toMatchObject({+ currentTab: "recent",+ currentFolderId: null,+ search: "notes",+ originFilter: "local",+ });++ act(() => result.current.setCurrentTab("all"));+ expect(result.current.location.pathname).toBe("/files/invoices");+ expect(result.current.selectedFileIds).toEqual(selected);+ });++ it("opens a sidebar folder in one history step without changing Recent's filters", () => {+ const { result } = setup(["/files?view=recent"]);+ act(() => {+ result.current.setSearch("draft");+ result.current.setOriginFilter("local");+ result.current.openFolder("invoices" as FolderId);+ result.current.setOriginFilter("all");+ });+ expect(result.current).toMatchObject({+ currentTab: "all",+ currentFolderId: "invoices",+ originFilter: "all",+ });+ expect(result.current.location.search).toBe("");++ act(() => result.current.navigate(-1));+ expect(result.current).toMatchObject({+ currentTab: "recent",+ search: "draft",+ originFilter: "local",+ });++ act(() => result.current.navigate(1));+ expect(result.current.currentFolderId).toBe("invoices");+ });++ it("does not add history entries when the active tab or folder is clicked again", () => {+ const { result } = setup(["/editor", "/files?view=recent"]);+ act(() => result.current.setCurrentTab("recent"));+ act(() => result.current.navigate(-1));+ expect(result.current.location.pathname).toBe("/editor");++ act(() => result.current.navigate(1));+ act(() => result.current.openFolder(null));+ act(() => result.current.openFolder(null));+ act(() => result.current.navigate(-1));+ expect(result.current.location.search).toBe("?view=recent");+ expect(result.current.currentTab).toBe("recent");+ });++ it("restores folder navigation within Stirling library", () => {+ const { result } = setup(["/files/invoices"]);+ act(() => result.current.openFolder("receipts" as FolderId));+ act(() => result.current.navigate(-1));+ expect(result.current.currentTab).toBe("all");+ expect(result.current.currentFolderId).toBe("invoices");+ act(() => result.current.navigate(1));+ expect(result.current.currentFolderId).toBe("receipts");+ });++ it("uses Stirling library for an unrecognized view", () => {+ const { result } = setup(["/files?view=unknown"]);+ expect(result.current.currentTab).toBe("all");+ expect(result.current.currentFolderId).toBeNull();+ });+});diff --git a/frontend/editor/src/core/components/filesPage/useRoutedLibraryViewState.ts b/frontend/editor/src/core/components/filesPage/useRoutedLibraryViewState.tsnew file mode 100644index 0000000000..5b1caf0305--- /dev/null+++ b/frontend/editor/src/core/components/filesPage/useRoutedLibraryViewState.ts@@ -0,0 +1,60 @@+import { useCallback, useEffect } from "react";+import { useLocation, useNavigate } from "react-router-dom";+import { useLibraryViewState } from "@app/components/filesPage/useLibraryViewState";+import type { FilesPageTab } from "@app/contexts/FilesPageContext";+import type { FolderId } from "@app/types/folder";++function tabFromSearch(search: string): FilesPageTab {+ const view = new URLSearchParams(search).get("view");+ switch (view) {+ case "recent":+ case "cloud":+ case "shared":+ case "sharedByMe":+ return view;+ default:+ return "all";+ }+}++/** The page's URL owns its tab and folder; filters and selection stay in per-tab memory. */+export function useRoutedLibraryViewState() {+ const location = useLocation();+ const navigate = useNavigate();+ const routeTab = tabFromSearch(location.search);+ const view = useLibraryViewState(routeTab, routeTab);+ const {+ currentTab,+ setCurrentTab: selectTab,+ folderForTab,+ setCurrentFolderId: rememberFolder,+ } = view;++ useEffect(() => {+ const match = location.pathname.match(/^\/files(?:\/([^/]+))?\/?$/);+ if (!match) return;+ rememberFolder((match[1] as FolderId | undefined) ?? null);+ }, [location.pathname, location.search, rememberFolder]);++ const navigateToView = useCallback(+ (tab: FilesPageTab, folderId: FolderId | null) => {+ const path = folderId === null ? "/files" : `/files/${folderId}`;+ const target = tab === "all" ? path : `${path}?view=${tab}`;+ selectTab(tab);+ if (target !== `${location.pathname}${location.search}`) navigate(target);+ },+ [location.pathname, location.search, navigate, selectTab],+ );+ const setCurrentTab = useCallback(+ (tab: FilesPageTab) => {+ if (tab !== currentTab) navigateToView(tab, folderForTab(tab));+ },+ [currentTab, folderForTab, navigateToView],+ );+ const openFolder = useCallback(+ (id: FolderId | null) => navigateToView("all", id),+ [navigateToView],+ );++ return { ...view, setCurrentTab, openFolder };+}diff --git a/frontend/editor/src/core/components/filesPage/useVirtualFileRows.ts b/frontend/editor/src/core/components/filesPage/useVirtualFileRows.tsindex 65d82a2c6b..9bbea0a3c7 100644--- a/frontend/editor/src/core/components/filesPage/useVirtualFileRows.ts+++ b/frontend/editor/src/core/components/filesPage/useVirtualFileRows.ts@@ -4,11 +4,7 @@ import { useVirtualizer } from "@tanstack/react-virtual";/** Rows above and below the viewport kept mounted, so a fast scroll stays filled. */const OVERSCAN = 3;-/**- * How many columns the grid is actually laying out. Read off the computed style- * rather than recomputed from a breakpoint, so `auto-fill` stays the one place the- * column count is decided.- */+/** Read CSS auto-fill columns so virtualisation uses the grid's actual layout. */function useColumnCount(el: HTMLElement | null): number {const [columns, setColumns] = useState(1);useEffect(() => {@@ -27,11 +23,13 @@ function useColumnCount(el: HTMLElement | null): number {return columns;}-/** The scrolling ancestor the virtualiser measures against. */+/** Lists scroll themselves; the card grid scrolls within its content pane. */function useScrollParent(el: HTMLElement | null): HTMLElement | null {const [parent, setParent] = useState<HTMLElement | null>(null);useEffect(() => {- setParent(el?.closest<HTMLElement>(".files-page-content") ?? null);+ setParent(+ el?.closest<HTMLElement>(".files-page-list, .files-page-content") ?? null,+ );}, [el]);return parent;}@@ -43,18 +41,12 @@ interface VirtualFileRows {padTop: number;padBottom: number;columns: number;- /** Ref for the element the rows live in. */setContainer: (el: HTMLDivElement | null) => void;}/**- * Renders a window of a long file list instead of all of it, as a slice plus a- * spacer at each end. Spacers rather than absolute positioning so the grid keeps- * its own `auto-fill` layout and the list its own row flow.- *- * Stands down - every item rendered, no spacers - until there is a scrolling- * ancestor with a measured height. That covers a short list, the first paint- * before layout, and any environment without real geometry.+ * Virtualises with flow spacers so CSS auto-fill still owns the grid layout.+ * Renders all entries until the scrolling ancestor has a measured height.*/export function useVirtualFileRows(itemCount: number,@@ -102,9 +94,7 @@ export function useVirtualFileRows(};}-// Read once. The root font size is a layout read, and this is called on every render-// of a list whose whole point is not doing needless work. A root restyled mid-session-// keeps the first answer, which only shifts an estimate.+// Cache the layout read; a later root font-size change affects only the height estimate.let rootFontSizePx = 0;/** Card and row heights including their gap, matching contain-intrinsic-size. */diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsxindex 64bea49ec1..f2def18eff 100644--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx@@ -86,8 +86,7 @@ const WATCHED_FOLDER_WORKBENCH_ID = "custom:watchedFolder";const NO_FOLDERS: never[] = [];const NO_POLICIES: never[] = [];-/** Only surface the "Adding files…" progress row for drops big enough that the- * pre-dispatch scan is user-visible; small adds finish before it would paint. */+/** Show pre-dispatch progress only for large drops; small imports finish before it paints. */const BULK_ADD_INDICATOR_MIN = 8;export interface FileSidebarProps {@@ -113,12 +112,7 @@ export interface FileSidebarProps {}>;}-/**- * Slim "Adding files… X/Y" indicator during a bulk drop's pre-dispatch scan, so- * a 200-file folder never looks frozen between drop and rows appearing. A- * SEPARATE component so the per-file progress emissions re-render only this row- * — not the whole sidebar (and its file list) hundreds of times per drop.- */+/** Isolates per-file progress updates from the sidebar's file-list renders. */function BulkAddProgressRow() {const { t } = useTranslation();const bulkAdd = useBulkAddProgress();@@ -145,22 +139,11 @@ function BulkAddProgressRow() {);}-/**- * The library's folder tree, as a section of the file sidebar. Separate so the- * subscription to the library's state belongs to the only part that reads it: that- * state changes on every keystroke in the library's filter, and the sidebar renders- * in every view.- */+/** Isolates library-state subscriptions from the sidebar used by every workspace. */function FolderTreeSection() {- const { t } = useTranslation();const filesPage = useFilesPage();return (<div className="file-sidebar-folders-section sidebar-content-fade">- <div className="file-sidebar-section-header">- <span className="file-sidebar-section-label">- {t("filesPage.tree", "Folders")}- </span>- </div><FolderTreeSidebarfileCounts={filesPage.fileCountsByFolder}onRequestNewFolder={filesPage.openNewFolderDialog}@@ -193,13 +176,12 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(ref,) {const { t } = useTranslation();- // Resolves a file's stored classification label id to its display name.const labelName = useLabelName();// Classification off (non-SaaS / AI-off) → never show the per-row label chip,// even if a stub carries labels from an imported PDF; keeps the row plain.const classificationEnabled = useClassificationEnabled();const nativeFileInputRef = useRef<HTMLInputElement>(null);- // State (not ref) so setting it triggers a re-render - avoids racing addFiles state updates.+ // State schedules the viewer transition after the file enters the workspace.const [pendingViewFileId, setPendingViewFileId] = useState<string | null>(null,);@@ -217,17 +199,13 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const { workbench: currentWorkbench, selectedTool } = useNavigationState();const isWatchedFoldersActive =currentWorkbench === WATCHED_FOLDER_WORKBENCH_ID;- // The folder currently open in the Watched Folders view (null = folder list/home).const watchedFolderView = customWorkbenchViews.find((v) => v.id === WATCHED_FOLDER_VIEW_ID,);const activeWatchedFolderId =(watchedFolderView?.data as WatchedFolderViewData | undefined)?.folderId ?? null;- // fileId → folderId[] across all watch folders. In the Watched Folders view the- // sidebar tick reflects "already in the open folder" instead of workbench- // membership (which is meaningless there - a click sends to the folder, not- // the workbench). The same map drives the per-file membership dots.+ // In Watched Folders, selection means membership of the open folder, not the workspace.const folderMembership = useFolderMembership();const allFolders = useAllWatchedFolders();const policyFileBadges = usePolicyFileBadges();@@ -236,7 +214,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([allFolders],);- // Clicking a file's membership dot jumps straight into that folder.const openWatchedFolder = useCallback((folderId: string) => {setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId });@@ -275,11 +252,8 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const credits = useFreeCreditsSummary();const openPlan = useOpenPlan();- // Leaf files = user-visible files (excludes intermediate tool outputs)const [allFileStubs, setAllFileStubs] = useState<StirlingFileStub[]>([]);- // Files whose stored bytes this session PROVED unreadable. Rows render a- // "data lost" state instead of pretending the file can open; storage keeps- // the record so a reload re-tests it.+ // Keep unreadable records so a reload can retry their bytes.const [lostFileIds, setLostFileIds] = useState<ReadonlySet<string>>(() => new Set(),);@@ -291,11 +265,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([],);const [stubsLoaded, setStubsLoaded] = useState(false);- // Kebab "Save to cloud" target; drives BulkUploadToServerModal.const [saveToServerTarget, setSaveToServerTarget] = useState<StirlingFileStub[] | null>(null);- // Kebab "Version history" target; drives VersionHistoryModal.const [versionHistoryTarget, setVersionHistoryTarget] =useState<StirlingFileStub | null>(null);// Kebab "Delete" target when the file is on the cloud; drives the@@ -303,7 +275,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const [deleteTarget, setDeleteTarget] = useState<StirlingFileStub | null>(null,);- // Kebab "Rename" target; drives RenameFileDialog.const [renameTarget, setRenameTarget] = useState<StirlingFileStub | null>(null,);@@ -316,7 +287,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(// every path - callers never await this, so a rejection goes nowhere.let stubs: StirlingFileStub[] = [];try {- // Leaf files from IDB - same source as the file selection modal.stubs = await indexedDB.loadLeafMetadata();} catch (error) {// Carry on with the in-memory workbench files: an unreadable library@@ -327,7 +297,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(try {const idbIds = new Set(stubs.map((s) => s.id as string));- // Also include workbench files not yet flushed to IDB.const pendingStubs = state.files.ids.map((id) => state.files.byId[id]).filter(@@ -336,7 +305,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>();const allStubs = [...stubs, ...pendingStubs];- // A version swap briefly lists both the old leaf (IDB) and its replacement (workbench); two stubs for one lineage collide on the row key and corrupt React reconciliation, so drop any stub another names as its parent.+ // During a version swap, drop the superseded IDB leaf to avoid duplicate lineage keys.const superseded = new Set(allStubs.map((s) => s.parentFileId as string | undefined),);@@ -353,13 +322,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(}}, [indexedDB, state.files.ids, state.files.byId]);- // Refresh on mount, workbench changes, or external IndexedDB writes —- // COALESCED. refreshStubs is a full IDB metadata scan, and it's re-created on- // every workspace change: during a big folder drop (or a policy wave) that's- // hundreds of triggers (per-file thumbnail hydrations, versioned deliveries),- // which uncoalesced means O(files²) IDB reads and a re-render storm. A short- // trailing throttle turns a burst into one scan per window; the first run- // fires immediately so mount/load isn't delayed.+ // Coalesce per-file updates to avoid quadratic IDB scans during imports and processing.const indexedDBRevision = useIndexedDBRevision();const lastRefreshAt = useRef(0);useEffect(() => {@@ -375,9 +338,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(return () => window.clearTimeout(timer);}, [refreshStubs, indexedDBRevision]);- // Kebab delete: local-only files go immediately (cheap, re-addable). When- // the file is also on the cloud, open the choice dialog so the user picks- // where to remove it from.+ // Server copies require a deletion-scope choice; local-only files delete immediately.const handleSidebarDelete = useCallback(async (fileId: FileId) => {const stub = allFileStubs.find((s) => s.id === fileId);@@ -430,7 +391,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([deleteTarget, fileActions, refreshStubs],);- // Kebab: open the upload-to-server modal for this one file.const handleSaveToCloud = useCallback((fileId: FileId) => {const stub = allFileStubs.find((s) => s.id === fileId);@@ -439,7 +399,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([allFileStubs],);- // Kebab: open the version-history modal for this one file.const handleVersionHistory = useCallback((fileId: FileId) => {const stub = allFileStubs.find((s) => s.id === fileId);@@ -490,7 +449,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([allFileStubs, warnDataUnavailable, t],);- // Kebab: copy the file into the library under a free "(copy)" name.const handleDuplicate = useCallback(async (fileId: FileId) => {const stub = allFileStubs.find((s) => s.id === fileId);@@ -519,7 +477,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([allFileStubs, addFiles, refreshStubs, warnDataUnavailable, t],);- // Kebab: open the rename dialog for this one file.const handleRename = useCallback((fileId: FileId) => {const stub = allFileStubs.find((s) => s.id === fileId);@@ -528,8 +485,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([allFileStubs],);- // The stub name is what the UI and exports read, so a rename is a metadata- // write - storage first, then the workbench copy if the file is open.+ // Persist the rename before updating the open workspace copy.const handleConfirmRename = useCallback(async (name: string) => {const stub = renameTarget;@@ -563,7 +519,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([allFileStubs, openInNewWindow],);- // Once a pending file lands in state, open it in the viewer.useEffect(() => {if (!pendingViewFileId) return;const isInWorkbench = state.files.ids.some(@@ -578,7 +533,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(// SaaS groups by classification label; core returns null → one flat, recency-sorted list.const fileGroups = useFileSidebarGroups(allFileStubs);- // Workbench membership as a Set for O(1) per-row lookups (see renderFileRow).const workbenchIds = useMemo(() => new Set(state.files.ids.map((id) => id as string)),[state.files.ids],@@ -593,7 +547,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(}return counts;}, [allFileStubs]);- // Per-group expand/collapse, falling back to each group's default until toggled.const [groupOpen, setGroupOpen] = useState<Record<string, boolean>>({});const setGroupOpenState = useCallback((id: string, open: boolean) =>@@ -601,7 +554,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>([],);- // Handle Google Driveconst handleGoogleDriveClick = useCallback(async () => {if (!isGoogleDriveEnabled) return;const files = await openGoogleDrivePicker({ multiple: true });@@ -623,7 +575,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(onPickGoogleDriveFiles,]);- // Toggle file in/out of workbenchconst handleFileClick = useCallback(async (fileId: FileId) => {const stub = allFileStubs.find((s) => s.id === fileId);@@ -830,10 +781,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(return () => onRegisterOpenFromComputer(null);}, [onRegisterOpenFromComputer, openNativeFilePicker]);- // Native OS file drop onto the sidebar - mirrors the workbench drop zone.- // Only react to OS file drags ("Files" type); internal element drags (e.g.- // watched-folder file moves) set their own dataTransfer keys and must pass- // through untouched.+ // Internal folder drags have their own payloads and must bypass file ingestion.const [isFileDragOver, setIsFileDragOver] = useState(false);const dragDepth = useRef(0);@@ -878,9 +826,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const eligibleFileIds = useToolEligibleFileIds();- // Render one file row (shared by the flat list and the grouped SaaS layout).const renderFileRow = (stub: StirlingFileStub) => {- // O(1) membership instead of a per-row linear scan of the workbench ids.const isInWorkbench = workbenchIds.has(stub.id as string);const workbenchFileId = isInWorkbench ? (stub.id as FileId) : undefined;const isSelected = isWatchedFoldersActive@@ -917,10 +863,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(const fileOrigin = getFileOrigin(stub);const dataUnavailable =stub.dataUnavailable === true || lostFileIds.has(stub.id as string);- // Key by lineage (originalFileId) so a version swap updates the row in place instead of- // remounting. But a 1-input→many-output op (split) yields sibling leaves that share one- // originalFileId; those would collide on the key, so fall back to the unique leaf id when a- // lineage is present more than once.+ // Lineage keys preserve rows across version changes; split siblings need unique leaf IDs.const lineageKey = (stub.originalFileId ?? stub.id) as string;const rowKey =(lineageCounts.get(lineageKey) ?? 0) > 1@@ -974,6 +917,60 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>();};+ const sidebarActions: NonNullable<FileSidebarProps["extraActions"]> = [+ ...(currentWorkbench === "myFiles"+ ? [+ {+ icon: <Icon name="plus" />,+ label: t("fileSidebar.addFiles", "Add files"),+ onClick: openNativeFilePicker,+ testId: "pdf-library-add-files",+ },+ ...(isGoogleDriveEnabled+ ? [+ {+ icon: <Icon name="googledrive" />,+ label: t(+ "fileSidebar.googleDrive",+ "Open from Google Drive",+ ),+ onClick: () => void handleGoogleDriveClick(),+ testId: "google-drive-button",+ },+ ]+ : []),+ ]+ : []),+ ...(extraActions ?? []),+ ];++ const importActions = (+ <>+ {isGoogleDriveEnabled && (+ <ActionIcon+ variant="quiet"+ className="file-sidebar-section-btn file-sidebar-section-btn-drive"+ onClick={handleGoogleDriveClick}+ title={t("fileSidebar.googleDrive", "Open from Google Drive")}+ aria-label={t("fileSidebar.googleDrive", "Open from Google Drive")}+ data-testid="google-drive-button"+ >+ <Icon name="googledrive" size={16} />+ </ActionIcon>+ )}+ <ActionIcon+ variant="quiet"+ className="file-sidebar-section-btn file-sidebar-section-btn-add"+ data-testid="pdf-library-add-files"+ onClick={openNativeFilePicker}+ title={t("fileSidebar.addFiles", "Add files")}+ aria-label={t("fileSidebar.addFiles", "Add files")}+ >+ <Icon name="plus" size={"1rem"} />+ </ActionIcon>+ </>+ );+return (<divref={ref}@@ -1006,21 +1003,17 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(ref={nativeFileInputRef}type="file"multiple- // No `accept` filter - this picker feeds the global workspace,- // not a specific tool, so users may legitimately upload PNGs,- // ZIPs, etc. for the convert/merge/extract tools to handle.+ // The global workspace accepts all formats for conversion, merging and extraction.style={{ display: "none" }}onChange={handleNativeFilePick}data-testid="file-input"/>- {/* Open from computer lives in quick navigation; what is left here is- the library's own actions, so the box goes when it has none. */}<NavSurfaceclassName="file-sidebar-controls"- hidden={!extraActions?.length}+ hidden={sidebarActions.length === 0}>- {extraActions?.map((action) => (+ {sidebarActions.map((action) => (<React.Fragment key={action.label}>{action.render ? (action.render()@@ -1029,8 +1022,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(label={action.disabledTooltip ?? action.label}position="right"withinPortal- // Only force a wide multiline box when the long disabled- // reason is shown; the short label fits one line.multiline={Boolean(action.disabled && action.disabledTooltip,)}@@ -1039,8 +1030,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(? 220: undefined}- // The row carries its own label, so the tooltip is only- // there to say why it cannot be used.+ // The tooltip explains why an already-labelled action is disabled.disabled={!(action.disabled && action.disabledTooltip)}><div@@ -1075,12 +1065,8 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>())}</NavSurface>- {/* Box 2 — the file tree (this box scrolls). */}<NavSurface className="file-sidebar-files-box"><div className="file-sidebar-scroll">- {/* The library browses folders, so there the box carries the tree the- file list would otherwise fill: one sidebar, its contents following- the view. */}{currentWorkbench === "myFiles" && <FolderTreeSection />}{currentWorkbench !== "myFiles" && (@@ -1106,34 +1092,7 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(><Icon name="maximize-2" size={"1rem"} /></ActionIcon>- {isGoogleDriveEnabled && (- <ActionIcon- variant="quiet"- className="file-sidebar-section-btn file-sidebar-section-btn-drive"- onClick={handleGoogleDriveClick}- title={t(- "fileSidebar.googleDrive",- "Open from Google Drive",- )}- aria-label={t(- "fileSidebar.googleDrive",- "Open from Google Drive",- )}- data-testid="google-drive-button"- >- <Icon name="googledrive" size={16} />- </ActionIcon>- )}- <ActionIcon- variant="quiet"- className="file-sidebar-section-btn file-sidebar-section-btn-add"- data-testid="pdf-library-add-files"- onClick={openNativeFilePicker}- title={t("fileSidebar.addFiles", "Add files")}- aria-label={t("fileSidebar.addFiles", "Add files")}- >- <Icon name="plus" size={"1rem"} />- </ActionIcon>+ {importActions}</div><BulkAddProgressRow />@@ -1246,12 +1205,9 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(</div></NavSurface>- {/* Offer to process a folder of files (e.g. Downloads), beneath the- files section. Empty in builds without a policy engine. */}<SidebarProcessingSlot /></div>- {/* Kebab "Save to cloud" upload modal (one file at a time). */}<BulkUploadToServerModalopened={Boolean(saveToServerTarget && saveToServerTarget.length > 0)}onClose={() => setSaveToServerTarget(null)}@@ -1259,7 +1215,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(onUploaded={refreshStubs}/>- {/* Kebab "Version history" modal. */}<VersionHistoryModalopened={Boolean(versionHistoryTarget)}onClose={() => setVersionHistoryTarget(null)}@@ -1267,7 +1222,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(onChanged={refreshStubs}/>- {/* Kebab "Rename" dialog. */}<RenameFileDialogopened={Boolean(renameTarget)}fileName={renameTarget?.name ?? ""}@@ -1275,7 +1229,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(onSubmit={handleConfirmRename}/>- {/* Cloud-aware delete choice (only opened for cloud-uploaded files). */}<DeleteFilesDialogopened={Boolean(deleteTarget)}files={deleteTarget ? [deleteTarget] : []}@@ -1286,7 +1239,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>({/* Getting-started checklist, floating above the footer (SaaS only). */}<SidebarChecklistSlot />- {/* Box 3 — the shared footer: credits, plan, and the account row unless hoisted. */}<NavFooterclassName="file-sidebar-footer-box"displayName={displayName}diff --git a/frontend/editor/src/core/components/shared/LandingActions.tsx b/frontend/editor/src/core/components/shared/LandingActions.tsxindex 16205adcec..d70ee5d6ec 100644--- a/frontend/editor/src/core/components/shared/LandingActions.tsx+++ b/frontend/editor/src/core/components/shared/LandingActions.tsx@@ -4,11 +4,13 @@ import { Button } from "@app/ui/Button";import { ActionIcon } from "@app/ui/ActionIcon";import { Icon } from "@app/ui/Icon";import { useFilesModalContext } from "@app/contexts/FilesModalContext";+import { useFilesPage } from "@app/contexts/FilesPageContext";+import { useFolders } from "@app/contexts/FolderContext";import { useFileActionTerminology } from "@app/hooks/useFileActionTerminology";-import { useFileActionIcons } from "@app/hooks/useFileActionIcons";import { useAppConfig } from "@app/contexts/AppConfigContext";import { useIsMobile } from "@app/hooks/useIsMobile";import { CreateProcessingFolderButton } from "@app/components/policies/CreateProcessingFolderButton";+import { folderKind } from "@app/types/folder";type LandingActionsProps = {fileInputRef: React.RefObject<HTMLInputElement | null>;@@ -25,31 +27,30 @@ export function LandingActions({}: LandingActionsProps) {const terminology = useFileActionTerminology();const { openFilesModal } = useFilesModalContext();- const icons = useFileActionIcons();+ const { allFiles, loading } = useFilesPage();+ const folders = useFolders();const { config } = useAppConfig();const isMobile = useIsMobile();+ // Mounted directories are listed on demand, so their files may not be cached yet.+ const hasMountedFolders = folders.folders.some(+ (folder) => folderKind(folder) === "local",+ );+ const libraryEmpty =+ !loading && !folders.loading && allFiles.length === 0 && !hasMountedFolders;return (<><Group gap="sm" justify="center" wrap="wrap" mb="xs"><Button- fat- leftSection={<Icon name={icons.upload} size="1rem" />}- onClick={(e) => {- e.stopPropagation();- onUploadClick();- }}- >- {terminology.uploadFromComputer}- </Button>-- <Button- variant="secondary"fatleftSection={<Icon name="plus" size="1rem" />}onClick={(e) => {e.stopPropagation();- openFilesModal();+ if (libraryEmpty) {+ onUploadClick();+ } else {+ openFilesModal();+ }}}>{terminology.addFiles}diff --git a/frontend/editor/src/core/components/shared/LandingPage.tsx b/frontend/editor/src/core/components/shared/LandingPage.tsxindex 5363e596ce..5515201f21 100644--- a/frontend/editor/src/core/components/shared/LandingPage.tsx+++ b/frontend/editor/src/core/components/shared/LandingPage.tsx@@ -7,10 +7,12 @@ import MobileUploadModal from "@app/components/shared/MobileUploadModal";import { openFilesFromDisk } from "@app/services/openFilesFromDisk";import { Logo } from "@app/ui/Logo";import { LandingActions } from "@app/components/shared/LandingActions";+import { useDropzoneFiles } from "@app/hooks/useDropzoneFiles";import "@app/components/shared/LandingPage.css";const LandingPage = () => {const { addFiles } = useFileHandler();+ const getDropzoneFiles = useDropzoneFiles();const fileInputRef = React.useRef<HTMLInputElement | null>(null);const terminology = useFileActionTerminology();const [mobileUploadModalOpen, setMobileUploadModalOpen] = useState(false);@@ -57,6 +59,8 @@ const LandingPage = () => {onDrop={handleFileDrop}multipleactivateOnClick={false}+ useFsAccessApi={false}+ getFilesFromEvent={getDropzoneFiles}enablePointerEventsaria-label={terminology.dropFilesHere}className="landing-dropzone flex min-h-0 flex-1 cursor-default flex-col items-center justify-center border-none bg-transparent px-4 py-8 shadow-none outline-none"diff --git a/frontend/editor/src/core/contexts/FileManagerContext.tsx b/frontend/editor/src/core/contexts/FileManagerContext.tsxdeleted file mode 100644index 2a63294c83..0000000000--- a/frontend/editor/src/core/contexts/FileManagerContext.tsx+++ /dev/null@@ -1,1271 +0,0 @@-import React, {- createContext,- useContext,- useState,- useRef,- useCallback,- useEffect,- useMemo,-} from "react";-import { Group, Modal, Stack, Text } from "@mantine/core";-import { Button } from "@app/ui/Button";-import { fileStorage } from "@app/services/fileStorage";-import { useFileActions, useFileManagement } from "@app/contexts/FileContext";-import { zipFileService } from "@app/services/zipFileService";-import { StirlingFileStub } from "@app/types/fileContext";-import { downloadFiles } from "@app/utils/downloadUtils";-import { FileId } from "@app/types/file";-import { groupFilesByOriginal } from "@app/utils/fileHistoryUtils";-import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@app/styles/zIndex";-import apiClient from "@app/services/apiClient";-import { alert } from "@app/components/toast";-import {- extractLatestFilesFromBundle,- parseContentDispositionFilename,- readResponseHeader,-} from "@app/services/shareBundleUtils";-import { useTranslation } from "react-i18next";-import { openFilesFromDisk } from "@app/services/openFilesFromDisk";-export { pendingFilePathMappings } from "@app/services/pendingFilePathMappings";--// Type for the context value - now contains everything directly-interface FileManagerContextValue {- // State- activeSource: "recent" | "local" | "drive";- storageFilter: "all" | "local" | "sharedWithMe" | "sharedByMe";- selectedFileIds: FileId[];- searchTerm: string;- selectedFiles: StirlingFileStub[];- filteredFiles: StirlingFileStub[];- fileInputRef: React.RefObject<HTMLInputElement | null>;- selectedFilesSet: Set<FileId>;- expandedFileIds: Set<FileId>;- fileGroups: Map<FileId, StirlingFileStub[]>;- loadedHistoryFiles: Map<FileId, StirlingFileStub[]>;- isLoading: boolean;- activeFileIds: FileId[];-- // Handlers- onSourceChange: (source: "recent" | "local" | "drive") => void;- onStorageFilterChange: (- filter: "all" | "local" | "sharedWithMe" | "sharedByMe",- ) => void;- onLocalFileClick: () => void;- onFileSelect: (- file: StirlingFileStub,- index: number,- shiftKey?: boolean,- ) => void;- onFileRemove: (index: number) => void;- onHistoryFileRemove: (file: StirlingFileStub) => void;- onFileDoubleClick: (file: StirlingFileStub) => void;- onOpenFiles: () => void;- onSearchChange: (value: string) => void;- onFileInputChange: (event: React.ChangeEvent<HTMLInputElement>) => void;- onSelectAll: () => void;- onDeleteSelected: () => void;- onDownloadSelected: () => void;- onDownloadSingle: (file: StirlingFileStub) => void;- onToggleExpansion: (fileId: FileId) => void;- onAddToRecents: (file: StirlingFileStub) => void;- onUnzipFile: (file: StirlingFileStub) => Promise<void>;- onMakeCopy: (file: StirlingFileStub) => Promise<void>;- onNewFilesSelect: (files: File[]) => void;- onGoogleDriveSelect: (files: File[]) => void;- refreshRecentFiles: () => Promise<void>;-- // External props- recentFiles: StirlingFileStub[];- isFileSupported: (fileName: string) => boolean;- modalHeight: string;-}--// Create the context-const FileManagerContext = createContext<FileManagerContextValue | null>(null);--// Provider component props-interface FileManagerProviderProps {- children: React.ReactNode;- recentFiles: StirlingFileStub[];- onRecentFilesSelected: (files: StirlingFileStub[]) => void; // For selecting stored files- onNewFilesSelect: (files: File[]) => void; // For uploading new local files- onClose: () => void;- isFileSupported: (fileName: string) => boolean;- isOpen: boolean;- onFileRemove: (index: number) => void;- onBulkRemove?: (fileIds: FileId[]) => void;- modalHeight: string;- refreshRecentFiles: () => Promise<void>;- isLoading: boolean;- activeFileIds: FileId[];- maxSelectable?: number | null;-}--type RemoteDeleteChoice = "local" | "server" | "both" | "leave" | "cancel";--export const FileManagerProvider: React.FC<FileManagerProviderProps> = ({- children,- recentFiles,- onRecentFilesSelected,- onNewFilesSelect,- onClose,- isFileSupported,- isOpen,- onFileRemove,- onBulkRemove,- modalHeight,- refreshRecentFiles,- isLoading,- activeFileIds,- maxSelectable = null,-}) => {- const [activeSource, setActiveSource] = useState<- "recent" | "local" | "drive"- >("recent");- const [storageFilter, setStorageFilter] = useState<- "all" | "local" | "sharedWithMe" | "sharedByMe"- >("all");- const [selectedFileIds, setSelectedFileIds] = useState<FileId[]>(- () => activeFileIds,- );- const [searchTerm, setSearchTerm] = useState("");- const [lastClickedIndex, setLastClickedIndex] = useState<number | null>(null);- const [expandedFileIds, setExpandedFileIds] = useState<Set<FileId>>(- new Set(),- );- const [loadedHistoryFiles, setLoadedHistoryFiles] = useState<- Map<FileId, StirlingFileStub[]>- >(new Map()); // Cache for loaded history- const fileInputRef = useRef<HTMLInputElement>(null);- const [deletePromptFile, setDeletePromptFile] =- useState<StirlingFileStub | null>(null);- const deletePromptResolveRef = useRef<- ((choice: RemoteDeleteChoice) => void) | null- >(null);- const { t } = useTranslation();- const { actions } = useFileActions();- const { removeFiles } = useFileManagement();-- // Re-seed selection with active file IDs each time the modal opens- useEffect(() => {- if (isOpen) {- setSelectedFileIds(activeFileIds);- }- }, [isOpen, activeFileIds]);-- // Track blob URLs for cleanup- const createdBlobUrls = useRef<Set<string>>(new Set());-- // Computed values (with null safety)- const selectedFilesSet = new Set(selectedFileIds);-- // Group files by original file ID for version management- const fileGroups = useMemo(() => {- if (!recentFiles || recentFiles.length === 0) return new Map();-- // Convert StirlingFileStub to FileRecord-like objects for grouping utility- const recordsForGrouping = recentFiles.map((file) => ({- ...file,- originalFileId: file.originalFileId,- versionNumber: file.versionNumber || 1,- }));-- return groupFilesByOriginal(recordsForGrouping);- }, [recentFiles]);-- // Get files to display with expansion logic- const displayFiles = useMemo(() => {- if (!recentFiles || recentFiles.length === 0) return [];-- // Only return leaf files - history files will be handled by separate components- if (storageFilter === "sharedWithMe") {- return recentFiles.filter(- (file) =>- file.remoteOwnedByCurrentUser === false || file.remoteSharedViaLink,- );- }- if (storageFilter === "sharedByMe") {- return recentFiles.filter(- (file) =>- file.remoteOwnedByCurrentUser !== false && file.remoteHasShareLinks,- );- }- if (storageFilter === "local") {- return recentFiles.filter(- (file) => !file.remoteStorageId && !file.remoteSharedViaLink,- );- }- return recentFiles;- }, [recentFiles, storageFilter]);-- const selectedFiles =- selectedFileIds.length === 0- ? []- : displayFiles.filter((file) => selectedFilesSet.has(file.id));-- const filteredFiles = !searchTerm- ? displayFiles- : displayFiles.filter((file) =>- file.name.toLowerCase().includes(searchTerm.toLowerCase()),- );-- const handleSourceChange = useCallback(- (source: "recent" | "local" | "drive") => {- setActiveSource(source);- if (source !== "recent") {- setSelectedFileIds([]);- setSearchTerm("");- setLastClickedIndex(null);- }- },- [],- );-- const handleStorageFilterChange = useCallback(- (filter: "all" | "local" | "sharedWithMe" | "sharedByMe") => {- setStorageFilter(filter);- setSelectedFileIds([]);- setLastClickedIndex(null);- },- [],- );-- const requestDeleteChoice = useCallback(- (file: StirlingFileStub): Promise<RemoteDeleteChoice> => {- return new Promise((resolve) => {- deletePromptResolveRef.current = resolve;- setDeletePromptFile(file);- });- },- [],- );-- const resolveDeleteChoice = useCallback((choice: RemoteDeleteChoice) => {- const resolver = deletePromptResolveRef.current;- deletePromptResolveRef.current = null;- setDeletePromptFile(null);- resolver?.(choice);- }, []);-- const handleLocalFileClick = useCallback(async () => {- console.log("[FileManager] Opening file dialog...");-- // Try native dialog first (desktop), falls back to empty array (web)- const files = await openFilesFromDisk({- multiple: true,- onFallbackOpen: () => fileInputRef.current?.click(),- });-- if (files.length > 0) {- console.log(- "[FileManager] Passing files to FileContext:",- files.map((f) => f.name),- );- onNewFilesSelect(files);-- await refreshRecentFiles();- onClose();- }- }, [onNewFilesSelect, refreshRecentFiles, onClose]);-- const handleFileSelect = useCallback(- (file: StirlingFileStub, currentIndex: number, shiftKey?: boolean) => {- const fileId = file.id;- if (!fileId) return;-- if (shiftKey && lastClickedIndex !== null) {- // Range selection with shift-click- const startIndex = Math.min(lastClickedIndex, currentIndex);- const endIndex = Math.max(lastClickedIndex, currentIndex);-- setSelectedFileIds((prev) => {- const selectedSet = new Set(prev);-- // Add all files in the range to selection- for (let i = startIndex; i <= endIndex; i++) {- const rangeFileId = filteredFiles[i]?.id;- if (rangeFileId) {- selectedSet.add(rangeFileId);- }- }-- return Array.from(selectedSet);- });- } else {- // Normal click behavior - optimized with Set for O(1) lookup- setSelectedFileIds((prev) => {- const selectedSet = new Set(prev);-- if (selectedSet.has(fileId)) {- selectedSet.delete(fileId);- } else {- selectedSet.add(fileId);- // Enforce maxSelectable: drop the oldest selection if over the limit- if (maxSelectable != null && selectedSet.size > maxSelectable) {- const [oldest] = selectedSet;- selectedSet.delete(oldest);- }- }-- return Array.from(selectedSet);- });-- // Update last clicked index for future range selections- setLastClickedIndex(currentIndex);- }- },- [filteredFiles, lastClickedIndex, maxSelectable],- );-- // Helper function to safely determine which files can be deleted- const getSafeFilesToDelete = useCallback(- (fileIds: FileId[], allStoredStubs: StirlingFileStub[]): FileId[] => {- const fileMap = new Map(allStoredStubs.map((f) => [f.id, f]));- const filesToDelete = new Set<FileId>();- const filesToPreserve = new Set<FileId>();-- // First, identify all files in the lineages of the leaf files being deleted- for (const leafFileId of fileIds) {- const currentFile = fileMap.get(leafFileId);- if (!currentFile) continue;-- // Always include the leaf file itself for deletion- filesToDelete.add(leafFileId);-- // If this is a processed file with history, trace back through its lineage- if (currentFile.versionNumber && currentFile.versionNumber > 1) {- const originalFileId = currentFile.originalFileId || currentFile.id;-- // Find all files in this history chain- const chainFiles = allStoredStubs.filter(- (file: StirlingFileStub) =>- (file.originalFileId || file.id) === originalFileId,- );-- // Add all files in this lineage as candidates for deletion- chainFiles.forEach((file) => filesToDelete.add(file.id));- }- }-- // Now identify files that must be preserved because they're referenced by OTHER lineages- for (const file of allStoredStubs) {- const fileOriginalId = file.originalFileId || file.id;-- // If this file is a leaf node (not being deleted) and its lineage overlaps with files we want to delete- if (file.isLeaf !== false && !fileIds.includes(file.id)) {- // Find all files in this preserved lineage- const preservedChainFiles = allStoredStubs.filter(- (chainFile: StirlingFileStub) =>- (chainFile.originalFileId || chainFile.id) === fileOriginalId,- );-- // Mark all files in this preserved lineage as must-preserve- preservedChainFiles.forEach((chainFile) =>- filesToPreserve.add(chainFile.id),- );- }- }-- // Final list: files to delete minus files that must be preserved- let safeToDelete = Array.from(filesToDelete).filter(- (fileId) => !filesToPreserve.has(fileId),- );-- // Check for orphaned non-leaf files after main deletion- const remainingFiles = allStoredStubs.filter(- (file) => !safeToDelete.includes(file.id),- );- const orphanedNonLeafFiles: FileId[] = [];-- for (const file of remainingFiles) {- // Only check non-leaf files (files that have been processed and have children)- if (file.isLeaf === false) {- const fileOriginalId = file.originalFileId || file.id;-- // Check if this non-leaf file has any living descendants- const hasLivingDescendants = remainingFiles.some((otherFile) => {- // Check if otherFile is a descendant of this file- const otherOriginalId = otherFile.originalFileId || otherFile.id;- return (- // Direct parent relationship- otherFile.parentFileId === file.id ||- // Same lineage but different from this file- (otherOriginalId === fileOriginalId && otherFile.id !== file.id)- );- });-- if (!hasLivingDescendants) {- orphanedNonLeafFiles.push(file.id);- }- }- }-- // Add orphaned non-leaf files to deletion list- safeToDelete = [...safeToDelete, ...orphanedNonLeafFiles];-- return safeToDelete;- },- [],- );-- // Shared internal delete logic- const performFileDelete = useCallback(- async (fileToRemove: StirlingFileStub) => {- let deleteChoice: RemoteDeleteChoice = "local";- if (fileToRemove.remoteStorageId) {- deleteChoice = await requestDeleteChoice(fileToRemove);- if (deleteChoice === "cancel") {- return;- }- }-- const canDeleteServer = fileToRemove.remoteOwnedByCurrentUser !== false;- const shouldDeleteServer =- canDeleteServer &&- (deleteChoice === "server" || deleteChoice === "both");- const shouldDeleteLocal =- deleteChoice === "local" || deleteChoice === "both";- const isServerOnly =- Boolean(fileToRemove.remoteStorageId) &&- fileToRemove.id.startsWith("server-");- const canLeaveShare =- fileToRemove.remoteOwnedByCurrentUser === false &&- !fileToRemove.remoteSharedViaLink &&- Boolean(fileToRemove.remoteStorageId);-- if (- deleteChoice === "leave" &&- canLeaveShare &&- fileToRemove.remoteStorageId- ) {- try {- await apiClient.delete(- `/api/v1/storage/files/${fileToRemove.remoteStorageId}/shares/self`,- {- suppressErrorToast: true,- },- );- await refreshRecentFiles();- alert({- alertType: "success",- title: t(- "fileManager.leaveShareSuccess",- "Removed from your shared list.",- ),- expandable: false,- durationMs: 2500,- });- return;- } catch (error) {- console.error("Failed to leave shared file:", error);- alert({- alertType: "error",- title: t(- "fileManager.leaveShareFailed",- "Could not remove the shared file.",- ),- expandable: false,- durationMs: 3500,- });- return;- }- }-- if (shouldDeleteServer && fileToRemove.remoteStorageId) {- try {- await apiClient.delete(- `/api/v1/storage/files/${fileToRemove.remoteStorageId}`,- { suppressErrorToast: true },- );- } catch (error) {- console.error("Failed to delete file from server:", error);- alert({- alertType: "error",- title: t(- "fileManager.removeServerFailed",- "Could not remove the file from the server.",- ),- expandable: false,- durationMs: 3500,- });- return;- }-- if (!shouldDeleteLocal) {- const originalFileId = (fileToRemove.originalFileId ||- fileToRemove.id) as FileId;- const chain = await fileStorage.getHistoryChainStubs(originalFileId);- for (const stub of chain) {- await fileStorage.updateFileMetadata(stub.id, {- remoteStorageId: undefined,- remoteStorageUpdatedAt: undefined,- });- }- await refreshRecentFiles();- alert({- alertType: "success",- title: t("fileManager.removeServerSuccess", "Removed from server."),- expandable: false,- durationMs: 2500,- });- return;- }- }-- if (shouldDeleteLocal && isServerOnly) {- await refreshRecentFiles();- return;- }-- const deletedFileId = fileToRemove.id;-- // Get all stored files to analyze lineages- const allStoredStubs = await fileStorage.getAllStirlingFileStubs();-- // Get safe files to delete (respecting shared lineages)- const filesToDelete = getSafeFilesToDelete(- [deletedFileId],- allStoredStubs,- );-- // Clear from selection immediately- setSelectedFileIds((prev) =>- prev.filter((id) => !filesToDelete.includes(id)),- );-- // Clear from expanded state to prevent ghost entries- setExpandedFileIds((prev) => {- const newExpanded = new Set(prev);- filesToDelete.forEach((id) => newExpanded.delete(id));- return newExpanded;- });-- // Clear from history cache - remove all files in the chain- setLoadedHistoryFiles((prev) => {- const newCache = new Map(prev);-- // Remove cache entries for all deleted files- filesToDelete.forEach((id) => newCache.delete(id as FileId));-- // Also remove deleted files from any other file's history cache- for (const [mainFileId, historyFiles] of newCache.entries()) {- const filteredHistory = historyFiles.filter(- (histFile) => !filesToDelete.includes(histFile.id),- );- if (filteredHistory.length !== historyFiles.length) {- newCache.set(mainFileId, filteredHistory);- }- }-- return newCache;- });-- // Delete safe files from IndexedDB- try {- for (const fileId of filesToDelete) {- await fileStorage.deleteStirlingFile(fileId as FileId);- }- } catch (error) {- console.error("Failed to delete files from chain:", error);- }-- // ID-based removal avoids stale index issues when multiple server files are deleted sequentially.- onBulkRemove?.(filesToDelete as FileId[]);-- // Refresh to ensure consistent state- await refreshRecentFiles();- },- [- getSafeFilesToDelete,- setSelectedFileIds,- setExpandedFileIds,- setLoadedHistoryFiles,- onBulkRemove,- refreshRecentFiles,- requestDeleteChoice,- t,- ],- );-- const handleFileRemove = useCallback(- async (index: number) => {- const fileToRemove = filteredFiles[index];- if (fileToRemove) {- await performFileDelete(fileToRemove);- }- },- [filteredFiles, performFileDelete],- );-- // Handle deletion by fileId (more robust than index-based)- const handleFileRemoveById = useCallback(- async (fileId: FileId) => {- // Find the file and its index in filteredFiles- const fileIndex = filteredFiles.findIndex((file) => file.id === fileId);- const fileToRemove = filteredFiles[fileIndex];-- if (fileToRemove && fileIndex !== -1) {- await performFileDelete(fileToRemove);- }- },- [filteredFiles, performFileDelete],- );-- // Handle deletion of specific history files (not index-based)- const handleHistoryFileRemove = useCallback(- async (fileToRemove: StirlingFileStub) => {- const deletedFileId = fileToRemove.id;-- // Clear from expanded state to prevent ghost entries- setExpandedFileIds((prev) => {- const newExpanded = new Set(prev);- newExpanded.delete(deletedFileId);- return newExpanded;- });-- // Clear from history cache - remove all files in the chain- setLoadedHistoryFiles((prev) => {- const newCache = new Map(prev);-- // Remove cache entries for all deleted files- newCache.delete(deletedFileId);-- // Also remove deleted files from any other file's history cache- for (const [mainFileId, historyFiles] of newCache.entries()) {- const filteredHistory = historyFiles.filter(- (histFile) => deletedFileId != histFile.id,- );- if (filteredHistory.length !== historyFiles.length) {- newCache.set(mainFileId, filteredHistory);- }- }-- return newCache;- });-- // Delete safe files from IndexedDB- try {- await fileStorage.deleteStirlingFile(deletedFileId);- } catch (error) {- console.error("Failed to delete files from chain:", error);- }-- // Refresh to ensure consistent state- await refreshRecentFiles();- },- [filteredFiles, onFileRemove, refreshRecentFiles, getSafeFilesToDelete],- );-- const handleFileDoubleClick = useCallback(- (file: StirlingFileStub) => {- if (isFileSupported(file.name)) {- onRecentFilesSelected([file]);- onClose();- }- },- [isFileSupported, onRecentFilesSelected, onClose],- );-- const handleOpenFiles = useCallback(() => {- // Remove active files that were unchecked, skipping files with unsaved changes- const uncheckedActiveIds = activeFileIds.filter((id) => {- if (selectedFilesSet.has(id)) return false;- const stub = filteredFiles.find((f) => f.id === id);- return !stub?.isDirty;- });- if (uncheckedActiveIds.length > 0) {- removeFiles(uncheckedActiveIds, false);- }-- // Add newly checked files (not already active)- const newlySelected = selectedFiles.filter(- (f) => !activeFileIds.includes(f.id),- );- if (newlySelected.length > 0) {- onRecentFilesSelected(newlySelected);- }-- onClose();- }, [- selectedFiles,- selectedFilesSet,- activeFileIds,- filteredFiles,- removeFiles,- onRecentFilesSelected,- onClose,- ]);-- const handleSearchChange = useCallback((value: string) => {- setSearchTerm(value);- }, []);-- const handleFileInputChange = useCallback(- async (event: React.ChangeEvent<HTMLInputElement>) => {- const files = Array.from(event.target.files || []);- if (files.length > 0) {- try {- // For local file uploads, pass File objects directly to FileContext- onNewFilesSelect(files);- await refreshRecentFiles();- onClose();- } catch (error) {- console.error("Failed to process selected files:", error);- }- }- event.target.value = "";- },- [onNewFilesSelect, refreshRecentFiles, onClose],- );-- const handleSelectAll = useCallback(() => {- const allFilesSelected =- filteredFiles.length > 0 &&- selectedFileIds.length === filteredFiles.length;- if (allFilesSelected) {- // Deselect all- setSelectedFileIds([]);- setLastClickedIndex(null);- } else {- // Select all filtered files, capped at maxSelectable- const allIds = filteredFiles- .map((file) => file.id)- .filter(Boolean) as FileId[];- setSelectedFileIds(- maxSelectable != null ? allIds.slice(0, maxSelectable) : allIds,- );- setLastClickedIndex(null);- }- }, [filteredFiles, selectedFileIds, maxSelectable]);-- const handleDeleteSelected = useCallback(async () => {- if (selectedFileIds.length === 0) return;-- // Split into server files (need modal prompts) and local files (bulk path).- const serverFiles = selectedFileIds- .map((id) => filteredFiles.find((f) => f.id === id))- .filter((f): f is StirlingFileStub => !!f && !!f.remoteStorageId);-- const localIds = selectedFileIds.filter((id) => {- const f = filteredFiles.find((ff) => ff.id === id);- return f && !f.remoteStorageId;- }) as FileId[];-- // Server files — sequential, each may need a modal prompt.- for (const file of serverFiles) {- await performFileDelete(file);- }-- // Local files — single IDB transaction, one UI update.- if (localIds.length > 0) {- try {- const allStoredStubs = await fileStorage.getAllStirlingFileStubs();- const safeIds = getSafeFilesToDelete(- localIds,- allStoredStubs,- ) as FileId[];- const safeIdSet = new Set(safeIds);-- // Clear UI state in one pass.- setSelectedFileIds((prev) => prev.filter((id) => !safeIdSet.has(id)));- setExpandedFileIds((prev) => {- const next = new Set(prev);- safeIds.forEach((id) => next.delete(id));- return next;- });- setLoadedHistoryFiles((prev) => {- const next = new Map(prev);- safeIds.forEach((id) => next.delete(id));- for (const [mainId, histFiles] of next.entries()) {- const filtered = histFiles.filter((h) => !safeIdSet.has(h.id));- if (filtered.length !== histFiles.length)- next.set(mainId, filtered);- }- return next;- });-- // Optimistic UI update.- onBulkRemove?.(safeIds);-- // Remove from workbench.- removeFiles(safeIds, false);-- // Single-transaction IDB delete, then refresh.- fileStorage- .deleteMultipleStirlingFiles(safeIds)- .then(() => refreshRecentFiles())- .catch((error) => {- console.error("Failed to bulk delete files from IndexedDB:", error);- refreshRecentFiles();- });- } catch (error) {- console.error("Failed to bulk delete local files:", error);- await refreshRecentFiles();- }- }- }, [- selectedFileIds,- filteredFiles,- performFileDelete,- getSafeFilesToDelete,- removeFiles,- refreshRecentFiles,- onBulkRemove,- ]);-- const handleDownloadSelected = useCallback(async () => {- if (selectedFileIds.length === 0) return;-- try {- // Get selected files- const selectedFilesToDownload = filteredFiles.filter((file) =>- selectedFileIds.includes(file.id),- );-- // Use generic download utility- await downloadFiles(selectedFilesToDownload, {- zipFilename: `selected-files-${new Date().toISOString().slice(0, 19).replace(/[:-]/g, "")}.zip`,- });- } catch (error) {- console.error("Failed to download selected files:", error);- }- }, [selectedFileIds, filteredFiles]);-- const handleDownloadSingle = useCallback(async (file: StirlingFileStub) => {- try {- await downloadFiles([file]);- } catch (error) {- console.error("Failed to download file:", error);- }- }, []);-- const handleToggleExpansion = useCallback(- async (fileId: FileId) => {- const isCurrentlyExpanded = expandedFileIds.has(fileId);-- // Update expansion state- setExpandedFileIds((prev) => {- const newSet = new Set(prev);- if (newSet.has(fileId)) {- newSet.delete(fileId);- } else {- newSet.add(fileId);- }- return newSet;- });-- // Load complete history chain if expanding- if (!isCurrentlyExpanded) {- const currentFileMetadata = recentFiles.find((f) => f.id === fileId);- if (- currentFileMetadata &&- (currentFileMetadata.versionNumber || 1) > 1- ) {- try {- // Get all stored file metadata for chain traversal- const allStoredStubs = await fileStorage.getAllStirlingFileStubs();- const fileMap = new Map(allStoredStubs.map((f) => [f.id, f]));-- // Get the current file's IndexedDB data- const currentStoredStub = fileMap.get(fileId as FileId);- if (!currentStoredStub) {- console.warn(`No stored file found for ${fileId}`);- return;- }-- // Build complete history chain using IndexedDB metadata- const historyFiles: StirlingFileStub[] = [];-- // Find the original file-- // Collect only files in this specific branch (ancestors of current file)- const chainFiles: StirlingFileStub[] = [];- const allFiles = Array.from(fileMap.values());-- // Build a map for fast parent lookups- const fileIdMap = new Map<FileId, StirlingFileStub>();- allFiles.forEach((f) => fileIdMap.set(f.id, f));-- // Trace back from current file through parent chain- let currentFile = fileIdMap.get(fileId);- while (currentFile?.parentFileId) {- const parentFile = fileIdMap.get(currentFile.parentFileId);- if (parentFile) {- chainFiles.push(parentFile);- currentFile = parentFile;- } else {- break; // Parent not found, stop tracing- }- }-- // Sort by version number (oldest first for history display)- chainFiles.sort(- (a, b) => (a.versionNumber || 1) - (b.versionNumber || 1),- );-- // StirlingFileStubs already have all the data we need - no conversion required!- historyFiles.push(...chainFiles);-- // Cache the loaded history files- setLoadedHistoryFiles(- (prev) => new Map(prev.set(fileId as FileId, historyFiles)),- );- } catch (error) {- console.warn(- `Failed to load history chain for file ${fileId}:`,- error,- );- }- }- } else {- // Clear loaded history when collapsing- setLoadedHistoryFiles((prev) => {- const newMap = new Map(prev);- newMap.delete(fileId as FileId);- return newMap;- });- }- },- [expandedFileIds, recentFiles],- );-- const handleAddToRecents = useCallback(- async (file: StirlingFileStub) => {- try {- // Mark the file as a leaf node so it appears in recent files- await fileStorage.markFileAsLeaf(file.id);-- // Refresh the recent files list to show updated state- await refreshRecentFiles();- } catch (error) {- console.error("Failed to add to recents:", error);- }- },- [refreshRecentFiles],- );-- const handleGoogleDriveSelect = useCallback(- async (files: File[]) => {- if (files.length > 0) {- try {- // Process Google Drive files same as local files- onNewFilesSelect(files);- await refreshRecentFiles();- onClose();- } catch (error) {- console.error("Failed to process Google Drive files:", error);- }- }- },- [onNewFilesSelect, refreshRecentFiles, onClose],- );-- const handleUnzipFile = useCallback(- async (file: StirlingFileStub) => {- try {- // Load the full file from storage- const stirlingFile = await fileStorage.getStirlingFile(file.id);- if (!stirlingFile) {- return;- }-- // Extract and store files using shared service method- const result = await zipFileService.extractAndStoreFilesWithHistory(- stirlingFile,- file,- );-- if (result.success) {- // Refresh file manager to show new files- await refreshRecentFiles();- }-- if (result.errors.length > 0) {- console.error("Errors during unzip:", result.errors);- }- } catch (error) {- console.error("Failed to unzip file:", error);- }- },- [refreshRecentFiles],- );-- const handleMakeCopy = useCallback(- async (file: StirlingFileStub) => {- if (!file.remoteStorageId) {- return;- }- try {- const response = await apiClient.get(- `/api/v1/storage/files/${file.remoteStorageId}/download`,- {- responseType: "blob",- suppressErrorToast: true,- skipAuthRedirect: true,- },- );- const contentType = readResponseHeader(- response.headers,- "content-type",- );- const disposition = readResponseHeader(- response.headers,- "content-disposition",- );- const filename =- parseContentDispositionFilename(disposition) ||- file.name ||- "shared-file";- const blob = response.data as Blob;- const contentTypeValue = contentType || blob.type;- const latestFiles = await extractLatestFilesFromBundle(- blob,- filename,- contentTypeValue,- );- if (latestFiles.length > 0) {- await actions.addFilesWithOptions(latestFiles, {- selectFiles: true,- allowDuplicates: true,- autoUnzip: false,- skipAutoUnzip: false,- });- await refreshRecentFiles();- alert({- alertType: "success",- title: t("fileManager.copyCreated", "Copy saved to this device."),- expandable: false,- durationMs: 2500,- });- }- } catch (error) {- console.error("Failed to create a copy:", error);- alert({- alertType: "error",- title: t("fileManager.copyFailed", "Could not create a copy."),- expandable: false,- durationMs: 3500,- });- }- },- [actions, refreshRecentFiles, t],- );-- // Cleanup blob URLs when component unmounts- useEffect(() => {- return () => {- // Clean up all created blob URLs- createdBlobUrls.current.forEach((url) => {- URL.revokeObjectURL(url);- });- createdBlobUrls.current.clear();- };- }, []);-- // Reset state when modal closes- useEffect(() => {- if (!isOpen) {- setActiveSource("recent");- setStorageFilter("all");- setSelectedFileIds([]);- setSearchTerm("");- setLastClickedIndex(null);- }- }, [isOpen]);-- const contextValue: FileManagerContextValue = useMemo(- () => ({- // State- activeSource,- storageFilter,- selectedFileIds,- searchTerm,- selectedFiles,- filteredFiles,- fileInputRef,- selectedFilesSet,- expandedFileIds,- fileGroups,- loadedHistoryFiles,- isLoading,- activeFileIds,-- // Handlers- onSourceChange: handleSourceChange,- onStorageFilterChange: handleStorageFilterChange,- onLocalFileClick: handleLocalFileClick,- onFileSelect: handleFileSelect,- onFileRemove: handleFileRemove,- onHistoryFileRemove: handleHistoryFileRemove,- onFileDoubleClick: handleFileDoubleClick,- onOpenFiles: handleOpenFiles,- onSearchChange: handleSearchChange,- onFileInputChange: handleFileInputChange,- onSelectAll: handleSelectAll,- onDeleteSelected: handleDeleteSelected,- onDownloadSelected: handleDownloadSelected,- onDownloadSingle: handleDownloadSingle,- onToggleExpansion: handleToggleExpansion,- onAddToRecents: handleAddToRecents,- onUnzipFile: handleUnzipFile,- onMakeCopy: handleMakeCopy,- onNewFilesSelect,- onGoogleDriveSelect: handleGoogleDriveSelect,- refreshRecentFiles,-- // External props- recentFiles,- isFileSupported,- modalHeight,- }),- [- activeSource,- storageFilter,- selectedFileIds,- searchTerm,- selectedFiles,- filteredFiles,- fileInputRef,- expandedFileIds,- fileGroups,- loadedHistoryFiles,- isLoading,- activeFileIds,- handleSourceChange,- handleStorageFilterChange,- handleLocalFileClick,- handleFileSelect,- handleFileRemove,- handleFileRemoveById,- performFileDelete,- handleFileDoubleClick,- handleOpenFiles,- handleSearchChange,- handleFileInputChange,- handleSelectAll,- handleDeleteSelected,- handleDownloadSelected,- handleToggleExpansion,- handleAddToRecents,- handleUnzipFile,- handleMakeCopy,- onNewFilesSelect,- handleGoogleDriveSelect,- recentFiles,- isFileSupported,- modalHeight,- refreshRecentFiles,- ],- );-- const deletePromptIsServerOnly =- Boolean(deletePromptFile?.remoteStorageId) &&- deletePromptFile?.id?.startsWith("server-");- const deletePromptIsShared =- deletePromptFile?.remoteOwnedByCurrentUser === false;- const deletePromptCanLeaveShare =- deletePromptIsShared &&- !deletePromptFile?.remoteSharedViaLink &&- Boolean(deletePromptFile?.remoteStorageId);-- return (- <FileManagerContext.Provider value={contextValue}>- {children}- <Modal- opened={Boolean(deletePromptFile)}- onClose={() => resolveDeleteChoice("cancel")}- centered- title={t("fileManager.removeFileTitle", "Remove file")}- zIndex={Z_INDEX_OVER_FILE_MANAGER_MODAL}- >- <Stack gap="sm">- <Text size="sm">- {deletePromptIsServerOnly- ? deletePromptIsShared- ? deletePromptCanLeaveShare- ? t(- "fileManager.removeSharedServerOnlyPrompt",- "This file is shared with you and stored only on the server. Remove it from your list?",- )- : t(- "fileManager.removeSharedServerOnlyBlockedPrompt",- "This file is shared with you and stored only on the server.",- )- : t(- "fileManager.removeServerOnlyPrompt",- "This file is stored only on your server. Would you like to remove it from the server?",- )- : deletePromptIsShared- ? t(- "fileManager.removeSharedPrompt",- "This file is shared with you. You can remove it from this device or your shared list.",- )- : t(- "fileManager.removeFilePrompt",- "This file is saved on this device and on your server. Where would you like to remove it from?",- )}- </Text>- <Text size="sm" c="dimmed">- {deletePromptFile?.name}- </Text>- <Group justify="flex-end" gap="sm">- <Button- variant="secondary"- onClick={() => resolveDeleteChoice("cancel")}- >- {t("cancel", "Cancel")}- </Button>- {!deletePromptIsServerOnly && (- <Button- variant="secondary"- onClick={() => resolveDeleteChoice("local")}- >- {t("fileManager.removeLocalOnly", "This device only")}- </Button>- )}- {deletePromptCanLeaveShare && (- <Button- variant="secondary"- onClick={() => resolveDeleteChoice("leave")}- >- {t("fileManager.leaveShare", "Remove from my list")}- </Button>- )}- {deletePromptFile?.remoteOwnedByCurrentUser !== false && (- <>- <Button- variant="secondary"- onClick={() => resolveDeleteChoice("server")}- >- {t("fileManager.removeServerOnly", "Server only")}- </Button>- {!deletePromptIsServerOnly && (- <Button- accent="danger"- onClick={() => resolveDeleteChoice("both")}- >- {t("fileManager.removeBoth", "Remove from both")}- </Button>- )}- </>- )}- </Group>- </Stack>- </Modal>- </FileManagerContext.Provider>- );-};--// Custom hook to use the context-export const useFileManagerContext = (): FileManagerContextValue => {- const context = useContext(FileManagerContext);-- if (!context) {- throw new Error(- "useFileManagerContext must be used within a FileManagerProvider. " +- "Make sure you wrap your component with <FileManagerProvider>.",- );- }-- return context;-};diff --git a/frontend/editor/src/core/contexts/FilesModalContext.test.tsx b/frontend/editor/src/core/contexts/FilesModalContext.test.tsxnew file mode 100644index 0000000000..e6a7d7108d--- /dev/null+++ b/frontend/editor/src/core/contexts/FilesModalContext.test.tsx@@ -0,0 +1,347 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { allowConsole } from "@app/tests/failOnConsole";+import {+ FilesModalProvider,+ useFilesModalContext,+} from "@app/contexts/FilesModalContext";+import {+ createNewStirlingFileStub,+ type StirlingFileStub,+} from "@app/types/fileContext";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, fallback: string, values?: Record<string, string>) =>+ (fallback ?? key).replace(+ /\{\{(\w+)\}\}/g,+ (_, name: string) => values?.[name] ?? "",+ ),+ }),+}));++const state = vi.hoisted(() => ({+ addFiles: vi.fn().mockResolvedValue(undefined),+ addStirlingFileStubs: vi.fn().mockResolvedValue(undefined),+ setSelectedFiles: vi.fn(),+ setWorkbench: vi.fn(),+ getStirlingFile: vi.fn(),+ apiGet: vi.fn(),+}));+vi.mock("@app/hooks/useFileHandler", () => ({+ useFileHandler: () => ({ addFiles: state.addFiles }),+}));+vi.mock("@app/contexts/FileContext", () => ({+ useFileActions: () => ({+ actions: {+ addStirlingFileStubs: state.addStirlingFileStubs,+ setSelectedFiles: state.setSelectedFiles,+ },+ }),+}));+vi.mock("@app/contexts/file/fileHooks", () => ({+ useFileContext: () => ({+ findFileId: () => "uploaded",+ selectors: { getSelectedStirlingFileStubs: () => [{ id: "already-open" }] },+ }),+}));+vi.mock("@app/contexts/NavigationContext", () => ({+ useNavigationActions: () => ({+ actions: { setWorkbench: state.setWorkbench },+ }),+ useNavigationState: () => ({ workbench: "pageEditor" }),+}));+vi.mock("@app/services/fileStorage", () => ({+ fileStorage: { getStirlingFile: state.getStirlingFile },+}));+vi.mock("@app/services/apiClient", () => ({ default: { get: state.apiGet } }));++beforeEach(() => vi.clearAllMocks());++describe("file picker caller contract", () => {+ it("inserts readable files when a share is revoked and another local blob is missing", async () => {+ allowConsole.error(/Could not load selected file/);+ const first = new File(["first"], "First.pdf");+ const last = new File(["last"], "Last.pdf");+ const stubs = [first, new File([], "Missing.pdf"), last].map((file) =>+ createNewStirlingFileStub(file),+ );+ const shared = {+ ...createNewStirlingFileStub(new File([], "Revoked.pdf")),+ remoteShareToken: "revoked",+ };+ const upload = new File(["upload"], "Upload.pdf");+ state.getStirlingFile.mockImplementation(async (id) =>+ id === stubs[0].id ? first : id === stubs[2].id ? last : null,+ );+ state.apiGet.mockRejectedValueOnce(new Error("Share revoked"));+ const handler = vi.fn();+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() =>+ result.current.openFilesModal({+ customHandler: handler,+ insertAfterPage: 3,+ }),+ );++ await act(async () => {+ result.current.closeFilesModal();+ await expect(+ result.current.onRecentFileSelect(+ [stubs[0], shared, ...stubs.slice(1)],+ [upload],+ ),+ ).rejects.toThrow(/Revoked.pdf[\s\S]*Missing.pdf/);+ });++ expect(handler).toHaveBeenCalledExactlyOnceWith([first, last, upload], 3);+ expect(result.current.isFilesModalOpen).toBe(false);+ expect(state.setWorkbench).not.toHaveBeenCalled();+ });++ it("still opens local selections after a remote download fails", async () => {+ allowConsole.error(/Could not import selected file/);+ const locals = ["First.pdf", "Last.pdf"].map((name) =>+ createNewStirlingFileStub(new File([], name)),+ );+ const shared = {+ ...createNewStirlingFileStub(new File([], "Revoked.pdf")),+ remoteShareToken: "revoked",+ };+ state.apiGet.mockRejectedValueOnce(new Error("Share revoked"));+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });++ await act(async () => {+ await expect(+ result.current.onRecentFileSelect([locals[0], shared, locals[1]]),+ ).rejects.toThrow("Revoked.pdf");+ });++ expect(state.addStirlingFileStubs).toHaveBeenCalledWith(locals, {+ selectFiles: false,+ });+ expect(state.setSelectedFiles).toHaveBeenCalledWith([+ "already-open",+ ...locals.map((stub) => stub.id),+ ]);+ expect(state.setWorkbench).toHaveBeenCalledWith("fileEditor");+ });++ it("preserves selection order when loading mixed sources", async () => {+ const local = new File(["local"], "Local.pdf");+ state.getStirlingFile.mockResolvedValue(local);+ state.apiGet.mockImplementation(async (path: string) => ({+ data: new Blob(["PDF"], { type: "application/pdf" }),+ headers: {+ "content-type": "application/pdf",+ "content-disposition": `attachment; filename="${path.includes("share-links") ? "Shared.pdf" : "Server.pdf"}"`,+ },+ }));+ const server = {+ ...createNewStirlingFileStub(new File([], "Server.pdf")),+ id: "server-12" as StirlingFileStub["id"],+ remoteStorageId: 12,+ };+ const shared = {+ ...createNewStirlingFileStub(new File([], "Shared.pdf")),+ remoteShareToken: "share-token",+ };+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ const files = await result.current.loadFiles([+ server,+ createNewStirlingFileStub(local),+ shared,+ ]);+ expect(files.map((file) => file.name)).toEqual([+ "Server.pdf",+ "Local.pdf",+ "Shared.pdf",+ ]);+ });++ it("downloads a shared server entry once through its share link", async () => {+ state.apiGet.mockResolvedValue({+ data: new Blob(["PDF"], { type: "application/pdf" }),+ headers: { "content-type": "application/pdf" },+ });+ const shared = {+ ...createNewStirlingFileStub(new File([], "Shared.pdf")),+ id: "server-12" as StirlingFileStub["id"],+ remoteStorageId: 12,+ remoteShareToken: "share-token",+ };+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ const files = await result.current.loadFiles([shared]);+ expect(files.map((file) => file.name)).toEqual(["Shared.pdf"]);+ expect(state.apiGet).toHaveBeenCalledExactlyOnceWith(+ "/api/v1/storage/share-links/share-token",+ expect.anything(),+ );+ expect(state.getStirlingFile).not.toHaveBeenCalled();+ });++ it("loads server and shared files through the existing download paths", async () => {+ state.apiGet.mockResolvedValue({+ data: new Blob(["PDF"], { type: "application/pdf" }),+ headers: {+ "content-type": "application/pdf",+ "content-disposition": 'attachment; filename="Remote.pdf"',+ },+ });+ const server = {+ ...createNewStirlingFileStub(new File([], "Remote.pdf")),+ id: "server-12" as StirlingFileStub["id"],+ remoteStorageId: 12,+ };+ const shared = {+ ...createNewStirlingFileStub(new File([], "Shared.pdf")),+ remoteShareToken: "share-token",+ };+ const handler = vi.fn();+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() => result.current.openFilesModal({ customHandler: handler }));+ await act(() => result.current.onRecentFileSelect([server, shared]));+ expect(state.apiGet).toHaveBeenCalledWith(+ "/api/v1/storage/files/12/download",+ expect.anything(),+ );+ expect(state.apiGet).toHaveBeenCalledWith(+ "/api/v1/storage/share-links/share-token",+ expect.anything(),+ );+ expect(handler.mock.calls[0][0]).toHaveLength(2);+ expect(state.setWorkbench).not.toHaveBeenCalled();+ });+ it("delivers stored and new files together to a page-insertion handler without navigation", async () => {+ const stored = new File(["local"], "Stored.pdf");+ const upload = new File(["upload"], "Upload.pdf");+ state.getStirlingFile.mockResolvedValue(stored);+ const handler = vi.fn();+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() =>+ result.current.openFilesModal({+ insertAfterPage: 4,+ customHandler: handler,+ maxSelectable: 2,+ }),+ );+ await act(async () => {+ result.current.closeFilesModal();+ await result.current.onRecentFileSelect(+ [createNewStirlingFileStub(stored)],+ [upload],+ );+ });+ expect(handler).toHaveBeenCalledExactlyOnceWith([stored, upload], 4);+ expect(state.addFiles).not.toHaveBeenCalled();+ expect(state.setWorkbench).not.toHaveBeenCalled();+ expect(result.current.isFilesModalOpen).toBe(false);+ });++ it("adds to the existing workspace selection", async () => {+ const stored = createNewStirlingFileStub(new File(["local"], "Stored.pdf"));+ const upload = new File(["upload"], "Upload.pdf");+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() => result.current.openFilesModal());+ await act(() => result.current.onRecentFileSelect([stored], [upload]));+ expect(state.addFiles).toHaveBeenCalledWith([upload]);+ expect(state.addStirlingFileStubs).toHaveBeenCalledWith([stored], {+ selectFiles: false,+ });+ expect(state.setSelectedFiles).toHaveBeenCalledWith([+ "already-open",+ stored.id,+ "uploaded",+ ]);+ expect(state.setWorkbench).toHaveBeenCalledWith("fileEditor");+ });++ it("does not close a reopened picker when a previous import finishes", async () => {+ let finishImport!: () => void;+ state.addFiles.mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finishImport = resolve;+ }),+ );+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() => result.current.openFilesModal());+ let importing!: Promise<void>;+ act(() => {+ result.current.closeFilesModal();+ importing = result.current.onRecentFileSelect(+ [],+ [new File(["PDF"], "Upload.pdf")],+ );+ });+ expect(result.current.isFilesModalOpen).toBe(false);+ act(() => result.current.openFilesModal({ maxSelectable: 1 }));+ await act(async () => {+ finishImport();+ await importing;+ });+ expect(result.current.isFilesModalOpen).toBe(true);+ expect(result.current.maxSelectable).toBe(1);+ });++ it("closes a direct upload immediately and leaves a subsequently opened picker alone", async () => {+ let finishImport!: () => void;+ state.addFiles.mockReturnValueOnce(+ new Promise<void>((resolve) => {+ finishImport = resolve;+ }),+ );+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() => result.current.openFilesModal());+ let importing!: Promise<void>;+ act(() => {+ importing = result.current.onFileUpload([+ new File(["PDF"], "Upload.pdf"),+ ]);+ });+ expect(result.current.isFilesModalOpen).toBe(false);+ act(() => result.current.openFilesModal({ maxSelectable: 1 }));+ await act(async () => {+ finishImport();+ await importing;+ });+ expect(result.current.isFilesModalOpen).toBe(true);+ expect(result.current.maxSelectable).toBe(1);+ });++ it("rejects without calling the insertion handler or reopening the picker if a selected file disappears", async () => {+ allowConsole.error(/Could not load selected file/);+ state.getStirlingFile.mockResolvedValue(null);+ const handler = vi.fn();+ const stub = createNewStirlingFileStub(new File(["local"], "Missing.pdf"));+ const { result } = renderHook(useFilesModalContext, {+ wrapper: FilesModalProvider,+ });+ act(() => result.current.openFilesModal({ customHandler: handler }));+ await act(async () => {+ result.current.closeFilesModal();+ await expect(result.current.onRecentFileSelect([stub])).rejects.toThrow(+ "Missing.pdf",+ );+ });+ expect(handler).not.toHaveBeenCalled();+ expect(result.current.isFilesModalOpen).toBe(false);+ });+});diff --git a/frontend/editor/src/core/contexts/FilesModalContext.tsx b/frontend/editor/src/core/contexts/FilesModalContext.tsxindex 1a559ea19e..3b7d0c45ee 100644--- a/frontend/editor/src/core/contexts/FilesModalContext.tsx+++ b/frontend/editor/src/core/contexts/FilesModalContext.tsx@@ -5,6 +5,7 @@ import React, {useCallback,useMemo,} from "react";+import { useTranslation } from "react-i18next";import { useFileHandler } from "@app/hooks/useFileHandler";import { useFileActions } from "@app/contexts/FileContext";import { useFileContext } from "@app/contexts/file/fileHooks";@@ -16,7 +17,6 @@ import { StirlingFileStub } from "@app/types/fileContext";import type { FileId } from "@app/types/file";import { fileStorage } from "@app/services/fileStorage";import apiClient from "@app/services/apiClient";-import { alert } from "@app/components/toast";import {extractLatestFilesFromBundle,getShareBundleEntryRootId,@@ -26,17 +26,31 @@ import {readResponseHeader,} from "@app/services/shareBundleUtils";+type CustomFileHandler = (+ files: File[],+ insertAfterPage?: number,+) => void | Promise<void>;++interface FilesModalOptions {+ insertAfterPage?: number;+ customHandler?: CustomFileHandler;+ maxSelectable?: number | null;+}+interface FilesModalContextType {isFilesModalOpen: boolean;- openFilesModal: (options?: {- insertAfterPage?: number;- customHandler?: (files: File[], insertAfterPage?: number) => void;- maxSelectable?: number | null;- }) => void;+ openFilesModal: (options?: FilesModalOptions) => void;closeFilesModal: () => void;maxSelectable: number | null;- onFileUpload: (files: File[]) => void;- onRecentFileSelect: (stirlingFileStubs: StirlingFileStub[]) => void;+ /** Closes the picker before ingestion; rejects on import failure. */+ onFileUpload: (files: File[]) => Promise<void>;+ /** Imports readable selections before rejecting with unavailable filenames; leaves modal state unchanged. */+ onRecentFileSelect: (+ stirlingFileStubs: StirlingFileStub[],+ uploads?: File[],+ ) => Promise<void>;+ /** Reads inputs in selection order without changing the workspace; rejects if any file is unavailable. */+ loadFiles: (stubs: StirlingFileStub[]) => Promise<File[]>;onModalClose?: () => void;setOnModalClose: (callback: () => void) => void;}@@ -48,6 +62,7 @@ export const FilesModalContext = createContext<FilesModalContextType | null>(export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({children,}) => {+ const { t } = useTranslation();const { addFiles } = useFileHandler();const { actions } = useFileActions();const fileCtx = useFileContext();@@ -58,9 +73,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({const [isFilesModalOpen, setIsFilesModalOpen] = useState(false);const [onModalClose, setOnModalClose] = useState<(() => void) | undefined>();const [insertAfterPage, setInsertAfterPage] = useState<number | undefined>();- const [customHandler, setCustomHandler] = useState<- ((files: File[], insertAfterPage?: number) => void) | undefined- >();+ const [customHandler, setCustomHandler] = useState<CustomFileHandler>();const [maxSelectable, setMaxSelectable] = useState<number | null>(null);const importBundleToWorkbench = useCallback(@@ -178,261 +191,167 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({[actions, fileStorage],);- const downloadServerFile = useCallback(async (remoteId: number) => {- const response = await apiClient.get(- `/api/v1/storage/files/${remoteId}/download`,- {- responseType: "blob",- suppressErrorToast: true,- skipAuthRedirect: true,- },- );+ const downloadRemoteFile = useCallback(async (stub: StirlingFileStub) => {+ const path = stub.remoteShareToken+ ? `/api/v1/storage/share-links/${stub.remoteShareToken}`+ : stub.remoteStorageId && stub.id.startsWith("server-")+ ? `/api/v1/storage/files/${stub.remoteStorageId}/download`+ : null;+ if (!path) return null;+ const response = await apiClient.get(path, {+ responseType: "blob",+ suppressErrorToast: true,+ skipAuthRedirect: true,+ });const contentType = readResponseHeader(response.headers, "content-type");const disposition = readResponseHeader(response.headers,"content-disposition",);- const filename =- parseContentDispositionFilename(disposition) || "server-file";+ const filename = parseContentDispositionFilename(disposition) || stub.name;const blob = response.data as Blob;const contentTypeValue = contentType || blob.type;return { blob, filename, contentType: contentTypeValue };}, []);- const downloadShareLinkFile = useCallback(async (shareToken: string) => {- const response = await apiClient.get(- `/api/v1/storage/share-links/${shareToken}`,- {- responseType: "blob",- suppressErrorToast: true,- skipAuthRedirect: true,- },- );- const contentType = readResponseHeader(response.headers, "content-type");- const disposition = readResponseHeader(- response.headers,- "content-disposition",- );- const filename =- parseContentDispositionFilename(disposition) || "shared-file";- const blob = response.data as Blob;- const contentTypeValue = contentType || blob.type;- return { blob, filename, contentType: contentTypeValue };+ const openFilesModal = useCallback((options?: FilesModalOptions) => {+ setInsertAfterPage(options?.insertAfterPage);+ setCustomHandler(() => options?.customHandler);+ setMaxSelectable(options?.maxSelectable ?? null);+ setIsFilesModalOpen(true);}, []);- const openFilesModal = useCallback(- (options?: {- insertAfterPage?: number;- customHandler?: (files: File[], insertAfterPage?: number) => void;- maxSelectable?: number | null;- }) => {- setInsertAfterPage(options?.insertAfterPage);- setCustomHandler(() => options?.customHandler);- setMaxSelectable(options?.maxSelectable ?? null);- setIsFilesModalOpen(true);- },- [],- );-const closeFilesModal = useCallback(() => {setIsFilesModalOpen(false);- setInsertAfterPage(undefined); // Clear insertion position- setCustomHandler(undefined); // Clear custom handler+ setInsertAfterPage(undefined);+ setCustomHandler(undefined);onModalClose?.();}, [onModalClose]);- const handleFileUpload = useCallback(- async (files: File[]) => {- if (customHandler) {- // Use custom handler for special cases (like page insertion) — no auto-navigation- customHandler(files, insertAfterPage);- } else {- // 1) Add via standard flow (auto-selects new files)- await addFiles(files);- // 2) Merge all requested file IDs (covers already-present files too)- const ids = files- .map((f) => fileCtx.findFileId(f) as FileId | undefined)- .filter((id): id is FileId => Boolean(id));- if (ids.length > 0) {- const currentSelected = fileCtx.selectors- .getSelectedStirlingFileStubs()- .map((s) => s.id);- const nextSelection = Array.from(- new Set([...currentSelected, ...ids]),+ const loadFiles = useCallback(+ async (stirlingFileStubs: StirlingFileStub[]) => {+ const loadedFiles: File[] = [];+ for (const stub of stirlingFileStubs) {+ const remote = await downloadRemoteFile(stub);+ if (remote) {+ loadedFiles.push(+ ...(await extractLatestFilesFromBundle(+ remote.blob,+ remote.filename,+ remote.contentType,+ )),);- actions.setSelectedFiles(nextSelection);- }- // Stay in multi-tool; otherwise single file → viewer, multiple → active files- if (!isMultiTool) {- navActions.setWorkbench(files.length === 1 ? "viewer" : "fileEditor");+ } else {+ const file = await fileStorage.getStirlingFile(stub.id);+ if (!file) throw new Error(`${stub.name} is no longer available.`);+ loadedFiles.push(file);}}- closeFilesModal();+ return loadedFiles;},- [- addFiles,- closeFilesModal,- insertAfterPage,- customHandler,- actions,- fileCtx,- navActions,- isMultiTool,- ],+ [downloadRemoteFile],);const handleRecentFileSelect = useCallback(- async (stirlingFileStubs: StirlingFileStub[]) => {- const serverOnlyStubs = stirlingFileStubs.filter(- (stub) => stub.remoteStorageId && stub.id.startsWith("server-"),- );- const sharedLinkStubs = stirlingFileStubs.filter(- (stub) => stub.remoteShareToken,- );- const localStubs = stirlingFileStubs.filter(- (stub) =>- !serverOnlyStubs.includes(stub) && !sharedLinkStubs.includes(stub),- );-+ async (stirlingFileStubs: StirlingFileStub[], uploads: File[] = []) => {+ const failedNames: string[] = [];+ const reportUnavailable = () => {+ if (failedNames.length)+ throw new Error(+ t("filePicker.filesUnavailable", "Could not add: {{names}}", {+ names: failedNames.join(", "),+ }),+ );+ };if (customHandler) {- try {- const loadedFiles: File[] = [];- for (const stub of localStubs) {- const stirlingFile = await fileStorage.getStirlingFile(stub.id);- if (stirlingFile) {- loadedFiles.push(stirlingFile);- }- }- for (const stub of serverOnlyStubs) {- if (!stub.remoteStorageId) continue;- const { blob, filename, contentType } = await downloadServerFile(- stub.remoteStorageId,- );- const latestFiles = await extractLatestFilesFromBundle(- blob,- filename,- contentType,- );- loadedFiles.push(...latestFiles);+ const loadedFiles: File[] = [];+ for (const stub of stirlingFileStubs) {+ try {+ loadedFiles.push(...(await loadFiles([stub])));+ } catch (cause) {+ console.error("Could not load selected file", stub.name, cause);+ failedNames.push(stub.name);}- for (const stub of sharedLinkStubs) {- if (!stub.remoteShareToken) continue;- const { blob, filename, contentType } = await downloadShareLinkFile(- stub.remoteShareToken,- );- const latestFiles = await extractLatestFilesFromBundle(- blob,- filename,- contentType,- );- loadedFiles.push(...latestFiles);- }-- if (loadedFiles.length > 0) {- customHandler(loadedFiles, insertAfterPage);- }- } catch (error) {- console.error("Failed to load files for custom handler:", error);- alert({- alertType: "error",- title: "Unable to download one or more server files.",- expandable: false,- durationMs: 3500,- });}- closeFilesModal();+ const files = [...loadedFiles, ...uploads];+ if (files.length) await customHandler(files, insertAfterPage);+ reportUnavailable();return;}+ if (uploads.length > 0) await addFiles(uploads);- const selectedFromServer: FileId[] = [];- try {- for (const stub of serverOnlyStubs) {- if (!stub.remoteStorageId) continue;- const { blob, filename, contentType } = await downloadServerFile(- stub.remoteStorageId,- );- const importedIds = await importBundleToWorkbench(- blob,- filename,- contentType,- stub.remoteStorageId,- stub.remoteStorageUpdatedAt,- stub.remoteOwnerUsername,- stub.remoteOwnedByCurrentUser,- stub.remoteSharedViaLink,- stub.remoteShareToken,- );- selectedFromServer.push(...importedIds);- }- for (const stub of sharedLinkStubs) {- if (!stub.remoteShareToken) continue;- const { blob, filename, contentType } = await downloadShareLinkFile(- stub.remoteShareToken,- );+ const localStubs: StirlingFileStub[] = [];+ const requestedIds: FileId[] = [];+ for (const stub of stirlingFileStubs) {+ try {+ const remote = await downloadRemoteFile(stub);+ if (!remote) {+ localStubs.push(stub);+ requestedIds.push(stub.id);+ continue;+ }const importedIds = await importBundleToWorkbench(- blob,- filename,- contentType,+ remote.blob,+ remote.filename,+ remote.contentType,stub.remoteStorageId,stub.remoteStorageUpdatedAt,stub.remoteOwnerUsername,stub.remoteOwnedByCurrentUser,- true,+ stub.remoteShareToken ? true : stub.remoteSharedViaLink,stub.remoteShareToken,);- selectedFromServer.push(...importedIds);+ requestedIds.push(...importedIds);+ } catch (cause) {+ console.error("Could not import selected file", stub.name, cause);+ failedNames.push(stub.name);}- } catch (error) {- console.error("Failed to load server files:", error);- alert({- alertType: "error",- title: "Unable to download one or more server files.",- expandable: false,- durationMs: 3500,- });}- if (actions.addStirlingFileStubs) {+ if (localStubs.length)await actions.addStirlingFileStubs(localStubs, { selectFiles: false });- // Union newly picked files with the current selection so tools like- // Compare that depend on multi-file selection don't lose existing- // selections when the user picks an additional file from the modal.- const requestedIds = localStubs.map((s) => s.id);- const currentSelected = fileCtx.selectors- .getSelectedStirlingFileStubs()- .map((s) => s.id);- const nextSelection = Array.from(- new Set([...currentSelected, ...requestedIds, ...selectedFromServer]),- );- actions.setSelectedFiles(nextSelection);- } else {- console.error("addStirlingFileStubs action not available");- }+ // Adding an input must preserve a tool's existing selection.+ const uploadedIds = uploads+ .map((file) => fileCtx.findFileId(file))+ .filter((id): id is FileId => Boolean(id));+ const currentSelected = fileCtx.selectors+ .getSelectedStirlingFileStubs()+ .map((s) => s.id);+ actions.setSelectedFiles(+ Array.from(+ new Set([...currentSelected, ...requestedIds, ...uploadedIds]),+ ),+ );- // Stay in multi-tool; otherwise single file → viewer, multiple → active files- if (!isMultiTool) {- const totalAdded = stirlingFileStubs.length;+ const totalAdded = requestedIds.length + uploads.length;+ if (!isMultiTool && totalAdded > 0) {navActions.setWorkbench(totalAdded === 1 ? "viewer" : "fileEditor");}-- closeFilesModal();+ reportUnavailable();},[- actions.addStirlingFileStubs,+ addFiles,+ loadFiles,actions,- closeFilesModal,customHandler,insertAfterPage,fileCtx,- downloadServerFile,- downloadShareLinkFile,- extractLatestFilesFromBundle,+ downloadRemoteFile,importBundleToWorkbench,navActions,isMultiTool,+ t,],);+ const handleFileUpload = useCallback(+ (files: File[]) => {+ closeFilesModal();+ return handleRecentFileSelect([], files);+ },+ [closeFilesModal, handleRecentFileSelect],+ );+const setModalCloseCallback = useCallback((callback: () => void) => {setOnModalClose(() => callback);}, []);@@ -444,6 +363,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({closeFilesModal,onFileUpload: handleFileUpload,onRecentFileSelect: handleRecentFileSelect,+ loadFiles,onModalClose,setOnModalClose: setModalCloseCallback,maxSelectable,@@ -454,6 +374,7 @@ export const FilesModalProvider: React.FC<{ children: React.ReactNode }> = ({closeFilesModal,handleFileUpload,handleRecentFileSelect,+ loadFiles,onModalClose,setModalCloseCallback,maxSelectable,diff --git a/frontend/editor/src/core/contexts/FilesPageContext.tsx b/frontend/editor/src/core/contexts/FilesPageContext.tsxindex 858bc101e0..1d293b0361 100644--- a/frontend/editor/src/core/contexts/FilesPageContext.tsx+++ b/frontend/editor/src/core/contexts/FilesPageContext.tsx@@ -1,5 +1,3 @@-/** Shared state for the My Files view. */-import React, {createContext,useCallback,@@ -38,10 +36,11 @@ import {import { useFileActions } from "@app/contexts/file/fileHooks";import { useDiskLinkReconcile } from "@app/hooks/useDiskLinkReconcile";import { useFolders } from "@app/contexts/FolderContext";+import { getFileOrigin } from "@app/components/filesPage/fileOrigin";+import { useRoutedLibraryViewState } from "@app/components/filesPage/useRoutedLibraryViewState";import { useAppConfig } from "@app/contexts/AppConfigContext";import { useAuth } from "@app/auth/UseSession";-/** View-toggle modes; tuple keeps the union and iterator in sync. */export const FILES_PAGE_VIEW_MODES = ["grid", "list"] as const;export type FilesPageViewMode = (typeof FILES_PAGE_VIEW_MODES)[number];export type FilesPageSortMode =@@ -57,7 +56,6 @@ export type FilesPageOriginFilter =| "cloud"| "shared-with-me";-/** all|local|cloud|recent|shared filter presets. */export type FilesPageTab = "all" | "cloud" | "recent" | "shared" | "sharedByMe";export interface FolderNameDialogState {@@ -77,11 +75,6 @@ export interface MoveDialogState {const VIEW_MODE_STORAGE_KEY = "stirling.filesPageViewMode";-/**- * The list is the default: it shows more files per screen and carries the columns the- * grid has no room for. The grid is one click away, and the choice is the user's from- * then on.- */function readPersistedViewMode(): FilesPageViewMode {try {const stored = localStorage.getItem(VIEW_MODE_STORAGE_KEY);@@ -93,23 +86,20 @@ function readPersistedViewMode(): FilesPageViewMode {}interface FilesPageContextValue {- // Cached files (leaf-only)+ /** Leaf versions only; includes local and server library entries. */allFiles: StirlingFileStub[];fileMap: Map<FileId, StirlingFileStub>;fileCountsByFolder: Map<FolderId | null, number>;loading: boolean;refresh: () => Promise<void>;- /** Bumped to re-read a mounted directory, which is listed from disk rather than- * from storage and so has nothing to react to when its contents change. */+ /** Invalidates disk listings, which cannot observe IndexedDB revisions. */diskRevision: number;bumpDiskRevision: () => void;- // SelectionselectedFileIds: Set<FileId>;setSelectedFileIds: React.Dispatch<React.SetStateAction<Set<FileId>>>;clearSelection: () => void;- // View + sort + search + filtersviewMode: FilesPageViewMode;setViewMode: (mode: FilesPageViewMode) => void;sortMode: FilesPageSortMode;@@ -123,11 +113,11 @@ interface FilesPageContextValue {typeFilter: string[];setTypeFilter: (next: string[]) => void;- /** Active filter-tab. Drives which files appear and which UI affordances enable. */currentTab: FilesPageTab;setCurrentTab: (tab: FilesPageTab) => void;+ /** Opens the folder in Stirling library with one browser history entry. */+ openFolder: (id: FolderId | null) => void;- // Dialog statefolderNameDialog: FolderNameDialogState;openNewFolderDialog: (parentId?: FolderId | null, kind?: FolderKind) => void;openRenameFolderDialog: (folder: FolderRecord) => void;@@ -138,13 +128,21 @@ interface FilesPageContextValue {promptMoveFiles: (fileIds: FileId[]) => void;closeMoveDialog: () => void;- // Action helpers- moveFilesTo: (fileIds: FileId[], folderId: FolderId | null) => Promise<void>;+ /**+ * Server folders upload local files; moving to root uploads only with uploadToRoot.+ * Can reject after partial completion; successful uploads and moves are not rolled back.+ * Mounted and browser-only destinations report skipped files through FolderContext.+ */+ moveFilesTo: (+ fileIds: FileId[],+ folderId: FolderId | null,+ options?: { uploadToRoot?: boolean },+ ) => Promise<void>;moveFolderTo: (folderId: FolderId,newParentId: FolderId | null,) => Promise<void>;- /** Queue files for deletion - opens the DeleteFilesDialog. */+ /** Prompts for a scope if any selected server copy is owned; otherwise deletes browser copies. */removeFiles: (fileIds: FileId[]) => Promise<void>;/** Files currently queued in the delete dialog (empty when closed). */deleteDialogFileIds: FileId[];@@ -182,19 +180,14 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {const { config: appConfig } = useAppConfig();const { isAnonymous } = useAuth();- // Refs inside, so refresh isn't recreated (and re-run) every time the- // workbench changes - it only needs whichever files are open when it runs.+ // Refs keep workspace changes from restarting library refreshes.const { openFileIdsRef, onOpenFilesDetached } = useDiskLinkReconcile();const [allFiles, setAllFiles] = useState<StirlingFileStub[]>([]);const [loading, setLoading] = useState(true);- // Generation counter to drop stale reconcile results when a second refresh- // overlaps the first. Mirrors the pattern FolderContext.pullFromServer uses- // via pullInFlight, but kept as a counter so we can also discard results- // from clearly-out-of-date calls instead of just serializing them.+ // Only the newest refresh may publish results or clear loading.const refreshGenRef = useRef(0);- // Narrow dep so refresh isn't recreated on every folders field change.const setFoldersError = folders.setError;const storageEnabled = appConfig?.storageEnabled === true;const shareLinksEnabled = appConfig?.storageShareLinksEnabled === true;@@ -206,12 +199,8 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {setLoading(true);try {const localStubs = await fileStorage.getAllStirlingFileStubs();- // Bail if a newer refresh started while IDB was reading.if (gen !== refreshGenRef.current) return;- // A file the user deleted outside the app must not be offered here, so- // reconcile before anything is rendered. Leaves only: every version behind- // them shares a source, and checking all of them multiplies the work by- // the length of the history.+ // Reconcile disk deletions before displaying leaves; checking every version repeats the same IO.const localLeaf = await pruneMissingRecentFiles(localStubs.filter((s) => s.isLeaf !== false),{@@ -227,8 +216,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {shareLinksEnabled,isAnonymous,});- // Drop the merged result if a newer refresh has already started -- // otherwise its stale snapshot will clobber the newer one's state.if (gen !== refreshGenRef.current) return;setAllFiles(merged);} catch (err) {@@ -238,7 +225,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {err instanceof Error ? err.message : "Failed to load files",);} finally {- // Only the latest refresh should clear the loading state.if (gen === refreshGenRef.current) setLoading(false);}}, [@@ -266,23 +252,29 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {for (const f of folders.folders) map.set(f.id, 0);for (const file of allFiles) {const fid = file.folderId ?? null;+ if (fid === null && getFileOrigin(file) === "local") continue;map.set(fid, (map.get(fid) ?? 0) + 1);}return map;}, [allFiles, folders.folders]);- // Selection ---------------------------------------------------------------- const [selectedFileIds, setSelectedFileIds] = useState<Set<FileId>>(- () => new Set(),- );- const clearSelection = useCallback(() => setSelectedFileIds(new Set()), []);+ const {+ selectedFileIds,+ setSelectedFileIds,+ clearSelection,+ sortMode,+ setSortMode,+ search,+ setSearch,+ originFilter,+ setOriginFilter,+ typeFilter,+ setTypeFilter,+ currentTab,+ setCurrentTab,+ openFolder,+ } = useRoutedLibraryViewState();- // Clear selection when folder changes.- useEffect(() => {- clearSelection();- }, [folders.currentFolderId, clearSelection]);-- // View + sort + search + filters ----------------------------------------const [viewMode, setViewModeState] = useState<FilesPageViewMode>(readPersistedViewMode,);@@ -294,14 +286,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {// A browser that refuses storage still gets the choice for this session.}}, []);- const [sortMode, setSortMode] = useState<FilesPageSortMode>("modified-desc");- const [search, setSearch] = useState("");- const [originFilter, setOriginFilter] =- useState<FilesPageOriginFilter>("all");- const [typeFilter, setTypeFilter] = useState<string[]>([]);- const [currentTab, setCurrentTab] = useState<FilesPageTab>("all");-- // Dialog: folder name -----------------------------------------------------+const [folderNameDialog, setFolderNameDialog] =useState<FolderNameDialogState>({ mode: null });@@ -326,7 +311,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {const submitFolderName = useCallback(async (name: string) => {if (folderNameDialog.mode === "new") {- // Chosen before the dialog opened, and only used at the root.const created = await folders.createFolder(name,folderNameDialog.parentId ?? folders.currentFolderId,@@ -343,7 +327,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {[folderNameDialog, folders, navigate],);- // Dialog: move ------------------------------------------------------------const [moveDialog, setMoveDialog] = useState<MoveDialogState>({open: false,initial: ROOT_FOLDER_ID,@@ -351,7 +334,11 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {const promptMoveFiles = useCallback((fileIds: FileId[]) => {- setMoveDialog({ open: true, fileIds, initial: folders.currentFolderId });+ setMoveDialog({+ open: true,+ fileIds,+ initial: folders.currentFolderId,+ });},[folders.currentFolderId],);@@ -360,14 +347,14 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {setMoveDialog((m) => ({ ...m, open: false }));}, []);- // Action helpers ------------------------------------------------------------ /** Cloud files move server-first; local files auto-upload then move. */const moveFilesTo = useCallback(- async (fileIds: FileId[], folderId: FolderId | null) => {+ async (+ fileIds: FileId[],+ folderId: FolderId | null,+ options?: { uploadToRoot?: boolean },+ ) => {if (fileIds.length === 0) return;- // fileMap is a render-time snapshot, so a file created moments ago is not in- // it yet. Storage is the truth, and falling back keeps it in the move.+ // Newly imported files may not be in the render snapshot yet; read them from storage.const fetched = await Promise.all(fileIds.map((id) => fileMap.get(id) ?? fileStorage.getStirlingFileStub(id),@@ -375,7 +362,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {);const stubs = fetched.filter((s): s is StirlingFileStub => Boolean(s));const localOnly = stubs.filter((s) => s.remoteStorageId == null);- // Cloud list is mutated below with newly-promoted local files.const cloudFiles = stubs.filter((s) => s.remoteStorageId != null);const targetFolder =@@ -383,8 +369,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {const targetKind = targetFolder ? folderKind(targetFolder) : null;if (targetKind === "local") {- // In a mount means on the disk: write each file into the directory, then retire- // the app-side copy once the bytes verifiably landed.+ // Retire app-side copies only after their bytes have been written into the mounted directory.const { written, failedCount } = await writeIntoMount(targetFolder?.directory,localOnly.map((stub) => ({@@ -400,7 +385,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {const orphans = await fileStorage.orphanedAncestorIds(movedIds);await fileActions.removeFiles([...movedIds, ...orphans], true);}- // One error slot, two possible failures: report both.const notices: string[] = [];if (failedCount > 0) {notices.push(@@ -449,10 +433,14 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {return;}- if (folderId !== null && localOnly.length > 0) {- // Per-file uploadHistoryChain so each gets its own remoteStorageId.- try {- for (const stub of localOnly) {+ const uploadErrors: string[] = [];+ if (+ (folderId !== null || options?.uploadToRoot) &&+ localOnly.length > 0+ ) {+ // Independent files keep separate server records and can succeed independently.+ for (const stub of localOnly) {+ try {const rootId = (stub.originalFileId || stub.id) as FileId;const { remoteId, updatedAt, chain } =await uploadHistoryChain(rootId);@@ -470,7 +458,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {remoteSharedViaLink: false,});}- // Promoted file joins the bulk-move round.cloudFiles.push({...stub,remoteStorageId: remoteId,@@ -478,14 +465,11 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {remoteOwnedByCurrentUser: true,remoteSharedViaLink: false,});+ } catch (err) {+ uploadErrors.push(+ `${stub.name}: ${err instanceof Error ? err.message : String(err)}`,+ );}- } catch (err) {- folders.setError(- err instanceof Error- ? `Could not save files to server: ${err.message}`- : "Could not save files to server.",- );- throw err;}}@@ -499,13 +483,13 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {folderId,);if (result.skippedFileIds.length > 0) {- folders.setError(- t(- "filesPage.moveSkippedRemote",- "{{count}} file(s) couldn't be moved on the server (no permission or already deleted).",- { count: result.skippedFileIds.length },- ),+ const message = t(+ "filesPage.moveSkippedRemote",+ "{{count}} file(s) couldn't be moved on the server (no permission or already deleted).",+ { count: result.skippedFileIds.length },);+ folders.setError(message);+ if (options?.uploadToRoot) uploadErrors.push(message);}const movedRemoteSet = new Set(result.movedFileIds);const idsToCacheMove = cloudFiles@@ -524,10 +508,8 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {}}- // Local files moving to the root DO need a write when they are leaving a folder —- // their membership is a browser-side folderId that nothing above has touched (the- // upload branch only runs for a non-null target).- if (folderId === null && localOnly.length > 0) {+ // Moving a browser copy to root must not implicitly upload it.+ if (folderId === null && !options?.uploadToRoot && localOnly.length > 0) {const leaving = localOnly.filter((s) => (s.folderId ?? null) !== null).map((s) => s.id);@@ -536,13 +518,13 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {}}await refresh();+ if (uploadErrors.length) throw new Error(uploadErrors.join("\n"));},[indexedDB, refresh, fileMap, folders, t, fileActions],);const moveFolderTo = useCallback(async (folderId: FolderId, newParentId: FolderId | null) => {- // Client-side cycle guard.if (newParentId !== null && folders.isDescendant(newParentId, folderId)) {folders.setError(t(@@ -552,9 +534,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {);return;}- // A subtree is one kind throughout (each kind has its own system of- // record), so a cross-kind drop is refused here as a message rather- // than surfacing as a thrown error from the context.+ // Each folder kind has its own storage authority, so moves cannot cross kinds.if (newParentId !== null) {const source = folders.foldersById.get(folderId);const target = folders.foldersById.get(newParentId);@@ -573,13 +553,9 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {[folders, t],);- // Delete dialog state. removeFiles only queues + opens when a cloud copy is- // involved; local-only deletes skip the dialog and run immediately.const [deleteDialogFileIds, setDeleteDialogFileIds] = useState<FileId[]>([]);const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);- // The actual deletion for a chosen scope. Shared by the direct (local-only)- // path and the dialog's confirm.const performDelete = useCallback(async (fileIds: FileId[], scope: DeleteScope) => {const stubs = fileIds@@ -617,7 +593,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {}}- // Local delete - skip ephemeral server-/shared- stubs (no IDB row).+ // Server/shared placeholders have no IndexedDB row to delete.if (scope === "device" || scope === "everywhere") {const localIds = stubs.filter((s) => {@@ -642,14 +618,12 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {// reconcile picks up the cloud deletions and strips stale remote pointers.await refresh();},- [fileMap, fileActions, folders, refresh, t],+ [fileMap, fileActions, folders, refresh, setSelectedFileIds, t],);const removeFiles = useCallback(async (fileIds: FileId[]) => {if (fileIds.length === 0) return;- // Only prompt when a cloud copy is in play (the user must pick where to- // delete). Local-only files have nothing to choose - delete immediately.const hasDeletableCloud = fileIds.some((id) => {const s = fileMap.get(id);return (@@ -726,9 +700,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {const promptDeleteFolder = useCallback((folder: FolderRecord) => {if (folderKind(folder) === "local") {- // Removing a mount destroys nothing — the record goes, the directory and every- // file in it stay — so there is nothing to warn about and the delete dialog's- // "what about the files?" question would be a scary lie.+ // Unmounting only removes the mapping; the directory and its files remain on disk.void folders.deleteFolder(folder.id).catch((err) => {folders.setError(err instanceof Error@@ -764,7 +736,6 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {[fileActions, filesInSubtree, folders, refresh],);- // Memoise to avoid re-rendering every FileCard on unrelated state churn.const value = useMemo<FilesPageContextValue>(() => ({allFiles,@@ -789,6 +760,7 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {setTypeFilter,currentTab,setCurrentTab,+ openFolder,folderNameDialog,openNewFolderDialog,openRenameFolderDialog,@@ -819,13 +791,20 @@ export function FilesPageProvider({ children }: { children: React.ReactNode }) {diskRevision,bumpDiskRevision,selectedFileIds,+ setSelectedFileIds,clearSelection,viewMode,sortMode,+ setSortMode,search,+ setSearch,originFilter,+ setOriginFilter,typeFilter,+ setTypeFilter,currentTab,+ setCurrentTab,+ openFolder,folderNameDialog,openNewFolderDialog,openRenameFolderDialog,diff --git a/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsx b/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsxnew file mode 100644index 0000000000..7056f42f2d--- /dev/null+++ b/frontend/editor/src/core/contexts/FilesPageContext.upload.test.tsx@@ -0,0 +1,172 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { MemoryRouter } from "react-router-dom";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ FilesPageProvider,+ useFilesPage,+} from "@app/contexts/FilesPageContext";+import type { StirlingFileStub } from "@app/types/fileContext";+import type { FolderId, FolderRecord } from "@app/types/folder";+import type { FileId } from "@app/types/file";++const state = vi.hoisted(() => ({+ files: [] as StirlingFileStub[],+ upload: vi.fn(),+ bulkMove: vi.fn(),+ cacheMove: vi.fn(),+ updateMetadata: vi.fn(),+ folders: {+ folders: [] as FolderRecord[],+ foldersById: new Map<FolderId, FolderRecord>(),+ currentFolderId: null,+ setError: vi.fn(),+ },+ actions: { updateStirlingFileStub: vi.fn() },+ disk: { openFileIdsRef: { current: [] }, onOpenFilesDetached: vi.fn() },+}));+vi.mock("@app/services/fileStorage", () => ({+ fileStorage: {+ getAllStirlingFileStubs: async () => state.files,+ getStirlingFileStub: async (id: FileId) =>+ state.files.find((file) => file.id === id),+ updateFileMetadata: state.updateMetadata,+ },+}));+vi.mock("@app/services/serverStorageUpload", () => ({+ uploadHistoryChain: state.upload,+}));+vi.mock("@app/services/folderSyncService", () => ({+ folderSyncService: { bulkMoveFiles: state.bulkMove },+}));+vi.mock("@app/services/fileSyncService", () => ({+ reconcileServerFiles: async (files: StirlingFileStub[]) => files,+}));+vi.mock("@app/services/pruneMissingRecentFiles", () => ({+ pruneMissingRecentFiles: async (files: StirlingFileStub[]) => files,+}));+vi.mock("@app/contexts/IndexedDBContext", () => ({+ useIndexedDB: () => ({ moveFilesToFolder: state.cacheMove }),+ useIndexedDBRevision: () => 0,+}));+vi.mock("@app/contexts/FolderContext", () => ({+ useFolders: () => state.folders,+}));+vi.mock("@app/contexts/file/fileHooks", () => ({+ useFileActions: () => ({ actions: state.actions }),+}));+vi.mock("@app/hooks/useDiskLinkReconcile", () => ({+ useDiskLinkReconcile: () => state.disk,+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: { storageEnabled: true } }),+}));+vi.mock("@app/auth/UseSession", () => ({+ useAuth: () => ({ isAnonymous: false }),+}));++const stub = (id: string): StirlingFileStub => ({+ id: id as FileId,+ originalFileId: id as FileId,+ name: `${id}.pdf`,+ isLeaf: true,+ versionNumber: 1,+ type: "application/pdf",+ size: 1024,+ lastModified: 123,+});+const show = () =>+ renderHook(() => useFilesPage(), {+ wrapper: ({ children }) => (+ <MemoryRouter initialEntries={["/files?view=recent"]}>+ <FilesPageProvider>{children}</FilesPageProvider>+ </MemoryRouter>+ ),+ });++describe("adding browser files to the library", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ state.files = [stub("one"), stub("two"), stub("three")];+ state.updateMetadata.mockImplementation(+ async (id: FileId, patch: Partial<StirlingFileStub>) => {+ state.files = state.files.map((file) =>+ file.id === id ? { ...file, ...patch } : file,+ );+ },+ );+ state.upload.mockImplementation(async (id: FileId) => ({+ remoteId: state.files.findIndex((file) => file.id === id) + 1,+ updatedAt: 123,+ chain: [state.files.find((file) => file.id === id)],+ }));+ state.bulkMove.mockImplementation(async (ids: number[]) => ({+ movedFileIds: ids,+ skippedFileIds: [],+ }));+ });++ it("uploads separate files to root and keeps Recents selected", async () => {+ const { result } = show();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(() =>+ result.current.moveFilesTo([state.files[0].id, state.files[1].id], null, {+ uploadToRoot: true,+ }),+ );+ expect(state.upload).toHaveBeenCalledTimes(2);+ expect(state.bulkMove).toHaveBeenCalledWith([1, 2], null);+ expect(state.cacheMove).toHaveBeenCalledWith(["one", "two"], null);+ expect(result.current.fileMap.get("one" as FileId)?.remoteStorageId).toBe(+ 1,+ );+ expect(result.current.fileMap.get("two" as FileId)?.remoteStorageId).toBe(+ 2,+ );+ expect(result.current.currentTab).toBe("recent");+ });++ it("places successful uploads in the chosen folder even when a file between them fails", async () => {+ const normalUpload = state.upload.getMockImplementation()!;+ state.upload.mockImplementation(async (id: FileId) => {+ if (id === "two") throw new Error("Missing file data");+ return normalUpload(id);+ });+ const { result } = show();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async () => {+ await expect(+ result.current.moveFilesTo(+ state.files.map((file) => file.id),+ "target" as FolderId,+ { uploadToRoot: true },+ ),+ ).rejects.toThrow("two.pdf: Missing file data");+ });+ expect(state.bulkMove).toHaveBeenCalledWith([1, 3], "target");+ expect(state.cacheMove).toHaveBeenCalledWith(["one", "three"], "target");+ expect(+ result.current.fileMap.get("two" as FileId)?.remoteStorageId,+ ).toBeUndefined();+ });++ it("does not upload a normal move to root", async () => {+ const { result } = show();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(() => result.current.moveFilesTo([state.files[0].id], null));+ expect(state.upload).not.toHaveBeenCalled();+ });++ it("reports a refused destination instead of reporting a successful add", async () => {+ state.bulkMove.mockResolvedValue({ movedFileIds: [], skippedFileIds: [1] });+ const { result } = show();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async () => {+ await expect(+ result.current.moveFilesTo([state.files[0].id], "target" as FolderId, {+ uploadToRoot: true,+ }),+ ).rejects.toThrow();+ });+ expect(state.cacheMove).not.toHaveBeenCalled();+ });+});diff --git a/frontend/editor/src/core/contexts/FolderContext.test.tsx b/frontend/editor/src/core/contexts/FolderContext.test.tsxindex 9090731e93..6ce550bc7a 100644--- a/frontend/editor/src/core/contexts/FolderContext.test.tsx+++ b/frontend/editor/src/core/contexts/FolderContext.test.tsx@@ -526,7 +526,7 @@ describe("FolderContext disk subfolder resolution", () => {</MemoryRouter>,);await waitFor(() =>- expect(screen.getByTestId("count").textContent).toBe("1"),+ expect(apiRef.current?.knows(diskFolderId(MOUNT_DIR))).toBe(true),);if (!apiRef.current) throw new Error("DiskProbe never reported ready");return apiRef as { current: DiskProbeApi };diff --git a/frontend/editor/src/core/hooks/useDropzoneFiles.test.ts b/frontend/editor/src/core/hooks/useDropzoneFiles.test.tsnew file mode 100644index 0000000000..8dff9e60dc--- /dev/null+++ b/frontend/editor/src/core/hooks/useDropzoneFiles.test.ts@@ -0,0 +1,29 @@+import { renderHook } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import { useDropzoneFiles } from "@app/hooks/useDropzoneFiles";++const { alert } = vi.hoisted(() => ({ alert: vi.fn() }));+vi.mock("@app/components/toast", () => ({ alert }));++describe("drop failure reporting", () => {+ it("reports partial failures outside a modal while retaining readable files", async () => {+ const file = new File(["PDF"], "Readable.pdf");+ const event = Object.assign(new Event("drop"), {+ dataTransfer: {+ items: [+ { kind: "file", getAsFile: () => null },+ { kind: "file", getAsFile: () => file },+ ],+ },+ });+ const { result } = renderHook(() => useDropzoneFiles());++ await expect(result.current(event)).resolves.toEqual([file]);+ expect(alert).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ alertType: "error",+ body: "Could not read a dropped file.",+ }),+ );+ });+});diff --git a/frontend/editor/src/core/hooks/useDropzoneFiles.ts b/frontend/editor/src/core/hooks/useDropzoneFiles.tsnew file mode 100644index 0000000000..b2538af3bd--- /dev/null+++ b/frontend/editor/src/core/hooks/useDropzoneFiles.ts@@ -0,0 +1,43 @@+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { alert } from "@app/components/toast";+import { getDropzoneFiles } from "@app/utils/getDropzoneFiles";++/**+ * Keeps readable files when entries fail; reports errors through onError or a toast.+ * Mantine dropzones must set useFsAccessApi=false; native drop events work directly.+ */+export function useDropzoneFiles(onError?: (error: Error) => void) {+ const { t } = useTranslation();+ return useCallback(+ async (event: Parameters<typeof getDropzoneFiles>[0]) => {+ const reportError = (error: Error) => {+ if (onError) onError(error);+ else+ alert({+ alertType: "error",+ title: t("filePicker.errorTitle", "Couldn't add files"),+ body: error.message,+ expandable: false,+ durationMs: 5000,+ });+ };+ try {+ return await getDropzoneFiles(event, reportError);+ } catch (cause) {+ reportError(+ cause instanceof Error+ ? cause+ : new Error(+ t(+ "filePicker.error",+ "Could not add these files. Please try again.",+ ),+ ),+ );+ return [];+ }+ },+ [onError, t],+ );+}diff --git a/frontend/editor/src/core/hooks/useGoogleDrivePicker.test.ts b/frontend/editor/src/core/hooks/useGoogleDrivePicker.test.tsnew file mode 100644index 0000000000..0f538834f8--- /dev/null+++ b/frontend/editor/src/core/hooks/useGoogleDrivePicker.test.ts@@ -0,0 +1,39 @@+import { act, renderHook, waitFor } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import { useGoogleDrivePicker } from "@app/hooks/useGoogleDrivePicker";+import { allowConsole } from "@app/tests/failOnConsole";++const service = vi.hoisted(() => ({+ initialize: vi.fn().mockResolvedValue(undefined),+ openPicker: vi.fn(),+}));+vi.mock("@app/contexts/AppConfigContext", () => ({+ useAppConfig: () => ({ config: { googleDriveEnabled: true } }),+}));+vi.mock("@app/services/googleDrivePickerService", () => ({+ extractGoogleDriveBackendConfig: () => ({}),+ isGoogleDriveConfigured: () => true,+ getGoogleDriveConfig: () => ({}),+ getGoogleDrivePickerService: () => service,+}));++it("clears a failed Drive attempt and can retry without reinitializing the service", async () => {+ allowConsole.error(/Google Drive picker error/);+ const file = new File(["PDF"], "Drive.pdf");+ service.openPicker+ .mockRejectedValueOnce(new Error("Access denied"))+ .mockResolvedValueOnce([file]);+ const { result } = renderHook(useGoogleDrivePicker);+ await waitFor(() => expect(result.current.isEnabled).toBe(true));+ await act(async () => {+ expect(await result.current.openPicker()).toEqual([]);+ });+ expect(result.current.error).toBe("Access denied");+ expect(result.current.isLoading).toBe(false);+ act(() => result.current.clearError());+ expect(result.current.error).toBeNull();+ await act(async () => {+ expect(await result.current.openPicker()).toEqual([file]);+ });+ expect(service.initialize).toHaveBeenCalledOnce();+});diff --git a/frontend/editor/src/core/hooks/useGoogleDrivePicker.ts b/frontend/editor/src/core/hooks/useGoogleDrivePicker.tsindex 901270553d..acc0890b01 100644--- a/frontend/editor/src/core/hooks/useGoogleDrivePicker.ts+++ b/frontend/editor/src/core/hooks/useGoogleDrivePicker.ts@@ -1,7 +1,3 @@-/**- * React hook for Google Drive file picker- */-import { useState, useCallback, useEffect, useMemo } from "react";import { useAppConfig } from "@app/contexts/AppConfigContext";import {@@ -20,20 +16,20 @@ interface UseGoogleDrivePickerReturn {isEnabled: boolean;isLoading: boolean;error: string | null;+ clearError: () => void;openPicker: (options?: UseGoogleDrivePickerOptions) => Promise<File[]>;}-/**- * Hook to use Google Drive file picker- */+/** Initializes Drive lazily; failed picks resolve to [] and set error until cleared or retried. */export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {const { config } = useAppConfig();const [isEnabled, setIsEnabled] = useState(false);const [isLoading, setIsLoading] = useState(false);const [error, setError] = useState<string | null>(null);+ const clearError = useCallback(() => setError(null), []);const [isInitialized, setIsInitialized] = useState(false);- // Memoize backend config to only track Google Drive specific properties+ // Unrelated app settings must not invalidate Drive's config or picker callbacks.const googleDriveBackendConfig = useMemo(() => extractGoogleDriveBackendConfig(config),[@@ -44,19 +40,14 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {],);- // Check if Google Drive is configured and reset initialization if disableduseEffect(() => {const configured = isGoogleDriveConfigured(googleDriveBackendConfig);setIsEnabled(configured);- // Reset initialization state if Google Drive becomes disabledif (!configured) {setIsInitialized(false);}}, [googleDriveBackendConfig]);- /**- * Initialize the Google Drive service (lazy initialization)- */const initializeService = useCallback(async () => {if (isInitialized) return;@@ -70,9 +61,6 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {setIsInitialized(true);}, [isInitialized, googleDriveBackendConfig]);- /**- * Open the Google Drive picker- */const openPicker = useCallback(async (options: UseGoogleDrivePickerOptions = {}): Promise<File[]> => {if (!isEnabled) {@@ -84,10 +72,8 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {setIsLoading(true);setError(null);- // Initialize service if neededawait initializeService();- // Open pickerconst service = getGoogleDrivePickerService();const files = await service.openPicker({multiple: options.multiple ?? true,@@ -114,6 +100,7 @@ export function useGoogleDrivePicker(): UseGoogleDrivePickerReturn {isEnabled,isLoading,error,+ clearError,openPicker,};}diff --git a/frontend/editor/src/core/hooks/useNewFolderFlow.ts b/frontend/editor/src/core/hooks/useNewFolderFlow.tsindex a5ab6b85e9..65febcae55 100644--- a/frontend/editor/src/core/hooks/useNewFolderFlow.ts+++ b/frontend/editor/src/core/hooks/useNewFolderFlow.ts@@ -5,24 +5,40 @@ import { useFolders } from "@app/contexts/FolderContext";import { useFilesPage } from "@app/contexts/FilesPageContext";import { canPickDirectory, pickDirectory } from "@app/services/directoryPicker";import { useServerFolderBlock } from "@app/hooks/useServerFolderBlock";+import { folderKind } from "@app/types/folder";-/** The folder-creation flows, shared by every surface that offers them so they- * cannot drift apart. */+/**+ * Mounts and opens picked directories; otherwise opens the creation dialog.+ * Reports picker and mount failures through FolderContext.+ */export function useNewFolderFlow() {const { t } = useTranslation();const folders = useFolders();- const { openNewFolderDialog } = useFilesPage();+ const { currentTab, openNewFolderDialog } = useFilesPage();const navigate = useNavigate();const serverFolderBlock = useServerFolderBlock();+ const currentFolder = folders.currentFolderId+ ? folders.foldersById.get(folders.currentFolderId)+ : undefined;+ const needsServer =+ (currentFolder && folderKind(currentFolder) === "server") ||+ (folders.currentFolderId === null && !canPickDirectory);+ const createFolderHereBlockedReason =+ currentTab !== "all" && currentTab !== "cloud"+ ? t(+ "filesPage.newFolderTabUnavailable",+ "Switch to Stirling library to create folders.",+ )+ : needsServer+ ? serverFolderBlock+ : null;- // No dialog: the picker is the whole interaction and the directory names the folder.const addLocalFolder = useCallback(async () => {try {const picked = await pickDirectory();if (!picked) return;const record = await folders.mountLocalFolder(picked.path, picked.name);- // The path owns folder selection: setting state here races the effect that- // re-runs with the old pathname and snaps back to root.+ // The URL owns folder selection; updating folder state first races navigation.navigate(`/files/${record.id}`);} catch (err) {folders.setError(@@ -36,10 +52,8 @@ export function useNewFolderFlow() {}}, [folders, navigate, t]);- // Single-click New folder for surfaces with no menu: the picker where the build- // can see the disk, a server folder on the web, and blocked rather than silent- // when the server cannot take one. Inside a folder the kind is inherited.const createFolderHere = useCallback(() => {+ if (createFolderHereBlockedReason !== null) return;if (folders.currentFolderId !== null) {openNewFolderDialog(folders.currentFolderId);return;@@ -48,23 +62,18 @@ export function useNewFolderFlow() {void addLocalFolder();return;}- // Backstop: surfaces disable themselves, so a click here means stale UI.- if (serverFolderBlock === null) {- openNewFolderDialog(null, "server");- }+ openNewFolderDialog(null, "server");}, [addLocalFolder,+ createFolderHereBlockedReason,folders.currentFolderId,openNewFolderDialog,- serverFolderBlock,]);- // Why the single-click surfaces are disabled, or null. Only the web root blocks:- // desktop always has the picker, and subfolders inherit their kind.- const createFolderHereBlockedReason =- folders.currentFolderId === null && !canPickDirectory- ? serverFolderBlock- : null;-- return { addLocalFolder, createFolderHere, createFolderHereBlockedReason };+ return {+ addLocalFolder,+ createFolderHere,+ createFolderHereBlockedReason,+ serverFolderBlock,+ };}diff --git a/frontend/editor/src/core/icons/icons.ts b/frontend/editor/src/core/icons/icons.tsindex 4d0d15ec6b..351f07fe4e 100644--- a/frontend/editor/src/core/icons/icons.ts+++ b/frontend/editor/src/core/icons/icons.ts@@ -79,6 +79,7 @@ import ClipboardPlus from "lucide-static/icons/clipboard-plus.svg?react";import Clock from "lucide-static/icons/clock.svg?react";import Cloud from "lucide-static/icons/cloud.svg?react";import CloudCheck from "lucide-static/icons/cloud-check.svg?react";+import CloudOff from "lucide-static/icons/cloud-off.svg?react";import CloudUpload from "lucide-static/icons/cloud-upload.svg?react";import Code from "lucide-static/icons/code.svg?react";import Cog from "lucide-static/icons/cog.svg?react";@@ -483,6 +484,7 @@ export const ICONS = {clock: { Component: Clock, kind: "lucide" },cloud: { Component: Cloud, kind: "lucide" },"cloud-check": { Component: CloudCheck, kind: "lucide" },+ "cloud-off": { Component: CloudOff, kind: "lucide" },"cloud-upload": { Component: CloudUpload, kind: "lucide" },code: { Component: Code, kind: "lucide" },cog: { Component: Cog, kind: "lucide" },diff --git a/frontend/editor/src/core/pages/HomePage.tsx b/frontend/editor/src/core/pages/HomePage.tsxindex 7706681d07..0019ff4a5e 100644--- a/frontend/editor/src/core/pages/HomePage.tsx+++ b/frontend/editor/src/core/pages/HomePage.tsx@@ -61,15 +61,13 @@ import {useFilesPage,} from "@app/contexts/FilesPageContext";import { useFolders } from "@app/contexts/FolderContext";-import { folderKind } from "@app/types/folder";-import { useServerFolderBlock } from "@app/hooks/useServerFolderBlock";import { useNewFolderFlow } from "@app/hooks/useNewFolderFlow";import { NewFolderButton } from "@app/components/filesPage/NewFolderButton";import MobileUploadModal from "@app/components/shared/MobileUploadModal";import { useLibraryRefresh } from "@app/hooks/useLibraryRefresh";import { useAuth } from "@app/auth/UseSession";import { canPickDirectory } from "@app/services/directoryPicker";-import { useFileHandler } from "@app/hooks/useFileHandler";+import { useLibraryUpload } from "@app/components/filesPage/useLibraryUpload";import { useProcessingFolderCreation } from "@app/hooks/useProcessingFolderCreation";import { consumeProcessingFolderCreationRequest } from "@app/utils/pendingProcessingFolderCreation";import type { FileSidebarProps } from "@app/components/shared/FileSidebar";@@ -191,19 +189,12 @@ export default function HomePage() {return () => window.removeEventListener("keydown", onKeyDown);}, [readerMode, searchInterfaceActions]);- // Clean slate: no tool, out of the file library and reading.const goToDefaultState = useCallback(() => {handleBackToTools();actions.setWorkbench(getDefaultWorkbenchForFileCount(activeFiles.length));}, [handleBackToTools, actions, activeFiles.length]);- // The library is a view like the viewer and the file editor: which view is on screen- // is state, the path says which folder you are in. Each side moves the other on a- // transition only: asserting either on every render lets the path re-impose- // "myFiles" a render after anything else has set a view.-- // Path moved, so the path is the cause: arrival, back/forward, or a deliberate- // navigate. Mount included, which is what seeds a deep link.+ // Reconcile route and workspace only on transitions, or the old route can undo a view change.const derivedFromPath = actions.viewDerivedFromPathRef;useEffect(() => {if (derivedFromPath.current === location.pathname) return;@@ -339,7 +330,6 @@ export default function HomePage() {const brandAltText = t("home.mobile.brandAlt", "Stirling PDF logo");- // The tool picker's own helpers, so the wording can't drift.const quickNavToolReasons = useMemo(() => {const reasons: QuickNavToolReasons = {};for (const id of ["automate", "sharedSign"] as const) {@@ -424,7 +414,6 @@ export default function HomePage() {const offset = activeMobileView === "tools" ? 0 : container.offsetWidth;container.scrollTo({ left: offset, behavior: "smooth" });- // Re-enable scroll listener after animation completessetTimeout(() => {isProgrammaticScroll.current = false;}, 500);@@ -478,7 +467,6 @@ export default function HomePage() {};}, [isMobile, dismissSwipeHint]);- // Automatically switch to workbench when read mode or multiTool is activated in mobileuseEffect(() => {if (isMobile && (readerMode || selectedToolKey === "multiTool")) {setActiveMobileView("workbench");@@ -496,7 +484,6 @@ export default function HomePage() {// When navigating back to tools view in mobile with a workbench-only tool, show tool pickeruseEffect(() => {if (isMobile && activeMobileView === "tools" && selectedTool) {- // Check if this is a workbench-only tool (has workbench but no component)if (selectedTool.workbench && !selectedTool.component) {setLeftPanelView("toolPicker");}@@ -546,8 +533,6 @@ export default function HomePage() {: baseUrl,});- // Note: File selection limits are now handled directly by individual tools-return (<div className="h-screen overflow-hidden"><HomePageExtensions />@@ -723,7 +708,6 @@ export default function HomePage() {</span></Button></div>- <FileManager selectedTool={selectedTool} /></div>) : (<Group@@ -754,9 +738,9 @@ export default function HomePage() {{wingsMounted && !hideToolPanel && <RightSidebar />}{readerMode && <ReaderRail />}{readerMode && !strip.enabled && <ReaderSuperSearch />}- <FileManager selectedTool={selectedTool} /></Group>)}+ <FileManager selectedTool={selectedTool} /></FilesPageProvider></div>);@@ -783,9 +767,13 @@ const MyFilesSidebarOverrides = forwardRef<HTMLDivElement, FileSidebarProps>(const { t } = useTranslation();const filesPage = useFilesPage();const folders = useFolders();- const { addFiles } = useFileHandler();- const { addLocalFolder, createFolderHere, createFolderHereBlockedReason } =- useNewFolderFlow();+ const handleUpload = useLibraryUpload();+ const {+ addLocalFolder,+ createFolderHere,+ createFolderHereBlockedReason: newFolderDisabledReason,+ serverFolderBlock,+ } = useNewFolderFlow();const { refreshing, refresh: refreshLibrary } = useLibraryRefresh();const { isAnonymous } = useAuth();const { config: appConfig } = useAppConfig();@@ -799,35 +787,6 @@ const MyFilesSidebarOverrides = forwardRef<HTMLDivElement, FileSidebarProps>(? t("filesPage.signInRequired", "Sign in to use cloud storage."): null;- const handleUpload = useCallback(- async (files: File[]) => {- const added = await addFiles(files, { skipWorkspaceDispatch: true });- await filesPage.refresh();- // If the user is inside a cloud folder, place uploads there.- if (folders.currentFolderId !== null && added.length > 0) {- await filesPage.moveFilesTo(- added.map((f) => f.fileId),- folders.currentFolderId,- );- }- },- [addFiles, filesPage, folders.currentFolderId],- );-- // Kind-aware: only a server folder's subfolder needs the server, and a mounted- // directory takes no subfolders from here at all.- const railCurrentFolder = folders.currentFolderId- ? folders.foldersById.get(folders.currentFolderId)- : undefined;- const railCurrentKind = railCurrentFolder- ? folderKind(railCurrentFolder)- : null;- const serverFolderBlock = useServerFolderBlock();- const newFolderDisabledReason =- railCurrentKind === "server"- ? serverFolderBlock- : createFolderHereBlockedReason;-return (<><FileSidebar@@ -843,9 +802,7 @@ const MyFilesSidebarOverrides = forwardRef<HTMLDivElement, FileSidebarProps>(disabled: newFolderDisabledReason !== null,disabledTooltip: newFolderDisabledReason ?? undefined,testId: "files-rail-new-folder",- // The same control the library's other surfaces use, so one row- // cannot offer less than another: where a folder can go decides- // its shape.+ // Share folder availability rules with the library toolbar.render: () => (<NewFolderButtontrigger="row"diff --git a/frontend/editor/src/core/services/fileSyncService.ts b/frontend/editor/src/core/services/fileSyncService.tsindex 599f397b12..5cdf1e85d4 100644--- a/frontend/editor/src/core/services/fileSyncService.ts+++ b/frontend/editor/src/core/services/fileSyncService.ts@@ -237,6 +237,7 @@ export async function reconcileServerFiles(const lastModified = Number.isFinite(updatedAtMs)? updatedAtMs: Date.now();+ const createdAtMs = file.createdAt ? Date.parse(file.createdAt) : NaN;const id = `server-${file.id}` as FileId;serverStubs.push({id,@@ -244,7 +245,7 @@ export async function reconcileServerFiles(type: file.contentType || "application/octet-stream",size: file.sizeBytes ?? 0,lastModified,- createdAt: lastModified,+ createdAt: Number.isFinite(createdAtMs) ? createdAtMs : lastModified,isLeaf: true,originalFileId: id,versionNumber: 1,diff --git a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts b/frontend/editor/src/core/tests/helpers/tauriDiskStub.tsindex 648cecb496..5bf5076c8d 100644--- a/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts+++ b/frontend/editor/src/core/tests/helpers/tauriDiskStub.ts@@ -294,10 +294,7 @@ export async function seedFiles(page: Page, files: SeedFile[]) {export async function dismissModals(page: Page) {for (let i = 0; i < 8; i++) {- // Dialog-scoped first, and deliberately not by aria-label: the welcome- // carousel's close button carries none, so an attribute match lands on the- // window chrome's Close - which is earlier in the DOM and does nothing -- // and the carousel's overlay then eats every click that follows.+ // Scope to the modal: the window chrome also has a Close control but cannot dismiss overlays.const inDialog = page.getByRole("dialog").getByRole("button", { name: "Close" })@@ -310,14 +307,12 @@ export async function dismissModals(page: Page) {await close.click({ timeout: 2000 }).catch(() => {});await page.waitForTimeout(250);}- // Deliberately no Escape here: it backs the file manager out to the editor,- // which silently moved every later scenario off the file list.+ // Escape leaves the library, so dismiss overlays with their own controls.await page.waitForTimeout(300);}export async function openCard(page: Page, name: string) {- // Scope to the grid card: a bare text match also hits the library rail on the- // left, which navigates without loading the file into the workbench.+ // Sidebar matches navigate without opening the file; target the grid card.const card = page.locator(".files-page-card", { hasText: name.replace(/\.pdf$/, "") }).first();@@ -329,8 +324,7 @@ export async function openCard(page: Page, name: string) {.getByRole("button", { name: /Open Files/i }).waitFor({ state: "detached", timeout: 15_000 }).catch(() => {});- // And for the document itself to render - a re-read from disk re-parses the- // file, so the viewer sits on "Loading tool…" well after the toast has fired.+ // Disk reads reparse the document; wait for rendering as well as the route change.await page.getByText(/Loading tool/i).waitFor({ state: "detached", timeout: 20_000 })@@ -339,7 +333,7 @@ export async function openCard(page: Page, name: string) {}export async function gotoFiles(page: Page) {- await page.goto("/files");+ await page.goto("/files?view=recent");await page.waitForLoadState("networkidle");await page.waitForTimeout(800);}diff --git a/frontend/editor/src/core/tests/helpers/ui-helpers.ts b/frontend/editor/src/core/tests/helpers/ui-helpers.tsindex 1a8583b168..85577fc890 100644--- a/frontend/editor/src/core/tests/helpers/ui-helpers.ts+++ b/frontend/editor/src/core/tests/helpers/ui-helpers.ts@@ -1,52 +1,29 @@import { expect, type Page, type Locator } from "@playwright/test";-/**- * Shared UI helpers for Playwright specs.- *- * Centralises the patterns repeated across the suite (file upload, settings- * dialog, run-button + review-panel wait, viewer-mode escape, modal-overlay- * waits) so each spec stays focused on its assertion rather than the- * machinery.- */-const MANTINE_MODAL_OVERLAY = ".mantine-Modal-overlay";+/** Opens Recents through in-app navigation, preserving the current workspace. */+export async function openRecents(page: Page): Promise<void> {+ await page+ .getByRole("navigation", { name: /Quick navigation/i })+ .getByRole("button", { name: /^File library$/i })+ .click();+ await page+ .getByRole("navigation", { name: "File sources", exact: true })+ .getByRole("button", { name: "Recents", exact: true })+ .click();+ await expect(page).toHaveURL(/\/files\?view=recent$/);+}+/**- * Suppress the native OS file picker for the whole page, on every browser.- *- * Several upload entry points (the FileSidebar "Open from computer" button,- * the Mantine `<FileInput>`, AddFileCard, etc.) open a file dialog by clicking- * a hidden `<input type="file">`. On firefox/webkit Playwright only intercepts- * that dialog while the page has a `filechooser` listener - it toggles- * `Page.setInterceptFileChooserDialog` off the event subscription. With no- * listener the real OS picker leaks onto the host and hangs the nightly run.- *- * Registering a (no-op) `filechooser` listener flips that interception on for- * every browser, so the dialog is suppressed at the browser level however it- * was triggered - a programmatic `.click()`, a `<label>` activation, or- * Playwright's own click. We deliberately don't set files in the handler: specs- * still drive uploads explicitly via `setInputFiles()`, which sets files- * through the protocol regardless of the pending intercepted chooser. This lets- * a spec click the real entry-point button while the picker stays mocked- * cross-browser - unlike a global `HTMLInputElement.prototype.click` override,- * which misses `<label>`-triggered pickers and never enables Playwright's own- * interception.- *- * Installed once per page by the shared test fixtures (stub + live), so no spec- * has to opt in.+ * Installs file-chooser interception for every browser; specs supply files via setInputFiles().+ * A listener is required even for hidden-input clicks, or Firefox/WebKit open a real OS dialog.+ * Stub and live fixtures install this once per page.*/export function suppressNativeFilePicker(page: Page): void {- page.on("filechooser", () => {- // Interception alone suppresses the native dialog; specs provide the files- // themselves via setInputFiles() on the hidden input.- });+ page.on("filechooser", () => {});}-/**- * Wait for a Mantine Modal overlay to appear or disappear. Most file pickers,- * settings dialogs, encrypted-PDF unlock prompts and so on render through- * this overlay; specs use it as a synchronisation point.- */export async function waitForModalOpen(page: Page,timeout = 5_000,@@ -67,13 +44,7 @@ export async function waitForModalClose(});}-/**- * Upload one or more files through the FileSidebar's "Open from computer"- * action. The native picker is mocked globally by `suppressNativeFilePicker`,- * so the click is safe on every browser; files are set on the hidden input via- * `setInputFiles`. Returns only once the files are durably in IndexedDB, so- * callers may navigate or reload without racing the write.- */+/** Uploads through the sidebar and waits for IndexedDB persistence before callers navigate. */export async function uploadFiles(page: Page,filePaths: string | string[],@@ -82,22 +53,13 @@ export async function uploadFiles(const names = paths.map((p) => p.split(/[\\/]/).pop() ?? p);await page.getByTestId("files-button").click();await page.locator('[data-testid="file-input"]').setInputFiles(paths);- // The sidebar renders from in-memory state, before the IDB write commits.- // first() so multi-file uploads pass too.await expect(page.locator(".file-sidebar-file-item").first()).toBeVisible({timeout: 10_000,});- // A navigation before the write commits aborts the transaction and drops the- // file, so wait for it to land rather than assume the sidebar means it did.await waitForStoredFiles(page, names);}-/**- * Resolve once every uploaded name is in the files store. Read-only: aborts- * rather than create or upgrade the DB, so it can't race the app's own- * versioned open and leave it without object stores. Reads only a DB the app- * already made; until then each poll returns false and retries.- */+/** Polls an existing database without creating or upgrading it, so setup cannot race the app. */async function waitForStoredFiles(page: Page, names: string[]): Promise<void> {await page.waitForFunction((expected) =>@@ -140,33 +102,18 @@ async function waitForStoredFiles(page: Page, names: string[]): Promise<void> {);}-/**- * Some tools (Merge in particular) park the workbench in `viewer` mode after- * upload, which keeps the run button disabled. The UI exposes a "Go to file- * editor" affordance to switch out of viewer mode; this helper clicks it- * when present and is a no-op otherwise.- */+/** Leaves upload-induced viewer mode when present, so tool controls can enable. */export async function switchToEditorIfViewerMode(page: Page): Promise<void> {const goToEditor = page.getByRole("button", {name: /go to file editor/i,});- // The affordance only exists while the workbench is transiently in viewer- // mode after an upload. The app can auto-leave viewer mode and detach the- // button between our visibility check and the click - the transition timing- // differs on firefox/webkit, where the detached button hangs a plain- // `click()` for the full actionability timeout. Treat a vanished button as- // "already in editor mode": swallow the click failure and let the caller's- // run-button assertion catch any genuine regression.+ // Auto-navigation may detach this button; the caller's run-button assertion checks readiness.if (await goToEditor.isVisible({ timeout: 1_000 }).catch(() => false)) {await goToEditor.click({ timeout: 5_000 }).catch(() => {});}}-/**- * Click the tool's run button and wait for the review panel to render with- * the produced output. Throws if the run button never enables or the review- * panel never appears, both of which are real regressions.- */+/** Runs the tool and waits for its output review panel; rejects if either stays unavailable. */export async function runToolAndWaitForReview(page: Page,opts: { runTimeout?: number; reviewTimeout?: number } = {},@@ -183,12 +130,7 @@ export async function runToolAndWaitForReview(/** The settings page's root. Settings is a route, not a dialog. */export const SETTINGS_SURFACE = ".settings-page";-/**- * Go to the global Settings page by the rail's avatar, the only entry there is,- * which opens on the Account section. Pass `section` to land on a named one- * instead. Returns the page's root locator so callers can scope further- * queries to it.- */+/** Opens Settings through the avatar and returns its root for scoped queries. Defaults to Account. */export async function openSettings(page: Page,section?: string | RegExp,@@ -211,10 +153,7 @@ export async function openSettings(return surface;}-/**- * Leave Settings the way a reader does now that the nav has no Back control:- * browser back, which lands on the origin because tab switches replace.- */+/** Uses browser Back to leave Settings; section changes replace the current history entry. */export async function closeSettings(page: Page): Promise<void> {const surface = page.locator(SETTINGS_SURFACE);// Retry: one back can land on another /settings entry if a spec pushed one.diff --git a/frontend/editor/src/core/tests/stubbed/file-actions-menu.spec.ts b/frontend/editor/src/core/tests/stubbed/file-actions-menu.spec.tsindex 9695a36d6a..59c0a095c8 100644--- a/frontend/editor/src/core/tests/stubbed/file-actions-menu.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/file-actions-menu.spec.ts@@ -1,14 +1,10 @@import path from "path";import type { Page } from "@playwright/test";import { test, expect } from "@app/tests/helpers/stub-test-base";-import { uploadFiles } from "@app/tests/helpers/ui-helpers";+import { openRecents, uploadFiles } from "@app/tests/helpers/ui-helpers";-// Reads the library as cards, so it asks for the grid.test.use({ filesViewMode: "grid" });-// Per-file actions live behind a kebab on two surfaces - the file sidebar and-// the My Files grid. They must offer the same file actions on both.-const SAMPLE = path.join(import.meta.dirname, "../test-fixtures/sample.pdf");const rows = (page: Page) => page.locator(".file-sidebar-file-item");@@ -101,33 +97,25 @@ test("a duplicate inherits the original's classification", async ({ page }) => {await openKebab(page);await page.getByRole("menuitem", { name: "Duplicate" }).click();- // The copy carries the label straight away - its row shows the label chip...const copy = rows(page).filter({ hasText: "classified_invoice (copy).pdf" }).first();await expect(copy).toContainText("Invoice", { timeout: 5_000 });- // ...and it counts towards the same category group.await expect(financial.locator(".file-sidebar-group-count")).toHaveText("2");});-// ─── My Files grid: the same actions, same behaviour ────────────────────────-const cards = (page: Page) => page.locator(".files-page-card:not(.is-folder)");-/** Upload a file, cross to My Files, and open the card's kebab. */async function openCardKebab(page: Page): Promise<void> {await uploadFiles(page, SAMPLE);- await page- .getByRole("navigation", { name: /Quick navigation/i })- .getByRole("button", { name: /^File library$/i })- .click();+ await openRecents(page);const card = cards(page).filter({ hasText: "sample.pdf" }).first();await expect(card).toBeVisible();await card.getByRole("button", { name: /File actions/i }).click();await expect(page.getByRole("menu")).toBeVisible();}-test("My Files offers the same file actions as the sidebar", async ({+test("Recents offers file actions and adds browser files to the library", async ({page,}) => {await openCardKebab(page);@@ -136,14 +124,17 @@ test("My Files offers the same file actions as the sidebar", async ({await expect(menu.getByRole("menuitem", { name: "Add to workspace" }),).toBeVisible();- await expect(menu.getByRole("menuitem", { name: "Move to…" })).toBeVisible();+ await expect(+ menu.getByRole("menuitem", { name: /Add to Stirling library/ }),+ ).toBeVisible();+ await expect(menu.getByRole("menuitem", { name: "Move to…" })).toHaveCount(0);await expect(menu.getByRole("menuitem", { name: "Download" })).toBeVisible();await expect(menu.getByRole("menuitem", { name: "Rename" })).toBeVisible();await expect(menu.getByRole("menuitem", { name: "Duplicate" })).toBeVisible();await expect(menu.getByRole("menuitem", { name: "Delete" })).toBeVisible();});-test("My Files Download saves the file under its current name", async ({+test("Recents Download saves the file under its current name", async ({page,}) => {await openCardKebab(page);@@ -153,7 +144,7 @@ test("My Files Download saves the file under its current name", async ({expect((await download).suggestedFilename()).toBe("sample.pdf");});-test("My Files Rename updates the card", async ({ page }) => {+test("Recents Rename updates the card", async ({ page }) => {await openCardKebab(page);await page.getByRole("menuitem", { name: "Rename" }).click();@@ -163,7 +154,7 @@ test("My Files Rename updates the card", async ({ page }) => {await expect(cards(page).filter({ hasText: "statement.pdf" })).toHaveCount(1);});-test("My Files Duplicate adds a copy", async ({ page }) => {+test("Recents Duplicate adds a copy", async ({ page }) => {await openCardKebab(page);await page.getByRole("menuitem", { name: "Duplicate" }).click();diff --git a/frontend/editor/src/core/tests/stubbed/file-state-across-tools.spec.ts b/frontend/editor/src/core/tests/stubbed/file-state-across-tools.spec.tsindex ddd274c175..26f0b74b25 100644--- a/frontend/editor/src/core/tests/stubbed/file-state-across-tools.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/file-state-across-tools.spec.ts@@ -1,51 +1,27 @@import { test, expect } from "@app/tests/helpers/stub-test-base";-import { uploadFiles } from "@app/tests/helpers/ui-helpers";+import { openRecents, uploadFiles } from "@app/tests/helpers/ui-helpers";import path from "path";-// Reads the library as cards, so it asks for the grid.test.use({ filesViewMode: "grid" });const FIXTURES_DIR = path.join(import.meta.dirname, "../test-fixtures");const SAMPLE_PDF = path.join(FIXTURES_DIR, "sample.pdf");-/**- * Files uploaded on one tool page should remain in the workbench when the- * user navigates to a different tool. This is FileContext behaviour and- * easy to break with a stale-effect or unmount-clear bug.- *- * Covered for both navigation mechanisms, which take different code paths:- * - a full page reload (page.goto) -> FileContext re-hydrates from IndexedDB- * - an in-app tool-link click -> client-side nav, FileContext stays- * in memory- */test.describe("File state persists across tool navigation", () => {test("file uploaded on /merge survives navigation to /split", async ({page,}) => {await uploadFiles(page, SAMPLE_PDF);- // Sanity: My Files page lists the upload- await page- .getByRole("navigation", { name: /Quick navigation/i })- .getByRole("button", { name: /^File library$/i })- .click();- // The library's grid, which loads its own listing: in the library the sidebar- // shows folders, not files, so nothing answers this sooner.+ await openRecents(page);await expect(page.locator(".files-page-card").filter({ hasText: /sample\.pdf/i }),).toBeVisible({ timeout: 15_000 });- // Navigate to /splitawait page.goto("/split");await page.waitForLoadState("domcontentloaded");- // Re-open My Files - sample.pdf must still be there (persisted across tools)- await page- .getByRole("navigation", { name: /Quick navigation/i })- .getByRole("button", { name: /^File library$/i })- .click();- // The library's grid, which loads its own listing: in the library the sidebar- // shows folders, not files, so nothing answers this sooner.+ await openRecents(page);await expect(page.locator(".files-page-card").filter({ hasText: /sample\.pdf/i }),).toBeVisible({ timeout: 15_000 });@@ -58,10 +34,6 @@ test.describe("File state persists across tool navigation", () => {await page.waitForLoadState("domcontentloaded");await uploadFiles(page, SAMPLE_PDF);- // Navigate via the in-app tool link (client-side React Router nav) rather- // than a full reload, so this exercises the in-memory FileContext path the- // page.goto test above doesn't. Fall back to a direct visit if the nav- // rail isn't showing the link yet.const splitNav = page.getByRole("link", { name: /^Split$/i }).first();if (await splitNav.isVisible({ timeout: 1_000 }).catch(() => false)) {await splitNav.click();@@ -69,19 +41,10 @@ test.describe("File state persists across tool navigation", () => {await page.goto("/split");}- // A client-side nav has no document load event, so waitForLoadState is a- // no-op here. Wait for the route to actually commit before opening the- // file manager; otherwise the my-files click fires mid-transition and- // opens it against a not-yet-settled workbench, which renders a permanent- // empty state (the flaky "0 items" that then passes on retry).+ // Wait for the route to commit before opening the library, or the two navigations race.await expect(page).toHaveURL(/\/split(?:$|[/?#])/);- // The upload must still be listed after the tool switch. A "no files"- // empty state here would mean the client-side nav silently dropped it.- await page- .getByRole("navigation", { name: /Quick navigation/i })- .getByRole("button", { name: /^File library$/i })- .click();+ await openRecents(page);await expect(page.locator(".files-page-card").filter({ hasText: /sample\.pdf/i }),).toBeVisible({ timeout: 15_000 });diff --git a/frontend/editor/src/core/tests/stubbed/files-page-screenshots.spec.ts b/frontend/editor/src/core/tests/stubbed/files-page-screenshots.spec.tsindex 1f0172cc94..3418c5e336 100644--- a/frontend/editor/src/core/tests/stubbed/files-page-screenshots.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/files-page-screenshots.spec.ts@@ -13,9 +13,7 @@ interface SeedFile {}async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {- // Build the server-side view from the cloud entries so reconcileServerFiles- // sees them as still-existing on the server (otherwise they get detached- // and the cloud cards vanish before the screenshot is taken).+ // Match the server listing to the seed so reconciliation keeps its remote pointers.const serverFiles = files.filter((f) => f.remoteStorageId != null).map((f) => ({@@ -40,7 +38,6 @@ async function seedFiles(page: Page, files: SeedFile[]): Promise<void> {const open = window.indexedDB.open("stirling-pdf-files", dbVersion);open.onupgradeneeded = (event) => {const db = (event.target as IDBOpenDBRequest).result;- // Create both `files` and `folders` stores on this DB.if (!db.objectStoreNames.contains("files")) {const store = db.createObjectStore("files", { keyPath: "id" });store.createIndex("name", "name", { unique: false });@@ -141,9 +138,7 @@ async function settle(page: Page, ms = 350): Promise<void> {}test.describe("Files page screenshots", () => {- // Seed a logged-in session: the cloud-folder surfaces (move-dialog- // create-folder, the seeded "Reports" folder) only render once a confirmed,- // non-anonymous user triggers the folder pull (see FolderContext gating).+ // Server folders load only for an authenticated, non-anonymous user.test.use({filesViewMode: "grid",autoGoto: false,@@ -178,7 +173,7 @@ test.describe("Files page screenshots", () => {{ id: "bravo", name: "bravo.pdf", remoteStorageId: null },{ id: "cloud-c", name: "cloud-c.pdf", remoteStorageId: 1001 },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -188,12 +183,12 @@ test.describe("Files page screenshots", () => {await page.screenshot({ path: shotPath("03_subtoolbar_with_files") });});- test("04_kebab_save_to_server_local", async ({ page }) => {+ test("04_kebab_add_to_library_local", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -204,13 +199,13 @@ test.describe("Files page screenshots", () => {.filter({ hasText: "alpha.pdf" });await card.getByRole("button", { name: /File actions/i }).click();await expect(- page.getByRole("menuitem", { name: /^Save to server$/i }),+ page.getByRole("menuitem", { name: /^Add to Stirling library/i }),).toBeVisible();await settle(page);- await page.screenshot({ path: shotPath("04_kebab_save_to_server_local") });+ await page.screenshot({ path: shotPath("04_kebab_add_to_library_local") });});- test("05_kebab_no_save_to_server_cloud", async ({ page }) => {+ test("05_kebab_no_add_to_library_cloud", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [{ id: "cloud-c", name: "cloud-c.pdf", remoteStorageId: 1001 },@@ -227,16 +222,16 @@ test.describe("Files page screenshots", () => {await card.getByRole("button", { name: /File actions/i }).click();await settle(page);await page.screenshot({- path: shotPath("05_kebab_no_save_to_server_cloud"),+ path: shotPath("05_kebab_no_add_to_library_cloud"),});});- test("06_details_panel_save_to_server", async ({ page }) => {+ test("06_details_panel_add_to_library", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -249,16 +244,16 @@ test.describe("Files page screenshots", () => {await expect(page.locator(".files-page-details")).toBeVisible();await settle(page);await page.screenshot({- path: shotPath("06_details_panel_save_to_server"),+ path: shotPath("06_details_panel_add_to_library"),});});test("07_move_dialog_collapsed", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [- { id: "alpha", name: "alpha.pdf", remoteStorageId: null },+ { id: "alpha", name: "alpha.pdf", remoteStorageId: 1001 },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -279,9 +274,9 @@ test.describe("Files page screenshots", () => {test("08_move_dialog_create_folder_expanded", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [- { id: "alpha", name: "alpha.pdf", remoteStorageId: null },+ { id: "alpha", name: "alpha.pdf", remoteStorageId: 1001 },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -312,7 +307,7 @@ test.describe("Files page screenshots", () => {{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },]);await page.setViewportSize({ width: 900, height: 700 });- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -325,7 +320,7 @@ test.describe("Files page screenshots", () => {test("08b_move_dialog_after_create_folder", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [- { id: "alpha", name: "alpha.pdf", remoteStorageId: null },+ { id: "alpha", name: "alpha.pdf", remoteStorageId: 1001 },]);await page.route("**/api/v1/storage/folders",@@ -349,7 +344,7 @@ test.describe("Files page screenshots", () => {},{ times: 5 },);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -365,7 +360,6 @@ test.describe("Files page screenshots", () => {.getByRole("textbox", { name: /New folder name/i }).fill("Reports");await page.getByRole("button", { name: /^Create$/i }).click();- // Inline row collapses back; create succeeded.await expect(page.getByRole("button", { name: /Create new folder/i }),).toBeVisible({ timeout: 3_000 });@@ -375,7 +369,6 @@ test.describe("Files page screenshots", () => {});});- // ─── Dark mode pass ─────────────────────────────────────────────────────async function enableDarkMode(page: Page): Promise<void> {await page.addInitScript(() => {localStorage.setItem("mantine-color-scheme", "dark");@@ -402,7 +395,7 @@ test.describe("Files page screenshots", () => {{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },{ id: "bravo", name: "bravo.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -416,9 +409,9 @@ test.describe("Files page screenshots", () => {await enableDarkMode(page);await stubStorageApis(page);await seedFiles(page, [- { id: "alpha", name: "alpha.pdf", remoteStorageId: null },+ { id: "alpha", name: "alpha.pdf", remoteStorageId: 1001 },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -439,18 +432,12 @@ test.describe("Files page screenshots", () => {});});- // ─── RTL pass ────────────────────────────────────────────────────────────async function enableRtl(page: Page): Promise<void> {- // Seed language + dir before first paint.await page.addInitScript(() => {localStorage.setItem("i18nextLng", "ar-AR");localStorage.setItem("stirling-language", "ar-AR");localStorage.setItem("stirling-language-source", "user");- // On webkit, `document.documentElement` is still null when Playwright- // runs init scripts, so calling setAttribute directly throws - and that- // uncaught error aborts the *following* init script (the IndexedDB seed- // in seedFiles), leaving the grid stuck on skeletons. Guard the access- // and defer to DOMContentLoaded when the element isn't there yet.+ // WebKit init scripts may run before documentElement exists; defer so the IDB seed still runs.const applyDir = () => {document.documentElement.setAttribute("dir", "rtl");document.documentElement.setAttribute("lang", "ar-AR");@@ -478,7 +465,7 @@ test.describe("Files page screenshots", () => {{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },{ id: "bravo", name: "bravo.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -492,9 +479,9 @@ test.describe("Files page screenshots", () => {await enableRtl(page);await stubStorageApis(page);await seedFiles(page, [- { id: "alpha", name: "alpha.pdf", remoteStorageId: null },+ { id: "alpha", name: "alpha.pdf", remoteStorageId: 1001 },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -503,9 +490,7 @@ test.describe("Files page screenshots", () => {const card = page.locator(".files-page-card:not(.is-folder)").filter({ hasText: "alpha.pdf" });- // Locate by stable test ids, not translated accessible names: this test- // runs in Arabic (enableRtl), so English-text locators break once the- // ar-AR strings are actually translated.+ // Arabic labels need language-independent test IDs.await card.getByTestId("file-card-actions").click();await page.getByTestId("file-menu-move-to").click();await page.getByTestId("move-dialog-create-folder-toggle").click();@@ -516,13 +501,13 @@ test.describe("Files page screenshots", () => {});});- test("18_rtl_details_panel_save_to_server", async ({ page }) => {+ test("18_rtl_details_panel_add_to_library", async ({ page }) => {await enableRtl(page);await stubStorageApis(page);await seedFiles(page, [{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -535,17 +520,17 @@ test.describe("Files page screenshots", () => {await expect(page.locator(".files-page-details")).toBeVisible();await settle(page);await page.screenshot({- path: shotPath("18_rtl_details_panel_save_to_server"),+ path: shotPath("18_rtl_details_panel_add_to_library"),});});- test("14_dark_details_panel_save_to_server", async ({ page }) => {+ test("14_dark_details_panel_add_to_library", async ({ page }) => {await enableDarkMode(page);await stubStorageApis(page);await seedFiles(page, [{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({@@ -558,7 +543,7 @@ test.describe("Files page screenshots", () => {await expect(page.locator(".files-page-details")).toBeVisible();await settle(page);await page.screenshot({- path: shotPath("14_dark_details_panel_save_to_server"),+ path: shotPath("14_dark_details_panel_add_to_library"),});});@@ -596,11 +581,9 @@ test.describe("Files page screenshots", () => {});});await page.goto("/files", { waitUntil: "domcontentloaded" });- // Wait for the Reports folder card or list row.await expect(page.getByText("Reports").first()).toBeVisible({timeout: 5_000,});- // Open the kebab on the folder card.const folderCard = page.locator(".files-page-card.is-folder").filter({ hasText: "Reports" })@@ -620,7 +603,7 @@ test.describe("Files page screenshots", () => {{ id: "alpha", name: "alpha.pdf", remoteStorageId: null },]);await page.setViewportSize({ width: 500, height: 900 });- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({diff --git a/frontend/editor/src/core/tests/stubbed/files-page.spec.ts b/frontend/editor/src/core/tests/stubbed/files-page.spec.tsindex 25a5e352ec..f2ea6b54cd 100644--- a/frontend/editor/src/core/tests/stubbed/files-page.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/files-page.spec.ts@@ -1,4 +1,5 @@import { test, expect } from "@app/tests/helpers/stub-test-base";+import { readFileSync } from "node:fs";import type { Locator, Page, Route } from "@playwright/test";import { DATABASE_CONFIGS } from "@app/services/indexedDBManager";@@ -180,16 +181,17 @@ async function openMenuItem(return dropdown.getByRole("menuitem", { name });}-/** Navigate to /files and wait for at least one real (non-skeleton) card.- * `.files-page-card` also matches the loading-state skeleton placeholders, and- * their parent grid carries `aria-busy="true"` which intercepts pointer events- * -- so waiting for any `.files-page-card` races the skeleton→real transition- * and causes flaky timeouts on slower CI runners. */+/** Waits for an interactive card; skeleton cards also match the general card class. */async function gotoFilesPage(page: Page,- { timeout = 10_000 }: { timeout?: number } = {},+ {+ timeout = 10_000,+ view = "recent",+ }: { timeout?: number; view?: "all" | "recent" } = {},): Promise<void> {- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto(view === "recent" ? "/files?view=recent" : "/files", {+ waitUntil: "domcontentloaded",+ });await expect(page.locator(".files-page-card:not(.files-page-skeleton-card)").first(),).toBeVisible({ timeout });@@ -274,14 +276,16 @@ test.describe("Files page", () => {});test.use({ autoGoto: false });- test("Save to server hidden when nothing selected", async ({ page }) => {+ test("Add to Stirling library hidden when nothing selected", async ({+ page,+ }) => {await gotoFilesPage(page);await expect(- page.getByRole("button", { name: /^Save to server$/i }),+ page.locator(".files-page-toolbar-bulk-trigger"),).toHaveCount(0);});- test("Save to server visible when local file selected", async ({+ test("Add to Stirling library visible when local file selected", async ({page,}) => {await gotoFilesPage(page);@@ -295,7 +299,7 @@ test.describe("Files page", () => {// dropdowns stay mounted once opened, so each is read through the id its// own trigger controls.await expect(- page.getByRole("button", { name: /^Save to server$/i }),+ page.getByRole("button", { name: /^Add to Stirling library/i }),).toHaveCount(0);await expect(await openMenuItem(@@ -303,7 +307,7 @@ test.describe("Files page", () => {page.locator(".files-page-selection-actions .files-page-toolbar-bulk-trigger",),- /^Save to server$/i,+ /^Add to Stirling library/i,),).toBeVisible();await expect(@@ -312,12 +316,12 @@ test.describe("Files page", () => {page.locator(".files-page-details-actions-row").getByRole("button", { name: /^Actions$/i }),- /^Save to server$/i,+ /^Add to Stirling library/i,),).toBeVisible();});- test("Save to server hidden when ONLY cloud files selected", async ({+ test("Add to Stirling library hidden when ONLY cloud files selected", async ({page,}) => {await gotoFilesPage(page);@@ -327,11 +331,26 @@ test.describe("Files page", () => {.filter({ hasText: "cloud-a.pdf" }).click();await expect(- page.getByRole("button", { name: /^Save to server$/i }),+ await openMenuItem(+ page,+ page.locator(+ ".files-page-selection-actions .files-page-toolbar-bulk-trigger",+ ),+ /^Add to Stirling library/i,+ ),+ ).toHaveCount(0);+ await expect(+ await openMenuItem(+ page,+ page+ .locator(".files-page-details-actions-row")+ .getByRole("button", { name: /^Actions$/i }),+ /^Add to Stirling library/i,+ ),).toHaveCount(0);});- test("Per-file kebab has Save to server item for local file", async ({+ test("Per-file kebab has Add to Stirling library item for local file", async ({page,}) => {await gotoFilesPage(page);@@ -341,30 +360,27 @@ test.describe("Files page", () => {.filter({ hasText: "local-a.pdf" });await localCard.getByRole("button", { name: /File actions/i }).click();await expect(- page.getByRole("menuitem", { name: /^Save to server$/i }),+ page.getByRole("menuitem", { name: /^Add to Stirling library/i }),).toBeVisible();});- test("Per-file kebab hides Save to server for cloud file", async ({+ test("Per-file kebab hides Add to Stirling library for cloud file", async ({page,}) => {await gotoFilesPage(page);- // Cloud file kebab omits Save to server.const cloudCard = page.locator(".files-page-card:not(.is-folder)").filter({ hasText: "cloud-a.pdf" });await cloudCard.getByRole("button", { name: /File actions/i }).click();await expect(- page.getByRole("menuitem", { name: /^Save to server$/i }),+ page.getByRole("menuitem", { name: /^Add to Stirling library/i }),).toHaveCount(0);});});- test.describe("Save to server gating (storage disabled)", () => {+ test.describe("Add to Stirling library gating (storage disabled)", () => {test.beforeEach(async ({ page }) => {- // storageEnabled:false -> Save-to-server stays visible for local-only- // files but is disabled (with an explanatory tooltip), not hidden, so- // users discover the feature and know to ask their admin.+ // Keep the disabled action discoverable so users know to ask their admin.await stubStorageApis(page, { storageEnabled: false });await seedFiles(page, [{ id: "local-a", name: "local-a.pdf", remoteStorageId: null },@@ -372,7 +388,7 @@ test.describe("Files page", () => {});test.use({ autoGoto: false });- test("bulk Save to server is disabled (not hidden) when storage off", async ({+ test("bulk Add to Stirling library is disabled (not hidden) when storage off", async ({page,}) => {await gotoFilesPage(page);@@ -385,7 +401,7 @@ test.describe("Files page", () => {page.locator(".files-page-selection-actions .files-page-toolbar-bulk-trigger",),- /^Save to server$/i,+ /^Add to Stirling library/i,);await expect(selectionSave).toBeVisible();await expect(selectionSave).toBeDisabled();@@ -395,13 +411,13 @@ test.describe("Files page", () => {page.locator(".files-page-details-actions-row").getByRole("button", { name: /^Actions$/i }),- /^Save to server$/i,+ /^Add to Stirling library/i,);await expect(panelSave).toBeVisible();await expect(panelSave).toBeDisabled();});- test("per-file kebab Save to server is disabled (not hidden) when storage off", async ({+ test("per-file kebab Add to Stirling library is disabled (not hidden) when storage off", async ({page,}) => {await gotoFilesPage(page);@@ -409,7 +425,9 @@ test.describe("Files page", () => {.locator(".files-page-card:not(.is-folder)").filter({ hasText: "local-a.pdf" });await localCard.getByRole("button", { name: /File actions/i }).click();- const item = page.getByRole("menuitem", { name: /^Save to server$/i });+ const item = page.getByRole("menuitem", {+ name: /^Add to Stirling library/i,+ });await expect(item).toBeVisible();await expect(item).toBeDisabled();});@@ -473,7 +491,7 @@ test.describe("Files page", () => {await expect(page).not.toHaveURL(/\/files/, { timeout: 3_000 });// Re-add the now-active file; activation branches on requested stubs.- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });const card2 = page.locator(".files-page-card:not(.is-folder)").filter({ hasText: "active-test.pdf" });@@ -517,7 +535,7 @@ test.describe("Files page", () => {});// Back to the library and open the same file again.- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(card()).toBeVisible({ timeout: 10_000 });await card().dblclick();await expect(page).not.toHaveURL(/\/files/, { timeout: 5_000 });@@ -539,6 +557,74 @@ test.describe("Files page", () => {});test.use({ autoGoto: false });+ test("imports dropped folders and loose files despite an unreadable entry", async ({+ page,+ }) => {+ await gotoFilesPage(page);+ const bytes = Array.from(+ readFileSync(+ new URL("../test-fixtures/form-fields-sample.pdf", import.meta.url),+ ),+ );+ await page.locator(".files-page").evaluate((element, pdfBytes) => {+ const file = (name: string) =>+ new File([new Uint8Array(pdfBytes)], name, {+ type: "application/pdf",+ });+ const fileEntry = (name: string) => ({+ isFile: true,+ file: (resolve: (value: File) => void) => resolve(file(name)),+ });+ const directory = (batches: object[][]) => ({+ isDirectory: true,+ createReader: () => ({+ readEntries: (resolve: (entries: object[]) => void) =>+ setTimeout(() => resolve(batches.shift() ?? []), 0),+ }),+ });+ const folder = directory([+ [+ directory([[fileEntry("nested.pdf")]]),+ {+ isFile: true,+ name: "unreadable.pdf",+ file: (_resolve: unknown, reject: (error: Error) => void) =>+ reject(new Error("Access denied")),+ },+ ],+ [fileEntry("later-batch.pdf")],+ ]);+ const loose = file("loose.pdf");+ element.dispatchEvent(+ Object.assign(+ new Event("drop", { bubbles: true, cancelable: true }),+ {+ dataTransfer: {+ types: ["Files"],+ files: [loose],+ items: [+ { kind: "file", webkitGetAsEntry: () => folder },+ { kind: "file", getAsFile: () => loose },+ ],+ },+ },+ ),+ );+ }, bytes);++ await expect(+ page.getByText("unreadable.pdf: Access denied"),+ ).toBeVisible();+ const cards = page.locator(".files-page-card:not(.is-folder)");+ for (const name of ["nested.pdf", "later-batch.pdf", "loose.pdf"]) {+ await expect(cards.filter({ hasText: name })).toBeVisible({+ timeout: 15_000,+ });+ }+ await expect(cards).toHaveCount(4);+ await expect(page).toHaveURL(/\/files\?view=recent$/);+ });+test("card thumbnail <img> is not natively draggable", async ({ page }) => {// draggable={false} keeps the card's onDragStart as drag authority.await gotoFilesPage(page);@@ -656,6 +742,139 @@ test.describe("Files page", () => {});});+ test.describe("Add to Stirling library", () => {+ test.use({ autoGoto: false, seedJwt: true });++ for (const destination of ["root", "new folder"] as const) {+ test(`uploads to ${destination} after dismissing the picker and keeps Recents open`, async ({+ page,+ }) => {+ await stubStorageApis(page);+ await seedFiles(page, [+ { id: "to-add", name: "to-add.pdf", remoteStorageId: null },+ ]);+ const folder = {+ id: "11111111-1111-4111-8111-111111111111",+ name: "Reports",+ parentFolderId: null,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ };+ let createdFolder = false;+ await page.route("**/api/v1/storage/folders", async (route) => {+ if (route.request().method() === "POST") {+ expect(route.request().postDataJSON()).toMatchObject({+ name: folder.name,+ parentFolderId: null,+ });+ createdFolder = true;+ await route.fulfill({ json: folder });+ } else {+ await route.fulfill({ json: createdFolder ? [folder] : [] });+ }+ });+ const storedFile = {+ id: 1001,+ fileName: "to-add.pdf",+ contentType: "application/pdf",+ sizeBytes: 1024,+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ owner: "testuser",+ ownedByCurrentUser: true,+ accessRole: "owner",+ shareLinks: [],+ filePurpose: "generic",+ folderId: destination === "root" ? null : folder.id,+ };+ let finishUpload!: () => void;+ const uploadGate = new Promise<void>((resolve) => {+ finishUpload = resolve;+ });+ let uploaded = false;+ await page.route("**/api/v1/storage/files", async (route) => {+ if (route.request().method() === "POST") {+ await uploadGate;+ uploaded = true;+ await route.fulfill({ json: storedFile });+ } else {+ await route.fulfill({ json: uploaded ? [storedFile] : [] });+ }+ });+ await page.route("**/api/v1/storage/files/folder", (route) =>+ route.fulfill({+ json: { movedFileIds: [storedFile.id], skippedFileIds: [] },+ }),+ );++ await gotoFilesPage(page);+ const card = page+ .locator(".files-page-card:not(.is-folder)")+ .filter({ hasText: "to-add.pdf" });+ await card.getByRole("button", { name: /File actions/i }).click();+ await expect(+ page.getByRole("menuitem", { name: /Move to/i }),+ ).toHaveCount(0);+ await page+ .getByRole("menuitem", { name: /Add to Stirling library/i })+ .click();+ const picker = page.getByRole("dialog").filter({+ has: page.getByRole("button", { name: "Add here", exact: true }),+ });+ await expect(picker).toBeVisible();+ if (destination === "new folder") {+ await picker+ .getByRole("button", { name: "New folder", exact: true })+ .click();+ const createDialog = page.getByRole("dialog", {+ name: "New folder",+ exact: true,+ });+ await createDialog+ .getByRole("textbox", { name: "Folder name" })+ .fill(folder.name);+ await createDialog+ .getByRole("button", { name: "Create", exact: true })+ .click();+ await expect(createDialog).toBeHidden();+ await expect(+ picker.getByRole("button", { name: folder.name, exact: true }),+ ).toBeVisible();+ }++ const uploadRequest = page.waitForRequest(+ (request) =>+ request.url().endsWith("/api/v1/storage/files") &&+ request.method() === "POST",+ );+ const placement = page.waitForRequest("**/api/v1/storage/files/folder");+ try {+ await picker+ .getByRole("button", { name: "Add here", exact: true })+ .click();+ await uploadRequest;+ await expect(picker).toBeHidden();+ expect(uploaded).toBe(false);+ await expect(page).toHaveURL(/\/files\?view=recent$/);+ } finally {+ finishUpload();+ }+ expect((await placement).postDataJSON()).toEqual({+ folderId: storedFile.folderId,+ fileIds: [storedFile.id],+ });+ await card.getByRole("button", { name: /File actions/i }).click();+ await expect(+ page.getByRole("menuitem", { name: /Move to/i }),+ ).toBeVisible();+ await expect(+ page.getByRole("menuitem", { name: /Add to Stirling library/i }),+ ).toHaveCount(0);+ await expect(page).toHaveURL(/\/files\?view=recent$/);+ });+ }+ });+test.describe("Move dialog inline create-folder", () => {// The inline create-folder affordance is gated on `serverReachable`, which// only flips true once a confirmed, non-anonymous user triggers the folder@@ -665,7 +884,7 @@ test.describe("Files page", () => {test("Move dialog shows Create new folder affordance", async ({ page }) => {await stubStorageApis(page);await seedFiles(page, [- { id: "to-move", name: "to-move.pdf", remoteStorageId: null },+ { id: "to-move", name: "to-move.pdf", remoteStorageId: 1001 },]);await gotoFilesPage(page);// Open the move dialog via the per-file kebab.@@ -837,7 +1056,9 @@ test.describe("Files page", () => {page.locator(".files-page-card:not(.is-folder)").filter({ hasText: "cross-browser.pdf" }),- ).toBeVisible({ timeout: 5_000 });+ ).toBeVisible({+ timeout: 5_000,+ });});});@@ -905,9 +1126,9 @@ test.describe("Files page", () => {parentFolderId: i === 0 ? undefined : ids[i - 1],})),);- await gotoFilesPage(page);+ await gotoFilesPage(page, { view: "all" });- const header = page.locator(".files-page-tabs-row");+ const header = page.locator(".files-page-navigation");const atRoot = await header.evaluate((el) => el.getBoundingClientRect().height,);@@ -944,9 +1165,9 @@ test.describe("Files page", () => {[{ id: "h-1", name: "h-1.pdf", remoteStorageId: null }],[{ id: CHROME_FOLDER, name: "Invoices" }],);- await gotoFilesPage(page);+ await gotoFilesPage(page, { view: "all" });- const header = page.locator(".files-page-tabs-row");+ const header = page.locator(".files-page-navigation");const atRoot = await header.evaluate((el) => el.getBoundingClientRect().height,);@@ -976,7 +1197,7 @@ test.describe("Files page", () => {await seedFiles(page, [{ id: "l-1", name: "l-1.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });await expect(page.locator(".files-page-list-row").first()).toBeVisible({timeout: 15_000,@@ -1031,7 +1252,7 @@ test.describe("Files page", () => {{ id: "s-2", name: "beta.pdf", remoteStorageId: null },{ id: "s-3", name: "gamma.pdf", remoteStorageId: null },]);- await page.goto("/files", { waitUntil: "domcontentloaded" });+ await page.goto("/files?view=recent", { waitUntil: "domcontentloaded" });const rows = page.locator(".files-page-list-row:not(.is-header)");await expect(rows.first()).toBeVisible({ timeout: 15_000 });@@ -1046,7 +1267,7 @@ test.describe("Files page", () => {const before = await topOf();await rows.nth(0).click();await rows.nth(1).click({ modifiers: ["ControlOrMeta"] });- await expect(page.locator(".files-page-list-selection-count")).toHaveText(+ await expect(page.locator(".files-page-toolbar-info")).toHaveText(/2 selected/i,);await expect.poll(topOf, { timeout: 15_000 }).toBeCloseTo(before, 0);@@ -1070,15 +1291,15 @@ test.describe("Files page", () => {{ id: NESTED, name: "Signed originals", parentFolderId: PARENT },],);- await gotoFilesPage(page);+ await gotoFilesPage(page, { view: "all" });const bar = page.locator(".workbench-bar");await expect(bar).toBeVisible({ timeout: 10_000 });- const row = page.locator(".files-page-tabs-row");+ const row = page.locator(".files-page-navigation");// On the library's row, and not in the bar above it.await expect(row.getByRole("navigation", { name: /Folder path/i }),- ).toBeVisible();+ ).toHaveCount(0);await expect(row.getByRole("button", { name: /New folder/i }),).toHaveCount(0);@@ -1157,7 +1378,7 @@ test.describe("Files page", () => {* A breadcrumb is a plain jump to an ancestor. Everything the selection change* drives - the listing, the folder filters, the path write - has to survive it.*/- test("clicking a breadcrumb returns to the root without throwing", async ({+ test("clicking the active library tab returns to the root without throwing", async ({page,}) => {await page.goto("/files", { waitUntil: "domcontentloaded" });@@ -1165,7 +1386,13 @@ test.describe("Files page", () => {const crumbs = page.getByRole("navigation", { name: /Folder path/i });await expect(crumbs).toBeVisible({ timeout: 5_000 });- await crumbs.getByRole("button", { name: /All files/i }).click();+ await expect(+ crumbs.getByRole("button", { name: /Stirling library/i }),+ ).toHaveCount(0);+ await page+ .getByRole("navigation", { name: "File sources" })+ .getByRole("button", { name: "Stirling library", exact: true })+ .click();await expect(page).toHaveURL(/\/files\/?$/, { timeout: 5_000 });await expect(page.getByText(/Something went wrong/i)).toHaveCount(0);diff --git a/frontend/editor/src/core/utils/getDropzoneFiles.test.ts b/frontend/editor/src/core/utils/getDropzoneFiles.test.tsnew file mode 100644index 0000000000..a97a098811--- /dev/null+++ b/frontend/editor/src/core/utils/getDropzoneFiles.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it, vi } from "vitest";+import { getDropzoneFiles } from "@app/utils/getDropzoneFiles";++function dropEvent(items: object[], files: File[] = []) {+ return Object.assign(new Event("drop"), {+ dataTransfer: { items, files },+ });+}++describe("getDropzoneFiles", () => {+ it("keeps readable siblings when a dropped item throws before the data store closes", async () => {+ const file = new File(["PDF"], "Readable.pdf");+ const getAsFile = vi.fn(() => file);+ const onError = vi.fn();+ const result = getDropzoneFiles(+ dropEvent([+ {+ kind: "file",+ getAsFile: () => {+ throw new Error("Access denied");+ },+ },+ { kind: "file", getAsFile },+ { kind: "file", getAsFile: () => null },+ ]),+ onError,+ );+ expect(getAsFile).toHaveBeenCalledOnce();+ getAsFile.mockImplementation(() => {+ throw new Error("Drop ended");+ });+ await expect(result).resolves.toEqual([file]);+ expect(onError).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({+ message: "Access denied\nCould not read a dropped file.",+ }),+ );+ });++ it("keeps files from later directory batches when an earlier child is unreadable", async () => {+ const first = new File(["first"], "First.pdf");+ const last = new File(["last"], "Last.pdf");+ const readable = (file: File) => ({+ isFile: true,+ file: (resolve: (file: File) => void) => resolve(file),+ });+ const batches = [+ [+ readable(first),+ {+ isFile: true,+ name: "Missing.pdf",+ file: (_resolve: unknown, reject: (error: Error) => void) =>+ reject(new Error("Deleted")),+ },+ ],+ [readable(last)],+ [],+ ];+ const root = {+ isDirectory: true,+ createReader: () => ({+ readEntries: (resolve: (entries: object[]) => void) =>+ resolve(batches.shift() ?? []),+ }),+ };+ const onError = vi.fn();+ await expect(+ getDropzoneFiles(+ dropEvent([{ kind: "file", webkitGetAsEntry: () => root }]),+ onError,+ ),+ ).resolves.toEqual([first, last]);+ expect(onError).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ message: "Missing.pdf: Deleted" }),+ );+ });++ it("rejects an unreadable drop when the caller has no error reporter", async () => {+ await expect(+ getDropzoneFiles(dropEvent([{ kind: "file", getAsFile: () => null }])),+ ).rejects.toThrow("Could not read a dropped file.");+ });++ it("captures every file while the drop event can still read the data store", async () => {+ const files = [new File(["a"], "a.pdf"), new File(["b"], "b.pdf")];+ const items = files.map((file) => ({+ kind: "file",+ getAsFile: vi.fn(() => file),+ }));+ const result = getDropzoneFiles(dropEvent(items));+ for (const item of items) {+ item.getAsFile.mockImplementation(() => {+ throw new Error("The drop event has ended");+ });+ }+ await expect(result).resolves.toEqual(files);+ });++ it("reports drag metadata without trying to read files before the drop", async () => {+ const getAsFile = vi.fn();+ const fileItem = { kind: "file", type: "application/pdf", getAsFile };+ const event = Object.assign(new Event("dragenter"), {+ dataTransfer: { items: [fileItem, { kind: "string" }] },+ });+ await expect(getDropzoneFiles(event)).resolves.toEqual([fileItem]);+ expect(getAsFile).not.toHaveBeenCalled();+ });++ it("reads nested directories through every reader batch", async () => {+ const first = new File(["a"], "a.pdf");+ const nested = new File(["b"], "b.pdf");+ const last = new File(["c"], "c.pdf");+ const fileEntry = (file: File) => ({+ isFile: true,+ file: (resolve: (file: File) => void) => resolve(file),+ });+ const directory = (batches: object[][]) => ({+ isDirectory: true,+ createReader: () => ({+ readEntries: (resolve: (entries: object[]) => void) =>+ resolve(batches.shift() ?? []),+ }),+ });+ const root = directory([+ [fileEntry(first), directory([[fileEntry(nested)]])],+ [fileEntry(last)],+ ]);+ const getAsFile = vi.fn();+ await expect(+ getDropzoneFiles(+ dropEvent([{ kind: "file", webkitGetAsEntry: () => root, getAsFile }]),+ ),+ ).resolves.toEqual([first, nested, last]);+ expect(getAsFile).not.toHaveBeenCalled();+ });++ it("accepts FileList-only drops and excludes system thumbnail files", async () => {+ const file = new File(["PDF"], "a.pdf");+ await expect(+ getDropzoneFiles(+ dropEvent(+ [],+ [file, new File([], "Thumbs.db"), new File([], ".DS_Store")],+ ),+ ),+ ).resolves.toEqual([file]);+ });++ it("keeps the input-file chooser working without file-system handles", async () => {+ const file = new File(["PDF"], "a.pdf");+ const event = new Event("change");+ Object.defineProperty(event, "target", { value: { files: [file] } });+ await expect(getDropzoneFiles(event)).resolves.toEqual([file]);+ });+});diff --git a/frontend/editor/src/core/utils/getDropzoneFiles.ts b/frontend/editor/src/core/utils/getDropzoneFiles.tsnew file mode 100644index 0000000000..5137d4f294--- /dev/null+++ b/frontend/editor/src/core/utils/getDropzoneFiles.ts@@ -0,0 +1,90 @@+import type { DropzoneProps } from "@mantine/dropzone";++type DropEvent = Parameters<NonNullable<DropzoneProps["getFilesFromEvent"]>>[0];++async function readEntryFiles(+ entry: FileSystemEntry,+ errors: string[],+): Promise<File[]> {+ const files: File[] = [];+ try {+ if (entry.isFile) {+ const file = await new Promise<File>((resolve, reject) =>+ (entry as FileSystemFileEntry).file(resolve, reject),+ );+ return [file];+ }+ const reader = (entry as FileSystemDirectoryEntry).createReader();+ while (true) {+ const batch = await new Promise<FileSystemEntry[]>((resolve, reject) =>+ reader.readEntries(resolve, reject),+ );+ if (batch.length === 0) break;+ const nested = await Promise.all(+ batch.map((child) => readEntryFiles(child, errors)),+ );+ for (const children of nested) files.push(...children);+ }+ } catch (cause) {+ errors.push(`${entry.fullPath || entry.name}: ${dropErrorMessage(cause)}`);+ }+ return files;+}++function dropErrorMessage(cause: unknown): string {+ return cause instanceof Error+ ? cause.message+ : "Could not read a dropped file.";+}++/**+ * Call during the drop event to capture files and directory entries before its data store closes.+ * Expands nested directories without permission-gated handles. Earlier drag events return metadata only.+ * Mantine callers must set useFsAccessApi=false so file dialogs supply input events.+ * With onError, reports unreadable entries once and returns readable files; otherwise rejects.+ */+export async function getDropzoneFiles(+ event: DropEvent,+ onError?: (error: Error) => void,+): Promise<Array<File | DataTransferItem>> {+ if ("dataTransfer" in event && event.dataTransfer) {+ const transfer = event.dataTransfer;+ const items = Array.from(transfer.items ?? []).filter(+ (item) => item.kind === "file",+ );+ if (event.type !== "drop") return items;++ const errors: string[] = [];+ const files = items.length+ ? (+ await Promise.all(+ items.map(async (item) => {+ try {+ const entry = item.webkitGetAsEntry?.();+ if (entry?.isDirectory) return readEntryFiles(entry, errors);+ const file = item.getAsFile();+ if (!file) throw new Error("Could not read a dropped file.");+ return [file];+ } catch (cause) {+ errors.push(dropErrorMessage(cause));+ return [];+ }+ }),+ )+ ).flat()+ : Array.from(transfer.files);+ if (errors.length) {+ const error = new Error(errors.join("\n"));+ if (!onError) throw error;+ onError(error);+ }+ return files.filter(+ (file) => file.name !== ".DS_Store" && file.name !== "Thumbs.db",+ );+ }++ if ("target" in event && event.target && "files" in event.target) {+ return Array.from((event.target as HTMLInputElement).files ?? []);+ }+ return [];+}diff --git a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsxindex eea457ebda..a66028f5ac 100644--- a/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx+++ b/frontend/editor/src/proprietary/components/policies/ProcessingFolderWizard.tsx@@ -268,7 +268,6 @@ export function ProcessingFolderWizard({</li>))}</ol>- {loading && <p role="status">{t("loading", "Loading...")}</p>}{unsupportedSteps && (<Bannertone="warning"diff --git a/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsx b/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsxindex bcab5225f9..2c9acb3bb1 100644--- a/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsx+++ b/frontend/editor/src/proprietary/hooks/useProcessingFolderCreation.tsx@@ -1,5 +1,4 @@import { lazy, Suspense, useCallback, useState } from "react";-import { useTranslation } from "react-i18next";import type { ProcessingFolderCreation } from "@core/hooks/useProcessingFolderCreation";export type { ProcessingFolderCreation };@@ -14,7 +13,6 @@ const Setup = lazy(async () => {/** The wizard stays inside the editor's file providers when opened from the outer navigation rail. */export function useProcessingFolderCreation(): ProcessingFolderCreation {- const { t } = useTranslation();const [opened, setOpened] = useState(false);const open = useCallback(() => setOpened(true), []);const close = useCallback(() => setOpened(false), []);@@ -22,9 +20,7 @@ export function useProcessingFolderCreation(): ProcessingFolderCreation {return {open,dialog: opened ? (- <Suspense- fallback={<span role="status">{t("loading", "Loading...")}</span>}- >+ <Suspense fallback={null}><Setup onClose={close} /></Suspense>) : null,