Skip to content

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

Remove the policies management surface from the editor sidebar (#6932)

Reece Browne16f589448d95
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index 847b3be863..c57174a81e 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -5937,59 +5937,12 @@ keyDescription = "Paste the license key from your email"
success = "License Activated!"
successMessage = "Your license has been successfully activated. You can now close this window."
-[policies]
-deleteConfirmBody = "This removes the policy and its workflow. Documents already processed are not affected."
-deleteConfirmTitle = "Delete {{label}} policy?"
-
[policies.activity]
-enforced = "enforced"
-enforcing = "Enforcing..."
-failed = "Enforcement failed"
outputsUnavailable = "Policy outputs are no longer available to download."
partialOutputsUnavailable = "Some policy outputs are no longer available to download."
-retrying = "Busy, retrying..."
runNotFound = "The enforcement run could no longer be found."
-step = "step {{current}}/{{total}}"
timedOut = "Enforcement timed out before the run could finish."
-[policies.catalog]
-compliance = "Compliance"
-ingestion = "Ingestion"
-retention = "Retention"
-routing = "Routing"
-security = "Security"
-
-[policies.detail]
-close = "Close"
-editSettings = "Edit Settings"
-enforces = "Enforces"
-managedByOrg = "Managed by your organization. Contact a team leader to change this policy."
-noActivityDescription = "Documents will appear here once this policy runs."
-noActivityTitle = "No activity yet"
-onEveryUpload = "On every upload"
-originalsNote = "Originals stay untouched • Enforced version saved alongside"
-pause = "Pause"
-recentActivity = "Recent Activity"
-resume = "Resume"
-retry = "Retry"
-showLess = "Show less"
-showMore = "Show more"
-statActive = "Active"
-statDataProcessed = "Data processed"
-statDocsEnforced = "Docs enforced"
-statusActive = "Active"
-statusPaused = "Paused"
-
-[policies.docType]
-Contracts = "Contracts"
-"Financial reports" = "Financial reports"
-"HR records" = "HR records"
-Insurance = "Insurance"
-Invoices = "Invoices"
-"Legal filings" = "Legal filings"
-"Medical / PHI" = "Medical / PHI"
-"Tax documents" = "Tax documents"
-
[policies.enforcement]
applying = "Applying {{names}}"
applyingProgress = "Applying {{names}} ({{done}} of {{total}})"
@@ -5999,32 +5952,10 @@ failureBody = "{{failures}} of {{total}} file(s) couldn't be processed and were
failureTitle = "Exported without full enforcement"
printPolicyAppliedBody = "This PDF was updated to meet a policy. Review the changes, then print again."
printPolicyAppliedTitle = "Policy applied before printing"
-queued = "+{{count}} queued"
successTitle = "{{names}} applied"
summaryMore = "{{first}}, {{second}} and {{more}} more"
summaryTwo = "{{first}} and {{second}}"
-[policies.enforcement.triggerVerb]
-convert = "Enforcing before convert"
-default = "Enforcing"
-export = "Enforcing before export"
-input = "Enforcing on import"
-print = "Enforcing before print"
-
-[policies.field]
-accessLog = "Access log"
-archiveAfter = "Archive after"
-auditTrail = "Audit trail"
-belowThreshold = "Below threshold"
-destination = "Destination"
-frameworks = "Frameworks"
-immutableHold = "Immutable hold"
-keepFor = "Keep for"
-minConfidence = "Min confidence"
-notify = "Notify on route"
-onViolation = "When non-compliant"
-webhookUrl = "Webhook URL"
-
[policies.fieldOption.archiveAfter]
"1 year" = "1 year"
"30 days" = "30 days"
@@ -6070,9 +6001,6 @@ Indefinite = "Indefinite"
"Flag for review" = "Flag for review"
"Quarantine document" = "Quarantine document"
-[policies.fields]
-selectedCount = "{{count}} selected"
-
[policies.labels]
add = "Add"
addPlaceholder = "Add a label…"
@@ -6111,90 +6039,6 @@ placeholder = "Select PII types"
routing = "US routing numbers (ABA)"
ssn = "Social Security numbers"
-[policies.settings]
-noneExport = "No policies currently run on export."
-noneUpload = "No policies currently run on upload."
-onExport = "On export"
-onUpload = "On upload"
-reorderHandle = "Drag to reorder"
-runOrderDesc = "When more than one policy runs on the same trigger, they run in this order — each on the previous policy's output. Drag to reorder."
-title = "Policy settings"
-
-[policies.sidebar]
-activeCount = "{{count}} active"
-infoTooltip = "A policy is a fixed set of tools that runs automatically whenever it's triggered — for example when a new document arrives — enforcing rules like redacting PII with no manual steps."
-loading = "Loading…"
-optionsAriaLabel = "Policy options"
-policySettings = "Policy settings"
-railAriaLabel = "{{label}} policy — {{status}}"
-railSuffixActive = " (Active)"
-railSuffixPaused = " (Paused)"
-retryFailed = "Retry failed policies ({{count}})"
-rowProgress = "{{completed}} of {{total}} files processed"
-setUp = "Set up"
-title = "Policies"
-upgradeToEnterprise = "Upgrade to enterprise"
-whatIsPolicy = "What is a policy?"
-
-[policies.status]
-active = "Active"
-paused = "Paused"
-setup = "Set up"
-
-[policies.toolConfig]
-enableAriaLabel = "Enable {{tool}}"
-infoAriaLabel = "What does {{tool}} do?"
-
-[policies.toolConfig.info]
-redact = "Automatically finds and blacks out sensitive details — like Social Security and card numbers — so they can't be read in the document."
-sanitize = "Removes hidden JavaScript from the file, so nothing can run automatically when someone opens it."
-watermark = "Stamps a visible mark (e.g. \"Confidential\") across every page."
-
-[policies.wizard]
-allDocTypesDescription = "Enable the Classification policy to filter by document type."
-allDocTypesTitle = "All document types"
-back = "Back"
-builderDesc = "Build the sequence of tools this policy runs on each document."
-clear = "Clear"
-close = "Close"
-continue = "Continue"
-docTypesLabel = "Document types"
-edit = "Edit"
-editTitle = "Edit {{label}} Policy"
-enablePolicy = "Enable Policy"
-filenameAutoNumber = "Auto-number"
-filenamePositionAria = "Filename position"
-filenamePrefix = "Prefix"
-filenameSuffix = "Suffix"
-filenameTextAria = "Filename text"
-filenameTextPlaceholder = "Text to add (optional)"
-lockedDescription = "Contact a team leader to change this policy."
-lockedTitle = "Managed by your organization"
-maxRetriesLabel = "Max retries"
-noToolsError = "Add at least one configured tool to the workflow first."
-outputAsLabel = "Output as"
-outputFilenameSubhead = "Output filename"
-outputModeAria = "Output mode"
-outputNewFile = "New file"
-outputNewVersion = "New version"
-outputRetriesLabel = "Output & retries"
-outputSubhead = "Output"
-retryDelayAria = "Retry delay minutes"
-retryDelayLabel = "Retry delay (min)"
-runOnExport = "Export"
-runOnLabel = "Run on"
-runOnSubhead = "Run on"
-runOnUpload = "Upload"
-saveChanges = "Save Changes"
-saveError = "Couldn't save the policy. Please try again."
-setupClassification = "Set up Classification"
-setupTitle = "Set up {{label}} Policy"
-sourcesDesc = "Choose where this policy runs and which document types it applies to."
-sourcesLabel = "Sources"
-stepOf = "Step {{step}} of {{total}}"
-toolChainDesc = "Configure the tools this policy runs on each document."
-typesSelected = "{{count}} types selected"
-
[policy]
badgeEnforcing = "{{name}} enforcing..."
badgeRan = "{{name}} policy ran on this file"
diff --git a/frontend/editor/src/core/components/policies/PoliciesSidebar.tsx b/frontend/editor/src/core/components/policies/PoliciesSidebar.tsx
deleted file mode 100644
index 9d9cbed2e2..0000000000
--- a/frontend/editor/src/core/components/policies/PoliciesSidebar.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Core stubs for the right-rail Policies UI.
- *
- * The real implementations live in {@code proprietary/components/policies/PoliciesSidebar.tsx}
- * and shadow these stubs via the {@code @app/*} alias cascade when the proprietary
- * build is active. Core builds render nothing, so the right rail shows only the
- * tool list unchanged.
- */
-
-import type { ReactNode } from "react";
-
-/** Whether the right rail should host the Policies section. False in core. */
-export function usePoliciesEnabled(): boolean {
- return false;
-}
-
-/** Whether the Policies list should appear for the current user. False in core. */
-export function usePoliciesVisible(): boolean {
- return false;
-}
-
-/**
- * Whether a policy is open (its detail should take over the rail). Always false
- * in core; proprietary bridges to the policy-selection store.
- */
-export function usePolicyDetailActive(): boolean {
- return false;
-}
-
-/** Collapsible policy list rendered above the Tools section. Null in core. */
-export function PoliciesSection(_props: { leadingControl?: ReactNode } = {}) {
- return null;
-}
-
-/** Open-policy detail/wizard/settings that replaces the tool area. Null in core. */
-export function PolicyDetailTakeover() {
- return null;
-}
-
-/** Collapsed-rail policy icons. Null in core; proprietary renders the rail. */
-export function PoliciesCollapsedButton(_props: { onExpand: () => void }) {
- return null;
-}
diff --git a/frontend/editor/src/core/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/core/components/policies/usePoliciesEnabled.ts
new file mode 100644
index 0000000000..d8bb52e159
--- /dev/null
+++ b/frontend/editor/src/core/components/policies/usePoliciesEnabled.ts
@@ -0,0 +1,8 @@
+/**
+ * Core stub — whether policy enforcement is active for this build. Gates
+ * mounting the headless PolicyAutoRunController. Always false in core; the
+ * proprietary and desktop builds shadow this via the {@code @app/*} alias.
+ */
+export function usePoliciesEnabled(): boolean {
+ return false;
+}
diff --git a/frontend/editor/src/core/components/tools/RightSidebar.tsx b/frontend/editor/src/core/components/tools/RightSidebar.tsx
index 4333e263f1..41110ac034 100644
--- a/frontend/editor/src/core/components/tools/RightSidebar.tsx
+++ b/frontend/editor/src/core/components/tools/RightSidebar.tsx
@@ -5,14 +5,7 @@ import { useSidebarContext } from "@app/contexts/SidebarContext";
import { useIsMobile } from "@app/hooks/useIsMobile";
import ToolPanel from "@app/components/tools/ToolPanel";
import ToolSearch from "@app/components/tools/toolPicker/ToolSearch";
-import {
- PoliciesCollapsedButton,
- PoliciesSection,
- PolicyDetailTakeover,
- usePoliciesEnabled,
- usePoliciesVisible,
- usePolicyDetailActive,
-} from "@app/components/policies/PoliciesSidebar";
+import { usePoliciesEnabled } from "@app/components/policies/usePoliciesEnabled";
import { PolicyAutoRunController } from "@app/components/policies/PolicyAutoRunController";
import { useFavoriteToolItems } from "@app/hooks/tools/useFavoriteToolItems";
import { useToolSections } from "@app/hooks/useToolSections";
@@ -66,8 +59,6 @@ export default function RightSidebar() {
} = useToolWorkflow();
const policiesEnabled = usePoliciesEnabled();
- const policiesVisible = usePoliciesVisible();
- const rawPolicyDetailActive = usePolicyDetailActive();
const fullscreenExpanded = useIsFullscreenExpanded();
const fullscreenGeometry = useToolPanelGeometry({
enabled: fullscreenExpanded,
@@ -100,39 +91,12 @@ export default function RightSidebar() {
});
};
- // Opening a policy (e.g. from the collapsed rail) lands the rail in the clean
- // default tool-picker view — the only view the policy takeover renders in — so
- // it never collides with an open tool or the all-tools/search view.
- const handleOpenPolicy = () => {
- withViewTransition(() => {
- if (readerMode) setReaderMode(false);
- setLeftPanelView("toolPicker");
- if (!sidebarsVisible) setSidebarsVisible(true);
- setAllToolsView(false);
- setSearchQuery("");
- });
- };
-
// The header shows [back] [search] when we have somewhere to go back to —
// i.e. the user is in a specific tool, or already in the all-tools/search view.
const inToolView = leftPanelView !== "toolPicker";
// Show X (close) button only when there's somewhere to go back to.
const showCloseButton = inToolView || allToolsView;
- // Policies sit above the tool list in the default tool-picker view — but only
- // when the current user actually has policies to see (see usePoliciesVisible),
- // so regular users with none get the plain tool picker with no empty block.
- const showPolicies =
- policiesEnabled &&
- policiesVisible &&
- !allToolsView &&
- leftPanelView === "toolPicker";
- // When Policies are shown, the search moves OUT of the header to sit between
- // the Policies and Tools sections (separating them); otherwise it stays in the
- // header. Show the header search when there's a close button, or in the
- // default tool-picker view.
- const showInlineSearch = showPolicies && !showCloseButton;
- const showHeaderSearch =
- !showInlineSearch && (showCloseButton || leftPanelView === "toolPicker");
+ const showHeaderSearch = showCloseButton || leftPanelView === "toolPicker";
const handleHeaderBack = () => {
if (inToolView) {
@@ -165,15 +129,7 @@ export default function RightSidebar() {
? (toolRegistry[selectedToolKey as ToolId] ?? null)
: null;
- // The detail takeover replaces the tool list ONLY in the same default view —
- // never over an open tool or the all-tools view (which must keep priority).
- // A lingering selection is harmless: it stays hidden behind a tool and the
- // list/takeover reappears on return to the picker (as in the prototype).
- const policyDetailActive = rawPolicyDetailActive && showPolicies;
-
- // The rail widens when a policy detail takes it over — the tool list is fine
- // at 18.5rem, but the policy detail/wizard/settings need more breathing room.
- const expandedWidth = policyDetailActive ? "25rem" : "18.5rem";
+ const expandedWidth = "18.5rem";
const computedWidth = () => {
if (isMobile) return "100%";
@@ -236,9 +192,6 @@ export default function RightSidebar() {
</ActionIcon>
</div>
<div className="tool-panel__collapsed-divider" />
- {policiesEnabled && (
- <PoliciesCollapsedButton onExpand={handleOpenPolicy} />
- )}
<div className="tool-panel__collapsed-tools">
{collapsedRailItems.map(({ id, tool }) => (
<AppTooltip
@@ -283,109 +236,74 @@ export default function RightSidebar() {
flexDirection: "column",
}}
>
- {policyDetailActive ? (
- <div className="pol-takeover">
- <PolicyDetailTakeover />
- </div>
- ) : (
- <>
- {!showPolicies &&
- (activeTool ? (
- <ToolPanelHeader
- icon={
- <ToolIcon
- icon={activeTool.icon}
- marginRight="0"
- color="currentColor"
- />
- }
- title={activeTool.name}
- onClose={handleHeaderBack}
- closeLabel={
+ <>
+ {activeTool ? (
+ <ToolPanelHeader
+ icon={
+ <ToolIcon
+ icon={activeTool.icon}
+ marginRight="0"
+ color="currentColor"
+ />
+ }
+ title={activeTool.name}
+ onClose={handleHeaderBack}
+ closeLabel={
+ inToolView
+ ? t("toolPanel.backToAllTools", "Back to all tools")
+ : t("toolPanel.goBack", "Go back")
+ }
+ />
+ ) : (
+ <div className="tool-panel__compact-header">
+ {showHeaderSearch ? (
+ <div className="tool-panel__compact-header-search">
+ <ToolSearch
+ value={searchQuery}
+ onChange={handleHeaderSearchChange}
+ toolRegistry={toolRegistry}
+ mode="filter"
+ autoFocus={allToolsView && !inToolView}
+ />
+ </div>
+ ) : null}
+ {showCloseButton ? (
+ <ActionIcon
+ variant="tertiary"
+ size="md"
+ shape="circle"
+ onClick={handleHeaderBack}
+ aria-label={
inToolView
? t("toolPanel.backToAllTools", "Back to all tools")
: t("toolPanel.goBack", "Go back")
}
- />
+ className="tool-panel__expand-btn"
+ >
+ <CloseIcon sx={{ fontSize: "1.1rem" }} />
+ </ActionIcon>
) : (
- <div className="tool-panel__compact-header">
- {showHeaderSearch ? (
- <div className="tool-panel__compact-header-search">
- <ToolSearch
- value={searchQuery}
- onChange={handleHeaderSearchChange}
- toolRegistry={toolRegistry}
- mode="filter"
- autoFocus={allToolsView && !inToolView}
- />
- </div>
- ) : null}
- {showCloseButton ? (
- <ActionIcon
- variant="tertiary"
- size="md"
- shape="circle"
- onClick={handleHeaderBack}
- aria-label={
- inToolView
- ? t("toolPanel.backToAllTools", "Back to all tools")
- : t("toolPanel.goBack", "Go back")
- }
- className="tool-panel__expand-btn"
- >
- <CloseIcon sx={{ fontSize: "1.1rem" }} />
- </ActionIcon>
- ) : (
- <ActionIcon
- variant="secondary"
- size="md"
- shape="circle"
- onClick={handleCollapse}
- aria-label={t("toolPanel.collapse", "Collapse panel")}
- className="tool-panel__expand-btn tool-panel__toggle-vt"
- >
- <ChevronRightIcon sx={{ fontSize: "1.1rem" }} />
- </ActionIcon>
- )}
- </div>
- ))}
-
- {showPolicies && (
- <PoliciesSection
- leadingControl={
- <ActionIcon
- aria-label={t("toolPanel.collapse", "Collapse panel")}
- variant="secondary"
- size="md"
- shape="circle"
- onClick={handleCollapse}
- className="tool-panel__expand-btn tool-panel__toggle-vt"
- >
- <ChevronRightIcon sx={{ fontSize: "1.1rem" }} />
- </ActionIcon>
- }
- />
- )}
+ <ActionIcon
+ variant="secondary"
+ size="md"
+ shape="circle"
+ onClick={handleCollapse}
+ aria-label={t("toolPanel.collapse", "Collapse panel")}
+ className="tool-panel__expand-btn tool-panel__toggle-vt"
+ >
+ <ChevronRightIcon sx={{ fontSize: "1.1rem" }} />
+ </ActionIcon>
+ )}
+ </div>
+ )}
- {showInlineSearch && (
- <div className="tool-panel__between-search">
- <ToolSearch
- value={searchQuery}
- onChange={handleHeaderSearchChange}
- toolRegistry={toolRegistry}
- mode="filter"
- />
- </div>
- )}
-
- <ToolPanel
- allToolsView={allToolsView}
- onShowAllTools={handleShowAllTools}
- onToolSelect={handleToolSelectWithTransition}
- compact={false}
- />
- </>
- )}
+ <ToolPanel
+ allToolsView={allToolsView}
+ onShowAllTools={handleShowAllTools}
+ onToolSelect={handleToolSelectWithTransition}
+ compact={false}
+ />
+ </>
</div>
)}
diff --git a/frontend/editor/src/core/tests/stubbed/policy-admin-gate.spec.ts b/frontend/editor/src/core/tests/stubbed/policy-admin-gate.spec.ts
deleted file mode 100644
index 7e60a8c189..0000000000
--- a/frontend/editor/src/core/tests/stubbed/policy-admin-gate.spec.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { test, expect } from "@app/tests/helpers/stub-test-base";
-
-/**
- * Policy editing is admin-only (mirrors the backend's enforcement on the
- * save/delete endpoints). The frontend gate is `canConfigure = !enableLogin ||
- * isAdmin`, surfaced through `usePolicies()`:
- * - login enabled + non-admin → read-only: the setup wizard shows the
- * "Managed by your organization" locked state instead of the steps.
- * - login enabled + admin → full setup flow ("Step 1 of 2").
- * - login disabled (single-user/desktop) → open to the local operator.
- *
- * Backend-free: the app-config (`enableLogin`/`isAdmin`) and the empty policy
- * list are stubbed via `mockAppApis`, so this asserts the gating wiring without
- * a live Spring Boot server. "Security" is the only non-coming-soon policy, so
- * it's the one we open.
- */
-
-const LOCKED_TITLE = "Managed by your organization";
-const LOCKED_DESC = "Contact a team leader to change this policy.";
-
-/** Open the Security policy from the right-sidebar Policies list. */
-async function openSecurityPolicy(page: import("@playwright/test").Page) {
- const row = page.locator("button.pol-row").filter({ hasText: "Security" });
- await expect(row).toBeVisible({ timeout: 15_000 });
- await row.click();
- // The wizard header confirms we opened the right policy in either state.
- await expect(page.getByText("Set up Security Policy")).toBeVisible();
-}
-
-// Policies are a SaaS-only feature: POLICIES_ENABLED is off in the proprietary
-// and core builds this stubbed suite runs against, so the policy UI never
-// renders here. Skip unless the app under test is built with policies enabled
-// and the runner opts in via POLICIES_E2E=1.
-test.beforeEach(() => {
- const enabled = ["1", "true"].includes(process.env.POLICIES_E2E ?? "");
- test.skip(!enabled, "Policies are SaaS-only; set POLICIES_E2E=1 to run");
-});
-
-test.describe("Policy editing gate — non-admin (login on)", () => {
- test.use({
- stubOptions: { enableLogin: true, isAdmin: false },
- seedJwt: true,
- });
-
- test("non-admin gets the read-only locked state", async ({ page }) => {
- await openSecurityPolicy(page);
- await expect(page.getByText(LOCKED_TITLE)).toBeVisible();
- await expect(page.getByText(LOCKED_DESC)).toBeVisible();
- // The editable flow must NOT be reachable.
- await expect(page.getByText(/Step \d+ of \d+/)).toHaveCount(0);
- });
-});
-
-test.describe("Policy editing gate — admin (login on)", () => {
- test.use({
- stubOptions: { enableLogin: true, isAdmin: true },
- seedJwt: true,
- });
-
- test("admin can reach the setup wizard", async ({ page }) => {
- await openSecurityPolicy(page);
- await expect(page.getByText(/Step \d+ of \d+/)).toBeVisible();
- await expect(page.getByText(LOCKED_TITLE)).toHaveCount(0);
- });
-});
-
-test.describe("Policy editing gate — single-user (login off)", () => {
- test.use({ stubOptions: { enableLogin: false, isAdmin: false } });
-
- test("local operator can reach the setup wizard with no admin role", async ({
- page,
- }) => {
- await openSecurityPolicy(page);
- await expect(page.getByText(/Step \d+ of \d+/)).toBeVisible();
- await expect(page.getByText(LOCKED_TITLE)).toHaveCount(0);
- });
-});
diff --git a/frontend/editor/src/desktop/components/policies/PoliciesSidebar.tsx b/frontend/editor/src/desktop/components/policies/PoliciesSidebar.tsx
deleted file mode 100644
index c757b0d260..0000000000
--- a/frontend/editor/src/desktop/components/policies/PoliciesSidebar.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Desktop shadow of the proprietary Policies right-rail.
- *
- * Re-exports the proprietary module unchanged EXCEPT `usePoliciesEnabled`, which
- * additionally requires an active SaaS connection. Policy runs execute + bill via
- * the cloud (POST /api/v1/policies/.../run hits the SaaS backend), so on desktop
- * the feature must be hidden in local ("disconnected") and self-hosted modes —
- * otherwise the panel + auto-run controller would fire policy runs against a
- * backend that doesn't serve them. On web the build flavor already gates it.
- *
- * `usePoliciesEnabled` is the single gate RightSidebar uses for BOTH the rail
- * section and mounting PolicyAutoRunController, so this one override covers both.
- */
-import { POLICIES_ENABLED } from "@app/constants/featureFlags";
-import { useConfirmedSaaSMode } from "@app/hooks/useConfirmedSaaSMode";
-
-export * from "@proprietary/components/policies/PoliciesSidebar";
-
-export function usePoliciesEnabled(): boolean {
- // Pessimistic SaaS-mode check (starts false): this gate also controls whether
- // PolicyAutoRunController mounts, and that fires GET /api/v1/policies on mount.
- // useSaaSMode()'s optimistic-true default would leak that request against the
- // local/self-hosted backend on cold start before the mode resolves.
- return POLICIES_ENABLED && useConfirmedSaaSMode();
-}
diff --git a/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
new file mode 100644
index 0000000000..efc8f33fa7
--- /dev/null
+++ b/frontend/editor/src/desktop/components/policies/usePoliciesEnabled.ts
@@ -0,0 +1,19 @@
+import { POLICIES_ENABLED } from "@app/constants/featureFlags";
+import { useConfirmedSaaSMode } from "@app/hooks/useConfirmedSaaSMode";
+
+/**
+ * Desktop shadow: policy runs execute + bill via the cloud (POST
+ * /api/v1/policies/.../run hits the SaaS backend), so the feature must stay
+ * off in local ("disconnected") and self-hosted modes — otherwise the
+ * auto-run controller would fire policy runs against a backend that doesn't
+ * serve them.
+ *
+ * Pessimistic SaaS-mode check (starts false): this gate controls whether
+ * PolicyAutoRunController mounts, and that fires GET /api/v1/policies on
+ * mount. useSaaSMode()'s optimistic-true default would leak that request
+ * against the local/self-hosted backend on cold start before the mode
+ * resolves.
+ */
+export function usePoliciesEnabled(): boolean {
+ return POLICIES_ENABLED && useConfirmedSaaSMode();
+}
diff --git a/frontend/editor/src/desktop/constants/featureFlags.ts b/frontend/editor/src/desktop/constants/featureFlags.ts
index 957860b7cf..d003b3e642 100644
--- a/frontend/editor/src/desktop/constants/featureFlags.ts
+++ b/frontend/editor/src/desktop/constants/featureFlags.ts
@@ -2,8 +2,8 @@
* Desktop-build feature gates. Shadows `proprietary/constants/featureFlags.ts`
* (the desktop `@app/*` alias has no saas layer). Re-exports the proprietary
* flags and re-enables Policies: the desktop Policies gate additionally requires
- * an active SaaS connection (see desktop PoliciesSidebar's `usePoliciesEnabled`),
- * so the flag must be on for that runtime check to ever apply.
+ * an active SaaS connection (see the desktop `usePoliciesEnabled` shadow), so
+ * the flag must be on for that runtime check to ever apply.
*/
export * from "@proprietary/constants/featureFlags";
diff --git a/frontend/editor/src/proprietary/components/policies/EnforcementQueueStatus.tsx b/frontend/editor/src/proprietary/components/policies/EnforcementQueueStatus.tsx
deleted file mode 100644
index e06bda98a3..0000000000
--- a/frontend/editor/src/proprietary/components/policies/EnforcementQueueStatus.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Compact status row for the {@link enforcementQueue}, shown in the Policies
- * panel whenever enforcement jobs are pending or running. The queue is serial,
- * so a slow policy run would otherwise be invisible — this surfaces what's being
- * enforced (before export, print, convert, …) and how many jobs are waiting.
- */
-import { useTranslation } from "react-i18next";
-import { Group, Text, Loader } from "@mantine/core";
-import { useEnforcementQueue } from "@app/components/policies/enforcementQueue";
-
-export function EnforcementQueueStatus() {
- const { t } = useTranslation();
- const jobs = useEnforcementQueue();
- const active = jobs.filter(
- (j) => j.status === "pending" || j.status === "running",
- );
- if (active.length === 0) return null;
-
- // The running job leads the row; everything else is still queued behind it.
- const lead = active.find((j) => j.status === "running") ?? active[0];
- const queued = active.length - 1;
-
- return (
- <Group
- gap="xs"
- wrap="nowrap"
- px="sm"
- py={6}
- role="status"
- aria-live="polite"
- >
- <Loader size="xs" />
- <Text size="xs" c="dimmed" truncate>
- {t(`policies.enforcement.triggerVerb.${lead.trigger}`, {
- defaultValue: t("policies.enforcement.triggerVerb.default"),
- })}
- : {lead.label}
- {queued > 0
- ? ` · ${t("policies.enforcement.queued", { count: queued })}`
- : "…"}
- </Text>
- </Group>
- );
-}
-
-export default EnforcementQueueStatus;
diff --git a/frontend/editor/src/proprietary/components/policies/Policies.css b/frontend/editor/src/proprietary/components/policies/Policies.css
deleted file mode 100644
index 3cbbb306f3..0000000000
--- a/frontend/editor/src/proprietary/components/policies/Policies.css
+++ /dev/null
@@ -1,709 +0,0 @@
-/* ============================ Policies ============================ */
-/* The Policies surface is docked in the right tool sidebar: a list section */
-/* above Tools, a detail takeover that replaces Tools when a policy is open, */
-/* and a collapsed-rail of policy icons. */
-/* */
-/* Chrome (headers, cards, buttons, badges, chips, lists, steps…) uses SUI */
-/* (@app/ui). The bespoke .pol-* bits below are thin layout */
-/* scaffolding + the collapsed rail; spacing snaps to the SUI --space-* */
-/* scale and colour to the SUI token set so it reads as one product. */
-
-/* Dark mode only: remap SUI surface/border tokens to the app's neutral-grey values so policy cards read as one product with the rail; accent tokens are left alone. */
-[data-theme="dark"] .pol-list,
-[data-theme="dark"] .pol-takeover,
-[data-theme="dark"] .pol-detail,
-[data-theme="dark"] .pol-crail {
- --color-bg: var(--bg-toolbar);
- --color-bg-alt: var(--bg-toolbar);
- --color-bg-subtle: var(--bg-toolbar);
- --color-surface: var(--bg-surface);
- --color-surface-alt: #323942;
- --color-bg-hover: #323942;
- --color-bg-muted: var(--bg-surface);
- --color-border: var(--border-default);
- --color-border-light: var(--border-subtle);
- --color-border-input: var(--border-strong);
- --color-border-hover: var(--border-strong);
- --color-divider: var(--border-subtle);
- --color-dropdown-bg: var(--bg-surface);
- --color-dropdown-border: var(--border-default);
-}
-
-/* ---- List ---- */
-.pol-list {
- width: 100%;
- display: flex;
- flex-direction: column;
-}
-/* Header row: optional leading control (sidebar collapse) + the SectionHeader,
- mirroring the back-button + title layout inside an open policy. */
-.pol-list-head {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- padding: var(--space-2) var(--space-3);
-}
-.pol-list-head .sui-sectionhdr {
- flex: 1;
- min-width: 0;
-}
-/* Small "what is a policy?" info button on the header. */
-/* Bare info icon matching the tool-step affordance (LocalIcon, no chrome). */
-.pol-info-btn {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- padding: 0;
- border: none;
- background: none;
- cursor: pointer;
- transition: opacity var(--motion-fast);
-}
-.pol-info-btn:hover {
- opacity: 0.7;
-}
-.pol-list-rows {
- display: flex;
- flex-direction: column;
- padding: var(--space-1) var(--space-1_5);
- gap: 0.0625rem;
-}
-/* A policy row: tinted icon tile + label + trailing status/CTA. */
-.pol-row {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- width: 100%;
- padding: var(--space-1_5) var(--space-2);
- border: none;
- border-radius: var(--radius-lg);
- background: transparent;
- cursor: pointer;
- text-align: left;
- transition: background var(--motion-fast);
-}
-.pol-row:hover {
- background: var(--color-bg-hover);
-}
-.pol-row:focus-visible {
- outline: 2px solid var(--color-blue);
- outline-offset: -2px;
-}
-/* Processing indicator: a spinning ring around the category icon while the
- policy has runs in flight. */
-.pol-row-icon {
- position: relative;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- --pol-ring: var(--color-blue);
-}
-.pol-row-icon[data-accent="purple"] {
- --pol-ring: var(--color-purple);
-}
-.pol-row-icon[data-accent="green"] {
- --pol-ring: var(--color-green);
-}
-.pol-row-icon[data-accent="amber"] {
- --pol-ring: var(--color-amber);
-}
-.pol-row-icon[data-accent="red"] {
- --pol-ring: var(--color-red);
-}
-.pol-row-icon[data-accent="orange"] {
- --pol-ring: var(--color-orange);
-}
-.pol-row-icon.is-processing .sui-iconbadge {
- --ib-accent: var(--ib-base);
-}
-.pol-row-ring {
- position: absolute;
- inset: -3px;
- border-radius: 999px;
- border: 2px solid color-mix(in srgb, var(--pol-ring) 20%, transparent);
- border-top-color: var(--pol-ring);
- animation: pol-ring-spin 0.7s linear infinite;
- pointer-events: none;
-}
-
-/* Global "Retry failed policies (N)" action under the panel header — one place
- to resume every file the chain stranded, whichever step failed. Amber, so it
- reads as "needs attention" without screaming error. */
-.pol-retry-failed {
- display: flex;
- align-items: center;
- gap: var(--space-1_5);
- width: calc(100% - 2 * var(--space-1_5));
- margin: 0 var(--space-1_5) var(--space-1);
- padding: var(--space-1) var(--space-2);
- border: none;
- border-radius: var(--radius-lg);
- font-family: inherit;
- font-size: 0.75rem;
- font-weight: 500;
- text-align: left;
- cursor: pointer;
- color: var(--color-amber, #d97706);
- background: color-mix(in srgb, var(--color-amber, #d97706) 12%, transparent);
- transition: background var(--motion-fast);
-}
-.pol-retry-failed:hover {
- background: color-mix(in srgb, var(--color-amber, #d97706) 20%, transparent);
-}
-.pol-retry-failed:focus-visible {
- outline: 2px solid var(--color-amber, #d97706);
- outline-offset: -2px;
-}
-@keyframes pol-ring-spin {
- to {
- transform: rotate(360deg);
- }
-}
-
-@media (prefers-reduced-motion: reduce) {
- .pol-row-ring {
- animation-duration: 2s;
- }
-}
-
-.pol-row-label {
- flex: 1;
- min-width: 0;
- /* Match a normal `sm` button label so icon-bearing rows aren't smaller. */
- font-size: 0.875rem;
- font-weight: 500;
- color: var(--color-text-1);
-}
-
-.pol-row > .mantine-Button-inner {
- width: 100%;
-}
-.pol-row > .mantine-Button-inner > .mantine-Button-label {
- flex: 1;
- min-width: 0;
- justify-content: flex-start;
- overflow: visible;
-}
-.pol-row-trail {
- display: inline-flex;
- align-items: center;
- gap: var(--space-1);
- margin-left: auto;
-}
-/* Unconfigured rows: a quiet blue "Set up" call-to-action instead of a status pill. */
-.pol-row-setup {
- font-size: 0.6875rem;
- font-weight: 600;
- color: var(--color-blue);
-}
-/* Trailing drill-in chevron on each policy row (after the status / CTA). */
-.pol-row-chevron {
- color: var(--color-text-4);
- flex-shrink: 0;
-}
-
-/* ── Policy settings: per-trigger run-order lists ── */
-.pol-reorder-section {
- margin-top: var(--space-3);
-}
-.pol-reorder-list {
- display: flex;
- flex-direction: column;
- margin-top: var(--space-1);
-}
-/* A reorder row: leading grip + tinted icon + label. Square (no radius) so the
- drop line reads as one straight rule across the list. */
-.pol-reorder-row {
- position: relative;
- display: flex;
- align-items: center;
- gap: var(--space-2);
- padding: var(--space-1_5) var(--space-2);
-}
-.pol-reorder-row[data-dragging] {
- opacity: 0.4;
-}
-/* Straight, full-width blue insertion line at the drop position (no curves). */
-.pol-reorder-row[data-drop="above"]::before,
-.pol-reorder-row[data-drop="below"]::after {
- content: "";
- position: absolute;
- left: 0;
- right: 0;
- height: 2px;
- background: var(--color-blue);
- pointer-events: none;
-}
-.pol-reorder-row[data-drop="above"]::before {
- top: -1px;
-}
-.pol-reorder-row[data-drop="below"]::after {
- bottom: -1px;
-}
-.pol-reorder-grip {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- width: 1.25rem;
- color: var(--color-text-4);
- cursor: grab;
-}
-.pol-reorder-grip:active {
- cursor: grabbing;
-}
-.pol-reorder-label {
- flex: 1;
- min-width: 0;
- font-size: 0.8125rem;
- font-weight: 500;
- color: var(--color-text-1);
-}
-/* The drag ghost (a cloned row): the whole row with a full blue outline, kept
- translucent so the list shows through as it moves. */
-.pol-reorder-row--ghost {
- border-radius: var(--radius-lg);
- outline: 2px solid var(--color-blue);
- outline-offset: -2px;
- background: var(--color-surface);
- box-shadow: var(--shadow-md);
- opacity: 0.55;
-}
-/* Empty-state line for a trigger with no policies. */
-.pol-reorder-empty {
- margin: var(--space-1) 0 0;
- padding: var(--space-1_5) var(--space-2);
- font-size: 0.8125rem;
- color: var(--color-text-3);
-}
-
-/* Retry button on a failed activity row. */
-/* Expandable error text in the activity feed — long backend errors are clamped
- and collapsed by default so they don't blow up the row. */
-.pol-activity-error {
- display: flex;
- flex-direction: column;
- align-items: flex-start;
- gap: 0.125rem;
-}
-.pol-activity-error__text {
- white-space: pre-wrap;
- word-break: break-word;
-}
-.pol-activity-error__text--clamped {
- display: -webkit-box;
- -webkit-line-clamp: 2;
- -webkit-box-orient: vertical;
- overflow: hidden;
-}
-.pol-activity-error__toggle {
- border: none;
- background: none;
- padding: 0;
- font-size: inherit;
- font-weight: 600;
- color: var(--color-blue);
- cursor: pointer;
-}
-.pol-activity-error__toggle:hover {
- text-decoration: underline;
-}
-
-/* Enterprise-only ("coming soon") row — shown to admins / team leaders but not
- available on the current plan, so the whole box is dimmed to read as disabled.
- The row itself isn't a button; its trailing "Upgrade to enterprise" link is. */
-.pol-row--soon {
- cursor: default;
- opacity: 0.55;
-}
-.pol-row--soon:hover {
- background: transparent;
-}
-/* Trailing "Upgrade to enterprise" link → contact us. Greyed to match the
- disabled row; still clickable for admins who want to enquire. */
-.pol-row-upgrade {
- font-size: 0.6875rem;
- font-weight: 600;
- color: var(--color-text-4);
- text-decoration: none;
- white-space: nowrap;
- cursor: pointer;
- transition: color var(--motion-fast);
-}
-.pol-row-upgrade:hover {
- color: var(--color-text-1);
-}
-.pol-row-upgrade:hover {
- text-decoration: underline;
-}
-
-/* In-progress activity icon spins gently. */
-.pol-spin {
- animation: pol-spin 1.2s linear infinite;
-}
-@keyframes pol-spin {
- to {
- transform: rotate(360deg);
- }
-}
-
-/* ---- Locked, per-tool config (PolicyToolConfig): one section per tool ---- */
-.pol-tool-config {
- display: flex;
- flex-direction: column;
- gap: var(--space-3);
-}
-.pol-tool-head {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- padding: var(--space-3);
-}
-.pol-tool-icon {
- display: inline-flex;
- align-items: center;
- color: var(--color-text-3);
-}
-.pol-tool-name {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--color-text-1);
- margin-right: auto;
-}
-.pol-tool-body {
- padding: 0 var(--space-3) var(--space-3);
- border-top: 1px solid var(--color-border);
- padding-top: var(--space-3);
-}
-
-/* ---- Detail container (wizard / narrative / settings share this) ---- */
-.pol-detail {
- display: flex;
- flex-direction: column;
- height: 100%;
- min-height: 0;
- max-width: 32rem;
- width: 100%;
-}
-
-/* ---- Step indicator (wraps a SUI StepIndicator) ---- */
-.pol-steps {
- display: flex;
- flex-direction: column;
- gap: 0.75rem;
- padding: 0 var(--space-5) var(--space-3);
- border-bottom: 1px solid var(--color-border);
-}
-.pol-step-label {
- font-size: 0.75rem;
- font-weight: 600;
- color: var(--color-text-4);
-}
-
-/* ---- Scroll body ---- */
-.pol-scroll {
- flex: 1;
- min-height: 0;
- overflow-y: auto;
- padding: var(--space-3) var(--space-5);
- display: flex;
- flex-direction: column;
- gap: var(--space-3);
-}
-.pol-desc {
- font-size: 0.8125rem;
- line-height: 1.5;
- color: var(--color-text-4);
- margin: 0;
- margin-bottom: var(--space-3);
-}
-.pol-section-label {
- font-size: 0.6875rem;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--color-text-4);
- /* Bottom gap so the label doesn't hug its card/chips. */
- margin: 0 0 var(--space-2);
-}
-
-/* A section label rendered as a collapse toggle (Recent Activity): strip the
- button chrome but keep the .pol-section-label typography, chevron pushed right. */
-.pol-section-toggle {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- width: 100%;
- background: none;
- border: none;
- padding: 0;
- cursor: pointer;
- text-align: left;
- font-family: inherit;
-}
-
-.pol-section-chevron {
- margin-left: auto;
- color: var(--color-text-4);
- transition: transform 0.15s ease;
-}
-.pol-section-chevron.is-open {
- transform: rotate(180deg);
-}
-
-/* Recent-activity feed: cap to ~4.5 rows (and never more than ~45% of the
- viewport) then scroll, so a long history doesn't push the stats footer away. */
-.pol-activity-list {
- max-height: min(22rem, 45vh);
- overflow-y: auto;
-}
-
-/* Sub-section header inside a settings card (e.g. "Output filename"). The field
- directly below it carries data-first so the borders don't double up. */
-.pol-subhead {
- padding: 0.55rem 0.875rem 0.4rem;
- font-size: 0.625rem;
- font-weight: 600;
- text-transform: uppercase;
- letter-spacing: 0.05em;
- color: var(--color-text-4);
- background: var(--color-surface);
- border-top: 1px solid var(--color-border);
-}
-
-/* Position dropdown + custom-text input sitting on one row under the
- "Output filename" subhead — the dropdown sizes to content, text fills. */
-.pol-name-row {
- display: flex;
- gap: var(--space-2);
- align-items: center;
-}
-.pol-name-row > :first-child {
- flex: 0 0 auto;
-}
-.pol-name-row > :last-child {
- flex: 1 1 auto;
- min-width: 0;
-}
-
-/* ---- Fields (PolicyFieldRow) — row inset matches SUI ListRow ---- */
-.pol-field {
- padding: 0.7rem 0.875rem;
- background: var(--color-surface);
-}
-.pol-field:not([data-first]) {
- border-top: 1px solid var(--color-border);
-}
-.pol-field-label {
- font-size: 0.8125rem;
- font-weight: 500;
- color: var(--color-text-1);
-}
-.pol-field-count {
- font-size: 0.6875rem;
- color: var(--color-text-4);
-}
-.pol-field-chips-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: var(--space-2);
-}
-.pol-field-chips {
- display: flex;
- flex-wrap: wrap;
- gap: var(--space-1_5);
-}
-
-/* ---- Sources ---- */
-.pol-source {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- padding: 0.7rem 0.875rem;
- cursor: pointer;
- background: var(--color-surface);
-}
-.pol-source:not([data-first]) {
- border-top: 1px solid var(--color-border);
-}
-
-/* ---- Doc types ---- */
-.pol-link {
- font-size: 0.75rem;
- font-weight: 500;
- color: var(--color-blue);
- background: none;
- border: none;
- padding: 0;
- cursor: pointer;
-}
-.pol-doctypes-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 0.7rem 0.875rem;
-}
-.pol-doctypes {
- display: flex;
- flex-direction: column;
- gap: var(--space-2);
- padding: var(--space-2) 0.875rem var(--space-3);
- border-top: 1px solid var(--color-border);
-}
-
-/* ---- Summary ---- */
-.pol-summary-head {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- margin-bottom: var(--space-2);
-}
-.pol-summary-title {
- font-size: 0.8125rem;
- font-weight: 600;
- color: var(--color-text-1);
-}
-.pol-summary-rows {
- display: flex;
- flex-direction: column;
- gap: var(--space-1_5);
-}
-/* Muted placeholder for an unset summary value (e.g. no reviewer chosen). */
-.pol-muted {
- color: var(--color-text-4);
-}
-
-/* ---- Enforces rule flow (wraps a SUI ChipFlow) ---- */
-.pol-rule-flow {
- margin-bottom: var(--space-2);
-}
-
-/* ---- Meta / note ---- */
-.pol-meta-row {
- display: flex;
- gap: var(--space-3);
- padding-top: var(--space-2);
- border-top: 1px solid var(--color-border);
-}
-.pol-meta-item {
- display: inline-flex;
- align-items: center;
- gap: var(--space-1_5);
- font-size: 0.75rem;
- color: var(--color-text-4);
-}
-.pol-note {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- margin-top: var(--space-2);
- padding: var(--space-2) var(--space-3);
- border-radius: var(--radius-lg);
- background: var(--color-bg-muted);
- font-size: 0.75rem;
- color: var(--color-text-4);
-}
-
-/* ---- Stats: one grouped card with three divided columns. ---- */
-.pol-stats {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
-}
-.pol-stat {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: var(--space-0_5);
- padding: var(--space-3) var(--space-2);
- text-align: center;
-}
-.pol-stat:not(:first-child) {
- border-left: 1px solid var(--color-border);
-}
-.pol-stat-value {
- font-size: 1rem;
- font-weight: 600;
- line-height: 1.1;
- color: var(--color-text-1);
-}
-.pol-stat-label {
- font-size: 0.6875rem;
- color: var(--color-text-4);
-}
-
-/* ---- Footer (hosts SUI Buttons) ---- */
-.pol-footer {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- padding: var(--space-3) var(--space-5);
- border-top: 1px solid var(--color-border);
- flex-shrink: 0;
-}
-.pol-footer-end {
- justify-content: flex-end;
-}
-
-/* ---- Detail takeover (fills the rail when a policy is open) ---- */
-.pol-takeover {
- flex: 1;
- min-height: 0;
- display: flex;
- flex-direction: column;
-}
-
-/* ---- Collapsed rail policy icons ---- */
-.pol-crail {
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: var(--space-1);
- flex-shrink: 0;
- /* The collapsed-rail dividers carry 8px of space below them only, so the
- divider above gives the row 8px of headroom while the one below (rendered
- straight after) hugs it. Match that 8px underneath so the row sits centred
- between the two dividers. */
- margin-bottom: 8px;
-}
-.pol-crail-btn {
- position: relative;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 2.25rem;
- height: 2.25rem;
- padding: 0;
- border: none;
- border-radius: var(--radius-md);
- background: transparent;
- color: var(--color-text-3);
- cursor: pointer;
- transition: background var(--motion-fast);
-}
-.pol-crail-btn:hover {
- background: var(--color-blue-light);
-}
-.pol-crail-btn[data-status="active"] {
- color: var(--color-blue);
-}
-.pol-crail-btn[data-status="paused"] {
- color: var(--color-amber);
-}
-.pol-crail-dot {
- position: absolute;
- top: 0.1rem;
- right: 0.1rem;
- width: 0.55rem;
- height: 0.55rem;
- border-radius: 50%;
- border: 2px solid var(--bg-toolbar, var(--color-surface));
-}
-.pol-crail-dot[data-status="active"] {
- background: var(--color-green);
-}
-.pol-crail-dot[data-status="paused"] {
- background: var(--color-amber);
-}
diff --git a/frontend/editor/src/proprietary/components/policies/Policies.stories.tsx b/frontend/editor/src/proprietary/components/policies/Policies.stories.tsx
deleted file mode 100644
index c13a4daf55..0000000000
--- a/frontend/editor/src/proprietary/components/policies/Policies.stories.tsx
+++ /dev/null
@@ -1,163 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import { PolicyDetailPanel } from "@app/components/policies/PolicyDetailPanel";
-import { PoliciesSection } from "@app/components/policies/PoliciesSidebar";
-import { POLICY_CATEGORIES, POLICY_CONFIG } from "@app/data/policyDefinitions";
-import type { PolicyActivityItem, PolicyStats } from "@app/types/policies";
-import "@app/components/policies/Policies.css";
-
-/**
- * The Policies surface lives in the editor's right tool sidebar. These stories
- * render the three rich detail surfaces (narrative / setup wizard / settings)
- * inside a frame the width of the rail when a policy is open (25rem), so the
- * SUI composition can be reviewed in isolation — no app shell, login, or
- * backend required. Toggle the Storybook theme switcher to check dark mode.
- */
-const RAIL_WIDTH = "25rem";
-
-/** Frame that mimics the right rail's open width + surface so the panel reads true. */
-function RailFrame({ children }: { children: React.ReactNode }) {
- return (
- <div
- style={{
- width: RAIL_WIDTH,
- height: "780px",
- display: "flex",
- flexDirection: "column",
- background: "var(--color-surface)",
- border: "1px solid var(--color-border)",
- borderRadius: "var(--radius-lg)",
- overflow: "hidden",
- }}
- >
- {children}
- </div>
- );
-}
-
-const ingestion = POLICY_CATEGORIES.find((c) => c.id === "ingestion")!;
-const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;
-
-// Illustrative activity/stats for the static stories. In the app these are
-// derived live from the user's real uploaded files (see policyLiveData).
-const sampleActivity: PolicyActivityItem[] = [
- {
- doc: "MSA_Acme_2026.pdf",
- action: "1.2 MB • enforced on upload",
- time: "2h ago",
- status: "enforced",
- },
- {
- doc: "scan_002.pdf",
- action: "Low confidence • flagged for review",
- time: "Yesterday",
- status: "flagged",
- },
-];
-const sampleStats: PolicyStats = {
- enforced: 1284,
- dataProcessed: "3.2 GB",
- activeFor: "18d",
-};
-
-const noop = () => {};
-
-const meta: Meta = {
- title: "Editor/Policies",
- parameters: { layout: "centered" },
-};
-export default meta;
-
-type Story = StoryObj;
-
-/** Configured policy, running — Enforces / Activity / Stats narrative. */
-export const DetailActive: Story = {
- render: () => (
- <RailFrame>
- <PolicyDetailPanel
- category={ingestion}
- config={POLICY_CONFIG.ingestion}
- status="active"
- steps={POLICY_CONFIG.ingestion.defaultOperations}
- activity={[
- {
- doc: "Q4_Report.pdf",
- action: "Enforcing…",
- time: "Just now",
- status: "processing",
- },
- ...sampleActivity,
- ]}
- stats={sampleStats}
- canConfigure
- canDelete
- onBack={noop}
- onEditSettings={noop}
- onTogglePause={noop}
- onDelete={noop}
- />
- </RailFrame>
- ),
-};
-
-/** Configured policy, paused — amber accent + warning badge. */
-export const DetailPaused: Story = {
- render: () => (
- <RailFrame>
- <PolicyDetailPanel
- category={security}
- config={POLICY_CONFIG.security}
- status="paused"
- activity={sampleActivity}
- stats={sampleStats}
- canConfigure
- canDelete
- onBack={noop}
- onEditSettings={noop}
- onTogglePause={noop}
- onDelete={noop}
- />
- </RailFrame>
- ),
-};
-
-/** Read-only view for a member without configure permission. */
-export const DetailManaged: Story = {
- render: () => (
- <RailFrame>
- <PolicyDetailPanel
- category={ingestion}
- config={POLICY_CONFIG.ingestion}
- status="active"
- activity={sampleActivity}
- stats={sampleStats}
- canConfigure={false}
- canDelete={false}
- onBack={noop}
- onEditSettings={noop}
- onTogglePause={noop}
- onDelete={noop}
- />
- </RailFrame>
- ),
-};
-
-/** The policy list section (above Tools). */
-export const ListSection: Story = {
- render: () => (
- <div
- style={{
- width: RAIL_WIDTH,
- background: "var(--color-surface)",
- border: "1px solid var(--color-border)",
- borderRadius: "var(--radius-lg)",
- padding: "var(--space-2) 0",
- }}
- >
- <PoliciesSection />
- </div>
- ),
-};
-
-// The setup + edit wizard embeds the Watch Folders automation builder (its
-// Workflow step), which needs the ToolWorkflow context - so the wizard is
-// exercised in-app, not via an isolated story here.
diff --git a/frontend/editor/src/proprietary/components/policies/PoliciesSidebar.test.tsx b/frontend/editor/src/proprietary/components/policies/PoliciesSidebar.test.tsx
deleted file mode 100644
index 2ab524b495..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PoliciesSidebar.test.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-import "fake-indexeddb/auto";
-import type { ReactNode } from "react";
-import { describe, it, expect, beforeEach, vi } from "vitest";
-import { render, screen, fireEvent } from "@testing-library/react";
-import { MantineProvider } from "@mantine/core";
-
-// The global setup mock returns the i18n KEY (t: (key) => key); these tests
-// assert the rendered English copy, so override locally to return the default
-// value passed to t() — mirroring i18next's runtime fallback when a key is
-// missing. (Interpolated strings are returned raw; no test here asserts them.)
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({
- t: (key: string, defaultValue?: string) =>
- typeof defaultValue === "string" ? defaultValue : key,
- i18n: { changeLanguage: vi.fn() },
- }),
- initReactI18next: { type: "3rdParty", init: vi.fn() },
- I18nextProvider: ({ children }: { children: ReactNode }) => children,
-}));
-
-// Policies ship gated SaaS-only via the build-flavor flag; these tests exercise
-// the component itself, so force the flag on regardless of the test build flavor.
-vi.mock("@app/constants/featureFlags", () => ({ POLICIES_ENABLED: true }));
-
-// usePolicies derives `canConfigure` from app-config; with no AppConfigProvider
-// here `config` is null, which (tri-state gate) hides the edit affordances. Mock
-// app-config as a single-user deployment (login off) so the local operator can
-// configure and the narrative view's Edit/Pause/Delete actions render.
-vi.mock("@app/contexts/AppConfigContext", async (orig) => ({
- ...(await orig<typeof import("@app/contexts/AppConfigContext")>()),
- useAppConfig: () => ({ config: { enableLogin: false } }),
-}));
-
-// The shared Tooltip (used by the "what is a policy?" info button) pulls in
-// preferences/sidebar contexts we don't set up here — passthrough it.
-vi.mock("@app/components/shared/Tooltip", () => ({
- Tooltip: ({ children }: { children: ReactNode }) => children,
-}));
-
-// The wizard's Workflow step embeds the Watch Folders automation builder, which
-// needs the ToolWorkflow context. Mock it: a stub that wires the save trigger to
-// hand back the seed automation, so the wizard's submit still completes.
-vi.mock("@app/components/policies/PolicyWorkflowStep", () => ({
- AutomationMode: { CREATE: "create", EDIT: "edit", SUGGESTED: "suggested" },
- PolicyWorkflowStep: (props: {
- automation: unknown;
- saveTriggerRef: { current: (() => void) | null };
- onComplete: (automation: unknown, toolRegistry: unknown) => void;
- }) => {
- props.saveTriggerRef.current = () => props.onComplete(props.automation, {});
- return null;
- },
-}));
-
-// The backend is the source of truth, but these UI tests run offline: list
-// rejects (so the mount reconcile keeps the local cache), while save/delete
-// resolve so the enable flow completes.
-vi.mock("@app/services/policyApi", () => ({
- listPolicies: vi.fn().mockRejectedValue(new Error("offline")),
- savePolicy: vi.fn().mockImplementation(async (p: { id?: string }) => ({
- ...p,
- id: p.id && p.id.length > 0 ? p.id : "be-test",
- })),
- getPolicy: vi.fn(),
- deletePolicy: vi.fn().mockResolvedValue(undefined),
- runStoredPolicy: vi.fn(),
- runPolicyPipeline: vi.fn(),
- getPolicyRun: vi.fn(),
-}));
-
-// Enabling a policy creates its backing Watched Folders WatchedFolder (IndexedDB);
-// jsdom's crypto lacks randomUUID, which watchedFolderStorage uses for folder ids.
-if (typeof globalThis.crypto?.randomUUID !== "function") {
- const orig = globalThis.crypto;
- vi.stubGlobal("crypto", {
- getRandomValues: orig?.getRandomValues?.bind(orig),
- randomUUID: () =>
- `p-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,
- });
-}
-import {
- PoliciesSection,
- PolicyDetailTakeover,
- usePolicyDetailActive,
-} from "@app/components/policies/PoliciesSidebar";
-import { resetPolicySelection } from "@app/components/policies/policySelectionStore";
-
-/**
- * Mirrors how RightSidebar swaps the policy list for the detail takeover: the
- * list shows above Tools when nothing is open, the takeover replaces it when a
- * policy is selected.
- */
-function PoliciesHost() {
- const active = usePolicyDetailActive();
- return active ? <PolicyDetailTakeover /> : <PoliciesSection />;
-}
-
-function renderHost() {
- return render(
- <MantineProvider>
- <PoliciesHost />
- </MantineProvider>,
- );
-}
-
-describe("Policies right-sidebar surface", () => {
- beforeEach(() => {
- localStorage.clear();
- // Seed a configured Security policy (the only live category) in the local
- // cache. The backend list is mocked to reject (offline), so the mount
- // reconcile leaves it in place — giving the narrative tests a policy to open.
- localStorage.setItem(
- "stirling-policies-state",
- JSON.stringify({
- security: {
- configured: true,
- status: "active",
- sources: ["editor"],
- scopeTypes: [],
- reviewerEmail: "",
- fieldValues: {},
- },
- }),
- );
- resetPolicySelection();
- });
-
- it("renders the policy list with every category", () => {
- renderHost();
- expect(screen.getByText("Policies")).toBeInTheDocument();
- for (const label of [
- "Ingestion",
- "Security",
- "Compliance",
- "Routing",
- "Retention",
- ]) {
- expect(screen.getByText(label)).toBeInTheDocument();
- }
- });
-
- it("shows Security as active and the unbuilt categories as upgrade-gated", () => {
- renderHost();
- expect(screen.getAllByText("Active").length).toBeGreaterThanOrEqual(1);
- // Ingestion, Compliance, Routing, Retention are locked for this release.
- expect(screen.getAllByText("Upgrade to enterprise")).toHaveLength(4);
- });
-
- it("does not open an upgrade-gated policy when its row is clicked", () => {
- renderHost();
- fireEvent.click(screen.getByText("Ingestion"));
- // The locked row isn't a button — we stay on the list, nothing opens.
- expect(screen.getByText("Policies")).toBeInTheDocument();
- expect(screen.queryByText("Enforces")).not.toBeInTheDocument();
- });
-
- it("opens the narrative view when a live policy is clicked", () => {
- renderHost();
- fireEvent.click(screen.getByText("Security"));
- expect(screen.getByText("Enforces")).toBeInTheDocument();
- expect(screen.getByText("Edit Settings")).toBeInTheDocument();
- });
-
- it("shows an honest empty activity feed when no files have been uploaded", async () => {
- renderHost();
- fireEvent.click(screen.getByText("Security"));
- expect(screen.getByText("Recent Activity")).toBeInTheDocument();
- // Activity is derived from real uploads; with none, the empty state shows.
- expect(await screen.findByText("No activity yet")).toBeInTheDocument();
- });
-
- it("returns to the list via the close button", () => {
- renderHost();
- fireEvent.click(screen.getByText("Security"));
- expect(screen.getByText("Enforces")).toBeInTheDocument();
- fireEvent.click(screen.getByLabelText("Close"));
- expect(screen.getByText("Policies")).toBeInTheDocument();
- });
-});
diff --git a/frontend/editor/src/proprietary/components/policies/PoliciesSidebar.tsx b/frontend/editor/src/proprietary/components/policies/PoliciesSidebar.tsx
deleted file mode 100644
index 99d9e3169d..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PoliciesSidebar.tsx
+++ /dev/null
@@ -1,927 +0,0 @@
-/**
- * Proprietary implementation of the right-sidebar Policies surface.
- *
- * Shadows the core stubs at {@code core/components/policies/PoliciesSidebar.tsx}
- * via the {@code @app/*} alias cascade. Three slots, all driven by the shared
- * {@link policySelectionStore} so they stay in sync:
- * • {@link PoliciesSection} — the collapsible policy list, rendered above the
- * Tools section in {@code RightSidebar} when no policy is open.
- * • {@link PolicyDetailTakeover} — the detail / wizard / settings view, which
- * replaces the Tools area when a policy is open.
- * • {@link PoliciesCollapsedButton} — the icon rail shown when the sidebar is
- * collapsed; clicking an icon selects the policy and expands the rail.
- */
-
-import {
- useState,
- useEffect,
- useMemo,
- type DragEvent,
- type ReactNode,
-} from "react";
-import { useTranslation } from "react-i18next";
-import { Menu } from "@mantine/core";
-import ChevronRightIcon from "@mui/icons-material/ChevronRight";
-import ReplayRounded from "@mui/icons-material/ReplayRounded";
-import DragIndicatorRounded from "@mui/icons-material/DragIndicatorRounded";
-import MoreHorizRounded from "@mui/icons-material/MoreHorizRounded";
-import TuneRounded from "@mui/icons-material/TuneRounded";
-import InfoOutlined from "@mui/icons-material/InfoOutlined";
-import { usePolicies } from "@app/hooks/usePolicies";
-import { usePolicyCatalog } from "@app/hooks/usePolicyCatalog";
-import { useAppConfig } from "@app/contexts/AppConfigContext";
-import { useAuth } from "@app/auth/UseSession";
-import { getPolicyAutomation } from "@app/services/policyFolders";
-import { watchedFolderStorage } from "@app/services/watchedFolderStorage";
-import {
- runsToActivity,
- runsToStats,
- progressByCategory,
- retryableFailedRuns,
- EMPTY_RUN_PROGRESS,
-} from "@app/services/policyLiveData";
-import {
- removeRun,
- usePolicyRuns,
- usePolicyWaveStart,
-} from "@app/components/policies/policyRunStore";
-import { runPolicyOnFile } from "@app/components/policies/usePolicyAutoRun";
-import type { FileId } from "@app/types/file";
-import type {
- AutomationConfig,
- AutomationOperation,
-} from "@app/types/automation";
-import type { WatchedFolder } from "@app/types/watchedFolders";
-import { POLICIES_ENABLED } from "@app/constants/featureFlags";
-import { Tooltip as AppTooltip } from "@app/components/shared/Tooltip";
-import { Button } from "@app/ui/Button";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { IconBadge } from "@app/ui/IconBadge";
-import {
- deriveRowStatus,
- STATUS_LABEL,
- ROW_ACCENT,
-} from "@app/components/policies/policyStatus";
-import { StatusBadge } from "@app/ui/StatusBadge";
-import { SectionHeader } from "@app/ui/SectionHeader";
-import { PolicySetupWizard } from "@app/components/policies/PolicySetupWizard";
-import { PolicyDetailPanel } from "@app/components/policies/PolicyDetailPanel";
-import { PolicyDeleteConfirmModal } from "@app/components/policies/PolicyDeleteConfirmModal";
-import type { PolicyCategory, PolicyConfigResult } from "@app/types/policies";
-import { PanelHeader } from "@app/ui/PanelHeader";
-import {
- usePolicySelection,
- selectPolicy,
- setPolicyDetailView,
- closePolicy,
- openPolicySettings,
- closePolicySettings,
-} from "@app/components/policies/policySelectionStore";
-import "@app/components/policies/Policies.css";
-
-/** localStorage key persisting the Policies section's expand/collapse state. */
-const POLICIES_COLLAPSED_KEY = "stirling-policies-section-collapsed";
-
-/** Whether the right rail should host the Policies section. True in proprietary. */
-export function usePoliciesEnabled(): boolean {
- return POLICIES_ENABLED;
-}
-
-/**
- * Whether the right rail should show the Policies section.
- */
-export function usePoliciesVisible(): boolean {
- const pol = usePolicies();
- const { categories } = usePolicyCatalog();
- if (!POLICIES_ENABLED) return false;
- return pol.canConfigure || categories.some((c) => !c.comingSoon);
-}
-
-/**
- * Whether the current user is a guest who can't open or configure policies —
- * an anonymous user on a login-enabled deployment (i.e. a SaaS sign-up prompt
- * candidate). The policy list stays visible but its rows don't open; the guest
- * sign-up banner explains why. A login-disabled single-user deployment has an
- * anonymous local operator with full access, so it is not gated.
- */
-export function usePolicyGuestBlocked(): boolean {
- const { config } = useAppConfig();
- const { user } = useAuth();
- return config?.enableLogin === true && user?.is_anonymous === true;
-}
-
-/** Re-summon the guest sign-up banner (the saas GuestUserBanner listens for this;
- * a no-op on builds without it). Used when a guest clicks a gated policy. */
-function promptGuestSignup(): void {
- window.dispatchEvent(new CustomEvent("stirling:show-guest-banner"));
-}
-
-/**
- * Whether a policy is open — i.e. its detail view should take over the rail in
- * place of the tool list. False when the feature is off or nothing is selected.
- */
-export function usePolicyDetailActive(): boolean {
- const { selectedId, settingsOpen } = usePolicySelection();
- return POLICIES_ENABLED && (selectedId != null || settingsOpen);
-}
-
-/** The collapsible policy list, rendered above the Tools section. */
-export function PoliciesSection({
- leadingControl,
-}: {
- /** Optional control rendered to the left of the header (e.g. the sidebar
- * collapse button), mirroring the back-button + title in a policy. */
- leadingControl?: ReactNode;
-} = {}) {
- const { t } = useTranslation();
- const pol = usePolicies();
- const { categories } = usePolicyCatalog();
- const guestBlocked = usePolicyGuestBlocked();
-
- // Live run tallies drive the per-row processing ring + the header summary,
- // scoped to the current upload wave so they don't accumulate across the whole
- // persisted run history.
- const runs = usePolicyRuns();
- const waveStart = usePolicyWaveStart();
- const progress = useMemo(
- () => progressByCategory(runs, waveStart),
- [runs, waveStart],
- );
- // Failed runs still worth retrying, across ALL policies — drives the single
- // global "Retry failed policies" action. Deliberately not per-policy: a chain
- // failure strands the file mid-pipeline whichever step failed, and retrying
- // globally resumes every stranded file (successful steps are never re-run;
- // completed runs chain onward automatically). NOT wave-scoped: failures from
- // earlier uploads still count.
- const retryableRuns = useMemo(() => retryableFailedRuns(runs), [runs]);
- const retryAllFailed = () => {
- // Same replace-in-place pattern as the queue-full auto-retry: drop the stale
- // failed row, fire a fresh run. Queue-full rejections during the burst are
- // absorbed by the existing backoff.
- for (const failed of retryableRuns) {
- const backendId = pol.policies[failed.categoryId]?.backendId;
- if (!backendId) continue;
- removeRun(failed.runId);
- void runPolicyOnFile(
- failed.categoryId,
- backendId,
- failed.fileId as FileId,
- failed.fileName,
- );
- }
- };
- // Persist the expand/collapse state across refreshes.
- const [expanded, setExpanded] = useState(() => {
- try {
- return localStorage.getItem(POLICIES_COLLAPSED_KEY) !== "1";
- } catch {
- return true;
- }
- });
- const toggleExpanded = () =>
- setExpanded((open) => {
- const next = !open;
- try {
- localStorage.setItem(POLICIES_COLLAPSED_KEY, next ? "0" : "1");
- } catch {
- // Best-effort; ignore quota/availability failures.
- }
- return next;
- });
-
- if (!POLICIES_ENABLED) return null;
-
- // Admins / team leads see the full catalogue (coming-soon rows greyed as an
- // enterprise upsell); regular users only see the live policies — the
- // coming-soon "Upgrade to enterprise" rows are hidden from them.
- const visibleCategories = pol.canConfigure
- ? categories
- : categories.filter((c) => !c.comingSoon);
- if (visibleCategories.length === 0) return null;
-
- // The header tally counts every CONFIGURED policy (active + paused), not just
- // the active ones.
- const configuredCount = categories.filter(
- (c) => pol.policies[c.id]?.configured,
- ).length;
-
- // Rows render in execution order (defaults to catalog order until reordered
- // on the Policy settings page).
- const displayCategories = [...visibleCategories].sort(
- (a, b) =>
- (pol.policies[a.id]?.order ?? 0) - (pol.policies[b.id]?.order ?? 0),
- );
-
- return (
- <div className="pol-list">
- <div className="pol-list-head">
- {leadingControl}
- <SectionHeader
- title={t("policies.sidebar.title", "Policies")}
- count={t("policies.sidebar.activeCount", "{{count}} active", {
- count: configuredCount,
- })}
- collapsible
- expanded={expanded}
- onToggle={toggleExpanded}
- />
- <Menu position="bottom-end" width="13rem" withinPortal>
- <Menu.Target>
- <ActionIcon
- variant="quiet"
- className="pol-info-btn"
- aria-label={t(
- "policies.sidebar.optionsAriaLabel",
- "Policy options",
- )}
- >
- <MoreHorizRounded sx={{ fontSize: "1.25rem" }} />
- </ActionIcon>
- </Menu.Target>
- <Menu.Dropdown>
- {/* Hovering surfaces the same explanation the info tooltip used to show. */}
- <AppTooltip
- content={t(
- "policies.sidebar.infoTooltip",
- "A policy is a fixed set of tools that runs automatically whenever it's triggered — for example when a new document arrives — enforcing rules like redacting PII with no manual steps.",
- )}
- position="left"
- maxWidth="16rem"
- >
- <Menu.Item
- leftSection={<InfoOutlined sx={{ fontSize: "1rem" }} />}
- >
- {t("policies.sidebar.whatIsPolicy", "What is a policy?")}
- </Menu.Item>
- </AppTooltip>
- {pol.canConfigure && (
- <Menu.Item
- leftSection={<TuneRounded sx={{ fontSize: "1rem" }} />}
- onClick={() => openPolicySettings()}
- >
- {t("policies.sidebar.policySettings", "Policy settings")}
- </Menu.Item>
- )}
- </Menu.Dropdown>
- </Menu>
- </div>
-
- {retryableRuns.length > 0 && !guestBlocked && (
- <Button
- variant="secondary"
- size="sm"
- fullWidth
- className="pol-retry-failed"
- onClick={retryAllFailed}
- leftSection={<ReplayRounded sx={{ fontSize: "0.95rem" }} />}
- >
- {t(
- "policies.sidebar.retryFailed",
- "Retry failed policies ({{count}})",
- {
- count: retryableRuns.length,
- },
- )}
- </Button>
- )}
-
- {expanded && (
- <>
- <div className="pol-list-rows">
- {displayCategories.map((cat) => {
- if (cat.comingSoon) {
- return (
- <div key={cat.id} className="pol-row pol-row--soon">
- <IconBadge size="sm" accent={ROW_ACCENT[cat.id] ?? "blue"}>
- {cat.icon}
- </IconBadge>
- <span className="pol-row-label">
- {t(`policies.catalog.${cat.id}`, cat.label)}
- </span>
- <span className="pol-row-trail">
- <Button
- variant="quiet"
- size="sm"
- fontSize="xs"
- accent="neutral"
- onClick={() =>
- window.open(
- "https://stirling.com/contact",
- "_blank",
- "noopener,noreferrer",
- )
- }
- >
- {t(
- "policies.sidebar.upgradeToEnterprise",
- "Upgrade to enterprise",
- )}
- </Button>
- </span>
- </div>
- );
- }
- const status = deriveRowStatus(pol.policies[cat.id]);
- const rowProgress = progress.get(cat.id) ?? EMPTY_RUN_PROGRESS;
- const isProcessing = rowProgress.running > 0;
- const icon = (
- <span
- className={`pol-row-icon${isProcessing ? " is-processing" : ""}`}
- data-accent={ROW_ACCENT[cat.id] ?? "blue"}
- >
- {isProcessing && (
- <span className="pol-row-ring" aria-hidden="true" />
- )}
- <IconBadge size="sm" accent={ROW_ACCENT[cat.id] ?? "blue"}>
- {cat.icon}
- </IconBadge>
- </span>
- );
- return (
- <Button
- key={cat.id}
- type="button"
- variant="tertiary"
- hover={false}
- fullWidth
- justify="between"
- className="pol-row"
- leftSection={
- rowProgress.total > 0 ? (
- <AppTooltip
- position="left"
- content={t(
- "policies.sidebar.rowProgress",
- "{{completed}} of {{total}} files processed",
- {
- completed: rowProgress.completed,
- total: rowProgress.total,
- },
- )}
- >
- {icon}
- </AppTooltip>
- ) : (
- icon
- )
- }
- rightSection={
- <span className="pol-row-trail">
- {status === "setup" ? (
- <span className="pol-row-setup">
- {t("policies.sidebar.setUp", "Set up")}
- </span>
- ) : (
- <StatusBadge
- tone={status === "active" ? "success" : "warning"}
- size="sm"
- >
- {t(`policies.status.${status}`, STATUS_LABEL[status])}
- </StatusBadge>
- )}
- <ChevronRightIcon
- className="pol-row-chevron"
- sx={{ fontSize: "1rem" }}
- />
- </span>
- }
- onClick={() =>
- guestBlocked ? promptGuestSignup() : selectPolicy(cat.id)
- }
- >
- <span className="pol-row-label">
- {t(`policies.catalog.${cat.id}`, cat.label)}
- </span>
- </Button>
- );
- })}
- </div>
- </>
- )}
- </div>
- );
-}
-
-/**
- * Takeover dispatcher: shows the policy-settings page (execution order), an open
- * policy's detail, or nothing — whichever the selection store currently holds.
- * The heavy per-policy hooks live in {@link PolicyOpenDetail}, so the settings
- * page doesn't pay for (or trip over) them.
- */
-export function PolicyDetailTakeover() {
- const { selectedId, settingsOpen } = usePolicySelection();
- if (!POLICIES_ENABLED) return null;
- if (settingsOpen && selectedId == null) return <PolicySettingsPanel />;
- if (selectedId == null) return null;
- return <PolicyOpenDetail />;
-}
-
-/**
- * The open-policy view — narrative detail, setup wizard, or edit-settings —
- * which replaces the Tools area while a policy is selected.
- */
-function PolicyOpenDetail() {
- const { t } = useTranslation();
- const pol = usePolicies();
- const { categories, configs, sources, docTypes } = usePolicyCatalog();
- const { selectedId, detailView } = usePolicySelection();
-
- // The configured policy's backing folder + automation (its real, editable
- // pipeline). `reloadKey` bumps after the edit modal saves so the detail
- // reflects the new steps. Falls back to the preset's rules when unconfigured.
- const folderId = selectedId ? pol.policies[selectedId]?.folderId : undefined;
- const [steps, setSteps] = useState<AutomationOperation[]>([]);
- const [backingFolder, setBackingFolder] = useState<WatchedFolder | null>(
- null,
- );
- const [backingAutomation, setBackingAutomation] =
- useState<AutomationConfig | null>(null);
- const [reloadKey, setReloadKey] = useState(0);
- const [confirmingDelete, setConfirmingDelete] = useState(false);
- useEffect(() => {
- if (!folderId) {
- setSteps([]);
- setBackingFolder(null);
- setBackingAutomation(null);
- return;
- }
- let cancelled = false;
- void (async () => {
- const [folder, automation] = await Promise.all([
- watchedFolderStorage.getFolder(folderId),
- getPolicyAutomation(folderId),
- ]);
- if (cancelled) return;
- setBackingFolder(folder);
- setBackingAutomation(automation);
- setSteps(automation?.operations ?? []);
- })();
- return () => {
- cancelled = true;
- };
- }, [folderId, reloadKey]);
-
- // Activity/stats come from the real backend runs the auto-run controller fires
- // on every upload (policyRunStore), filtered to this policy's category. The
- // store is reactive, so the feed updates live as runs progress — no polling
- // here (the controller does the run-status polling).
- const allRuns = usePolicyRuns();
- const categoryRuns = useMemo(
- () => allRuns.filter((r) => r.categoryId === selectedId),
- [allRuns, selectedId],
- );
-
- if (!POLICIES_ENABLED || selectedId == null) return null;
-
- const category = categories.find((c) => c.id === selectedId);
- const state = pol.policies[selectedId];
- const config = configs[selectedId];
- if (!category || !state || !config) return null;
- // Coming-soon categories can't be opened (the list row is locked anyway).
- if (category.comingSoon) return null;
-
- const status = deriveRowStatus(state);
-
- const onSetupClassification = () => {
- const classifier = categories.find((c) => c.providesClassification);
- if (classifier) selectPolicy(classifier.id);
- };
-
- // Preset (tool-chain) policies configure via the wizard's locked tool-config
- // step instead of the add/remove builder; the wizard fires onCommitConfig for
- // them (and onComplete for builder-based categories). One commit path serves
- // both first-time configure and edits.
- const commitConfig = (result: PolicyConfigResult) =>
- pol.commitPolicyConfig(selectedId, result).then(() => {
- setReloadKey((k) => k + 1);
- setPolicyDetailView("detail");
- });
-
- // Setup: the shared wizard in create mode.
- if (!state.configured) {
- return (
- <PolicySetupWizard
- key={selectedId}
- category={category}
- config={config}
- initial={state}
- sources={sources}
- docTypes={docTypes}
- canConfigure={pol.canConfigure}
- // No standalone classification policy exists yet to enable doc-type
- // narrowing, so it stays off for this release.
- classificationEnabled={false}
- mode="create"
- onCancel={() => closePolicy()}
- onComplete={(result) =>
- pol
- .enablePolicy(selectedId, result)
- .then(() => setPolicyDetailView("detail"))
- }
- onCommitConfig={commitConfig}
- onSetupClassification={onSetupClassification}
- />
- );
- }
-
- // Edit: the same wizard in edit mode, pre-filled — so editing has the settings
- // steps (not just the workflow). Wait for the backing automation to load so
- // the workflow step edits the real pipeline.
- if (detailView === "settings" && pol.canConfigure) {
- if (!backingAutomation) {
- return (
- <div className="pol-detail">
- <div className="pol-scroll">
- <p className="pol-desc">
- {t("policies.sidebar.loading", "Loading…")}
- </p>
- </div>
- </div>
- );
- }
- return (
- <PolicySetupWizard
- key={`edit-${selectedId}`}
- category={category}
- config={config}
- initial={state}
- sources={sources}
- docTypes={docTypes}
- canConfigure={pol.canConfigure}
- classificationEnabled={false}
- mode="edit"
- existingAutomation={backingAutomation}
- initialFolder={backingFolder ?? undefined}
- onCancel={() => setPolicyDetailView("detail")}
- onComplete={(result) =>
- pol.savePolicyConfig(selectedId, result).then(() => {
- setReloadKey((k) => k + 1);
- setPolicyDetailView("detail");
- })
- }
- onCommitConfig={commitConfig}
- onSetupClassification={onSetupClassification}
- />
- );
- }
-
- return (
- <>
- <PolicyDetailPanel
- category={category}
- config={config}
- status={status}
- steps={steps}
- activity={runsToActivity(categoryRuns)}
- stats={runsToStats(categoryRuns, backingFolder?.createdAt)}
- canConfigure={pol.canConfigure}
- canDelete={!state.isDefault}
- onBack={() => closePolicy()}
- onEditSettings={() => {
- // Seeded/active policies may have no backing folder yet — create one
- // from the preset so there's a workflow to edit, then open settings.
- void pol
- .ensurePolicyFolder(selectedId)
- .then(() => setPolicyDetailView("settings"));
- }}
- onTogglePause={() =>
- status === "paused"
- ? pol.resumePolicy(selectedId)
- : pol.pausePolicy(selectedId)
- }
- onDelete={() => setConfirmingDelete(true)}
- onRetry={(item) => {
- if (item.fileId && state.backendId) {
- void runPolicyOnFile(
- selectedId,
- state.backendId,
- item.fileId as FileId,
- item.doc,
- );
- }
- }}
- />
- {confirmingDelete && (
- <PolicyDeleteConfirmModal
- opened
- label={category.label}
- onCancel={() => setConfirmingDelete(false)}
- onConfirm={() => {
- setConfirmingDelete(false);
- closePolicy();
- void pol.deletePolicy(selectedId);
- }}
- />
- )}
- </>
- );
-}
-
-/**
- * The Policy settings takeover — reached from the section header's "…" menu.
- * Each trigger (upload / export) gets its own run-order list, since a chain only
- * spans policies that fire on the same trigger — reordering one never affects the
- * other. Admin-only (the menu entry is gated on canConfigure).
- */
-function PolicySettingsPanel() {
- const { t } = useTranslation();
- const pol = usePolicies();
- const { categories } = usePolicyCatalog();
-
- // Configured, live policies for a trigger, in execution order.
- const inOrder = (trigger: "upload" | "export") =>
- categories
- .filter(
- (c) =>
- pol.policies[c.id]?.configured &&
- !c.comingSoon &&
- (pol.policies[c.id]?.runOn ?? "upload") === trigger,
- )
- .sort(
- (a, b) =>
- (pol.policies[a.id]?.order ?? 0) - (pol.policies[b.id]?.order ?? 0),
- );
-
- const uploadCats = inOrder("upload");
- const exportCats = inOrder("export");
-
- // Order is one global sort key, so persist both groups together (upload first)
- // to keep each group's members contiguous — the auto-run chain reads relative
- // order within a trigger.
- const persist = (uploadIds: string[], exportIds: string[]) =>
- pol.reorderPolicies([...uploadIds, ...exportIds]);
-
- return (
- <div className="pol-detail">
- <PanelHeader
- icon={<TuneRounded sx={{ fontSize: "1.1rem" }} />}
- title={t("policies.settings.title", "Policy settings")}
- onClose={() => closePolicySettings()}
- closeLabel={t("policies.detail.close", "Close")}
- />
- <div className="pol-scroll">
- <p className="pol-desc">
- {t(
- "policies.settings.runOrderDesc",
- "When more than one policy runs on the same trigger, they run in this order — each on the previous policy's output. Drag to reorder.",
- )}
- </p>
- {/* Both triggers are always shown so the run order for each is explicit,
- with an empty note when a trigger has no policies. */}
- <PolicyReorderSection
- title={t("policies.settings.onUpload", "On upload")}
- cats={uploadCats}
- emptyText={t(
- "policies.settings.noneUpload",
- "No policies currently run on upload.",
- )}
- onReorder={(ids) =>
- persist(
- ids,
- exportCats.map((c) => c.id),
- )
- }
- />
- <PolicyReorderSection
- title={t("policies.settings.onExport", "On export")}
- cats={exportCats}
- emptyText={t(
- "policies.settings.noneExport",
- "No policies currently run on export.",
- )}
- onReorder={(ids) =>
- persist(
- uploadCats.map((c) => c.id),
- ids,
- )
- }
- />
- </div>
- </div>
- );
-}
-
-/**
- * One trigger's run-order list. Rows drag to reorder (only when there's more than
- * one to order); the drag ghost is the whole row with a blue outline, and a
- * straight blue line marks where the policy will land. Reorders in isolation and
- * hands the new id order back to the parent to persist.
- */
-function PolicyReorderSection({
- title,
- cats,
- emptyText,
- onReorder,
-}: {
- title: string;
- cats: PolicyCategory[];
- emptyText: string;
- onReorder: (orderedIds: string[]) => void;
-}) {
- const { t } = useTranslation();
- const [dragId, setDragId] = useState<string | null>(null);
- const [overId, setOverId] = useState<string | null>(null);
- // Whether the drop would land after (vs before) the hovered row.
- const [overBelow, setOverBelow] = useState(false);
- const draggable = cats.length >= 2;
-
- const clear = () => {
- setDragId(null);
- setOverId(null);
- };
-
- const handleDrop = (targetId: string) => {
- if (!dragId || dragId === targetId) return clear();
- const ids = cats.map((c) => c.id);
- const from = ids.indexOf(dragId);
- let to = ids.indexOf(targetId) + (overBelow ? 1 : 0);
- if (from < 0 || to < 0) return clear();
- ids.splice(from, 1);
- if (from < to) to -= 1;
- ids.splice(to, 0, dragId);
- onReorder(ids);
- clear();
- };
-
- // The native drag image would be just the grip under the cursor; instead snapshot
- // the whole row (a styled clone) so the ghost that follows the mouse is the full
- // row with a blue outline.
- const startDrag = (e: DragEvent<HTMLSpanElement>, catId: string) => {
- setDragId(catId);
- e.dataTransfer.effectAllowed = "move";
- const row = (e.currentTarget as HTMLElement).closest(".pol-reorder-row");
- if (row instanceof HTMLElement) {
- const clone = row.cloneNode(true) as HTMLElement;
- clone.classList.add("pol-reorder-row--ghost");
- clone.style.width = `${row.offsetWidth}px`;
- clone.style.position = "fixed";
- clone.style.top = "-1000px";
- clone.style.left = "-1000px";
- clone.style.pointerEvents = "none";
- document.body.appendChild(clone);
- e.dataTransfer.setDragImage(clone, 24, row.offsetHeight / 2);
- window.setTimeout(() => clone.remove(), 0);
- }
- };
-
- if (cats.length === 0) {
- return (
- <section className="pol-reorder-section">
- <p className="pol-section-label">{title}</p>
- <p className="pol-reorder-empty">{emptyText}</p>
- </section>
- );
- }
-
- return (
- <section className="pol-reorder-section">
- <p className="pol-section-label">{title}</p>
- <div className="pol-reorder-list">
- {cats.map((cat) => (
- <div
- key={cat.id}
- className="pol-reorder-row"
- data-dragging={dragId === cat.id || undefined}
- data-drop={
- draggable && overId === cat.id && dragId !== cat.id
- ? overBelow
- ? "below"
- : "above"
- : undefined
- }
- onDragOver={
- draggable
- ? (e) => {
- if (!dragId) return;
- e.preventDefault();
- const rect = e.currentTarget.getBoundingClientRect();
- setOverId(cat.id);
- setOverBelow(e.clientY > rect.top + rect.height / 2);
- }
- : undefined
- }
- onDragLeave={
- draggable
- ? () => setOverId((id) => (id === cat.id ? null : id))
- : undefined
- }
- onDrop={
- draggable
- ? (e) => {
- e.preventDefault();
- handleDrop(cat.id);
- }
- : undefined
- }
- >
- {draggable && (
- <span
- className="pol-reorder-grip"
- draggable
- onDragStart={(e) => startDrag(e, cat.id)}
- onDragEnd={clear}
- role="button"
- tabIndex={-1}
- aria-label={t(
- "policies.settings.reorderHandle",
- "Drag to reorder",
- )}
- >
- <DragIndicatorRounded sx={{ fontSize: "1rem" }} />
- </span>
- )}
- <IconBadge size="sm" accent={ROW_ACCENT[cat.id] ?? "blue"}>
- {cat.icon}
- </IconBadge>
- <span className="pol-reorder-label">
- {t(`policies.catalog.${cat.id}`, cat.label)}
- </span>
- </div>
- ))}
- </div>
- </section>
- );
-}
-
-/**
- * Collapsed-rail policy icons. Each tints blue when active and carries a small
- * status dot (green active / amber paused). Clicking selects the policy and
- * expands the rail.
- */
-export function PoliciesCollapsedButton({
- onExpand,
-}: {
- onExpand: () => void;
-}) {
- const { t } = useTranslation();
- const pol = usePolicies();
- const { categories } = usePolicyCatalog();
- const guestBlocked = usePolicyGuestBlocked();
-
- if (!POLICIES_ENABLED) return null;
-
- // Coming-soon policies are excluded; admins see all real policies, others only see configured ones — renders nothing when empty.
- const railCategories = categories.filter((cat) => {
- if (cat.comingSoon) return false;
- if (pol.canConfigure) return true;
- return pol.policies[cat.id]?.configured;
- });
- if (railCategories.length === 0) return null;
-
- return (
- <>
- <div className="pol-crail">
- {railCategories.map((cat) => {
- const status = deriveRowStatus(pol.policies[cat.id]);
- const label = t(`policies.catalog.${cat.id}`, cat.label);
- const statusLabel = t(
- `policies.status.${status}`,
- STATUS_LABEL[status],
- );
- const suffix =
- status === "active"
- ? t("policies.sidebar.railSuffixActive", " (Active)")
- : status === "paused"
- ? t("policies.sidebar.railSuffixPaused", " (Paused)")
- : "";
- return (
- <AppTooltip
- key={cat.id}
- content={`${label}${suffix}`}
- position="left"
- arrow
- delay={300}
- >
- <Button
- type="button"
- variant="tertiary"
- hover={false}
- className="pol-crail-btn"
- data-status={status}
- aria-label={t(
- "policies.sidebar.railAriaLabel",
- "{{label}} policy — {{status}}",
- { label, status: statusLabel },
- )}
- onClick={() => {
- if (guestBlocked) {
- promptGuestSignup();
- return;
- }
- selectPolicy(cat.id);
- onExpand();
- }}
- >
- {cat.icon}
- {(status === "active" || status === "paused") && (
- <span className="pol-crail-dot" data-status={status} />
- )}
- </Button>
- </AppTooltip>
- );
- })}
- </div>
- <div className="tool-panel__collapsed-divider" />
- </>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyDeleteConfirmModal.tsx b/frontend/editor/src/proprietary/components/policies/PolicyDeleteConfirmModal.tsx
deleted file mode 100644
index 89d3dde57a..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicyDeleteConfirmModal.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { Modal, Text, Stack, Group } from "@mantine/core";
-import { useTranslation } from "react-i18next";
-import { Button } from "@app/ui/Button";
-
-interface PolicyDeleteConfirmModalProps {
- opened: boolean;
- /** The policy's display label (the category name). */
- label: string;
- onConfirm: () => void;
- onCancel: () => void;
-}
-
-/** Confirm before deleting a policy — removing it discards its backing workflow. */
-export function PolicyDeleteConfirmModal({
- opened,
- label,
- onConfirm,
- onCancel,
-}: PolicyDeleteConfirmModalProps) {
- const { t } = useTranslation();
- return (
- <Modal
- opened={opened}
- onClose={onCancel}
- title={t("policies.deleteConfirmTitle", "Delete {{label}} policy?", {
- label,
- })}
- centered
- size="sm"
- >
- <Stack gap="md">
- <Text size="sm">
- {t(
- "policies.deleteConfirmBody",
- "This removes the policy and its workflow. Documents already processed are not affected.",
- )}
- </Text>
- <Group gap="sm" justify="flex-end">
- <Button variant="secondary" size="sm" onClick={onCancel}>
- {t("cancel", "Cancel")}
- </Button>
- <Button accent="danger" size="sm" onClick={onConfirm}>
- {t("delete", "Delete")}
- </Button>
- </Group>
- </Stack>
- </Modal>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyDetailPanel.tsx b/frontend/editor/src/proprietary/components/policies/PolicyDetailPanel.tsx
deleted file mode 100644
index 95f554edcc..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicyDetailPanel.tsx
+++ /dev/null
@@ -1,338 +0,0 @@
-import { useState } from "react";
-import { useTranslation } from "react-i18next";
-import PublicIcon from "@mui/icons-material/Public";
-import ScheduleIcon from "@mui/icons-material/Schedule";
-import HistoryIcon from "@mui/icons-material/History";
-import DescriptionIcon from "@mui/icons-material/Description";
-import CheckCircleIcon from "@mui/icons-material/CheckCircle";
-import WarningAmberIcon from "@mui/icons-material/WarningAmber";
-import AutorenewIcon from "@mui/icons-material/Autorenew";
-import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown";
-import LockIcon from "@mui/icons-material/Lock";
-import DeleteOutlineIcon from "@mui/icons-material/DeleteOutlined";
-import { PanelHeader } from "@app/ui/PanelHeader";
-import { ROW_ACCENT } from "@app/components/policies/policyStatus";
-import { Card } from "@app/ui/Card";
-import { ChipFlow } from "@app/ui/ChipFlow";
-import { StatusBadge } from "@app/ui/StatusBadge";
-import { EmptyState } from "@app/ui/EmptyState";
-import { Button } from "@app/ui/Button";
-import { Banner } from "@app/ui/Banner";
-import { ListRow } from "@app/ui/ListRow";
-import type {
- PolicyActivityItem,
- PolicyCategory,
- PolicyConfigDef,
- PolicyRowStatus,
- PolicyStats,
-} from "@app/types/policies";
-import type { AutomationOperation } from "@app/types/automation";
-
-interface PolicyDetailPanelProps {
- category: PolicyCategory;
- config: PolicyConfigDef;
- /** Derived display status. */
- status: PolicyRowStatus;
- /**
- * The policy's real configured steps (from its backing automation). When
- * present these drive the Enforces flow; otherwise the preset's decorative
- * `rules` are shown (e.g. before configuration).
- */
- steps?: AutomationOperation[];
- /** Activity feed derived from the user's files; empty until files exist. */
- activity?: PolicyActivityItem[];
- /** Summary stats derived from the user's files. */
- stats?: PolicyStats;
- canConfigure: boolean;
- /** Default (built-in) policies aren't deletable, so the Delete action hides. */
- canDelete: boolean;
- onBack: () => void;
- onEditSettings: () => void;
- onTogglePause: () => void;
- onDelete: () => void;
- /** Re-run a failed activity item's policy on its file. */
- onRetry?: (item: PolicyActivityItem) => void;
-}
-
-/** "addWatermark" → "Add Watermark" — a light humanisation of op ids for display. */
-function humanizeOperation(op: string): string {
- return op
- .replace(/([A-Z])/g, " $1")
- .replace(/^./, (c) => c.toUpperCase())
- .trim();
-}
-
-/**
- * A failed run's error in the activity feed. Backend errors can be long (or
- * multi-line stack traces) and would otherwise blow up the row, so anything
- * lengthy is clamped and collapsed by default with a Show more/less toggle.
- * Short messages (e.g. "Enforcement failed") render plainly with no toggle.
- */
-function ActivityError({
- message,
- t,
-}: {
- message: string;
- t: (key: string, defaultValue: string) => string;
-}) {
- const [expanded, setExpanded] = useState(false);
- const needsToggle = message.length > 80 || message.includes("\n");
- if (!needsToggle) return <>{message}</>;
- return (
- <span className="pol-activity-error">
- <span
- className={`pol-activity-error__text${expanded ? "" : " pol-activity-error__text--clamped"}`}
- >
- {message}
- </span>
- <Button
- variant="tertiary"
- className="pol-activity-error__toggle"
- onClick={() => setExpanded((v) => !v)}
- >
- {expanded
- ? t("policies.detail.showLess", "Show less")
- : t("policies.detail.showMore", "Show more")}
- </Button>
- </span>
- );
-}
-
-/** Narrative view for a configured policy (Enforces / Activity / Stats). */
-export function PolicyDetailPanel({
- category,
- config,
- status,
- steps,
- activity,
- stats,
- canConfigure,
- canDelete,
- onBack,
- onEditSettings,
- onTogglePause,
- onDelete,
- onRetry,
-}: PolicyDetailPanelProps) {
- const { t } = useTranslation();
- const isPaused = status === "paused";
- const [activityOpen, setActivityOpen] = useState(true);
- // Real configured steps drive the flow; fall back to the preset's rule labels.
- const enforceItems =
- steps && steps.length > 0
- ? steps.map((s) => humanizeOperation(s.operation))
- : config.rules;
- // Activity + stats are derived from the user's real files; until they load (or
- // if none exist) show an honest empty feed / zeroed stats.
- const activityItems = activity ?? [];
- const statValues = stats ?? {
- enforced: 0,
- dataProcessed: "0 B",
- activeFor: "—",
- };
- return (
- <div className="pol-detail">
- <PanelHeader
- icon={category.icon}
- accent={ROW_ACCENT[category.id]}
- title={t(`policies.catalog.${category.id}`, category.label)}
- onClose={onBack}
- closeLabel={t("policies.detail.close", "Close")}
- actions={
- <StatusBadge
- tone={isPaused ? "warning" : "success"}
- showDot
- pulse={!isPaused}
- >
- {isPaused
- ? t("policies.detail.statusPaused", "Paused")
- : t("policies.detail.statusActive", "Active")}
- </StatusBadge>
- }
- />
-
- <div className="pol-scroll">
- {/* Enforces */}
- <div>
- <p className="pol-section-label">
- {t("policies.detail.enforces", "Enforces")}
- </p>
- <Card padding="default">
- <div className="pol-rule-flow">
- <ChipFlow items={enforceItems} separator="arrow" />
- </div>
- <div className="pol-meta-row">
- <span className="pol-meta-item">
- <PublicIcon sx={{ fontSize: "0.8rem" }} />
- {config.scopeLabel}
- </span>
- <span className="pol-meta-item">
- <ScheduleIcon sx={{ fontSize: "0.8rem" }} />
- {t("policies.detail.onEveryUpload", "On every upload")}
- </span>
- </div>
- <div className="pol-note">
- <HistoryIcon sx={{ fontSize: "0.8rem" }} />
- {t(
- "policies.detail.originalsNote",
- "Originals stay untouched • Enforced version saved alongside",
- )}
- </div>
- </Card>
- </div>
-
- {/* Recent Activity */}
- <div>
- <Button
- variant="quiet"
- fullWidth
- justify="between"
- className="pol-section-label pol-section-toggle"
- onClick={() => setActivityOpen((o) => !o)}
- aria-expanded={activityOpen}
- rightSection={
- <KeyboardArrowDownIcon
- className={`pol-section-chevron${activityOpen ? " is-open" : ""}`}
- fontSize="small"
- />
- }
- >
- <span>
- {t("policies.detail.recentActivity", "Recent Activity")}
- </span>
- </Button>
- {activityOpen &&
- (activityItems.length > 0 ? (
- <Card padding="none">
- <div className="pol-activity-list">
- {activityItems.map((item, i) => (
- <ListRow
- key={item.runId ?? `${item.doc}-${item.time}`}
- divider={i > 0}
- leadingTone={
- item.status === "flagged"
- ? "warning"
- : item.status === "processing"
- ? "info"
- : "success"
- }
- leading={
- item.status === "flagged" ? (
- <WarningAmberIcon sx={{ fontSize: "0.85rem" }} />
- ) : item.status === "processing" ? (
- <AutorenewIcon
- className="pol-spin"
- sx={{ fontSize: "0.85rem" }}
- />
- ) : (
- <CheckCircleIcon sx={{ fontSize: "0.85rem" }} />
- )
- }
- title={item.doc}
- description={
- item.status === "flagged" ? (
- <ActivityError message={item.action} t={t} />
- ) : (
- item.action
- )
- }
- meta={item.time}
- trailing={
- item.status === "flagged" && onRetry ? (
- <Button
- variant="tertiary"
- size="sm"
- onClick={() => onRetry(item)}
- >
- {t("policies.detail.retry", "Retry")}
- </Button>
- ) : undefined
- }
- />
- ))}
- </div>
- </Card>
- ) : (
- <Card padding="default">
- <EmptyState
- size="compact"
- icon={<DescriptionIcon sx={{ fontSize: "1.5rem" }} />}
- title={t(
- "policies.detail.noActivityTitle",
- "No activity yet",
- )}
- description={t(
- "policies.detail.noActivityDescription",
- "Documents will appear here once this policy runs.",
- )}
- />
- </Card>
- ))}
- </div>
-
- {/* Stats — one grouped card with divided columns, intentionally
- unlabelled for a quiet summary footer. */}
- <Card padding="none">
- <div className="pol-stats">
- <div className="pol-stat">
- <span className="pol-stat-value">
- {statValues.enforced.toLocaleString()}
- </span>
- <span className="pol-stat-label">
- {t("policies.detail.statDocsEnforced", "Docs enforced")}
- </span>
- </div>
- <div className="pol-stat">
- <span className="pol-stat-value">{statValues.dataProcessed}</span>
- <span className="pol-stat-label">
- {t("policies.detail.statDataProcessed", "Data processed")}
- </span>
- </div>
- <div className="pol-stat">
- <span className="pol-stat-value">{statValues.activeFor}</span>
- <span className="pol-stat-label">
- {t("policies.detail.statActive", "Active")}
- </span>
- </div>
- </div>
- </Card>
-
- {!canConfigure && (
- <Banner
- tone="neutral"
- icon={<LockIcon sx={{ fontSize: "1rem" }} />}
- description={t(
- "policies.detail.managedByOrg",
- "Managed by your organization. Contact a team leader to change this policy.",
- )}
- />
- )}
- </div>
-
- {canConfigure && (
- <div className={`pol-footer${canDelete ? "" : " pol-footer-end"}`}>
- {canDelete && (
- <Button
- variant="tertiary"
- accent="danger"
- size="sm"
- leftSection={<DeleteOutlineIcon sx={{ fontSize: "0.9rem" }} />}
- onClick={onDelete}
- style={{ marginRight: "auto" }}
- >
- {t("delete", "Delete")}
- </Button>
- )}
- <Button variant="secondary" size="sm" onClick={onTogglePause}>
- {isPaused
- ? t("policies.detail.resume", "Resume")
- : t("policies.detail.pause", "Pause")}
- </Button>
- <Button size="sm" onClick={onEditSettings}>
- {t("policies.detail.editSettings", "Edit Settings")}
- </Button>
- </div>
- )}
- </div>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyFieldRow.tsx b/frontend/editor/src/proprietary/components/policies/PolicyFieldRow.tsx
deleted file mode 100644
index 1210b997ca..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicyFieldRow.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { ToggleSwitch } from "@app/ui/ToggleSwitch";
-import { Select } from "@app/ui/Select";
-import { Input } from "@app/ui/Input";
-import { Chip } from "@app/ui/Chip";
-import { SettingsRow } from "@app/ui/SettingsRow";
-import type { PolicyField } from "@app/types/policies";
-
-interface PolicyFieldRowProps {
- field: PolicyField;
- /** Effective current value (override or definition default). */
- value: boolean | string | string[];
- onChange: (value: boolean | string | string[]) => void;
- /** First row in a group omits the top divider. */
- first?: boolean;
-}
-
-/**
- * Renders one policy setting: toggle, select, multi-select chips, or text.
- * Controlled — the parent owns the value. Uses SUI controls (ToggleSwitch /
- * Select / Input / Chip) so it matches the rest of the policy surface.
- */
-export function PolicyFieldRow({
- field,
- value,
- onChange,
- first,
-}: PolicyFieldRowProps) {
- const { t } = useTranslation();
- // Field labels and option labels come from the policy catalog data, so they're
- // wrapped at the render site with data-keyed ids (English stays the fallback).
- const fieldLabel = t(`policies.field.${field.key}`, field.label);
-
- if (field.type === "chips") {
- const selected = Array.isArray(value) ? value : [];
- const toggle = (opt: string) =>
- onChange(
- selected.includes(opt)
- ? selected.filter((o) => o !== opt)
- : [...selected, opt],
- );
- return (
- <div className="pol-field" data-first={first || undefined}>
- <div className="pol-field-chips-head">
- <span className="pol-field-label">{fieldLabel}</span>
- <span className="pol-field-count">
- {t("policies.fields.selectedCount", "{{count}} selected", {
- count: selected.length,
- })}
- </span>
- </div>
- <div className="pol-field-chips">
- {(field.options ?? []).map((opt) => (
- <Chip key={opt} size="sm" onClick={() => toggle(opt)}>
- {t(`policies.fieldOption.${field.key}.${opt}`, opt)}
- </Chip>
- ))}
- </div>
- </div>
- );
- }
-
- const control =
- field.type === "toggle" ? (
- <ToggleSwitch
- size="sm"
- checked={Boolean(value)}
- onChange={(checked) => onChange(checked)}
- aria-label={fieldLabel}
- />
- ) : field.type === "select" ? (
- <Select
- inputSize="sm"
- options={(field.options ?? []).map((o) => ({
- value: o,
- label: t(`policies.fieldOption.${field.key}.${o}`, o),
- }))}
- value={typeof value === "string" ? value : ""}
- onChange={(value) => onChange(value ?? "")}
- aria-label={fieldLabel}
- />
- ) : (
- <Input
- inputSize="sm"
- value={typeof value === "string" ? value : ""}
- onChange={(e) => onChange(e.target.value)}
- aria-label={fieldLabel}
- />
- );
-
- return (
- <div className="pol-field" data-first={first || undefined}>
- <SettingsRow label={fieldLabel} control={control} />
- </div>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
deleted file mode 100644
index cffb02c28c..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicySetupWizard.tsx
+++ /dev/null
@@ -1,737 +0,0 @@
-import { useState, useMemo, useRef } from "react";
-import { useTranslation } from "react-i18next";
-import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
-import { PanelHeader } from "@app/ui/PanelHeader";
-import { ROW_ACCENT } from "@app/components/policies/policyStatus";
-import { Card } from "@app/ui/Card";
-import { Button } from "@app/ui/Button";
-import { Input } from "@app/ui/Input";
-import { Select } from "@app/ui/Select";
-import { SettingsRow } from "@app/ui/SettingsRow";
-import { Checkbox } from "@app/ui/Checkbox";
-import { Banner } from "@app/ui/Banner";
-import { EmptyState } from "@app/ui/EmptyState";
-import { StepIndicator } from "@app/ui/StepIndicator";
-import type {
- PolicyCategory,
- PolicyConfigDef,
- PolicyConfigResult,
- PolicySource,
- PolicyState,
- PolicyWizardResult,
-} from "@app/types/policies";
-import type {
- AutomationConfig,
- AutomationOperation,
-} from "@app/types/automation";
-import type { ToolRegistry } from "@app/data/toolsTaxonomy";
-import type { WatchedFolder } from "@app/types/watchedFolders";
-import { buildPipelineDefinition } from "@app/services/policyPipeline";
-import { useAuth } from "@app/auth/UseSession";
-import { PolicyFieldRow } from "@app/components/policies/PolicyFieldRow";
-import { resolveFieldValues } from "@app/components/policies/policyValues";
-import {
- PolicyWorkflowStep,
- AutomationMode,
-} from "@app/components/policies/PolicyWorkflowStep";
-import { PolicyToolConfigStep } from "@app/components/policies/PolicyToolConfigStep";
-import { getPolicyToolChain } from "@app/components/policies/policyToolChains";
-import { ClassificationLabelsSection } from "@app/components/policies/ClassificationLabelsSection";
-
-// Sources are always "editor" for this release, so the Sources step is dropped
-// from the flow (its panel code is kept below for when other sources return).
-const SOURCES_IN_FLOW = false;
-const TOTAL_STEPS = SOURCES_IN_FLOW ? 3 : 2;
-
-interface PolicySetupWizardProps {
- category: PolicyCategory;
- config: PolicyConfigDef;
- initial: PolicyState;
- /** Sources a policy can run over (catalog-supplied). */
- sources: PolicySource[];
- /** Document types scope can be narrowed to (catalog-supplied). */
- docTypes: string[];
- canConfigure: boolean;
- /** Whether the Classification (ingestion) policy is active — gates doc-type narrowing. */
- classificationEnabled: boolean;
- /** "create" seeds the workflow from the preset; "edit" loads the backing automation. */
- mode?: "create" | "edit";
- /** The backing automation to edit (edit mode). */
- existingAutomation?: AutomationConfig;
- /** The backing folder, to pre-fill output + retry settings (edit mode). */
- initialFolder?: WatchedFolder;
- onCancel: () => void;
- /**
- * Fires on submit with the saved workflow + collected settings. May be async;
- * if the returned promise rejects, the wizard re-enables submit and surfaces
- * the failure rather than hanging on a permanently-disabled button.
- */
- onComplete: (result: PolicyWizardResult) => void | Promise<void>;
- /**
- * For preset (tool-chain) policies whose Workflow step is the locked tool
- * config: fires instead of `onComplete`, carrying the configured tools as
- * operations + mapped pipeline steps. When absent the wizard uses the
- * add/remove builder + `onComplete`.
- */
- onCommitConfig?: (result: PolicyConfigResult) => void | Promise<void>;
- onSetupClassification: () => void;
-}
-
-/**
- * The shared policy wizard, used for both setup and edit. Two steps: Workflow
- * (the tool pipeline, reusing the Watch Folders builder) → Settings (the policy
- * fields + output/retry config). The workflow builder is kept mounted across
- * steps so the final action can trigger its save.
- */
-export function PolicySetupWizard({
- category,
- config,
- initial,
- sources: sourceDefs,
- docTypes,
- canConfigure,
- classificationEnabled,
- mode = "create",
- existingAutomation,
- initialFolder,
- onCancel,
- onComplete,
- onCommitConfig,
- onSetupClassification,
-}: PolicySetupWizardProps) {
- const { t } = useTranslation();
- const isEdit = mode === "edit";
- // Preset (tool-chain) policies render the locked tool config as their Workflow
- // step instead of the add/remove builder.
- const toolChain = getPolicyToolChain(category.id);
- // A single-tool chain has nothing to toggle/configure, so its config UI is
- // hidden (kept mounted so the submit trigger still emits that one tool).
- const singleToolChain = toolChain != null && toolChain.length === 1;
- const { user } = useAuth();
- const [step, setStep] = useState(1);
- const [fieldValues, setFieldValues] = useState(() =>
- resolveFieldValues(config, initial),
- );
- const [sources, setSources] = useState<string[]>(
- initial.sources.length ? initial.sources : ["editor"],
- );
- const [scopeNarrow, setScopeNarrow] = useState(initial.scopeTypes.length > 0);
- const [scopeTypes, setScopeTypes] = useState<string[]>(initial.scopeTypes);
- // Reviewer isn't shown in the flow; the field is still saved on the policy,
- // defaulted to the signed-in user.
- const reviewerEmail = initial.reviewerEmail || user?.email || "";
- // Output + retry settings — the real, working folder settings (the engine
- // applies them). Pre-filled from the backing folder in edit mode.
- const [outputMode, setOutputMode] = useState<"new_file" | "new_version">(
- initialFolder?.outputMode ?? "new_version",
- );
- const [outputName, setOutputName] = useState(initialFolder?.outputName ?? "");
- const [outputNamePosition, setOutputNamePosition] = useState<
- "prefix" | "suffix" | "auto-number"
- >(initialFolder?.outputNamePosition ?? "prefix");
- const [maxRetries, setMaxRetries] = useState(initialFolder?.maxRetries ?? 3);
- const [retryDelayMinutes, setRetryDelayMinutes] = useState(
- initialFolder?.retryDelayMinutes ?? 5,
- );
- // The editor event this policy runs on: input on upload, or output on export.
- const [runOn, setRunOn] = useState<"upload" | "export">(
- initial.runOn ?? "upload",
- );
- const workflowSave = useRef<(() => void) | null>(null);
- const [submitting, setSubmitting] = useState(false);
- const [saveError, setSaveError] = useState<string | null>(null);
-
- // Seed the workflow builder: the backing automation in edit, else a synthetic
- // config carrying the category preset's operations (created on save).
- const seedAutomation = useMemo<AutomationConfig>(
- () =>
- existingAutomation ?? {
- id: "",
- name: `${category.label} Policy`,
- description: `${category.label} policy workflow`,
- icon: "WorkIcon",
- operations: config.defaultOperations,
- createdAt: "",
- updatedAt: "",
- },
- [existingAutomation, category.label, config.defaultOperations],
- );
-
- if (!canConfigure) {
- return (
- <div className="pol-detail">
- <PanelHeader
- icon={category.icon}
- accent={ROW_ACCENT[category.id]}
- title={
- isEdit
- ? t("policies.wizard.editTitle", "Edit {{label}} Policy", {
- label: t(`policies.catalog.${category.id}`, category.label),
- })
- : t("policies.wizard.setupTitle", "Set up {{label}} Policy", {
- label: t(`policies.catalog.${category.id}`, category.label),
- })
- }
- onClose={onCancel}
- closeLabel={t("policies.wizard.close", "Close")}
- />
- <div className="pol-scroll">
- <EmptyState
- title={t(
- "policies.wizard.lockedTitle",
- "Managed by your organization",
- )}
- description={t(
- "policies.wizard.lockedDescription",
- "Contact a team leader to change this policy.",
- )}
- />
- </div>
- </div>
- );
- }
-
- const back = () =>
- step > 1 ? setStep((s) => Math.max(1, s - 1)) : onCancel();
-
- const toggleSource = (id: string) =>
- setSources((prev) =>
- prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id],
- );
-
- // Once the builder persists the workflow, map its operations to backend
- // endpoint paths (the registry only lives in the Workflow step) and hand the
- // automation + built steps + settings to the host (which closes the wizard on
- // success). If the host's async save rejects, recover so the submit button
- // doesn't stay disabled forever.
- const handleWorkflowSaved = (
- automation: AutomationConfig,
- toolRegistry: Partial<ToolRegistry>,
- ) => {
- const { definition, unresolved } = buildPipelineDefinition(
- automation,
- toolRegistry,
- );
- Promise.resolve(
- onComplete({
- automation,
- fieldValues,
- sources,
- scopeTypes: scopeNarrow ? scopeTypes : [],
- reviewerEmail,
- folder: {
- runOn,
- outputMode,
- outputName: outputName.trim(),
- outputNamePosition,
- maxRetries,
- retryDelayMinutes,
- },
- pipelineSteps: definition.steps,
- unresolvedOps: unresolved,
- }),
- ).catch(() => {
- setSubmitting(false);
- setSaveError(
- t(
- "policies.wizard.saveError",
- "Couldn't save the policy. Please try again.",
- ),
- );
- });
- };
-
- // Tool-chain policies: the locked config step emits its enabled tools as
- // operations + mapped steps; hand them to the host's commit path.
- const handleToolConfigSaved = (
- operations: AutomationOperation[],
- pipelineSteps: { operation: string; parameters: Record<string, unknown> }[],
- unresolvedOps: string[],
- ) => {
- Promise.resolve(
- onCommitConfig?.({
- operations,
- pipelineSteps,
- unresolvedOps,
- fieldValues,
- sources,
- scopeTypes: scopeNarrow ? scopeTypes : [],
- reviewerEmail,
- folder: {
- runOn,
- outputMode,
- outputName: outputName.trim(),
- outputNamePosition,
- maxRetries,
- retryDelayMinutes,
- },
- }),
- ).catch(() => {
- setSubmitting(false);
- setSaveError(
- t(
- "policies.wizard.saveError",
- "Couldn't save the policy. Please try again.",
- ),
- );
- });
- };
-
- // Final submit: guard against double-submit (the step stays mounted, so a
- // second click would persist twice), then trigger the step's save.
- const submit = () => {
- if (submitting) return;
- setSaveError(null);
- setSubmitting(true);
- workflowSave.current?.();
- };
-
- // The builder couldn't save (e.g. no configured tools) — surface it and send
- // the user back to the Workflow step to fix it.
- const handleSaveFailed = () => {
- setSubmitting(false);
- setSaveError(
- t(
- "policies.wizard.noToolsError",
- "Add at least one configured tool to the workflow first.",
- ),
- );
- setStep(1);
- };
-
- return (
- <div className="pol-detail">
- <PanelHeader
- icon={category.icon}
- accent={ROW_ACCENT[category.id]}
- title={
- isEdit
- ? t("policies.wizard.editTitle", "Edit {{label}} Policy", {
- label: t(`policies.catalog.${category.id}`, category.label),
- })
- : t("policies.wizard.setupTitle", "Set up {{label}} Policy", {
- label: t(`policies.catalog.${category.id}`, category.label),
- })
- }
- onClose={onCancel}
- closeLabel={t("cancel", "Cancel")}
- />
-
- <div className="pol-steps">
- <span className="pol-step-label">
- {t("policies.wizard.stepOf", "Step {{step}} of {{total}}", {
- step,
- total: TOTAL_STEPS,
- })}
- </span>
- <StepIndicator total={TOTAL_STEPS} current={step} />
- </div>
-
- <div className="pol-scroll">
- {saveError && (
- <Banner
- tone="danger"
- icon={<InfoOutlinedIcon sx={{ fontSize: "1rem" }} />}
- description={saveError}
- />
- )}
- {/* Step 1 — Workflow. Kept mounted (hidden on other steps) so the final
- submit can trigger its save. Preset (tool-chain) policies show the
- locked, per-tool config; the rest show the add/remove builder. */}
- <div style={{ display: step === 1 ? undefined : "none" }}>
- {toolChain ? (
- <>
- {/* Single-tool chains have nothing to configure — hide the prompt
- and the toggle, but keep the step mounted (display:none) so the
- final submit still emits that one tool. */}
- {!singleToolChain && (
- <p className="pol-desc">
- {t(
- "policies.wizard.toolChainDesc",
- "Configure the tools this policy runs on each document.",
- )}
- </p>
- )}
- <div style={{ display: singleToolChain ? "none" : undefined }}>
- <PolicyToolConfigStep
- chainIds={toolChain}
- initialOperations={
- existingAutomation?.operations ?? config.defaultOperations
- }
- presetOperations={config.defaultOperations}
- categoryLabel={category.label}
- saveTriggerRef={workflowSave}
- onComplete={handleToolConfigSaved}
- />
- </div>
- </>
- ) : (
- <>
- <p className="pol-desc">
- {t(
- "policies.wizard.builderDesc",
- "Build the sequence of tools this policy runs on each document.",
- )}
- </p>
- <PolicyWorkflowStep
- automation={seedAutomation}
- mode={isEdit ? AutomationMode.EDIT : AutomationMode.SUGGESTED}
- saveTriggerRef={workflowSave}
- onComplete={handleWorkflowSaved}
- onSaveFailed={handleSaveFailed}
- />
- </>
- )}
- {/* The Classification policy owns the editable label sets (team-shared
- + personal) the classifier picks from. Kept on the first step
- alongside the tool so it's not buried. */}
- {category.id === "classification" && (
- <ClassificationLabelsSection canConfigure={canConfigure} />
- )}
- </div>
-
- {step === 2 && (
- <>
- <p className="pol-desc">{category.desc}</p>
- {config.fields.length > 0 && (
- <Card padding="none">
- {config.fields.map((f, i) => (
- <PolicyFieldRow
- key={f.key}
- field={f}
- value={fieldValues[f.key]}
- first={i === 0}
- onChange={(v) =>
- setFieldValues((prev) => ({ ...prev, [f.key]: v }))
- }
- />
- ))}
- </Card>
- )}
-
- {/* Real, working output + retry settings (applied by the engine). */}
- <p className="pol-section-label">
- {t("policies.wizard.outputRetriesLabel", "Output & retries")}
- </p>
- <Card padding="none">
- {/* The editor event the policy runs on: input on upload, or
- output on export (enforced before the file is exported). */}
- <div className="pol-subhead">
- {t("policies.wizard.runOnSubhead", "Run on")}
- </div>
- <div className="pol-field" data-first>
- <SettingsRow
- label={t("policies.wizard.runOnLabel", "Run on")}
- control={
- <Select
- inputSize="sm"
- value={runOn}
- onChange={(value) =>
- setRunOn((value ?? "upload") as "upload" | "export")
- }
- aria-label={t("policies.wizard.runOnLabel", "Run on")}
- options={[
- {
- value: "upload",
- label: t("policies.wizard.runOnUpload", "Upload"),
- },
- {
- value: "export",
- label: t("policies.wizard.runOnExport", "Export"),
- },
- ]}
- />
- }
- />
- </div>
- <div className="pol-subhead">
- {t("policies.wizard.outputSubhead", "Output")}
- </div>
- <div className="pol-field" data-first>
- <SettingsRow
- label={t("policies.wizard.outputAsLabel", "Output as")}
- control={
- <Select
- inputSize="sm"
- value={outputMode}
- onChange={(value) => {
- const mode = (value ?? "new_file") as
- | "new_file"
- | "new_version";
- setOutputMode(mode);
- // Auto-number only applies to new files; a new version
- // replaces the file in place, so fall back to suffix.
- if (
- mode === "new_version" &&
- outputNamePosition === "auto-number"
- ) {
- setOutputNamePosition("suffix");
- }
- }}
- aria-label={t(
- "policies.wizard.outputModeAria",
- "Output mode",
- )}
- options={[
- {
- value: "new_file",
- label: t("policies.wizard.outputNewFile", "New file"),
- },
- {
- value: "new_version",
- label: t(
- "policies.wizard.outputNewVersion",
- "New version",
- ),
- },
- ]}
- />
- }
- />
- </div>
- {/* Output filename: position + custom text together as one row. */}
- <div className="pol-subhead">
- {t("policies.wizard.outputFilenameSubhead", "Output filename")}
- </div>
- <div className="pol-field" data-first>
- <div className="pol-name-row">
- <Select
- inputSize="sm"
- value={outputNamePosition}
- onChange={(value) =>
- setOutputNamePosition(
- (value ?? "suffix") as
- | "prefix"
- | "suffix"
- | "auto-number",
- )
- }
- aria-label={t(
- "policies.wizard.filenamePositionAria",
- "Filename position",
- )}
- options={[
- {
- value: "prefix",
- label: t("policies.wizard.filenamePrefix", "Prefix"),
- },
- {
- value: "suffix",
- label: t("policies.wizard.filenameSuffix", "Suffix"),
- },
- // Auto-number only makes sense for separate new files.
- ...(outputMode === "new_file"
- ? [
- {
- value: "auto-number",
- label: t(
- "policies.wizard.filenameAutoNumber",
- "Auto-number",
- ),
- },
- ]
- : []),
- ]}
- />
- {/* Auto-number names the file itself, so there's no custom
- text to add — only show the input for prefix/suffix. */}
- {outputNamePosition !== "auto-number" && (
- <Input
- inputSize="sm"
- value={outputName}
- onChange={(e) => setOutputName(e.target.value)}
- placeholder={t(
- "policies.wizard.filenameTextPlaceholder",
- "Text to add (optional)",
- )}
- aria-label={t(
- "policies.wizard.filenameTextAria",
- "Filename text",
- )}
- />
- )}
- </div>
- </div>
- <div className="pol-field">
- <SettingsRow
- label={t("policies.wizard.maxRetriesLabel", "Max retries")}
- control={
- <Input
- type="number"
- inputSize="sm"
- value={String(maxRetries)}
- onChange={(e) =>
- setMaxRetries(Math.max(0, Number(e.target.value) || 0))
- }
- aria-label={t(
- "policies.wizard.maxRetriesLabel",
- "Max retries",
- )}
- />
- }
- />
- </div>
- <div className="pol-field">
- <SettingsRow
- label={t(
- "policies.wizard.retryDelayLabel",
- "Retry delay (min)",
- )}
- control={
- <Input
- type="number"
- inputSize="sm"
- value={String(retryDelayMinutes)}
- onChange={(e) =>
- setRetryDelayMinutes(
- Math.max(0, Number(e.target.value) || 0),
- )
- }
- aria-label={t(
- "policies.wizard.retryDelayAria",
- "Retry delay minutes",
- )}
- />
- }
- />
- </div>
- </Card>
- </>
- )}
-
- {/* Sources step — kept in code, out of the flow for this release
- (SOURCES_IN_FLOW), since sources are always "editor" for now. */}
- {SOURCES_IN_FLOW && step === 3 && (
- <>
- <p className="pol-desc">
- {t(
- "policies.wizard.sourcesDesc",
- "Choose where this policy runs and which document types it applies to.",
- )}
- </p>
- <p className="pol-section-label">
- {t("policies.wizard.sourcesLabel", "Sources")}
- </p>
- <Card padding="none">
- {sourceDefs.map((src, i) => (
- <div
- key={src.id}
- className="pol-source"
- data-first={i === 0 || undefined}
- >
- <Checkbox
- checked={sources.includes(src.id)}
- onChange={() => toggleSource(src.id)}
- leadingIcon={src.icon}
- label={src.label}
- description={src.desc}
- />
- </div>
- ))}
- </Card>
-
- <p className="pol-section-label">
- {t("policies.wizard.docTypesLabel", "Document types")}
- </p>
- {!classificationEnabled ? (
- <Banner
- tone="warning"
- icon={<InfoOutlinedIcon sx={{ fontSize: "1rem" }} />}
- title={t(
- "policies.wizard.allDocTypesTitle",
- "All document types",
- )}
- description={t(
- "policies.wizard.allDocTypesDescription",
- "Enable the Classification policy to filter by document type.",
- )}
- action={
- <Button
- variant="tertiary"
- size="sm"
- onClick={onSetupClassification}
- >
- {t(
- "policies.wizard.setupClassification",
- "Set up Classification",
- )}
- </Button>
- }
- />
- ) : (
- <Card padding="none">
- <div className="pol-doctypes-head">
- <span className="pol-field-label">
- {scopeTypes.length === 0
- ? t(
- "policies.wizard.allDocTypesTitle",
- "All document types",
- )
- : t(
- "policies.wizard.typesSelected",
- "{{count}} types selected",
- { count: scopeTypes.length },
- )}
- </span>
- <Button
- variant="tertiary"
- className="pol-link"
- onClick={() => setScopeNarrow((v) => !v)}
- >
- {scopeNarrow
- ? t("policies.wizard.clear", "Clear")
- : t("policies.wizard.edit", "Edit")}
- </Button>
- </div>
- {scopeNarrow && (
- <div className="pol-doctypes">
- {docTypes.map((dt) => (
- <Checkbox
- key={dt}
- checked={scopeTypes.includes(dt)}
- onChange={() =>
- setScopeTypes((prev) =>
- prev.includes(dt)
- ? prev.filter((d) => d !== dt)
- : [...prev, dt],
- )
- }
- label={t(`policies.docType.${dt}`, dt)}
- />
- ))}
- </div>
- )}
- </Card>
- )}
- </>
- )}
- </div>
-
- <div className="pol-footer">
- <Button variant="tertiary" size="sm" onClick={back}>
- {step > 1 ? t("policies.wizard.back", "Back") : t("cancel", "Cancel")}
- </Button>
- {step < TOTAL_STEPS ? (
- <Button
- size="sm"
- style={{ marginLeft: "auto" }}
- onClick={() => setStep((s) => Math.min(TOTAL_STEPS, s + 1))}
- >
- {t("policies.wizard.continue", "Continue")}
- </Button>
- ) : (
- <Button
- size="sm"
- style={{ marginLeft: "auto" }}
- onClick={submit}
- disabled={submitting}
- >
- {isEdit
- ? t("policies.wizard.saveChanges", "Save Changes")
- : t("policies.wizard.enablePolicy", "Enable Policy")}
- </Button>
- )}
- </div>
- </div>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyToolConfig.tsx b/frontend/editor/src/proprietary/components/policies/PolicyToolConfig.tsx
deleted file mode 100644
index 591ea1386f..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicyToolConfig.tsx
+++ /dev/null
@@ -1,165 +0,0 @@
-import { Suspense } from "react";
-import { useTranslation } from "react-i18next";
-import { Loader } from "@mantine/core";
-import { ToggleSwitch } from "@app/ui/ToggleSwitch";
-import { ActionIcon } from "@app/ui/ActionIcon";
-import { Card } from "@app/ui/Card";
-import LocalIcon from "@app/components/shared/LocalIcon";
-import { Tooltip as AppTooltip } from "@app/components/shared/Tooltip";
-import { PolicyRedactConfig } from "@app/components/policies/PolicyRedactConfig";
-import { PolicyWatermarkConfig } from "@app/components/policies/PolicyWatermarkConfig";
-import type { ToolRegistry } from "@app/data/toolsTaxonomy";
-import type { ToolId } from "@app/types/toolId";
-
-/**
- * Plain-language, non-technical descriptions shown by each tool's info button.
- * Stored as [i18n key, English default] pairs so they can be resolved with `t`
- * at render (the map lives at module scope, outside the component).
- */
-const TOOL_PLAIN_INFO: Record<string, readonly [key: string, en: string]> = {
- redact: [
- "policies.toolConfig.info.redact",
- "Automatically finds and blacks out sensitive details — like Social Security and card numbers — so they can't be read in the document.",
- ],
- sanitize: [
- "policies.toolConfig.info.sanitize",
- "Removes hidden JavaScript from the file, so nothing can run automatically when someone opens it.",
- ],
- watermark: [
- "policies.toolConfig.info.watermark",
- "Stamps a visible mark (e.g. “Confidential”) across every page.",
- ],
-};
-
-/** One tool in a policy's fixed chain: whether it runs + its configured params. */
-export interface PolicyToolState {
- /** Frontend tool-registry id (also the registry key + the thing we map to an endpoint). */
- operation: string;
- /** Whether this tool runs as part of the policy (the per-tool on/off). */
- enabled: boolean;
- /** Tool-specific parameters (the shape its endpoint accepts). */
- parameters: Record<string, unknown>;
-}
-
-interface PolicyToolConfigProps {
- /** The policy's fixed tool chain — locked (no add/remove), only configurable. */
- tools: PolicyToolState[];
- toolRegistry: Partial<ToolRegistry>;
- onChange: (tools: PolicyToolState[]) => void;
- /** Read-only when the policy is managed / the user can't configure. */
- editable?: boolean;
-}
-
-/**
- * Locked, configure-only tool panel for a policy. The chain is fixed (you can't
- * add or remove tools); each tool is a section that renders its OWN settings form
- * from the tool registry (`automationSettings`) — the same forms the automation
- * builder uses — so the config is generated from the tools in the workflow, not
- * hardcoded per policy. The parameters produced here are exactly what the backend
- * engine POSTs to each tool's endpoint.
- */
-export function PolicyToolConfig({
- tools,
- toolRegistry,
- onChange,
- editable = true,
-}: PolicyToolConfigProps) {
- const { t } = useTranslation();
- const patchTool = (index: number, patch: Partial<PolicyToolState>) =>
- onChange(tools.map((t, i) => (i === index ? { ...t, ...patch } : t)));
-
- return (
- <div className="pol-tool-config">
- {tools.map((tool, index) => {
- const entry = toolRegistry[tool.operation as ToolId];
- const Settings = entry?.automationSettings ?? null;
- const toolName = entry?.name ?? tool.operation;
- const plainInfo = TOOL_PLAIN_INFO[tool.operation];
- return (
- <Card key={tool.operation} padding="none">
- <div className="pol-tool-head">
- <span className="pol-tool-icon">{entry?.icon}</span>
- <span className="pol-tool-name">{toolName}</span>
- {plainInfo && (
- <AppTooltip
- content={t(plainInfo[0], plainInfo[1])}
- sidebarTooltip
- pinOnClick
- >
- <ActionIcon
- type="button"
- variant="tertiary"
- className="pol-info-btn"
- aria-label={t(
- "policies.toolConfig.infoAriaLabel",
- "What does {{tool}} do?",
- { tool: toolName },
- )}
- >
- <LocalIcon
- icon="info-outline-rounded"
- width="1rem"
- height="1rem"
- style={{ color: "var(--icon-files-color)" }}
- />
- </ActionIcon>
- </AppTooltip>
- )}
- <ToggleSwitch
- size="sm"
- checked={tool.enabled}
- disabled={!editable}
- onChange={(checked) => patchTool(index, { enabled: checked })}
- aria-label={t(
- "policies.toolConfig.enableAriaLabel",
- "Enable {{tool}}",
- {
- tool: toolName,
- },
- )}
- />
- </div>
- {tool.enabled &&
- (tool.operation === "redact" ? (
- <div className="pol-tool-body">
- <PolicyRedactConfig
- parameters={tool.parameters}
- onChange={(parameters) => patchTool(index, { parameters })}
- disabled={!editable}
- />
- </div>
- ) : tool.operation === "sanitize" ? (
- // Sanitize is config-less: it only removes JavaScript (params
- // are fixed in the policy preset), so no settings are shown.
- <></>
- ) : tool.operation === "watermark" ? (
- // Watermark settings with flatten hidden + forced on (see
- // PolicyWatermarkConfig).
- <div className="pol-tool-body">
- <PolicyWatermarkConfig
- parameters={tool.parameters}
- onChange={(parameters) => patchTool(index, { parameters })}
- disabled={!editable}
- />
- </div>
- ) : Settings ? (
- <div className="pol-tool-body">
- <Suspense fallback={<Loader size="sm" />}>
- <Settings
- parameters={tool.parameters}
- onParameterChange={(key: string, value: unknown) =>
- patchTool(index, {
- parameters: { ...tool.parameters, [key]: value },
- })
- }
- disabled={!editable}
- />
- </Suspense>
- </div>
- ) : null)}
- </Card>
- );
- })}
- </div>
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyToolConfigStep.tsx b/frontend/editor/src/proprietary/components/policies/PolicyToolConfigStep.tsx
deleted file mode 100644
index e4edf6477b..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicyToolConfigStep.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { useState, useEffect, type MutableRefObject } from "react";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-import { buildPipelineDefinition } from "@app/services/policyPipeline";
-import {
- PolicyToolConfig,
- type PolicyToolState,
-} from "@app/components/policies/PolicyToolConfig";
-import type { ToolId } from "@app/types/toolId";
-import type { AutomationOperation } from "@app/types/automation";
-
-/**
- * Seed a tool's parameters: start from the tool's own registry defaults, overlay
- * the preset's defaults (e.g. the PII patterns), then apply only the saved
- * values the user actually changed from the tool default. This means a policy
- * saved while a param was at its default (an empty redact list) still inherits
- * the preset value, while genuine user edits are preserved.
- */
-function seedToolParameters(
- registryDefaults: Record<string, unknown>,
- presetParams: Record<string, unknown>,
- savedParams: Record<string, unknown>,
-): Record<string, unknown> {
- const merged: Record<string, unknown> = {
- ...registryDefaults,
- ...presetParams,
- };
- const eq = (a: unknown, b: unknown) =>
- JSON.stringify(a) === JSON.stringify(b);
- for (const [key, value] of Object.entries(savedParams)) {
- if (!eq(value, registryDefaults[key])) merged[key] = value;
- }
- return merged;
-}
-
-interface PolicyToolConfigStepProps {
- /** The fixed, configurable tool chain (locked set) for this policy. */
- chainIds: string[];
- /** Operations to seed enabled/params from (saved ops, or preset defaults). */
- initialOperations: AutomationOperation[];
- /**
- * The preset's default operations. Their params seed any tool whose saved
- * value is still at the tool's own default — so e.g. a policy saved with the
- * PII list at its default inherits the preset patterns rather than running empty.
- */
- presetOperations: AutomationOperation[];
- /** Used to name the built pipeline definition. */
- categoryLabel: string;
- /** The wizard triggers this on its final submit (mirrors PolicyWorkflowStep). */
- saveTriggerRef: MutableRefObject<(() => void) | null>;
- /** Emits the enabled tools as operations + the endpoint-mapped backend steps. */
- onComplete: (
- operations: AutomationOperation[],
- pipelineSteps: { operation: string; parameters: Record<string, unknown> }[],
- unresolvedOps: string[],
- ) => void;
-}
-
-/**
- * The wizard's Workflow step for preset (tool-chain) policies: the locked,
- * per-tool config ({@link PolicyToolConfig}) instead of the add/remove builder.
- * Isolates the ToolWorkflow dependency (so it's mockable in the rail tests) and
- * wires the wizard's submit trigger to emit the configured tools as operations
- * + the endpoint-mapped pipeline steps.
- */
-export function PolicyToolConfigStep({
- chainIds,
- initialOperations,
- presetOperations,
- categoryLabel,
- saveTriggerRef,
- onComplete,
-}: PolicyToolConfigStepProps) {
- const { toolRegistry } = useToolWorkflow();
-
- const [tools, setTools] = useState<PolicyToolState[]>(() =>
- chainIds.map((op) => {
- const saved = initialOperations.find((o) => o.operation === op);
- const preset = presetOperations.find((o) => o.operation === op);
- const defaults = (toolRegistry[op as ToolId]?.operationConfig
- ?.defaultParameters ?? {}) as Record<string, unknown>;
- return {
- operation: op,
- enabled: Boolean(saved),
- parameters: seedToolParameters(
- defaults,
- (preset?.parameters ?? {}) as Record<string, unknown>,
- (saved?.parameters ?? {}) as Record<string, unknown>,
- ),
- };
- }),
- );
-
- // Re-wire the submit trigger whenever the tools change so it emits the latest.
- useEffect(() => {
- saveTriggerRef.current = () => {
- const operations: AutomationOperation[] = tools
- .filter((t) => t.enabled)
- .map((t) => ({ operation: t.operation, parameters: t.parameters }));
- const { definition, unresolved } = buildPipelineDefinition(
- { name: `${categoryLabel} Policy`, operations },
- toolRegistry,
- );
- onComplete(operations, definition.steps, unresolved);
- };
- }, [tools, toolRegistry, categoryLabel, saveTriggerRef, onComplete]);
-
- return (
- <PolicyToolConfig
- tools={tools}
- toolRegistry={toolRegistry}
- onChange={setTools}
- />
- );
-}
diff --git a/frontend/editor/src/proprietary/components/policies/PolicyWorkflowStep.tsx b/frontend/editor/src/proprietary/components/policies/PolicyWorkflowStep.tsx
deleted file mode 100644
index 842bf07e83..0000000000
--- a/frontend/editor/src/proprietary/components/policies/PolicyWorkflowStep.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { MutableRefObject } from "react";
-import AutomationCreation from "@app/components/tools/automate/AutomationCreation";
-import { AutomationMode } from "@app/types/automation";
-import type { AutomationConfig } from "@app/types/automation";
-import type { ToolRegistry } from "@app/data/toolsTaxonomy";
-import { useToolWorkflow } from "@app/contexts/ToolWorkflowContext";
-
-interface PolicyWorkflowStepProps {
- /**
- * The automation to seed/edit. For setup this is a synthetic config carrying
- * the category preset's operations; for edit it's the policy's backing
- * automation.
- */
- automation: AutomationConfig;
- /** SUGGESTED seeds-then-creates (setup); EDIT updates in place (settings). */
- mode: AutomationMode;
- /** The host (wizard) triggers the builder's save imperatively from its footer. */
- saveTriggerRef: MutableRefObject<(() => void) | null>;
- /**
- * Called with the saved automation once the builder persists it, plus the tool
- * registry (which lives here) so the wizard can map operations to backend
- * endpoint paths without depending on the ToolWorkflow context itself.
- */
- onComplete: (
- automation: AutomationConfig,
- toolRegistry: Partial<ToolRegistry>,
- ) => void;
- /** Called when save is triggered but the workflow isn't in a saveable state. */
- onSaveFailed?: () => void;
-}
-
-/**
- * The policy wizard's "Workflow" step: the Watch Folders automation builder
- * ({@link AutomationCreation}) reused to define a policy's tool pipeline. Kept
- * as its own component so the heavy builder + its ToolWorkflow dependency are
- * isolated (and mockable in the rail tests).
- */
-export function PolicyWorkflowStep({
- automation,
- mode,
- saveTriggerRef,
- onComplete,
- onSaveFailed,
-}: PolicyWorkflowStepProps) {
- const { toolRegistry } = useToolWorkflow();
- return (
- <AutomationCreation
- mode={mode}
- existingAutomation={automation}
- toolRegistry={toolRegistry}
- hideMetadata
- nameOverride={automation.name}
- saveTriggerRef={saveTriggerRef}
- onBack={() => {}}
- onComplete={(saved) => onComplete(saved, toolRegistry)}
- onSaveFailed={onSaveFailed}
- />
- );
-}
-
-export { AutomationMode };
diff --git a/frontend/editor/src/proprietary/components/policies/README.md b/frontend/editor/src/proprietary/components/policies/README.md
index edaa71b123..a08fc01452 100644
--- a/frontend/editor/src/proprietary/components/policies/README.md
+++ b/frontend/editor/src/proprietary/components/policies/README.md
@@ -1,84 +1,35 @@
-# Policies (frontend)
+# Policies (editor)
-Automation-backed document-enforcement policies — conceptually like Watch
-Folders but backend-driven, with non-folder triggers (editor save/export,
-device sweeps, cloud connectors). **This is the frontend only**: per-policy
-state is persisted locally (localStorage) and activity + stats are derived from
-your real uploaded files; server persistence + real enforcement land in a
-follow-up. It ships behind the `POLICIES_ENABLED` feature flag (proprietary
-build = on while in development, core build = off).
+Automation-backed document-enforcement policies. The editor side is
+**enforcement only**: policies are configured in the admin portal
+(`src/portal/views/Policies.tsx`); the editor runs enabled policies on
+uploaded files, blocks the file's exit points while a run is in flight, and
+badges files a policy has produced. It ships behind the `POLICIES_ENABLED`
+feature flag (SaaS build = on; proprietary and core builds = off; desktop
+additionally requires an active SaaS connection).
## Layout
| Path | Role |
|------|------|
| `types/policies.ts` | Type model (category, fields, state). |
-| `data/policyDefinitions.tsx` | Static preset definitions for the catalog: 5 categories (with the `providesClassification` data flag), per-category config fields, sources, doc types, and each category's default tool pipeline. Read it through `policyCatalog`, not directly. |
-| `services/policyCatalog.ts` | **The definitions seam.** `loadPolicyCatalog()` returns categories/configs/sources/doc-types. Components reach definitions only through here (via `usePolicyCatalog`) — swap this one function for a backend fetch to go live without touching a component. |
-| `hooks/usePolicyCatalog.ts` | Hook over the catalog seam (memoised; where loading/error state lands when it becomes async). |
-| `services/policyStorage.ts` | Local persistence (localStorage) of per-policy **state** + change events. Swap this layer for the real API. |
-| `hooks/usePolicies.ts` | State + lifecycle actions + permission flag. |
-| `services/policyLiveData.ts` | Derives the detail view's activity feed + stats from the user's real uploaded files. |
-| `components/policies/PoliciesSidebar.tsx` | The three right-rail slots: list section, detail takeover, collapsed-rail icons (+ `usePoliciesEnabled` / `usePolicyDetailActive`). Shadows the core stub. |
-| `components/policies/policySelectionStore.ts` | Shared selected-policy / detail-view store the three slots sync through. |
-| `components/policies/PolicySetupWizard.tsx` | 3-step setup (operations → sources/types → reviewer/confirm). |
-| `components/policies/PolicyDetailPanel.tsx` | Configured "narrative" view (Enforces / Activity / Stats). |
-| `components/policies/PolicySettingsForm.tsx` | Edit-settings sub-view. |
-| `components/policies/PolicyFieldRow.tsx` | toggle / select / chips / text field renderer (SUI `SettingsRow` + `ToggleSwitch`/`Select`/`Input`/`Chip`). |
-
-The core build gets a no-op stub at `core/components/policies/PoliciesSidebar.tsx`;
-`RightSidebar` (core) consumes the seam, so the section appears only in
-proprietary builds.
-
-## Design system (SUI + Mantine)
-
-The surface is composed almost entirely from the shared SUI design system
-(`@app/ui`), mixed with Mantine only where SUI has no equivalent.
-SUI components used here: `PanelHeader` (+ leading `IconBadge`), `Card`,
-`Button`, `Chip`, `ChipFlow`, `StatusBadge`, `Banner`, `EmptyState`,
-`MetricCard`, `Input`, `Select`, `ToggleSwitch`, `Checkbox`, `FormField`,
-`NavItem` (status `accent`), `ListRow`, `DataRow`, `SectionHeader`,
-`StepIndicator`. Several of those (`IconBadge`, `ListRow`, `DataRow`,
-`SectionHeader`, `StepIndicator`, `ChipFlow`, `SettingsRow`, plus the `NavItem`
-accent / `PanelHeader` icon slot / `Checkbox` leadingIcon / `MetricCard size`)
-were **built up in SUI** as part of this work — each has a Storybook story.
-
-Bootstrapping: the editor loads `@app/tokens/tokens.css` globally via
-`ThemeProvider`, which also mirrors the Mantine colour scheme onto
-`<html data-theme>` (SUI's dark palette keys on `data-theme`).
-
-The bespoke `.pol-*` CSS in `Policies.css` is now only thin layout scaffolding
-(detail/scroll/footer wrappers, the collapsed rail, row insets that match SUI
-`ListRow`); spacing snaps to the SUI `--space-*` scale and colour to the SUI
-token set.
-
-**Status-colour convention (locked):** blue = accent/identity (NavItem accent
-bar, rail icon, detail Card accent — the prototype's blue); green `success`
-StatusBadge = the "Active" pill/dot everywhere (list + detail + rail dot);
-amber = paused. Configured rows render as raised cards (surface + border).
-
-## Faithful to the prototype
-
-5 categories (Ingestion, Security, Compliance, Routing, Retention), their full
-field sets, the 3-step wizard (incl. the doc-type step gated behind the
-Classification/ingestion policy), the configured narrative view (Enforces /
-recent-activity feed / three-up stats), settings, the permission model
-(owner/admin/member + solo), and the
-docked right-sidebar placement: a collapsible **Policies** list above Tools, a
-detail view that takes over the rail when a policy is open, and a collapsed-rail
-of policy icons with active/paused status dots.
-
-## Deviations / follow-ups
-
-- **Billing upgrade flows.** The prototype's free → pay-as-you-go → enterprise
- upgrade/commit/bespoke modals live in the Settings billing tab — a
- billing-integration surface (Stripe/org state that doesn't exist yet),
- deferred. The in-rail surface shows only the spend-limit warning chip, as in
- the prototype's policy section.
-- **Backend.** All persistence, enforcement, activity, and stats are mock. To
- go live, replace `services/policyStorage.ts` and feed real activity/stats.
+| `data/policyDefinitions.tsx` | Static preset definitions for the catalog. Read through `services/policyCatalog.ts` (`loadPolicyCatalog()`), not directly. |
+| `services/policyStorage.ts` | Local persistence (localStorage) of per-policy state + change events. |
+| `hooks/usePolicies.ts` | Policy state + permission flag, consumed by the auto-run controller. |
+| `hooks/usePolicyFileBadges.ts` | Per-file badge map (which policies produced/are enforcing a file) — drives the shared `PolicyBadges` row and the exit-point blocking. |
+| `components/policies/usePoliciesEnabled.ts` | The single build/connection gate for mounting the auto-run controller. Core stub = false; desktop shadow adds the SaaS-connection check. |
+| `components/policies/PolicyAutoRunController.tsx` | Headless: enforces enabled policies on every uploaded file. Mounted by `RightSidebar`. |
+| `components/policies/usePolicyAutoRun.ts` | The auto-run engine: dispatch, polling, retry, output import, server reconcile. |
+| `components/policies/policyRunStore.ts` | `useSyncExternalStore` store of run records (status, progress, outputs), persisted to localStorage. |
+| `components/policies/enforcementQueue.ts` | Export-time enforcement queue used by `services/policyExport.ts`. |
+| `components/policies/policyStatus.ts` | Category → accent-colour mapping shared by badges and export toasts. |
+
+Enforcement UI lives with the surfaces it gates: `PolicyEnforcementOverlay`
+(proprietary viewer), `PolicyEnforcingOverlay` (thumbnails + viewer overlay
+body), and the shared `PolicyBadges` row (`core/components/shared/`).
## Tests
-`services/policyStorage.test.ts` (seed/update/reset/heal/events) and
-`data/policyDefinitions.test.ts` (permission matrix + definition integrity).
+`policyRunStore.test.ts`, `usePolicyAutoRun.test.ts` (+ `.retry` / `.import`
+variants), `hooks/usePolicyFileBadges.test.ts`,
+`services/policyStorage.test.ts`, and `data/policyDefinitions.test.ts`.
diff --git a/frontend/editor/src/proprietary/components/policies/policySelectionStore.ts b/frontend/editor/src/proprietary/components/policies/policySelectionStore.ts
deleted file mode 100644
index e8b80c06c8..0000000000
--- a/frontend/editor/src/proprietary/components/policies/policySelectionStore.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Tiny external store for the currently-selected policy and its detail sub-view.
- *
- * The Policies surface is split across two slots in the right tool sidebar — the
- * list section (above Tools) and the detail takeover (which replaces Tools when a
- * policy is open) — plus the collapsed-rail icons. They live in different parts of
- * {@code RightSidebar}'s tree, so selection can't be component-local useState.
- * This module-level store (read via {@code useSyncExternalStore}) lets all three
- * stay in sync without threading a context through the core sidebar.
- */
-
-import { useSyncExternalStore } from "react";
-import type { PolicyDetailView } from "@app/types/policies";
-
-interface PolicySelection {
- selectedId: string | null;
- detailView: PolicyDetailView;
- /** The policy-settings page (execution order) takes over the rail. Independent
- * of {@link selectedId} — it's a section-level view, not tied to one policy. */
- settingsOpen: boolean;
-}
-
-let state: PolicySelection = {
- selectedId: null,
- detailView: "detail",
- settingsOpen: false,
-};
-const listeners = new Set<() => void>();
-
-function emit() {
- for (const l of listeners) l();
-}
-
-function subscribe(listener: () => void) {
- listeners.add(listener);
- return () => listeners.delete(listener);
-}
-
-function getSnapshot(): PolicySelection {
- return state;
-}
-
-/** Deterministic initial snapshot for SSR/hydration (never the mutable store). */
-const SERVER_SNAPSHOT: PolicySelection = {
- selectedId: null,
- detailView: "detail",
- settingsOpen: false,
-};
-function getServerSnapshot(): PolicySelection {
- return SERVER_SNAPSHOT;
-}
-
-/** Open a policy's detail (resets the sub-view to the narrative). */
-export function selectPolicy(id: string | null) {
- state = { selectedId: id, detailView: "detail", settingsOpen: false };
- emit();
-}
-
-/** Switch the open policy between its narrative and edit-settings sub-views. */
-export function setPolicyDetailView(view: PolicyDetailView) {
- if (state.detailView === view) return;
- state = { ...state, detailView: view };
- emit();
-}
-
-/** Open the policy-settings page (execution order). Clears any open policy. */
-export function openPolicySettings() {
- state = { selectedId: null, detailView: "detail", settingsOpen: true };
- emit();
-}
-
-/** Close the policy-settings page and return to the list. */
-export function closePolicySettings() {
- if (!state.settingsOpen) return;
- state = { ...state, settingsOpen: false };
- emit();
-}
-
-/** Close the open policy and return to the list. */
-export function closePolicy() {
- selectPolicy(null);
-}
-
-/** Reset to the initial state — used by tests to isolate the module store. */
-export function resetPolicySelection() {
- state = { selectedId: null, detailView: "detail", settingsOpen: false };
- emit();
-}
-
-export function usePolicySelection(): PolicySelection {
- return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
-}
diff --git a/frontend/editor/src/proprietary/components/policies/policyStatus.ts b/frontend/editor/src/proprietary/components/policies/policyStatus.ts
index ada31ad11b..d06a8bdea8 100644
--- a/frontend/editor/src/proprietary/components/policies/policyStatus.ts
+++ b/frontend/editor/src/proprietary/components/policies/policyStatus.ts
@@ -1,21 +1,4 @@
import type { IconBadgeAccent } from "@app/ui/IconBadge";
-import type { PolicyRowStatus, PolicyState } from "@app/types/policies";
-
-/** Derive a single row/detail status from a policy's persisted state. */
-export function deriveRowStatus(
- state: PolicyState | undefined,
-): PolicyRowStatus {
- if (!state?.configured) return "setup";
- if (state.status === "paused") return "paused";
- return "active";
-}
-
-/** Human label for each row status. */
-export const STATUS_LABEL: Record<PolicyRowStatus, string> = {
- active: "Active",
- paused: "Paused",
- setup: "Set up",
-};
/** Per-category icon accent — neutral (no tint background) across all categories. */
export const ROW_ACCENT: Record<string, IconBadgeAccent> = {
diff --git a/frontend/editor/src/proprietary/components/policies/policyValues.ts b/frontend/editor/src/proprietary/components/policies/policyValues.ts
deleted file mode 100644
index 844156656e..0000000000
--- a/frontend/editor/src/proprietary/components/policies/policyValues.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { PolicyConfigDef, PolicyState } from "@app/types/policies";
-
-/**
- * Resolve each field's effective value for a policy: the saved override from
- * state, falling back to the definition's default.
- */
-export function resolveFieldValues(
- config: PolicyConfigDef,
- state: PolicyState,
-): Record<string, boolean | string | string[]> {
- const out: Record<string, boolean | string | string[]> = {};
- for (const f of config.fields) {
- out[f.key] = state.fieldValues[f.key] ?? f.value;
- }
- return out;
-}
diff --git a/frontend/editor/src/proprietary/components/policies/usePoliciesEnabled.ts b/frontend/editor/src/proprietary/components/policies/usePoliciesEnabled.ts
new file mode 100644
index 0000000000..48cb41e99b
--- /dev/null
+++ b/frontend/editor/src/proprietary/components/policies/usePoliciesEnabled.ts
@@ -0,0 +1,10 @@
+import { POLICIES_ENABLED } from "@app/constants/featureFlags";
+
+/**
+ * Whether policy enforcement is active for this build. Gates mounting the
+ * headless PolicyAutoRunController. Shadows the core stub; the desktop build
+ * shadows this again to additionally require an active SaaS connection.
+ */
+export function usePoliciesEnabled(): boolean {
+ return POLICIES_ENABLED;
+}
diff --git a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
index e17947f59e..78e170d0d6 100644
--- a/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
+++ b/frontend/editor/src/proprietary/components/policies/usePolicyAutoRun.ts
@@ -731,11 +731,8 @@ async function importOutputs(
}
}
-/**
- * Resolve the file's bytes, fire a backend run, and record it. Exported so the
- * activity feed's Retry action can re-run a policy on a previously-failed file.
- */
-export async function runPolicyOnFile(
+/** Resolve the file's bytes, fire a backend run, and record it. */
+async function runPolicyOnFile(
categoryId: string,
backendId: string,
fileId: FileId,
diff --git a/frontend/editor/src/proprietary/data/policyDefinitions.tsx b/frontend/editor/src/proprietary/data/policyDefinitions.tsx
index 837287cbdb..1b8eacf931 100644
--- a/frontend/editor/src/proprietary/data/policyDefinitions.tsx
+++ b/frontend/editor/src/proprietary/data/policyDefinitions.tsx
@@ -2,7 +2,7 @@
* Static preset definitions for Policies — the categories, their editable
* settings fields, scope labels, and the default tool pipeline each category
* seeds a new policy with. Runtime activity + stats are derived live from the
- * user's real files (see policyLiveData), not defined here.
+ * user's real files, not defined here.
*/
import LayersIcon from "@mui/icons-material/Layers";
diff --git a/frontend/editor/src/proprietary/hooks/usePolicyCatalog.ts b/frontend/editor/src/proprietary/hooks/usePolicyCatalog.ts
deleted file mode 100644
index c233333e39..0000000000
--- a/frontend/editor/src/proprietary/hooks/usePolicyCatalog.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { useMemo } from "react";
-import { useAiEngineEnabled } from "@app/hooks/useAiEngineEnabled";
-import {
- loadPolicyCatalog,
- type PolicyCatalog,
-} from "@app/services/policyCatalog";
-
-/**
- * Policy definitions (categories / fields / sources / doc types) delivered
- * through the catalog seam, so components never import the static definitions
- * directly. Memoised; when the catalog becomes a backend fetch, this hook is
- * where loading/error state would be introduced — its consumers already treat
- * it as the single source of definitions.
- *
- * Categories flagged {@link PolicyCategory.requiresAiEngine} are hidden while the
- * AI engine is off, so a policy only appears where it can actually run.
- */
-export function usePolicyCatalog(): PolicyCatalog {
- const aiEngineEnabled = useAiEngineEnabled();
- return useMemo(() => {
- const catalog = loadPolicyCatalog();
- if (aiEngineEnabled) return catalog;
- return {
- ...catalog,
- categories: catalog.categories.filter(
- (category) => !category.requiresAiEngine,
- ),
- };
- }, [aiEngineEnabled]);
-}
diff --git a/frontend/editor/src/proprietary/services/policyCatalog.ts b/frontend/editor/src/proprietary/services/policyCatalog.ts
index cefe191a8a..c4787430f5 100644
--- a/frontend/editor/src/proprietary/services/policyCatalog.ts
+++ b/frontend/editor/src/proprietary/services/policyCatalog.ts
@@ -2,8 +2,8 @@
* The catalog of available policy *definitions* — the policy types, their
* editable fields, the sources a policy can run over, and the document types
* scope can be narrowed to. This is the single seam through which definitions
- * reach the UI: components never import the static definitions directly, they
- * read the catalog (via {@link usePolicyCatalog}).
+ * reach consumers: nothing imports the static definitions directly, everything
+ * reads the catalog through {@link loadPolicyCatalog}.
*
* Backed by the static `policyDefinitions` today; swap {@link loadPolicyCatalog}
* for a fetch to move definitions server-side without touching any component.
diff --git a/frontend/editor/src/proprietary/services/policyLiveData.test.ts b/frontend/editor/src/proprietary/services/policyLiveData.test.ts
deleted file mode 100644
index 1bb4687164..0000000000
--- a/frontend/editor/src/proprietary/services/policyLiveData.test.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-import { describe, it, expect } from "vitest";
-
-import {
- runsToActivity,
- runsToStats,
- policyActiveFor,
- progressByCategory,
- retryableFailedRuns,
-} from "@app/services/policyLiveData";
-import type { PolicyRunRecord } from "@app/components/policies/policyRunStore";
-
-function run(over: Partial<PolicyRunRecord>): PolicyRunRecord {
- return {
- runId: "r1",
- categoryId: "security",
- fileId: "f1",
- fileName: "f.pdf",
- fileSize: 0,
- target: "saas",
- status: "COMPLETED",
- outputs: [],
- error: null,
- startedAt: Date.now(),
- ...over,
- };
-}
-
-const HOUR = 3_600_000;
-
-describe("runsToActivity", () => {
- it("maps completed/running/failed runs to activity rows", () => {
- const activity = runsToActivity([
- run({ runId: "a", fileName: "fresh.pdf", status: "RUNNING" }),
- run({
- runId: "b",
- fileName: "contract.pdf",
- status: "COMPLETED",
- fileSize: 2_100_000,
- startedAt: Date.now() - HOUR,
- }),
- run({
- runId: "c",
- fileName: "bad.pdf",
- status: "FAILED",
- error: "Step 2 failed",
- }),
- ]);
-
- expect(activity).toHaveLength(3);
- expect(activity[0]).toMatchObject({
- doc: "fresh.pdf",
- status: "processing",
- action: "Enforcing...",
- });
- expect(activity[1]).toMatchObject({
- doc: "contract.pdf",
- status: "enforced",
- });
- expect(activity[1].action).toContain("2.0 MB");
- expect(activity[2]).toMatchObject({
- doc: "bad.pdf",
- status: "flagged",
- action: "Step 2 failed",
- });
- });
-
- it("shows pipeline progress on a running run once the step is known", () => {
- const [withStep, noStep] = runsToActivity([
- run({ runId: "a", status: "RUNNING", currentStep: 1, stepCount: 2 }),
- run({ runId: "b", status: "RUNNING" }),
- ]);
- expect(withStep.action).toBe("Enforcing... · step 1/2");
- // Before the first status report (no step yet) it stays the plain label.
- expect(noStep.action).toBe("Enforcing...");
- });
-
- it("shows a queue-rejected run awaiting retry as busy, not a failure", () => {
- const [item] = runsToActivity([
- run({
- status: "FAILED",
- error: "Policy run could not be queued: Job queue full",
- errorCode: "POLICY_QUEUE_FULL",
- retrying: true,
- }),
- ]);
- expect(item.status).toBe("processing");
- expect(item.action).toBe("Busy, retrying...");
- });
-
- it("shows a queue rejection that has exhausted its retries as a failure", () => {
- const [item] = runsToActivity([
- run({
- status: "FAILED",
- error: "Policy run could not be queued: Job queue full",
- errorCode: "POLICY_QUEUE_FULL",
- // no `retrying` flag — the auto-retry budget is spent.
- }),
- ]);
- expect(item.status).toBe("flagged");
- expect(item.action).toContain("Job queue full");
- });
-});
-
-describe("runsToStats", () => {
- it("counts + sizes only the completed runs", () => {
- const stats = runsToStats(
- [
- run({ runId: "a", status: "COMPLETED", fileSize: 2_100_000 }),
- run({ runId: "b", status: "COMPLETED", fileSize: 900_000 }),
- run({ runId: "c", status: "RUNNING", fileSize: 5_000_000 }),
- ],
- undefined,
- );
- expect(stats.enforced).toBe(2);
- expect(stats.dataProcessed).toBe("2.9 MB");
- expect(stats.activeFor).toBe("Today");
- });
-
- it("derives activeFor from the backing folder's creation time", () => {
- const fiveDaysAgo = new Date(Date.now() - 5 * 86400000).toISOString();
- expect(runsToStats([], fiveDaysAgo).activeFor).toBe("5d");
- });
-});
-
-describe("progressByCategory", () => {
- it("tallies running / completed / total per category", () => {
- const map = progressByCategory([
- run({ runId: "a", categoryId: "classification", status: "RUNNING" }),
- run({
- runId: "b",
- categoryId: "classification",
- status: "COMPLETED",
- imported: true,
- }),
- run({ runId: "c", categoryId: "security", status: "RUNNING" }),
- ]);
- expect(map.get("classification")).toEqual({
- running: 1,
- completed: 1,
- total: 2,
- });
- expect(map.get("security")).toEqual({ running: 1, completed: 0, total: 1 });
- });
-
- it("a COMPLETED-but-not-imported run still counts as running (not done)", () => {
- const map = progressByCategory([
- run({ categoryId: "security", status: "COMPLETED", imported: false }),
- ]);
- expect(map.get("security")).toEqual({ running: 1, completed: 0, total: 1 });
- });
-
- it("scopes to the current wave — history before sinceStartedAt is excluded", () => {
- // The store persists runs across every upload; the panel must only count the
- // current wave, so an old batch (startedAt < sinceStartedAt) is ignored.
- const map = progressByCategory(
- [
- run({ runId: "new1", status: "RUNNING", startedAt: 1000 }),
- run({
- runId: "new2",
- status: "COMPLETED",
- imported: true,
- startedAt: 1000,
- }),
- run({
- runId: "old",
- status: "COMPLETED",
- imported: true,
- startedAt: 10,
- }),
- ],
- 1000,
- );
- // Only the two wave runs counted; the pre-wave "old" run is excluded.
- expect(map.get("security")).toEqual({ running: 1, completed: 1, total: 2 });
- });
-});
-
-describe("retryableFailedRuns — bulk-retry eligibility", () => {
- it("includes a plain failed run", () => {
- const eligible = retryableFailedRuns([
- run({ runId: "a", status: "FAILED" }),
- ]);
- expect(eligible.map((r) => r.runId)).toEqual(["a"]);
- });
-
- it("NEVER retries a (policy, file) that has since succeeded", () => {
- // The caveat: a stale failure row must not re-enforce a file that already
- // went through — e.g. the user retried it individually and it completed.
- const eligible = retryableFailedRuns([
- run({ runId: "ok", status: "COMPLETED", imported: true }), // newest
- run({ runId: "old-fail", status: "FAILED" }),
- ]);
- expect(eligible).toEqual([]);
- });
-
- it("skips a (policy, file) whose retry is already running", () => {
- const eligible = retryableFailedRuns([
- run({ runId: "live", status: "RUNNING" }), // newest
- run({ runId: "old-fail", status: "FAILED" }),
- ]);
- expect(eligible).toEqual([]);
- });
-
- it("keeps only the LATEST failed attempt per (policy, file)", () => {
- const eligible = retryableFailedRuns([
- run({ runId: "fail-new", status: "FAILED", startedAt: 2 }),
- run({ runId: "fail-old", status: "FAILED", startedAt: 1 }),
- ]);
- expect(eligible.map((r) => r.runId)).toEqual(["fail-new"]);
- });
-
- it("treats policies independently — the same file can retry under another policy", () => {
- const eligible = retryableFailedRuns([
- run({ runId: "sec-ok", categoryId: "security", status: "COMPLETED" }),
- run({ runId: "wm-fail", categoryId: "watermark", status: "FAILED" }),
- ]);
- expect(eligible.map((r) => r.runId)).toEqual(["wm-fail"]);
- });
-
- it("excludes runs mid auto-retry backoff and orphans with no local file", () => {
- const eligible = retryableFailedRuns([
- run({ runId: "backoff", status: "FAILED", retrying: true }),
- run({ runId: "orphan", fileId: "", status: "FAILED" }),
- ]);
- expect(eligible).toEqual([]);
- });
-
- it("includes cancelled runs (they never produced output)", () => {
- const eligible = retryableFailedRuns([
- run({ runId: "c", status: "CANCELLED" }),
- ]);
- expect(eligible.map((r) => r.runId)).toEqual(["c"]);
- });
-});
-
-describe("policyActiveFor", () => {
- it("returns 'Today' for a just-activated policy", () => {
- expect(policyActiveFor(new Date().toISOString())).toBe("Today");
- });
- it("returns 'Today' when there's no backing folder", () => {
- expect(policyActiveFor(undefined)).toBe("Today");
- });
- it("reports whole-day duration since activation", () => {
- const fiveDaysAgo = new Date(Date.now() - 5 * 86400000).toISOString();
- expect(policyActiveFor(fiveDaysAgo)).toBe("5d");
- });
-});
diff --git a/frontend/editor/src/proprietary/services/policyLiveData.ts b/frontend/editor/src/proprietary/services/policyLiveData.ts
deleted file mode 100644
index 2f177bb987..0000000000
--- a/frontend/editor/src/proprietary/services/policyLiveData.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * Maps real backend policy runs (from policyRunStore) into the detail view's
- * activity feed + summary stats. Runs are produced by the auto-run controller
- * firing `/api/v1/policies/{id}/run` on every uploaded file, so the feed is the
- * policy's actual enforcement history — not a cosmetic file listing.
- */
-
-import i18n from "@app/i18n";
-import type { PolicyActivityItem, PolicyStats } from "@app/types/policies";
-import {
- dispatchKey,
- isRunInFlight,
- type PolicyRunRecord,
-} from "@app/components/policies/policyRunStore";
-
-/**
- * The failed runs that are actually worth re-running, one per (policy, file):
- * - terminal-failed (FAILED/CANCELLED) and not already in an auto-retry backoff;
- * - with a local input file to re-run on (reconciled server orphans have none);
- * - EXCLUDING any (policy, file) that has since succeeded or is currently
- * running — a stale failure row must never re-enforce a file that already
- * went through, or race a run that's still going.
- * Runs are newest-first in the store, so the first failed run seen per key is
- * the latest attempt. This is the groundwork for bulk "retry all failed" and,
- * later, "run a newly-enabled policy across not-yet-processed files".
- */
-export function retryableFailedRuns(
- runs: PolicyRunRecord[],
-): PolicyRunRecord[] {
- // Keys settled by a success or still being worked — off-limits for retry.
- const settledOrActive = new Set<string>();
- for (const run of runs) {
- if (run.status === "COMPLETED" || isRunInFlight(run)) {
- settledOrActive.add(dispatchKey(run.categoryId, run.fileId));
- }
- }
- const seen = new Set<string>();
- const eligible: PolicyRunRecord[] = [];
- for (const run of runs) {
- if (run.status !== "FAILED" && run.status !== "CANCELLED") continue;
- if (run.retrying) continue;
- if (!run.fileId) continue;
- const key = dispatchKey(run.categoryId, run.fileId);
- if (settledOrActive.has(key) || seen.has(key)) continue;
- seen.add(key);
- eligible.push(run);
- }
- return eligible;
-}
-
-/** Live per-policy run tally — drives the panel's processing ring + counts. */
-export interface PolicyRunProgress {
- /** Runs still working: dispatched/running, retrying, or done-but-not-imported. */
- running: number;
- /** Runs that finished successfully AND landed in the workspace. */
- completed: number;
- /** Every run in the current wave for the policy (running + completed + failed). */
- total: number;
-}
-
-/** Empty tally, so callers can render a zero state without null checks. */
-export const EMPTY_RUN_PROGRESS: PolicyRunProgress = {
- running: 0,
- completed: 0,
- total: 0,
-};
-
-/**
- * Tally runs per policy category for the panel's live indicators: how many are
- * still processing, how many completed, and the total in the CURRENT wave.
- * Keyed by categoryId.
- *
- * `sinceStartedAt` scopes to the current upload wave (the store resets it when a
- * run starts with nothing in flight) so the counts reflect "this upload", not the
- * whole run history persisted in localStorage across every past upload.
- */
-export function progressByCategory(
- runs: PolicyRunRecord[],
- sinceStartedAt = 0,
-): Map<string, PolicyRunProgress> {
- const byCat = new Map<string, PolicyRunProgress>();
- for (const run of runs) {
- if (run.startedAt < sinceStartedAt) continue;
- const p = byCat.get(run.categoryId) ?? {
- running: 0,
- completed: 0,
- total: 0,
- };
- p.total += 1;
- if (isRunInFlight(run)) p.running += 1;
- else if (run.status === "COMPLETED") p.completed += 1;
- byCat.set(run.categoryId, p);
- }
- return byCat;
-}
-
-/** Relative "Nm/Nh ago" for an activity timestamp (epoch ms). */
-function relativeTime(ts: number): string {
- if (!ts) return "—";
- const mins = Math.floor((Date.now() - ts) / 60000);
- if (mins < 1) return "Just now";
- if (mins < 60) return `${mins}m ago`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h ago`;
- const days = Math.floor(hrs / 24);
- return days === 1 ? "Yesterday" : `${days}d ago`;
-}
-
-/** Duration since a timestamp, e.g. "18d" / "5h" (no "ago"). */
-function durationSince(ts: number): string {
- const ms = Date.now() - ts;
- const days = Math.floor(ms / 86400000);
- if (days >= 1) return `${days}d`;
- const hrs = Math.floor(ms / 3600000);
- return hrs >= 1 ? `${hrs}h` : "Today";
-}
-
-/**
- * Human byte size, e.g. "2.1 MB". Intentionally NOT core `formatFileSize`:
- * that one renders 2 decimals (`2.13 MB`), whereas the policy summary wants
- * the quieter whole-number / single-decimal form used across this surface.
- */
-function formatBytes(bytes: number): string {
- if (!bytes) return "0 B";
- const units = ["B", "KB", "MB", "GB", "TB"];
- let v = bytes;
- let i = 0;
- while (v >= 1024 && i < units.length - 1) {
- v /= 1024;
- i += 1;
- }
- return `${i > 0 && v < 10 ? v.toFixed(1) : Math.round(v)} ${units[i]}`;
-}
-
-/** Map a run's lifecycle status to an activity row's display status. */
-function activityStatus(run: PolicyRunRecord): PolicyActivityItem["status"] {
- if (run.status === "COMPLETED") return "enforced";
- // A queue-rejected run awaiting auto-retry is transient backpressure, not a failure.
- if (run.retrying) return "processing";
- if (run.status === "FAILED" || run.status === "CANCELLED") return "flagged";
- return "processing";
-}
-
-function activityAction(run: PolicyRunRecord): string {
- switch (activityStatus(run)) {
- case "enforced":
- return `${formatBytes(run.fileSize)} • ${i18n.t("policies.activity.enforced", "enforced")}`;
- case "flagged":
- return (
- run.error ?? i18n.t("policies.activity.failed", "Enforcement failed")
- );
- default: {
- if (run.retrying)
- return i18n.t("policies.activity.retrying", "Busy, retrying...");
- const enforcing = i18n.t("policies.activity.enforcing", "Enforcing...");
- // Show pipeline progress while running, once the status endpoint reports it
- const { currentStep, stepCount } = run;
- return currentStep && stepCount
- ? `${enforcing} · ${i18n.t("policies.activity.step", "step {{current}}/{{total}}", { current: currentStep, total: stepCount })}`
- : enforcing;
- }
- }
-}
-
-/** Build the detail view's activity feed from a category's runs (newest first). */
-export function runsToActivity(runs: PolicyRunRecord[]): PolicyActivityItem[] {
- return runs.map((run) => ({
- doc: run.fileName,
- action: activityAction(run),
- time: relativeTime(run.startedAt),
- status: activityStatus(run),
- runId: run.runId,
- fileId: run.fileId,
- }));
-}
-
-/** Build the summary stats from a category's runs. */
-export function runsToStats(
- runs: PolicyRunRecord[],
- folderCreatedAt: string | undefined,
-): PolicyStats {
- const enforced = runs.filter((r) => r.status === "COMPLETED");
- const bytes = enforced.reduce((sum, r) => sum + (r.fileSize ?? 0), 0);
- return {
- enforced: enforced.length,
- dataProcessed: formatBytes(bytes),
- activeFor: policyActiveFor(folderCreatedAt),
- };
-}
-
-/**
- * How long a policy has been active — from its backing folder's creation time
- * (when it was enabled), or "Today" when there's no folder yet.
- */
-export function policyActiveFor(folderCreatedAt: string | undefined): string {
- if (!folderCreatedAt) return "Today";
- return durationSince(new Date(folderCreatedAt).getTime());
-}
diff --git a/frontend/editor/src/proprietary/types/policies.ts b/frontend/editor/src/proprietary/types/policies.ts
index a1f6ea70f6..dbfadedb47 100644
--- a/frontend/editor/src/proprietary/types/policies.ts
+++ b/frontend/editor/src/proprietary/types/policies.ts
@@ -17,9 +17,6 @@ import type {
/** Lifecycle status of a policy category for the current user/org. */
export type PolicyStatus = "default" | "active" | "paused";
-/** Derived display status for a row/detail (treats a spend-limit hit as paused). */
-export type PolicyRowStatus = "active" | "paused" | "setup";
-
/** A configurable field within a policy's settings. */
export type PolicyFieldType = "toggle" | "select" | "chips" | "text";
@@ -60,7 +57,7 @@ export interface PolicyCategory {
/**
* The three-up summary stats shown at the foot of a configured policy's detail,
- * derived live from the user's uploaded files (see policyLiveData).
+ * derived live from the user's uploaded files.
*/
export interface PolicyStats {
/** Documents enforced (rendered with toLocaleString). */
@@ -231,6 +228,3 @@ export interface PolicyConfigResult {
reviewerEmail: string;
folder: PolicyFolderSettings;
}
-
-/** Which sub-view of a configured policy's detail panel is showing. */
-export type PolicyDetailView = "detail" | "settings";