Skip to content

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

Remove legacy Smart/Watched Folders editor UI (#8170)

Reece Browne839ad3477a82
diff --git a/.gitignore b/.gitignore
index 604cce2c24..e567e4af85 100644
--- a/.gitignore
+++ b/.gitignore
@@ -26,9 +26,6 @@ pipeline/
customFiles/
configs/
watchedFolders/
-# The rule above targets the app's runtime watched-folders working dir, but it
-# also matches this frontend source component dir; keep the source tracked.
-!frontend/editor/src/proprietary/components/watchedFolders/
clientWebUI/
policy-webhook-spool/
# Scratch dir used by local fixture-regeneration runs (see
@@ -73,7 +70,6 @@ app/core/src/main/resources/static/samples/
app/core/src/main/resources/static/og-metadata.json
app/core/src/main/resources/static/og-metadata.saas.json
app/core/src/main/resources/static/sitemap.xml
-app/core/src/main/resources/static/sw-folder-retry.js
app/core/src/main/resources/static/robots.txt
app/core/src/main/resources/static/android-chrome-*.png
app/core/src/main/resources/static/mstile-*.png
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 0906f8215e..99bd2443e5 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -13019,169 +13019,6 @@ title = "View/Edit PDF"
[warning]
tooltipTitle = "Warning"
-[watchedFolders]
-alreadyInFolder = "Already in this folder"
-defaultFolderWarning = "This is a default folder and will be recreated on next reload."
-deleteConfirmBody = "This will remove the folder and its run history. Files already downloaded are not affected."
-deleteConfirmTitle = "Delete folder?"
-folderNotFound = "Folder not found"
-newFolder = "New folder"
-noFolders = "No watched folders yet"
-sidebarTitle = "Watched Folders"
-title = "Watched Folders"
-
-[watchedFolders.actions]
-back = "Back"
-collapse = "Collapse"
-dismiss = "Dismiss"
-download = "Download"
-downloadInput = "Download input"
-downloadOutput = "Download output"
-expand = "Expand"
-retry = "Retry"
-
-[watchedFolders.card]
-delete = "Delete folder"
-edit = "Edit folder"
-
-[watchedFolders.home]
-addAnother = "Add another Watched Folder"
-addAnotherDesc = "Automatically process files with a new pipeline"
-create = "Create your first Watched Folder"
-deleteFolder = "Delete folder"
-editFolder = "Edit folder"
-empty = "No watched folders yet"
-emptyDesc = "Set up a Watched Folder once. Drop PDFs in and they're automatically compressed, OCR'd, split, merged — whatever your pipeline does."
-emptyTitle = "Automate your PDF workflows"
-file = "file"
-files = "files"
-pause = "Pause"
-resume = "Resume"
-
-[watchedFolders.howItWorks]
-step1Desc = "Drag PDFs onto any Watched Folder card — or send them from your file list"
-step1Title = "Drop files"
-step2Desc = "Your configured tools process each file automatically"
-step2Title = "Pipeline runs"
-step3Desc = "Download processed files from inside the folder"
-step3Title = "Output ready"
-title = "How Watched Folders work"
-
-[watchedFolders.modal]
-advanced = "Advanced"
-automation = "Automation"
-automationNameFallback = "Watched Folder automation"
-automationRequired = "Add at least one configured step before saving."
-autoNumber = "Auto-number"
-autoNumberExample = "e.g. document.pdf → document (1).pdf"
-autoScanHelp = "New PDF files in this folder are processed automatically every 10 seconds."
-changeFolder = "Change"
-chooseFolder = "Choose"
-clearFolder = "Clear"
-color = "Accent color"
-createFolder = "New folder"
-createTitle = "New Watched Folder"
-editTitle = "Edit Watched Folder"
-inputFolder = "Input folder"
-inputFolderNotChosen = "No folder chosen — required for auto-scan"
-inputSource = "Input source"
-inputSourceBrowser = "Browser — drop files here"
-inputSourceLocal = "Local folder (auto-scan)"
-inputSourceLocalUnsupported = "Local folder (auto-scan) — Chrome/Edge only"
-localOutputFolder = "Local output folder"
-maxRetries = "Max retries"
-name = "Folder name"
-namePlaceholder = "My Watched Folder"
-nameRequired = "Folder name is required"
-nameTooLong = "Folder name must be 50 characters or less"
-outputFolderNotSet = "Not set — outputs stay in app"
-outputFolderUnsupported = "Not supported in this browser"
-outputModeNewDesc = "Output is saved as a new separate file"
-outputModeVersion = "Replace original?"
-outputModeVersionDesc = "Output becomes a new version of the input file rather than a separate file"
-outputName = "Output filename prefix"
-outputNamePrefix = "Filename prefix"
-outputNameSuffix = "Suffix"
-positionPrefix = "Prefix"
-positionSuffix = "Suffix"
-replaceOriginal = "Replace original file"
-retryDelay = "Delay (minutes)"
-saveChanges = "Save Changes"
-saveFailed = "Failed to save folder. Please try again."
-sectionFolder = "Folder"
-sectionSourceOutput = "Source & Output"
-sectionSteps = "Steps"
-
-[watchedFolders.status]
-active = "Active"
-done = "Done"
-paused = "Paused"
-processing = "Processing"
-
-[watchedFolders.time]
-daysAgo = "{{count}}d ago"
-hoursAgo = "{{count}}h ago"
-justNow = "just now"
-minutesAgo = "{{count}}m ago"
-
-[watchedFolders.workbench]
-activity = "Activity"
-addFiles = "Add files"
-allTime = "All time"
-cancel = "Cancel"
-chartTooltipComplete = "{{count}} complete"
-chartTooltipFailed = "{{count}} failed"
-clearSelection = "Clear selection"
-countProcessing = "{{count}} processing"
-countQueued = "{{count}} queued"
-countSelected = "{{count}} selected"
-dataSaved = "Saved"
-dayRunning = "day running"
-daysRunning = "days running"
-delete = "Delete"
-deleteConfirmBody = "Remove notifications only clears the activity log. Delete outputs also removes the processed files from storage. Your original input files are never touched."
-deleteOutputs = "Delete outputs"
-directionIn = "in"
-directionOut = "out"
-dropToProcess = "Drop to process"
-export = "Export"
-exportSeparately = "Export separately"
-exportZip = "Export zip"
-failed = "Failed"
-filesProcessedOverTime = "Files processed over time"
-filterAll = "All"
-filterPending = "Pending"
-inputs = "Inputs"
-inputSize = "Input size"
-legendComplete = "Complete"
-noActivity = "No activity yet — drop a PDF to start"
-noActivityMatch = "No matching activity"
-noInputFolder = "No input folder — edit to configure"
-outputs = "Outputs"
-pause = "Pause"
-preview = "Preview"
-previewInput = "Preview input"
-previewLoadFailed = "Could not load file preview."
-previewOutput = "Preview output"
-queued = "Queued"
-queuedWaiting = "Queued — waiting to run"
-removeEntries = "Remove {{count}} entries"
-removeEntry = "Remove entry"
-removeNotificationsOnly = "Remove notifications only"
-resume = "Resume"
-retryAll = "Retry all"
-retryIn = "retry in {{count}}m"
-retryingSoon = "retrying…"
-retryMixedConfirm = "Some selected files have already completed and will be skipped. Only failed files will be retried. Continue?"
-running = "Running"
-search = "Search…"
-selectAll = "Select all {{count}}"
-sortNameAsc = "A → Z"
-sortNameDesc = "Z → A"
-sortNewest = "Newest"
-sortOldest = "Oldest"
-watching = "Watching: {{name}}"
-
[watermark]
desc = "Add text or image watermarks to PDF files"
submit = "Add Watermark"
diff --git a/frontend/editor/public/sw-folder-retry.js b/frontend/editor/public/sw-folder-retry.js
deleted file mode 100644
index fbf0ed1fda..0000000000
--- a/frontend/editor/public/sw-folder-retry.js
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Service worker for Watched Folder retry scheduling.
- *
- * Reads the earliest pending retry from IndexedDB and sets a setTimeout for it.
- * When the timer fires it posts PROCESS_DUE_RETRIES to all window clients so
- * the main thread can atomically claim and process the due entries.
- *
- * Limitations:
- * - Browsers may terminate idle service workers after ~30 s. The main thread
- * therefore also drains due retries on mount and on visibilitychange as a
- * fallback — no retries are lost, they may just fire slightly late.
- * - Multiple clients each post a SCHEDULE_RETRY message; the SW deduplicates
- * by resetting the timer each time, so only one notification is sent.
- */
-
-const DB_NAME = "stirling-pdf-retry-schedule";
-const STORE_NAME = "retries";
-
-let retryTimer = null;
-
-self.addEventListener("install", () => self.skipWaiting());
-
-self.addEventListener("activate", (event) => {
- event.waitUntil(self.clients.claim().then(scheduleNextTimer));
-});
-
-self.addEventListener("message", (event) => {
- if (event.data?.type === "SCHEDULE_RETRY") {
- scheduleNextTimer();
- }
-});
-
-function openDB() {
- return new Promise((resolve, reject) => {
- const req = indexedDB.open(DB_NAME, 1);
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => reject(new Error("SW: failed to open retry DB"));
- // Create store if this SW activates before the main thread has opened the DB
- req.onupgradeneeded = (event) => {
- const db = event.target.result;
- if (!db.objectStoreNames.contains(STORE_NAME)) {
- const store = db.createObjectStore(STORE_NAME, { keyPath: "id" });
- store.createIndex("dueAt", "dueAt", { unique: false });
- }
- };
- });
-}
-
-async function getEarliestDueAt() {
- try {
- const db = await openDB();
- return new Promise((resolve) => {
- const tx = db.transaction([STORE_NAME], "readonly");
- const req = tx.objectStore(STORE_NAME).index("dueAt").openCursor();
- req.onsuccess = () => resolve(req.result ? req.result.value.dueAt : null);
- req.onerror = () => resolve(null);
- });
- } catch {
- return null;
- }
-}
-
-async function notifyClients() {
- const clients = await self.clients.matchAll({
- type: "window",
- includeUncontrolled: true,
- });
- for (const client of clients) {
- client.postMessage({ type: "PROCESS_DUE_RETRIES" });
- }
-}
-
-async function scheduleNextTimer() {
- if (retryTimer !== null) {
- clearTimeout(retryTimer);
- retryTimer = null;
- }
- const earliest = await getEarliestDueAt();
- if (earliest === null) return;
-
- const delay = Math.max(0, earliest - Date.now());
- retryTimer = setTimeout(async () => {
- retryTimer = null;
- await notifyClients();
- // Re-schedule for any remaining entries that were not yet due
- await scheduleNextTimer();
- }, delay);
-}
diff --git a/frontend/editor/scripts/lint/theme-lint.mjs b/frontend/editor/scripts/lint/theme-lint.mjs
index 52bd304a5a..8c8b8e7309 100644
--- a/frontend/editor/scripts/lint/theme-lint.mjs
+++ b/frontend/editor/scripts/lint/theme-lint.mjs
@@ -637,7 +637,7 @@ const CODE_EXEMPT_PATH = [
/pdfTextEditor|pixelCompare|\/compare\.ts$|customPrimary|accentColors|formFieldColors/,
/validateSignature\/outputtedPDFSections|CenteredMessageSection|StatusBadgeSection/,
/\/viewer\/|Annotation|useViewerReadAloud|CommentsSidebar|\/constants\/search\.ts$|SignaturePreview/,
- /ColorPicker|ColorControl|WatchedFolderManagementModal|watchedFolderPresets|fileColors|unifiedBackground|folder\.ts$|policyFolders/,
+ /ColorPicker|ColorControl|fileColors|unifiedBackground|folder\.ts$|policyFolders/,
/OAuthButtons|oauthCallbackHtml/,
/mantineTheme|\/theme\.ts$|toolsTaxonomy|LayoutPreview|PageNumberPreview|CloudStorageIcons|BrandMarks/,
/\/onboarding\//,
diff --git a/frontend/editor/src/core/components/AppProviders.tsx b/frontend/editor/src/core/components/AppProviders.tsx
index 6a9ae1615c..6d9db23cd2 100644
--- a/frontend/editor/src/core/components/AppProviders.tsx
+++ b/frontend/editor/src/core/components/AppProviders.tsx
@@ -35,13 +35,16 @@ import AppConfigLoader from "@app/components/shared/AppConfigLoader";
import { UpdateStartupPopup } from "@app/components/shared/UpdateStartupPopup";
import { RedactionProvider } from "@app/contexts/RedactionContext";
import { FormFillProvider } from "@app/tools/formFill/FormFillContext";
-import { FolderFileContextProvider } from "@app/contexts/FolderFileContext";
import { FolderProvider } from "@app/contexts/FolderContext";
import { WorkbenchSessionPersistence } from "@app/components/session/WorkbenchSessionPersistence";
+import { retireLegacyFolderWorker } from "@app/services/retireLegacyFolderWorker";
// Component to run app-level initialization (must be inside AppProviders for context access)
function AppInitializer() {
useAppInitialization();
+ useEffect(() => {
+ void retireLegacyFolderWorker();
+ }, []);
return null;
}
@@ -148,10 +151,8 @@ export function AppProviders({
<WorkbenchBarProvider>
<TourOrchestrationProvider>
<AdminTourOrchestrationProvider>
- <FolderFileContextProvider>
- <WorkbenchSessionPersistence />
- {children}
- </FolderFileContextProvider>
+ <WorkbenchSessionPersistence />
+ {children}
</AdminTourOrchestrationProvider>
</TourOrchestrationProvider>
</WorkbenchBarProvider>
diff --git a/frontend/editor/src/core/components/shared/FileSidebar.tsx b/frontend/editor/src/core/components/shared/FileSidebar.tsx
index 9ed868c4f5..957492b365 100644
--- a/frontend/editor/src/core/components/shared/FileSidebar.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebar.tsx
@@ -34,7 +34,6 @@ import {
import { SidebarHeader } from "@app/components/shared/SidebarHeader";
import type { StirlingFileStub } from "@app/types/fileContext";
import type { FileId } from "@app/types/file";
-import type { WatchedFolderViewData } from "@app/types/watchedFolders";
import { FileItem } from "@app/components/shared/FileSidebarFileItem";
import { useLabelName } from "@app/data/labelDisplay";
import { useClassificationEnabled } from "@app/hooks/useClassificationEnabled";
@@ -60,32 +59,19 @@ import { useOpenInNewWindow } from "@app/extensions/openInNewWindow";
import { openSuperSearch } from "@app/components/shared/superSearch/openSuperSearch";
import { alert } from "@app/components/toast";
import { useBulkAddProgress } from "@app/services/bulkAddProgress";
-import { useFolderMembership } from "@app/hooks/useFolderMembership";
import { useIsScrolled } from "@app/hooks/useIsScrolled";
-import { useAllWatchedFolders } from "@app/hooks/useAllWatchedFolders";
import { usePolicyFileBadges } from "@app/hooks/usePolicyFileBadges";
-import {
- setWatchedFolderDraggedFileIds,
- clearWatchedFolderDraggedFileIds,
-} from "@app/components/watchedFolders/watchedFolderDragState";
-import { WATCHED_FOLDERS_ENABLED } from "@app/constants/featureFlags";
import { FolderTreeSidebar } from "@app/components/filesPage/FolderTreeSidebar";
import { useFilesPage } from "@app/contexts/FilesPageContext";
import type { FolderId, FolderRecord } from "@app/types/folder";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
import { useToolEligibleFileIds } from "@app/contexts/ToolFileEligibilityContext";
import "@app/components/shared/FileSidebar.css";
// Shared with the processor sidebar via tokens, so the two cannot drift.
const SIDEBAR_WIDTH = "var(--sidebar-w)";
-// Inlined to avoid a circular import with WatchedFoldersRegistration.
-const WATCHED_FOLDER_VIEW_ID = "watchedFolder";
-const WATCHED_FOLDER_WORKBENCH_ID = "custom:watchedFolder";
-
-// Stable empty props for rows without folders/policies, so the memoized
+// Stable empty props for rows without policies, so the memoized
// FileItem isn't re-rendered by a fresh `?? []` identity on every list render.
-const NO_FOLDERS: never[] = [];
const NO_POLICIES: never[] = [];
/** Show pre-dispatch progress only for large drops; small imports finish before it paints. */
@@ -198,52 +184,8 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const { state } = useFileState();
const { actions: fileActions } = useFileActions();
const { actions: navActions } = useNavigationActions();
- const { setCustomWorkbenchViewData, customWorkbenchViews } =
- useToolWorkflow();
const { workbench: currentWorkbench, selectedTool } = useNavigationState();
- const isWatchedFoldersActive =
- currentWorkbench === WATCHED_FOLDER_WORKBENCH_ID;
- const watchedFolderView = customWorkbenchViews.find(
- (v) => v.id === WATCHED_FOLDER_VIEW_ID,
- );
- const activeWatchedFolderId =
- (watchedFolderView?.data as WatchedFolderViewData | undefined)
- ?.folderId ?? null;
- // In Watched Folders, selection means membership of the open folder, not the workspace.
- const folderMembership = useFolderMembership();
- const allFolders = useAllWatchedFolders();
const policyFileBadges = usePolicyFileBadges();
- const folderById = useMemo(
- () => new Map(allFolders.map((f) => [f.id, f])),
- [allFolders],
- );
-
- const openWatchedFolder = useCallback(
- (folderId: string) => {
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId });
- navActions.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- },
- [setCustomWorkbenchViewData, navActions],
- );
-
- // In Watched Folders view, sidebar files can be dragged onto a folder card / drop
- // zone (which read the watchedFolderFileId dataTransfer key).
- const handleWatchedFolderDragStart = useCallback(
- (e: React.DragEvent, fileId: FileId) => {
- e.dataTransfer.setData("watchedFolderFileId", String(fileId));
- e.dataTransfer.effectAllowed = "copy";
- // Publish the id so drop targets can detect "already in folder" during
- // dragover (dataTransfer values are unreadable then). Clear on dragend
- // regardless of whether the drag ended in a drop or was cancelled.
- setWatchedFolderDraggedFileIds([String(fileId)]);
- const clear = () => {
- clearWatchedFolderDraggedFileIds();
- document.removeEventListener("dragend", clear);
- };
- document.addEventListener("dragend", clear);
- },
- [],
- );
const isMultiTool =
currentWorkbench === "pageEditor" && selectedTool === "multiTool";
const { requestNavigation } = useNavigationGuard();
@@ -600,19 +542,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
return;
}
- // In the Watched Folders view a click sends the file into the open folder
- // (mirrors how a click toggles a file into the active workbench elsewhere).
- // On the folder list (no folder open) it's a no-op so browsing isn't disrupted.
- if (isWatchedFoldersActive) {
- if (activeWatchedFolderId) {
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, {
- folderId: activeWatchedFolderId,
- pendingFileId: stub.id,
- });
- }
- return;
- }
-
const workbenchFileId = state.files.ids.find(
(id) => (id as string) === (stub.id as string),
);
@@ -664,9 +593,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
activeFileId,
requestNavigation,
isMultiTool,
- isWatchedFoldersActive,
- activeWatchedFolderId,
- setCustomWorkbenchViewData,
],
);
@@ -833,27 +759,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
const renderFileRow = (stub: StirlingFileStub) => {
const isInWorkbench = workbenchIds.has(stub.id as string);
const workbenchFileId = isInWorkbench ? (stub.id as FileId) : undefined;
- const isSelected = isWatchedFoldersActive
- ? activeWatchedFolderId != null &&
- (folderMembership
- .get(stub.id as string)
- ?.includes(activeWatchedFolderId) ??
- false)
- : isInWorkbench;
- const showFolderDots =
- WATCHED_FOLDERS_ENABLED &&
- isWatchedFoldersActive &&
- activeWatchedFolderId === null;
- const memberFolders = showFolderDots
- ? (folderMembership.get(stub.id as string) ?? [])
- .map((fid) => folderById.get(fid))
- .filter((f): f is NonNullable<typeof f> => !!f)
- .map((f) => ({
- id: f.id,
- name: f.name,
- accentColor: f.accentColor,
- }))
- : NO_FOLDERS;
const isViewedInViewer = !!(
viewedWorkbenchId && viewedWorkbenchId === (stub.id as string)
);
@@ -877,7 +782,6 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
<FileItem
isToolSkipped={
isInWorkbench &&
- !isWatchedFoldersActive &&
eligibleFileIds !== null &&
!eligibleFileIds.has(stub.id)
}
@@ -886,31 +790,25 @@ const FileSidebar = forwardRef<HTMLDivElement, FileSidebarProps>(
name={stub.name}
size={stub.size}
lastModified={stub.lastModified}
- isSelected={isSelected}
+ isSelected={isInWorkbench}
isActive={isActive}
isViewedInViewer={isViewedInViewer}
thumbnailUrl={thumbnailUrl}
onClick={handleFileClick}
onEyeClick={handleEyeClick}
dataUnavailable={dataUnavailable}
- draggable={isWatchedFoldersActive}
- onDragStart={handleWatchedFolderDragStart}
- folders={memberFolders}
- onFolderClick={openWatchedFolder}
policies={policyFileBadges.get(stub.id as string) ?? NO_POLICIES}
- onDelete={isWatchedFoldersActive ? undefined : handleSidebarDelete}
+ onDelete={handleSidebarDelete}
onDownload={handleDownload}
- onRename={isWatchedFoldersActive ? undefined : handleRename}
- onDuplicate={isWatchedFoldersActive ? undefined : handleDuplicate}
+ onRename={handleRename}
+ onDuplicate={handleDuplicate}
onOpenInNewWindow={
canOpenInNewWindow(stub) ? handleOpenInNewWindow : undefined
}
- onSaveToCloud={isWatchedFoldersActive ? undefined : handleSaveToCloud}
+ onSaveToCloud={handleSaveToCloud}
canSaveToCloud={storageEnabled && fileOrigin !== "shared-with-me"}
isUploadedToCloud={fileOrigin === "cloud"}
- onVersionHistory={
- isWatchedFoldersActive ? undefined : handleVersionHistory
- }
+ onVersionHistory={handleVersionHistory}
hasVersionHistory={(stub.versionNumber ?? 1) > 1}
primaryLabel={
classificationEnabled && stub.classificationLabels?.[0]
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.css b/frontend/editor/src/core/components/shared/FileSidebarFileItem.css
index b24b37a86c..5369bc5867 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.css
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.css
@@ -199,57 +199,6 @@
color: var(--c-accent-text);
}
-/* ---- Folder membership tags ---- */
-.file-sidebar-folder-tags {
- display: flex;
- align-items: center;
- gap: 4px;
- margin-top: 3px;
- min-width: 0;
-}
-
-.file-sidebar-folder-tag {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- max-width: 7.5rem;
- padding: 1px 6px 1px 5px;
- border: 1px solid transparent;
- border-radius: 10px;
- cursor: pointer;
- transition: filter 0.1s ease;
-}
-
-.file-sidebar-folder-tag:hover {
- filter: brightness(1.1);
-}
-
-.file-sidebar-folder-tag-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- flex-shrink: 0;
-}
-
-.file-sidebar-folder-tag-label {
- font-size: 10px;
- font-weight: 600;
- line-height: 1.2;
- color: var(--c-text-muted);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.file-sidebar-folder-tag-more {
- font-size: 10px;
- font-weight: 600;
- line-height: 1;
- color: var(--c-text-subtle);
- cursor: default;
- flex-shrink: 0;
-}
-
/* ---- Eye button (open in viewer) ---- */
.file-sidebar-eye-btn {
display: flex;
diff --git a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
index de90168860..051a2bf6da 100644
--- a/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
+++ b/frontend/editor/src/core/components/shared/FileSidebarFileItem.tsx
@@ -116,13 +116,6 @@ function getSidebarFileIcon(ext: string): React.ReactElement {
return <FileDocIcon className={cls} variant={getFileDocVariant(ext)} />;
}
-/** A Watched Folder this file currently belongs to, used for the membership dots. */
-export interface FileItemFolderRef {
- id: string;
- name: string;
- accentColor: string;
-}
-
export interface FileItemProps {
fileId: FileId;
name: string;
@@ -135,13 +128,6 @@ export interface FileItemProps {
thumbnailUrl?: string;
onClick: (fileId: FileId) => void;
onEyeClick: (fileId: FileId, e: React.MouseEvent) => void;
- /** When true, the row can be dragged (e.g. onto a Watched Folder). */
- draggable?: boolean;
- onDragStart?: (e: React.DragEvent, fileId: FileId) => void;
- /** Watched Folders this file is in — rendered as small accent dots. */
- folders?: FileItemFolderRef[];
- /** Clicking a membership dot opens that folder. */
- onFolderClick?: (folderId: string) => void;
/** Policies that have run on this file — rendered as small shield badges. */
policies?: FileItemPolicyRef[];
/** The file's primary classification label (display name), shown in the meta
@@ -172,8 +158,6 @@ export interface FileItemProps {
dataUnavailable?: boolean;
}
-const MAX_VISIBLE_FOLDER_TAGS = 2;
-
/** One kebab row. `disabledReason`, when set, greys the row out and says why. */
function FileMenuItem({
disabledReason,
@@ -229,10 +213,6 @@ export const FileItem = React.memo(function FileItem({
thumbnailUrl,
onClick,
onEyeClick,
- draggable,
- onDragStart,
- folders = [],
- onFolderClick,
policies = [],
primaryLabel,
onDelete,
@@ -295,9 +275,6 @@ export const FileItem = React.memo(function FileItem({
? t("fileSidebar.fileItem.closeViewer", "Close viewer")
: t("fileSidebar.fileItem.openInViewer", "Open in viewer");
- const visibleFolders = folders.slice(0, MAX_VISIBLE_FOLDER_TAGS);
- const overflowFolders = folders.slice(MAX_VISIBLE_FOLDER_TAGS);
-
// Only use raster thumbnails for PDFs and images — everything else uses scalable SVG icons
const useRasterThumb = ext === "pdf" || IMAGE_EXTENSIONS.has(ext);
const resolvedThumbnail = useLazyThumbnail(
@@ -335,10 +312,6 @@ export const FileItem = React.memo(function FileItem({
aria-description={toolSkipReason}
className={`file-sidebar-file-item${isSelected ? " selected" : ""}${isActive ? " active" : ""}${isViewedInViewer ? " viewed" : ""}`}
onClick={() => onClick(fileId)}
- draggable={draggable}
- onDragStart={
- draggable && onDragStart ? (e) => onDragStart(e, fileId) : undefined
- }
role="button"
tabIndex={0}
onKeyDown={(e) => e.key === "Enter" && onClick(fileId)}
@@ -410,54 +383,6 @@ export const FileItem = React.memo(function FileItem({
)}
<PolicyBadges policies={policies} />
</span>
- {folders.length > 0 && (
- <span className="file-sidebar-folder-tags" data-no-select>
- {visibleFolders.map((folder) => (
- <Tooltip
- key={folder.id}
- label={folder.name}
- withArrow
- position="top"
- withinPortal
- >
- <span
- className="file-sidebar-folder-tag"
- style={{
- backgroundColor: `${folder.accentColor}1f`,
- borderColor: `${folder.accentColor}55`,
- }}
- role="button"
- tabIndex={-1}
- aria-label={folder.name}
- onClick={(e) => {
- e.stopPropagation();
- onFolderClick?.(folder.id);
- }}
- >
- <span
- className="file-sidebar-folder-tag-dot"
- style={{ backgroundColor: folder.accentColor }}
- />
- <span className="file-sidebar-folder-tag-label">
- {folder.name}
- </span>
- </span>
- </Tooltip>
- ))}
- {overflowFolders.length > 0 && (
- <Tooltip
- label={overflowFolders.map((f) => f.name).join(", ")}
- withArrow
- position="top"
- withinPortal
- >
- <span className="file-sidebar-folder-tag-more">
- +{overflowFolders.length}
- </span>
- </Tooltip>
- )}
- </span>
- )}
</div>
<div className="file-sidebar-file-actions">
<ActionIcon
diff --git a/frontend/editor/src/core/components/tools/automate/AutomationCreation.stories.tsx b/frontend/editor/src/core/components/tools/automate/AutomationCreation.stories.tsx
index 8299f7222c..1b08181c07 100644
--- a/frontend/editor/src/core/components/tools/automate/AutomationCreation.stories.tsx
+++ b/frontend/editor/src/core/components/tools/automate/AutomationCreation.stories.tsx
@@ -45,15 +45,3 @@ export const EditExisting: Story = {
toolRegistry: emptyToolRegistry,
},
};
-
-export const EmbeddedHideMetadata: Story = {
- args: {
- mode: AutomationMode.CREATE,
- hideMetadata: true,
- nameOverride: "Watched Folder Automation",
- onBack: () => {},
- onComplete: () => {},
- onSaveFailed: () => {},
- toolRegistry: emptyToolRegistry,
- },
-};
diff --git a/frontend/editor/src/core/components/tools/automate/AutomationCreation.tsx b/frontend/editor/src/core/components/tools/automate/AutomationCreation.tsx
index d6508bd036..6bf3b30705 100644
--- a/frontend/editor/src/core/components/tools/automate/AutomationCreation.tsx
+++ b/frontend/editor/src/core/components/tools/automate/AutomationCreation.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
Text,
@@ -33,15 +33,6 @@ interface AutomationCreationProps {
onBack: () => void;
onComplete: (automation: AutomationConfig) => void;
toolRegistry: Partial<ToolRegistry>;
- /** Hide the name/description/icon fields and the action buttons. Used when embedding
- * the form (e.g. inside the Watched Folder modal) where the host owns those controls. */
- hideMetadata?: boolean;
- /** Force the automation name (used with hideMetadata so the host's name drives it). */
- nameOverride?: string;
- /** Called when an external save trigger fires but the form isn't in a saveable state. */
- onSaveFailed?: () => void;
- /** When provided, the host can trigger save imperatively (the internal Save button is hidden). */
- saveTriggerRef?: React.MutableRefObject<(() => void) | null>;
}
export default function AutomationCreation({
@@ -50,10 +41,6 @@ export default function AutomationCreation({
onBack,
onComplete,
toolRegistry,
- hideMetadata = false,
- nameOverride,
- onSaveFailed,
- saveTriggerRef,
}: AutomationCreationProps) {
const { t } = useTranslation();
@@ -166,29 +153,6 @@ export default function AutomationCreation({
}
};
- // Keep the (hidden) automation name in sync with a host-provided override.
- useEffect(() => {
- if (nameOverride !== undefined) {
- setAutomationName(nameOverride);
- }
- }, [nameOverride, setAutomationName]);
-
- // Expose an imperative save trigger to the host (e.g. the Watched Folder modal's
- // "Create Folder" button). Surfaces a failure callback when not saveable.
- useEffect(() => {
- if (!saveTriggerRef) return;
- saveTriggerRef.current = () => {
- if (!canSaveAutomation()) {
- onSaveFailed?.();
- return;
- }
- void saveAutomation();
- };
- return () => {
- saveTriggerRef.current = null;
- };
- });
-
const currentConfigTool =
configuraingToolIndex >= 0 ? selectedTools[configuraingToolIndex] : null;
@@ -230,45 +194,39 @@ export default function AutomationCreation({
<Divider mb="md" />
<Stack gap="md">
- {!hideMetadata && (
- <>
- {/* Automation Name and Icon */}
- <Group gap="xs" align="flex-end">
- <Stack gap="xs" style={{ flex: 1 }}>
- <TextInput
- placeholder={t(
- "automate.creation.name.placeholder",
- "My Automation",
- )}
- value={automationName}
- withAsterisk
- label={t("automate.creation.name.label", "Automation Name")}
- onChange={(e) => setAutomationName(e.currentTarget.value)}
- size="sm"
- />
- </Stack>
-
- <IconSelector
- value={automationIcon || "SettingsIcon"}
- onChange={setAutomationIcon}
- size="sm"
- />
- </Group>
-
- {/* Automation Description */}
- <Textarea
+ <Group gap="xs" align="flex-end">
+ <Stack gap="xs" style={{ flex: 1 }}>
+ <TextInput
placeholder={t(
- "automate.creation.description.placeholder",
- "Describe what this automation does...",
+ "automate.creation.name.placeholder",
+ "My Automation",
)}
- value={automationDescription}
- label={t("automate.creation.description.label", "Description")}
- onChange={(e) => setAutomationDescription(e.currentTarget.value)}
+ value={automationName}
+ withAsterisk
+ label={t("automate.creation.name.label", "Automation Name")}
+ onChange={(e) => setAutomationName(e.currentTarget.value)}
size="sm"
- rows={3}
/>
- </>
- )}
+ </Stack>
+
+ <IconSelector
+ value={automationIcon || "SettingsIcon"}
+ onChange={setAutomationIcon}
+ size="sm"
+ />
+ </Group>
+
+ <Textarea
+ placeholder={t(
+ "automate.creation.description.placeholder",
+ "Describe what this automation does...",
+ )}
+ value={automationDescription}
+ label={t("automate.creation.description.label", "Description")}
+ onChange={(e) => setAutomationDescription(e.currentTarget.value)}
+ size="sm"
+ rows={3}
+ />
{/* Selected Tools List */}
{selectedTools.length > 0 && (
@@ -284,52 +242,47 @@ export default function AutomationCreation({
/>
)}
- {!saveTriggerRef && (
- <>
- <Divider />
+ <Divider />
- {/* Action Buttons */}
- <Stack gap="sm">
- <Button
- leftSection={<Icon name="check" />}
- onClick={saveAutomation}
- disabled={!canSaveAutomation()}
- fullWidth
- >
- {t("automate.creation.save", "Save Automation")}
- </Button>
+ <Stack gap="sm">
+ <Button
+ leftSection={<Icon name="check" />}
+ onClick={saveAutomation}
+ disabled={!canSaveAutomation()}
+ fullWidth
+ >
+ {t("automate.creation.save", "Save Automation")}
+ </Button>
- <Group gap="sm" grow>
- <Button
- variant="secondary"
- leftSection={<Icon name="download" />}
- onClick={() => {
- downloadAutomationConfig(buildExportableAutomation());
- }}
- disabled={!canSaveAutomation()}
- >
- {t("automate.creation.export", "Export")}
- </Button>
- <Button
- variant="secondary"
- leftSection={<Icon name="download" />}
- onClick={() => {
- downloadFolderScanningConfig(
- buildExportableAutomation(),
- toolRegistry,
- );
- }}
- disabled={!canSaveAutomation()}
- >
- {t(
- "automate.creation.exportForFolderScanning",
- "Export for Folder Scanning",
- )}
- </Button>
- </Group>
- </Stack>
- </>
- )}
+ <Group gap="sm" grow>
+ <Button
+ variant="secondary"
+ leftSection={<Icon name="download" />}
+ onClick={() => {
+ downloadAutomationConfig(buildExportableAutomation());
+ }}
+ disabled={!canSaveAutomation()}
+ >
+ {t("automate.creation.export", "Export")}
+ </Button>
+ <Button
+ variant="secondary"
+ leftSection={<Icon name="download" />}
+ onClick={() => {
+ downloadFolderScanningConfig(
+ buildExportableAutomation(),
+ toolRegistry,
+ );
+ }}
+ disabled={!canSaveAutomation()}
+ >
+ {t(
+ "automate.creation.exportForFolderScanning",
+ "Export for Folder Scanning",
+ )}
+ </Button>
+ </Group>
+ </Stack>
</Stack>
{/* Tool Configuration Modal */}
diff --git a/frontend/editor/src/core/components/watchedFolders/watchedFolderDragState.ts b/frontend/editor/src/core/components/watchedFolders/watchedFolderDragState.ts
deleted file mode 100644
index 06e848c90d..0000000000
--- a/frontend/editor/src/core/components/watchedFolders/watchedFolderDragState.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-/**
- * Tracks which file ids are currently being dragged toward a Watched Folder.
- *
- * The HTML5 DnD spec hides `dataTransfer` values during `dragover`/`dragenter`
- * (they're only readable on `drop`), so a drop target can't tell *which* file is
- * hovering over it mid-drag. Drag sources publish the ids here on `dragstart`;
- * drop targets read them during `dragover` to give live feedback (e.g. "already
- * in this folder"). Cleared on `dragend`.
- */
-
-let draggedFileIds: string[] = [];
-
-export function setWatchedFolderDraggedFileIds(ids: string[]): void {
- draggedFileIds = ids;
-}
-
-export function getWatchedFolderDraggedFileIds(): string[] {
- return draggedFileIds;
-}
-
-export function clearWatchedFolderDraggedFileIds(): void {
- draggedFileIds = [];
-}
diff --git a/frontend/editor/src/core/constants/featureFlags.ts b/frontend/editor/src/core/constants/featureFlags.ts
index 8981dce2d6..f8a72b752f 100644
--- a/frontend/editor/src/core/constants/featureFlags.ts
+++ b/frontend/editor/src/core/constants/featureFlags.ts
@@ -3,14 +3,5 @@
* that's been temporarily pulled from the UI.
*/
-/**
- * Watched Folders. Disabled for now — gates both the custom workbench
- * registration (seeding, URL sync, view) and the sidebar entry point, so the
- * feature is unreachable from the UI. Flip to `true` to restore access.
- */
-// Annotated as `boolean` (not the literal `false`) so call sites aren't treated
-// as constant/unreachable conditions by the type checker and linter.
-export const WATCHED_FOLDERS_ENABLED: boolean = false;
-
// Refill an empty workbench from the tab's last session (survives a provider remount or a reload).
export const WORKBENCH_SESSION_RESTORE: boolean = true;
diff --git a/frontend/editor/src/core/contexts/FolderFileContext.tsx b/frontend/editor/src/core/contexts/FolderFileContext.tsx
deleted file mode 100644
index 6193a5c6b4..0000000000
--- a/frontend/editor/src/core/contexts/FolderFileContext.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { type ReactNode } from "react";
-
-/**
- * Core stub for the Watched Folders file context.
- *
- * Watched Folders is a proprietary feature — its real provider lives in
- * `proprietary/contexts/FolderFileContext.tsx`. The core build has no Watch
- * Folders consumers, so this is a pass-through that keeps `AppProviders`
- * (shared) compiling in the open-source build without pulling the feature in.
- */
-export function FolderFileContextProvider({
- children,
-}: {
- children: ReactNode;
-}) {
- return <>{children}</>;
-}
diff --git a/frontend/editor/src/core/hooks/useAllWatchedFolders.ts b/frontend/editor/src/core/hooks/useAllWatchedFolders.ts
deleted file mode 100644
index b1dbc2f579..0000000000
--- a/frontend/editor/src/core/hooks/useAllWatchedFolders.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * Read-only hook that returns all smart folders, kept in sync with storage changes.
- * Use this when you only need to read the folder list without CRUD operations.
- * For full CRUD, use useWatchedFolders instead.
- */
-
-import { useState, useEffect } from "react";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import {
- watchedFolderStorage,
- WATCHED_FOLDER_STORAGE_CHANGE_EVENT,
-} from "@app/services/watchedFolderStorage";
-
-export function useAllWatchedFolders(): WatchedFolder[] {
- const [folders, setFolders] = useState<WatchedFolder[]>([]);
-
- useEffect(() => {
- const load = async () => {
- try {
- // Policy-owned folders are managed by Policies, not shown here.
- const all = await watchedFolderStorage.getAllFolders();
- setFolders(all.filter((f) => !f.policyCategoryId));
- } catch (err) {
- console.error("Failed to load smart folders:", err);
- }
- };
-
- load();
- window.addEventListener(WATCHED_FOLDER_STORAGE_CHANGE_EVENT, load);
- return () =>
- window.removeEventListener(WATCHED_FOLDER_STORAGE_CHANGE_EVENT, load);
- }, []);
-
- return folders;
-}
diff --git a/frontend/editor/src/core/hooks/useFolderMembership.ts b/frontend/editor/src/core/hooks/useFolderMembership.ts
deleted file mode 100644
index 9484c133b0..0000000000
--- a/frontend/editor/src/core/hooks/useFolderMembership.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Returns a map of fileId → folderId[] for all files currently in any watched folder.
- * Both input files (keyed by their FileId in stirling-pdf-files) and their output
- * counterparts (displayFileId) are included so folder tags show on both versions.
- */
-
-import { useState, useEffect } from "react";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-import { useAllWatchedFolders } from "@app/hooks/useAllWatchedFolders";
-
-export function useFolderMembership(): Map<string, string[]> {
- const folders = useAllWatchedFolders();
- const [membership, setMembership] = useState<Map<string, string[]>>(
- new Map(),
- );
-
- useEffect(() => {
- if (folders.length === 0) {
- setMembership(new Map());
- return;
- }
-
- const load = async () => {
- const map = new Map<string, string[]>();
- const add = (fileId: string, folderId: string) => {
- const existing = map.get(fileId);
- if (existing) {
- if (!existing.includes(folderId)) existing.push(folderId);
- } else map.set(fileId, [folderId]);
- };
- for (const folder of folders) {
- try {
- const record = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- if (record) {
- Object.entries(record.files).forEach(([fileId, meta]) => {
- add(fileId, folder.id);
- const outputIds =
- meta?.displayFileIds ??
- (meta?.displayFileId ? [meta.displayFileId] : []);
- outputIds.forEach((oid) => add(oid, folder.id));
- });
- }
- } catch {
- // ignore individual folder failures
- }
- }
- setMembership(map);
- };
-
- load();
- return watchedFolderFileStorage.onFolderChange(load);
- }, [folders]);
-
- return membership;
-}
diff --git a/frontend/editor/src/core/icons/README.md b/frontend/editor/src/core/icons/README.md
index 7e521aa6f9..47e2ec442f 100644
--- a/frontend/editor/src/core/icons/README.md
+++ b/frontend/editor/src/core/icons/README.md
@@ -69,7 +69,7 @@ For a prop that takes *either* a name or your own node, narrow with `isIconName(
- **An unknown name never throws.** `<Icon>` draws a dashed-circle placeholder (`MISSING_ICON`) and, in dev, logs the name once; the svg carries `data-missing-icon` so a screenshot or e2e run can spot it. Seeing it means a typo, or a name from data that `icons.ts` does not map. `task frontend:lint:icons` catches Material Symbols names left in any position, and `isIconName` is the guard for names that arrive from data.
- **`fontSize` is inert on `<Icon>`.** The most likely regression when porting old code: the icon silently renders at the default size. Use `size`.
- **A filled/outline pair is one icon plus `filled`, not two.** MUI shipped `Star` and `StarBorder` as separate glyphs, so a component that rendered both collapsed to one name here. If a legacy diff shows a filled variant, check whether the difference encoded state before treating it as a duplicate.
-- **`iconMap.ts` keys are persisted.** A saved automation or watched folder stores `"SettingsIcon"`, so those keys must never be renamed — only their values.
+- **`iconMap.ts` keys are persisted.** A saved automation stores `"SettingsIcon"`, so those keys must never be renamed — only their values.
- **The classification label palette is mirrored in the backend** (`app/proprietary/src/main/resources/classification/classification-labels.json`) and a drift test enforces icon parity. Change both sides together.
- **Brand marks look unreferenced.** They resolve from connector ids the API returns, never from literals; the unused report and the gallery's *In use* view both allow for that.
- **No third-party icon artwork is checked in.** `Migration/Icon audit` gets its "before" glyphs from `virtual:legacy-icons`, served straight out of the icon packages by `editor/scripts/icons/legacyIcons.vite.mts`; never commit another icon set's geometry. The audit and everything it needs go once the mapping is signed off.
diff --git a/frontend/editor/src/core/services/retireLegacyFolderWorker.test.ts b/frontend/editor/src/core/services/retireLegacyFolderWorker.test.ts
new file mode 100644
index 0000000000..8710b9922d
--- /dev/null
+++ b/frontend/editor/src/core/services/retireLegacyFolderWorker.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { retireLegacyFolderWorker } from "@app/services/retireLegacyFolderWorker";
+
+const legacyScript = new URL("/sw-folder-retry.js", window.location.origin)
+ .href;
+
+function registration(
+ active: string | null,
+ waiting: string | null = null,
+ installing: string | null = null,
+) {
+ return {
+ active: active ? { scriptURL: active } : null,
+ waiting: waiting ? { scriptURL: waiting } : null,
+ installing: installing ? { scriptURL: installing } : null,
+ unregister: vi.fn().mockResolvedValue(true),
+ };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe("retireLegacyFolderWorker", () => {
+ it("retires legacy workers in any lifecycle phase and leaves other registrations alone", async () => {
+ const active = registration(legacyScript);
+ const waiting = registration(null, legacyScript);
+ const installing = registration(null, null, legacyScript);
+ const unrelated = registration(
+ new URL("/app-worker.js", window.location.origin).href,
+ );
+ const replacement = registration(legacyScript, unrelated.active?.scriptURL);
+ const empty = registration(null);
+ const getRegistrations = vi
+ .fn()
+ .mockResolvedValue([
+ active,
+ waiting,
+ installing,
+ unrelated,
+ replacement,
+ empty,
+ ]);
+ vi.stubGlobal("navigator", { serviceWorker: { getRegistrations } });
+
+ await retireLegacyFolderWorker();
+
+ for (const worker of [active, waiting, installing]) {
+ expect(worker.unregister).toHaveBeenCalledOnce();
+ }
+ for (const worker of [unrelated, replacement, empty]) {
+ expect(worker.unregister).not.toHaveBeenCalled();
+ }
+ });
+
+ it("works when service workers are unavailable", async () => {
+ vi.stubGlobal("navigator", {});
+ await expect(retireLegacyFolderWorker()).resolves.toBeUndefined();
+ });
+
+ it("allows startup when browser permissions prevent reading registrations", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.stubGlobal("navigator", {
+ serviceWorker: {
+ getRegistrations: vi.fn().mockRejectedValue(new Error("Access denied")),
+ },
+ });
+ await expect(retireLegacyFolderWorker()).resolves.toBeUndefined();
+ });
+
+ it("allows startup when unregistering fails", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+ const legacy = registration(legacyScript);
+ legacy.unregister.mockRejectedValue(new Error("Access denied"));
+ vi.stubGlobal("navigator", {
+ serviceWorker: { getRegistrations: vi.fn().mockResolvedValue([legacy]) },
+ });
+ await expect(retireLegacyFolderWorker()).resolves.toBeUndefined();
+ });
+});
diff --git a/frontend/editor/src/core/services/retireLegacyFolderWorker.ts b/frontend/editor/src/core/services/retireLegacyFolderWorker.ts
new file mode 100644
index 0000000000..f55d556ae2
--- /dev/null
+++ b/frontend/editor/src/core/services/retireLegacyFolderWorker.ts
@@ -0,0 +1,26 @@
+/** Unregister the retired folder-retry worker without changing stored files or folder data. */
+export async function retireLegacyFolderWorker(): Promise<void> {
+ if (!("serviceWorker" in navigator)) return;
+
+ try {
+ const scriptURL = new URL("/sw-folder-retry.js", window.location.origin)
+ .href;
+ const registrations = await navigator.serviceWorker.getRegistrations();
+ for (const registration of registrations) {
+ const workers = [
+ registration.active,
+ registration.waiting,
+ registration.installing,
+ ].filter((worker) => worker !== null);
+ // A different worker waiting on the same scope belongs to its current feature.
+ if (
+ workers.length > 0 &&
+ workers.every((worker) => worker.scriptURL === scriptURL)
+ ) {
+ await registration.unregister();
+ }
+ }
+ } catch (error) {
+ console.warn("Could not retire the legacy folder retry worker", error);
+ }
+}
diff --git a/frontend/editor/src/core/services/watchedFolderFileStorage.ts b/frontend/editor/src/core/services/watchedFolderFileStorage.ts
deleted file mode 100644
index 9a6be44e17..0000000000
--- a/frontend/editor/src/core/services/watchedFolderFileStorage.ts
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * Service for managing folder-file associations in IndexedDB.
- * File blobs are stored in the main stirling-pdf-files database (fileStorage).
- * This service only maintains folder record metadata: which file IDs belong to
- * which folders and their processing status.
- */
-
-import { FolderFileMetadata, FolderRecord } from "@app/types/watchedFolders";
-
-const FOLDER_CHANGE_EVENT = "folder-storage-changed";
-
-class WatchedFolderFileStorage {
- private dbName = "stirling-pdf-folder-files";
- private dbVersion = 3;
- private recordsStore = "folderRecords";
- private db: IDBDatabase | null = null;
-
- async init(): Promise<void> {
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(this.dbName, this.dbVersion);
-
- request.onerror = () => {
- reject(new Error("Failed to open folder files database"));
- };
-
- request.onsuccess = () => {
- this.db = request.result;
- resolve();
- };
-
- request.onupgradeneeded = (event) => {
- const db = (event.target as IDBOpenDBRequest).result;
- if (!db.objectStoreNames.contains(this.recordsStore)) {
- db.createObjectStore(this.recordsStore, { keyPath: "folderId" });
- }
- if (db.objectStoreNames.contains("folderOutputFiles")) {
- db.deleteObjectStore("folderOutputFiles");
- }
- if (db.objectStoreNames.contains("folderInputFiles")) {
- db.deleteObjectStore("folderInputFiles");
- }
- };
- });
- }
-
- private async ensureDB(): Promise<IDBDatabase> {
- if (!this.db) {
- await this.init();
- }
- if (!this.db) {
- throw new Error("Folder files database not initialized");
- }
- return this.db;
- }
-
- private dispatchChange(folderId: string): void {
- window.dispatchEvent(
- new CustomEvent(FOLDER_CHANGE_EVENT, { detail: { folderId } }),
- );
- }
-
- onFolderChange(listener: (folderId: string) => void): () => void {
- const handler = (e: Event) => {
- listener((e as CustomEvent).detail.folderId);
- };
- window.addEventListener(FOLDER_CHANGE_EVENT, handler);
- return () => window.removeEventListener(FOLDER_CHANGE_EVENT, handler);
- }
-
- async getFolderData(folderId: string): Promise<FolderRecord | null> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.recordsStore], "readonly");
- const store = transaction.objectStore(this.recordsStore);
- const request = store.get(folderId);
- request.onsuccess = () => resolve(request.result || null);
- request.onerror = () => reject(new Error("Failed to get folder data"));
- });
- }
-
- async addFileToFolder(
- folderId: string,
- fileId: string,
- metadata?: Partial<FolderFileMetadata>,
- ): Promise<void> {
- const db = await this.ensureDB();
- const now = new Date();
- return new Promise((resolve, reject) => {
- // Single readwrite transaction for both read and write — prevents lost-update
- // races when multiple files are added to the same folder concurrently.
- const transaction = db.transaction([this.recordsStore], "readwrite");
- const store = transaction.objectStore(this.recordsStore);
- const getRequest = store.get(folderId);
- getRequest.onsuccess = () => {
- const record: FolderRecord = getRequest.result || {
- folderId,
- files: {},
- lastUpdated: Date.now(),
- };
- record.files[fileId] = { addedAt: now, status: "pending", ...metadata };
- record.lastUpdated = Date.now();
- const putRequest = store.put(record);
- putRequest.onsuccess = () => {
- this.dispatchChange(folderId);
- resolve();
- };
- putRequest.onerror = () =>
- reject(new Error("Failed to add file to folder"));
- };
- getRequest.onerror = () =>
- reject(new Error("Failed to read folder for add"));
- });
- }
-
- async updateFileMetadata(
- folderId: string,
- fileId: string,
- updates: Partial<FolderFileMetadata>,
- ): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- // Single readwrite transaction — prevents lost-update races during concurrent
- // pipeline runs where multiple files update their status simultaneously.
- const transaction = db.transaction([this.recordsStore], "readwrite");
- const store = transaction.objectStore(this.recordsStore);
- const getRequest = store.get(folderId);
- getRequest.onsuccess = () => {
- const existing: FolderRecord | undefined = getRequest.result;
- if (!existing) {
- resolve();
- return;
- }
- existing.files[fileId] = { ...existing.files[fileId], ...updates };
- existing.lastUpdated = Date.now();
- const putRequest = store.put(existing);
- putRequest.onsuccess = () => {
- this.dispatchChange(folderId);
- resolve();
- };
- putRequest.onerror = () =>
- reject(new Error("Failed to update file metadata"));
- };
- getRequest.onerror = () =>
- reject(new Error("Failed to read folder for update"));
- });
- }
-
- async removeFileFromFolder(folderId: string, fileId: string): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.recordsStore], "readwrite");
- const store = transaction.objectStore(this.recordsStore);
- const getRequest = store.get(folderId);
- getRequest.onsuccess = () => {
- const existing: FolderRecord | undefined = getRequest.result;
- if (!existing) {
- resolve();
- return;
- }
- delete existing.files[fileId];
- existing.lastUpdated = Date.now();
- const putRequest = store.put(existing);
- putRequest.onsuccess = () => {
- this.dispatchChange(folderId);
- resolve();
- };
- putRequest.onerror = () =>
- reject(new Error("Failed to remove file from folder"));
- };
- getRequest.onerror = () =>
- reject(new Error("Failed to read folder for remove"));
- });
- }
-
- /**
- * Overwrite the entire folder record.
- * Pass `{ silent: true }` for mirror writes — these reflect a read,
- * not a user action, so dispatching change events would cause subscribers
- * (which themselves call getFolderData) to re-fetch in an infinite loop.
- */
- async setFolderData(
- folderId: string,
- record: FolderRecord,
- opts?: { silent?: boolean },
- ): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.recordsStore], "readwrite");
- const store = transaction.objectStore(this.recordsStore);
- const request = store.put(record);
- request.onsuccess = () => {
- if (!opts?.silent) this.dispatchChange(folderId);
- resolve();
- };
- request.onerror = () => reject(new Error("Failed to set folder data"));
- });
- }
-
- async clearFolder(folderId: string): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.recordsStore], "readwrite");
- const store = transaction.objectStore(this.recordsStore);
- const request = store.delete(folderId);
- request.onsuccess = () => {
- this.dispatchChange(folderId);
- resolve();
- };
- request.onerror = () => reject(new Error("Failed to clear folder"));
- });
- }
-}
-
-export const watchedFolderFileStorage = new WatchedFolderFileStorage();
diff --git a/frontend/editor/src/core/services/watchedFolderStorage.ts b/frontend/editor/src/core/services/watchedFolderStorage.ts
deleted file mode 100644
index 08f814abfd..0000000000
--- a/frontend/editor/src/core/services/watchedFolderStorage.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-/**
- * Service for managing Watched Folder configurations in IndexedDB
- */
-
-import { WatchedFolder } from "@app/types/watchedFolders";
-
-const STORAGE_CHANGE_EVENT = "watched-folder-storage-changed";
-
-class WatchedFolderStorage {
- private dbName = "stirling-pdf-watched-folders";
- private dbVersion = 1;
- private storeName = "watchedFolders";
- private db: IDBDatabase | null = null;
- private initPromise: Promise<void> | null = null;
-
- async init(): Promise<void> {
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(this.dbName, this.dbVersion);
-
- request.onerror = () => {
- reject(new Error("Failed to open smart folder storage database"));
- };
-
- request.onsuccess = () => {
- this.db = request.result;
- this.db.onclose = () => {
- this.db = null;
- this.initPromise = null;
- };
- resolve();
- };
-
- request.onupgradeneeded = (event) => {
- const db = (event.target as IDBOpenDBRequest).result;
- if (!db.objectStoreNames.contains(this.storeName)) {
- const store = db.createObjectStore(this.storeName, { keyPath: "id" });
- store.createIndex("name", "name", { unique: false });
- store.createIndex("createdAt", "createdAt", { unique: false });
- store.createIndex("order", "order", { unique: false });
- }
- };
- });
- }
-
- private async ensureDB(): Promise<IDBDatabase> {
- if (!this.db) {
- this.initPromise ??= this.init();
- await this.initPromise;
- }
- if (!this.db) {
- throw new Error("Smart folder database not initialized");
- }
- return this.db;
- }
-
- private dispatchChange(): void {
- window.dispatchEvent(new Event(STORAGE_CHANGE_EVENT));
- }
-
- async getAllFolders(): Promise<WatchedFolder[]> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readonly");
- const store = transaction.objectStore(this.storeName);
- const request = store.getAll();
- request.onsuccess = () => {
- const folders: WatchedFolder[] = request.result || [];
- folders.sort((a, b) => {
- const orderA = a.order ?? Number.MAX_SAFE_INTEGER;
- const orderB = b.order ?? Number.MAX_SAFE_INTEGER;
- if (orderA !== orderB) return orderA - orderB;
- return (
- new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
- );
- });
- resolve(folders);
- };
- request.onerror = () => reject(new Error("Failed to get smart folders"));
- });
- }
-
- async getFolder(id: string): Promise<WatchedFolder | null> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readonly");
- const store = transaction.objectStore(this.storeName);
- const request = store.get(id);
- request.onsuccess = () => resolve(request.result || null);
- request.onerror = () => reject(new Error("Failed to get smart folder"));
- });
- }
-
- async createFolder(
- data: Omit<WatchedFolder, "id" | "createdAt" | "updatedAt">,
- ): Promise<WatchedFolder> {
- const db = await this.ensureDB();
- const timestamp = new Date().toISOString();
- const folder: WatchedFolder = {
- id: crypto.randomUUID(),
- ...data,
- createdAt: timestamp,
- updatedAt: timestamp,
- };
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const request = store.add(folder);
- request.onsuccess = () => {
- this.dispatchChange();
- resolve(folder);
- };
- request.onerror = () =>
- reject(new Error("Failed to create smart folder"));
- });
- }
-
- async createFolderWithId(folder: WatchedFolder): Promise<WatchedFolder> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const request = store.put(folder);
- request.onsuccess = () => {
- this.dispatchChange();
- resolve(folder);
- };
- request.onerror = () =>
- reject(new Error("Failed to create smart folder with id"));
- });
- }
-
- async updateFolder(folder: WatchedFolder): Promise<WatchedFolder> {
- const db = await this.ensureDB();
- const updated: WatchedFolder = {
- ...folder,
- updatedAt: new Date().toISOString(),
- };
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const request = store.put(updated);
- request.onsuccess = () => {
- this.dispatchChange();
- resolve(updated);
- };
- request.onerror = () =>
- reject(new Error("Failed to update smart folder"));
- });
- }
-
- async deleteFolder(id: string): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const request = store.delete(id);
- request.onsuccess = () => {
- this.dispatchChange();
- resolve();
- };
- request.onerror = () =>
- reject(new Error("Failed to delete smart folder"));
- });
- }
-}
-
-export const watchedFolderStorage = new WatchedFolderStorage();
-export { STORAGE_CHANGE_EVENT as WATCHED_FOLDER_STORAGE_CHANGE_EVENT };
diff --git a/frontend/editor/src/core/tests/live/watched-folders.spec.ts b/frontend/editor/src/core/tests/live/watched-folders.spec.ts
deleted file mode 100644
index 0021a4edf4..0000000000
--- a/frontend/editor/src/core/tests/live/watched-folders.spec.ts
+++ /dev/null
@@ -1,580 +0,0 @@
-/**
- * Comprehensive Playwright tests for the Watched Folders feature.
- *
- * Tests cover: navigation, folder CRUD, preset seeding, drag-and-drop,
- * modal interactions, sidebar integration, IndexedDB state, and error states.
- *
- * Run: npx playwright test watched-folders --project=chromium --reporter=list
- */
-
-import type { Page } from "@playwright/test";
-import { test, expect } from "@app/tests/helpers/test-base";
-import { loginAndSetup } from "@app/tests/helpers/login";
-
-// ---------------------------------------------------------------------------
-// Shared helpers
-// ---------------------------------------------------------------------------
-
-// Watched Folders ships behind the WATCHED_FOLDERS_ENABLED flag, which is off in
-// every build today, so its entry points never render. This live suite is
-// therefore skipped unless the app under test is built with the feature enabled
-// and the runner opts in via WATCHED_FOLDERS_E2E=1. When re-enabling, also revisit
-// the sidebar entry point (the old QuickAccessBar button no longer exists).
-test.beforeEach(() => {
- const enabled = ["1", "true"].includes(process.env.WATCHED_FOLDERS_E2E ?? "");
- test.skip(
- !enabled,
- "Watched Folders is feature-flagged off; set WATCHED_FOLDERS_E2E=1 to run",
- );
-});
-
-async function setupApp(page: Page): Promise<void> {
- // Use the shared login helper (real UI login with the bootstrapped
- // `admin / adminadmin` credentials). The previous bespoke /api/v1/auth/login
- // call used the pre-bootstrap `stirling` password and always 401'd.
- await loginAndSetup(page);
- await page.waitForSelector('[data-testid="watchedFolders-button"]', {
- timeout: 30000,
- });
-}
-
-async function navigateToWatchedFolders(page: Page): Promise<void> {
- await page.locator('[data-testid="watchedFolders-button"]').click();
- await page.waitForSelector('button:has-text("New folder")', {
- timeout: 10000,
- });
-}
-
-async function getIDBFolderCount(page: Page): Promise<number> {
- return page.evaluate(async () => {
- return new Promise<number>((resolve) => {
- const req = indexedDB.open("stirling-pdf-watched-folders");
- req.onsuccess = () => {
- const db = req.result;
- const storeName = db.objectStoreNames[0];
- if (!storeName) {
- resolve(0);
- return;
- }
- const tx = db.transaction(storeName, "readonly");
- const count = tx.objectStore(storeName).count();
- count.onsuccess = () => resolve(count.result);
- count.onerror = () => resolve(0);
- };
- req.onerror = () => resolve(0);
- });
- });
-}
-
-async function getIDBFolders(
- page: Page,
-): Promise<{ id: string; name: string }[]> {
- return page.evaluate(async () => {
- return new Promise<{ id: string; name: string }[]>((resolve) => {
- const req = indexedDB.open("stirling-pdf-watched-folders");
- req.onsuccess = () => {
- const db = req.result;
- const storeName = db.objectStoreNames[0];
- if (!storeName) {
- resolve([]);
- return;
- }
- const tx = db.transaction(storeName, "readonly");
- const all = tx.objectStore(storeName).getAll();
- all.onsuccess = () =>
- resolve(
- (all.result || []).map((f: { id: string; name: string }) => ({
- id: f.id,
- name: f.name,
- })),
- );
- all.onerror = () => resolve([]);
- };
- req.onerror = () => resolve([]);
- });
- });
-}
-
-async function clearAllIDBFolders(page: Page): Promise<void> {
- await page.evaluate(async () => {
- const dbNames = [
- "stirling-pdf-watched-folders",
- "stirling-pdf-folder-files",
- "stirling-pdf-folder-run-state",
- "stirling-pdf-retry-schedule",
- "stirling-pdf-folder-seen-files",
- "stirling-pdf-folder-directory-handles",
- ];
- for (const name of dbNames) {
- await new Promise<void>((resolve) => {
- const req = indexedDB.deleteDatabase(name);
- req.onsuccess = () => resolve();
- req.onerror = () => resolve();
- req.onblocked = () => resolve();
- });
- }
- localStorage.removeItem("watched_folders_seeded");
- });
-}
-
-// ---------------------------------------------------------------------------
-// Test: Navigation
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Navigation", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- });
-
- test("sidebar button navigates to Watched Folders home", async ({ page }) => {
- await page.locator('[data-testid="watchedFolders-button"]').click();
- // Should see the home page with "New folder" button
- await expect(
- page.getByRole("button", { name: "New folder" }).first(),
- ).toBeVisible({ timeout: 10000 });
- });
-
- test("clicking Watched Folders button twice returns to home", async ({
- page,
- }) => {
- await navigateToWatchedFolders(page);
- // Click a folder card to navigate into it, then click the button again
- const firstCard = page.locator('[data-testid="watchedFolders-button"]');
- await firstCard.click();
- await expect(
- page.getByRole("button", { name: "New folder" }).first(),
- ).toBeVisible({ timeout: 10000 });
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: Preset Seeding
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Presets", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- await clearAllIDBFolders(page);
- });
-
- test("seeds 4 default folders on first visit", async ({ page }) => {
- // Navigate to watched folders — this triggers WatchedFoldersRegistration which calls seedDefaultFolders
- await navigateToWatchedFolders(page);
- // Wait a bit for seeding to complete
- await page.waitForTimeout(2000);
-
- const count = await getIDBFolderCount(page);
- expect(count).toBe(4);
-
- const folders = await getIDBFolders(page);
- const names = folders.map((f) => f.name).sort();
- expect(names).toEqual([
- "Email Prep",
- "Pre-publish",
- "Rotate & Optimise",
- "Secure Ingestion",
- ]);
- });
-
- test("does not re-seed on second visit", async ({ page }) => {
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(2000);
- const count1 = await getIDBFolderCount(page);
-
- // Navigate away and back
- await page.goto("/editor", { waitUntil: "domcontentloaded" });
- await page.waitForSelector('[data-testid="watchedFolders-button"]', {
- timeout: 15000,
- });
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1000);
-
- const count2 = await getIDBFolderCount(page);
- expect(count2).toBe(count1);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: Folder CRUD
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Create / Edit / Delete", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- });
-
- test("create a new folder via modal", async ({ page }) => {
- await navigateToWatchedFolders(page);
-
- const initialCount = await getIDBFolderCount(page);
-
- // Open modal
- await page.getByRole("button", { name: "New folder" }).first().click();
- await page.waitForTimeout(500);
-
- // Fill name
- const nameInput = page.getByPlaceholder("My watched folder");
- if (await nameInput.isVisible({ timeout: 3000 }).catch(() => false)) {
- await nameInput.fill("Test Folder");
- } else {
- // Fallback — find the first text input in the modal
- await page.locator('input[type="text"]').first().fill("Test Folder");
- }
-
- // We need to configure at least the minimum tools before save will work
- // Try to find and fill tool slots
- const toolInputs = page.getByPlaceholder("Select a tool...");
- if (
- await toolInputs
- .first()
- .isVisible({ timeout: 2000 })
- .catch(() => false)
- ) {
- await toolInputs.first().click();
- await page.waitForTimeout(200);
- await toolInputs.first().fill("compress");
- await page.waitForTimeout(400);
- // Click the compress option
- const compressOption = page
- .getByRole("button", { name: /compress/i })
- .first();
- if (
- await compressOption.isVisible({ timeout: 2000 }).catch(() => false)
- ) {
- await compressOption.click();
- await page.waitForTimeout(300);
- }
- }
-
- // Try to save
- const createBtn = page.getByText("Create Folder");
- if (await createBtn.isVisible({ timeout: 2000 }).catch(() => false)) {
- await createBtn.click();
- await page.waitForTimeout(2000);
- }
-
- const newCount = await getIDBFolderCount(page);
- // Should have at least one more folder than before
- expect(newCount).toBeGreaterThanOrEqual(initialCount);
- });
-
- test("delete a folder cleans up all related IDB stores", async ({ page }) => {
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1000);
-
- const folders = await getIDBFolders(page);
- if (folders.length === 0) {
- test.skip();
- return;
- }
-
- const targetFolder = folders[0];
-
- // Delete via IDB directly and check cleanup
- await page.evaluate(
- async ({ folderId }) => {
- // Seed some test data in related stores
- const seedStore = (
- dbName: string,
- storeName: string,
- key: string,
- value: unknown,
- ) =>
- new Promise<void>((resolve) => {
- const req = indexedDB.open(dbName);
- req.onsuccess = () => {
- const db = req.result;
- if (!db.objectStoreNames.contains(storeName)) {
- resolve();
- return;
- }
- const tx = db.transaction(storeName, "readwrite");
- tx.objectStore(storeName).put(value, key);
- tx.oncomplete = () => resolve();
- tx.onerror = () => resolve();
- };
- req.onerror = () => resolve();
- });
-
- await seedStore(
- "stirling-pdf-folder-seen-files",
- "seenFiles",
- `${folderId}|test.pdf|1234|5678`,
- Date.now(),
- );
- },
- { folderId: targetFolder.id },
- );
-
- // Now trigger folder deletion via the hook mechanism
- // We simulate what the delete button does by calling the storage directly
- await page.evaluate(
- async ({ folderId }) => {
- // Delete from watched folder storage
- await new Promise<void>((resolve) => {
- const req = indexedDB.open("stirling-pdf-watched-folders");
- req.onsuccess = () => {
- const db = req.result;
- const storeName = db.objectStoreNames[0];
- if (!storeName) {
- resolve();
- return;
- }
- const tx = db.transaction(storeName, "readwrite");
- tx.objectStore(storeName).delete(folderId);
- tx.oncomplete = () => resolve();
- tx.onerror = () => resolve();
- };
- req.onerror = () => resolve();
- });
- },
- { folderId: targetFolder.id },
- );
-
- // Verify the folder is gone
- const remaining = await getIDBFolders(page);
- expect(remaining.find((f) => f.id === targetFolder.id)).toBeUndefined();
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: Management Modal
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Management Modal", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- await navigateToWatchedFolders(page);
- });
-
- test("modal opens and shows name input", async ({ page }) => {
- await page.getByRole("button", { name: "New folder" }).first().click();
- await page.waitForTimeout(500);
-
- // Should show the name input
- const nameInput = page.getByPlaceholder("My watched folder");
- await expect(nameInput).toBeVisible({ timeout: 5000 });
- });
-
- test("modal closes on Escape key", async ({ page }) => {
- await page.getByRole("button", { name: "New folder" }).first().click();
- await page.waitForTimeout(500);
-
- const nameInput = page.getByPlaceholder("My watched folder");
- await expect(nameInput).toBeVisible({ timeout: 5000 });
-
- await page.keyboard.press("Escape");
- await page.waitForTimeout(500);
-
- // Modal should be gone
- await expect(nameInput).toBeHidden({ timeout: 5000 });
- });
-
- test("name input enforces 50 character limit", async ({ page }) => {
- await page.getByRole("button", { name: "New folder" }).first().click();
- await page.waitForTimeout(500);
-
- const nameInput = page.getByPlaceholder("My watched folder");
- await expect(nameInput).toBeVisible({ timeout: 5000 });
-
- // Type a very long string
- const longName = "A".repeat(60);
- await nameInput.fill(longName);
- const value = await nameInput.inputValue();
- expect(value.length).toBeLessThanOrEqual(50);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: Home Page UI
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Home Page", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1500); // wait for seeding
- });
-
- test("displays folder cards for seeded presets", async ({ page }) => {
- // Should see at least some folder cards
- const folderNames = [
- "Secure Ingestion",
- "Pre-publish",
- "Email Prep",
- "Rotate & Optimise",
- ];
- for (const name of folderNames) {
- const card = page.getByText(name).first();
- const visible = await card
- .isVisible({ timeout: 3000 })
- .catch(() => false);
- if (visible) {
- expect(visible).toBe(true);
- }
- }
- });
-
- test('shows "How it works" section on first visit', async ({ page }) => {
- // Clear the session storage flag
- await page.evaluate(() =>
- sessionStorage.removeItem("watchedFolderHowItWorksDismissed"),
- );
- // Re-navigate
- await page.goto("/editor", { waitUntil: "domcontentloaded" });
- await page.waitForSelector('[data-testid="watchedFolders-button"]', {
- timeout: 15000,
- });
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1000);
-
- // Look for "How" text
- const howItWorks = page.getByText(/How.*[Ww]atch.*[Ff]olders.*work/i);
- const visible = await howItWorks
- .isVisible({ timeout: 3000 })
- .catch(() => false);
- // This is expected to be visible on first visit (if not dismissed)
- // Don't hard-fail if not found — it may have been dismissed in session
- if (visible) {
- expect(visible).toBe(true);
- }
- });
-
- test('"New folder" button is present and clickable', async ({ page }) => {
- const btn = page.getByRole("button", { name: "New folder" }).first();
- await expect(btn).toBeVisible();
- await expect(btn).toBeEnabled();
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: Sidebar Section
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Sidebar", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1500);
- });
-
- test("sidebar shows folder entries", async ({ page }) => {
- // The sidebar should have a section with folder names
- const sidebar = page
- .locator('[class*="sidebar"], [data-testid*="sidebar"]')
- .first();
- if (await sidebar.isVisible({ timeout: 3000 }).catch(() => false)) {
- // Check for at least one folder name in the sidebar area
- const sidebarText = await sidebar.textContent();
- // Should contain at least one preset name
- const hasFolder = ["Secure", "Pre-publish", "Email", "Rotate"].some(
- (name) => sidebarText?.includes(name),
- );
- expect(hasFolder).toBe(true);
- }
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: IndexedDB Storage Integrity
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Storage Integrity", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- });
-
- test("folder IDs are valid UUIDs (no prefix)", async ({ page }) => {
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(2000);
-
- const folders = await getIDBFolders(page);
- for (const folder of folders) {
- // Should be a valid UUID format
- expect(folder.id).toMatch(
- /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
- );
- // Should NOT have the old prefix
- expect(folder.id).not.toMatch(/^folder-/);
- }
- });
-
- test("seeded flag is set in localStorage after seeding", async ({ page }) => {
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(2000);
-
- const flag = await page.evaluate(() =>
- localStorage.getItem("watched_folders_seeded"),
- );
- expect(flag).toBe("true");
- });
-
- test("clearing localStorage flag and reloading re-seeds folders", async ({
- page,
- }) => {
- await clearAllIDBFolders(page);
-
- // Navigate to trigger seeding
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(2000);
-
- const count = await getIDBFolderCount(page);
- expect(count).toBe(4);
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: Responsive / Accessibility basics
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — Accessibility", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1500);
- });
-
- test("New folder button is focusable via Tab", async ({ page }) => {
- // Tab through the page until we reach the New folder button
- for (let i = 0; i < 30; i++) {
- await page.keyboard.press("Tab");
- const focused = await page.evaluate(
- () => document.activeElement?.textContent,
- );
- if (focused?.includes("New folder")) {
- expect(true).toBe(true);
- return;
- }
- }
- // If we didn't find it in 30 tabs, that's concerning but not necessarily a failure
- // (depends on page structure)
- });
-});
-
-// ---------------------------------------------------------------------------
-// Test: File Count Display
-// ---------------------------------------------------------------------------
-
-test.describe("Watched Folders — File Count", () => {
- test.beforeEach(async ({ page }) => {
- await setupApp(page);
- await navigateToWatchedFolders(page);
- await page.waitForTimeout(1500);
- });
-
- test("file count text is visible in both light and dark themes", async ({
- page,
- }) => {
- // The file count should NOT have hardcoded white color (we fixed this)
- // Verify by checking computed styles
- const fileCountTexts = page.locator("text=file").first();
- if (await fileCountTexts.isVisible({ timeout: 2000 }).catch(() => false)) {
- const color = await fileCountTexts.evaluate(
- (el) => window.getComputedStyle(el).color,
- );
- // Should not be pure white (#fff = rgb(255, 255, 255))
- // In light theme, it should be a dark color
- expect(color).toBeDefined();
- }
- });
-});
diff --git a/frontend/editor/src/core/types/watchedFolders.ts b/frontend/editor/src/core/types/watchedFolders.ts
deleted file mode 100644
index f87ce6e0a2..0000000000
--- a/frontend/editor/src/core/types/watchedFolders.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * Types for Watched Folders (a.k.a. Watched Folders) functionality.
- *
- * Server-backed persistence and server-side processing fields are intentionally
- * not in this type — they land in a follow-up PR.
- */
-
-export interface WatchedFolder {
- id: string;
- name: string;
- description: string;
- automationId: string; // FK → AutomationConfig.id
- icon: string; // icon name string
- accentColor: string; // hex e.g. '#3b82f6'
- createdAt: string;
- updatedAt: string;
- order?: number;
- isDefault?: boolean;
- isPaused?: boolean;
- maxRetries?: number; // 0 = disabled; default 3
- retryDelayMinutes?: number; // default 5
- outputMode?: "new_file" | "new_version"; // default: 'new_file'
- outputName?: string; // output filename prefix/suffix
- outputNamePosition?: "prefix" | "suffix" | "auto-number"; // default: 'prefix'
- hasOutputDirectory?: boolean; // true when a local FS output folder is configured
- /** Where input files come from. Default: 'idb' (dropped/sidebar files stay in browser). */
- inputSource?: "idb" | "local-folder";
- /** Set when this folder is the backing store for a Policy (its category id).
- * Policy-owned folders are filtered out of the Watched Folders UI. */
- policyCategoryId?: string;
-}
-
-export interface FolderFileMetadata {
- addedAt: Date;
- status: "pending" | "processing" | "processed" | "error";
- processedAt?: Date;
- /** All output file ids produced by this run — references stirling-pdf-files */
- displayFileIds?: string[];
- /** First output file id — kept for backwards compat with existing records */
- displayFileId?: string;
- /** True when the folder created this file from a disk drop and therefore owns it.
- * False / absent when the file came from the shared sidebar store — do NOT delete on folder removal. */
- ownedByFolder?: boolean;
- errorMessage?: string;
- failedAttempts?: number;
- nextRetryAt?: number; // ms timestamp — set when an automatic retry is scheduled
- lastFailedAt?: Date;
- name?: string; // original filename
-}
-
-export interface FolderRecord {
- folderId: string;
- files: Record<string, FolderFileMetadata>;
- lastUpdated: number;
-}
-
-export interface WatchedFolderRunEntry {
- inputFileId: string;
- /** First output file id */
- displayFileId: string;
- /** All output file ids produced by this run — kept in sync with FolderFileMetadata.displayFileIds */
- displayFileIds?: string[];
- /** When this run completed — used for TTL-based "done" status */
- processedAt?: Date;
- status: "processing" | "processed";
-}
-
-export interface WatchedFolderViewData {
- /** Folder currently open in the view; null = the folder list / home. */
- folderId: string | null;
- pendingFileId?: string;
- pendingFileIds?: string[];
-}
diff --git a/frontend/editor/src/core/ui/IconPicker.tsx b/frontend/editor/src/core/ui/IconPicker.tsx
index c6fe67df11..e5bfeefa1f 100644
--- a/frontend/editor/src/core/ui/IconPicker.tsx
+++ b/frontend/editor/src/core/ui/IconPicker.tsx
@@ -27,8 +27,8 @@ export interface IconPickerProps {
/**
* Pick an icon from a caller-supplied set. The chosen glyph is the trigger; the menu is a grid. The
- * icon set is injected (via {@link options}) rather than baked in, so any surface - a pipeline, a
- * watched folder, an automation - passes its own vocabulary and shares the one control.
+ * icon set is injected (via {@link options}) rather than baked in, so any surface - a pipeline, an
+ * automation - passes its own vocabulary and shares the one control.
*/
export function IconPicker({
value,
diff --git a/frontend/editor/src/desktop/hooks/useAllWatchedFolders.test.ts b/frontend/editor/src/desktop/hooks/useAllWatchedFolders.test.ts
deleted file mode 100644
index 9164da230e..0000000000
--- a/frontend/editor/src/desktop/hooks/useAllWatchedFolders.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { renderHook } from "@testing-library/react";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import type { WatchedFolder } from "@app/types/watchedFolders";
-import { useAllWatchedFolders } from "@app/hooks/useAllWatchedFolders";
-
-const state = vi.hoisted(() => ({
- enabled: false,
- folders: [] as WatchedFolder[],
-}));
-
-vi.mock("@core/hooks/useAllWatchedFolders", () => ({
- useAllWatchedFolders: () => state.folders,
-}));
-vi.mock("@app/components/policies/usePoliciesEnabled", () => ({
- usePoliciesEnabled: () => state.enabled,
-}));
-
-beforeEach(() => {
- state.enabled = false;
- state.folders = [
- {
- id: "invoices",
- name: "Invoices",
- description: "",
- automationId: "classify",
- icon: "folder",
- accentColor: "",
- createdAt: "2026-09-16T00:00:00Z",
- updatedAt: "2026-09-16T00:00:00Z",
- },
- ];
-});
-
-describe("desktop watched folders", () => {
- test("keeps the disabled snapshot stable so membership effects settle", () => {
- const { result, rerender } = renderHook(useAllWatchedFolders);
- const disabled = result.current;
- expect(disabled).toEqual([]);
-
- state.folders = [...state.folders];
- rerender();
-
- expect(result.current).toBe(disabled);
- });
-
- test("exposes stored folders only while automation is enabled", () => {
- const { result, rerender } = renderHook(useAllWatchedFolders);
- const disabled = result.current;
-
- state.enabled = true;
- rerender();
- expect(result.current).toBe(state.folders);
-
- state.enabled = false;
- rerender();
- expect(result.current).toBe(disabled);
- });
-});
diff --git a/frontend/editor/src/desktop/hooks/useAllWatchedFolders.ts b/frontend/editor/src/desktop/hooks/useAllWatchedFolders.ts
deleted file mode 100644
index c359e159be..0000000000
--- a/frontend/editor/src/desktop/hooks/useAllWatchedFolders.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { useAllWatchedFolders as useStoredWatchedFolders } from "@core/hooks/useAllWatchedFolders";
-import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
-import type { WatchedFolder } from "@app/types/watchedFolders";
-
-// Membership consumers use this snapshot as an effect dependency.
-const EMPTY_FOLDERS: WatchedFolder[] = [];
-
-/** Legacy watched folders are visible only while connected to an authenticated server. */
-export function useAllWatchedFolders(): WatchedFolder[] {
- const folders = useStoredWatchedFolders();
- const enabled = usePoliciesEnabled();
- return enabled ? folders : EMPTY_FOLDERS;
-}
diff --git a/frontend/editor/src/proprietary/App.tsx b/frontend/editor/src/proprietary/App.tsx
index 0ff43f75cf..b5d98c877b 100644
--- a/frontend/editor/src/proprietary/App.tsx
+++ b/frontend/editor/src/proprietary/App.tsx
@@ -5,7 +5,6 @@ import { AppLayout } from "@app/components/AppLayout";
import { LoadingFallback } from "@app/components/shared/LoadingFallback";
import { PreferencesProvider } from "@app/contexts/PreferencesContext";
import { ThemeProvider } from "@app/components/shared/ThemeProvider";
-import { useConnectedServer } from "@app/hooks/useConnectedServer";
const Landing = lazy(() => import("@app/routes/Landing"));
const Login = lazy(() => import("@app/routes/Login"));
@@ -16,13 +15,9 @@ const ParticipantView = lazy(
() => import("@app/components/workflow/ParticipantView"),
);
const Onboarding = lazy(() => import("@app/components/onboarding/Onboarding"));
-const WatchedFoldersRegistration = lazy(
- () => import("@app/components/watchedFolders/WatchedFoldersRegistration"),
-);
const MobileScannerPage = lazy(() => import("@app/pages/MobileScannerPage"));
const MobileSignPage = lazy(() => import("@app/pages/MobileSignPage"));
-import { WATCHED_FOLDERS_ENABLED } from "@app/constants/featureFlags";
import { getAdminRouteExtensions } from "@app/routes/adminRouteExtensions";
import { AppFrame } from "@app/components/layout/AppFrame";
import { NoAppChrome } from "@app/components/layout/NoAppChrome";
@@ -55,7 +50,6 @@ function ParticipantViewPage() {
}
export default function App() {
- const connectedServer = useConnectedServer();
return (
<Suspense fallback={<LoadingFallback />}>
<Routes>
@@ -128,9 +122,6 @@ export default function App() {
<Route path="/*" element={<Landing />} />
</Routes>
<Onboarding />
- {WATCHED_FOLDERS_ENABLED && connectedServer && (
- <WatchedFoldersRegistration />
- )}
</AppLayout>
</AppProviders>
</RootGate>
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/CardExpansionModal.tsx b/frontend/editor/src/proprietary/components/watchedFolders/CardExpansionModal.tsx
deleted file mode 100644
index f0ca2bcbf5..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/CardExpansionModal.tsx
+++ /dev/null
@@ -1,278 +0,0 @@
-import React, { useState, useEffect } from "react";
-import { createPortal } from "react-dom";
-import { useTranslation } from "react-i18next";
-import { Text, ScrollArea } from "@mantine/core";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Icon } from "@app/ui/Icon";
-import {
- CardModalPhase,
- CARD_MODAL_TIMINGS,
-} from "@app/hooks/useCardModalAnimation";
-
-interface CardExpansionModalProps {
- phase: CardModalPhase;
- cardRect: DOMRect | null;
- textExpanded: boolean;
- onClose: () => void;
- icon: React.ReactNode;
- count: number;
- labelSingular: string;
- labelPlural: string;
- children: React.ReactNode;
- footer?: React.ReactNode;
- toolbar?: React.ReactNode;
- widthRem?: number;
- heightRem?: number;
- /** Replace ScrollArea with a flex-fill container so children can expand to full body height */
- fillHeight?: boolean;
-}
-
-const MODAL_W_REM = 56;
-const MODAL_H_REM = 38;
-const HEADER_H_REM = 3.5;
-const MODAL_TOP_FRACTION = 0.12;
-const EASING = "cubic-bezier(0.22,1,0.36,1)";
-
-export function CardExpansionModal({
- phase,
- cardRect,
- textExpanded,
- onClose,
- icon,
- count,
- labelSingular,
- labelPlural,
- children,
- footer,
- toolbar,
- widthRem,
- heightRem,
- fillHeight,
-}: CardExpansionModalProps) {
- const { t } = useTranslation();
- const [viewportW, setViewportW] = useState(window.innerWidth);
- const [viewportH, setViewportH] = useState(window.innerHeight);
-
- useEffect(() => {
- const handler = () => {
- setViewportW(window.innerWidth);
- setViewportH(window.innerHeight);
- };
- window.addEventListener("resize", handler);
- return () => window.removeEventListener("resize", handler);
- }, []);
-
- if (phase === "closed" || !cardRect) return null;
-
- const rootFontSize = parseFloat(
- getComputedStyle(document.documentElement).fontSize,
- );
- const modalW = Math.min(
- (widthRem ?? MODAL_W_REM) * rootFontSize,
- viewportW * 0.9,
- );
- const modalH = Math.min(
- (heightRem ?? MODAL_H_REM) * rootFontSize,
- viewportH * 0.85,
- );
- const headerH = HEADER_H_REM * rootFontSize;
- const finalLeft = (viewportW - modalW) / 2;
- const finalTop = Math.min(
- viewportH * MODAL_TOP_FRACTION,
- viewportH - modalH - 16,
- );
-
- const isAtCard = phase === "entering" || phase === "closing-header";
- const isAtHeader = phase === "header-open";
-
- const cardH = isAtCard ? cardRect.height : isAtHeader ? headerH : modalH;
-
- const getTransition = () => {
- const s = CARD_MODAL_TIMINGS;
- if (phase === "header-open")
- return `top ${s.headerStretch}ms ${EASING}, left ${s.headerStretch}ms ${EASING}, width ${s.headerStretch}ms ${EASING}, height ${s.headerStretch}ms ${EASING}`;
- if (phase === "open") return `height ${s.bodyDrop}ms ${EASING}`;
- if (phase === "closing-body") return `height ${s.closeBody}ms ease-in`;
- if (phase === "closing-header")
- return `top ${s.closeStretch}ms ${EASING}, left ${s.closeStretch}ms ${EASING}, width ${s.closeStretch}ms ${EASING}, height ${s.closeStretch}ms ${EASING}, opacity ${s.closeStretch}ms ease`;
- return "none";
- };
-
- const backdropOpacity =
- phase === "entering" || phase === "closing-header" ? 0 : 1;
- const cardOpacity = phase === "closing-header" ? 0 : 1;
-
- const showBody = phase === "open" || phase === "closing-body";
-
- return createPortal(
- <div style={{ position: "fixed", inset: 0, zIndex: 300 }}>
- <div
- onClick={onClose}
- style={{
- position: "absolute",
- inset: 0,
- backgroundColor: "rgba(0,0,0,0.55)",
- opacity: backdropOpacity,
- transition: "opacity 220ms ease",
- willChange: "opacity",
- }}
- />
-
- <div
- style={{
- position: "fixed",
- top: isAtCard ? cardRect.top : finalTop,
- left: isAtCard ? cardRect.left : finalLeft,
- width: isAtCard ? cardRect.width : modalW,
- height: cardH,
- opacity: cardOpacity,
- transition: getTransition(),
- willChange: "top, left, width, height, opacity",
- borderRadius: "var(--mantine-radius-md)",
- overflow: "hidden",
- backgroundColor: "var(--c-bg-raised)",
- display: "flex",
- flexDirection: "column",
- boxShadow: "0 1.5rem 3rem rgba(0,0,0,0.3)",
- }}
- >
- {/* Header */}
- <div
- style={{
- position: "relative",
- height: headerH,
- flexShrink: 0,
- borderBottom: "0.0625rem solid var(--c-border-subtle)",
- overflow: "hidden",
- }}
- >
- <div
- style={{
- position: "absolute",
- inset: 0,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <div
- style={{
- position: "absolute",
- left: "1rem",
- display: "flex",
- alignItems: "center",
- }}
- >
- {icon}
- </div>
-
- <Text
- component="span"
- fw={800}
- style={{ fontSize: "1.375rem", lineHeight: 1, margin: 0 }}
- >
- {count}
- </Text>
- <div
- style={{
- maxWidth: textExpanded ? "16rem" : "0",
- opacity: textExpanded ? 1 : 0,
- overflow: "hidden",
- whiteSpace: "nowrap",
- display: "flex",
- alignItems: "center",
- transition: `max-width 100ms ${EASING}, opacity 80ms ease`,
- }}
- >
- <Text
- component="span"
- c="dimmed"
- style={{
- fontSize: "1rem",
- paddingLeft: "0.5rem",
- lineHeight: 1,
- margin: 0,
- }}
- >
- {count === 1 ? labelSingular : labelPlural}
- </Text>
- </div>
-
- <ActionIcon
- variant="tertiary"
- size="lg"
- onClick={onClose}
- aria-label={t("close", "Close")}
- style={{
- position: "absolute",
- top: "0.25rem",
- right: "0.375rem",
- }}
- >
- <Icon name="x" size={"1.25rem"} />
- </ActionIcon>
- </div>
- </div>
-
- {showBody && (
- <div
- style={{
- flex: 1,
- display: "flex",
- flexDirection: "column",
- minHeight: 0,
- backgroundColor: "var(--c-bg-raised)",
- }}
- >
- {toolbar && (
- <div
- style={{
- flexShrink: 0,
- borderBottom: "0.0625rem solid var(--c-border-subtle)",
- }}
- >
- {toolbar}
- </div>
- )}
- {fillHeight ? (
- <div
- style={{
- flex: 1,
- minHeight: 0,
- padding: "0.75rem 1rem",
- display: "flex",
- flexDirection: "column",
- }}
- >
- {children}
- </div>
- ) : (
- <ScrollArea style={{ flex: 1, minHeight: 0 }}>
- <div
- style={{
- padding: "0.75rem 1rem",
- backgroundColor: "var(--c-bg-raised)",
- }}
- >
- {children}
- </div>
- </ScrollArea>
- )}
- {footer && (
- <div
- style={{
- padding: "0.75rem 1rem",
- borderTop: "0.0625rem solid var(--c-border-subtle)",
- flexShrink: 0,
- }}
- >
- {footer}
- </div>
- )}
- </div>
- )}
- </div>
- </div>,
- document.body,
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/DeleteFolderConfirmModal.tsx b/frontend/editor/src/proprietary/components/watchedFolders/DeleteFolderConfirmModal.tsx
deleted file mode 100644
index 8f485b9613..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/DeleteFolderConfirmModal.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { Modal, Text, Stack, Group } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { useTranslation } from "react-i18next";
-import { WatchedFolder } from "@app/types/watchedFolders";
-
-interface DeleteFolderConfirmModalProps {
- opened: boolean;
- folder: WatchedFolder | null;
- onConfirm: () => void;
- onCancel: () => void;
-}
-
-export function DeleteFolderConfirmModal({
- opened,
- folder,
- onConfirm,
- onCancel,
-}: DeleteFolderConfirmModalProps) {
- const { t } = useTranslation();
-
- if (!folder) return null;
-
- return (
- <Modal
- opened={opened}
- onClose={onCancel}
- title={t("watchedFolders.deleteConfirmTitle", "Delete folder?")}
- centered
- size="sm"
- >
- <Stack gap="md">
- {folder.isDefault && (
- <Text size="sm" c="var(--color-amber-dark)">
- {t(
- "watchedFolders.defaultFolderWarning",
- "This is a default folder and will be recreated on next reload.",
- )}
- </Text>
- )}
- <Text size="sm">
- {t(
- "watchedFolders.deleteConfirmBody",
- "This will remove the folder and its run history. Files already downloaded are not affected.",
- )}
- </Text>
- <Group gap="sm" justify="flex-end">
- <Button variant="secondary" size="sm" onClick={onCancel}>
- {t("cancel", "Cancel")}
- </Button>
- <Button
- variant="primary"
- accent="danger"
- size="sm"
- onClick={onConfirm}
- >
- {t("delete", "Delete")}
- </Button>
- </Group>
- </Stack>
- </Modal>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/FilePreviewModal.tsx b/frontend/editor/src/proprietary/components/watchedFolders/FilePreviewModal.tsx
deleted file mode 100644
index 23e0056910..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/FilePreviewModal.tsx
+++ /dev/null
@@ -1,101 +0,0 @@
-import { useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { Modal, Center, Text, Box, Loader } from "@mantine/core";
-import { FileId } from "@app/types/fileContext";
-import { fileStorage } from "@app/services/fileStorage";
-import { LocalEmbedPDF } from "@app/components/viewer/LocalEmbedPDF";
-import { PdfViewerToolbar } from "@app/components/viewer/PdfViewerToolbar";
-import { ViewerProvider } from "@app/contexts/ViewerContext";
-import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@app/styles/zIndex";
-
-interface FilePreviewModalProps {
- fileId?: FileId | null;
- /** Pass a File directly (e.g. outputs not stored in IDB). */
- file?: File | null;
- fileName: string;
- onClose: () => void;
-}
-
-export function FilePreviewModal({
- fileId,
- file: fileProp,
- fileName,
- onClose,
-}: FilePreviewModalProps) {
- const { t } = useTranslation();
- const [file, setFile] = useState<File | null>(null);
- const [loading, setLoading] = useState(false);
- const [error, setError] = useState(false);
-
- useEffect(() => {
- if (fileProp) {
- setFile(fileProp);
- setError(false);
- setLoading(false);
- return;
- }
- if (!fileId) {
- setFile(null);
- setError(false);
- setLoading(false);
- return;
- }
- setError(false);
- setLoading(true);
- fileStorage
- .getStirlingFile(fileId)
- .then((f) => {
- if (f) setFile(f);
- else setError(true);
- })
- .catch(() => setError(true))
- .finally(() => setLoading(false));
- }, [fileId, fileProp]);
-
- const opened = !!(fileId || fileProp);
-
- return (
- <Modal
- opened={opened}
- onClose={onClose}
- title={fileName}
- size="90%"
- zIndex={Z_INDEX_OVER_FILE_MANAGER_MODAL}
- styles={{
- body: {
- height: "82vh",
- padding: 0,
- overflow: "hidden",
- display: "flex",
- flexDirection: "column",
- },
- }}
- >
- {loading ? (
- <Center h="100%">
- <Loader size="sm" />
- </Center>
- ) : error ? (
- <Center h="100%">
- <Text c="dimmed">
- {t(
- "watchedFolders.workbench.previewLoadFailed",
- "Could not load file preview.",
- )}
- </Text>
- </Center>
- ) : !file ? (
- <Center h="100%">
- <Loader size="sm" />
- </Center>
- ) : (
- <ViewerProvider>
- <PdfViewerToolbar />
- <Box style={{ flex: 1, minHeight: 0 }}>
- <LocalEmbedPDF file={file} fileName={fileName} />
- </Box>
- </ViewerProvider>
- )}
- </Modal>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/IconPicker.tsx b/frontend/editor/src/proprietary/components/watchedFolders/IconPicker.tsx
deleted file mode 100644
index 55dc6f1939..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/IconPicker.tsx
+++ /dev/null
@@ -1,7 +0,0 @@
-/**
- * Icon picker for Watched Folder create/edit.
- * Re-exports IconSelector from the automate tools so smart folder components
- * don't need to reach into the automate tools directory.
- */
-
-export { default as IconPicker } from "@app/components/tools/automate/IconSelector";
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/StatCard.tsx b/frontend/editor/src/proprietary/components/watchedFolders/StatCard.tsx
deleted file mode 100644
index a8d7499878..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/StatCard.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-import React from "react";
-import { Text } from "@mantine/core";
-
-interface StatCardProps {
- icon: React.ReactNode;
- count: React.ReactNode;
- label: string;
- hoverColor?: string;
- onClick?: (rect: DOMRect) => void;
- disabled?: boolean;
- isActive?: boolean;
-}
-
-export function StatCard({
- icon,
- count,
- label,
- hoverColor,
- onClick,
- disabled,
- isActive,
-}: StatCardProps) {
- const isClickable = !!onClick && !disabled;
-
- return (
- <div
- onClick={(e) => {
- if (isClickable) onClick(e.currentTarget.getBoundingClientRect());
- }}
- style={{
- padding: "0.5rem 0.75rem 2rem",
- borderRadius: "var(--mantine-radius-sm)",
- border: `0.0625rem solid ${isActive && hoverColor ? hoverColor : "var(--c-border-subtle)"}`,
- backgroundColor:
- isActive && hoverColor ? `${hoverColor}10` : "var(--c-bg-raised)",
- textAlign: "center",
- cursor: isClickable ? "pointer" : "default",
- transition: "border-color 0.15s ease, background-color 0.15s ease",
- }}
- onMouseEnter={(e) => {
- if (isClickable && hoverColor && !isActive)
- e.currentTarget.style.borderColor = hoverColor;
- }}
- onMouseLeave={(e) => {
- if (isClickable && !isActive)
- e.currentTarget.style.borderColor = "var(--c-border-subtle)";
- }}
- >
- <div style={{ display: "block", marginBottom: "0.375rem" }}>{icon}</div>
- <Text
- fw={800}
- style={{
- fontSize: "1.375rem",
- lineHeight: 1,
- marginBottom: "0.25rem",
- }}
- >
- {count}
- </Text>
- <Text
- style={{
- fontSize: "0.5625rem",
- textTransform: "uppercase",
- letterSpacing: "0.06em",
- }}
- c="dimmed"
- >
- {label}
- </Text>
- </div>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderCard.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderCard.tsx
deleted file mode 100644
index 51f79f6f87..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderCard.tsx
+++ /dev/null
@@ -1,177 +0,0 @@
-import { useState } from "react";
-import { Box, Text, Group, Loader } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@app/ui/Icon";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { FolderRunStatus } from "@app/hooks/useFolderRunStatuses";
-import { iconMap } from "@app/components/tools/automate/iconMap";
-
-// The 12px status glyphs scale the app stroke to under 1px; this keeps them legible.
-const STATUS_DOT_STROKE = 2.5;
-
-interface WatchedFolderCardProps {
- folder: WatchedFolder;
- isActive: boolean;
- status: FolderRunStatus;
- onSelect: () => void;
- onEdit: (e: React.MouseEvent) => void;
- onDelete: (e: React.MouseEvent) => void;
- onFileDrop?: (fileIds: string[]) => void;
-}
-
-export function WatchedFolderCard({
- folder,
- isActive,
- status,
- onSelect,
- onEdit,
- onDelete,
- onFileDrop,
-}: WatchedFolderCardProps) {
- const { t } = useTranslation();
- const [isHovered, setIsHovered] = useState(false);
- const [isDragOver, setIsDragOver] = useState(false);
- const folderIcon = iconMap[folder.icon ?? ""] ?? iconMap.FolderIcon;
-
- const handleDragOver = (e: React.DragEvent) => {
- const types = e.dataTransfer.types;
- if (
- !types.includes("watchedFolderFileId") &&
- !types.includes("watchedFolderFileIds")
- )
- return;
- e.preventDefault();
- e.dataTransfer.dropEffect = "copy";
- setIsDragOver(true);
- };
-
- const handleDragLeave = () => setIsDragOver(false);
-
- const handleDrop = (e: React.DragEvent) => {
- e.preventDefault();
- setIsDragOver(false);
- const multiRaw = e.dataTransfer.getData("watchedFolderFileIds");
- if (multiRaw) {
- try {
- const ids: string[] = JSON.parse(multiRaw);
- if (ids.length > 0 && onFileDrop) onFileDrop(ids);
- return;
- } catch {
- /* fall through */
- }
- }
- const fileId = e.dataTransfer.getData("watchedFolderFileId");
- if (fileId && onFileDrop) onFileDrop([fileId]);
- };
-
- return (
- <Box
- className="tool-button-container"
- onMouseEnter={() => setIsHovered(true)}
- onMouseLeave={() => setIsHovered(false)}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- style={
- isDragOver
- ? {
- backgroundColor:
- "color-mix(in srgb, var(--c-primary) 10%, transparent)",
- borderRadius: "var(--mantine-radius-sm)",
- }
- : undefined
- }
- >
- <Button
- variant="tertiary"
- accent="neutral"
- size="sm"
- className="tool-button"
- fullWidth
- justify="start"
- style={
- isActive
- ? { backgroundColor: "var(--tool-button-selected-bg)" }
- : undefined
- }
- leftSection={
- <Box
- style={{
- width: 18,
- height: 18,
- borderRadius: "50%",
- backgroundColor: `${folder.accentColor}22`,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- flexShrink: 0,
- }}
- >
- <Icon
- name={folderIcon}
- size={11}
- style={{ color: folder.accentColor }}
- />
- </Box>
- }
- rightSection={
- isHovered ? (
- <Group gap={2} onClick={(e) => e.stopPropagation()}>
- <ActionIcon
- as="span"
- size="sm"
- variant="tertiary"
- onClick={onEdit}
- aria-label={t("watchedFolders.card.edit", "Edit folder")}
- >
- <Icon name="pencil" size={11} />
- </ActionIcon>
- {!folder.isDefault && (
- <ActionIcon
- as="span"
- size="sm"
- variant="tertiary"
- accent="danger"
- onClick={onDelete}
- aria-label={t("watchedFolders.card.delete", "Delete folder")}
- >
- <Icon name="trash" size={11} />
- </ActionIcon>
- )}
- </Group>
- ) : folder.isPaused ? (
- <Icon
- name="circle-pause"
- size={12}
- strokeWidth={STATUS_DOT_STROKE}
- style={{ color: "var(--mantine-color-dimmed)" }}
- />
- ) : status === "processing" ? (
- <Loader size={10} color={folder.accentColor} />
- ) : status === "done" ? (
- <Icon
- name="circle-check"
- size={12}
- strokeWidth={STATUS_DOT_STROKE}
- style={{ color: "var(--color-green-500)" }}
- />
- ) : null
- }
- onClick={onSelect}
- >
- <Text
- size="sm"
- style={{
- overflow: "hidden",
- textOverflow: "ellipsis",
- whiteSpace: "nowrap",
- }}
- >
- {folder.name}
- </Text>
- </Button>
- </Box>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderHomePage.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderHomePage.tsx
deleted file mode 100644
index 9be89f1c80..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderHomePage.tsx
+++ /dev/null
@@ -1,657 +0,0 @@
-import { useState, useCallback, useEffect } from "react";
-import { Box, Text, Stack, Group, Loader, ScrollArea } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@app/ui/Icon";
-import { useWatchedFolders } from "@app/hooks/useWatchedFolders";
-import { useFolderRunStatuses } from "@app/hooks/useFolderRunStatuses";
-import {
- useFolderAutomation,
- resolveInputFile,
-} from "@app/hooks/useFolderAutomation";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { type FileId } from "@app/types/file";
-import { AutomationConfig } from "@app/types/automation";
-import { automationStorage } from "@app/services/automationStorage";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-import { getWatchedFolderDraggedFileIds } from "@app/components/watchedFolders/watchedFolderDragState";
-import { fileStorage } from "@app/services/fileStorage";
-import { FolderThumbnail } from "@app/components/filesPage/FolderThumbnail";
-import { WatchedFolderManagementModal } from "@app/components/watchedFolders/WatchedFolderManagementModal";
-import { DeleteFolderConfirmModal } from "@app/components/watchedFolders/DeleteFolderConfirmModal";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { useNavigationActions } from "@app/contexts/NavigationContext";
-import {
- WATCHED_FOLDER_VIEW_ID,
- WATCHED_FOLDER_WORKBENCH_ID,
- timeAgo,
-} from "@app/components/watchedFolders/watchedFolderShared";
-import "@app/components/watchedFolders/WatchedFolders.css";
-
-interface FolderCardProps {
- folder: WatchedFolder;
- status: "idle" | "processing" | "done";
- isProcessing: boolean;
- onEdit: (folder: WatchedFolder) => void;
- onDelete: (folder: WatchedFolder) => void;
- onOpen: (folderId: string) => void;
- onDropFiles: (folder: WatchedFolder, files: File[]) => void;
- onDropSidebarFile: (folder: WatchedFolder, fileIds: string[]) => void;
- onTogglePause: (folder: WatchedFolder) => void;
-}
-
-function FolderCard({
- folder,
- status,
- isProcessing,
- onEdit,
- onDelete,
- onOpen,
- onDropFiles,
- onDropSidebarFile,
- onTogglePause,
-}: FolderCardProps) {
- const { t } = useTranslation();
- const [automation, setAutomation] = useState<AutomationConfig | null>(null);
- const [fileCount, setFileCount] = useState(0);
- const [lastAdded, setLastAdded] = useState<Date | null>(null);
- const [isDragOver, setIsDragOver] = useState(false);
- // True while a drag hovers this card AND every dragged file is already in it
- // (so the drop would be a no-op — see the guard in processFiles).
- const [dragAlreadyPresent, setDragAlreadyPresent] = useState(false);
- // Ids of files currently in this folder, used for the live dragover check.
- const [memberIds, setMemberIds] = useState<Set<string>>(new Set());
-
- useEffect(() => {
- automationStorage.getAutomation(folder.automationId).then(setAutomation);
-
- const loadData = () =>
- watchedFolderFileStorage.getFolderData(folder.id).then((record) => {
- if (!record) {
- setFileCount(0);
- setLastAdded(null);
- setMemberIds(new Set());
- return;
- }
- const files = Object.values(record.files);
- setFileCount(files.length);
- setMemberIds(new Set(Object.keys(record.files)));
- const dates = files
- .map((f) => new Date(f.addedAt))
- .filter((d) => !isNaN(d.getTime()));
- setLastAdded(
- dates.length
- ? new Date(Math.max(...dates.map((d) => d.getTime())))
- : null,
- );
- });
- loadData();
-
- const unsub = watchedFolderFileStorage.onFolderChange((changedId) => {
- if (changedId === folder.id) loadData();
- });
- return unsub;
- }, [folder.id, folder.automationId]);
-
- const isPaused = folder.isPaused ?? false;
- const isActive = !isPaused && (isProcessing || status === "processing");
- const isDone = !isPaused && status === "done" && !isActive;
-
- const statusDotColor = isPaused
- ? "var(--mantine-color-dimmed)"
- : isActive
- ? "var(--mantine-color-blue-filled)"
- : isDone
- ? "var(--color-green-500)"
- : "var(--c-text-subtle)";
- const statusDotPulse = isActive;
-
- const statusLabel = isPaused
- ? t("watchedFolders.status.paused", "Paused")
- : isActive
- ? t("watchedFolders.status.processing", "Processing")
- : isDone
- ? t("watchedFolders.status.done", "Done")
- : t("watchedFolders.status.active", "Active");
-
- const handleDragOver = (e: React.DragEvent) => {
- e.preventDefault();
- setIsDragOver(true);
- // Live feedback: are all the files being dragged already in this folder?
- const dragged = getWatchedFolderDraggedFileIds();
- setDragAlreadyPresent(
- dragged.length > 0 && dragged.every((id) => memberIds.has(id)),
- );
- };
- const handleDragLeave = (e: React.DragEvent) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node)) {
- setIsDragOver(false);
- setDragAlreadyPresent(false);
- }
- };
- const handleDrop = (e: React.DragEvent) => {
- e.preventDefault();
- setIsDragOver(false);
- setDragAlreadyPresent(false);
- const multiRaw = e.dataTransfer.getData("watchedFolderFileIds");
- if (multiRaw) {
- try {
- const ids: string[] = JSON.parse(multiRaw);
- if (ids.length > 0) {
- onDropSidebarFile(folder, ids);
- return;
- }
- } catch {
- /* fall through */
- }
- }
- const sidebarFileId = e.dataTransfer.getData("watchedFolderFileId");
- if (sidebarFileId) {
- onDropSidebarFile(folder, [sidebarFileId]);
- } else if (e.dataTransfer.files.length > 0) {
- onDropFiles(folder, Array.from(e.dataTransfer.files));
- }
- };
-
- // `automation` is loaded by the per-card effect above; the steps it holds
- // are no longer rendered on the card but the load is preserved.
- void automation;
-
- return (
- <div
- className={`wf-card${isDragOver ? " is-drop-target" : ""}${
- isDragOver && dragAlreadyPresent ? " is-already-member" : ""
- }`}
- role="listitem"
- tabIndex={0}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- onClick={() => onOpen(folder.id)}
- onKeyDown={(e) => {
- if (e.key === "Enter") onOpen(folder.id);
- }}
- >
- {isDragOver && dragAlreadyPresent && (
- <div className="wf-card-drag-message" aria-hidden="true">
- {t("watchedFolders.alreadyInFolder", "Already in this folder")}
- </div>
- )}
- <div
- className="wf-card-thumb"
- style={{
- background: `linear-gradient(135deg, color-mix(in srgb, ${folder.accentColor} 18%, var(--c-surface)), color-mix(in srgb, ${folder.accentColor} 6%, var(--c-surface)))`,
- }}
- >
- <FolderThumbnail
- color={folder.accentColor}
- fileCount={fileCount}
- size="thumb"
- />
- </div>
-
- <div className="wf-card-body">
- <div className="wf-card-name" title={folder.name}>
- {folder.name}
- </div>
- <div className="wf-card-meta">
- <span>
- {fileCount}{" "}
- {fileCount === 1
- ? t("watchedFolders.home.file", "file")
- : t("watchedFolders.home.files", "files")}
- </span>
- {lastAdded && (
- <>
- <span>·</span>
- <span>{timeAgo(lastAdded, t)}</span>
- </>
- )}
- <span style={{ flex: 1 }} />
- <span
- className={`wf-card-status-dot${statusDotPulse ? " is-pulsing" : ""}`}
- style={{ backgroundColor: statusDotColor }}
- />
- <span style={{ fontSize: "0.7rem" }}>{statusLabel}</span>
- </div>
- </div>
-
- <div className="wf-card-actions" onClick={(e) => e.stopPropagation()}>
- <ActionIcon
- size="md"
- variant="tertiary"
- onClick={() => onTogglePause(folder)}
- aria-label={
- isPaused
- ? t("watchedFolders.home.resume", "Resume")
- : t("watchedFolders.home.pause", "Pause")
- }
- title={
- isPaused
- ? t("watchedFolders.home.resume", "Resume")
- : t("watchedFolders.home.pause", "Pause")
- }
- >
- {isPaused ? (
- <Icon name="circle-play" size={"1.125rem"} />
- ) : (
- <Icon name="circle-pause" size={"1.125rem"} />
- )}
- </ActionIcon>
- <ActionIcon
- size="md"
- variant="tertiary"
- onClick={() => onEdit(folder)}
- aria-label={t("watchedFolders.home.editFolder", "Edit folder")}
- >
- <Icon name="pencil" size={"1.125rem"} />
- </ActionIcon>
- <ActionIcon
- size="md"
- variant="tertiary"
- accent="danger"
- onClick={() => onDelete(folder)}
- aria-label={t("watchedFolders.home.deleteFolder", "Delete folder")}
- >
- <Icon name="trash" size={"1.125rem"} />
- </ActionIcon>
- </div>
- </div>
- );
-}
-
-function HowItWorks() {
- const { t } = useTranslation();
-
- const [dismissed, setDismissed] = useState(
- () => sessionStorage.getItem("wf_howItWorks_dismissed") === "1",
- );
-
- if (dismissed) return null;
-
- const steps = [
- {
- n: "1",
- title: t("watchedFolders.howItWorks.step1Title", "Drop files"),
- desc: t(
- "watchedFolders.howItWorks.step1Desc",
- "Drag PDFs onto any Watched Folder card — or send them from your file list",
- ),
- },
- {
- n: "2",
- title: t("watchedFolders.howItWorks.step2Title", "Pipeline runs"),
- desc: t(
- "watchedFolders.howItWorks.step2Desc",
- "Your configured tools process each file automatically",
- ),
- },
- {
- n: "3",
- title: t("watchedFolders.howItWorks.step3Title", "Output ready"),
- desc: t(
- "watchedFolders.howItWorks.step3Desc",
- "Download processed files from inside the folder",
- ),
- },
- ];
-
- return (
- <Box
- mt="lg"
- style={{
- padding: "1rem 1.25rem",
- borderRadius: "var(--mantine-radius-md)",
- border: "0.0625rem solid var(--c-border-subtle)",
- backgroundColor: "var(--c-bg-raised)",
- }}
- >
- <Group gap="xs" mb="sm" justify="space-between">
- <Group gap="xs">
- <Icon
- name="info"
- size={"1rem"}
- style={{ color: "var(--c-accent-text)" }}
- />
- <Text fw={600} size="xs">
- {t("watchedFolders.howItWorks.title", "How Watched Folders work")}
- </Text>
- </Group>
- <ActionIcon
- size="sm"
- variant="tertiary"
- onClick={() => {
- sessionStorage.setItem("wf_howItWorks_dismissed", "1");
- setDismissed(true);
- }}
- aria-label={t("watchedFolders.actions.dismiss", "Dismiss")}
- >
- <Icon
- name="x"
- size={"0.75rem"}
- style={{ color: "var(--mantine-color-text)" }}
- />
- </ActionIcon>
- </Group>
- <Group gap="xl" wrap="nowrap" align="flex-start">
- {steps.map((step) => (
- <Group
- key={step.n}
- gap="sm"
- wrap="nowrap"
- align="flex-start"
- style={{ flex: 1 }}
- >
- <Box
- style={{
- width: "1.375rem",
- height: "1.375rem",
- borderRadius: "50%",
- backgroundColor: "var(--mantine-color-blue-light)",
- color: "var(--c-accent-text)",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- fontSize: "0.6875rem",
- fontWeight: 700,
- flexShrink: 0,
- }}
- >
- {step.n}
- </Box>
- <Stack gap={2}>
- <Text size="xs" fw={600}>
- {step.title}
- </Text>
- <Text size="xs" c="dimmed" style={{ lineHeight: 1.5 }}>
- {step.desc}
- </Text>
- </Stack>
- </Group>
- ))}
- </Group>
- </Box>
- );
-}
-
-function EmptyState({ onCreate }: { onCreate: () => void }) {
- const { t } = useTranslation();
-
- return (
- <div className="wf-empty">
- <span className="wf-empty-icon">
- <Icon name="folder-plus" size={"2.5rem"} />
- </span>
- <div className="wf-empty-title">
- {t("watchedFolders.home.emptyTitle", "Automate your PDF workflows")}
- </div>
- <div className="wf-empty-hint">
- {t(
- "watchedFolders.home.emptyDesc",
- "Set up a Watched Folder once. Drop PDFs in and they're automatically compressed, OCR'd, split, merged — whatever your pipeline does.",
- )}
- </div>
-
- <Button
- size="md"
- variant="primary"
- leftSection={<Icon name="plus" size={"1.125rem"} />}
- onClick={onCreate}
- style={{ marginTop: "var(--mantine-spacing-sm)" }}
- >
- {t("watchedFolders.home.create", "Create your first Watched Folder")}
- </Button>
-
- <HowItWorks />
- </div>
- );
-}
-
-export function WatchedFolderHomePage() {
- const { t } = useTranslation();
- const { folders, loading, deleteFolder, updateFolder, refreshFolders } =
- useWatchedFolders();
- const statuses = useFolderRunStatuses(folders);
- const { toolRegistry, setCustomWorkbenchViewData } = useToolWorkflow();
- const { actions } = useNavigationActions();
- const { processBatch } = useFolderAutomation(toolRegistry);
-
- const [createModalOpen, setCreateModalOpen] = useState(false);
- const [editFolder, setEditFolder] = useState<WatchedFolder | null>(null);
- const [editAutomation, setEditAutomation] = useState<AutomationConfig | null>(
- null,
- );
- const [processingFolderIds, setProcessingFolderIds] = useState<Set<string>>(
- new Set(),
- );
- const [deleteTarget, setDeleteTarget] = useState<WatchedFolder | null>(null);
-
- const navigateToFolder = useCallback(
- (folderId: string) => {
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId });
- actions.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- },
- [setCustomWorkbenchViewData, actions],
- );
-
- const handleEdit = useCallback(async (folder: WatchedFolder) => {
- setEditFolder(folder);
- const automation = await automationStorage.getAutomation(
- folder.automationId,
- );
- setEditAutomation(automation);
- setCreateModalOpen(true);
- }, []);
-
- const handleModalClose = () => {
- setCreateModalOpen(false);
- setEditFolder(null);
- setEditAutomation(null);
- };
-
- const processFiles = useCallback(
- async (folder: WatchedFolder, files: File[]) => {
- const pdfs = files.filter((f) => f.name.toLowerCase().endsWith(".pdf"));
- if (pdfs.length === 0) return;
-
- // Load existing folder data once so we can skip files already in the folder.
- const existingData = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- // Register files sequentially — addFileToFolder/updateFileMetadata are read-modify-write
- // without IDB transactions, so concurrent calls on the same folder lose updates.
- const items: Array<{
- file: File;
- inputFileId: string;
- ownedByFolder: boolean;
- }> = [];
- for (const file of pdfs) {
- const { inputFileId, ownedByFolder } = await resolveInputFile(file);
- // Guard against multiple adds: if this file is already in the folder,
- // skip it entirely rather than resetting its status and reprocessing.
- // (Dropping the same sidebar file onto a card again is a no-op.)
- if (existingData?.files[inputFileId]) {
- continue;
- }
- await watchedFolderFileStorage.addFileToFolder(folder.id, inputFileId, {
- status: "pending",
- name: file.name,
- ownedByFolder: ownedByFolder || undefined,
- });
- items.push({ file, inputFileId, ownedByFolder });
- }
-
- // Nothing new to process (every dropped file was already in the folder).
- if (items.length === 0) return;
-
- if (folder.isPaused) return;
-
- setProcessingFolderIds((prev) => new Set([...prev, folder.id]));
- try {
- await processBatch(folder, items);
- } finally {
- setProcessingFolderIds((prev) => {
- const next = new Set(prev);
- next.delete(folder.id);
- return next;
- });
- }
- },
- [processBatch],
- );
-
- const handleTogglePause = useCallback(
- async (folder: WatchedFolder) => {
- const resuming = folder.isPaused;
- const updatedFolder = { ...folder, isPaused: !folder.isPaused };
- await updateFolder(updatedFolder);
- refreshFolders();
-
- if (resuming) {
- const record = await watchedFolderFileStorage.getFolderData(folder.id);
- if (record) {
- const pendingEntries = Object.entries(record.files).filter(
- ([, meta]) => meta.status === "pending",
- );
- if (pendingEntries.length > 0) {
- const items: Array<{
- file: File;
- inputFileId: string;
- ownedByFolder: boolean;
- }> = [];
- for (const [id, meta] of pendingEntries) {
- const stirlingFile = await fileStorage.getStirlingFile(
- id as FileId,
- );
- if (stirlingFile) {
- items.push({
- file: stirlingFile,
- inputFileId: id,
- ownedByFolder: meta.ownedByFolder ?? false,
- });
- }
- }
- if (items.length > 0) processBatch(updatedFolder, items);
- }
- }
- }
- },
- [updateFolder, refreshFolders, processBatch],
- );
-
- const handleDropSidebarFile = useCallback(
- async (folder: WatchedFolder, fileIds: string[]) => {
- const results = await Promise.all(
- fileIds.map((id) => fileStorage.getStirlingFile(id as FileId)),
- );
- const stirlingFiles = results.filter(Boolean) as File[];
- if (stirlingFiles.length > 0) processFiles(folder, stirlingFiles);
- },
- [processFiles],
- );
-
- const handleDeleteConfirm = async () => {
- if (!deleteTarget) return;
- await deleteFolder(deleteTarget.id);
- setDeleteTarget(null);
- };
-
- return (
- <Box
- style={{
- display: "flex",
- flexDirection: "column",
- height: "100%",
- overflow: "hidden",
- }}
- >
- <ScrollArea style={{ flex: 1 }}>
- <Box p="xl">
- {loading ? (
- <Box
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- padding: "4rem",
- }}
- >
- <Loader size="md" />
- </Box>
- ) : folders.length === 0 ? (
- <EmptyState onCreate={() => setCreateModalOpen(true)} />
- ) : (
- <Stack gap="md">
- <HowItWorks />
-
- <div className="wf-grid" role="list">
- {folders.map((folder) => {
- const status = statuses[folder.id] ?? "idle";
- const isProcessing =
- processingFolderIds.has(folder.id) ||
- status === "processing";
- return (
- <FolderCard
- key={folder.id}
- folder={folder}
- status={status}
- isProcessing={isProcessing}
- onEdit={handleEdit}
- onDelete={setDeleteTarget}
- onOpen={navigateToFolder}
- onDropFiles={processFiles}
- onDropSidebarFile={handleDropSidebarFile}
- onTogglePause={handleTogglePause}
- />
- );
- })}
-
- <div
- className="wf-new-tile"
- role="button"
- tabIndex={0}
- onClick={() => setCreateModalOpen(true)}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ")
- setCreateModalOpen(true);
- }}
- >
- <span className="wf-new-tile-icon">
- <Icon name="folder-plus" size={"1.5rem"} />
- </span>
- <Text size="sm" fw={600}>
- {t(
- "watchedFolders.home.addAnother",
- "Add another Watched Folder",
- )}
- </Text>
- <Text size="xs" c="dimmed">
- {t(
- "watchedFolders.home.addAnotherDesc",
- "Automatically process files with a new pipeline",
- )}
- </Text>
- </div>
- </div>
- </Stack>
- )}
- </Box>
- </ScrollArea>
-
- <WatchedFolderManagementModal
- opened={createModalOpen}
- editFolder={editFolder}
- existingAutomation={editAutomation}
- onClose={handleModalClose}
- onSaved={refreshFolders}
- />
- <DeleteFolderConfirmModal
- opened={!!deleteTarget}
- folder={deleteTarget}
- onConfirm={handleDeleteConfirm}
- onCancel={() => setDeleteTarget(null)}
- />
- </Box>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx
deleted file mode 100644
index d61f3478f9..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderManagementModal.tsx
+++ /dev/null
@@ -1,904 +0,0 @@
-import { useState, useCallback, useRef, useEffect } from "react";
-import {
- Stack,
- Group,
- TextInput,
- ColorInput,
- NumberInput,
- Text,
- Alert,
- Switch,
- Select,
- Box,
- Collapse,
- Tooltip,
- Modal,
-} from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { useTranslation } from "react-i18next";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { AutomationConfig, AutomationMode } from "@app/types/automation";
-import { IconPicker as IconSelector } from "@app/components/watchedFolders/IconPicker";
-import AutomationCreation from "@app/components/tools/automate/AutomationCreation";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-import { folderDirectoryHandleStorage } from "@app/services/folderDirectoryHandleStorage";
-import {
- canReadLocalFolder,
- canWriteLocalFolder,
- FS_WRITE_UNSUPPORTED_MSG,
-} from "@app/utils/fsAccessCapability";
-import { Icon } from "@app/ui/Icon";
-import {
- Z_INDEX_AUTOMATE_MODAL,
- Z_INDEX_AUTOMATE_DROPDOWN,
-} from "@app/styles/zIndex";
-
-const ACCENT_SWATCHES = [
- "#3b82f6",
- "#0ea5e9",
- "#14b8a6",
- "#22c55e",
- "#f97316",
- "#ef4444",
- "#9333ea",
- "#ec4899",
- "#6366f1",
- "#eab308",
- "#64748b",
- "#0f172a",
-];
-
-function SectionLabel({ children }: { children: string }) {
- return (
- <Text
- size="xs"
- fw={600}
- tt="uppercase"
- style={{
- letterSpacing: "0.06em",
- color: "var(--c-text-subtle)",
- marginBottom: "0.5rem",
- }}
- >
- {children}
- </Text>
- );
-}
-
-interface WatchedFolderManagementModalProps {
- opened: boolean;
- editFolder?: WatchedFolder | null;
- existingAutomation?: AutomationConfig | null;
- onClose: () => void;
- onSaved: () => void;
-}
-
-export function WatchedFolderManagementModal({
- opened,
- editFolder,
- existingAutomation,
- onClose,
- onSaved,
-}: WatchedFolderManagementModalProps) {
- const { t } = useTranslation();
- const { toolRegistry } = useToolWorkflow();
- const isEditMode = !!editFolder;
-
- const [name, setName] = useState(editFolder?.name ?? "");
- const [icon, setIcon] = useState(editFolder?.icon ?? "FolderIcon");
- const [accentColor, setAccentColor] = useState(
- editFolder?.accentColor ?? "#3b82f6",
- );
- const [maxRetries, setMaxRetries] = useState<number>(
- editFolder?.maxRetries ?? 3,
- );
- const [retryDelayMinutes, setRetryDelayMinutes] = useState<number>(
- editFolder?.retryDelayMinutes ?? 5,
- );
- const [outputMode, setOutputMode] = useState<"new_file" | "new_version">(
- editFolder?.outputMode ?? "new_file",
- );
- const [outputName, setOutputName] = useState(
- editFolder?.outputName ?? editFolder?.name ?? "",
- );
- const [outputNamePosition, setOutputNamePosition] = useState<
- "prefix" | "suffix" | "auto-number"
- >(editFolder?.outputNamePosition ?? "prefix");
- const [inputSource, setInputSource] = useState<
- NonNullable<WatchedFolder["inputSource"]>
- >(editFolder?.inputSource ?? "idb");
- const outputNameDirty = useRef(!!editFolder?.outputName);
- const [saving, setSaving] = useState(false);
- const [outputDirName, setOutputDirName] = useState<string | null>(
- editFolder?.hasOutputDirectory ? "(loading…)" : null,
- );
- const pendingDirHandle = useRef<FileSystemDirectoryHandle | null>(null);
- const [inputDirName, setInputDirName] = useState<string | null>(
- editFolder?.inputSource === "local-folder" ? "(loading…)" : null,
- );
- const pendingInputDirHandle = useRef<FileSystemDirectoryHandle | null>(null);
- const [nameError, setNameError] = useState("");
- const [automationError, setAutomationError] = useState("");
- const [saveError, setSaveError] = useState<string | null>(null);
- const [showAdvanced, setShowAdvanced] = useState(isEditMode);
-
- const automationSaveTrigger = useRef<(() => void) | null>(null);
-
- const resetState = useCallback(() => {
- setName(editFolder?.name ?? "");
- setIcon(editFolder?.icon ?? "FolderIcon");
- setAccentColor(editFolder?.accentColor ?? "#3b82f6");
- setMaxRetries(editFolder?.maxRetries ?? 3);
- setRetryDelayMinutes(editFolder?.retryDelayMinutes ?? 5);
- setOutputMode(editFolder?.outputMode ?? "new_file");
- setOutputName(editFolder?.outputName ?? editFolder?.name ?? "");
- setOutputNamePosition(
- (editFolder?.outputNamePosition as "prefix" | "suffix" | "auto-number") ??
- "prefix",
- );
- setInputSource(editFolder?.inputSource ?? "idb");
- setInputDirName(
- editFolder?.inputSource === "local-folder" ? "(loading…)" : null,
- );
- outputNameDirty.current = !!editFolder?.outputName;
- setShowAdvanced(!!editFolder);
- setNameError("");
- setAutomationError("");
- setSaveError(null);
- setSaving(false);
- }, [editFolder]);
-
- useEffect(() => {
- if (opened) {
- resetState();
- pendingDirHandle.current = null;
- pendingInputDirHandle.current = null;
- if (editFolder?.hasOutputDirectory && editFolder.id) {
- folderDirectoryHandleStorage
- .get(editFolder.id)
- .then((h) => setOutputDirName(h?.name ?? null));
- } else {
- setOutputDirName(null);
- }
- if (editFolder?.inputSource === "local-folder" && editFolder.id) {
- folderDirectoryHandleStorage
- .getInput(editFolder.id)
- .then((h) => setInputDirName(h?.name ?? null));
- } else {
- setInputDirName(null);
- }
- }
- }, [opened, resetState, editFolder]);
-
- const handleClose = () => {
- resetState();
- onClose();
- };
-
- const handleAutomationComplete = useCallback(
- async (automation: AutomationConfig) => {
- const trimmedName = name.trim();
-
- try {
- const retryFields = { maxRetries, retryDelayMinutes };
- const hasOutputDirectory = outputDirName !== null;
- const folderData = {
- name: trimmedName,
- description: "",
- icon,
- accentColor,
- automationId: automation.id,
- ...retryFields,
- outputMode:
- outputMode === "new_version" ? ("new_version" as const) : undefined,
- outputName: outputName.trim() || undefined,
- outputNamePosition:
- outputNamePosition !== "prefix" ? outputNamePosition : undefined,
- hasOutputDirectory,
- inputSource: inputSource !== "idb" ? inputSource : undefined,
- };
-
- if (isEditMode && editFolder) {
- const wasLocalFolder = editFolder.inputSource === "local-folder";
- await watchedFolderStorage.updateFolder({
- ...editFolder,
- ...folderData,
- });
- if (pendingDirHandle.current) {
- await folderDirectoryHandleStorage.set(
- editFolder.id,
- pendingDirHandle.current,
- );
- } else if (!hasOutputDirectory) {
- await folderDirectoryHandleStorage.remove(editFolder.id);
- }
- if (inputSource === "local-folder") {
- if (pendingInputDirHandle.current) {
- await folderDirectoryHandleStorage.setInput(
- editFolder.id,
- pendingInputDirHandle.current,
- );
- }
- } else if (wasLocalFolder) {
- await folderDirectoryHandleStorage.removeInput(editFolder.id);
- }
- } else {
- const newFolder = await watchedFolderStorage.createFolder(folderData);
- if (pendingDirHandle.current) {
- await folderDirectoryHandleStorage.set(
- newFolder.id,
- pendingDirHandle.current,
- );
- }
- if (inputSource === "local-folder" && pendingInputDirHandle.current) {
- await folderDirectoryHandleStorage.setInput(
- newFolder.id,
- pendingInputDirHandle.current,
- );
- }
- }
- resetState();
- onSaved();
- onClose();
- } catch (error) {
- console.error("Failed to save smart folder:", error);
- setSaveError(
- t(
- "watchedFolders.modal.saveFailed",
- "Failed to save folder. Please try again.",
- ),
- );
- } finally {
- setSaving(false);
- }
- },
- [
- name,
- icon,
- accentColor,
- outputMode,
- outputName,
- outputNamePosition,
- outputDirName,
- maxRetries,
- retryDelayMinutes,
- inputSource,
- isEditMode,
- editFolder,
- resetState,
- onSaved,
- onClose,
- t,
- ],
- );
-
- const handleSave = () => {
- const trimmedName = name.trim();
- if (!trimmedName) {
- setNameError(
- t("watchedFolders.modal.nameRequired", "Folder name is required"),
- );
- return;
- }
- if (trimmedName.length > 50) {
- setNameError(
- t(
- "watchedFolders.modal.nameTooLong",
- "Folder name must be 50 characters or less",
- ),
- );
- return;
- }
- setAutomationError("");
- setSaving(true);
- automationSaveTrigger.current?.();
- };
-
- const title = isEditMode
- ? t("watchedFolders.modal.editTitle", "Edit Watched Folder")
- : t("watchedFolders.modal.createTitle", "New Watched Folder");
-
- return (
- <Modal
- opened={opened}
- onClose={handleClose}
- title={title}
- size="min(90rem, 94vw)"
- centered
- zIndex={Z_INDEX_AUTOMATE_MODAL}
- styles={{
- content: {
- height: "min(90vh, 60rem)",
- display: "flex",
- flexDirection: "column",
- },
- body: {
- flex: 1,
- minHeight: 0,
- padding: 0,
- display: "flex",
- flexDirection: "column",
- },
- }}
- >
- {/* Body: two-column layout */}
- <div style={{ display: "flex", flex: 1, minHeight: 0 }}>
- {/* ── Left panel: folder config ── */}
- <div
- style={{
- width: "28rem",
- flexShrink: 0,
- borderRight: "0.0625rem solid var(--c-border-subtle)",
- display: "flex",
- flexDirection: "column",
- overflow: "hidden",
- }}
- >
- <div
- style={{ flex: 1, overflowY: "auto", padding: "1.25rem 1.5rem" }}
- >
- <Stack gap="lg">
- {/* ── Identity ── */}
- <div>
- <SectionLabel>
- {t("watchedFolders.modal.sectionFolder", "Folder")}
- </SectionLabel>
- <Stack gap="xs">
- <Group gap="xs" align="flex-end">
- <TextInput
- placeholder={t(
- "watchedFolders.modal.namePlaceholder",
- "My Watched Folder",
- )}
- value={name}
- onChange={(e) => {
- const val = e.currentTarget.value;
- setName(val);
- setNameError("");
- if (!outputNameDirty.current) setOutputName(val);
- }}
- error={nameError}
- withAsterisk
- maxLength={50}
- style={{ flex: 1 }}
- size="sm"
- />
- <IconSelector value={icon} onChange={setIcon} size="sm" />
- </Group>
-
- <ColorInput
- label={t("watchedFolders.modal.color", "Accent colour")}
- value={accentColor}
- onChange={setAccentColor}
- format="hex"
- swatches={ACCENT_SWATCHES}
- size="sm"
- popoverProps={{
- withinPortal: true,
- zIndex: Z_INDEX_AUTOMATE_DROPDOWN,
- }}
- />
- </Stack>
- </div>
-
- {/* ── Source & Output ── */}
- <div>
- <SectionLabel>
- {t(
- "watchedFolders.modal.sectionSourceOutput",
- "Source & Output",
- )}
- </SectionLabel>
- <Stack gap="sm">
- <Select
- label={t(
- "watchedFolders.modal.inputSource",
- "Input source",
- )}
- value={inputSource}
- onChange={(v) =>
- v &&
- setInputSource(
- v as NonNullable<WatchedFolder["inputSource"]>,
- )
- }
- data={[
- {
- value: "idb",
- label: t(
- "watchedFolders.modal.inputSourceBrowser",
- "Browser — drop files here",
- ),
- },
- {
- value: "local-folder",
- label: canReadLocalFolder
- ? t(
- "watchedFolders.modal.inputSourceLocal",
- "Local folder (auto-scan)",
- )
- : t(
- "watchedFolders.modal.inputSourceLocalUnsupported",
- "Local folder (auto-scan) — Chrome/Edge only",
- ),
- disabled: !canReadLocalFolder,
- },
- ]}
- size="sm"
- comboboxProps={{
- withinPortal: true,
- zIndex: Z_INDEX_AUTOMATE_DROPDOWN,
- }}
- />
-
- {/* Local-folder input directory picker */}
- {inputSource === "local-folder" && (
- <Box
- style={{
- marginLeft: "0.75rem",
- paddingLeft: "0.75rem",
- borderLeft: "2px solid var(--c-border-subtle)",
- }}
- >
- <Box
- style={{
- padding: "0.5rem 0.75rem",
- borderRadius: "var(--mantine-radius-sm)",
- border: `0.0625rem solid ${inputDirName ? "var(--mantine-color-green-filled)" : "var(--mantine-color-yellow-5)"}`,
- backgroundColor: inputDirName
- ? "var(--mantine-color-green-light)"
- : "var(--mantine-color-yellow-light)",
- }}
- >
- <Group gap="xs" align="center" wrap="nowrap">
- <Icon
- name="folder-bookmark"
- size={"1rem"}
- style={{
- color: inputDirName
- ? "var(--color-green-500)"
- : "var(--mantine-color-yellow-6)",
- flexShrink: 0,
- }}
- />
- <Stack gap={1} style={{ flex: 1, minWidth: 0 }}>
- <Text size="xs" fw={500}>
- {t(
- "watchedFolders.modal.inputFolder",
- "Input folder",
- )}
- </Text>
- <Text size="xs" c="dimmed" lineClamp={1}>
- {inputDirName ??
- t(
- "watchedFolders.modal.inputFolderNotChosen",
- "No folder chosen — required for auto-scan",
- )}
- </Text>
- </Stack>
- <Button
- size="sm"
- variant="tertiary"
- onClick={async () => {
- try {
- const handle =
- await window.showDirectoryPicker?.({
- mode: "read",
- });
- if (!handle) return;
- pendingInputDirHandle.current = handle;
- setInputDirName(handle.name);
- } catch {
- /* cancelled */
- }
- }}
- >
- {inputDirName
- ? t("watchedFolders.modal.changeFolder", "Change")
- : t(
- "watchedFolders.modal.chooseFolder",
- "Choose",
- )}
- </Button>
- {inputDirName && (
- <Button
- size="sm"
- variant="tertiary"
- accent="danger"
- onClick={() => {
- pendingInputDirHandle.current = null;
- setInputDirName(null);
- }}
- >
- {t("watchedFolders.modal.clearFolder", "Clear")}
- </Button>
- )}
- </Group>
- </Box>
- <Text size="xs" c="dimmed" mt={6}>
- {t(
- "watchedFolders.modal.autoScanHelp",
- "New PDF files in this folder are processed automatically every 10 seconds.",
- )}
- </Text>
- </Box>
- )}
-
- {/* Local output folder */}
- <Box
- style={{
- padding: "0.5rem 0.75rem",
- borderRadius: "var(--mantine-radius-sm)",
- border: `0.0625rem solid ${outputDirName ? "var(--mantine-color-green-filled)" : "var(--c-border-subtle)"}`,
- backgroundColor: outputDirName
- ? "var(--mantine-color-green-light)"
- : "transparent",
- }}
- >
- <Group gap="xs" align="center" wrap="nowrap">
- <Icon
- name="folder-bookmark"
- size={"1rem"}
- style={{
- color: outputDirName
- ? "var(--color-green-500)"
- : "var(--mantine-color-dimmed)",
- flexShrink: 0,
- }}
- />
- <Stack gap={1} style={{ flex: 1, minWidth: 0 }}>
- <Text size="xs" fw={500}>
- {t(
- "watchedFolders.modal.localOutputFolder",
- "Local output folder",
- )}
- </Text>
- <Text size="xs" c="dimmed" lineClamp={1}>
- {!canWriteLocalFolder
- ? t(
- "watchedFolders.modal.outputFolderUnsupported",
- "Not supported in this browser",
- )
- : (outputDirName ??
- t(
- "watchedFolders.modal.outputFolderNotSet",
- "Not set — outputs stay in app",
- ))}
- </Text>
- </Stack>
- <Tooltip
- label={FS_WRITE_UNSUPPORTED_MSG}
- disabled={canWriteLocalFolder}
- withinPortal
- zIndex={Z_INDEX_AUTOMATE_DROPDOWN}
- >
- <Button
- size="sm"
- variant="tertiary"
- disabled={!canWriteLocalFolder}
- onClick={async () => {
- try {
- const handle = await window.showDirectoryPicker?.(
- {
- mode: "readwrite",
- },
- );
- if (!handle) return;
- pendingDirHandle.current = handle;
- setOutputDirName(handle.name);
- } catch {
- /* cancelled */
- }
- }}
- >
- {outputDirName
- ? t("watchedFolders.modal.changeFolder", "Change")
- : t("watchedFolders.modal.chooseFolder", "Choose")}
- </Button>
- </Tooltip>
- {outputDirName && (
- <Button
- size="sm"
- variant="tertiary"
- accent="danger"
- onClick={() => {
- pendingDirHandle.current = null;
- setOutputDirName(null);
- }}
- >
- {t("watchedFolders.modal.clearFolder", "Clear")}
- </Button>
- )}
- </Group>
- </Box>
- </Stack>
- </div>
-
- {/* ── Advanced (collapsible) ── */}
- <div>
- <Button
- variant="tertiary"
- onClick={() => setShowAdvanced((v) => !v)}
- style={{
- display: "flex",
- alignItems: "center",
- gap: "0.35rem",
- padding: "0.25rem 0",
- width: "100%",
- color: "var(--c-text-subtle)",
- fontSize: "0.7rem",
- fontWeight: 600,
- letterSpacing: "0.06em",
- textTransform: "uppercase",
- }}
- >
- <Icon
- name="chevron-right"
- size={"1rem"}
- style={{
- transform: showAdvanced ? "rotate(90deg)" : "none",
- transition: "transform 160ms ease",
- }}
- />
- {t("watchedFolders.modal.advanced", "Advanced")}
- </Button>
-
- <Collapse in={showAdvanced} transitionDuration={180}>
- <Stack gap="sm" mt="sm">
- {/* Replace original */}
- <Switch
- label={t(
- "watchedFolders.modal.replaceOriginal",
- "Replace original file",
- )}
- description={
- outputMode === "new_version"
- ? t(
- "watchedFolders.modal.outputModeVersionDesc",
- "Output replaces input as a new version",
- )
- : t(
- "watchedFolders.modal.outputModeNewDesc",
- "Output saved as a separate new file",
- )
- }
- checked={outputMode === "new_version"}
- onChange={(e) =>
- setOutputMode(
- e.currentTarget.checked ? "new_version" : "new_file",
- )
- }
- size="sm"
- />
-
- {/* Filename prefix / suffix */}
- <Box
- style={{
- opacity: outputMode === "new_version" ? 0.4 : 1,
- pointerEvents:
- outputMode === "new_version" ? "none" : "auto",
- }}
- >
- <Group gap="xs" align="flex-end">
- {outputNamePosition === "auto-number" ? (
- <Box style={{ flex: 1 }}>
- <Text size="xs" fw={500} mb={4}>
- {t(
- "watchedFolders.modal.autoNumber",
- "Auto-number",
- )}
- </Text>
- <Text size="xs" c="dimmed">
- {t(
- "watchedFolders.modal.autoNumberExample",
- "e.g. document.pdf → document (1).pdf",
- )}
- </Text>
- </Box>
- ) : (
- <TextInput
- label={
- outputNamePosition === "suffix"
- ? t(
- "watchedFolders.modal.outputNameSuffix",
- "Filename suffix",
- )
- : t(
- "watchedFolders.modal.outputNamePrefix",
- "Filename prefix",
- )
- }
- value={outputName}
- onChange={(e) => {
- outputNameDirty.current = true;
- setOutputName(e.currentTarget.value);
- }}
- maxLength={100}
- size="sm"
- style={{ flex: 1 }}
- />
- )}
- <Select
- size="xs"
- value={outputNamePosition}
- onChange={(v) =>
- v &&
- setOutputNamePosition(
- v as "prefix" | "suffix" | "auto-number",
- )
- }
- data={[
- {
- value: "prefix",
- label: t(
- "watchedFolders.modal.positionPrefix",
- "Prefix",
- ),
- },
- {
- value: "suffix",
- label: t(
- "watchedFolders.modal.positionSuffix",
- "Suffix",
- ),
- },
- {
- value: "auto-number",
- label: t(
- "watchedFolders.modal.autoNumber",
- "Auto-number",
- ),
- },
- ]}
- style={{ width: "8rem", flexShrink: 0 }}
- mb={4}
- comboboxProps={{
- withinPortal: true,
- zIndex: Z_INDEX_AUTOMATE_DROPDOWN,
- }}
- />
- </Group>
- </Box>
-
- {/* Retry settings */}
- <Group gap="sm" grow>
- <NumberInput
- label={t(
- "watchedFolders.modal.maxRetries",
- "Max auto retries",
- )}
- value={maxRetries}
- onChange={(v) =>
- setMaxRetries(
- typeof v === "number"
- ? Math.max(0, Math.min(10, v))
- : 0,
- )
- }
- min={0}
- max={10}
- size="sm"
- />
- <NumberInput
- label={t(
- "watchedFolders.modal.retryDelay",
- "Retry interval (min)",
- )}
- value={retryDelayMinutes}
- onChange={(v) =>
- setRetryDelayMinutes(
- typeof v === "number"
- ? Math.max(1, Math.min(60, v))
- : 5,
- )
- }
- min={1}
- max={60}
- size="sm"
- disabled={maxRetries === 0}
- />
- </Group>
- </Stack>
- </Collapse>
- </div>
- </Stack>
- </div>
-
- {/* Footer actions */}
- <div
- style={{
- padding: "1rem 1.5rem",
- borderTop: "0.0625rem solid var(--c-border-subtle)",
- flexShrink: 0,
- }}
- >
- {saveError && (
- <Alert
- color="red"
- variant="light"
- onClose={() => setSaveError(null)}
- withCloseButton
- mb="sm"
- >
- {saveError}
- </Alert>
- )}
- <Group justify="flex-end" gap="sm">
- <Button variant="tertiary" size="sm" onClick={handleClose}>
- {t("cancel", "Cancel")}
- </Button>
- <Button
- variant="primary"
- size="sm"
- onClick={handleSave}
- loading={saving}
- disabled={!name.trim()}
- >
- {isEditMode
- ? t("watchedFolders.modal.saveChanges", "Save changes")
- : t("watchedFolders.modal.createFolder", "New folder")}
- </Button>
- </Group>
- </div>
- </div>
-
- {/* ── Right panel: automation steps ── */}
- <div
- style={{
- flex: 1,
- minWidth: 0,
- display: "flex",
- flexDirection: "column",
- overflow: "hidden",
- }}
- >
- <div style={{ padding: "1rem 1.5rem 0.5rem", flexShrink: 0 }}>
- <SectionLabel>
- {t("watchedFolders.modal.sectionSteps", "Steps")}
- </SectionLabel>
- {automationError && (
- <Text size="xs" c="var(--color-red-dark)" mt={4}>
- {automationError}
- </Text>
- )}
- </div>
- <div
- style={{
- flex: 1,
- minHeight: 0,
- overflowY: "auto",
- padding: "0 1.5rem 1.5rem",
- }}
- >
- <AutomationCreation
- mode={isEditMode ? AutomationMode.EDIT : AutomationMode.CREATE}
- existingAutomation={existingAutomation ?? undefined}
- onBack={handleClose}
- onComplete={handleAutomationComplete}
- onSaveFailed={() => {
- setSaving(false);
- setAutomationError(
- t(
- "watchedFolders.modal.automationRequired",
- "Add at least one configured step before saving.",
- ),
- );
- }}
- toolRegistry={toolRegistry}
- hideMetadata
- nameOverride={
- name.trim() ||
- t(
- "watchedFolders.modal.automationNameFallback",
- "Watched Folder Automation",
- )
- }
- saveTriggerRef={automationSaveTrigger}
- />
- </div>
- </div>
- </div>
- </Modal>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderSection.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderSection.tsx
deleted file mode 100644
index a4824cc151..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderSection.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import { useState } from "react";
-import { Box, Text, Stack } from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@app/ui/Icon";
-import { useWatchedFolders } from "@app/hooks/useWatchedFolders";
-import { useFolderRunStatuses } from "@app/hooks/useFolderRunStatuses";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { useNavigationActions } from "@app/contexts/NavigationContext";
-import { WatchedFolderManagementModal } from "@app/components/watchedFolders/WatchedFolderManagementModal";
-import { DeleteFolderConfirmModal } from "@app/components/watchedFolders/DeleteFolderConfirmModal";
-import { WatchedFolderCard } from "@app/components/watchedFolders/WatchedFolderCard";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { AutomationConfig } from "@app/types/automation";
-import { automationStorage } from "@app/services/automationStorage";
-import {
- WATCHED_FOLDER_VIEW_ID,
- WATCHED_FOLDER_WORKBENCH_ID,
-} from "@app/components/watchedFolders/watchedFolderShared";
-
-export function WatchedFolderSection() {
- const { t } = useTranslation();
- const [createModalOpen, setCreateModalOpen] = useState(false);
- const [editFolder, setEditFolder] = useState<WatchedFolder | null>(null);
- const [editAutomation, setEditAutomation] = useState<AutomationConfig | null>(
- null,
- );
- const [deleteTarget, setDeleteTarget] = useState<WatchedFolder | null>(null);
- const [activeFolderId, setActiveFolderId] = useState<string | null>(null);
-
- const { folders, loading, deleteFolder, refreshFolders } =
- useWatchedFolders();
- const statuses = useFolderRunStatuses(folders);
-
- const { setCustomWorkbenchViewData } = useToolWorkflow();
- const { actions } = useNavigationActions();
-
- const handleFolderClick = (folderId: string) => {
- setActiveFolderId(folderId);
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId });
- actions.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- };
-
- const handleEditFolder = async (
- e: React.MouseEvent,
- folder: WatchedFolder,
- ) => {
- e.stopPropagation();
- setEditFolder(folder);
- const automation = await automationStorage.getAutomation(
- folder.automationId,
- );
- setEditAutomation(automation);
- setCreateModalOpen(true);
- };
-
- const handleDeleteClick = (e: React.MouseEvent, folder: WatchedFolder) => {
- e.stopPropagation();
- setDeleteTarget(folder);
- };
-
- const handleDeleteConfirm = async () => {
- if (!deleteTarget) return;
- if (activeFolderId === deleteTarget.id) {
- setActiveFolderId(null);
- actions.setWorkbench("fileEditor");
- }
- await deleteFolder(deleteTarget.id);
- setDeleteTarget(null);
- };
-
- const handleModalClose = () => {
- setCreateModalOpen(false);
- setEditFolder(null);
- setEditAutomation(null);
- };
-
- return (
- <Box
- style={{
- borderTop: "1px solid var(--c-border-subtle)",
- backgroundColor: "var(--c-bg-raised)",
- display: "flex",
- flexDirection: "column",
- height: "100%",
- overflow: "hidden",
- }}
- >
- <Box px="sm" pt="xs" pb="2px" style={{ flexShrink: 0 }}>
- <Box className="tool-subcategory-row">
- <Text
- className="tool-subcategory-row-title"
- style={{ cursor: "pointer" }}
- onClick={() => {
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, {
- folderId: null,
- });
- actions.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- }}
- >
- {t("watchedFolders.title", "Watched Folders")}
- </Text>
- <Box className="tool-subcategory-row-rule" />
- </Box>
- </Box>
-
- <Box className="tool-picker-scrollable" style={{ flex: 1, minHeight: 0 }}>
- <Stack gap={0} pb="xs">
- {!loading && folders.length === 0 && (
- <Text size="xs" c="dimmed" ta="center" py="sm" px="sm">
- {t("watchedFolders.noFolders", "No watch folders yet")}
- </Text>
- )}
-
- {folders.map((folder) => (
- <WatchedFolderCard
- key={folder.id}
- folder={folder}
- isActive={activeFolderId === folder.id}
- status={statuses[folder.id] ?? "idle"}
- onSelect={() => handleFolderClick(folder.id)}
- onEdit={(e) => handleEditFolder(e, folder)}
- onDelete={(e) => handleDeleteClick(e, folder)}
- onFileDrop={(fileIds) => {
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, {
- folderId: folder.id,
- pendingFileIds: fileIds,
- });
- actions.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- setActiveFolderId(folder.id);
- }}
- />
- ))}
-
- <Button
- variant="tertiary"
- accent="neutral"
- size="sm"
- className="tool-button"
- fullWidth
- justify="start"
- leftSection={
- <Icon
- name="plus"
- size={14}
- style={{ color: "var(--mantine-color-gray-5)" }}
- />
- }
- onClick={() => setCreateModalOpen(true)}
- >
- <Text size="sm" c="dimmed">
- {t("watchedFolders.newFolder", "New folder")}
- </Text>
- </Button>
- </Stack>
- </Box>
-
- <WatchedFolderManagementModal
- opened={createModalOpen}
- editFolder={editFolder}
- existingAutomation={editAutomation}
- onClose={handleModalClose}
- onSaved={refreshFolders}
- />
- <DeleteFolderConfirmModal
- opened={!!deleteTarget}
- folder={deleteTarget}
- onConfirm={handleDeleteConfirm}
- onCancel={() => setDeleteTarget(null)}
- />
- </Box>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderWorkbenchView.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderWorkbenchView.tsx
deleted file mode 100644
index e1674dd338..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolderWorkbenchView.tsx
+++ /dev/null
@@ -1,2369 +0,0 @@
-import React, {
- useState,
- useCallback,
- useRef,
- useEffect,
- useMemo,
-} from "react";
-import {
- Box,
- Text,
- Stack,
- Group,
- Modal,
- ScrollArea,
- Loader,
- TextInput,
- Select,
-} from "@mantine/core";
-import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Z_INDEX_OVER_FILE_MANAGER_MODAL } from "@app/styles/zIndex";
-
-import { useCardModalAnimation } from "@app/hooks/useCardModalAnimation";
-import { CardExpansionModal } from "@app/components/watchedFolders/CardExpansionModal";
-import { StatCard } from "@app/components/watchedFolders/StatCard";
-import { useTranslation } from "react-i18next";
-import { Icon } from "@app/ui/Icon";
-import JSZip from "jszip";
-import { useWatchedFolders } from "@app/hooks/useWatchedFolders";
-import { useFolderData } from "@app/hooks/useFolderData";
-import type { TFunction } from "i18next";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import {
- WATCHED_FOLDER_VIEW_ID,
- WATCHED_FOLDER_WORKBENCH_ID,
- timeAgo,
- humaniseOp,
-} from "@app/components/watchedFolders/watchedFolderShared";
-import { automationStorage } from "@app/services/automationStorage";
-import {
- useFolderAutomation,
- resolveInputFile,
-} from "@app/hooks/useFolderAutomation";
-import { useLocalFolderPoller } from "@app/hooks/useLocalFolderPoller";
-import { AutomationConfig } from "@app/types/automation";
-import type { WatchedFolderViewData } from "@app/types/watchedFolders";
-import { iconMap } from "@app/components/tools/automate/iconMap";
-import { fileStorage } from "@app/services/fileStorage";
-import { FileId, StirlingFile } from "@app/types/fileContext";
-import { WatchedFolderHomePage } from "@app/components/watchedFolders/WatchedFolderHomePage";
-import { useNavigationActions } from "@app/contexts/NavigationContext";
-import { FilePreviewModal } from "@app/components/watchedFolders/FilePreviewModal";
-import { folderDirectoryHandleStorage } from "@app/services/folderDirectoryHandleStorage";
-
-const SORT_OPTIONS = [
- {
- value: "newest",
- labelKey: "watchedFolders.workbench.sortNewest",
- labelDefault: "Newest",
- },
- {
- value: "oldest",
- labelKey: "watchedFolders.workbench.sortOldest",
- labelDefault: "Oldest",
- },
- {
- value: "name-asc",
- labelKey: "watchedFolders.workbench.sortNameAsc",
- labelDefault: "A → Z",
- },
- {
- value: "name-desc",
- labelKey: "watchedFolders.workbench.sortNameDesc",
- labelDefault: "Z → A",
- },
-];
-
-const ACTIVITY_STATUS_OPTIONS = [
- {
- value: "all",
- labelKey: "watchedFolders.workbench.filterAll",
- labelDefault: "All",
- },
- {
- value: "processed",
- labelKey: "watchedFolders.status.done",
- labelDefault: "Done",
- },
- {
- value: "processing",
- labelKey: "watchedFolders.status.active",
- labelDefault: "Active",
- },
- {
- value: "error",
- labelKey: "watchedFolders.workbench.failed",
- labelDefault: "Failed",
- },
- {
- value: "pending",
- labelKey: "watchedFolders.workbench.filterPending",
- labelDefault: "Pending",
- },
-];
-
-function FilterSortBar({
- search,
- onSearchChange,
- sort,
- onSortChange,
- extra,
-}: {
- search: string;
- onSearchChange: (v: string) => void;
- sort: string;
- onSortChange: (v: string) => void;
- extra?: React.ReactNode;
-}) {
- const { t } = useTranslation();
- return (
- <Box
- style={{
- display: "flex",
- gap: "0.5rem",
- alignItems: "center",
- padding: "0.5rem 0.75rem",
- }}
- >
- <TextInput
- size="xs"
- placeholder={t("watchedFolders.workbench.search", "Search…")}
- value={search}
- onChange={(e) => onSearchChange(e.currentTarget.value)}
- leftSection={<Icon name="search" size={"0.875rem"} />}
- style={{ flex: 1 }}
- styles={{ input: { fontSize: "0.75rem" } }}
- />
- {extra}
- <Select
- size="xs"
- value={sort}
- onChange={(v) => v && onSortChange(v)}
- data={SORT_OPTIONS.map((o) => ({
- value: o.value,
- label: t(o.labelKey, o.labelDefault),
- }))}
- style={{ width: "6.5rem" }}
- styles={{ input: { fontSize: "0.75rem" } }}
- comboboxProps={{ withinPortal: true, zIndex: 400 }}
- />
- </Box>
- );
-}
-
-interface WatchedFolderWorkbenchViewProps {
- data: WatchedFolderViewData;
-}
-
-function RetryCountdown({
- nextRetryAt,
- t,
-}: {
- nextRetryAt: number;
- t: TFunction;
-}) {
- const [remaining, setRemaining] = useState(() =>
- Math.max(0, nextRetryAt - Date.now()),
- );
- useEffect(() => {
- const tick = () => setRemaining(Math.max(0, nextRetryAt - Date.now()));
- const id = setInterval(tick, 10_000);
- return () => clearInterval(id);
- }, [nextRetryAt]);
- const mins = Math.ceil(remaining / 60_000);
- return (
- <Text size="xs" c="yellow.6" style={{ flexShrink: 0 }}>
- {remaining <= 0
- ? t("watchedFolders.workbench.retryingSoon", "retrying…")
- : t("watchedFolders.workbench.retryIn", {
- count: mins,
- defaultValue: `retry in ${mins}m`,
- })}
- </Text>
- );
-}
-
-export function WatchedFolderWorkbenchView({
- data,
-}: WatchedFolderWorkbenchViewProps) {
- const { folderId } = data;
- const { t } = useTranslation();
- const { toolRegistry, setCustomWorkbenchViewData } = useToolWorkflow();
- const { actions } = useNavigationActions();
- const { folders, updateFolder } = useWatchedFolders();
- const folder = folders.find((f) => f.id === folderId);
- const { runPipeline } = useFolderAutomation(toolRegistry);
- useLocalFolderPoller(runPipeline);
-
- const {
- folderRecord,
- fileIds,
- processingFileIds,
- addFile,
- updateFileMetadata,
- removeFile,
- } = useFolderData(folderId ?? "");
-
- const isLocalFolder = folder?.inputSource === "local-folder";
-
- const [isDragOver, setIsDragOver] = useState(false);
- const [localInputFolderName, setLocalInputFolderName] = useState<
- string | null
- >(null);
- const [outputFiles, setOutputFiles] = useState<StirlingFile[]>([]);
- const [inputFiles, setInputFiles] = useState<StirlingFile[]>([]);
- const [previewFileId, setPreviewFileId] = useState<FileId | null>(null);
- const [previewFileName, setPreviewFileName] = useState("");
- const [previewFile, setPreviewFile] = useState<File | null>(null);
-
- // Filter / sort state
- const [activitySearch, setActivitySearch] = useState("");
- const [activitySort, setActivitySort] = useState("newest");
- const [activityStatusFilter, setActivityStatusFilter] = useState("all");
- const [automation, setAutomation] = useState<AutomationConfig | null>(null);
- const handledPendingRef = useRef<string | null>(null);
-
- // Load input/output blobs from the main file store whenever folderRecord changes.
- useEffect(() => {
- if (!folderRecord) {
- setInputFiles([]);
- setOutputFiles([]);
- return;
- }
- const inputIds = Object.keys(folderRecord.files);
- Promise.all(
- inputIds.map((id) => fileStorage.getStirlingFile(id as FileId)),
- ).then((files) => setInputFiles(files.filter(Boolean) as StirlingFile[]));
-
- const outputIds = Object.values(folderRecord.files).flatMap(
- (m) => m.displayFileIds ?? (m.displayFileId ? [m.displayFileId] : []),
- );
- Promise.all(
- outputIds.map((id) => fileStorage.getStirlingFile(id as FileId)),
- ).then((files) => setOutputFiles(files.filter(Boolean) as StirlingFile[]));
- }, [folderRecord]);
-
- useEffect(() => {
- if (folder?.automationId) {
- automationStorage.getAutomation(folder.automationId).then(setAutomation);
- }
- }, [folder?.automationId]);
-
- useEffect(() => {
- if (isLocalFolder && folderId) {
- folderDirectoryHandleStorage
- .getInput(folderId)
- .then((h) => setLocalInputFolderName(h?.name ?? null));
- } else {
- setLocalInputFolderName(null);
- }
- }, [isLocalFolder, folderId]);
-
- const handleFiles = useCallback(
- async (files: FileList | File[], sourceFileId?: string) => {
- if (!folder) return;
- const fileArray = Array.from(files);
- for (const file of fileArray) {
- if (!file.name.toLowerCase().endsWith(".pdf")) continue;
-
- let inputFileId: string;
- let ownedByFolder = false;
- if (sourceFileId) {
- // File from sidebar — already in stirling-pdf-files; user still owns it
- inputFileId = sourceFileId;
- } else {
- const resolved = await resolveInputFile(file);
- inputFileId = resolved.inputFileId;
- ownedByFolder = resolved.ownedByFolder;
- }
-
- if (folderRecord?.files[inputFileId]) {
- // Re-processing an existing file — reset status without losing addedAt/ownedByFolder
- await updateFileMetadata(inputFileId, {
- status: "pending",
- errorMessage: undefined,
- });
- } else {
- await addFile(inputFileId, {
- status: "pending",
- name: file.name,
- ownedByFolder: ownedByFolder || undefined,
- });
- }
-
- // Only run immediately if not paused; pending files will run when folder is resumed
- if (!folder.isPaused) {
- runPipeline(folder, file, inputFileId, ownedByFolder);
- }
- }
- },
- [folder, folderRecord, addFile, updateFileMetadata, runPipeline],
- );
-
- useEffect(() => {
- const { pendingFileId, pendingFileIds } = data;
-
- // Multi-file pending (from sidebar multi-select drag to sidebar folder card)
- if (pendingFileIds && pendingFileIds.length > 0) {
- const key = pendingFileIds.join(",");
- if (handledPendingRef.current === key) return;
- handledPendingRef.current = key;
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId });
- Promise.all(
- pendingFileIds.map((id) => fileStorage.getStirlingFile(id as FileId)),
- ).then(async (results) => {
- for (let i = 0; i < results.length; i++) {
- if (results[i]) await handleFiles([results[i]!], pendingFileIds[i]);
- }
- });
- return;
- }
-
- // Single pending file (legacy path)
- if (!pendingFileId || handledPendingRef.current === pendingFileId) return;
- handledPendingRef.current = pendingFileId;
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId });
- fileStorage
- .getStirlingFile(pendingFileId as FileId)
- .then((stirlingFile) => {
- if (stirlingFile) handleFiles([stirlingFile], pendingFileId);
- });
- }, [data, folderId, handleFiles, setCustomWorkbenchViewData]);
-
- const handleDrop = useCallback(
- (e: React.DragEvent) => {
- e.preventDefault();
- setIsDragOver(false);
-
- // Multi-file sidebar drag
- const multiRaw = e.dataTransfer.getData("watchedFolderFileIds");
- if (multiRaw) {
- try {
- const ids: string[] = JSON.parse(multiRaw);
- Promise.all(
- ids.map((id) => fileStorage.getStirlingFile(id as FileId)),
- ).then(async (results) => {
- for (let i = 0; i < results.length; i++) {
- if (results[i]) await handleFiles([results[i]!], ids[i]);
- }
- });
- return;
- } catch {
- /* fall through */
- }
- }
-
- // Single sidebar drag
- const sidebarFileId = e.dataTransfer.getData("watchedFolderFileId");
- if (sidebarFileId) {
- fileStorage
- .getStirlingFile(sidebarFileId as FileId)
- .then((stirlingFile) => {
- if (stirlingFile) handleFiles([stirlingFile], sidebarFileId);
- });
- } else if (e.dataTransfer.files.length > 0) {
- handleFiles(e.dataTransfer.files);
- }
- },
- [handleFiles],
- );
-
- const handleFileInput = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && e.target.files.length > 0)
- handleFiles(e.target.files);
- e.target.value = "";
- },
- [handleFiles],
- );
-
- const handleView = useCallback((file: StirlingFile) => {
- setPreviewFileId(file.fileId);
- setPreviewFileName(file.name);
- }, []);
-
- const handleDownload = useCallback(async (blob: Blob, name: string) => {
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = name;
- a.click();
- URL.revokeObjectURL(url);
- }, []);
-
- const goHome = useCallback(() => {
- setCustomWorkbenchViewData(WATCHED_FOLDER_VIEW_ID, { folderId: null });
- actions.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- }, [setCustomWorkbenchViewData, actions]);
-
- const handlePauseResume = useCallback(async () => {
- if (!folder) return;
- const nowPaused = !folder.isPaused;
- await updateFolder({ ...folder, isPaused: nowPaused });
- // When resuming, run all files that were queued while paused
- if (!nowPaused) {
- const pendingIds = fileIds.filter(
- (id) => folderRecord?.files[id]?.status === "pending",
- );
- for (const fileId of pendingIds) {
- const file = inputFiles.find((f) => f.fileId === fileId);
- if (file) {
- runPipeline(
- { ...folder, isPaused: false },
- file,
- fileId,
- folderRecord?.files[fileId]?.ownedByFolder ?? false,
- );
- }
- }
- }
- }, [folder, updateFolder, fileIds, folderRecord, inputFiles, runPipeline]);
-
- const {
- phase: statsModalPhase,
- cardRect: statsCardRect,
- textExpanded: statsTextExpanded,
- openModal: openStatsModal,
- closeModal: closeStatsModal,
- } = useCardModalAnimation();
- const [statsPeriod, setStatsPeriod] = useState<"24h" | "7d" | "30d" | "all">(
- "7d",
- );
-
- const dashboardStats = useMemo(() => {
- const getTs = (d: Date | string | number | undefined): number =>
- !d
- ? 0
- : d instanceof Date
- ? d.getTime()
- : typeof d === "number"
- ? d
- : new Date(d).getTime();
- const now = Date.now();
- const cutoff =
- statsPeriod === "24h"
- ? now - 86_400_000
- : statsPeriod === "7d"
- ? now - 7 * 86_400_000
- : statsPeriod === "30d"
- ? now - 30 * 86_400_000
- : 0;
- const entries = Object.entries(folderRecord?.files ?? {}).filter(
- ([, m]) => getTs(m.addedAt) >= cutoff,
- );
- const processed = entries.filter(
- ([, m]) => m.status === "processed",
- ).length;
- const failed = entries.filter(([, m]) => m.status === "error").length;
- const pending = entries.filter(
- ([, m]) => m.status === "pending" || m.status === "processing",
- ).length;
- const totalIn = entries.reduce(
- (s, [id]) => s + (inputFiles.find((f) => f.fileId === id)?.size ?? 0),
- 0,
- );
- const totalOut = entries
- .filter(([, m]) => m.status === "processed")
- .reduce((s, [, m]) => {
- const ids =
- m.displayFileIds ?? (m.displayFileId ? [m.displayFileId] : []);
- return (
- s +
- ids.reduce(
- (ss, oid) =>
- ss + (outputFiles.find((f) => f.fileId === oid)?.size ?? 0),
- 0,
- )
- );
- }, 0);
- const isHourly = statsPeriod === "24h";
- const bucketMs = isHourly ? 3_600_000 : 86_400_000;
- const bucketCount = isHourly
- ? 24
- : statsPeriod === "7d"
- ? 7
- : statsPeriod === "30d"
- ? 30
- : 30;
- const buckets: Array<{ processed: number; failed: number }> = Array.from(
- { length: bucketCount },
- () => ({ processed: 0, failed: 0 }),
- );
- for (const [, m] of Object.entries(folderRecord?.files ?? {})) {
- const ts = getTs(m.processedAt ?? m.addedAt);
- if (!ts) continue;
- const idx = Math.floor((now - ts) / bucketMs);
- if (idx >= 0 && idx < bucketCount) {
- const b = buckets[bucketCount - 1 - idx];
- if (m.status === "processed") b.processed++;
- else if (m.status === "error") b.failed++;
- }
- }
- const maxBucket = Math.max(
- ...buckets.map((b) => b.processed + b.failed),
- 1,
- );
- return {
- processed,
- failed,
- pending,
- totalIn,
- totalOut,
- saved: totalIn - totalOut,
- buckets,
- maxBucket,
- };
- }, [folderRecord, inputFiles, outputFiles, statsPeriod]);
-
- const [expandedActivityIds, setExpandedActivityIds] = useState<Set<string>>(
- new Set(),
- );
- const [selectedActivityIds, setSelectedActivityIds] = useState<Set<string>>(
- new Set(),
- );
- const [hoveredRowId, setHoveredRowId] = useState<string | null>(null);
- const [focusedRowIndex, setFocusedRowIndex] = useState<number | null>(null);
- const [chartHover, setChartHover] = useState<{
- i: number;
- relX: number;
- relY: number;
- } | null>(null);
- const [deleteConfirm, setDeleteConfirm] = useState<{ ids: string[] } | null>(
- null,
- );
- const listRef = useRef<HTMLDivElement>(null);
- const toggleActivityRow = useCallback((id: string) => {
- setExpandedActivityIds((prev) => {
- const next = new Set(prev);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return next;
- });
- }, []);
-
- const handleListKeyDown = useCallback(
- (e: React.KeyboardEvent, ids: string[]) => {
- if (ids.length === 0) return;
- const cur = focusedRowIndex ?? -1;
-
- if (e.key === "ArrowDown") {
- e.preventDefault();
- setFocusedRowIndex(Math.min(cur + 1, ids.length - 1));
- } else if (e.key === "ArrowUp") {
- e.preventDefault();
- setFocusedRowIndex(Math.max(cur - 1, 0));
- } else if (e.key === " " && cur >= 0) {
- e.preventDefault();
- const id = ids[cur];
- setSelectedActivityIds((prev) => {
- const n = new Set(prev);
- if (n.has(id)) n.delete(id);
- else n.add(id);
- return n;
- });
- } else if (e.key === "Enter" && cur >= 0) {
- e.preventDefault();
- toggleActivityRow(ids[cur]);
- } else if (e.key === "a" && (e.ctrlKey || e.metaKey)) {
- e.preventDefault();
- setSelectedActivityIds(new Set(ids));
- } else if (e.key === "Escape") {
- setSelectedActivityIds(new Set());
- setFocusedRowIndex(null);
- }
- },
- [focusedRowIndex, toggleActivityRow],
- );
-
- // input fileId → output StirlingFiles produced by that run
- const activityOutputMap = useMemo(() => {
- const map = new Map<string, StirlingFile[]>();
- for (const [id, meta] of Object.entries(folderRecord?.files ?? {})) {
- const ids =
- meta.displayFileIds ?? (meta.displayFileId ? [meta.displayFileId] : []);
- const files = ids
- .map((oid) => outputFiles.find((f) => f.fileId === oid))
- .filter((f): f is StirlingFile => !!f);
- if (files.length > 0) map.set(id, files);
- }
- return map;
- }, [folderRecord, outputFiles]);
-
- const execDelete = useCallback(
- async (ids: string[], withOutputFiles: boolean) => {
- await Promise.all(
- ids.map(async (id) => {
- if (withOutputFiles) {
- const meta = folderRecord?.files[id];
- const outputIds =
- meta?.displayFileIds ??
- (meta?.displayFileId ? [meta.displayFileId] : []);
- await Promise.all(
- outputIds.map((oid) =>
- fileStorage.deleteStirlingFile(oid as FileId).catch(() => {}),
- ),
- );
- }
- await removeFile(id);
- }),
- );
- setSelectedActivityIds((prev) => {
- const n = new Set(prev);
- ids.forEach((id) => n.delete(id));
- return n;
- });
- setDeleteConfirm(null);
- },
- [folderRecord, removeFile],
- );
-
- const handleDeleteOne = useCallback((fileId: string) => {
- setDeleteConfirm({ ids: [fileId] });
- }, []);
-
- const handleBatchDelete = useCallback(() => {
- setDeleteConfirm({ ids: [...selectedActivityIds] });
- }, [selectedActivityIds]);
-
- const doRetryIds = useCallback(
- (ids: Iterable<string>) => {
- if (!folder) return;
- for (const id of ids) {
- const meta = folderRecord?.files[id];
- if (meta?.status !== "error") continue;
- const inputFile = inputFiles.find((f) => f.fileId === id);
- if (!inputFile) continue;
- updateFileMetadata(id, { status: "pending", errorMessage: undefined });
- void runPipeline(folder, inputFile, id, meta?.ownedByFolder ?? false);
- }
- },
- [folder, folderRecord, inputFiles, updateFileMetadata, runPipeline],
- );
-
- const handleBatchRetry = useCallback(() => {
- const hasMixed = [...selectedActivityIds].some(
- (id) => folderRecord?.files[id]?.status !== "error",
- );
- if (
- hasMixed &&
- !window.confirm(
- t(
- "watchedFolders.workbench.retryMixedConfirm",
- "Some selected files have already completed and will be skipped. Only failed files will be retried. Continue?",
- ),
- )
- )
- return;
- doRetryIds(selectedActivityIds);
- }, [selectedActivityIds, folderRecord, doRetryIds]);
-
- const collectExportFiles = useCallback(
- (ids: Iterable<string>): StirlingFile[] => {
- const files: StirlingFile[] = [];
- for (const id of ids) {
- const outputs = activityOutputMap.get(id);
- const toAdd =
- outputs && outputs.length > 0
- ? outputs
- : ([inputFiles.find((f) => f.fileId === id)].filter(
- Boolean,
- ) as StirlingFile[]);
- files.push(...toAdd);
- }
- return files;
- },
- [activityOutputMap, inputFiles],
- );
-
- const handleBatchDownload = useCallback(
- async (ids: Iterable<string> = selectedActivityIds) => {
- const zip = new JSZip();
- let count = 0;
- for (const f of collectExportFiles(ids)) {
- zip.file(f.name, await f.arrayBuffer());
- count++;
- }
- if (count === 0) return;
- const blob = await zip.generateAsync({ type: "blob" });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `${folder?.name ?? "watch-folder"}-export.zip`;
- a.click();
- URL.revokeObjectURL(url);
- },
- [selectedActivityIds, collectExportFiles, folder],
- );
-
- const handleBatchDownloadSeparate = useCallback(
- async (ids: Iterable<string> = selectedActivityIds) => {
- for (const f of collectExportFiles(ids)) {
- const url = URL.createObjectURL(f);
- const a = document.createElement("a");
- a.href = url;
- a.download = f.name;
- a.click();
- URL.revokeObjectURL(url);
- await new Promise((res) => setTimeout(res, 150));
- }
- },
- [selectedActivityIds, collectExportFiles],
- );
-
- // ── Filtered + sorted lists — all before early returns ──
-
- const filteredActivityIds = useMemo(() => {
- const q = activitySearch.toLowerCase();
- let items = fileIds.map((id) => {
- const meta = folderRecord?.files[id];
- const name =
- meta?.name ?? inputFiles.find((f) => f.fileId === id)?.name ?? id;
- const status = meta?.status ?? "pending";
- const time = meta?.processedAt
- ? new Date(meta.processedAt).getTime()
- : meta?.addedAt
- ? new Date(meta.addedAt).getTime()
- : 0;
- return { id, name, status, time };
- });
- if (q) items = items.filter((i) => i.name.toLowerCase().includes(q));
- if (activityStatusFilter !== "all")
- items = items.filter((i) => i.status === activityStatusFilter);
- if (activitySort === "newest") items = [...items].reverse();
- else if (activitySort === "name-asc")
- items = [...items].sort((a, b) => a.name.localeCompare(b.name));
- else if (activitySort === "name-desc")
- items = [...items].sort((a, b) => b.name.localeCompare(a.name));
- // 'oldest' keeps the original order (insertion order = oldest first)
- return items.map((i) => i.id);
- }, [
- fileIds,
- folderRecord,
- inputFiles,
- activitySearch,
- activityStatusFilter,
- activitySort,
- ]);
-
- const handleRetryAllFiltered = useCallback(() => {
- doRetryIds(filteredActivityIds);
- }, [filteredActivityIds, doRetryIds]);
-
- // Early returns — after all hooks
- if (!folderId) return <WatchedFolderHomePage />;
-
- const folderIcon =
- (folder ? iconMap[folder.icon ?? ""] : undefined) ?? iconMap.FolderIcon;
-
- if (!folder) {
- return (
- <Box
- p="xl"
- style={{
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- height: "100%",
- }}
- >
- <Text c="dimmed">
- {t("watchedFolders.folderNotFound", "Folder not found")}
- </Text>
- </Box>
- );
- }
-
- const failedFileIds = fileIds.filter(
- (id) => folderRecord?.files[id]?.status === "error",
- );
- const isProcessingAny = processingFileIds.length > 0;
- const ops = automation?.operations ?? [];
-
- const hasCompressStep = ops.some((op) => op.operation === "compress");
- const totalInputBytes = inputFiles.reduce((sum, f) => sum + f.size, 0);
- const totalOutputBytes = outputFiles.reduce((sum, f) => sum + f.size, 0);
- const dataSavedBytes = totalInputBytes - totalOutputBytes;
-
- function formatBytes(bytes: number): string {
- const abs = Math.abs(bytes);
- if (abs >= 1073741824) return `${(bytes / 1073741824).toFixed(1)} GB`;
- if (abs >= 1048576) return `${(bytes / 1048576).toFixed(1)} MB`;
- if (abs >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
- return `${bytes} B`;
- }
-
- const daysRunning = folder.createdAt
- ? Math.floor((Date.now() - new Date(folder.createdAt).getTime()) / 86400000)
- : null;
-
- return (
- <Box
- style={{
- display: "flex",
- flexDirection: "column",
- height: "100%",
- overflow: "hidden",
- }}
- >
- {/* ── Header ── */}
- <Box
- px="xl"
- py="md"
- style={{
- borderBottom: "0.0625rem solid var(--c-border-subtle)",
- backgroundColor: "var(--c-bg-raised)",
- flexShrink: 0,
- }}
- >
- <Group justify="space-between" align="center">
- <Group gap="md" align="center">
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={goHome}
- aria-label={t("watchedFolders.actions.back", "Back")}
- >
- <Icon name="arrow-left" size={"1rem"} />
- </ActionIcon>
-
- {/* Icon with status dot */}
- <Box style={{ position: "relative", flexShrink: 0 }}>
- <Box
- style={{
- width: "2.5rem",
- height: "2.5rem",
- borderRadius: "0.625rem",
- backgroundColor: `${folder.accentColor}18`,
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <Icon
- name={folderIcon}
- size="1.25rem"
- style={{ color: folder.accentColor }}
- />
- </Box>
- <Box
- style={{
- position: "absolute",
- bottom: "-0.1875rem",
- right: "-0.1875rem",
- width: "0.75rem",
- height: "0.75rem",
- borderRadius: "50%",
- backgroundColor: "var(--c-bg-raised)",
- textAlign: "center",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- }}
- >
- <Box
- style={{
- width: "0.4375rem",
- height: "0.4375rem",
- borderRadius: "50%",
- backgroundColor: folder.isPaused
- ? "var(--color-yellow-500)"
- : isProcessingAny
- ? "var(--mantine-color-blue-filled)"
- : "var(--color-green-500)",
- }}
- />
- </Box>
- </Box>
-
- <Stack gap={2}>
- <Text
- fw={700}
- size="md"
- style={{ letterSpacing: "-0.01em", lineHeight: 1.2 }}
- >
- {folder.name}
- </Text>
- {/* Pipeline summary */}
- {ops.length > 0 && (
- <Group gap={4} wrap="nowrap">
- {ops.map((op, i) => (
- <Group key={i} gap={4} wrap="nowrap" align="center">
- {i > 0 && (
- <Icon
- name="chevron-right"
- size={"0.625rem"}
- style={{ color: "var(--mantine-color-gray-5)" }}
- />
- )}
- <Text
- size="xs"
- c="dimmed"
- style={{ fontSize: "0.6875rem" }}
- >
- {humaniseOp(op.operation)}
- </Text>
- </Group>
- ))}
- </Group>
- )}
- {folder.description && !ops.length && (
- <Text size="xs" c="dimmed">
- {folder.description}
- </Text>
- )}
- {isLocalFolder && (
- <Text
- size="xs"
- c={localInputFolderName ? "green" : "yellow"}
- style={{ fontSize: "0.6875rem" }}
- >
- {localInputFolderName
- ? t("watchedFolders.workbench.watching", {
- name: localInputFolderName,
- defaultValue: `Watching: ${localInputFolderName}`,
- })
- : t(
- "watchedFolders.workbench.noInputFolder",
- "No input folder — edit to configure",
- )}
- </Text>
- )}
- </Stack>
- </Group>
-
- {/* Add files + pause/resume */}
- <Group gap="sm" align="center">
- {folder.isPaused ? (
- <Button
- size="sm"
- variant="secondary"
- accent="success"
- onClick={handlePauseResume}
- leftSection={<Icon name="play" size={"0.875rem"} />}
- >
- {t("watchedFolders.workbench.resume", "Resume")}
- </Button>
- ) : (
- <Button
- size="sm"
- variant="tertiary"
- onClick={handlePauseResume}
- leftSection={<Icon name="pause" size={"0.875rem"} />}
- >
- {t("watchedFolders.workbench.pause", "Pause")}
- </Button>
- )}
- <Button
- size="sm"
- variant="secondary"
- onClick={() =>
- document
- .getElementById(`folder-file-input-${folderId}`)
- ?.click()
- }
- >
- {t("watchedFolders.workbench.addFiles", "Add files")}
- </Button>
- <input
- id={`folder-file-input-${folderId}`}
- type="file"
- accept=".pdf"
- multiple
- style={{ display: "none" }}
- onChange={handleFileInput}
- />
- </Group>
- </Group>
- </Box>
-
- {/* ── Body ── */}
- <Box style={{ flex: 1, display: "flex", minHeight: 0 }}>
- {/* Left: Activity */}
- <Box
- style={{
- flex: 1,
- display: "flex",
- flexDirection: "column",
- overflow: "hidden",
- outline: isDragOver
- ? "0.125rem dashed var(--mantine-color-blue-filled)"
- : "none",
- outlineOffset: "-0.25rem",
- backgroundColor: isDragOver
- ? "var(--mantine-color-blue-light)"
- : "transparent",
- transition: "background-color 0.15s ease",
- }}
- onDragOver={(e) => {
- e.preventDefault();
- setIsDragOver(true);
- }}
- onDragLeave={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node))
- setIsDragOver(false);
- }}
- onDrop={handleDrop}
- >
- {/* Storage cards */}
- <Box style={{ padding: "0.5rem 1rem 0", flexShrink: 0 }}>
- <Box
- style={{
- display: "grid",
- gridTemplateColumns: "repeat(auto-fit, minmax(4.5rem, 1fr))",
- gap: "0.5rem",
- marginBottom: "0.5rem",
- }}
- >
- {/* Inputs */}
- <StatCard
- icon={
- <Icon
- name="folder-open"
- size={"1.125rem"}
- style={{ color: "var(--c-accent-text)" }}
- />
- }
- count={inputFiles.length}
- label={t("watchedFolders.workbench.inputs", "Inputs")}
- hoverColor="var(--mantine-color-blue-filled)"
- isActive={activityStatusFilter === "all"}
- onClick={() => {
- if (
- activityStatusFilter === "all" &&
- expandedActivityIds.size > 0
- ) {
- setExpandedActivityIds(new Set());
- } else {
- setActivityStatusFilter("all");
- setExpandedActivityIds(new Set(fileIds));
- }
- }}
- />
-
- {/* Outputs */}
- <StatCard
- icon={
- <Icon
- name="circle-check-big"
- size={"1.125rem"}
- style={{ color: "var(--color-green-500)" }}
- />
- }
- count={outputFiles.length}
- label={t("watchedFolders.workbench.outputs", "Outputs")}
- hoverColor="var(--color-green-500)"
- isActive={activityStatusFilter === "processed"}
- onClick={() => {
- setActivityStatusFilter(
- activityStatusFilter === "processed" ? "all" : "processed",
- );
- setExpandedActivityIds(new Set());
- }}
- />
-
- {/* Failed */}
- <StatCard
- icon={
- <Icon
- name="circle-alert"
- size={"1.125rem"}
- style={{
- color:
- failedFileIds.length > 0
- ? "var(--color-red-500)"
- : "var(--mantine-color-dimmed)",
- }}
- />
- }
- count={failedFileIds.length}
- label={t("watchedFolders.workbench.failed", "Failed")}
- hoverColor="var(--color-red-500)"
- isActive={activityStatusFilter === "error"}
- onClick={
- failedFileIds.length > 0
- ? () => {
- setActivityStatusFilter(
- activityStatusFilter === "error" ? "all" : "error",
- );
- setExpandedActivityIds(new Set());
- }
- : undefined
- }
- />
-
- {/* Data saved — only when compress is in pipeline */}
- {hasCompressStep && (
- <StatCard
- icon={
- <Icon
- name="download"
- size={"1.125rem"}
- style={{
- color:
- dataSavedBytes > 0
- ? "var(--color-green-500)"
- : "var(--mantine-color-dimmed)",
- }}
- />
- }
- count={dataSavedBytes > 0 ? formatBytes(dataSavedBytes) : "—"}
- label={t("watchedFolders.workbench.dataSaved", "Saved")}
- />
- )}
-
- {/* Days running */}
- <StatCard
- icon={
- <Icon
- name="rotate-ccw-clock"
- size={"1.125rem"}
- style={{ color: "var(--mantine-color-dimmed)" }}
- />
- }
- count={
- daysRunning !== null && daysRunning > 0
- ? `${daysRunning}d`
- : "—"
- }
- label={t("watchedFolders.workbench.running", "Running")}
- hoverColor="var(--mantine-color-dimmed)"
- onClick={openStatsModal}
- />
- </Box>
- </Box>
-
- {/* Queue depth indicator */}
- {(processingFileIds.length > 0 ||
- fileIds.filter(
- (id) => folderRecord?.files[id]?.status === "pending",
- ).length > 0) &&
- (() => {
- const queuedCount = fileIds.filter(
- (id) => folderRecord?.files[id]?.status === "pending",
- ).length;
- const activeCount = processingFileIds.length;
- const totalWidth = activeCount + queuedCount;
- return (
- <Box style={{ padding: "0 1rem 0.5rem", flexShrink: 0 }}>
- <Box
- style={{
- display: "flex",
- alignItems: "center",
- gap: "0.5rem",
- marginBottom: "0.25rem",
- }}
- >
- {activeCount > 0 && (
- <Text
- style={{
- fontSize: "0.625rem",
- color: "var(--c-accent-text)",
- }}
- >
- {t("watchedFolders.workbench.countProcessing", {
- count: activeCount,
- defaultValue: `${activeCount} processing`,
- })}
- </Text>
- )}
- {queuedCount > 0 && (
- <Text style={{ fontSize: "0.625rem" }} c="dimmed">
- {t("watchedFolders.workbench.countQueued", {
- count: queuedCount,
- defaultValue: `${queuedCount} queued`,
- })}
- </Text>
- )}
- </Box>
- <Box
- style={{
- height: "0.1875rem",
- borderRadius: "999px",
- backgroundColor: "var(--c-border-subtle)",
- overflow: "hidden",
- }}
- >
- <Box
- style={{
- display: "flex",
- height: "100%",
- width: `${(activeCount / totalWidth) * 100}%`,
- }}
- >
- <div
- style={{
- flex: activeCount,
- backgroundColor: "var(--mantine-color-blue-filled)",
- borderRadius: "999px",
- animation: "pulse 1.5s ease-in-out infinite",
- }}
- />
- </Box>
- </Box>
- </Box>
- );
- })()}
-
- {/* Activity label */}
- <Box
- style={{
- padding: "1rem 1rem 0.5rem",
- flexShrink: 0,
- display: "flex",
- alignItems: "center",
- gap: "0.5rem",
- }}
- >
- <Text
- fw={600}
- style={{
- fontSize: "0.75rem",
- flex: 1,
- color: isDragOver
- ? "var(--mantine-color-blue-filled)"
- : "var(--c-text-subtle)",
- textTransform: "uppercase",
- letterSpacing: "0.05em",
- }}
- >
- {isDragOver
- ? t("watchedFolders.workbench.dropToProcess", "Drop to process")
- : t("watchedFolders.workbench.activity", "Activity")}
- </Text>
- {activityStatusFilter === "error" &&
- filteredActivityIds.length > 0 && (
- <Button
- size="sm"
- variant="secondary"
- onClick={handleRetryAllFiltered}
- leftSection={<Icon name="rotate-ccw" size={"0.75rem"} />}
- >
- {t("watchedFolders.workbench.retryAll", "Retry all")}
- </Button>
- )}
- {activityStatusFilter === "processed" &&
- filteredActivityIds.length > 0 && (
- <>
- <Button
- size="sm"
- variant="secondary"
- onClick={() =>
- void handleBatchDownload(filteredActivityIds)
- }
- leftSection={<Icon name="download" size={"0.75rem"} />}
- >
- {t("watchedFolders.workbench.exportZip", "Export zip")}
- </Button>
- <Button
- size="sm"
- variant="secondary"
- onClick={() =>
- void handleBatchDownloadSeparate(filteredActivityIds)
- }
- leftSection={<Icon name="download" size={"0.75rem"} />}
- >
- {t(
- "watchedFolders.workbench.exportSeparately",
- "Export separately",
- )}
- </Button>
- </>
- )}
- </Box>
-
- {/* Activity filter/sort toolbar */}
- {fileIds.length > 0 && (
- <FilterSortBar
- search={activitySearch}
- onSearchChange={setActivitySearch}
- sort={activitySort}
- onSortChange={setActivitySort}
- extra={
- <Select
- size="xs"
- value={activityStatusFilter}
- onChange={(v) => v && setActivityStatusFilter(v)}
- data={ACTIVITY_STATUS_OPTIONS.map((o) => ({
- value: o.value,
- label: t(o.labelKey, o.labelDefault),
- }))}
- style={{ width: "5.5rem" }}
- styles={{ input: { fontSize: "0.75rem" } }}
- comboboxProps={{ withinPortal: true, zIndex: 400 }}
- />
- }
- />
- )}
-
- {selectedActivityIds.size > 0 &&
- (() => {
- const hasAnyFailed = [...selectedActivityIds].some(
- (id) =>
- folderRecord?.files[id]?.status === "error" &&
- inputFiles.some((f) => f.fileId === id),
- );
- const hasDownloadable = [...selectedActivityIds].some(
- (id) =>
- (activityOutputMap.get(id)?.length ?? 0) > 0 ||
- inputFiles.some((f) => f.fileId === id),
- );
- const showRetry =
- hasAnyFailed && activityStatusFilter !== "processed";
- const showExport =
- hasDownloadable && activityStatusFilter !== "error";
- return (
- <Box
- style={{
- padding: "0.375rem 0.75rem",
- borderTop: "0.0625rem solid var(--c-border-subtle)",
- borderBottom: "0.0625rem solid var(--c-border-subtle)",
- backgroundColor: "var(--mantine-color-blue-light)",
- display: "flex",
- alignItems: "center",
- gap: "0.5rem",
- flexShrink: 0,
- }}
- >
- <Text
- size="xs"
- fw={600}
- style={{ color: "var(--c-accent-text)" }}
- >
- {t("watchedFolders.workbench.countSelected", {
- count: selectedActivityIds.size,
- defaultValue: `${selectedActivityIds.size} selected`,
- })}
- </Text>
- {selectedActivityIds.size < filteredActivityIds.length && (
- <Button
- size="sm"
- variant="tertiary"
- onClick={() =>
- setSelectedActivityIds(new Set(filteredActivityIds))
- }
- >
- {t("watchedFolders.workbench.selectAll", {
- count: filteredActivityIds.length,
- defaultValue: `Select all ${filteredActivityIds.length}`,
- })}
- </Button>
- )}
- <Box style={{ flex: 1 }} />
- {showRetry && (
- <Button
- size="sm"
- variant="secondary"
- onClick={handleBatchRetry}
- leftSection={<Icon name="rotate-ccw" size={"0.75rem"} />}
- >
- {t("watchedFolders.actions.retry", "Retry")}
- </Button>
- )}
- {showExport && (
- <>
- <Button
- size="sm"
- variant="secondary"
- onClick={() => void handleBatchDownload()}
- leftSection={<Icon name="download" size={"0.75rem"} />}
- >
- {t("watchedFolders.workbench.exportZip", "Export zip")}
- </Button>
- <Button
- size="sm"
- variant="secondary"
- onClick={() => void handleBatchDownloadSeparate()}
- leftSection={<Icon name="download" size={"0.75rem"} />}
- >
- {t(
- "watchedFolders.workbench.exportSeparately",
- "Export separately",
- )}
- </Button>
- </>
- )}
- <Button
- size="sm"
- variant="secondary"
- accent="danger"
- onClick={() => void handleBatchDelete()}
- leftSection={<Icon name="trash" size={"0.75rem"} />}
- >
- {t("watchedFolders.workbench.delete", "Delete")}
- </Button>
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={() => setSelectedActivityIds(new Set())}
- aria-label={t(
- "watchedFolders.workbench.clearSelection",
- "Clear selection",
- )}
- >
- <Icon name="x" size={"0.875rem"} />
- </ActionIcon>
- </Box>
- );
- })()}
-
- <ScrollArea
- style={{ flex: 1 }}
- viewportRef={listRef}
- onKeyDown={(e) => handleListKeyDown(e, filteredActivityIds)}
- tabIndex={0}
- styles={{ viewport: { outline: "none" } }}
- >
- <Stack gap="xs" px="md" pb="md">
- {fileIds.length === 0 ? (
- <Text size="xs" c="dimmed" ta="center" py="lg">
- {t(
- "watchedFolders.workbench.noActivity",
- "No activity yet — drop a PDF to start",
- )}
- </Text>
- ) : filteredActivityIds.length === 0 ? (
- <Text size="xs" c="dimmed" ta="center" py="lg">
- {t(
- "watchedFolders.workbench.noActivityMatch",
- "No matching activity",
- )}
- </Text>
- ) : (
- <>
- {filteredActivityIds.map((fileId, rowIdx) => {
- const meta = folderRecord?.files[fileId];
- const status = meta?.status ?? "pending";
- const inputFile = inputFiles.find(
- (f) => f.fileId === fileId,
- );
- const filename = meta?.name ?? inputFile?.name ?? fileId;
- const isExpanded = expandedActivityIds.has(fileId);
- const isSelected = selectedActivityIds.has(fileId);
- const isHovered = hoveredRowId === fileId;
- const isFocused = focusedRowIndex === rowIdx;
- const outputs = activityOutputMap.get(fileId) ?? [];
- const primaryFile = outputs[0] ?? inputFile;
- return (
- <Box
- key={fileId}
- style={{
- borderRadius: "var(--mantine-radius-sm)",
- border: `0.0625rem solid ${isFocused ? "var(--mantine-color-blue-4)" : isSelected ? "var(--mantine-color-blue-filled)" : status === "error" ? "var(--mantine-color-red-light)" : "var(--c-border-subtle)"}`,
- backgroundColor: isSelected
- ? "var(--mantine-color-blue-light)"
- : "var(--c-bg-raised)",
- overflow: "hidden",
- outline: "none",
- }}
- onMouseEnter={() => setHoveredRowId(fileId)}
- onMouseLeave={() => setHoveredRowId(null)}
- onMouseDown={() => setFocusedRowIndex(rowIdx)}
- >
- {/* Row header */}
- <Box
- style={{
- padding: "0.375rem 0.5rem 0.375rem 0.25rem",
- display: "flex",
- alignItems: "center",
- gap: "0.5rem",
- cursor: "pointer",
- userSelect: "none",
- }}
- onClick={() =>
- setSelectedActivityIds((prev) => {
- const n = new Set(prev);
- if (n.has(fileId)) n.delete(fileId);
- else n.add(fileId);
- return n;
- })
- }
- >
- <ActionIcon
- variant="tertiary"
- size="sm"
- style={{ flexShrink: 0 }}
- onClick={(e) => {
- e.stopPropagation();
- toggleActivityRow(fileId);
- }}
- aria-label={
- isExpanded
- ? t(
- "watchedFolders.actions.collapse",
- "Collapse",
- )
- : t("watchedFolders.actions.expand", "Expand")
- }
- >
- <Icon
- name="chevron-right"
- size={"0.75rem"}
- style={{
- transform: isExpanded
- ? "rotate(90deg)"
- : "none",
- transition: "transform 0.15s",
- }}
- />
- </ActionIcon>
- {status === "processed" && (
- <Icon
- name="circle-check"
- size={"0.875rem"}
- style={{
- color: "var(--color-green-500)",
- flexShrink: 0,
- }}
- />
- )}
- {status === "processing" && (
- <Loader size="0.625rem" style={{ flexShrink: 0 }} />
- )}
- {status === "error" && !meta?.nextRetryAt && (
- <Icon
- name="circle-alert"
- size={"0.875rem"}
- style={{
- color: "var(--color-red-500)",
- flexShrink: 0,
- }}
- />
- )}
- {status === "error" && meta?.nextRetryAt && (
- <Icon
- name="rotate-ccw"
- size={"0.875rem"}
- style={{
- color: "var(--color-yellow-500)",
- flexShrink: 0,
- }}
- />
- )}
- {status === "pending" && (
- <Box
- style={{
- width: "0.5rem",
- height: "0.5rem",
- borderRadius: "50%",
- backgroundColor:
- "var(--mantine-color-yellow-5)",
- flexShrink: 0,
- }}
- />
- )}
- <Text
- size="xs"
- lineClamp={1}
- style={{ flex: 1, minWidth: 0 }}
- >
- {filename}
- </Text>
- {status === "error" &&
- (meta?.failedAttempts ?? 0) > 0 && (
- <Box
- style={{
- padding: "0.0625rem 0.3rem",
- borderRadius: "0.25rem",
- backgroundColor:
- "var(--mantine-color-red-light)",
- border:
- "0.0625rem solid var(--mantine-color-red-light)",
- flexShrink: 0,
- }}
- >
- <Text
- style={{
- fontSize: "0.625rem",
- fontWeight: 700,
- color: "var(--color-red-500)",
- letterSpacing: "0.03em",
- }}
- >
- {meta!.failedAttempts}×
- </Text>
- </Box>
- )}
- {meta?.nextRetryAt && (
- <RetryCountdown
- nextRetryAt={meta.nextRetryAt}
- t={t}
- />
- )}
- <Text
- size="xs"
- c="dimmed"
- style={{ fontSize: "0.6875rem", flexShrink: 0 }}
- >
- {meta?.processedAt || meta?.addedAt
- ? timeAgo(
- new Date(meta.processedAt ?? meta.addedAt),
- t,
- )
- : ""}
- </Text>
- {isHovered && (
- <Box
- style={{
- display: "flex",
- alignItems: "center",
- gap: "0.125rem",
- flexShrink: 0,
- }}
- >
- {!isExpanded && primaryFile && (
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- handleView(primaryFile);
- }}
- aria-label={t(
- "watchedFolders.workbench.preview",
- "Preview",
- )}
- >
- <Icon name="eye" size={"0.875rem"} />
- </ActionIcon>
- )}
- {!isExpanded && primaryFile && (
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- void handleDownload(
- primaryFile,
- primaryFile.name,
- );
- }}
- aria-label={t(
- "watchedFolders.workbench.export",
- "Export",
- )}
- >
- <Icon name="download" size={"0.875rem"} />
- </ActionIcon>
- )}
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- void handleDeleteOne(fileId);
- }}
- aria-label={t(
- "watchedFolders.workbench.delete",
- "Delete",
- )}
- >
- <Icon name="trash" size={"0.875rem"} />
- </ActionIcon>
- </Box>
- )}
- </Box>
- {/* Expanded panel */}
- {isExpanded && (
- <Box
- style={{
- borderTop: `0.0625rem solid ${status === "error" ? "var(--mantine-color-red-light)" : "var(--c-border-subtle)"}`,
- padding: "0.375rem 0.625rem 0.375rem 2rem",
- backgroundColor: "var(--bg-app)",
- }}
- >
- {/* Input file row */}
- {inputFile && (
- <Box
- style={{
- display: "flex",
- alignItems: "center",
- gap: "0.5rem",
- padding: "0.2rem 0",
- marginBottom:
- outputs.length > 0 || status === "error"
- ? "0.25rem"
- : 0,
- }}
- >
- <Text
- style={{
- fontSize: "0.625rem",
- letterSpacing: "0.04em",
- color: "var(--mantine-color-dimmed)",
- textTransform: "uppercase",
- flexShrink: 0,
- }}
- >
- {t(
- "watchedFolders.workbench.directionIn",
- "in",
- )}
- </Text>
- <Text
- size="xs"
- style={{ flex: 1, minWidth: 0 }}
- lineClamp={1}
- >
- {inputFile.name}
- </Text>
- <Text
- size="xs"
- c="dimmed"
- style={{ flexShrink: 0 }}
- >
- {formatBytes(inputFile.size)}
- </Text>
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- handleView(inputFile);
- }}
- aria-label={t(
- "watchedFolders.workbench.previewInput",
- "Preview input",
- )}
- >
- <Icon name="eye" size={"0.875rem"} />
- </ActionIcon>
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- handleDownload(inputFile, inputFile.name);
- }}
- aria-label={t(
- "watchedFolders.actions.downloadInput",
- "Download input",
- )}
- >
- <Icon name="download" size={"0.875rem"} />
- </ActionIcon>
- </Box>
- )}
- {/* Output files (stored in IDB) */}
- {outputs.map((out) => (
- <Box
- key={out.fileId}
- style={{
- display: "flex",
- alignItems: "center",
- gap: "0.5rem",
- padding: "0.2rem 0",
- }}
- >
- <Text
- style={{
- fontSize: "0.625rem",
- letterSpacing: "0.04em",
- color: "var(--color-green-500)",
- textTransform: "uppercase",
- flexShrink: 0,
- }}
- >
- {t(
- "watchedFolders.workbench.directionOut",
- "out",
- )}
- </Text>
- <Text
- size="xs"
- style={{ flex: 1, minWidth: 0 }}
- lineClamp={1}
- >
- {out.name}
- </Text>
- <Text
- size="xs"
- c="dimmed"
- style={{ flexShrink: 0 }}
- >
- {formatBytes(out.size)}
- </Text>
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- handleView(out);
- }}
- aria-label={t(
- "watchedFolders.workbench.previewOutput",
- "Preview output",
- )}
- >
- <Icon name="eye" size={"0.875rem"} />
- </ActionIcon>
- <ActionIcon
- variant="tertiary"
- size="sm"
- onClick={(e) => {
- e.stopPropagation();
- handleDownload(out, out.name);
- }}
- aria-label={t(
- "watchedFolders.actions.downloadOutput",
- "Download output",
- )}
- >
- <Icon name="download" size={"0.875rem"} />
- </ActionIcon>
- </Box>
- ))}
- {/* Error detail + retry */}
- {status === "error" && (
- <Box
- style={{
- display: "flex",
- alignItems: "flex-start",
- gap: "0.5rem",
- paddingTop: "0.25rem",
- }}
- >
- {meta?.errorMessage && (
- <Text
- size="xs"
- c="var(--color-red-dark)"
- style={{
- flex: 1,
- minWidth: 0,
- wordBreak: "break-word",
- opacity: 0.85,
- fontFamily: "monospace",
- fontSize: "0.6875rem",
- }}
- >
- {meta.errorMessage}
- </Text>
- )}
- {inputFile && (
- <Button
- size="sm"
- variant="secondary"
- style={{ flexShrink: 0 }}
- leftSection={
- <Icon
- name="rotate-ccw"
- size={"0.75rem"}
- />
- }
- onClick={(e) => {
- e.stopPropagation();
- updateFileMetadata(fileId, {
- status: "pending",
- errorMessage: undefined,
- });
- runPipeline(
- folder,
- inputFile,
- fileId,
- folderRecord?.files[fileId]
- ?.ownedByFolder ?? false,
- );
- }}
- >
- {t("watchedFolders.actions.retry", "Retry")}
- </Button>
- )}
- </Box>
- )}
- {status === "processing" && (
- <Group gap="xs">
- <Loader size={8} />
- <Text size="xs" c="dimmed">
- {t(
- "watchedFolders.status.processing",
- "Processing…",
- )}
- </Text>
- </Group>
- )}
- {status === "pending" && (
- <Text size="xs" c="dimmed">
- {t(
- "watchedFolders.workbench.queuedWaiting",
- "Queued — waiting to run",
- )}
- </Text>
- )}
- </Box>
- )}
- </Box>
- );
- })}
- </>
- )}
- </Stack>
- </ScrollArea>
- </Box>
- </Box>
-
- {/* Stats modal */}
- <CardExpansionModal
- phase={statsModalPhase}
- cardRect={statsCardRect}
- textExpanded={statsTextExpanded}
- onClose={closeStatsModal}
- icon={
- <Icon
- name="rotate-ccw-clock"
- size={"1.125rem"}
- style={{ color: "var(--mantine-color-dimmed)" }}
- />
- }
- count={daysRunning !== null && daysRunning > 0 ? daysRunning : 0}
- labelSingular={t("watchedFolders.workbench.dayRunning", "day running")}
- labelPlural={t("watchedFolders.workbench.daysRunning", "days running")}
- widthRem={72}
- heightRem={48}
- fillHeight
- toolbar={
- <Box style={{ padding: "0.625rem 0.75rem" }}>
- <Group gap="0.375rem">
- {(["24h", "7d", "30d", "all"] as const).map((p) => (
- <Button
- key={p}
- size="sm"
- variant={statsPeriod === p ? "secondary" : "tertiary"}
- onClick={() => setStatsPeriod(p)}
- >
- {p === "all"
- ? t("watchedFolders.workbench.allTime", "All time")
- : p}
- </Button>
- ))}
- </Group>
- </Box>
- }
- >
- <Stack gap="lg" style={{ flex: 1, minHeight: 0 }}>
- {/* Stat numbers */}
- <Group gap="xl">
- <Box>
- <Text
- style={{ fontSize: "0.625rem", letterSpacing: "0.05em" }}
- c="dimmed"
- tt="uppercase"
- fw={600}
- >
- {t("watchedFolders.status.done", "Done")}
- </Text>
- <Text size="xl" fw={800} c="var(--color-green-500)">
- {dashboardStats.processed}
- </Text>
- </Box>
- {dashboardStats.failed > 0 && (
- <Box>
- <Text
- style={{ fontSize: "0.625rem", letterSpacing: "0.05em" }}
- c="dimmed"
- tt="uppercase"
- fw={600}
- >
- {t("watchedFolders.workbench.failed", "Failed")}
- </Text>
- <Text size="xl" fw={800} c="var(--color-red-dark)">
- {dashboardStats.failed}
- </Text>
- </Box>
- )}
- {dashboardStats.pending > 0 && (
- <Box>
- <Text
- style={{ fontSize: "0.625rem", letterSpacing: "0.05em" }}
- c="dimmed"
- tt="uppercase"
- fw={600}
- >
- {t("watchedFolders.workbench.queued", "Queued")}
- </Text>
- <Text size="xl" fw={800}>
- {dashboardStats.pending}
- </Text>
- </Box>
- )}
- {dashboardStats.totalIn > 0 && (
- <Box>
- <Text
- style={{ fontSize: "0.625rem", letterSpacing: "0.05em" }}
- c="dimmed"
- tt="uppercase"
- fw={600}
- >
- {t("watchedFolders.workbench.inputSize", "Input size")}
- </Text>
- <Text size="xl" fw={800}>
- {formatBytes(dashboardStats.totalIn)}
- </Text>
- </Box>
- )}
- {dashboardStats.saved > 0 && (
- <Box>
- <Text
- style={{ fontSize: "0.625rem", letterSpacing: "0.05em" }}
- c="dimmed"
- tt="uppercase"
- fw={600}
- >
- {t("watchedFolders.workbench.dataSaved", "Saved")}
- </Text>
- <Text size="xl" fw={800} c="var(--color-green-500)">
- ↓ {formatBytes(dashboardStats.saved)}
- </Text>
- </Box>
- )}
- </Group>
-
- {/* Bar chart */}
- {(() => {
- const isHourly = statsPeriod === "24h";
- const bucketMs2 = isHourly ? 3_600_000 : 86_400_000;
- const count = dashboardStats.buckets.length;
- const nowMs = Date.now();
- const stride = isHourly ? 6 : statsPeriod === "7d" ? 1 : 5;
- const bucketLabel = (i: number) => {
- const ts = nowMs - (count - 1 - i) * bucketMs2;
- const d = new Date(ts);
- if (isHourly) {
- const h = d.getHours();
- if (h === 0)
- return `${d.getDate()} ${d.toLocaleDateString("en", { month: "short" })}`;
- return h < 12 ? `${h}am` : h === 12 ? "12pm" : `${h - 12}pm`;
- }
- if (statsPeriod === "7d")
- return d.toLocaleDateString("en", { weekday: "short" });
- return `${d.getDate()} ${d.toLocaleDateString("en", { month: "short" })}`;
- };
- const bucketTooltipLabel = (
- i: number,
- b: { processed: number; failed: number },
- ) => {
- const ts = nowMs - (count - 1 - i) * bucketMs2;
- const d = new Date(ts);
- let dateStr: string;
- if (isHourly) {
- const h = d.getHours();
- const hEnd = (h + 1) % 24;
- const fmt = (n: number) =>
- n === 0
- ? "12am"
- : n < 12
- ? `${n}am`
- : n === 12
- ? "12pm"
- : `${n - 12}pm`;
- dateStr = `${fmt(h)} – ${fmt(hEnd)}, ${d.getDate()} ${d.toLocaleDateString("en", { month: "short" })}`;
- } else if (statsPeriod === "7d") {
- dateStr = d.toLocaleDateString("en", {
- weekday: "long",
- day: "numeric",
- month: "short",
- });
- } else {
- dateStr = d.toLocaleDateString("en", {
- weekday: "short",
- day: "numeric",
- month: "short",
- year: "numeric",
- });
- }
- return `${dateStr}\n${t("watchedFolders.workbench.chartTooltipComplete", { count: b.processed, defaultValue: `${b.processed} complete` })} ${t("watchedFolders.workbench.chartTooltipFailed", { count: b.failed, defaultValue: `${b.failed} failed` })}`;
- };
- const yMax = Math.max(dashboardStats.maxBucket, 10);
- const yTicks = [
- yMax,
- Math.round(yMax * 0.75),
- Math.round(yMax * 0.5),
- Math.round(yMax * 0.25),
- 0,
- ];
- const yAxisWidth = `${Math.max(...yTicks.map((v) => String(v).length)) * 0.5 + 0.25}rem`;
- return (
- <Box
- style={{
- flex: 1,
- minHeight: 0,
- display: "flex",
- flexDirection: "column",
- }}
- >
- <Text size="xs" c="dimmed" mb="0.5rem">
- {t(
- "watchedFolders.workbench.filesProcessedOverTime",
- "Files processed over time",
- )}
- </Text>
- <div
- style={{
- flex: 1,
- minHeight: 0,
- display: "flex",
- gap: "0.5rem",
- }}
- >
- {/* Y-axis labels */}
- <div
- style={{
- display: "flex",
- flexDirection: "column",
- justifyContent: "space-between",
- alignItems: "flex-end",
- flexShrink: 0,
- width: yAxisWidth,
- paddingBottom: "0.0625rem",
- }}
- >
- {yTicks.map((v, i) => (
- <Text
- key={i}
- style={{ fontSize: "0.625rem", lineHeight: 1 }}
- c="dimmed"
- >
- {v}
- </Text>
- ))}
- </div>
- {/* Bars + gridlines */}
- <div
- style={{
- flex: 1,
- position: "relative",
- borderBottom: "0.0625rem solid var(--c-border-subtle)",
- }}
- >
- {[0, 25, 50, 75].map((pct) => (
- <div
- key={pct}
- style={{
- position: "absolute",
- top: `${pct}%`,
- left: 0,
- right: 0,
- borderTop: "0.0625rem dashed var(--c-border-subtle)",
- pointerEvents: "none",
- }}
- />
- ))}
- <div
- style={{
- display: "flex",
- alignItems: "flex-end",
- gap: "2px",
- height: "100%",
- }}
- onMouseMove={(e) => {
- const rect = e.currentTarget.getBoundingClientRect();
- const relX = e.clientX - rect.left;
- const relY = e.clientY - rect.top;
- const i = Math.min(
- Math.floor((relX / rect.width) * count),
- count - 1,
- );
- setChartHover({ i, relX, relY });
- }}
- onMouseLeave={() => setChartHover(null)}
- >
- {chartHover &&
- (() => {
- const b = dashboardStats.buckets[chartHover.i];
- const label = bucketTooltipLabel(chartHover.i, b);
- const flipLeft = chartHover.relX > 200;
- return (
- <div
- style={{
- position: "absolute",
- left: flipLeft
- ? undefined
- : chartHover.relX + 12,
- right: flipLeft
- ? `calc(100% - ${chartHover.relX}px + 12px)`
- : undefined,
- top: Math.max(chartHover.relY - 36, 4),
- backgroundColor: "var(--c-bg-raised)",
- border:
- "0.0625rem solid var(--c-border-subtle)",
- borderRadius: "var(--mantine-radius-sm)",
- padding: "0.3rem 0.5rem",
- pointerEvents: "none",
- zIndex: 10,
- whiteSpace: "pre-line",
- fontSize: "0.75rem",
- lineHeight: 1.5,
- boxShadow: "0 2px 8px rgba(0,0,0,0.18)",
- }}
- >
- {label}
- </div>
- );
- })()}
- {dashboardStats.buckets.map((b, i) => {
- const total = b.processed + b.failed;
- const h =
- total === 0 ? 0 : Math.max((total / yMax) * 100, 2);
- return (
- <div
- key={i}
- style={{
- flex: 1,
- height: `${Math.max(h, total > 0 ? 2 : 0)}%`,
- display: "flex",
- flexDirection: "column",
- borderRadius: "2px 2px 0 0",
- overflow: "hidden",
- cursor: "default",
- }}
- >
- {b.failed > 0 && (
- <div
- style={{
- flex: b.failed,
- backgroundColor: "var(--color-red-500)",
- minHeight: "2px",
- }}
- />
- )}
- {b.processed > 0 && (
- <div
- style={{
- flex: b.processed,
- backgroundColor: "var(--color-green-500)",
- minHeight: "2px",
- }}
- />
- )}
- </div>
- );
- })}
- </div>
- </div>
- </div>
- {/* X-axis labels */}
- <div
- style={{
- display: "flex",
- gap: "2px",
- marginTop: "0.25rem",
- paddingLeft: `calc(${yAxisWidth} + 0.5rem)`,
- }}
- >
- {dashboardStats.buckets.map((_, i) => (
- <div
- key={i}
- style={{
- flex: 1,
- textAlign: "center",
- overflow: "hidden",
- }}
- >
- {i % stride === 0 && (
- <Text
- style={{
- fontSize: "0.6875rem",
- whiteSpace: "nowrap",
- }}
- c="dimmed"
- >
- {bucketLabel(i)}
- </Text>
- )}
- </div>
- ))}
- </div>
- <Group gap="md" mt="0.625rem">
- <Group gap="0.3rem">
- <div
- style={{
- width: "0.5rem",
- height: "0.5rem",
- borderRadius: "2px",
- backgroundColor: "var(--color-green-500)",
- }}
- />
- <Text size="xs" c="dimmed">
- {t("watchedFolders.workbench.legendComplete", "Complete")}
- </Text>
- </Group>
- <Group gap="0.3rem">
- <div
- style={{
- width: "0.5rem",
- height: "0.5rem",
- borderRadius: "2px",
- backgroundColor: "var(--color-red-500)",
- }}
- />
- <Text size="xs" c="dimmed">
- {t("watchedFolders.workbench.failed", "Failed")}
- </Text>
- </Group>
- </Group>
- </Box>
- );
- })()}
- </Stack>
- </CardExpansionModal>
-
- <FilePreviewModal
- fileId={previewFileId}
- file={previewFile}
- fileName={previewFileName}
- onClose={() => {
- setPreviewFileId(null);
- setPreviewFile(null);
- }}
- />
-
- {/* Delete confirmation */}
- <Modal
- opened={!!deleteConfirm}
- onClose={() => setDeleteConfirm(null)}
- title={
- deleteConfirm && deleteConfirm.ids.length === 1
- ? t("watchedFolders.workbench.removeEntry", "Remove entry")
- : t("watchedFolders.workbench.removeEntries", {
- count: deleteConfirm?.ids.length ?? 0,
- defaultValue: `Remove ${deleteConfirm?.ids.length ?? 0} entries`,
- })
- }
- zIndex={Z_INDEX_OVER_FILE_MANAGER_MODAL}
- >
- <Stack gap="md">
- <Text size="sm" c="dimmed">
- {t(
- "watchedFolders.workbench.deleteConfirmBody",
- "Remove notifications only clears the activity log. Delete outputs also removes the processed files from storage. Your original input files are never touched.",
- )}
- </Text>
- <Group justify="flex-end">
- <Button variant="secondary" onClick={() => setDeleteConfirm(null)}>
- {t("watchedFolders.workbench.cancel", "Cancel")}
- </Button>
- <Button
- variant="secondary"
- onClick={() =>
- deleteConfirm && void execDelete(deleteConfirm.ids, false)
- }
- >
- {t(
- "watchedFolders.workbench.removeNotificationsOnly",
- "Remove notifications only",
- )}
- </Button>
- <Button
- variant="primary"
- accent="danger"
- onClick={() =>
- deleteConfirm && void execDelete(deleteConfirm.ids, true)
- }
- >
- {t("watchedFolders.workbench.deleteOutputs", "Delete outputs")}
- </Button>
- </Group>
- </Stack>
- </Modal>
- </Box>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolders.css b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolders.css
deleted file mode 100644
index bb87349198..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFolders.css
+++ /dev/null
@@ -1,238 +0,0 @@
-/* Watched Folders home-page card grid.
- *
- * Mirrors the files-page card vocabulary (see filesPage/FilesPage.css) but
- * with its own `.wf-*` namespace so the two surfaces can evolve
- * independently. Values are intentionally copied rather than shared. */
-
-@keyframes wf-pulse {
- 0%,
- 100% {
- opacity: 1;
- transform: scale(1);
- }
- 50% {
- opacity: 0.35;
- transform: scale(0.7);
- }
-}
-
-.wf-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr));
- gap: 1rem;
-}
-
-.wf-card {
- position: relative;
- display: flex;
- flex-direction: column;
- background: var(--c-surface);
- border: 1px solid var(--c-border-subtle);
- border-radius: 0.85rem;
- overflow: hidden;
- cursor: pointer;
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
- transition:
- transform 0.16s cubic-bezier(0.32, 0.72, 0.32, 1),
- border-color 0.14s ease,
- box-shadow 0.18s ease;
-}
-
-.wf-card:hover {
- transform: translateY(-2px);
- border-color: color-mix(
- in srgb,
- var(--c-primary) 35%,
- var(--c-border-subtle)
- );
- box-shadow:
- 0 4px 6px -1px rgba(0, 0, 0, 0.08),
- 0 8px 24px -8px rgba(0, 0, 0, 0.18);
-}
-
-.wf-card:focus-visible {
- outline: 2px solid var(--c-primary);
- outline-offset: 2px;
-}
-
-.wf-card.is-drop-target {
- background: color-mix(in srgb, var(--c-primary) 10%, var(--c-surface));
- box-shadow: 0 0 0 2px var(--c-primary);
- border-color: var(--c-primary);
-}
-
-/* Dragging a file the folder already contains — signal it's a no-op, not an add. */
-.wf-card.is-already-member {
- background: color-mix(in srgb, var(--c-warning) 8%, var(--c-surface));
- box-shadow: 0 0 0 2px var(--c-warning);
- border-color: var(--c-warning);
-}
-
-.wf-card-drag-message {
- position: absolute;
- inset: 0;
- z-index: 3;
- display: flex;
- align-items: center;
- justify-content: center;
- text-align: center;
- padding: 0.5rem;
- font-size: 0.8rem;
- font-weight: 600;
- color: var(--c-text);
- background: color-mix(in srgb, var(--c-surface) 72%, transparent);
- backdrop-filter: blur(1px);
- border-radius: inherit;
- /* Let drag/drop events pass through to the card underneath. */
- pointer-events: none;
-}
-
-.wf-card-thumb {
- display: flex;
- align-items: center;
- justify-content: center;
- background: linear-gradient(
- 180deg,
- color-mix(in srgb, var(--c-text-subtle) 5%, var(--c-surface)),
- var(--c-surface)
- );
- aspect-ratio: 1.6 / 1;
- padding: 0.75rem;
-}
-
-.wf-card-body {
- padding: 0.65rem 0.85rem 0.7rem;
- display: flex;
- flex-direction: column;
- gap: 0.25rem;
- min-width: 0;
-}
-
-.wf-card-name {
- font-size: 0.9rem;
- font-weight: 600;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- color: var(--c-text);
- letter-spacing: -0.005em;
-}
-
-.wf-card-meta {
- font-size: 0.76rem;
- color: var(--c-text-subtle);
- display: flex;
- align-items: center;
- gap: 0.4rem;
-}
-
-.wf-card-status-dot {
- width: 0.5rem;
- height: 0.5rem;
- border-radius: 50%;
- flex-shrink: 0;
-}
-
-.wf-card-status-dot.is-pulsing {
- animation: wf-pulse 1.4s ease-in-out infinite;
-}
-
-.wf-card-actions {
- position: absolute;
- top: 0.4rem;
- right: 0.4rem;
- opacity: 0;
- transition: opacity 0.12s ease;
- z-index: 4;
- display: flex;
- gap: 0.15rem;
-}
-
-.wf-card:hover .wf-card-actions,
-.wf-card:focus-within .wf-card-actions {
- opacity: 1;
-}
-
-/* "New folder" tile - a dashed call-to-action that sits in the grid
- alongside the real folder cards. */
-.wf-new-tile {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 0.5rem;
- text-align: center;
- background: var(--c-surface);
- border: 1.5px dashed var(--c-border-subtle);
- border-radius: 0.85rem;
- padding: 1rem;
- cursor: pointer;
- color: var(--c-text-subtle);
- min-height: 9rem;
- transition:
- border-color 0.14s ease,
- color 0.14s ease,
- background-color 0.14s ease;
-}
-
-.wf-new-tile:hover {
- border-color: var(--c-primary);
- color: var(--c-accent-text);
- background: color-mix(in srgb, var(--c-primary) 6%, var(--c-surface));
-}
-
-.wf-new-tile-icon {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 3rem;
- height: 3rem;
- border-radius: 50%;
- background: color-mix(in srgb, var(--c-primary) 12%, transparent);
- color: var(--c-accent-text);
-}
-
-.wf-empty {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 0.75rem;
- padding: 4rem 1.5rem;
- color: var(--c-text-subtle);
- text-align: center;
-}
-
-.wf-empty-icon {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 5rem;
- height: 5rem;
- border-radius: 50%;
- background: color-mix(in srgb, var(--c-primary) 12%, transparent);
- color: var(--c-accent-text);
- margin-bottom: 0.25rem;
-}
-
-.wf-empty-title {
- font-size: 1.15rem;
- color: var(--c-text);
- font-weight: 600;
- letter-spacing: -0.01em;
-}
-
-.wf-empty-hint {
- font-size: 0.9rem;
- color: var(--c-text-subtle);
- max-width: 30rem;
- line-height: 1.5;
-}
-
-@media (prefers-reduced-motion: reduce) {
- .wf-card,
- .wf-card:hover {
- transform: none;
- transition: none;
- }
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFoldersRegistration.tsx b/frontend/editor/src/proprietary/components/watchedFolders/WatchedFoldersRegistration.tsx
deleted file mode 100644
index a0249163db..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/WatchedFoldersRegistration.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useEffect, useRef } from "react";
-import { useTranslation } from "react-i18next";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { WatchedFolderWorkbenchView } from "@app/components/watchedFolders/WatchedFolderWorkbenchView";
-import { seedDefaultFolders } from "@app/data/watchedFolderPresets";
-import { useWatchedFolderUrlSync } from "@app/hooks/useWatchedFolderUrlSync";
-import {
- WATCHED_FOLDER_VIEW_ID,
- WATCHED_FOLDER_WORKBENCH_ID,
-} from "@app/components/watchedFolders/watchedFolderShared";
-
-export default function WatchedFoldersRegistration() {
- const { t } = useTranslation();
- const {
- registerCustomWorkbenchView,
- unregisterCustomWorkbenchView,
- clearCustomWorkbenchViewData,
- } = useToolWorkflow();
- useWatchedFolderUrlSync();
-
- // Keep refs to latest cleanup callbacks so the registration effect doesn't
- // re-run (and tear down) when unregisterCustomWorkbenchView changes identity
- // due to NavigationContext re-renders.
- const unregisterRef = useRef(unregisterCustomWorkbenchView);
- const clearRef = useRef(clearCustomWorkbenchViewData);
- useEffect(() => {
- unregisterRef.current = unregisterCustomWorkbenchView;
- });
- useEffect(() => {
- clearRef.current = clearCustomWorkbenchViewData;
- });
-
- useEffect(() => {
- seedDefaultFolders();
- }, []);
-
- useEffect(() => {
- registerCustomWorkbenchView({
- id: WATCHED_FOLDER_VIEW_ID,
- workbenchId: WATCHED_FOLDER_WORKBENCH_ID,
- label: t("watchedFolders.sidebarTitle", "Watched Folders"),
- component: WatchedFolderWorkbenchView,
- // Show the standard workbench bar (view switcher) so users can navigate
- // back to Viewer / Active Files instead of being stranded in this view.
- hideTopControls: false,
- hideToolPanel: true,
- });
- return () => {
- clearRef.current(WATCHED_FOLDER_VIEW_ID);
- unregisterRef.current(WATCHED_FOLDER_VIEW_ID);
- };
- }, [registerCustomWorkbenchView]);
-
- return null;
-}
diff --git a/frontend/editor/src/proprietary/components/watchedFolders/watchedFolderShared.ts b/frontend/editor/src/proprietary/components/watchedFolders/watchedFolderShared.ts
deleted file mode 100644
index 3e8221d185..0000000000
--- a/frontend/editor/src/proprietary/components/watchedFolders/watchedFolderShared.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-// Leaf module for the watched-folders trio (registration, workbench view, home
-// page): the shared view IDs plus small pure formatters. Kept dependency-free so
-// those three components don't have to import one another and form a cycle.
-import type { TFunction } from "i18next";
-
-export const WATCHED_FOLDER_VIEW_ID = "watchedFolder";
-export const WATCHED_FOLDER_WORKBENCH_ID = "custom:watchedFolder" as const;
-
-export function timeAgo(date: Date, t: TFunction): string {
- const secs = Math.floor((Date.now() - date.getTime()) / 1000);
- if (secs < 60) return t("watchedFolders.time.justNow", "just now");
- const mins = Math.floor(secs / 60);
- if (mins < 60)
- return t("watchedFolders.time.minutesAgo", {
- count: mins,
- defaultValue: `${mins}m ago`,
- });
- const hours = Math.floor(mins / 60);
- if (hours < 24)
- return t("watchedFolders.time.hoursAgo", {
- count: hours,
- defaultValue: `${hours}h ago`,
- });
- const days = Math.floor(hours / 24);
- return t("watchedFolders.time.daysAgo", {
- count: days,
- defaultValue: `${days}d ago`,
- });
-}
-
-export function humaniseOp(op: string): string {
- return op
- .replace(/-pdf$|-pages$|-documents?$/i, "")
- .replace(/[-_]/g, " ")
- .replace(/\bocr\b/gi, "OCR")
- .replace(/\b\w/g, (c) => c.toUpperCase())
- .trim();
-}
diff --git a/frontend/editor/src/proprietary/constants/featureFlags.ts b/frontend/editor/src/proprietary/constants/featureFlags.ts
index 84af388005..73a7d2077d 100644
--- a/frontend/editor/src/proprietary/constants/featureFlags.ts
+++ b/frontend/editor/src/proprietary/constants/featureFlags.ts
@@ -5,14 +5,5 @@
* values.
*/
-/**
- * Watched Folders — a proprietary feature whose implementation lives under
- * `proprietary/`. Still disabled for now; flip to `true` to surface it in the
- * proprietary build only. The core override stays `false`, so the shared
- * sidebar entry point never appears in the open-source build (which has no
- * Watched Folders implementation to navigate to).
- */
-export const WATCHED_FOLDERS_ENABLED: boolean = false;
-
// Refill an empty workbench from the tab's last session (survives the editor/processor switch).
export const WORKBENCH_SESSION_RESTORE: boolean = true;
diff --git a/frontend/editor/src/proprietary/contexts/FolderFileContext.tsx b/frontend/editor/src/proprietary/contexts/FolderFileContext.tsx
deleted file mode 100644
index 0e394de444..0000000000
--- a/frontend/editor/src/proprietary/contexts/FolderFileContext.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import { createContext, useContext, useState, ReactNode } from "react";
-import { useFolderData } from "@app/hooks/useFolderData";
-import { FolderFileMetadata, FolderRecord } from "@app/types/watchedFolders";
-
-interface FolderFileContextValue {
- activeFolderId: string | null;
- setActiveFolderId: (id: string | null) => void;
- folderRecord: FolderRecord | null;
- fileIds: string[];
- pendingFileIds: string[];
- processingFileIds: string[];
- processedFileIds: string[];
- addFile: (
- fileId: string,
- metadata?: Partial<FolderFileMetadata>,
- ) => Promise<void>;
- removeFile: (fileId: string) => Promise<void>;
- updateFileMetadata: (
- fileId: string,
- updates: Partial<FolderFileMetadata>,
- ) => Promise<void>;
- clearFolder: () => Promise<void>;
- getFileMetadata: (fileId: string) => FolderFileMetadata | null;
- isFileProcessed: (fileId: string) => boolean;
- isFileProcessing: (fileId: string) => boolean;
-}
-
-const FolderFileContext = createContext<FolderFileContextValue | null>(null);
-
-interface FolderFileContextProviderProps {
- children: ReactNode;
-}
-
-// Inner component so useFolderData is only called once activeFolderId is set
-function FolderFileContextInner({
- activeFolderId,
- setActiveFolderId,
- children,
-}: {
- activeFolderId: string | null;
- setActiveFolderId: (id: string | null) => void;
- children: ReactNode;
-}) {
- const folderData = useFolderData(activeFolderId ?? "");
- return (
- <FolderFileContext.Provider
- value={{ activeFolderId, setActiveFolderId, ...folderData }}
- >
- {children}
- </FolderFileContext.Provider>
- );
-}
-
-export function FolderFileContextProvider({
- children,
-}: FolderFileContextProviderProps) {
- const [activeFolderId, setActiveFolderId] = useState<string | null>(null);
- return (
- <FolderFileContextInner
- activeFolderId={activeFolderId}
- setActiveFolderId={setActiveFolderId}
- >
- {children}
- </FolderFileContextInner>
- );
-}
-
-export function useFolderFileContext(): FolderFileContextValue {
- const ctx = useContext(FolderFileContext);
- if (!ctx)
- throw new Error(
- "useFolderFileContext must be used within FolderFileContextProvider",
- );
- return ctx;
-}
diff --git a/frontend/editor/src/proprietary/data/watchedFolderPresets.ts b/frontend/editor/src/proprietary/data/watchedFolderPresets.ts
deleted file mode 100644
index ac5dc858c0..0000000000
--- a/frontend/editor/src/proprietary/data/watchedFolderPresets.ts
+++ /dev/null
@@ -1,120 +0,0 @@
-/**
- * Default Watched Folder presets — seeded once on first run
- */
-
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { AutomationConfig } from "@app/types/automation";
-import { automationStorage } from "@app/services/automationStorage";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-
-const SEEDED_FLAG = "watched_folders_seeded";
-let seedingInProgress = false;
-
-interface PresetDefinition {
- folder: Omit<
- WatchedFolder,
- "id" | "automationId" | "createdAt" | "updatedAt"
- >;
- automation: Omit<AutomationConfig, "id" | "createdAt" | "updatedAt">;
-}
-
-const PRESETS: PresetDefinition[] = [
- {
- folder: {
- name: "Secure Ingestion",
- description: "Sanitize and flatten all incoming PDFs",
- icon: "SecurityIcon",
- accentColor: "#9333ea",
- order: 0,
- isDefault: true,
- },
- automation: {
- name: "Secure Ingestion",
- description: "Sanitize then flatten PDF to remove hidden data",
- icon: "SecurityIcon",
- operations: [
- { operation: "sanitize", parameters: {} },
- { operation: "flatten", parameters: {} },
- ],
- },
- },
- {
- folder: {
- name: "Pre-publish",
- description: "Sanitize and compress before publishing",
- icon: "CloudIcon",
- accentColor: "#0ea5e9",
- order: 1,
- isDefault: true,
- },
- automation: {
- name: "Pre-publish",
- description: "Sanitize and compress PDF for publication",
- icon: "CloudIcon",
- operations: [
- { operation: "sanitize", parameters: {} },
- { operation: "compress", parameters: {} },
- ],
- },
- },
- {
- folder: {
- name: "Email Prep",
- description: "Compress then sanitize for email distribution",
- icon: "CompressIcon",
- accentColor: "#14b8a6",
- order: 2,
- isDefault: true,
- },
- automation: {
- name: "Email Prep",
- description: "Compress then sanitize PDF for email",
- icon: "CompressIcon",
- operations: [
- { operation: "compress", parameters: {} },
- { operation: "sanitize", parameters: {} },
- ],
- },
- },
- {
- folder: {
- name: "Rotate & Optimise",
- description: "Auto-rotate pages and compress",
- icon: "RotateRightIcon",
- accentColor: "#f97316",
- order: 3,
- isDefault: true,
- },
- automation: {
- name: "Rotate & Optimise",
- description: "Rotate pages and compress PDF",
- icon: "RotateRightIcon",
- operations: [
- { operation: "rotate", parameters: { angle: 90 } },
- { operation: "compress", parameters: {} },
- ],
- },
- },
-];
-
-export async function seedDefaultFolders(): Promise<void> {
- if (localStorage.getItem(SEEDED_FLAG) || seedingInProgress) return;
- seedingInProgress = true;
-
- try {
- for (const preset of PRESETS) {
- const savedAutomation = await automationStorage.saveAutomation(
- preset.automation,
- );
- await watchedFolderStorage.createFolder({
- ...preset.folder,
- automationId: savedAutomation.id,
- });
- }
- localStorage.setItem(SEEDED_FLAG, "true");
- } catch (error) {
- console.error("Failed to seed default smart folders:", error);
- } finally {
- seedingInProgress = false;
- }
-}
diff --git a/frontend/editor/src/proprietary/hooks/useFolderAutomation.ts b/frontend/editor/src/proprietary/hooks/useFolderAutomation.ts
deleted file mode 100644
index c68af00622..0000000000
--- a/frontend/editor/src/proprietary/hooks/useFolderAutomation.ts
+++ /dev/null
@@ -1,416 +0,0 @@
-/**
- * Shared hook for running a file through a Watched Folder's automation pipeline.
- *
- * Local-only synchronous execution: each file is run through executeAutomationSequence
- * and the outputs are persisted to IndexedDB. Retries are scheduled in
- * folderRetryScheduleStorage and drained on mount / visibility / SW wake.
- *
- * Async server-side jobs and server watched folders are handled in a follow-up PR.
- */
-
-import { useCallback, useEffect, useRef } from "react";
-import { ToolRegistry } from "@app/data/toolsTaxonomy";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { automationStorage } from "@app/services/automationStorage";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-import { fileStorage } from "@app/services/fileStorage";
-import { folderRunStateStorage } from "@app/services/folderRunStateStorage";
-import { folderRetryScheduleStorage } from "@app/services/folderRetryScheduleStorage";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-import { executeAutomationSequence } from "@app/utils/automationExecutor";
-import { folderDirectoryHandleStorage } from "@app/services/folderDirectoryHandleStorage";
-import {
- FileId,
- StirlingFileStub,
- createFileId,
- createStirlingFile,
- createQuickKey,
- isStirlingFile,
-} from "@app/types/fileContext";
-
-/**
- * Resolves the storage ID for an input file.
- * - StirlingFiles (already in fileStorage): returns the existing fileId, ownedByFolder=false.
- * - Fresh disk drops: creates a new stub in fileStorage, returns new ID, ownedByFolder=true.
- */
-export async function resolveInputFile(
- file: File,
-): Promise<{ inputFileId: string; ownedByFolder: boolean }> {
- if (isStirlingFile(file)) {
- return { inputFileId: file.fileId, ownedByFolder: false };
- }
- const newFileId = createFileId();
- const stub: StirlingFileStub = {
- id: newFileId,
- name: file.name,
- type: file.type || "application/pdf",
- size: file.size,
- lastModified: file.lastModified,
- isLeaf: true,
- originalFileId: newFileId,
- versionNumber: 1,
- toolHistory: [],
- quickKey: createQuickKey(file),
- createdAt: Date.now(),
- };
- await fileStorage.storeStirlingFile(
- createStirlingFile(file, newFileId),
- stub,
- );
- return { inputFileId: newFileId, ownedByFolder: true };
-}
-
-/** Fire-and-forget: tell the service worker a new retry has been scheduled. */
-function notifySW(message: { type: string }): void {
- navigator.serviceWorker?.controller?.postMessage(message);
-}
-
-/**
- * Stores pipeline output files, updates folder metadata, and cleans up superseded outputs.
- */
-async function finalizeRun(
- folder: WatchedFolder,
- file: File,
- inputFileId: string,
- ownedByFolder: boolean,
- resultFiles: File[],
-): Promise<void> {
- const currentFolderData = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- const currentMeta = currentFolderData?.files[inputFileId];
- const prevOutputIds: string[] =
- currentMeta?.displayFileIds ??
- (currentMeta?.displayFileId ? [currentMeta.displayFileId] : []);
-
- const inputStub = await fileStorage.getStirlingFileStub(
- inputFileId as FileId,
- );
- const isVersionMode = folder.outputMode === "new_version";
- const chainRoot = isVersionMode
- ? (inputStub?.originalFileId ?? inputFileId)
- : inputFileId;
- const versionNum = isVersionMode ? (inputStub?.versionNumber ?? 1) + 1 : 2;
-
- const inputName = inputStub?.name ?? file.name;
- const outputLabel = folder.outputName?.trim() || folder.name;
- const isAutoNumber =
- folder.outputNamePosition === "auto-number" && !isVersionMode;
-
- // Collect taken names for auto-number deduplication
- const takenNames = new Set<string>();
- if (isAutoNumber) {
- for (const meta of Object.values(currentFolderData?.files ?? {})) {
- const ids =
- meta.displayFileIds ?? (meta.displayFileId ? [meta.displayFileId] : []);
- for (const oid of ids) {
- const stub = await fileStorage.getStirlingFileStub(oid as FileId);
- if (stub?.name) takenNames.add(stub.name);
- }
- }
- }
-
- const allOutputIds: string[] = [];
-
- for (const resultFile of resultFiles) {
- let outputFileName: string;
- if (isVersionMode) {
- outputFileName = inputName;
- } else if (isAutoNumber) {
- const lastDot = inputName.lastIndexOf(".");
- const nameBase = lastDot > 0 ? inputName.slice(0, lastDot) : inputName;
- const ext = lastDot > 0 ? inputName.slice(lastDot) : "";
- if (!takenNames.has(inputName)) {
- outputFileName = inputName;
- } else {
- let n = 1;
- while (takenNames.has(`${nameBase} (${n})${ext}`)) n++;
- outputFileName = `${nameBase} (${n})${ext}`;
- }
- takenNames.add(outputFileName);
- } else {
- outputFileName =
- folder.outputNamePosition === "suffix"
- ? `${inputName}_${outputLabel}`
- : `${outputLabel}_${inputName}`;
- }
-
- const outputId = createFileId();
- allOutputIds.push(outputId);
- const outputStub: StirlingFileStub = {
- id: outputId,
- name: outputFileName,
- type: resultFile.type || "application/pdf",
- size: resultFile.size,
- lastModified: resultFile.lastModified,
- isLeaf: true,
- originalFileId: chainRoot,
- versionNumber: versionNum,
- parentFileId: inputFileId as FileId,
- toolHistory: [],
- quickKey: createQuickKey(resultFile),
- createdAt: Date.now(),
- };
- const renamedFile =
- outputFileName !== resultFile.name
- ? new File([resultFile], outputFileName, {
- type: resultFile.type,
- lastModified: resultFile.lastModified,
- })
- : resultFile;
- await fileStorage.storeStirlingFile(
- createStirlingFile(renamedFile, outputId),
- outputStub,
- );
-
- // Write to local FS output directory if configured
- if (folder.hasOutputDirectory) {
- try {
- const dirHandle = await folderDirectoryHandleStorage.get(folder.id);
- if (dirHandle) {
- const hasPermission =
- await folderDirectoryHandleStorage.ensurePermission(dirHandle);
- if (hasPermission) {
- await folderDirectoryHandleStorage.writeFile(
- dirHandle,
- outputFileName,
- renamedFile,
- );
- }
- }
- } catch {
- // Best-effort — FS write failure doesn't block the pipeline
- }
- }
- }
-
- // Delete stale outputs from a previous run (skip in auto-number mode — outputs accumulate)
- if (!isAutoNumber) {
- for (const oldId of prevOutputIds) {
- try {
- await fileStorage.deleteStirlingFile(oldId as FileId);
- } catch {
- /* ignore */
- }
- }
- }
-
- // In version mode the input is always superseded; otherwise only hide it when the folder owns it.
- if (isVersionMode || ownedByFolder) {
- await fileStorage.markFileAsProcessed(inputFileId as FileId);
- }
-
- const processedAt = new Date();
- const accumulatedIds = isAutoNumber
- ? [...prevOutputIds, ...allOutputIds]
- : allOutputIds;
- await watchedFolderFileStorage.updateFileMetadata(folder.id, inputFileId, {
- status: "processed",
- processedAt,
- displayFileId: accumulatedIds[0],
- displayFileIds: accumulatedIds,
- });
-
- await folderRunStateStorage.appendRunEntries(folder.id, [
- {
- inputFileId,
- displayFileId: accumulatedIds[0],
- displayFileIds: accumulatedIds,
- processedAt,
- status: "processed",
- },
- ]);
-}
-
-/**
- * Returns a `runPipeline` function that executes a Watched Folder's automation
- * against a single input file synchronously, persisting outputs and updating
- * folder metadata.
- */
-export function useFolderAutomation(toolRegistry: Partial<ToolRegistry>) {
- const processingRef = useRef<Set<string>>(new Set());
-
- const runPipeline = useCallback(
- async (
- folder: WatchedFolder,
- file: File,
- inputFileId: string,
- ownedByFolder: boolean,
- ): Promise<void> => {
- if (processingRef.current.has(inputFileId)) return;
- processingRef.current.add(inputFileId);
-
- try {
- const automation = await automationStorage.getAutomation(
- folder.automationId,
- );
- if (!automation) {
- await watchedFolderFileStorage.updateFileMetadata(
- folder.id,
- inputFileId,
- {
- status: "error",
- errorMessage: "Automation not found",
- },
- );
- return;
- }
-
- await watchedFolderFileStorage.updateFileMetadata(
- folder.id,
- inputFileId,
- {
- status: "processing",
- },
- );
-
- const resultFiles = await executeAutomationSequence(
- automation,
- [file],
- toolRegistry as ToolRegistry,
- );
- await finalizeRun(
- folder,
- file,
- inputFileId,
- ownedByFolder,
- resultFiles,
- );
- } catch (err: unknown) {
- const existing = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- const prev = existing?.files[inputFileId];
- const attempts = (prev?.failedAttempts ?? 0) + 1;
- const maxRetries = folder.maxRetries ?? 3;
- const retryDelayMs = (folder.retryDelayMinutes ?? 5) * 60_000;
- const willRetry =
- maxRetries > 0 && attempts < maxRetries && retryDelayMs > 0;
- const nextRetryAt = willRetry ? Date.now() + retryDelayMs : undefined;
-
- await watchedFolderFileStorage.updateFileMetadata(
- folder.id,
- inputFileId,
- {
- status: "error",
- errorMessage: err instanceof Error ? err.message : "Unknown error",
- failedAttempts: attempts,
- nextRetryAt,
- lastFailedAt: new Date(),
- },
- );
-
- if (willRetry) {
- await folderRetryScheduleStorage.schedule(
- folder.id,
- inputFileId,
- Date.now() + retryDelayMs,
- attempts,
- prev?.ownedByFolder ?? ownedByFolder,
- );
- notifySW({ type: "SCHEDULE_RETRY" });
- }
- } finally {
- // Safety net: if still 'processing', something went wrong
- try {
- const record = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- const fileMeta = record?.files[inputFileId];
- if (fileMeta?.status === "processing") {
- await watchedFolderFileStorage.updateFileMetadata(
- folder.id,
- inputFileId,
- {
- status: "error",
- errorMessage: "Processing failed unexpectedly",
- },
- );
- }
- } catch {
- // Best-effort
- }
- processingRef.current.delete(inputFileId);
- }
- },
- [toolRegistry],
- );
-
- // Drain due retries on mount, on SW notification, and on visibility restore.
- useEffect(() => {
- async function drainDueRetries() {
- const due = await folderRetryScheduleStorage.claimDue();
- for (const entry of due) {
- const freshFolder = await watchedFolderStorage.getFolder(
- entry.folderId,
- );
- if (!freshFolder || freshFolder.isPaused) continue;
- const freshFile = await fileStorage.getStirlingFile(
- entry.fileId as FileId,
- );
- if (!freshFile) continue;
- await watchedFolderFileStorage.updateFileMetadata(
- entry.folderId,
- entry.fileId,
- {
- status: "pending",
- nextRetryAt: undefined,
- },
- );
- void runPipeline(
- freshFolder,
- freshFile,
- entry.fileId,
- entry.ownedByFolder,
- );
- }
- }
-
- void drainDueRetries();
-
- if ("serviceWorker" in navigator) {
- navigator.serviceWorker
- .register("/sw-folder-retry.js", { scope: "/" })
- .catch((err) =>
- console.warn("Watched Folder retry SW registration failed:", err),
- );
- }
-
- function handleSWMessage(event: MessageEvent) {
- if (event.data?.type === "PROCESS_DUE_RETRIES") void drainDueRetries();
- }
- navigator.serviceWorker?.addEventListener("message", handleSWMessage);
-
- function handleVisibilityChange() {
- if (document.visibilityState === "visible") {
- void drainDueRetries();
- }
- }
- document.addEventListener("visibilitychange", handleVisibilityChange);
-
- return () => {
- navigator.serviceWorker?.removeEventListener("message", handleSWMessage);
- document.removeEventListener("visibilitychange", handleVisibilityChange);
- };
- }, [runPipeline]);
-
- /** Run multiple files through the pipeline concurrently. */
- const processBatch = useCallback(
- (
- folder: WatchedFolder,
- items: Array<{
- file: File;
- inputFileId: string;
- ownedByFolder: boolean;
- }>,
- ) =>
- Promise.all(
- items.map(({ file, inputFileId, ownedByFolder }) =>
- runPipeline(folder, file, inputFileId, ownedByFolder),
- ),
- ),
- [runPipeline],
- );
-
- return { runPipeline, processBatch };
-}
diff --git a/frontend/editor/src/proprietary/hooks/useFolderData.ts b/frontend/editor/src/proprietary/hooks/useFolderData.ts
deleted file mode 100644
index ef1e7e1b17..0000000000
--- a/frontend/editor/src/proprietary/hooks/useFolderData.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-/**
- * Hook for reading and managing files within a Watched Folder
- */
-
-import { useState, useEffect, useCallback, useMemo } from "react";
-import { FolderFileMetadata, FolderRecord } from "@app/types/watchedFolders";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-
-interface UseFolderDataReturn {
- folderRecord: FolderRecord | null;
- fileIds: string[];
- processingFileIds: string[];
- processedFileIds: string[];
- pendingFileIds: string[];
- addFile: (
- fileId: string,
- metadata?: Partial<FolderFileMetadata>,
- ) => Promise<void>;
- removeFile: (fileId: string) => Promise<void>;
- updateFileMetadata: (
- fileId: string,
- updates: Partial<FolderFileMetadata>,
- ) => Promise<void>;
- clearFolder: () => Promise<void>;
- getFileMetadata: (fileId: string) => FolderFileMetadata | null;
- isFileProcessed: (fileId: string) => boolean;
- isFileProcessing: (fileId: string) => boolean;
-}
-
-export function useFolderData(folderId: string): UseFolderDataReturn {
- const [folderRecord, setFolderRecord] = useState<FolderRecord | null>(null);
-
- const refresh = useCallback(async () => {
- if (!folderId) return;
- try {
- const record = await watchedFolderFileStorage.getFolderData(folderId);
- setFolderRecord(record);
- } catch (error) {
- console.error("Failed to load folder data:", error);
- }
- }, [folderId]);
-
- useEffect(() => {
- refresh();
- }, [refresh]);
-
- useEffect(() => {
- const unsubscribe = watchedFolderFileStorage.onFolderChange(
- (changedFolderId) => {
- if (changedFolderId === folderId) {
- refresh();
- }
- },
- );
- return unsubscribe;
- }, [folderId, refresh]);
-
- const files = folderRecord?.files ?? {};
- const fileIds = useMemo(() => Object.keys(files), [files]);
- const processingFileIds = useMemo(
- () => fileIds.filter((id) => files[id]?.status === "processing"),
- [fileIds, files],
- );
- const processedFileIds = useMemo(
- () => fileIds.filter((id) => files[id]?.status === "processed"),
- [fileIds, files],
- );
- const pendingFileIds = useMemo(
- () => fileIds.filter((id) => files[id]?.status === "pending"),
- [fileIds, files],
- );
-
- const addFile = useCallback(
- async (fileId: string, metadata?: Partial<FolderFileMetadata>) => {
- await watchedFolderFileStorage.addFileToFolder(
- folderId,
- fileId,
- metadata,
- );
- },
- [folderId],
- );
-
- const removeFile = useCallback(
- async (fileId: string) => {
- await watchedFolderFileStorage.removeFileFromFolder(folderId, fileId);
- },
- [folderId],
- );
-
- const updateFileMetadata = useCallback(
- async (fileId: string, updates: Partial<FolderFileMetadata>) => {
- await watchedFolderFileStorage.updateFileMetadata(
- folderId,
- fileId,
- updates,
- );
- },
- [folderId],
- );
-
- const clearFolder = useCallback(async () => {
- await watchedFolderFileStorage.clearFolder(folderId);
- }, [folderId]);
-
- const getFileMetadata = useCallback(
- (fileId: string): FolderFileMetadata | null => {
- return folderRecord?.files[fileId] ?? null;
- },
- [folderRecord],
- );
-
- const isFileProcessed = useCallback(
- (fileId: string) => folderRecord?.files[fileId]?.status === "processed",
- [folderRecord],
- );
-
- const isFileProcessing = useCallback(
- (fileId: string) => folderRecord?.files[fileId]?.status === "processing",
- [folderRecord],
- );
-
- return {
- folderRecord,
- fileIds,
- processingFileIds,
- processedFileIds,
- pendingFileIds,
- addFile,
- removeFile,
- updateFileMetadata,
- clearFolder,
- getFileMetadata,
- isFileProcessed,
- isFileProcessing,
- };
-}
diff --git a/frontend/editor/src/proprietary/hooks/useFolderOutputIds.ts b/frontend/editor/src/proprietary/hooks/useFolderOutputIds.ts
deleted file mode 100644
index 2ea7398fe4..0000000000
--- a/frontend/editor/src/proprietary/hooks/useFolderOutputIds.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * Returns the set of file IDs that are outputs produced by any watched folder automation.
- * Reactive: re-evaluates whenever folder records change.
- */
-
-import { useState, useEffect } from "react";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-import { useAllWatchedFolders } from "@app/hooks/useAllWatchedFolders";
-
-export function useFolderOutputIds(): Set<string> {
- const folders = useAllWatchedFolders();
- const [outputIds, setOutputIds] = useState<Set<string>>(new Set());
-
- useEffect(() => {
- if (folders.length === 0) {
- setOutputIds(new Set());
- return;
- }
-
- const load = async () => {
- const ids = new Set<string>();
- for (const folder of folders) {
- try {
- const record = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- if (record) {
- Object.values(record.files).forEach((meta) => {
- const oids =
- meta?.displayFileIds ??
- (meta?.displayFileId ? [meta.displayFileId] : []);
- oids.forEach((id) => ids.add(id));
- });
- }
- } catch {
- /* ignore individual folder failures */
- }
- }
- setOutputIds(ids);
- };
-
- load();
- return watchedFolderFileStorage.onFolderChange(load);
- }, [folders]);
-
- return outputIds;
-}
diff --git a/frontend/editor/src/proprietary/hooks/useFolderRunState.ts b/frontend/editor/src/proprietary/hooks/useFolderRunState.ts
deleted file mode 100644
index 2fcbfaec2a..0000000000
--- a/frontend/editor/src/proprietary/hooks/useFolderRunState.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Hook for managing Watched Folder run state (recent run entries)
- */
-
-import { useState, useEffect, useCallback } from "react";
-import { WatchedFolderRunEntry } from "@app/types/watchedFolders";
-import { folderRunStateStorage } from "@app/services/folderRunStateStorage";
-
-interface UseFolderRunStateReturn {
- recentRuns: WatchedFolderRunEntry[];
- setRecentRuns: (runs: WatchedFolderRunEntry[]) => Promise<void>;
- clearRecentRuns: () => Promise<void>;
- isLoading: boolean;
-}
-
-export function useFolderRunState(folderId: string): UseFolderRunStateReturn {
- const [recentRuns, setRecentRunsState] = useState<WatchedFolderRunEntry[]>(
- [],
- );
- const [isLoading, setIsLoading] = useState(true);
-
- // Subscribe before loading to close the race window between load completing
- // and the listener being established (writes in that gap would be missed).
- useEffect(() => {
- if (!folderId) return;
- setIsLoading(true);
- const unsub = folderRunStateStorage.onRunStateChange((changedFolderId) => {
- if (changedFolderId !== folderId) return;
- folderRunStateStorage
- .getFolderRunState(folderId)
- .then(setRecentRunsState)
- .catch((err) =>
- console.error("Failed to reload folder run state:", err),
- );
- });
- folderRunStateStorage
- .getFolderRunState(folderId)
- .then(setRecentRunsState)
- .catch((err) => console.error("Failed to load folder run state:", err))
- .finally(() => setIsLoading(false));
- return unsub;
- }, [folderId]);
-
- const setRecentRuns = useCallback(
- async (runs: WatchedFolderRunEntry[]) => {
- await folderRunStateStorage.setFolderRunState(folderId, runs);
- setRecentRunsState(runs);
- },
- [folderId],
- );
-
- const clearRecentRuns = useCallback(async () => {
- await folderRunStateStorage.clearFolderRunState(folderId);
- setRecentRunsState([]);
- }, [folderId]);
-
- return { recentRuns, setRecentRuns, clearRecentRuns, isLoading };
-}
diff --git a/frontend/editor/src/proprietary/hooks/useFolderRunStatuses.ts b/frontend/editor/src/proprietary/hooks/useFolderRunStatuses.ts
deleted file mode 100644
index 78f00b1fab..0000000000
--- a/frontend/editor/src/proprietary/hooks/useFolderRunStatuses.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-/**
- * Hook that derives per-folder run status from run state entries
- * 'done' automatically reverts to 'idle' after 5 minutes
- */
-
-import { useState, useEffect, useRef } from "react";
-import {
- WatchedFolder,
- WatchedFolderRunEntry,
-} from "@app/types/watchedFolders";
-import { folderRunStateStorage } from "@app/services/folderRunStateStorage";
-
-export type FolderRunStatus = "idle" | "processing" | "done";
-
-const DONE_TTL_MS = 5 * 60 * 1000;
-
-function deriveStatus(runs: WatchedFolderRunEntry[]): FolderRunStatus {
- if (runs.some((r) => r.status === "processing")) return "processing";
- // Only treat recent runs (within TTL) as 'done' — avoids permanent green tick on old folders
- if (
- runs.some(
- (r) =>
- r.status === "processed" &&
- r.processedAt != null &&
- Date.now() - r.processedAt.getTime() < DONE_TTL_MS,
- )
- )
- return "done";
- return "idle";
-}
-
-export function useFolderRunStatuses(
- folders: WatchedFolder[],
-): Record<string, FolderRunStatus> {
- const [statuses, setStatuses] = useState<Record<string, FolderRunStatus>>({});
- const doneTimersRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(
- new Map(),
- );
- const foldersRef = useRef(folders);
- foldersRef.current = folders;
-
- useEffect(() => {
- if (folders.length === 0) return;
-
- const load = async () => {
- const results = await Promise.all(
- folders.map(async (folder) => {
- try {
- const runs = await folderRunStateStorage.getFolderRunState(
- folder.id,
- );
- return [folder.id, deriveStatus(runs)] as const;
- } catch {
- return [folder.id, "idle"] as const;
- }
- }),
- );
- const newStatuses: Record<string, FolderRunStatus> = {};
- for (const [id, status] of results) {
- newStatuses[id] = status;
- }
- setStatuses(newStatuses);
- };
-
- load();
- }, [folders]);
-
- useEffect(() => {
- return folderRunStateStorage.onRunStateChange((changedFolderId) => {
- if (!foldersRef.current.find((f) => f.id === changedFolderId)) return;
- folderRunStateStorage
- .getFolderRunState(changedFolderId)
- .then((runs) => {
- setStatuses((prev) => ({
- ...prev,
- [changedFolderId]: deriveStatus(runs),
- }));
- })
- .catch((err) => console.error("Failed to update run status:", err));
- });
- }, []);
-
- useEffect(() => {
- const timers = doneTimersRef.current;
- Object.entries(statuses).forEach(([folderId, status]) => {
- if (status === "done" && !timers.has(folderId)) {
- const timer = setTimeout(() => {
- setStatuses((prev) => ({ ...prev, [folderId]: "idle" }));
- timers.delete(folderId);
- }, DONE_TTL_MS);
- timers.set(folderId, timer);
- } else if (status !== "done" && timers.has(folderId)) {
- clearTimeout(timers.get(folderId));
- timers.delete(folderId);
- }
- });
- }, [statuses]);
-
- useEffect(() => {
- const timers = doneTimersRef.current;
- return () => {
- timers.forEach((timer) => clearTimeout(timer));
- timers.clear();
- };
- }, []);
-
- return statuses;
-}
diff --git a/frontend/editor/src/proprietary/hooks/useLocalFolderPoller.ts b/frontend/editor/src/proprietary/hooks/useLocalFolderPoller.ts
deleted file mode 100644
index ec71a18abe..0000000000
--- a/frontend/editor/src/proprietary/hooks/useLocalFolderPoller.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * Polls local input directories for Watched Folders with inputSource === 'local-folder'.
- * On each cycle it scans the chosen directory, skips already-seen files,
- * registers new ones in watchedFolderFileStorage, and kicks off the automation pipeline.
- *
- * Polling only happens while the page is visible; the interval is reset on visibility restore.
- */
-
-import { useEffect, useRef } from "react";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-import { folderDirectoryHandleStorage } from "@app/services/folderDirectoryHandleStorage";
-import {
- folderSeenFilesStorage,
- makeSeenKey,
-} from "@app/services/folderSeenFilesStorage";
-import { resolveInputFile } from "@app/hooks/useFolderAutomation";
-import { canReadLocalFolder } from "@app/utils/fsAccessCapability";
-
-const POLL_INTERVAL_MS = 10_000;
-
-export function useLocalFolderPoller(
- runPipeline: (
- folder: WatchedFolder,
- file: File,
- inputFileId: string,
- ownedByFolder: boolean,
- ) => Promise<void>,
-): void {
- const runPipelineRef = useRef(runPipeline);
- useEffect(() => {
- runPipelineRef.current = runPipeline;
- });
-
- useEffect(() => {
- let cancelled = false;
-
- async function poll() {
- if (
- cancelled ||
- document.visibilityState !== "visible" ||
- !canReadLocalFolder
- )
- return;
-
- let folders: WatchedFolder[];
- try {
- folders = await watchedFolderStorage.getAllFolders();
- } catch {
- return;
- }
-
- const localFolders = folders.filter(
- (f) => f.inputSource === "local-folder" && !f.isPaused,
- );
- if (localFolders.length === 0) return;
-
- for (const folder of localFolders) {
- if (cancelled) return;
- try {
- const inputHandle = await folderDirectoryHandleStorage.getInput(
- folder.id,
- );
- if (!inputHandle) continue;
-
- const hasPermission =
- await folderDirectoryHandleStorage.ensureReadPermission(
- inputHandle,
- );
- if (!hasPermission) continue;
-
- const folderData = await watchedFolderFileStorage.getFolderData(
- folder.id,
- );
- // Build set of file names already in the folder (any status) to avoid duplicates
- // keyed by name+size (can't use lastModified — file handle gives same value each time)
- const processingNames = new Set(
- Object.values(folderData?.files ?? {})
- .filter(
- (m) => m.status === "processing" || m.status === "pending",
- )
- .map((m) => m.name)
- .filter(Boolean) as string[],
- );
-
- for await (const [, entry] of (
- inputHandle as unknown as {
- entries(): AsyncIterableIterator<[string, FileSystemHandle]>;
- }
- ).entries()) {
- if (cancelled) return;
- if (entry.kind !== "file") continue;
-
- let file: File;
- try {
- file = await (entry as FileSystemFileHandle).getFile();
- } catch {
- continue;
- }
-
- if (!file.name.toLowerCase().endsWith(".pdf")) continue;
-
- if (processingNames.has(file.name)) continue;
-
- const seenKey = makeSeenKey(folder.id, file);
- const alreadySeen = await folderSeenFilesStorage.isSeen(seenKey);
- if (alreadySeen) continue;
-
- await folderSeenFilesStorage.markSeen(seenKey);
-
- const { inputFileId, ownedByFolder } = await resolveInputFile(file);
-
- await watchedFolderFileStorage.addFileToFolder(
- folder.id,
- inputFileId,
- {
- status: "pending",
- name: file.name,
- ownedByFolder,
- },
- );
-
- void runPipelineRef.current(
- folder,
- file,
- inputFileId,
- ownedByFolder,
- );
- }
- } catch (err) {
- console.warn(
- `[local-folder-poller] Error scanning folder ${folder.id}:`,
- err,
- );
- }
- }
- }
-
- poll();
- const interval = setInterval(poll, POLL_INTERVAL_MS);
-
- function handleVisibility() {
- if (document.visibilityState === "visible") poll();
- }
- document.addEventListener("visibilitychange", handleVisibility);
-
- return () => {
- cancelled = true;
- clearInterval(interval);
- document.removeEventListener("visibilitychange", handleVisibility);
- };
- }, []); // deliberately empty — uses refs for mutable callbacks
-}
diff --git a/frontend/editor/src/proprietary/hooks/usePolicies.ts b/frontend/editor/src/proprietary/hooks/usePolicies.ts
index 70e082869f..c8c864ec93 100644
--- a/frontend/editor/src/proprietary/hooks/usePolicies.ts
+++ b/frontend/editor/src/proprietary/hooks/usePolicies.ts
@@ -43,8 +43,7 @@ export function usePolicies() {
const refetchAppConfigRef = useRef(refetchAppConfig);
refetchAppConfigRef.current = refetchAppConfig;
- // Reconcile local cache against the backend (source of truth), preserving the
- // locally-cached folderId; retry with backoff since the backend may not be up yet.
+ // Retry with backoff since the backend may not be up yet.
// On recovery, also re-resolve app config in case its admin/team-leader flags settled false while down.
useEffect(() => {
let cancelled = false;
@@ -66,7 +65,7 @@ export function usePolicies() {
for (const cat of loadPolicyCatalog().categories) {
const decoded = byCategory.get(cat.id);
reconciled[cat.id] = decoded
- ? decodedToState(decoded, local[cat.id]?.folderId)
+ ? decodedToState(decoded)
: {
...local[cat.id],
configured: false,
@@ -78,7 +77,7 @@ export function usePolicies() {
// still policies: one set to run on the editor has to reach the auto-run.
for (const [key, decoded] of byCategory) {
if (reconciled[key]) continue;
- reconciled[key] = decodedToState(decoded, local[key]?.folderId);
+ reconciled[key] = decodedToState(decoded);
}
// A builder pipeline the backend no longer has was deleted on the Pipelines page. Its cached
// entry keeps a dead backendId that still satisfies the auto-run filter, so the dispatch
diff --git a/frontend/editor/src/proprietary/hooks/useWatchedFolderUrlSync.ts b/frontend/editor/src/proprietary/hooks/useWatchedFolderUrlSync.ts
deleted file mode 100644
index 4d2d7fbdd4..0000000000
--- a/frontend/editor/src/proprietary/hooks/useWatchedFolderUrlSync.ts
+++ /dev/null
@@ -1,195 +0,0 @@
-/**
- * URL synchronization for Watched Folders workbench.
- * Manages /watch-folders and /watch-folders/:slug routes
- * where :slug is derived from the folder name (e.g. "My Invoices" → "my-invoices").
- */
-
-import { useEffect, useRef, useMemo } from "react";
-import { BASE_PATH, withBasePath } from "@app/constants/app";
-import {
- useNavigationState,
- useNavigationActions,
-} from "@app/contexts/NavigationContext";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { useAllWatchedFolders } from "@app/hooks/useAllWatchedFolders";
-import { slugify } from "@app/utils/slug";
-import { EDITOR_BASENAME } from "@app/routes/editorBasename";
-
-// Inlined to avoid circular imports — must match WatchedFoldersRegistration.tsx
-const WATCHED_FOLDER_VIEW_ID = "watchedFolder";
-const WATCHED_FOLDER_WORKBENCH_ID = "custom:watchedFolder";
-
-const WATCHED_FOLDERS_BASE = "/watch-folders";
-
-export function slugifyFolderName(name: string): string {
- return slugify(name) || "folder";
-}
-
-function parseWatchedFolderRoute(): {
- isWatchedFolder: boolean;
- slug: string | null;
-} {
- const fullPath = window.location.pathname;
- const path =
- BASE_PATH && fullPath.startsWith(BASE_PATH)
- ? fullPath.slice(BASE_PATH.length) || "/"
- : fullPath;
-
- if (path === WATCHED_FOLDERS_BASE || path === WATCHED_FOLDERS_BASE + "/") {
- return { isWatchedFolder: true, slug: null };
- }
- if (path.startsWith(WATCHED_FOLDERS_BASE + "/")) {
- const slug = path.slice(WATCHED_FOLDERS_BASE.length + 1);
- return { isWatchedFolder: true, slug: slug || null };
- }
- return { isWatchedFolder: false, slug: null };
-}
-
-function isWatchedFolderUrl(): boolean {
- const fullPath = window.location.pathname;
- const path =
- BASE_PATH && fullPath.startsWith(BASE_PATH)
- ? fullPath.slice(BASE_PATH.length) || "/"
- : fullPath;
- return (
- path === WATCHED_FOLDERS_BASE || path.startsWith(WATCHED_FOLDERS_BASE + "/")
- );
-}
-
-export function useWatchedFolderUrlSync() {
- const folders = useAllWatchedFolders();
- const navigationState = useNavigationState();
- const { actions } = useNavigationActions();
- const { setCustomWorkbenchViewData, customWorkbenchViews } =
- useToolWorkflow();
-
- const isWatchedFolderWorkbench =
- navigationState.workbench === WATCHED_FOLDER_WORKBENCH_ID;
-
- const viewData = customWorkbenchViews.find(
- (v) => v.id === WATCHED_FOLDER_VIEW_ID,
- )?.data as { folderId: string | null } | null | undefined;
- const folderId = viewData?.folderId ?? null;
-
- const { slugToId, idToSlug } = useMemo(() => {
- const s2i = new Map<string, string>();
- const i2s = new Map<string, string>();
- for (const f of folders) {
- const slug = slugifyFolderName(f.name);
- if (!s2i.has(slug)) s2i.set(slug, f.id);
- i2s.set(f.id, slug);
- }
- return { slugToId: s2i, idToSlug: i2s };
- }, [folders]);
-
- const setDataRef = useRef(setCustomWorkbenchViewData);
- const actionsRef = useRef(actions);
- const slugToIdRef = useRef(slugToId);
- const foldersRef = useRef(folders);
- useEffect(() => {
- setDataRef.current = setCustomWorkbenchViewData;
- });
- useEffect(() => {
- actionsRef.current = actions;
- });
- useEffect(() => {
- slugToIdRef.current = slugToId;
- });
- useEffect(() => {
- foldersRef.current = folders;
- });
-
- const mountSlugRef = useRef<string | null | "none">("none");
- const hasMountNavigated = useRef(false);
- const pendingSlugRef = useRef<string | null>(null);
-
- // Phase 1a: capture URL slug on mount
- useEffect(() => {
- const { isWatchedFolder, slug } = parseWatchedFolderRoute();
- if (isWatchedFolder) {
- mountSlugRef.current = slug;
- }
- }, []);
-
- // Phase 1b: navigate once the view is registered
- useEffect(() => {
- if (hasMountNavigated.current) return;
- if (mountSlugRef.current === "none") return;
-
- const isRegistered = customWorkbenchViews.some(
- (v) => v.id === WATCHED_FOLDER_VIEW_ID,
- );
- if (!isRegistered) return;
-
- hasMountNavigated.current = true;
- const slug = mountSlugRef.current;
-
- if (!slug) {
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: null });
- actionsRef.current.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- return;
- }
-
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: null });
- actionsRef.current.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
-
- if (foldersRef.current.length > 0) {
- const id = slugToIdRef.current.get(slug) ?? null;
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: id });
- } else {
- pendingSlugRef.current = slug;
- }
- }, [customWorkbenchViews]);
-
- useEffect(() => {
- if (!pendingSlugRef.current || folders.length === 0) return;
- const slug = pendingSlugRef.current;
- pendingSlugRef.current = null;
- const id = slugToId.get(slug) ?? null;
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: id });
- }, [folders, slugToId]);
-
- // Phase 2: State → URL
- const prevIsWatchedFolder = useRef(false);
- useEffect(() => {
- if (isWatchedFolderWorkbench) {
- const slug = folderId ? (idToSlug.get(folderId) ?? null) : null;
- const targetPath = slug
- ? withBasePath(`${WATCHED_FOLDERS_BASE}/${slug}`)
- : withBasePath(WATCHED_FOLDERS_BASE);
- if (window.location.pathname !== targetPath) {
- window.history.pushState(null, "", targetPath);
- }
- } else if (prevIsWatchedFolder.current && isWatchedFolderUrl()) {
- window.history.pushState(null, "", withBasePath(EDITOR_BASENAME));
- }
- prevIsWatchedFolder.current = isWatchedFolderWorkbench;
- }, [isWatchedFolderWorkbench, folderId, idToSlug]);
-
- // Phase 3: popstate → State
- useEffect(() => {
- const handlePopState = () => {
- const { isWatchedFolder, slug } = parseWatchedFolderRoute();
- if (!isWatchedFolder) return;
-
- if (!slug) {
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: null });
- actionsRef.current.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
- return;
- }
-
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: null });
- actionsRef.current.setWorkbench(WATCHED_FOLDER_WORKBENCH_ID);
-
- if (foldersRef.current.length > 0) {
- const id = slugToIdRef.current.get(slug) ?? null;
- setDataRef.current(WATCHED_FOLDER_VIEW_ID, { folderId: id });
- } else {
- pendingSlugRef.current = slug;
- }
- };
-
- window.addEventListener("popstate", handlePopState);
- return () => window.removeEventListener("popstate", handlePopState);
- }, []);
-}
diff --git a/frontend/editor/src/proprietary/hooks/useWatchedFolders.ts b/frontend/editor/src/proprietary/hooks/useWatchedFolders.ts
deleted file mode 100644
index 3e599ab898..0000000000
--- a/frontend/editor/src/proprietary/hooks/useWatchedFolders.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Hook for managing Watched Folders — load, create, update, delete
- */
-
-import { useState, useEffect, useCallback } from "react";
-import { WatchedFolder } from "@app/types/watchedFolders";
-import {
- watchedFolderStorage,
- WATCHED_FOLDER_STORAGE_CHANGE_EVENT,
-} from "@app/services/watchedFolderStorage";
-import { watchedFolderFileStorage } from "@app/services/watchedFolderFileStorage";
-import { folderRunStateStorage } from "@app/services/folderRunStateStorage";
-import { fileStorage } from "@app/services/fileStorage";
-import { folderRetryScheduleStorage } from "@app/services/folderRetryScheduleStorage";
-import { folderSeenFilesStorage } from "@app/services/folderSeenFilesStorage";
-import { folderDirectoryHandleStorage } from "@app/services/folderDirectoryHandleStorage";
-import { FileId } from "@app/types/fileContext";
-
-interface UseWatchedFoldersReturn {
- folders: WatchedFolder[];
- loading: boolean;
- createFolder: (
- data: Omit<WatchedFolder, "id" | "createdAt" | "updatedAt">,
- ) => Promise<WatchedFolder>;
- updateFolder: (folder: WatchedFolder) => Promise<WatchedFolder>;
- deleteFolder: (id: string) => Promise<void>;
- refreshFolders: () => Promise<void>;
-}
-
-export function useWatchedFolders(): UseWatchedFoldersReturn {
- const [folders, setFolders] = useState<WatchedFolder[]>([]);
- const [loading, setLoading] = useState(true);
-
- const refreshFolders = useCallback(async () => {
- try {
- // Policy-owned folders are managed by Policies, not shown here.
- const all = await watchedFolderStorage.getAllFolders();
- setFolders(all.filter((f) => !f.policyCategoryId));
- } catch (error) {
- console.error("Failed to load smart folders:", error);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => {
- refreshFolders();
- }, [refreshFolders]);
-
- useEffect(() => {
- const handler = () => {
- refreshFolders();
- };
- window.addEventListener(WATCHED_FOLDER_STORAGE_CHANGE_EVENT, handler);
- return () =>
- window.removeEventListener(WATCHED_FOLDER_STORAGE_CHANGE_EVENT, handler);
- }, [refreshFolders]);
-
- const createFolder = useCallback(
- async (
- data: Omit<WatchedFolder, "id" | "createdAt" | "updatedAt">,
- ): Promise<WatchedFolder> => {
- return watchedFolderStorage.createFolder(data);
- },
- [],
- );
-
- const updateFolder = useCallback(
- async (folder: WatchedFolder): Promise<WatchedFolder> => {
- return watchedFolderStorage.updateFolder(folder);
- },
- [],
- );
-
- const deleteFolder = useCallback(async (id: string): Promise<void> => {
- const record = await watchedFolderFileStorage.getFolderData(id);
- if (record) {
- // Only delete input files the folder created from disk — never touch sidebar-sourced files.
- const ownedInputIds = Object.entries(record.files)
- .filter(([, meta]) => meta.ownedByFolder === true)
- .map(([fid]) => fid);
- // Always delete every output the folder produced (folder always owns those).
- const outputIds = Object.values(record.files).flatMap(
- (meta) =>
- meta.displayFileIds ??
- (meta.displayFileId ? [meta.displayFileId] : []),
- );
- const toDelete = [...new Set([...ownedInputIds, ...outputIds])];
- await Promise.all(
- toDelete.map((fid) =>
- fileStorage.deleteStirlingFile(fid as FileId).catch(() => {}),
- ),
- );
- }
- await watchedFolderFileStorage.clearFolder(id);
- await folderRunStateStorage.clearFolderRunState(id);
- await folderRetryScheduleStorage.clearFolder(id).catch(() => {});
- await folderSeenFilesStorage.clearFolder(id).catch(() => {});
- await folderDirectoryHandleStorage.remove(id).catch(() => {});
- await folderDirectoryHandleStorage.removeInput(id).catch(() => {});
- await watchedFolderStorage.deleteFolder(id);
- window.dispatchEvent(new CustomEvent("stirling:files-changed"));
- }, []);
-
- return {
- folders,
- loading,
- createFolder,
- updateFolder,
- deleteFolder,
- refreshFolders,
- };
-}
diff --git a/frontend/editor/src/proprietary/services/folderDirectoryHandleStorage.ts b/frontend/editor/src/proprietary/services/folderDirectoryHandleStorage.ts
deleted file mode 100644
index 3d51b99481..0000000000
--- a/frontend/editor/src/proprietary/services/folderDirectoryHandleStorage.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
- * Stores FileSystemDirectoryHandle instances per folder in IndexedDB.
- * Handles are structured-cloneable so they survive page refresh.
- * Permission must be re-requested each session before writing.
- */
-
-const DB_NAME = "stirling-pdf-folder-directory-handles";
-const DB_VERSION = 1;
-const STORE = "handles";
-
-/** Cached singleton DB connection — avoids opening a new connection per call. */
-let cachedDB: IDBDatabase | null = null;
-let initPromise: Promise<IDBDatabase> | null = null;
-
-function getDB(): Promise<IDBDatabase> {
- if (cachedDB) return Promise.resolve(cachedDB);
- if (initPromise) return initPromise;
- initPromise = new Promise<IDBDatabase>((resolve, reject) => {
- const req = indexedDB.open(DB_NAME, DB_VERSION);
- req.onupgradeneeded = () => req.result.createObjectStore(STORE);
- req.onsuccess = () => {
- cachedDB = req.result;
- cachedDB.onclose = () => {
- cachedDB = null;
- initPromise = null;
- };
- resolve(cachedDB);
- };
- req.onerror = () => {
- initPromise = null;
- reject(req.error);
- };
- });
- return initPromise;
-}
-
-type ExtendedDirHandle = FileSystemDirectoryHandle & {
- queryPermission(opts: object): Promise<PermissionState>;
- requestPermission(opts: object): Promise<PermissionState>;
-};
-
-export const folderDirectoryHandleStorage = {
- // ── Output directory handles (readwrite) ─────────────────────────────────
-
- async get(folderId: string): Promise<FileSystemDirectoryHandle | null> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db.transaction(STORE).objectStore(STORE).get(folderId);
- req.onsuccess = () => resolve(req.result ?? null);
- req.onerror = () => reject(req.error);
- });
- },
-
- async set(
- folderId: string,
- handle: FileSystemDirectoryHandle,
- ): Promise<void> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db
- .transaction(STORE, "readwrite")
- .objectStore(STORE)
- .put(handle, folderId);
- req.onsuccess = () => resolve();
- req.onerror = () => reject(req.error);
- });
- },
-
- async remove(folderId: string): Promise<void> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db
- .transaction(STORE, "readwrite")
- .objectStore(STORE)
- .delete(folderId);
- req.onsuccess = () => resolve();
- req.onerror = () => reject(req.error);
- });
- },
-
- /**
- * Verifies the handle still has readwrite permission, requesting it if needed.
- * Returns true if permission is granted, false if denied/dismissed.
- */
- async ensurePermission(handle: FileSystemDirectoryHandle): Promise<boolean> {
- const opts = { mode: "readwrite" };
- const h = handle as ExtendedDirHandle;
- if ((await h.queryPermission(opts)) === "granted") return true;
- return (await h.requestPermission(opts)) === "granted";
- },
-
- // ── Input directory handles (readonly) ────────────────────────────────────
- // Stored under key "input:{folderId}" to avoid collisions with output handles.
-
- async getInput(folderId: string): Promise<FileSystemDirectoryHandle | null> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db
- .transaction(STORE)
- .objectStore(STORE)
- .get(`input:${folderId}`);
- req.onsuccess = () => resolve(req.result ?? null);
- req.onerror = () => reject(req.error);
- });
- },
-
- async setInput(
- folderId: string,
- handle: FileSystemDirectoryHandle,
- ): Promise<void> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db
- .transaction(STORE, "readwrite")
- .objectStore(STORE)
- .put(handle, `input:${folderId}`);
- req.onsuccess = () => resolve();
- req.onerror = () => reject(req.error);
- });
- },
-
- async removeInput(folderId: string): Promise<void> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db
- .transaction(STORE, "readwrite")
- .objectStore(STORE)
- .delete(`input:${folderId}`);
- req.onsuccess = () => resolve();
- req.onerror = () => reject(req.error);
- });
- },
-
- /**
- * Verifies the handle still has read permission, requesting it if needed.
- * On browsers that don't support queryPermission/requestPermission (Firefox),
- * returns true optimistically — access errors will surface naturally during iteration.
- */
- async ensureReadPermission(
- handle: FileSystemDirectoryHandle,
- ): Promise<boolean> {
- const h = handle as ExtendedDirHandle;
- if (typeof h.queryPermission !== "function") return true; // Firefox — no permission API
- const opts = { mode: "read" };
- if ((await h.queryPermission(opts)) === "granted") return true;
- return (await h.requestPermission(opts)) === "granted";
- },
-
- /** Write a file blob into the directory, overwriting if it exists. */
- async writeFile(
- handle: FileSystemDirectoryHandle,
- name: string,
- blob: Blob,
- ): Promise<void> {
- const fileHandle = await handle.getFileHandle(name, { create: true });
- const writable = await fileHandle.createWritable();
- await writable.write(blob);
- await writable.close();
- },
-};
diff --git a/frontend/editor/src/proprietary/services/folderRetryScheduleStorage.ts b/frontend/editor/src/proprietary/services/folderRetryScheduleStorage.ts
deleted file mode 100644
index 228d68339f..0000000000
--- a/frontend/editor/src/proprietary/services/folderRetryScheduleStorage.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * Persistent retry schedule for Watched Folder automation.
- *
- * Stores pending retries in IndexedDB so they survive page close.
- * The service worker reads this store to schedule timers; the main thread
- * drains due entries on mount, on SW notification, and on visibilitychange.
- *
- * claimDue() is atomic (single readwrite IDB transaction) — safe across tabs.
- */
-
-export interface RetryEntry {
- /** `${folderId}:${fileId}` — natural composite key */
- id: string;
- folderId: string;
- fileId: string;
- /** Absolute ms timestamp when this retry should fire */
- dueAt: number;
- attempt: number;
- ownedByFolder: boolean;
-}
-
-class FolderRetryScheduleStorage {
- private dbName = "stirling-pdf-retry-schedule";
- private dbVersion = 1;
- private storeName = "retries";
- private db: IDBDatabase | null = null;
- private initPromise: Promise<void> | null = null;
-
- async init(): Promise<void> {
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(this.dbName, this.dbVersion);
- request.onerror = () =>
- reject(new Error("Failed to open retry schedule database"));
- request.onsuccess = () => {
- this.db = request.result;
- this.db.onclose = () => {
- this.db = null;
- this.initPromise = null;
- };
- resolve();
- };
- request.onupgradeneeded = (event) => {
- const db = (event.target as IDBOpenDBRequest).result;
- if (!db.objectStoreNames.contains(this.storeName)) {
- const store = db.createObjectStore(this.storeName, { keyPath: "id" });
- // Index on dueAt lets the SW and claimDue() range-scan efficiently
- store.createIndex("dueAt", "dueAt", { unique: false });
- }
- };
- });
- }
-
- private async ensureDB(): Promise<IDBDatabase> {
- if (!this.db) {
- this.initPromise ??= this.init();
- await this.initPromise;
- }
- if (!this.db) throw new Error("Retry schedule database not initialized");
- return this.db;
- }
-
- /** Upsert a retry entry. Calling again for the same file replaces the previous schedule. */
- async schedule(
- folderId: string,
- fileId: string,
- dueAt: number,
- attempt: number,
- ownedByFolder: boolean,
- ): Promise<void> {
- const db = await this.ensureDB();
- const entry: RetryEntry = {
- id: `${folderId}:${fileId}`,
- folderId,
- fileId,
- dueAt,
- attempt,
- ownedByFolder,
- };
- return new Promise((resolve, reject) => {
- const tx = db.transaction([this.storeName], "readwrite");
- const request = tx.objectStore(this.storeName).put(entry);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(new Error("Failed to schedule retry"));
- });
- }
-
- /** Remove a scheduled retry (e.g. when a folder is deleted or a file is manually retried). */
- async cancel(folderId: string, fileId: string): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const tx = db.transaction([this.storeName], "readwrite");
- const request = tx
- .objectStore(this.storeName)
- .delete(`${folderId}:${fileId}`);
- request.onsuccess = () => resolve();
- request.onerror = () => reject(new Error("Failed to cancel retry"));
- });
- }
-
- /**
- * Atomically reads and deletes all entries whose dueAt is in the past.
- * Because the delete happens inside the same readwrite transaction as the
- * read, two concurrent tabs cannot both claim the same entry.
- */
- async claimDue(): Promise<RetryEntry[]> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const now = Date.now();
- const claimed: RetryEntry[] = [];
- const tx = db.transaction([this.storeName], "readwrite");
- const index = tx.objectStore(this.storeName).index("dueAt");
- const cursorRequest = index.openCursor(IDBKeyRange.upperBound(now));
- cursorRequest.onsuccess = () => {
- const cursor = cursorRequest.result;
- if (cursor) {
- claimed.push(cursor.value as RetryEntry);
- cursor.delete();
- cursor.continue();
- }
- };
- tx.oncomplete = () => resolve(claimed);
- tx.onerror = () => reject(new Error("Failed to claim due retries"));
- });
- }
-
- /** Remove all scheduled retries for a folder (called when the folder is deleted). */
- async clearFolder(folderId: string): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const tx = db.transaction([this.storeName], "readwrite");
- const store = tx.objectStore(this.storeName);
- const cursorRequest = store.openCursor();
- cursorRequest.onsuccess = () => {
- const cursor = cursorRequest.result;
- if (!cursor) return;
- const entry = cursor.value as RetryEntry;
- if (entry.folderId === folderId) cursor.delete();
- cursor.continue();
- };
- tx.oncomplete = () => resolve();
- tx.onerror = () => reject(new Error("Failed to clear folder retries"));
- });
- }
-
- /** Returns the earliest scheduled dueAt timestamp, or null if no entries exist. */
- async getEarliestDueAt(): Promise<number | null> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const tx = db.transaction([this.storeName], "readonly");
- const cursorRequest = tx
- .objectStore(this.storeName)
- .index("dueAt")
- .openCursor();
- cursorRequest.onsuccess = () =>
- resolve(
- cursorRequest.result
- ? (cursorRequest.result.value as RetryEntry).dueAt
- : null,
- );
- cursorRequest.onerror = () =>
- reject(new Error("Failed to get earliest due at"));
- });
- }
-}
-
-export const folderRetryScheduleStorage = new FolderRetryScheduleStorage();
diff --git a/frontend/editor/src/proprietary/services/folderRunStateStorage.ts b/frontend/editor/src/proprietary/services/folderRunStateStorage.ts
deleted file mode 100644
index 1045747318..0000000000
--- a/frontend/editor/src/proprietary/services/folderRunStateStorage.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * Service for managing Watched Folder run state in IndexedDB
- */
-
-import { WatchedFolderRunEntry } from "@app/types/watchedFolders";
-
-const FOLDER_RUN_STATE_CHANGE_EVENT = "folder-run-state-changed";
-
-interface RunStateRecord {
- folderId: string;
- runs: WatchedFolderRunEntry[];
- lastUpdated: number;
-}
-
-class FolderRunStateStorage {
- private dbName = "stirling-pdf-folder-run-state";
- private dbVersion = 1;
- private storeName = "runStates";
- private db: IDBDatabase | null = null;
- private initPromise: Promise<void> | null = null;
-
- async init(): Promise<void> {
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(this.dbName, this.dbVersion);
- request.onerror = () =>
- reject(new Error("Failed to open folder run state database"));
- request.onsuccess = () => {
- this.db = request.result;
- this.db.onclose = () => {
- this.db = null;
- this.initPromise = null;
- };
- resolve();
- };
- request.onupgradeneeded = (event) => {
- const db = (event.target as IDBOpenDBRequest).result;
- if (!db.objectStoreNames.contains(this.storeName)) {
- db.createObjectStore(this.storeName, { keyPath: "folderId" });
- }
- };
- });
- }
-
- private async ensureDB(): Promise<IDBDatabase> {
- if (!this.db) {
- this.initPromise ??= this.init();
- await this.initPromise;
- }
- if (!this.db) {
- throw new Error("Folder run state database not initialized");
- }
- return this.db;
- }
-
- async getFolderRunState(folderId: string): Promise<WatchedFolderRunEntry[]> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readonly");
- const store = transaction.objectStore(this.storeName);
- const request = store.get(folderId);
- request.onsuccess = () => {
- const record: RunStateRecord | undefined = request.result;
- resolve(record?.runs || []);
- };
- request.onerror = () =>
- reject(new Error("Failed to get folder run state"));
- });
- }
-
- async setFolderRunState(
- folderId: string,
- runs: WatchedFolderRunEntry[],
- ): Promise<void> {
- const db = await this.ensureDB();
- const record: RunStateRecord = { folderId, runs, lastUpdated: Date.now() };
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const request = store.put(record);
- request.onsuccess = () => {
- window.dispatchEvent(
- new CustomEvent(FOLDER_RUN_STATE_CHANGE_EVENT, {
- detail: { folderId },
- }),
- );
- resolve();
- };
- request.onerror = () =>
- reject(new Error("Failed to set folder run state"));
- });
- }
-
- onRunStateChange(listener: (folderId: string) => void): () => void {
- const handler = (e: Event) => listener((e as CustomEvent).detail.folderId);
- window.addEventListener(FOLDER_RUN_STATE_CHANGE_EVENT, handler);
- return () =>
- window.removeEventListener(FOLDER_RUN_STATE_CHANGE_EVENT, handler);
- }
-
- /** Atomically appends entries to a folder's run state within a single readwrite transaction,
- * preventing lost-update races when multiple files are processed concurrently. */
- async appendRunEntries(
- folderId: string,
- entries: WatchedFolderRunEntry[],
- ): Promise<void> {
- if (entries.length === 0) return;
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const getRequest = store.get(folderId);
- getRequest.onsuccess = () => {
- const existing: RunStateRecord | undefined = getRequest.result;
- const MAX_RUN_ENTRIES = 500;
- const combined = [...(existing?.runs ?? []), ...entries];
- const record: RunStateRecord = {
- folderId,
- runs:
- combined.length > MAX_RUN_ENTRIES
- ? combined.slice(-MAX_RUN_ENTRIES)
- : combined,
- lastUpdated: Date.now(),
- };
- const putRequest = store.put(record);
- putRequest.onsuccess = () => {
- window.dispatchEvent(
- new CustomEvent(FOLDER_RUN_STATE_CHANGE_EVENT, {
- detail: { folderId },
- }),
- );
- resolve();
- };
- putRequest.onerror = () =>
- reject(new Error("Failed to append run entries"));
- };
- getRequest.onerror = () =>
- reject(new Error("Failed to read run state for append"));
- });
- }
-
- async clearFolderRunState(folderId: string): Promise<void> {
- const db = await this.ensureDB();
- return new Promise((resolve, reject) => {
- const transaction = db.transaction([this.storeName], "readwrite");
- const store = transaction.objectStore(this.storeName);
- const request = store.delete(folderId);
- request.onsuccess = () => resolve();
- request.onerror = () =>
- reject(new Error("Failed to clear folder run state"));
- });
- }
-}
-
-export const folderRunStateStorage = new FolderRunStateStorage();
diff --git a/frontend/editor/src/proprietary/services/folderSeenFilesStorage.ts b/frontend/editor/src/proprietary/services/folderSeenFilesStorage.ts
deleted file mode 100644
index 577fb28357..0000000000
--- a/frontend/editor/src/proprietary/services/folderSeenFilesStorage.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Tracks which local-folder input files have already been submitted for processing.
- * Key: `{folderId}|{filename}|{size}|{lastModified}` — uniquely identifies a file version.
- * Prevents re-submitting the same file on every poll cycle.
- */
-
-const DB_NAME = "stirling-pdf-folder-seen-files";
-const DB_VERSION = 1;
-const STORE = "seenFiles";
-
-/** Cached singleton DB connection — avoids opening a new connection per call. */
-let cachedDB: IDBDatabase | null = null;
-let initPromise: Promise<IDBDatabase> | null = null;
-
-function getDB(): Promise<IDBDatabase> {
- if (cachedDB) return Promise.resolve(cachedDB);
- if (initPromise) return initPromise;
- initPromise = new Promise<IDBDatabase>((resolve, reject) => {
- const req = indexedDB.open(DB_NAME, DB_VERSION);
- req.onupgradeneeded = () => req.result.createObjectStore(STORE);
- req.onsuccess = () => {
- cachedDB = req.result;
- cachedDB.onclose = () => {
- cachedDB = null;
- initPromise = null;
- };
- resolve(cachedDB);
- };
- req.onerror = () => {
- initPromise = null;
- reject(req.error);
- };
- });
- return initPromise;
-}
-
-export function makeSeenKey(folderId: string, file: File): string {
- return `${folderId}|${file.name}|${file.size}|${file.lastModified}`;
-}
-
-export const folderSeenFilesStorage = {
- async isSeen(key: string): Promise<boolean> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db.transaction(STORE).objectStore(STORE).get(key);
- req.onsuccess = () => resolve(req.result != null);
- req.onerror = () => reject(req.error);
- });
- },
-
- async markSeen(key: string): Promise<void> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const req = db
- .transaction(STORE, "readwrite")
- .objectStore(STORE)
- .put(Date.now(), key);
- req.onsuccess = () => resolve();
- req.onerror = () => reject(req.error);
- });
- },
-
- /** Remove all seen-file entries for a folder (called when folder is deleted or reset). */
- async clearFolder(folderId: string): Promise<void> {
- const db = await getDB();
- return new Promise((resolve, reject) => {
- const tx = db.transaction(STORE, "readwrite");
- const store = tx.objectStore(STORE);
- const prefix = `${folderId}|`;
- const range = IDBKeyRange.bound(prefix, prefix + "￿");
- const req = store.openCursor(range);
- req.onsuccess = () => {
- const cursor = req.result;
- if (!cursor) {
- resolve();
- return;
- }
- cursor.delete();
- cursor.continue();
- };
- req.onerror = () => reject(req.error);
- });
- },
-};
diff --git a/frontend/editor/src/proprietary/services/policyBackend.test.ts b/frontend/editor/src/proprietary/services/policyBackend.test.ts
index 7f4235b466..6d86fc159f 100644
--- a/frontend/editor/src/proprietary/services/policyBackend.test.ts
+++ b/frontend/editor/src/proprietary/services/policyBackend.test.ts
@@ -37,7 +37,7 @@ async function stateOf(wire: ReturnType<typeof policy>, key: string) {
listPolicies.mockResolvedValue([wire]);
const decoded = (await fetchPoliciesByCategory()).get(key);
if (!decoded) throw new Error(`no decoded policy for ${key}`);
- return decodedToState(decoded, undefined);
+ return decodedToState(decoded);
}
describe("fetchPoliciesByCategory", () => {
diff --git a/frontend/editor/src/proprietary/services/policyBackend.ts b/frontend/editor/src/proprietary/services/policyBackend.ts
index 2ea2234a9b..ce74f2e15a 100644
--- a/frontend/editor/src/proprietary/services/policyBackend.ts
+++ b/frontend/editor/src/proprietary/services/policyBackend.ts
@@ -37,15 +37,8 @@ export async function fetchPoliciesByCategory(): Promise<
return byCategory;
}
-/**
- * Project a decoded backend policy onto the frontend per-category state. The
- * locally-cached `folderId` (the editable-automation link, which the backend
- * doesn't track) is preserved by the caller via `localFolderId`.
- */
-export function decodedToState(
- decoded: DecodedPolicy,
- localFolderId: string | undefined,
-): PolicyState {
+/** Project backend policy settings onto the editor's cached enforcement state. */
+export function decodedToState(decoded: DecodedPolicy): PolicyState {
return {
configured: true,
enabled: decoded.enabled,
@@ -62,7 +55,6 @@ export function decodedToState(
outputName: decoded.folder.outputName,
outputNamePosition: decoded.folder.outputNamePosition,
runOn: decoded.folder.runOn,
- folderId: localFolderId,
backendId: decoded.id,
firstOperation: decoded.firstOperation,
// Server-side run-order position (team-wide); drives the settings reorder list.
diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.ts
index 0dc83028f6..f3321fa309 100644
--- a/frontend/editor/src/proprietary/types/policies.ts
+++ b/frontend/editor/src/proprietary/types/policies.ts
@@ -1,11 +1,8 @@
/**
* Types for Policies — a proprietary, automation-backed enforcement feature.
*
- * A Policy is conceptually like a Watch Folder (a configured automation that
- * runs over documents) but backend-driven and triggered by *sources/events*
- * (editor save/export, device sweeps, cloud connectors) rather than just a
- * folder. Per-policy state is persisted locally (localStorage). Activity + stats
- * shown in the detail view are derived live from the user's real uploaded files.
+ * Policies run on the backend in response to sources/events (editor save/export,
+ * device sweeps, cloud connectors). Per-policy state is cached locally in localStorage.
*/
import type { ReactNode } from "react";
@@ -81,14 +78,6 @@ export interface PolicyState {
* until an admin reorders them, which persists an explicit value for every policy.
*/
order?: number;
- /**
- * The backing folder-trigger record (a Watched Folders `WatchedFolder`) that
- * holds this policy's editable steps (its automation), output config and run
- * state. Present once the policy is configured. The folder trigger reuses the
- * Watched Folders engine; this is the link to it. Maps to the backend's
- * `Policy.trigger` (folder) + `steps` + `output`.
- */
- folderId?: string;
/**
* Id of this policy's record on the backend (the source of truth). Present once
* it has been persisted server-side; used to update/delete/run it.
@@ -106,10 +95,7 @@ export interface PolicyState {
export type PoliciesByKey = Record<string, PolicyState>;
-/**
- * Output + retry settings applied by the Watch Folders engine to a policy's
- * backing folder (the real, working settings reused from the folder setup).
- */
+/** Editor trigger, output and retry settings decoded from a backend policy. */
export interface PolicyFolderSettings {
/** The editor event the policy runs on: "upload" or "export". */
runOn: "upload" | "export";