#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Portal: unified-design surfaces (Policies, Users, Components, Agent Builder, Editor deploy) + Settings rebuild (#6696)
Reece Browne2b05865a8436
diff --git a/frontend/portal/MOCKS.md b/frontend/portal/MOCKS.mdindex fd3d832f9e..17d6c68d55 100644--- a/frontend/portal/MOCKS.md+++ b/frontend/portal/MOCKS.md@@ -53,12 +53,17 @@ non-2xx). Views consume via `useAsync()` + `useSectionFlags()` (`hooks/useAsync.| Home | `GET /v1/activity` | — | `fetchRecentActivity` | `ActivityEvent[]` || Home | `GET /v1/regions/health` | — | `fetchRegionHealth` | `RegionHealth[]` || Home | `GET /v1/onboarding` | — | `fetchOnboarding` | `OnboardingStep[]` |-| Documents | `GET /v1/endpoints` | `vertical?` | `fetchVerticals` | `Vertical[]` |-| Pipelines | `GET /v1/pipelines` | `tier` | `fetchPipelines` | `PipelinesResponse` |+| Users | `GET /v1/users` | `tier` | `fetchUsers` | `UsersResponse` |+| Documents | `GET /v1/documents` | `tier` | `fetchDocuments` | `DocumentsResponse` |+| Pipelines | `GET /v1/pipelines` · `POST /v1/pipelines/:id/promote-to-policy` | `tier` | `fetchPipelines` · `promoteToPolicy` | `PipelinesResponse` |+| Policies | `GET/POST /api/v1/policies` · `GET/DELETE /api/v1/policies/{id}` · `POST /api/v1/policies/{id}/run` | — | `fetchPolicies` · `savePolicy` · `deletePolicy` · `runPolicy` | `PoliciesResponse` · `Policy` |+| Agent Builder | `GET /v1/agents` | `tier` | `fetchAgents` | `AgentsResponse` || Sources | `GET /v1/sources` | `tier` | `fetchSources` | `SourcesResponse` |+| Components | `GET /v1/components` | `tier` | `fetchComponents` | `ComponentsResponse` || Infrastructure | `GET /v1/infrastructure/deployments` | `tier` | `fetchDeployments` | `DeploymentsResponse` || Infrastructure | `GET /v1/infrastructure/api-keys` | `tier` | `fetchApiKeys` | `ApiKey[]` || Infrastructure | `GET /v1/infrastructure/security` | `tier` | `fetchSecurity` | `SecurityConfig` |+| Infrastructure | `GET /v1/infrastructure/models` | `tier` | `fetchModels` | `ModelsResponse` || Infrastructure | `GET /v1/infrastructure/storage` | `tier` | `fetchStorage` | `StorageConfig` || Infrastructure | `GET /v1/infrastructure/audit-log` | `tier` | `fetchAuditLog` | `AuditLogResponse` || Usage & Billing | `GET /v1/billing/usage` | — | `fetchBillingUsage` | `UsageSeriesResponse` |@@ -66,6 +71,7 @@ non-2xx). Views consume via `useAsync()` + `useSectionFlags()` (`hooks/useAsync.| Usage & Billing | `GET /v1/billing/plans` | — | `fetchPlanOptions` | `PlanOption[]` || Usage & Billing | `GET /v1/billing/history` | `tier` | `fetchBillingHistory` | `BillingHistoryRow[]` || Developer Docs | `GET /v1/docs/nav` | — | `fetchDocsNav` | `DocsNavSection[]` |+| Editor | `GET /v1/editor/deployment` | `tier` | `fetchEditorDeployment` | `EditorDeploymentResponse` || Settings | `GET /v1/settings` | `tier` | `fetchSettings` | `UserSettings` || Notifications | `GET /v1/notifications` · `POST /v1/notifications/mark-all-read` | — | — | `Notification[]` || Ops | `GET /v1/ops/featured` · `POST /v1/ops/:opId/run` | — | — | — |@@ -74,3 +80,7 @@ non-2xx). Views consume via `useAsync()` + `useSectionFlags()` (`hooks/useAsync.> Catalogue generated from `mocks/handlers/*.ts`. The `api/<surface>.ts` JSDoc on> each function is the authoritative per-endpoint reference.+>+> **Policies** targets the **real** backend base `/api/v1/policies` (Stirling's+> `PolicyController`) rather than the mock `/v1/...` convention — its contract+> mirrors the live policy engine, so MSW can be dropped with no code change.diff --git a/frontend/portal/index.html b/frontend/portal/index.htmlindex 8148b26d25..c07e06d083 100644--- a/frontend/portal/index.html+++ b/frontend/portal/index.html@@ -4,8 +4,9 @@<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="theme-color" content="#0f172a" />- <meta name="description" content="Stirling developer portal" />- <title>Stirling — Developer Portal</title>+ <meta name="description" content="Stirling Processor" />+ <link rel="icon" href="/favicon.ico" />+ <title>Stirling Processor</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript>diff --git a/frontend/portal/public/favicon.ico b/frontend/portal/public/favicon.iconew file mode 100644index 0000000000..6d6c8521c1Binary files /dev/null and b/frontend/portal/public/favicon.ico differdiff --git a/frontend/portal/src/ViewRouter.tsx b/frontend/portal/src/ViewRouter.tsxindex 3051f74362..2efaabcc68 100644--- a/frontend/portal/src/ViewRouter.tsx+++ b/frontend/portal/src/ViewRouter.tsx@@ -1,8 +1,13 @@import { Navigate, Route, Routes } from "react-router-dom";import { Home } from "@portal/views/Home";+import { Users } from "@portal/views/Users";import { Documents } from "@portal/views/Documents";import { Pipelines } from "@portal/views/Pipelines";import { Sources } from "@portal/views/Sources";+import { AgentBuilder } from "@portal/views/AgentBuilder";+import { Policies } from "@portal/views/Policies";+import { Components } from "@portal/views/Components";+import { EditorAdmin } from "@portal/views/EditorAdmin";import { Infrastructure } from "@portal/views/Infrastructure";import { Usage } from "@portal/views/Usage";import { DeveloperDocs } from "@portal/views/DeveloperDocs";@@ -12,9 +17,14 @@ export function ViewRouter() {return (<Routes><Route path={VIEW_PATHS.home} element={<Home />} />+ <Route path={VIEW_PATHS.users} element={<Users />} /><Route path={VIEW_PATHS.pipelines} element={<Pipelines />} /><Route path={VIEW_PATHS.sources} element={<Sources />} />+ <Route path={VIEW_PATHS["agent-builder"]} element={<AgentBuilder />} />+ <Route path={VIEW_PATHS.policies} element={<Policies />} /><Route path={VIEW_PATHS.documents} element={<Documents />} />+ <Route path={VIEW_PATHS.components} element={<Components />} />+ <Route path={VIEW_PATHS.editor} element={<EditorAdmin />} /><Route path={VIEW_PATHS.infrastructure} element={<Infrastructure />} /><Route path={VIEW_PATHS.usage} element={<Usage />} /><Route path={VIEW_PATHS.docs} element={<DeveloperDocs />} />diff --git a/frontend/portal/src/api/agents.ts b/frontend/portal/src/api/agents.tsnew file mode 100644index 0000000000..842d5d398b--- /dev/null+++ b/frontend/portal/src/api/agents.ts@@ -0,0 +1,22 @@+import { httpJson } from "@portal/api/http";+import type { AgentsResponse } from "@portal/mocks/agents";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ Agent,+ AgentStatus,+ AgentVersion,+ AgentsResponse,+ AgentsSummary,+ EvalCase,+ Scenario,+ ToolMode,+} from "@portal/mocks/agents";+export { AGENT_STATUS_TONE, TOOL_CATALOGUE } from "@portal/mocks/agents";++/** GET /v1/agents?tier=… — fleet summary + every agent with its full builder state. */+export async function fetchAgents(tier: Tier): Promise<AgentsResponse> {+ return httpJson<AgentsResponse>(+ `/v1/agents?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/documents.ts b/frontend/portal/src/api/documents.tsnew file mode 100644index 0000000000..c64fd1227b--- /dev/null+++ b/frontend/portal/src/api/documents.ts@@ -0,0 +1,26 @@+import { httpJson } from "@portal/api/http";+import type { DocumentsResponse } from "@portal/mocks/documents";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ DocAuditEvent,+ DocAuditKind,+ DocumentStatus,+ DocumentsResponse,+ DocumentsSummary,+ Extraction,+ ReviewDocument,+} from "@portal/mocks/documents";+export {+ DOC_AUDIT_LABEL,+ DOC_AUDIT_TONE,+ DOCUMENT_STATUS_LABEL,+ DOCUMENT_STATUS_TONE,+} from "@portal/mocks/documents";++/** GET /v1/documents?tier=… — summary strip + the review queue for the tier. */+export async function fetchDocuments(tier: Tier): Promise<DocumentsResponse> {+ return httpJson<DocumentsResponse>(+ `/v1/documents?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/editorDeploy.ts b/frontend/portal/src/api/editorDeploy.tsnew file mode 100644index 0000000000..f565cb2955--- /dev/null+++ b/frontend/portal/src/api/editorDeploy.ts@@ -0,0 +1,35 @@+import { httpJson } from "@portal/api/http";+import type { EditorDeploymentResponse } from "@portal/mocks/editorDeploy";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ DeploymentTarget,+ DeploymentSummary,+ DeploymentSummaryMetric,+ EditorDeploymentResponse,+ EditorInstance,+ InstanceStatus,+ PairingMethod,+ PairingOption,+ TargetKind,+ TargetMeta,+ TargetState,+} from "@portal/mocks/editorDeploy";+export {+ INSTANCE_STATUS_LABEL,+ INSTANCE_STATUS_TONE,+ TARGET_META,+} from "@portal/mocks/editorDeploy";++/**+ * GET /v1/editor/deployment?tier=… — the org's Editor deployment: summary+ * metric strip, deployment targets (with run snippets), pairing options, and+ * the live instance health table for the tier.+ */+export async function fetchEditorDeployment(+ tier: Tier,+): Promise<EditorDeploymentResponse> {+ return httpJson<EditorDeploymentResponse>(+ `/v1/editor/deployment?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/endpoints.ts b/frontend/portal/src/api/endpoints.tsdeleted file mode 100644index 95bab777be..0000000000--- a/frontend/portal/src/api/endpoints.ts+++ /dev/null@@ -1,15 +0,0 @@-import { httpJson } from "@portal/api/http";-import type { Vertical } from "@shared/data/endpoints";--export type {- Endpoint,- EndpointSchema,- EndpointTierGate,- Vertical,- VerticalKey,-} from "@shared/data/endpoints";--/** GET /v1/endpoints — verticals plus their endpoints. */-export async function fetchVerticals(): Promise<Vertical[]> {- return httpJson<Vertical[]>("/v1/endpoints");-}diff --git a/frontend/portal/src/api/home.ts b/frontend/portal/src/api/home.tsindex b7b8fee648..122e1ca644 100644--- a/frontend/portal/src/api/home.ts+++ b/frontend/portal/src/api/home.ts@@ -13,10 +13,13 @@ export type {ActivityKind,KpiEntry,OnboardingStep,+ PipelineStage,+ PipelineTemplate,RegionHealth,UsagePoint,UsageSeriesResponse,} from "@portal/mocks/home";+export { PIPELINE_STAGES, PIPELINE_TEMPLATES } from "@portal/mocks/home";/** GET /v1/analytics/usage?window=30d */export async function fetchUsageSeries(): Promise<UsageSeriesResponse> {diff --git a/frontend/portal/src/api/infrastructure.ts b/frontend/portal/src/api/infrastructure.tsindex 0154ae6a40..92255aece2 100644--- a/frontend/portal/src/api/infrastructure.ts+++ b/frontend/portal/src/api/infrastructure.ts@@ -4,6 +4,7 @@ import type {ApiKey,AuditLogResponse,DeploymentRegion,+ ModelsResponse,RecentDeployment,SecurityConfig,StorageConfig,@@ -14,20 +15,32 @@ export type {ApiKey,ApiKeyPermission,ApiKeyStatus,+ AttestationStatus,AuditCategory,AuditEvent,AuditLogResponse,AuditStatus,AuditSummary,CertStatus,+ ComplianceAttestation,ComplianceCert,DataResidency,DeploymentRegion,DeploymentStatus,IpAllowEntry,+ KeyManagement,+ KeyMode,+ ModelCostUnit,+ ModelEntry,+ ModelProvider,+ ModelsResponse,+ ModelsSummary,+ ModelStatus,+ ModelType,RecentDeployment,RegionStatus,RetentionWindow,+ RoutingRule,SecurityConfig,StorageConfig,StorageProvider,@@ -59,6 +72,11 @@ export async function fetchSecurity(tier: Tier): Promise<SecurityConfig> {return httpJson<SecurityConfig>(`/v1/infrastructure/security${q(tier)}`);}+/** GET /v1/infrastructure/models?tier=… */+export async function fetchModels(tier: Tier): Promise<ModelsResponse> {+ return httpJson<ModelsResponse>(`/v1/infrastructure/models${q(tier)}`);+}+/** GET /v1/infrastructure/storage?tier=… */export async function fetchStorage(tier: Tier): Promise<StorageConfig> {return httpJson<StorageConfig>(`/v1/infrastructure/storage${q(tier)}`);diff --git a/frontend/portal/src/api/pipelines.ts b/frontend/portal/src/api/pipelines.tsindex d3a250f31e..e9c3ae2f2e 100644--- a/frontend/portal/src/api/pipelines.ts+++ b/frontend/portal/src/api/pipelines.ts@@ -9,6 +9,8 @@ export type {PipelineMetrics,PipelinesResponse,PipelineStatus,+ PromotedPipeline,+ PromotedStatus,SchemaDrift,StageKey,StageSummary,@@ -20,3 +22,18 @@ export async function fetchPipelines(tier: Tier): Promise<PipelinesResponse> {`/v1/pipelines?tier=${encodeURIComponent(tier)}`,);}++/**+ * Promote a watch-folder-derived pipeline into a governed org policy, so its+ * rules apply fleet-wide instead of just to the originating flow.+ *+ * TODO(backend): POST /v1/pipelines/{id}/promote-to-policy — should create the+ * policy from the pipeline's stages and return the new policy id. The mock+ * handler resolves `{ ok: true }`; the UI treats a resolved promise as accepted.+ */+export async function promoteToPolicy(id: string): Promise<{ ok: true }> {+ return httpJson<{ ok: true }>(+ `/v1/pipelines/${encodeURIComponent(id)}/promote-to-policy`,+ { method: "POST" },+ );+}diff --git a/frontend/portal/src/api/policies.ts b/frontend/portal/src/api/policies.tsnew file mode 100644index 0000000000..c17a5f0b11--- /dev/null+++ b/frontend/portal/src/api/policies.ts@@ -0,0 +1,90 @@+import { httpJson } from "@portal/api/http";+import type { PoliciesResponse, Policy } from "@portal/mocks/policies";++/**+ * Policies service layer — the backend contract.+ *+ * Unlike every other portal surface (which use the mock `/v1/...` base), this+ * one calls the REAL Stirling policy API base `/api/v1/policies` so it is+ * genuinely plug-and-play: drop MSW and these exact calls hit the live backend+ * (PolicyController). The list response is the portal's catalogue shape; the+ * single-policy / create / delete / run calls match the backend records.+ */++export type {+ CatalogueEntry,+ DecoratedPolicy,+ InputSpec,+ OutputSpec,+ PipelineStep,+ PoliciesResponse,+ PoliciesSummary,+ Policy,+ PolicyActivityItem,+ PolicyCategory,+ PolicyConfigDef,+ PolicyField,+ PolicyFieldType,+ PolicyRowStatus,+ PolicySetupResult,+ PolicySource,+ PolicyState,+ PolicyStats,+ PolicyStatus,+ TriggerConfig,+} from "@portal/mocks/policies";+export {+ ENDPOINT_LABELS,+ POLICY_CATEGORIES,+ POLICY_CONFIG,+ POLICY_DOC_TYPES,+ POLICY_SOURCES,+ TOOL_ENDPOINTS,+ humanizeEndpoint,+} from "@portal/mocks/policies";++/** GET /api/v1/policies — the catalogue + every configured policy. */+export async function fetchPolicies(): Promise<PoliciesResponse> {+ return httpJson<PoliciesResponse>("/api/v1/policies");+}++/** GET /api/v1/policies/{id} — one stored policy's raw record. */+export async function fetchPolicy(id: string): Promise<Policy> {+ return httpJson<Policy>(`/api/v1/policies/${encodeURIComponent(id)}`);+}++/**+ * POST /api/v1/policies — create (blank id) or update (matched id). The backend+ * assigns owner + team server-side and returns the stored policy with its id.+ */+export async function savePolicy(policy: Policy): Promise<Policy> {+ return httpJson<Policy>("/api/v1/policies", { method: "POST", body: policy });+}++/** DELETE /api/v1/policies/{id} — remove a stored policy. */+export async function deletePolicy(id: string): Promise<void> {+ await httpJson<void>(`/api/v1/policies/${encodeURIComponent(id)}`, {+ method: "DELETE",+ });+}++/** The async run acknowledgement: a run id to poll for status. */+export interface PolicyRunResponse {+ status: boolean;+ /** The run id (poll GET /api/v1/policies/run/{id} for status). */+ fileId: string | null;+ message: string | null;+}++/**+ * POST /api/v1/policies/{id}/run — run a stored policy now. The real endpoint+ * is multipart (the documents to process); the portal has no files to attach,+ * so this triggers the policy on whatever the backend has queued and returns a+ * run id. Runs regardless of the policy's enabled flag.+ */+export async function runPolicy(id: string): Promise<PolicyRunResponse> {+ return httpJson<PolicyRunResponse>(+ `/api/v1/policies/${encodeURIComponent(id)}/run`,+ { method: "POST" },+ );+}diff --git a/frontend/portal/src/api/sdkComponents.ts b/frontend/portal/src/api/sdkComponents.tsnew file mode 100644index 0000000000..ed02afd9a1--- /dev/null+++ b/frontend/portal/src/api/sdkComponents.ts@@ -0,0 +1,28 @@+import { httpJson } from "@portal/api/http";+import type { ComponentsResponse } from "@portal/mocks/sdkComponents";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ BillingUnit,+ ComponentMaturity,+ ComponentPricing,+ ComponentProp,+ ComponentsResponse,+ ComponentsSummary,+ Framework,+ MaturityMeta,+ SdkComponent,+} from "@portal/mocks/sdkComponents";+export {+ BILLING_UNIT_LABEL,+ MATURITY_META,+ formatPrice,+ isUnlocked,+} from "@portal/mocks/sdkComponents";++/** GET /v1/components?tier=… — summary strip + the embeddable SDK catalogue. */+export async function fetchComponents(tier: Tier): Promise<ComponentsResponse> {+ return httpJson<ComponentsResponse>(+ `/v1/components?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/settings.ts b/frontend/portal/src/api/settings.tsindex e6e850359a..8cba5d0cc1 100644--- a/frontend/portal/src/api/settings.ts+++ b/frontend/portal/src/api/settings.ts@@ -3,8 +3,11 @@ import type { SettingsSnapshot } from "@portal/mocks/settings";import type { Tier } from "@portal/contexts/TierContext";export type {+ ActiveSession,+ BetaFeature,NotificationDefault,RegionOption,+ SecuritySettings,SettingsSnapshot,} from "@portal/mocks/settings";diff --git a/frontend/portal/src/api/users.ts b/frontend/portal/src/api/users.tsnew file mode 100644index 0000000000..f9e7b11c08--- /dev/null+++ b/frontend/portal/src/api/users.ts@@ -0,0 +1,24 @@+import { httpJson } from "@portal/api/http";+import type { UsersResponse } from "@portal/mocks/users";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ AccessControls,+ Member,+ MemberStatus,+ Role,+ RoleId,+ UsersResponse,+ UsersSummary,+} from "@portal/mocks/users";+export {+ MEMBER_STATUS_TONE,+ ROLES,+ ROLE_LABEL,+ ROLE_TONE,+} from "@portal/mocks/users";++/** GET /v1/users?tier=… — summary strip, members table, role catalogue, access. */+export async function fetchUsers(tier: Tier): Promise<UsersResponse> {+ return httpJson<UsersResponse>(`/v1/users?tier=${encodeURIComponent(tier)}`);+}diff --git a/frontend/portal/src/components/DocumentTypeGrid.css b/frontend/portal/src/components/DocumentTypeGrid.cssdeleted file mode 100644index 9d97efd0c5..0000000000--- a/frontend/portal/src/components/DocumentTypeGrid.css+++ /dev/null@@ -1,227 +0,0 @@-.portal-doctype {- display: flex;- flex-direction: column;- gap: 1rem;-}--.portal-doctype__head {- display: flex;- flex-direction: column;- gap: 0.125rem;-}--.portal-doctype__title {- margin: 0;- font-size: 1.125rem;- font-weight: 600;- color: var(--color-text-1);-}--.portal-doctype__sub {- margin: 0;- font-size: 0.8125rem;- color: var(--color-text-4);-}--/* Tabs */-.portal-doctype__tabs {- display: flex;- gap: 0.375rem;- flex-wrap: wrap;-}--.portal-doctype__tab {- display: inline-flex;- align-items: center;- gap: 0.375rem;- padding: 0.3125rem 0.625rem;- font-size: 0.75rem;- color: var(--color-text-3);- background: var(--color-surface);- border: 1px solid var(--color-border);- border-radius: var(--radius-pill);- transition:- border-color var(--motion-fast),- background var(--motion-fast),- color var(--motion-fast);-}--.portal-doctype__tab:hover {- background: var(--color-bg-hover);- color: var(--color-text-1);-}--.portal-doctype__tab.is-active {- color: var(--portal-tab-accent, var(--color-blue));- border-color: var(--portal-tab-accent, var(--color-blue));- background: var(--color-surface);- font-weight: 500;-}--.portal-doctype__tab-dot {- width: 0.4375rem;- height: 0.4375rem;- border-radius: 50%;-}--.portal-doctype__tab-count {- font-size: 0.6875rem;- color: var(--color-text-5);-}--/* Vertical groups */-.portal-doctype__groups {- display: flex;- flex-direction: column;- gap: 1.5rem;-}--.portal-doctype__group-head {- display: flex;- align-items: center;- gap: 0.5rem;- margin-bottom: 0.625rem;-}--.portal-doctype__group-title {- margin: 0;- font-size: 0.875rem;- font-weight: 600;- color: var(--color-text-2);-}--.portal-doctype__group-count {- font-size: 0.75rem;- color: var(--color-text-5);-}--.portal-doctype__scroller {- display: flex;- gap: 0.75rem;- overflow-x: auto;- padding-bottom: 0.5rem;- scroll-snap-type: x mandatory;- scrollbar-width: thin;-}--.portal-doctype__scroller::-webkit-scrollbar {- height: 0.375rem;-}-.portal-doctype__scroller::-webkit-scrollbar-thumb {- background: var(--color-border-hover);- border-radius: var(--radius-pill);-}--/* Cards */-.portal-doctype__card {- flex: 0 0 17rem;- display: flex;- background: var(--color-surface);- border: 1px solid var(--color-border);- border-radius: var(--radius-md);- overflow: hidden;- scroll-snap-align: start;- transition:- border-color var(--motion-fast),- box-shadow var(--motion-fast),- transform var(--motion-fast);-}--.portal-doctype__card:hover {- border-color: var(--color-border-hover);- box-shadow: var(--shadow-md);- transform: translateY(-0.0625rem);-}--.portal-doctype__card-accent {- width: 0.25rem;- flex-shrink: 0;-}--.portal-doctype__card-body {- flex: 1 1 auto;- padding: 0.875rem 1rem;- display: flex;- flex-direction: column;- gap: 0.25rem;- min-width: 0;-}--.portal-doctype__card-eyebrow {- font-size: 0.625rem;- font-weight: 600;- letter-spacing: 0.08em;- color: var(--color-text-5);-}--.portal-doctype__card-title {- margin: 0.125rem 0 0;- font-size: 0.9375rem;- font-weight: 600;- color: var(--color-text-1);-}--.portal-doctype__card-desc {- margin: 0;- font-size: 0.75rem;- line-height: 1.45;- color: var(--color-text-4);- display: -webkit-box;- -webkit-line-clamp: 2;- -webkit-box-orient: vertical;- overflow: hidden;-}--.portal-doctype__card-meta {- margin-top: 0.5rem;- display: flex;- align-items: center;- justify-content: space-between;- gap: 0.5rem;- font-size: 0.6875rem;- color: var(--color-text-4);-}--.portal-doctype__regions {- font-family: var(--font-mono);-}--.portal-doctype__regions-more {- color: var(--color-text-5);-}--.portal-doctype__card-cta {- margin-top: 0.5rem;- font-size: 0.75rem;- font-weight: 500;- text-decoration: none;- transition: opacity var(--motion-fast);-}--.portal-doctype__card-cta:hover {- opacity: 0.8;-}--.portal-doctype__skel,-.portal-doctype__card-skel {- border-radius: var(--radius-md);- background: linear-gradient(- 90deg,- var(--color-bg-muted) 0%,- var(--color-bg-hover) 50%,- var(--color-bg-muted) 100%- );- background-size: 200% 100%;- animation: shimmer 1.4s linear infinite;-}--.portal-doctype__skel {- display: inline-block;- height: 0.75rem;-}--.portal-doctype__card-skel {- flex: 0 0 17rem;- height: 8rem;- border: 1px solid var(--color-border-light);-}diff --git a/frontend/portal/src/components/DocumentTypeGrid.stories.tsx b/frontend/portal/src/components/DocumentTypeGrid.stories.tsxdeleted file mode 100644index 56d0f33f3e..0000000000--- a/frontend/portal/src/components/DocumentTypeGrid.stories.tsx+++ /dev/null@@ -1,41 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse, delay } from "msw";-import { DocumentTypeGrid } from "@portal/components/DocumentTypeGrid";--const meta: Meta<typeof DocumentTypeGrid> = {- title: "Portal/Home/DocumentTypeGrid",- component: DocumentTypeGrid,- parameters: { layout: "padded" },- decorators: [- (S) => (- <div style={{ maxWidth: "72rem" }}>- <S />- </div>- ),- ],-};-export default meta;-type Story = StoryObj<typeof DocumentTypeGrid>;--export const Default: Story = {};--export const Loading: Story = {- parameters: {- msw: {- handlers: [- http.get("/v1/endpoints", async () => {- await delay("infinite");- return HttpResponse.json([]);- }),- ],- },- },-};--export const Empty: Story = {- parameters: {- msw: {- handlers: [http.get("/v1/endpoints", () => HttpResponse.json([]))],- },- },-};diff --git a/frontend/portal/src/components/DocumentTypeGrid.tsx b/frontend/portal/src/components/DocumentTypeGrid.tsxdeleted file mode 100644index 8aec2784aa..0000000000--- a/frontend/portal/src/components/DocumentTypeGrid.tsx+++ /dev/null@@ -1,181 +0,0 @@-import { useState } from "react";-import {- EmptyState,- Skeleton,- StatusBadge,- Tabs,- type TabItem,-} from "@shared/components";-import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";-import {- fetchVerticals,- type Endpoint,- type Vertical,- type VerticalKey,-} from "@portal/api/endpoints";-import "@portal/components/DocumentTypeGrid.css";--type ActiveTab = VerticalKey | "all";--const TIER_LABEL = ["Free", "Paid", "Enterprise"] as const;-const TIER_TONE = ["success", "info", "purple"] as const;--function tierBadge(tier: 0 | 1 | 2) {- return (- <StatusBadge tone={TIER_TONE[tier]} size="sm">- {TIER_LABEL[tier]}- </StatusBadge>- );-}--function EndpointCard({- endpoint,- vertical,-}: {- endpoint: Endpoint;- vertical: Vertical;-}) {- const visibleRegions = endpoint.regions.slice(0, 2);- const extraRegions = endpoint.regions.length - visibleRegions.length;- return (- <article className="portal-doctype__card">- <div- className="portal-doctype__card-accent"- style={{ background: vertical.color }}- aria-hidden- />- <div className="portal-doctype__card-body">- <div className="portal-doctype__card-eyebrow">- {vertical.label.toUpperCase()}- </div>- <h3 className="portal-doctype__card-title">{endpoint.name}</h3>- <p className="portal-doctype__card-desc">{endpoint.desc}</p>- <div className="portal-doctype__card-meta">- <span className="portal-doctype__regions">- {visibleRegions.join(" · ")}- {extraRegions > 0 && (- <span className="portal-doctype__regions-more">- {" "}- +{extraRegions} more- </span>- )}- </span>- {tierBadge(endpoint.tier)}- </div>- <a- className="portal-doctype__card-cta"- style={{ color: vertical.color }}- href={`#${endpoint.endpoint}`}- onClick={(e) => e.preventDefault()}- >- Explore <span aria-hidden>→</span>- </a>- </div>- </article>- );-}--function GridSkeleton() {- return (- <div className="portal-doctype__groups" aria-hidden>- {Array.from({ length: 2 }).map((_, gi) => (- <div key={gi} className="portal-doctype__group">- <div className="portal-doctype__group-head">- <Skeleton shape="circle" width="0.4375rem" height="0.4375rem" />- <Skeleton width="6rem" />- </div>- <div className="portal-doctype__scroller">- {Array.from({ length: 4 }).map((_, ci) => (- <Skeleton key={ci} shape="rect" width="17rem" height="8rem" />- ))}- </div>- </div>- ))}- </div>- );-}--export function DocumentTypeGrid() {- const [tab, setTab] = useState<ActiveTab>("all");- const state = useAsync<Vertical[]>(() => fetchVerticals(), []);- const { data: verticals } = state;- const { isLoading, isEmpty } = useSectionFlags(state);- const hasVerticals = verticals !== null && verticals.length > 0;-- const tabItems: TabItem<ActiveTab>[] = hasVerticals- ? [- { key: "all", label: "All" },- ...verticals.map<TabItem<ActiveTab>>((v) => ({- key: v.key,- label: v.label,- count: v.endpoints.length,- accentColor: v.color,- dotColor: v.color,- })),- ]- : [];-- return (- <section className="portal-doctype" aria-label="Document types">- <header className="portal-doctype__head">- <h2 className="portal-doctype__title">Document types</h2>- <p className="portal-doctype__sub">- Typed endpoints across every supported vertical — each carries a- schema, region availability and tier gate.- </p>- </header>-- {hasVerticals && (- <Tabs<ActiveTab>- items={tabItems}- activeKey={tab}- onChange={setTab}- ariaLabel="Document type verticals"- />- )}-- {isLoading && <GridSkeleton />}-- {isEmpty && (- <EmptyState- title="No document types yet"- description="When endpoints are registered they'll appear in this catalogue."- />- )}-- {hasVerticals && (- <div className="portal-doctype__groups">- {(tab === "all"- ? verticals- : verticals.filter((v) => v.key === tab)- ).map((v) => (- <div key={v.key} className="portal-doctype__group">- {tab === "all" && (- <div className="portal-doctype__group-head">- <span- className="portal-doctype__tab-dot"- style={{ background: v.color }}- aria-hidden- />- <h3 className="portal-doctype__group-title">{v.label}</h3>- <span className="portal-doctype__group-count">- {v.endpoints.length} endpoints- </span>- </div>- )}- <div className="portal-doctype__scroller">- {v.endpoints.map((endpoint) => (- <EndpointCard- key={endpoint.endpoint}- endpoint={endpoint}- vertical={v}- />- ))}- </div>- </div>- ))}- </div>- )}- </section>- );-}diff --git a/frontend/portal/src/components/PipelineForkWizard.css b/frontend/portal/src/components/PipelineForkWizard.cssnew file mode 100644index 0000000000..a126f0dc4f--- /dev/null+++ b/frontend/portal/src/components/PipelineForkWizard.css@@ -0,0 +1,225 @@+.portal-fork__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 0.75rem;+ margin-bottom: 0.875rem;+}++.portal-fork__title {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-fork__sub {+ margin: 0.125rem 0 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+ max-width: 32rem;+}++/* Template picker */+.portal-fork__templates {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.625rem;+}++@media (max-width: 48rem) {+ .portal-fork__templates {+ grid-template-columns: 1fr;+ }+}++.portal-fork__template {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ padding: 0.75rem 0.875rem;+ text-align: left;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-left: 3px solid var(--accent, var(--color-blue));+ border-radius: var(--radius-md);+ transition:+ background var(--motion-fast),+ border-color var(--motion-fast),+ transform var(--motion-fast);+}++.portal-fork__template[data-accent="blue"] {+ --accent: var(--color-blue);+}+.portal-fork__template[data-accent="purple"] {+ --accent: var(--color-purple);+}+.portal-fork__template[data-accent="green"] {+ --accent: var(--color-green);+}+.portal-fork__template[data-accent="amber"] {+ --accent: var(--color-amber);+}++.portal-fork__template:hover {+ background: var(--color-bg-hover);+ border-color: var(--color-border);+ border-left-color: var(--accent);+ transform: translateY(-1px);+}++.portal-fork__template-name {+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-fork__template-blurb {+ font-size: 0.75rem;+ color: var(--color-text-4);+ line-height: 1.45;+}++.portal-fork__template-types {+ display: flex;+ flex-wrap: wrap;+ gap: 0.25rem;+ margin-top: 0.125rem;+}++/* Build / ready state */+.portal-fork__build-head {+ display: flex;+ flex-direction: column;+ margin-bottom: 0.875rem;+}++.portal-fork__build-head strong {+ font-size: 0.875rem;+ color: var(--color-text-1);+}++.portal-fork__build-head span {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-fork__stages {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.5rem;+}++@media (max-width: 48rem) {+ .portal-fork__stages {+ grid-template-columns: 1fr 1fr;+ }+}++.portal-fork__stage {+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ padding: 0.625rem 0.75rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+ opacity: 0.55;+ transition:+ opacity var(--motion-base),+ border-color var(--motion-base),+ background var(--motion-base);+}++.portal-fork__stage.is-active,+.portal-fork__stage.is-done {+ opacity: 1;+}++.portal-fork__stage.is-active {+ border-color: var(--color-blue);+ background: var(--color-blue-light);+}++.portal-fork__stage.is-done {+ border-color: color-mix(in srgb, var(--color-green) 35%, transparent);+ background: var(--color-green-light);+}++.portal-fork__stage-mark {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.5rem;+ height: 1.5rem;+ border-radius: 50%;+ font-size: 0.75rem;+ font-weight: 600;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border);+ color: var(--color-text-4);+}++.portal-fork__stage.is-done .portal-fork__stage-mark {+ background: var(--color-green);+ border-color: var(--color-green);+ color: var(--color-text-on-accent);+}++.portal-fork__stage.is-active .portal-fork__stage-mark {+ border-color: var(--color-blue);+ color: var(--color-blue);+}++.portal-fork__stage-text {+ display: flex;+ flex-direction: column;+}++.portal-fork__stage-text strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-fork__stage-text span {+ font-size: 0.6875rem;+ color: var(--color-text-4);+ line-height: 1.4;+}++.portal-fork__stage-spin {+ position: absolute;+ top: 0.625rem;+ right: 0.625rem;+ width: 0.875rem;+ height: 0.875rem;+ border: 2px solid color-mix(in srgb, var(--color-blue) 30%, transparent);+ border-top-color: var(--color-blue);+ border-radius: 50%;+ animation: portal-fork-spin 0.7s linear infinite;+}++@keyframes portal-fork-spin {+ to {+ transform: rotate(360deg);+ }+}++@media (prefers-reduced-motion: reduce) {+ .portal-fork__stage-spin {+ animation: none;+ }+}++.portal-fork__build-actions {+ display: flex;+ justify-content: flex-end;+ gap: 0.5rem;+ margin-top: 1rem;+}diff --git a/frontend/portal/src/components/PipelineForkWizard.stories.tsx b/frontend/portal/src/components/PipelineForkWizard.stories.tsxnew file mode 100644index 0000000000..8701e8e9c5--- /dev/null+++ b/frontend/portal/src/components/PipelineForkWizard.stories.tsx@@ -0,0 +1,20 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PipelineForkWizard } from "@portal/components/PipelineForkWizard";++const meta: Meta<typeof PipelineForkWizard> = {+ title: "Portal/Home/PipelineForkWizard",+ component: PipelineForkWizard,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PipelineForkWizard>;++/** Pick a template to watch the deterministic four-stage build animation. */+export const Default: Story = {};diff --git a/frontend/portal/src/components/PipelineForkWizard.tsx b/frontend/portal/src/components/PipelineForkWizard.tsxnew file mode 100644index 0000000000..cd9e54e268--- /dev/null+++ b/frontend/portal/src/components/PipelineForkWizard.tsx@@ -0,0 +1,158 @@+import { useEffect, useRef, useState } from "react";+import { Button, Card, Chip, StatusBadge } from "@shared/components";+import { useView } from "@portal/contexts/ViewContext";+import {+ PIPELINE_STAGES,+ PIPELINE_TEMPLATES,+ type PipelineTemplate,+} from "@portal/api/home";+import "@portal/components/PipelineForkWizard.css";++/**+ * Wizard phases:+ * - `pick` — choose a starter template+ * - `building` — deterministic stage-by-stage build animation+ * - `ready` — all four stages lit; offer deploy+ */+type Phase = "pick" | "building" | "ready";++/** Time each build stage stays "in progress" before the next lights up. */+const STAGE_STEP_MS = 550;++export function PipelineForkWizard() {+ const { setActiveView } = useView();+ const [phase, setPhase] = useState<Phase>("pick");+ const [template, setTemplate] = useState<PipelineTemplate | null>(null);+ // How many stages have completed. Drives both the animation and the+ // pick→building→ready transitions; advanced purely by a fixed-interval timer+ // so the sequence is identical on every run (no Math.random / Date.now).+ const [builtStages, setBuiltStages] = useState(0);+ const timerRef = useRef<number | null>(null);++ // Advance one stage per tick while building; settle into `ready` once all+ // stages are done. The effect re-arms itself on each builtStages change+ // rather than holding a single long-lived interval, so cleanup is trivial.+ useEffect(() => {+ if (phase !== "building") return;+ if (builtStages >= PIPELINE_STAGES.length) {+ setPhase("ready");+ return;+ }+ timerRef.current = window.setTimeout(() => {+ setBuiltStages((n) => n + 1);+ }, STAGE_STEP_MS);+ return () => {+ if (timerRef.current !== null) window.clearTimeout(timerRef.current);+ };+ }, [phase, builtStages]);++ function fork(t: PipelineTemplate) {+ setTemplate(t);+ setBuiltStages(0);+ setPhase("building");+ }++ function reset() {+ setPhase("pick");+ setTemplate(null);+ setBuiltStages(0);+ }++ function deploy() {+ // TODO(backend): POST /v1/pipelines { templateId, name } to create the+ // forked pipeline. Without a backend, route to the pipelines list.+ setActiveView("pipelines");+ }++ return (+ <Card padding="loose" className="portal-fork">+ <header className="portal-fork__head">+ <div>+ <h2 className="portal-fork__title">Fork a starter pipeline</h2>+ <p className="portal-fork__sub">+ Clone a proven workflow and tune it — every template ships the same+ four-stage backbone.+ </p>+ </div>+ {phase !== "pick" && template && (+ <StatusBadge tone={phase === "ready" ? "success" : "info"} size="sm">+ {phase === "ready" ? "Ready to deploy" : "Building…"}+ </StatusBadge>+ )}+ </header>++ {phase === "pick" && (+ <div className="portal-fork__templates">+ {PIPELINE_TEMPLATES.map((t) => (+ <button+ key={t.id}+ type="button"+ className="portal-fork__template"+ data-accent={t.accent}+ onClick={() => fork(t)}+ >+ <span className="portal-fork__template-name">{t.name}</span>+ <span className="portal-fork__template-blurb">{t.blurb}</span>+ <span className="portal-fork__template-types">+ {t.docTypes.map((d) => (+ <Chip key={d} size="sm" tone="neutral">+ {d}+ </Chip>+ ))}+ </span>+ </button>+ ))}+ </div>+ )}++ {phase !== "pick" && template && (+ <div className="portal-fork__build">+ <div className="portal-fork__build-head">+ <strong>{template.name}</strong>+ <span>{template.blurb}</span>+ </div>++ <ol className="portal-fork__stages">+ {PIPELINE_STAGES.map((stage, i) => {+ const done = i < builtStages;+ const active = phase === "building" && i === builtStages;+ const cls =+ "portal-fork__stage" ++ (done ? " is-done" : "") ++ (active ? " is-active" : "");+ return (+ <li key={stage.key} className={cls}>+ <span className="portal-fork__stage-mark" aria-hidden>+ {done ? "✓" : i + 1}+ </span>+ <span className="portal-fork__stage-text">+ <strong>{stage.label}</strong>+ <span>{stage.detail}</span>+ </span>+ {active && (+ <span className="portal-fork__stage-spin" aria-hidden />+ )}+ </li>+ );+ })}+ </ol>++ <div className="portal-fork__build-actions">+ <Button variant="ghost" size="sm" onClick={reset}>+ {phase === "ready" ? "Pick another" : "Cancel"}+ </Button>+ <Button+ variant="gradient"+ size="sm"+ onClick={deploy}+ disabled={phase !== "ready"}+ trailingIcon={<span aria-hidden>→</span>}+ >+ {phase === "ready" ? "Deploy pipeline" : "Building…"}+ </Button>+ </div>+ </div>+ )}+ </Card>+ );+}diff --git a/frontend/portal/src/components/PolicySummary.css b/frontend/portal/src/components/PolicySummary.cssnew file mode 100644index 0000000000..9b4e475895--- /dev/null+++ b/frontend/portal/src/components/PolicySummary.css@@ -0,0 +1,76 @@+.portal-policysum__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 1rem 1.125rem 0.875rem;+ border-bottom: 1px solid var(--color-border-light);+}++.portal-policysum__title {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-policysum__sub {+ margin: 0.125rem 0 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+ max-width: 34rem;+}++.portal-policysum__cat {+ display: flex;+ align-items: center;+ gap: 0.625rem;+}++.portal-policysum__icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ flex: none;+ border-radius: var(--radius-md);+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ font-size: 0.9375rem;+}++.portal-policysum__cat-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}++.portal-policysum__cat-text strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-policysum__cat-text span {+ font-size: 0.6875rem;+ color: var(--color-text-4);+}++.portal-policysum__rule {+ font-size: 0.75rem;+ color: var(--color-text-3);+}++.portal-policysum__loading {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ padding: 1rem 1.125rem;+}++.portal-policysum__loading-row {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}diff --git a/frontend/portal/src/components/PolicySummary.stories.tsx b/frontend/portal/src/components/PolicySummary.stories.tsxnew file mode 100644index 0000000000..6de9f437ac--- /dev/null+++ b/frontend/portal/src/components/PolicySummary.stories.tsx@@ -0,0 +1,48 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { PolicySummary } from "@portal/components/PolicySummary";++const meta: Meta<typeof PolicySummary> = {+ title: "Portal/Home/PolicySummary",+ component: PolicySummary,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "60rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PolicySummary>;++export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/api/v1/policies", async () => {+ await delay("infinite");+ return HttpResponse.json({});+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/api/v1/policies", () =>+ HttpResponse.json({+ summary: { active: 0, paused: 0, categories: 0, docsEnforced: 0 },+ catalogue: [],+ }),+ ),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/PolicySummary.tsx b/frontend/portal/src/components/PolicySummary.tsxnew file mode 100644index 0000000000..37fe47deae--- /dev/null+++ b/frontend/portal/src/components/PolicySummary.tsx@@ -0,0 +1,172 @@+import {+ Button,+ Card,+ EmptyState,+ Skeleton,+ StatusBadge,+ Table,+ type TableColumn,+} from "@shared/components";+import { useView } from "@portal/contexts/ViewContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchPolicies,+ type CatalogueEntry,+ type PoliciesResponse,+} from "@portal/api/policies";+import { policyIcon } from "@portal/components/policies/policyIcons";+import "@portal/components/PolicySummary.css";++/**+ * Each row's display state collapses a category's facts into one of three+ * mutually-exclusive shapes:+ *+ * - `locked` — a coming-soon category; show a "Soon" affordance+ * - `active` — a configured policy that's enabled; offer "Configure"+ * - `off` — available but not set up (or paused); offer "Set up"+ */+type RowState = "locked" | "active" | "off";++interface PolicyRow {+ entry: CatalogueEntry;+ state: RowState;+}++const STATE_BADGE: Record<+ RowState,+ { tone: "success" | "neutral" | "info"; label: string }+> = {+ active: { tone: "success", label: "Active" },+ off: { tone: "neutral", label: "Off" },+ locked: { tone: "info", label: "Soon" },+};++function toRow(entry: CatalogueEntry): PolicyRow {+ if (entry.category.comingSoon) return { entry, state: "locked" };+ const active = entry.policy?.state.status === "active";+ return { entry, state: active ? "active" : "off" };+}++export function PolicySummary() {+ const { setActiveView } = useView();+ const state = useAsync<PoliciesResponse>(() => fetchPolicies(), []);+ const { data } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const goToPolicies = () => setActiveView("policies");++ const columns: TableColumn<PolicyRow>[] = [+ {+ key: "category",+ header: "Policy",+ render: ({ entry }) => (+ <div className="portal-policysum__cat">+ <span className="portal-policysum__icon" aria-hidden>+ {policyIcon(entry.category.icon)}+ </span>+ <div className="portal-policysum__cat-text">+ <strong>{entry.category.label}</strong>+ <span>{entry.category.desc}</span>+ </div>+ </div>+ ),+ },+ {+ key: "status",+ header: "Status",+ width: "7rem",+ render: ({ state }) => {+ const badge = STATE_BADGE[state];+ return (+ <StatusBadge tone={badge.tone} size="sm">+ {badge.label}+ </StatusBadge>+ );+ },+ },+ {+ key: "rule",+ header: "Active rule",+ render: ({ entry, state }) => (+ <span className="portal-policysum__rule">+ {state === "active" ? entry.config.summary : "No rule enforced yet"}+ </span>+ ),+ },+ {+ key: "action",+ header: "",+ align: "right",+ width: "9rem",+ render: ({ state }) => {+ if (state === "locked") {+ return (+ <Button size="sm" variant="ghost" onClick={goToPolicies}>+ Coming soon+ </Button>+ );+ }+ return (+ <Button+ size="sm"+ variant={state === "active" ? "ghost" : "outline"}+ onClick={goToPolicies}+ >+ {state === "active" ? "Configure" : "Set up"}+ </Button>+ );+ },+ },+ ];++ const rows: PolicyRow[] = data?.catalogue.map(toRow) ?? [];++ return (+ <section className="portal-policysum" aria-label="What runs on your PDFs">+ <Card padding="none">+ <header className="portal-policysum__head">+ <div>+ <h2 className="portal-policysum__title">What runs on your PDFs</h2>+ <p className="portal-policysum__sub">+ Standing automations every document passes through, regardless of+ which pipeline handles it.+ </p>+ </div>+ {data && (+ <StatusBadge tone="info" size="sm">+ {data.summary.active} / {data.summary.categories} active+ </StatusBadge>+ )}+ </header>++ {isLoading && (+ <div className="portal-policysum__loading" aria-hidden>+ {Array.from({ length: 5 }).map((_, i) => (+ <div key={i} className="portal-policysum__loading-row">+ <Skeleton width="9rem" />+ <Skeleton width="60%" height="0.625rem" />+ </div>+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ size="compact"+ title="No policies yet"+ description="Once policies are configured, the categories appear here."+ />+ )}++ {data && rows.length > 0 && (+ <Table+ columns={columns}+ rows={rows}+ rowKey={(r) => r.entry.category.id}+ onRowClick={goToPolicies}+ />+ )}+ </Card>+ </section>+ );+}diff --git a/frontend/portal/src/components/ProcessingStatusStrip.css b/frontend/portal/src/components/ProcessingStatusStrip.cssnew file mode 100644index 0000000000..911bf99541--- /dev/null+++ b/frontend/portal/src/components/ProcessingStatusStrip.css@@ -0,0 +1,78 @@+.portal-statusstrip--free {+ display: flex;+ flex-direction: column;+}++/* The Banner body already provides padding; lay out the free meter inside it. */+.portal-statusstrip--free .sui-banner__body {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}++.portal-statusstrip__free-row {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 0.5rem;+}++.portal-statusstrip__free-label {+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-statusstrip__free-label strong {+ color: var(--color-text-1);+ font-weight: 600;+}++.portal-statusstrip__free-pct {+ font-size: 0.75rem;+ font-family: var(--font-mono);+ color: var(--color-text-4);+}++/* Paid strip: single inline row */+.portal-statusstrip--paid {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ padding: 0.625rem 0.875rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+}++.portal-statusstrip__plan {+ display: inline-flex;+ align-items: center;+ gap: 0.4375rem;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-statusstrip__dot {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 50%;+}++.portal-statusstrip__sep {+ color: var(--color-text-5);+}++.portal-statusstrip__volume {+ font-size: 0.8125rem;+ color: var(--color-text-3);+}++.portal-statusstrip__volume strong {+ color: var(--color-text-1);+ font-weight: 600;+}++.portal-statusstrip__manage {+ margin-left: auto;+}diff --git a/frontend/portal/src/components/ProcessingStatusStrip.stories.tsx b/frontend/portal/src/components/ProcessingStatusStrip.stories.tsxnew file mode 100644index 0000000000..c5df1139d5--- /dev/null+++ b/frontend/portal/src/components/ProcessingStatusStrip.stories.tsx@@ -0,0 +1,36 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { ProcessingStatusStrip } from "@portal/components/ProcessingStatusStrip";++const meta: Meta<typeof ProcessingStatusStrip> = {+ title: "Portal/Home/ProcessingStatusStrip",+ component: ProcessingStatusStrip,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "60rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ProcessingStatusStrip>;++/** Switch the Tier toolbar to compare the free meter vs the paid plan row. */+export const Default: Story = {};++/** Free tier pushed near its cap so the meter and upgrade nudge turn amber. */+export const FreeNearCap: Story = {+ globals: { tier: "free" },+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/home/kpis", async () => {+ await delay(80);+ return HttpResponse.json([{ value: "472 / 500" }]);+ }),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/ProcessingStatusStrip.tsx b/frontend/portal/src/components/ProcessingStatusStrip.tsxnew file mode 100644index 0000000000..4268eb3ee8--- /dev/null+++ b/frontend/portal/src/components/ProcessingStatusStrip.tsx@@ -0,0 +1,112 @@+import { Banner, Button, ProgressBar, Skeleton } from "@shared/components";+import { TIER_INFO, useTier } from "@portal/contexts/TierContext";+import { useView } from "@portal/contexts/ViewContext";+import { useAsync } from "@portal/hooks/useAsync";+import { fetchHomeKpis, type KpiEntry } from "@portal/api/home";+import "@portal/components/ProcessingStatusStrip.css";++/**+ * Parses the free-tier "used / cap" KPI string (e.g. "247 / 500") into its+ * parts. The free meter is the headline KPI value rather than a separate+ * endpoint, so the strip reads it from the same `fetchHomeKpis` payload the+ * KPI cards use — no duplicate fetch, no second source of truth.+ */+function parseUsage(value: KpiEntry["value"]): {+ used: number;+ cap: number;+} | null {+ const match = String(value).match(/([\d,]+)\s*\/\s*([\d,]+)/);+ if (!match) return null;+ const used = Number(match[1].replace(/,/g, ""));+ const cap = Number(match[2].replace(/,/g, ""));+ if (!Number.isFinite(used) || !Number.isFinite(cap) || cap <= 0) return null;+ return { used, cap };+}++export function ProcessingStatusStrip() {+ const { tier } = useTier();+ const { setActiveView } = useView();+ const { data: kpis, loading } = useAsync<KpiEntry[]>(+ () => fetchHomeKpis(tier),+ [tier],+ );++ if (loading) {+ return (+ <div className="portal-statusstrip" aria-busy>+ <Skeleton width="9rem" height="0.875rem" />+ <Skeleton height="0.5rem" />+ </div>+ );+ }++ if (tier === "free") {+ const usage = parseUsage(kpis?.[0]?.value ?? "");+ const used = usage?.used ?? 0;+ const cap = usage?.cap ?? 500;+ const ratio = cap > 0 ? used / cap : 0;+ const nearCap = ratio >= 0.8;++ return (+ <Banner+ tone={nearCap ? "warning" : "neutral"}+ className="portal-statusstrip portal-statusstrip--free"+ action={+ nearCap ? (+ <Button+ size="sm"+ variant="outline"+ onClick={() => setActiveView("usage")}+ >+ Upgrade+ </Button>+ ) : undefined+ }+ >+ <div className="portal-statusstrip__free-row">+ <span className="portal-statusstrip__free-label">+ <strong>{used.toLocaleString()}</strong> / {cap.toLocaleString()}{" "}+ PDFs this month+ </span>+ <span className="portal-statusstrip__free-pct">+ {Math.round(ratio * 100)}%+ </span>+ </div>+ <ProgressBar+ value={ratio}+ thresholded+ label={`${used} of ${cap} PDFs used this month`}+ />+ </Banner>+ );+ }++ // Pro / enterprise: plan name + headline volume from the first KPI.+ const volume = kpis?.[0]?.value;+ return (+ <div className="portal-statusstrip portal-statusstrip--paid">+ <span className="portal-statusstrip__plan">+ <span+ className="portal-statusstrip__dot"+ style={{ background: TIER_INFO[tier].dotColor }}+ aria-hidden+ />+ {TIER_INFO[tier].label}+ </span>+ <span className="portal-statusstrip__sep" aria-hidden>+ ·+ </span>+ <span className="portal-statusstrip__volume">+ <strong>{volume ?? "—"}</strong> PDFs processed · last 30 days+ </span>+ <Button+ size="sm"+ variant="ghost"+ className="portal-statusstrip__manage"+ onClick={() => setActiveView("usage")}+ >+ Manage plan+ </Button>+ </div>+ );+}diff --git a/frontend/portal/src/components/SettingsModal.css b/frontend/portal/src/components/SettingsModal.cssindex c43e0655a5..59fa1e0bc4 100644--- a/frontend/portal/src/components/SettingsModal.css+++ b/frontend/portal/src/components/SettingsModal.css@@ -1,17 +1,8 @@-/* The modal body scrolls; keep the tab strip pinned at the top of it. */-.portal-settings__tabs {- position: sticky;- top: -1rem;- z-index: 1;- margin: -1rem -1.125rem 0;- padding: 0.5rem 1.125rem 0;- background: var(--color-surface);- border-bottom: 1px solid var(--color-border-light);-}--.portal-settings__panel {- padding-top: 1rem;- min-height: 18rem;+/* The settings overlay hosts a full-bleed two-pane SettingsShell, so the+ modal frame contributes no padding of its own and lets the shell scroll. */+.portal-settings .sui-modal__body {+ padding: 0;+ overflow: hidden;}.portal-settings__section {@@ -221,6 +212,13 @@color: var(--color-text-4);}+/* Label paired with a gating badge (e.g. "SCIM provisioning" + Enterprise). */+.portal-settings__row-label {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+}+/* ── Workspace plan card ──────────────────────────────────────────────── */.portal-settings__plan {display: flex;diff --git a/frontend/portal/src/components/SettingsModal.tsx b/frontend/portal/src/components/SettingsModal.tsxindex 3d3450d144..a770e9f587 100644--- a/frontend/portal/src/components/SettingsModal.tsx+++ b/frontend/portal/src/components/SettingsModal.tsx@@ -6,20 +6,49 @@ import {Input,Modal,Select,+ SettingsShell,Skeleton,StatusBadge,- Tabs,ToggleSwitch,type SelectOption,- type TabItem,+ type SettingsNavSection,} from "@shared/components";-import { useTier } from "@portal/contexts/TierContext";+import { useTier, type Tier } from "@portal/contexts/TierContext";import { useTheme, type Theme } from "@portal/contexts/ThemeContext";import { useAsync } from "@portal/hooks/useAsync";-import { fetchSettings, type SettingsSnapshot } from "@portal/api/settings";+import {+ fetchSettings,+ type ActiveSession,+ type BetaFeature,+ type SettingsSnapshot,+} from "@portal/api/settings";+import {+ UsersIcon,+ SunIcon,+ BellIcon,+ SettingsIcon,+ PoliciesIcon,+ InfrastructureIcon,+ SparklesIcon,+} from "@portal/components/icons";import "@portal/components/SettingsModal.css";-type SettingsTab = "profile" | "preferences" | "workspace";+type SettingsSection =+ | "profile"+ | "appearance"+ | "notifications"+ | "general"+ | "authentication"+ | "sessions"+ | "early-access";++/** Org-wide auth posture the Admin sections edit, mirrored into local state. */+interface SecurityForm {+ mfaEnforced: boolean;+ ssoEnabled: boolean;+ scimEnabled: boolean;+ sessionTimeoutMins: number;+}interface SettingsModalProps {open: boolean;@@ -57,10 +86,55 @@ const NOTIFICATION_COPY: Record<},};-const TABS: TabItem<SettingsTab>[] = [- { key: "profile", label: "Profile" },- { key: "preferences", label: "Preferences" },- { key: "workspace", label: "Workspace" },+const SECTION_LABEL: Record<SettingsSection, string> = {+ profile: "Profile",+ appearance: "Appearance",+ notifications: "Notifications",+ general: "General",+ authentication: "Authentication",+ sessions: "Active sessions",+ "early-access": "Early access",+};++const NAV_SECTIONS: SettingsNavSection[] = [+ {+ title: "Account",+ items: [+ { key: "profile", label: "Profile", icon: <UsersIcon size={16} /> },+ { key: "appearance", label: "Appearance", icon: <SunIcon size={16} /> },+ {+ key: "notifications",+ label: "Notifications",+ icon: <BellIcon size={16} />,+ },+ ],+ },+ {+ title: "Workspace",+ items: [+ { key: "general", label: "General", icon: <SettingsIcon size={16} /> },+ ],+ },+ {+ title: "Admin",+ items: [+ {+ key: "authentication",+ label: "Authentication",+ icon: <PoliciesIcon size={16} />,+ },+ {+ key: "sessions",+ label: "Active sessions",+ icon: <InfrastructureIcon size={16} />,+ },+ {+ key: "early-access",+ label: "Early access",+ icon: <SparklesIcon size={16} />,+ },+ ],+ },];const THEME_OPTIONS: { value: Theme; label: string; hint: string }[] = [@@ -68,17 +142,24 @@ const THEME_OPTIONS: { value: Theme; label: string; hint: string }[] = [{ value: "dark", label: "Dark", hint: "Dim surfaces" },];+const SESSION_TIMEOUT_OPTIONS: SelectOption[] = [+ { value: "60", label: "1 hour" },+ { value: "240", label: "4 hours" },+ { value: "480", label: "8 hours" },+ { value: "720", label: "12 hours" },+ { value: "1440", label: "24 hours" },+];+/**- * Account settings as a portal-wide overlay. Opens onto a tier-aware snapshot- * (profile, notification defaults, workspace + region) which seeds editable- * local form state. Save is a no-op for the demo — it simply closes — but the- * theme control writes straight through to ThemeProvider so the change is real- * and visible immediately.+ * Account settings as a portal-wide overlay. A grouped left-nav (Account /+ * Workspace / Admin) over a tier-aware snapshot that seeds editable local form+ * state. Save is a no-op for the demo — it closes — but the theme control+ * writes straight through to ThemeProvider so the change is real and visible.*/export function SettingsModal({ open, onClose }: SettingsModalProps) {const { tier } = useTier();const { theme, setTheme } = useTheme();- const [tab, setTab] = useState<SettingsTab>("profile");+ const [section, setSection] = useState<SettingsSection>("profile");const { data: snapshot, loading } = useAsync<SettingsSnapshot>(() => fetchSettings(tier),@@ -95,6 +176,13 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {const [notifications, setNotifications] = useState<Record<string, boolean>>({},);+ const [security, setSecurity] = useState<SecurityForm>({+ mfaEnforced: false,+ ssoEnabled: false,+ scimEnabled: false,+ sessionTimeoutMins: 480,+ });+ const [betaToggles, setBetaToggles] = useState<Record<string, boolean>>({});useEffect(() => {if (!snapshot) return;@@ -105,10 +193,19 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {setNotifications(Object.fromEntries(snapshot.notifications.map((n) => [n.id, n.enabled])),);+ setSecurity({+ mfaEnforced: snapshot.security.mfaEnforced,+ ssoEnabled: snapshot.security.ssoEnabled,+ scimEnabled: snapshot.security.scimEnabled,+ sessionTimeoutMins: snapshot.security.sessionTimeoutMins,+ });+ setBetaToggles(+ Object.fromEntries(snapshot.betaFeatures.map((f) => [f.id, f.enabled])),+ );}, [snapshot]);useEffect(() => {- if (open) setTab("profile");+ if (open) setSection("profile");}, [open]);const regionOptions = useMemo<SelectOption[]>(() => {@@ -129,36 +226,31 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {<Modalopen={open}onClose={onClose}- width="lg"- title="Settings"- subtitle="Manage your profile, preferences, and workspace."+ width="xl"+ ariaLabel="Settings"className="portal-settings"- footer={- <>- <span className="portal-settings__footer-note">- Changes apply to this workspace.- </span>- <Button variant="ghost" onClick={onClose}>- Cancel- </Button>- <Button variant="gradient" onClick={onClose}>- Save changes- </Button>- </>- }>- <div className="portal-settings__tabs">- <Tabs- items={TABS}- activeKey={tab}- onChange={setTab}- variant="underline"- ariaLabel="Settings sections"- />- </div>-- <div className="portal-settings__panel">- {tab === "profile" && (+ <SettingsShell+ sections={NAV_SECTIONS}+ activeKey={section}+ onSelect={(k) => setSection(k as SettingsSection)}+ title={SECTION_LABEL[section]}+ onClose={onClose}+ footer={+ <>+ <span className="portal-settings__footer-note">+ Changes apply to this workspace.+ </span>+ <Button variant="ghost" onClick={onClose}>+ Cancel+ </Button>+ <Button variant="gradient" onClick={onClose}>+ Save changes+ </Button>+ </>+ }+ >+ {section === "profile" && (<ProfilePanelloading={isLoading}name={name}@@ -170,20 +262,22 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {/>)}- {tab === "preferences" && (- <PreferencesPanel+ {section === "appearance" && (+ <AppearancePanel theme={theme} onTheme={setTheme} />+ )}++ {section === "notifications" && (+ <NotificationsPanelloading={isLoading}notifications={notifications}order={snapshot?.notifications.map((n) => n.id) ?? []}onToggle={(id, value) =>setNotifications((prev) => ({ ...prev, [id]: value }))}- theme={theme}- onTheme={setTheme}/>)}- {tab === "workspace" && (+ {section === "general" && (<WorkspacePanelloading={isLoading}workspaceName={workspaceName}@@ -195,7 +289,35 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {seats={snapshot?.workspace.seats}/>)}- </div>++ {section === "authentication" && (+ <AuthenticationPanel+ loading={isLoading}+ tier={tier}+ security={security}+ onSecurity={(patch) => setSecurity((s) => ({ ...s, ...patch }))}+ />+ )}++ {section === "sessions" && (+ <SessionsPanel+ loading={isLoading}+ sessions={snapshot?.security.activeSessions ?? []}+ />+ )}++ {section === "early-access" && (+ <EarlyAccessPanel+ loading={isLoading}+ tier={tier}+ betaFeatures={snapshot?.betaFeatures ?? []}+ betaToggles={betaToggles}+ onBeta={(id, value) =>+ setBetaToggles((prev) => ({ ...prev, [id]: value }))+ }+ />+ )}+ </SettingsShell></Modal>);}@@ -286,21 +408,13 @@ function ProfilePanel({}/* ──────────────────────────────────────────────────────────────────────── */-/* Preferences */+/* Appearance *//* ──────────────────────────────────────────────────────────────────────── */-function PreferencesPanel({- loading,- notifications,- order,- onToggle,+function AppearancePanel({theme,onTheme,}: {- loading: boolean;- notifications: Record<string, boolean>;- order: string[];- onToggle: (id: string, value: boolean) => void;theme: Theme;onTheme: (theme: Theme) => void;}) {@@ -308,7 +422,7 @@ function PreferencesPanel({<div className="portal-settings__section"><div className="portal-settings__group"><div className="portal-settings__group-head">- <h3 className="portal-settings__group-title">Appearance</h3>+ <h3 className="portal-settings__group-title">Theme</h3><p className="portal-settings__group-sub">Choose how the portal looks on this device.</p>@@ -345,10 +459,30 @@ function PreferencesPanel({))}</div></div>+ </div>+ );+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Notifications */+/* ──────────────────────────────────────────────────────────────────────── */+function NotificationsPanel({+ loading,+ notifications,+ order,+ onToggle,+}: {+ loading: boolean;+ notifications: Record<string, boolean>;+ order: string[];+ onToggle: (id: string, value: boolean) => void;+}) {+ return (+ <div className="portal-settings__section"><div className="portal-settings__group"><div className="portal-settings__group-head">- <h3 className="portal-settings__group-title">Notifications</h3>+ <h3 className="portal-settings__group-title">Email notifications</h3><p className="portal-settings__group-sub">Pick which events reach your inbox.</p>@@ -469,3 +603,233 @@ function WorkspacePanel({</div>);}++/* ──────────────────────────────────────────────────────────────────────── */+/* Admin · Authentication */+/* ──────────────────────────────────────────────────────────────────────── */++function AuthenticationPanel({+ loading,+ tier,+ security,+ onSecurity,+}: {+ loading: boolean;+ tier: Tier;+ security: SecurityForm;+ onSecurity: (patch: Partial<SecurityForm>) => void;+}) {+ if (loading) {+ return (+ <div className="portal-settings__section">+ <Skeleton height="3rem" />+ <Skeleton height="3rem" />+ <Skeleton height="3rem" />+ </div>+ );+ }++ // SSO/SCIM are enterprise capabilities; below it they render locked with a+ // badge rather than disappearing, so the upgrade path stays visible.+ const isEnterprise = tier === "enterprise";++ return (+ <div className="portal-settings__section">+ <div className="portal-settings__group">+ <div className="portal-settings__group-head">+ <h3 className="portal-settings__group-title">Sign-in policy</h3>+ <p className="portal-settings__group-sub">+ Organisation-wide authentication controls.+ </p>+ </div>++ <div className="portal-settings__notifs">+ <div className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <strong>Enforce two-factor (MFA)</strong>+ <span>Require every member to complete MFA at sign-in.</span>+ </div>+ <ToggleSwitch+ checked={security.mfaEnforced}+ onChange={(v) => onSecurity({ mfaEnforced: v })}+ />+ </div>++ <div className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <span className="portal-settings__row-label">+ <strong>Single sign-on (SAML)</strong>+ {!isEnterprise && (+ <StatusBadge tone="info" size="sm" showDot={false}>+ Enterprise+ </StatusBadge>+ )}+ </span>+ <span>Federate sign-in through your identity provider.</span>+ </div>+ <ToggleSwitch+ checked={isEnterprise && security.ssoEnabled}+ disabled={!isEnterprise}+ onChange={(v) => onSecurity({ ssoEnabled: v })}+ />+ </div>++ <div className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <span className="portal-settings__row-label">+ <strong>SCIM provisioning</strong>+ {!isEnterprise && (+ <StatusBadge tone="info" size="sm" showDot={false}>+ Enterprise+ </StatusBadge>+ )}+ </span>+ <span>Sync members and roles from your directory.</span>+ </div>+ <ToggleSwitch+ checked={isEnterprise && security.scimEnabled}+ disabled={!isEnterprise}+ onChange={(v) => onSecurity({ scimEnabled: v })}+ />+ </div>+ </div>++ <FormField+ label="Session timeout"+ helperText="Members re-authenticate after this idle period."+ >+ <Select+ value={String(security.sessionTimeoutMins)}+ onChange={(e) =>+ onSecurity({ sessionTimeoutMins: Number(e.target.value) })+ }+ options={SESSION_TIMEOUT_OPTIONS}+ />+ </FormField>+ </div>+ </div>+ );+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Admin · Active sessions */+/* ──────────────────────────────────────────────────────────────────────── */++function SessionsPanel({+ loading,+ sessions,+}: {+ loading: boolean;+ sessions: ActiveSession[];+}) {+ if (loading) {+ return (+ <div className="portal-settings__section">+ <Skeleton height="3rem" />+ <Skeleton height="3rem" />+ </div>+ );+ }++ return (+ <div className="portal-settings__section">+ <div className="portal-settings__group">+ <div className="portal-settings__group-head">+ <h3 className="portal-settings__group-title">Active sessions</h3>+ <p className="portal-settings__group-sub">+ Devices currently signed in to this account.+ </p>+ </div>+ <div className="portal-settings__notifs">+ {sessions.map((s) => (+ <div key={s.id} className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <strong>{s.device}</strong>+ <span>+ {s.location} · {s.lastActive}+ </span>+ </div>+ {s.current ? (+ <StatusBadge tone="success" size="sm">+ This device+ </StatusBadge>+ ) : (+ // TODO(backend): DELETE /v1/settings/sessions/{id}+ <Button variant="ghost" size="sm">+ Revoke+ </Button>+ )}+ </div>+ ))}+ </div>+ </div>+ </div>+ );+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Admin · Early access */+/* ──────────────────────────────────────────────────────────────────────── */++function EarlyAccessPanel({+ loading,+ tier,+ betaFeatures,+ betaToggles,+ onBeta,+}: {+ loading: boolean;+ tier: Tier;+ betaFeatures: BetaFeature[];+ betaToggles: Record<string, boolean>;+ onBeta: (id: string, value: boolean) => void;+}) {+ if (loading) {+ return (+ <div className="portal-settings__section">+ <Skeleton height="3rem" />+ <Skeleton height="3rem" />+ </div>+ );+ }++ const isEnterprise = tier === "enterprise";++ return (+ <div className="portal-settings__section">+ <div className="portal-settings__group">+ <div className="portal-settings__group-head">+ <h3 className="portal-settings__group-title">Preview features</h3>+ <p className="portal-settings__group-sub">+ Opt into features still in preview.+ </p>+ </div>+ <div className="portal-settings__notifs">+ {betaFeatures.map((f) => {+ const locked = Boolean(f.enterpriseOnly) && !isEnterprise;+ return (+ <div key={f.id} className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <span className="portal-settings__row-label">+ <strong>{f.label}</strong>+ {locked && (+ <StatusBadge tone="info" size="sm" showDot={false}>+ Enterprise+ </StatusBadge>+ )}+ </span>+ <span>{f.description}</span>+ </div>+ <ToggleSwitch+ checked={!locked && (betaToggles[f.id] ?? false)}+ disabled={locked}+ onChange={(v) => onBeta(f.id, v)}+ />+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/Sidebar.css b/frontend/portal/src/components/Sidebar.cssindex c61f8e5c97..c12b6debb0 100644--- a/frontend/portal/src/components/Sidebar.css+++ b/frontend/portal/src/components/Sidebar.css@@ -20,24 +20,24 @@border-bottom: 1px solid var(--color-sidebar-divider);}-/* Editor "Stirling PDF" wordmark logo (theme-switched in Sidebar.tsx) */+/* Stirling brand mark (theme-switched in Sidebar.tsx) + product wordmark */.portal-sidebar__brand {display: inline-flex;align-items: center;- gap: 0.25rem;+ gap: 0.4rem;}-.portal-sidebar__brand-logo {- height: 1.5rem;+.portal-sidebar__brand-mark {+ height: 1.375rem;width: auto;display: block;}-/* TEMP: "portal" suffix styled to read as part of the wordmark */.portal-sidebar__logo-suffix {font-family: var(--font-brand);- font-size: 1.125rem;+ font-size: 1.0625rem;font-weight: 700;- color: var(--color-text-3);+ color: var(--color-text-1);letter-spacing: 0.01em;+ white-space: nowrap;}/* App switcher (down-arrow → Portal / Editor) */diff --git a/frontend/portal/src/components/Sidebar.tsx b/frontend/portal/src/components/Sidebar.tsxindex 4897193f36..a31f59d933 100644--- a/frontend/portal/src/components/Sidebar.tsx+++ b/frontend/portal/src/components/Sidebar.tsx@@ -5,15 +5,16 @@ import { useTheme } from "@portal/contexts/ThemeContext";import { useUI } from "@portal/contexts/UIContext";import { useAsync } from "@portal/hooks/useAsync";import { fetchHomeKpis, type KpiEntry } from "@portal/api/home";-import wordmarkLight from "@shared/assets/stirling-pdf-logo-light.svg";-import wordmarkDark from "@shared/assets/stirling-pdf-logo-dark.svg";import markLight from "@shared/assets/stirling-mark-light.svg";import markDark from "@shared/assets/stirling-mark-dark.svg";import {HomeIcon,+ UsersIcon,SourcesIcon,+ PoliciesIcon,PipelinesIcon,DocumentsIcon,+ ComponentsIcon,InfrastructureIcon,UsageIcon,DocsIcon,@@ -22,10 +23,9 @@ import {} from "@portal/components/icons";import "@portal/components/Sidebar.css";-// TEMP app switcher. The editor is a separate Vite app — no shared shell yet-// (see PORTAL_INTEGRATION_PLAN.md), so switching is a hard navigation: the-// editor's own dev server in dev, the site root in prod. A standalone portal-// deploy will later gate this behind a configured editor URL.+// The editor is a separate Vite app with no shared shell, so switching apps is+// a hard navigation — the editor's dev server in dev, the site root in prod.+// A standalone portal deploy can gate this behind a configured editor URL.const EDITOR_URL = import.meta.env.DEV ? "http://localhost:5180/" : "/";interface NavEntry {@@ -39,9 +39,12 @@ const GROUP_PRIMARY: NavEntry[] = [];const GROUP_OPERATIONAL: NavEntry[] = [+ { id: "users", label: "Users", icon: <UsersIcon /> },{ id: "sources", label: "Sources", icon: <SourcesIcon /> },+ { id: "policies", label: "Policies", icon: <PoliciesIcon /> },{ id: "pipelines", label: "Pipelines", icon: <PipelinesIcon /> },{ id: "documents", label: "Documents", icon: <DocumentsIcon /> },+ { id: "components", label: "Components", icon: <ComponentsIcon /> },];const GROUP_PLATFORM: NavEntry[] = [@@ -132,11 +135,13 @@ export function Sidebar() {<div className="portal-sidebar__logo"><span className="portal-sidebar__brand"><img- className="portal-sidebar__brand-logo"- src={theme === "dark" ? wordmarkDark : wordmarkLight}- alt="Stirling PDF"+ className="portal-sidebar__brand-mark"+ src={theme === "dark" ? markDark : markLight}+ alt="Stirling"/>- <span className="portal-sidebar__logo-suffix">portal</span>+ <span className="portal-sidebar__logo-suffix">+ Stirling Processor+ </span></span><Dropdown.Root align="end" className="portal-sidebar__app-switch">@@ -160,7 +165,7 @@ export function Sidebar() {/>}>- Portal+ Processor</Dropdown.Item><Dropdown.ItemonSelect={() => {diff --git a/frontend/portal/src/components/agent-builder/AgentBuilderPanel.stories.tsx b/frontend/portal/src/components/agent-builder/AgentBuilderPanel.stories.tsxnew file mode 100644index 0000000000..2b096b5952--- /dev/null+++ b/frontend/portal/src/components/agent-builder/AgentBuilderPanel.stories.tsx@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { agentsFor } from "@portal/mocks/agents";+import { AgentBuilderPanel } from "@portal/components/agent-builder/AgentBuilderPanel";++const PRO = agentsFor("pro");++const meta: Meta<typeof AgentBuilderPanel> = {+ title: "Portal/AgentBuilder/AgentBuilderPanel",+ component: AgentBuilderPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "52rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof AgentBuilderPanel>;++/** Published agent with enterprise governance unlocked. */+export const Published: Story = {+ args: { agent: PRO[0], governanceUnlocked: true },+};++/** Draft agent with governance locked (pro/free posture). */+export const DraftLocked: Story = {+ args: { agent: PRO[2], governanceUnlocked: false },+};diff --git a/frontend/portal/src/components/agent-builder/AgentBuilderPanel.tsx b/frontend/portal/src/components/agent-builder/AgentBuilderPanel.tsxnew file mode 100644index 0000000000..39c65773d5--- /dev/null+++ b/frontend/portal/src/components/agent-builder/AgentBuilderPanel.tsx@@ -0,0 +1,72 @@+import { useState } from "react";+import { StatusBadge, Tabs, type TabItem } from "@shared/components";+import { type Agent, AGENT_STATUS_TONE } from "@portal/api/agents";+import { ScenariosPanel } from "@portal/components/agent-builder/ScenariosPanel";+import { ToolsPanel } from "@portal/components/agent-builder/ToolsPanel";+import { EvalsPanel } from "@portal/components/agent-builder/EvalsPanel";+import { VersionsPanel } from "@portal/components/agent-builder/VersionsPanel";+import "@portal/views/AgentBuilder.css";++type BuilderTab = "scenarios" | "tools" | "evals" | "versions";++interface AgentBuilderPanelProps {+ agent: Agent;+ /** Enterprise unlocks restricted-tools governance and deep version history. */+ governanceUnlocked: boolean;+}++/** The selected agent's builder: header + tabbed Scenarios / Tools / Evals / Versions. */+export function AgentBuilderPanel({+ agent,+ governanceUnlocked,+}: AgentBuilderPanelProps) {+ const [tab, setTab] = useState<BuilderTab>("scenarios");++ const tabs: TabItem<BuilderTab>[] = [+ { key: "scenarios", label: "Scenarios", count: agent.scenarios.length },+ { key: "tools", label: "Tools" },+ {+ key: "evals",+ label: "Evals",+ count: agent.evalsTotal > 0 ? agent.evalsTotal : undefined,+ },+ { key: "versions", label: "Versions", count: agent.versions.length },+ ];++ return (+ <section className="portal-agents__builder">+ <header className="portal-agents__builder-head">+ <div>+ <h2 className="portal-agents__builder-title">{agent.name}</h2>+ <span className="portal-agents__builder-sub">{agent.role}</span>+ </div>+ <div className="portal-agents__builder-meta">+ <StatusBadge tone={AGENT_STATUS_TONE[agent.status]} size="sm">+ {agent.status}+ </StatusBadge>+ <code className="portal-agents__builder-version">+ {agent.version}+ </code>+ <code className="portal-agents__builder-model">{agent.model}</code>+ </div>+ </header>++ <Tabs<BuilderTab>+ items={tabs}+ activeKey={tab}+ onChange={setTab}+ variant="underline"+ ariaLabel="Agent builder sections"+ />++ {tab === "scenarios" && <ScenariosPanel agent={agent} />}+ {tab === "tools" && (+ <ToolsPanel agent={agent} governanceUnlocked={governanceUnlocked} />+ )}+ {tab === "evals" && <EvalsPanel agent={agent} />}+ {tab === "versions" && (+ <VersionsPanel agent={agent} historyUnlocked={governanceUnlocked} />+ )}+ </section>+ );+}diff --git a/frontend/portal/src/components/agent-builder/AgentKpiStrip.stories.tsx b/frontend/portal/src/components/agent-builder/AgentKpiStrip.stories.tsxnew file mode 100644index 0000000000..9ab047309e--- /dev/null+++ b/frontend/portal/src/components/agent-builder/AgentKpiStrip.stories.tsx@@ -0,0 +1,23 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildAgentsResponse } from "@portal/mocks/agents";+import { AgentKpiStrip } from "@portal/components/agent-builder/AgentKpiStrip";++const meta: Meta<typeof AgentKpiStrip> = {+ title: "Portal/AgentBuilder/AgentKpiStrip",+ component: AgentKpiStrip,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof AgentKpiStrip>;++export const Pro: Story = {+ args: { summary: buildAgentsResponse("pro").summary, loading: false },+};++export const Enterprise: Story = {+ args: { summary: buildAgentsResponse("enterprise").summary, loading: false },+};++export const Loading: Story = {+ args: { summary: null, loading: true },+};diff --git a/frontend/portal/src/components/agent-builder/AgentKpiStrip.tsx b/frontend/portal/src/components/agent-builder/AgentKpiStrip.tsxnew file mode 100644index 0000000000..019e9653ab--- /dev/null+++ b/frontend/portal/src/components/agent-builder/AgentKpiStrip.tsx@@ -0,0 +1,52 @@+import { MetricCard, MetricStrip } from "@shared/components";+import type { AgentsSummary } from "@portal/api/agents";++/**+ * KPI labels are product copy — they describe what each metric IS, not its+ * value — so the strip's structure stays stable across loading / ready states;+ * only values flow from the API.+ */+const KPI_LABELS = [+ "Active agents",+ "Avg eval pass rate",+ "Scenarios",+ "Latest published",+] as const;++interface AgentKpiStripProps {+ summary: AgentsSummary | null;+ loading: boolean;+}++export function AgentKpiStrip({ summary, loading }: AgentKpiStripProps) {+ const values: (string | number)[] = summary+ ? [+ summary.activeAgents,+ `${Math.round(summary.avgPassRate * 100)}%`,+ summary.totalScenarios,+ summary.latestPublished,+ ]+ : ["—", "—", "—", "—"];++ const descriptions: (string | undefined)[] = summary+ ? [+ `${summary.totalAgents} total`,+ "across golden sets",+ "test cases",+ "fleet-wide",+ ]+ : [];++ return (+ <MetricStrip>+ {KPI_LABELS.map((label, i) => (+ <MetricCard+ key={label}+ label={label}+ value={loading ? "—" : values[i]}+ description={loading ? undefined : descriptions[i]}+ />+ ))}+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/agent-builder/AgentSelector.stories.tsx b/frontend/portal/src/components/agent-builder/AgentSelector.stories.tsxnew file mode 100644index 0000000000..064bd55da1--- /dev/null+++ b/frontend/portal/src/components/agent-builder/AgentSelector.stories.tsx@@ -0,0 +1,33 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { agentsFor } from "@portal/mocks/agents";+import { AgentSelector } from "@portal/components/agent-builder/AgentSelector";++const AGENTS = agentsFor("enterprise");++const meta: Meta<typeof AgentSelector> = {+ title: "Portal/AgentBuilder/AgentSelector",+ component: AgentSelector,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "18rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof AgentSelector>;++export const Default: Story = {+ args: { agents: AGENTS, selectedId: AGENTS[0].id, onSelect: () => {} },+};++/** Clicking a row moves the selection — drives which builder is shown. */+export const Interactive: Story = {+ render: () => {+ const [id, setId] = useState(AGENTS[0].id);+ return <AgentSelector agents={AGENTS} selectedId={id} onSelect={setId} />;+ },+};diff --git a/frontend/portal/src/components/agent-builder/AgentSelector.tsx b/frontend/portal/src/components/agent-builder/AgentSelector.tsxnew file mode 100644index 0000000000..c2128e176b--- /dev/null+++ b/frontend/portal/src/components/agent-builder/AgentSelector.tsx@@ -0,0 +1,44 @@+import { type Agent, AGENT_STATUS_TONE } from "@portal/api/agents";+import { StatusBadge } from "@shared/components";+import "@portal/views/AgentBuilder.css";++interface AgentSelectorProps {+ agents: Agent[];+ selectedId: string | null;+ onSelect: (id: string) => void;+}++/** Left-rail list of agents; the selected row drives which builder is shown. */+export function AgentSelector({+ agents,+ selectedId,+ onSelect,+}: AgentSelectorProps) {+ return (+ <nav className="portal-agents__selector" aria-label="Agents">+ {agents.map((a) => (+ <button+ key={a.id}+ type="button"+ className={+ "portal-agents__selector-item" ++ (a.id === selectedId ? " is-selected" : "")+ }+ aria-current={a.id === selectedId}+ onClick={() => onSelect(a.id)}+ >+ <span className="portal-agents__selector-main">+ <strong className="portal-agents__selector-name">{a.name}</strong>+ <span className="portal-agents__selector-role">{a.role}</span>+ </span>+ <span className="portal-agents__selector-meta">+ <StatusBadge tone={AGENT_STATUS_TONE[a.status]} size="sm">+ {a.status}+ </StatusBadge>+ <code className="portal-agents__selector-version">{a.version}</code>+ </span>+ </button>+ ))}+ </nav>+ );+}diff --git a/frontend/portal/src/components/agent-builder/BootstrapDialog.stories.tsx b/frontend/portal/src/components/agent-builder/BootstrapDialog.stories.tsxnew file mode 100644index 0000000000..8e96e7ac76--- /dev/null+++ b/frontend/portal/src/components/agent-builder/BootstrapDialog.stories.tsx@@ -0,0 +1,30 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { Button } from "@shared/components";+import { BootstrapDialog } from "@portal/components/agent-builder/BootstrapDialog";++const meta: Meta<typeof BootstrapDialog> = {+ title: "Portal/AgentBuilder/BootstrapDialog",+ component: BootstrapDialog,+ parameters: { layout: "fullscreen" },+};+export default meta;+type Story = StoryObj<typeof BootstrapDialog>;++/** Open by default so the dialog is visible in the canvas. */+export const Open: Story = {+ args: { open: true, onClose: () => {} },+};++/** Toggled from a trigger, mirroring how the view drives it. */+export const Triggered: Story = {+ render: () => {+ const [open, setOpen] = useState(false);+ return (+ <div style={{ padding: "1.5rem" }}>+ <Button onClick={() => setOpen(true)}>Bootstrap from document</Button>+ <BootstrapDialog open={open} onClose={() => setOpen(false)} />+ </div>+ );+ },+};diff --git a/frontend/portal/src/components/agent-builder/BootstrapDialog.tsx b/frontend/portal/src/components/agent-builder/BootstrapDialog.tsxnew file mode 100644index 0000000000..8165c14898--- /dev/null+++ b/frontend/portal/src/components/agent-builder/BootstrapDialog.tsx@@ -0,0 +1,70 @@+import { useState } from "react";+import { Button, Modal } from "@shared/components";+import "@portal/views/AgentBuilder.css";++interface BootstrapDialogProps {+ open: boolean;+ onClose: () => void;+}++/**+ * Seed a new agent from a sample document — the user drops one representative+ * file and the backend proposes scenarios and an extraction schema. Demo stub:+ * it captures the chosen file name locally and closes without provisioning.+ */+export function BootstrapDialog({ open, onClose }: BootstrapDialogProps) {+ const [fileName, setFileName] = useState<string | null>(null);++ function close() {+ onClose();+ setTimeout(() => setFileName(null), 200);+ }++ function bootstrap() {+ // TODO(backend): POST /v1/agents/bootstrap (multipart sample document) —+ // infer a starter agent (scenarios + extraction schema) from the file.+ close();+ }++ return (+ <Modal+ open={open}+ onClose={close}+ width="md"+ title="Bootstrap from a document"+ subtitle="Seed a new agent from one representative file"+ footer={+ <div className="portal-agents__dialog-footer">+ <Button variant="ghost" size="sm" onClick={close}>+ Cancel+ </Button>+ <Button size="sm" onClick={bootstrap} disabled={!fileName}>+ Bootstrap agent+ </Button>+ </div>+ }+ >+ <div className="portal-agents__bootstrap">+ <p className="portal-agents__bootstrap-lead">+ Drop a sample document and we'll propose scenarios and an+ extraction schema you can refine. Nothing is published until you+ review it.+ </p>+ <label className="portal-agents__dropzone">+ <input+ type="file"+ accept=".pdf,.png,.jpg,.jpeg,.tiff"+ className="portal-agents__dropzone-input"+ onChange={(e) => setFileName(e.target.files?.[0]?.name ?? null)}+ />+ <span className="portal-agents__dropzone-icon" aria-hidden>+ ⇪+ </span>+ <span className="portal-agents__dropzone-text">+ {fileName ?? "Choose a sample document (PDF or image)"}+ </span>+ </label>+ </div>+ </Modal>+ );+}diff --git a/frontend/portal/src/components/agent-builder/EvalsPanel.stories.tsx b/frontend/portal/src/components/agent-builder/EvalsPanel.stories.tsxnew file mode 100644index 0000000000..39d1676dd1--- /dev/null+++ b/frontend/portal/src/components/agent-builder/EvalsPanel.stories.tsx@@ -0,0 +1,36 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { agentsFor } from "@portal/mocks/agents";+import { EvalsPanel } from "@portal/components/agent-builder/EvalsPanel";++const PRO = agentsFor("pro");+const FREE = agentsFor("free");++const meta: Meta<typeof EvalsPanel> = {+ title: "Portal/AgentBuilder/EvalsPanel",+ component: EvalsPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof EvalsPanel>;++/** High pass-rate agent — bar and pass-rate tile read green. */+export const Passing: Story = {+ args: { agent: PRO[0] },+};++/** KYC draft sits below the green band, so the pass-rate tile warns. */+export const BelowTarget: Story = {+ args: { agent: PRO[2] },+};++/** Free-tier agent has no golden set — the panel shows the upgrade gate. */+export const NoGoldenSet: Story = {+ args: { agent: FREE[0] },+};diff --git a/frontend/portal/src/components/agent-builder/EvalsPanel.tsx b/frontend/portal/src/components/agent-builder/EvalsPanel.tsxnew file mode 100644index 0000000000..58c601accd--- /dev/null+++ b/frontend/portal/src/components/agent-builder/EvalsPanel.tsx@@ -0,0 +1,100 @@+import {+ Button,+ EmptyState,+ ProgressBar,+ StatTile,+ StatusBadge,+ Table,+ type TableColumn,+} from "@shared/components";+import type { Agent, EvalCase } from "@portal/api/agents";+import "@portal/views/AgentBuilder.css";++interface EvalsPanelProps {+ agent: Agent;+}++const COLUMNS: TableColumn<EvalCase>[] = [+ { key: "name", header: "Eval case", render: (c) => c.name },+ {+ key: "result",+ header: "Result",+ render: (c) =>+ c.passing === null ? (+ <span className="portal-agents__muted">not run</span>+ ) : (+ <StatusBadge tone={c.passing ? "success" : "danger"} size="sm">+ {c.passing ? "pass" : "fail"}+ </StatusBadge>+ ),+ },+ {+ key: "latency",+ header: "Latency",+ align: "right",+ render: (c) => (+ <span className="portal-agents__mono">{c.latencyMs} ms</span>+ ),+ },+];++/** Golden-set pass-rate, the per-case results table, and a run affordance. */+export function EvalsPanel({ agent }: EvalsPanelProps) {+ if (agent.evalsTotal === 0) {+ return (+ <div className="portal-agents__panel">+ <EmptyState+ title="No golden set yet"+ description="Evals turn your scenarios into a repeatable golden set. Upgrade to capture pass-rate over time and gate publishes on it."+ size="compact"+ />+ </div>+ );+ }++ const rate = agent.evalsPassing / agent.evalsTotal;++ function runEvals() {+ // TODO(backend): POST /v1/agents/{id}/evals/run — kick off a golden-set+ // run, then poll for the updated case results.+ }++ return (+ <div className="portal-agents__panel">+ <div className="portal-agents__eval-head">+ <div className="portal-agents__stat-grid portal-agents__stat-grid--two">+ <StatTile+ label="Pass rate"+ value={`${Math.round(rate * 100)}%`}+ tone={rate >= 0.95 ? "success" : rate >= 0.8 ? "warning" : "danger"}+ />+ <StatTile+ label="Cases passing"+ value={`${agent.evalsPassing} / ${agent.evalsTotal}`}+ />+ </div>+ <Button size="sm" variant="outline" onClick={runEvals}>+ Run evals+ </Button>+ </div>++ <div className="portal-agents__bar-row">+ <div className="portal-agents__bar-head">+ <span>Golden-set pass rate</span>+ <strong>{Math.round(rate * 100)}%</strong>+ </div>+ <ProgressBar+ value={rate}+ color={rate >= 0.95 ? "var(--color-green)" : "var(--color-amber)"}+ label="Golden-set pass rate"+ />+ </div>++ <Table<EvalCase>+ columns={COLUMNS}+ rows={agent.evalCases}+ rowKey={(c) => c.id}+ />+ </div>+ );+}diff --git a/frontend/portal/src/components/agent-builder/ScenariosPanel.stories.tsx b/frontend/portal/src/components/agent-builder/ScenariosPanel.stories.tsxnew file mode 100644index 0000000000..8ae91e390a--- /dev/null+++ b/frontend/portal/src/components/agent-builder/ScenariosPanel.stories.tsx@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { agentsFor } from "@portal/mocks/agents";+import { ScenariosPanel } from "@portal/components/agent-builder/ScenariosPanel";++const AGENTS = agentsFor("pro");++const meta: Meta<typeof ScenariosPanel> = {+ title: "Portal/AgentBuilder/ScenariosPanel",+ component: ScenariosPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ScenariosPanel>;++/** Contract Router ships three scenarios; the add-row stages a fourth locally. */+export const Default: Story = {+ args: { agent: AGENTS[0] },+};++/** An agent with a muted scenario (excluded from the eval run). */+export const WithMutedScenario: Story = {+ args: { agent: AGENTS[1] },+};diff --git a/frontend/portal/src/components/agent-builder/ScenariosPanel.tsx b/frontend/portal/src/components/agent-builder/ScenariosPanel.tsxnew file mode 100644index 0000000000..84ef11ecb2--- /dev/null+++ b/frontend/portal/src/components/agent-builder/ScenariosPanel.tsx@@ -0,0 +1,108 @@+import { useState } from "react";+import {+ Button,+ Chip,+ FormField,+ Input,+ StatusBadge,+} from "@shared/components";+import type { Agent, Scenario } from "@portal/api/agents";+import "@portal/views/AgentBuilder.css";++interface ScenariosPanelProps {+ agent: Agent;+}++/**+ * Named test cases describing expected behaviour. Edits live in local state —+ * the surface is mock-driven, so adding a row only stages it client-side until+ * the submit endpoint exists.+ */+export function ScenariosPanel({ agent }: ScenariosPanelProps) {+ // Seed from the agent and re-seed when the selection changes (key prop on the+ // builder forces a remount, so a plain useState initialiser is enough).+ const [scenarios, setScenarios] = useState<Scenario[]>(agent.scenarios);+ const [name, setName] = useState("");+ const [expectation, setExpectation] = useState("");++ const canAdd = name.trim() !== "" && expectation.trim() !== "";++ function addScenario() {+ if (!canAdd) return;+ const next: Scenario = {+ id: `sc-local-${Date.now()}`,+ name: name.trim(),+ expectation: expectation.trim(),+ enabled: true,+ };+ // TODO(backend): POST /v1/agents/{id}/scenarios { name, expectation } —+ // persist the scenario, then replace the optimistic row with the response.+ setScenarios((cur) => [...cur, next]);+ setName("");+ setExpectation("");+ }++ function toggleEnabled(id: string) {+ setScenarios((cur) =>+ cur.map((s) => (s.id === id ? { ...s, enabled: !s.enabled } : s)),+ );+ }++ return (+ <div className="portal-agents__panel">+ <ul className="portal-agents__scenarios">+ {scenarios.map((s) => (+ <li key={s.id} className="portal-agents__scenario">+ <div className="portal-agents__scenario-text">+ <div className="portal-agents__scenario-head">+ <strong>{s.name}</strong>+ <StatusBadge+ tone={s.enabled ? "success" : "neutral"}+ size="sm"+ showDot={false}+ >+ {s.enabled ? "in eval" : "muted"}+ </StatusBadge>+ </div>+ <span className="portal-agents__scenario-expect">+ {s.expectation}+ </span>+ </div>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => toggleEnabled(s.id)}+ >+ {s.enabled ? "Mute" : "Enable"}+ </Button>+ </li>+ ))}+ </ul>++ <div className="portal-agents__scenario-add">+ <Chip tone="blue" size="sm">+ Add scenario+ </Chip>+ <div className="portal-agents__scenario-form">+ <FormField label="Name">+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="e.g. Compliance escalation"+ />+ </FormField>+ <FormField label="Expected behaviour">+ <Input+ value={expectation}+ onChange={(e) => setExpectation(e.target.value)}+ placeholder="What the agent should do"+ />+ </FormField>+ <Button size="sm" onClick={addScenario} disabled={!canAdd}>+ Add+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/agent-builder/ToolsPanel.stories.tsx b/frontend/portal/src/components/agent-builder/ToolsPanel.stories.tsxnew file mode 100644index 0000000000..ed0de96ff9--- /dev/null+++ b/frontend/portal/src/components/agent-builder/ToolsPanel.stories.tsx@@ -0,0 +1,35 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { agentsFor } from "@portal/mocks/agents";+import { ToolsPanel } from "@portal/components/agent-builder/ToolsPanel";++const AGENTS = agentsFor("enterprise");++const meta: Meta<typeof ToolsPanel> = {+ title: "Portal/AgentBuilder/ToolsPanel",+ component: ToolsPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ToolsPanel>;++/** Restricted mode with a deny list — the enterprise governance posture. */+export const Restricted: Story = {+ args: { agent: AGENTS[0], governanceUnlocked: true },+};++/** Broad access — every tool callable. */+export const Broad: Story = {+ args: { agent: AGENTS[1], governanceUnlocked: true },+};++/** Governance locked: the toggle is disabled and explains the upgrade. */+export const GovernanceLocked: Story = {+ args: { agent: AGENTS[0], governanceUnlocked: false },+};diff --git a/frontend/portal/src/components/agent-builder/ToolsPanel.tsx b/frontend/portal/src/components/agent-builder/ToolsPanel.tsxnew file mode 100644index 0000000000..c53faa2a60--- /dev/null+++ b/frontend/portal/src/components/agent-builder/ToolsPanel.tsx@@ -0,0 +1,81 @@+import { useState } from "react";+import { Chip, ToggleSwitch } from "@shared/components";+import { type Agent, type ToolMode, TOOL_CATALOGUE } from "@portal/api/agents";+import "@portal/views/AgentBuilder.css";++interface ToolsPanelProps {+ agent: Agent;+ /** Restricted-tools governance is an enterprise capability. */+ governanceUnlocked: boolean;+}++/**+ * Tool-access posture. `broad` grants every tool; `restricted` is allow-by-+ * default minus an explicit deny list, picked from the known tool catalogue.+ */+export function ToolsPanel({ agent, governanceUnlocked }: ToolsPanelProps) {+ const [mode, setMode] = useState<ToolMode>(agent.toolMode);+ const [denied, setDenied] = useState<string[]>(agent.deniedTools);++ function setRestricted(on: boolean) {+ // TODO(backend): PATCH /v1/agents/{id}/tools { mode, deniedTools } —+ // persist the access posture.+ setMode(on ? "restricted" : "broad");+ }++ function toggleDenied(tool: string) {+ setDenied((cur) =>+ cur.includes(tool) ? cur.filter((t) => t !== tool) : [...cur, tool],+ );+ }++ const restricted = mode === "restricted";++ return (+ <div className="portal-agents__panel">+ <div className="portal-agents__tool-mode">+ <ToggleSwitch+ checked={restricted}+ onChange={setRestricted}+ disabled={!governanceUnlocked}+ label="Restricted tool access"+ description={+ governanceUnlocked+ ? "Allow every tool except the ones you deny below."+ : "Tool governance is available on the Enterprise plan."+ }+ />+ <Chip tone={restricted ? "amber" : "green"} size="sm">+ {restricted ? "Restricted" : "Broad access"}+ </Chip>+ </div>++ {restricted && (+ <div className="portal-agents__detail-section">+ <span className="portal-agents__detail-heading">Denied tools</span>+ <p className="portal-agents__hint">+ Selected tools are blocked. Everything else stays callable.+ </p>+ <div className="portal-agents__chips">+ {TOOL_CATALOGUE.map((tool) => {+ const isDenied = denied.includes(tool);+ return (+ <Chip+ key={tool}+ tone={isDenied ? "red" : "neutral"}+ size="sm"+ onClick={+ governanceUnlocked ? () => toggleDenied(tool) : undefined+ }+ >+ {isDenied ? "✕ " : ""}+ {tool}+ </Chip>+ );+ })}+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/frontend/portal/src/components/agent-builder/VersionsPanel.stories.tsx b/frontend/portal/src/components/agent-builder/VersionsPanel.stories.tsxnew file mode 100644index 0000000000..d15fdac6e0--- /dev/null+++ b/frontend/portal/src/components/agent-builder/VersionsPanel.stories.tsx@@ -0,0 +1,35 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { agentsFor } from "@portal/mocks/agents";+import { VersionsPanel } from "@portal/components/agent-builder/VersionsPanel";++const PRO = agentsFor("pro");++const meta: Meta<typeof VersionsPanel> = {+ title: "Portal/AgentBuilder/VersionsPanel",+ component: VersionsPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof VersionsPanel>;++/** Full history with rollback on prior published versions. */+export const FullHistory: Story = {+ args: { agent: PRO[0], historyUnlocked: true },+};++/** A draft current version offers a publish action. */+export const DraftAwaitingPublish: Story = {+ args: { agent: PRO[2], historyUnlocked: true },+};++/** History locked: only the current version shows, with an upgrade hint. */+export const HistoryLocked: Story = {+ args: { agent: PRO[0], historyUnlocked: false },+};diff --git a/frontend/portal/src/components/agent-builder/VersionsPanel.tsx b/frontend/portal/src/components/agent-builder/VersionsPanel.tsxnew file mode 100644index 0000000000..4a9bc5377a--- /dev/null+++ b/frontend/portal/src/components/agent-builder/VersionsPanel.tsx@@ -0,0 +1,99 @@+import { Button, StatusBadge } from "@shared/components";+import { type Agent, AGENT_STATUS_TONE } from "@portal/api/agents";+import "@portal/views/AgentBuilder.css";++interface VersionsPanelProps {+ agent: Agent;+ /** Deep version history is an enterprise capability; lower tiers see the gate. */+ historyUnlocked: boolean;+}++/** Render an ISO timestamp as a short, locale-stable date. */+function formatDate(iso: string): string {+ return new Date(iso).toLocaleDateString(undefined, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}++/** Version history with publish / rollback actions per row. */+export function VersionsPanel({ agent, historyUnlocked }: VersionsPanelProps) {+ // Without governance, only the current version is meaningful to show.+ const versions = historyUnlocked+ ? agent.versions+ : agent.versions.slice(0, 1);+ const publishedExists = agent.versions.some((v) => v.status === "published");++ function publish(version: string) {+ void version;+ // TODO(backend): POST /v1/agents/{id}/versions/{v}/publish — promote the+ // draft to published and demote the previous published version.+ }++ function rollback(version: string) {+ void version;+ // TODO(backend): POST /v1/agents/{id}/versions/{v}/rollback — re-publish a+ // prior version as the active one.+ }++ return (+ <div className="portal-agents__panel">+ <ol className="portal-agents__versions">+ {versions.map((v) => {+ const isCurrent = v.version === agent.version;+ return (+ <li key={v.version} className="portal-agents__version">+ <div className="portal-agents__version-main">+ <div className="portal-agents__version-head">+ <code className="portal-agents__version-tag">+ {v.version}+ </code>+ <StatusBadge tone={AGENT_STATUS_TONE[v.status]} size="sm">+ {v.status}+ </StatusBadge>+ {isCurrent && (+ <StatusBadge tone="info" size="sm" showDot={false}>+ current+ </StatusBadge>+ )}+ </div>+ <span className="portal-agents__version-note">{v.note}</span>+ <span className="portal-agents__version-meta">+ {formatDate(v.createdAt)} · {v.author}+ </span>+ </div>+ <div className="portal-agents__version-actions">+ {v.status === "draft" && (+ <Button+ size="sm"+ variant="outline"+ onClick={() => publish(v.version)}+ >+ Publish+ </Button>+ )}+ {v.status === "published" && !isCurrent && (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => rollback(v.version)}+ >+ Roll back+ </Button>+ )}+ </div>+ </li>+ );+ })}+ </ol>++ {!historyUnlocked && publishedExists && (+ <p className="portal-agents__hint">+ Full version history and rollback are available on the Enterprise+ plan.+ </p>+ )}+ </div>+ );+}diff --git a/frontend/portal/src/components/catalogue/ComponentCard.stories.tsx b/frontend/portal/src/components/catalogue/ComponentCard.stories.tsxnew file mode 100644index 0000000000..0b6c284d93--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentCard.stories.tsx@@ -0,0 +1,27 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { componentsFor } from "@portal/mocks/sdkComponents";+import { ComponentCard } from "@portal/components/catalogue/ComponentCard";++const PRO = componentsFor("pro");+const GA = PRO.find((c) => c.maturity === "ga")!;+const BETA = PRO.find((c) => c.maturity === "beta")!;++const meta: Meta<typeof ComponentCard> = {+ title: "Portal/Components/ComponentCard",+ component: ComponentCard,+ parameters: { layout: "padded" },+ args: { component: GA, unlocked: true, onOpen: () => {} },+};+export default meta;+type Story = StoryObj<typeof ComponentCard>;++export const GeneralAvailability: Story = {};++export const Beta: Story = {+ args: { component: BETA },+};++/** Sits above the tier — dimmed with a lock affordance. */+export const Locked: Story = {+ args: { component: BETA, unlocked: false },+};diff --git a/frontend/portal/src/components/catalogue/ComponentCard.tsx b/frontend/portal/src/components/catalogue/ComponentCard.tsxnew file mode 100644index 0000000000..6b2c46d8ab--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentCard.tsx@@ -0,0 +1,72 @@+import { Card, Chip, StatusBadge } from "@shared/components";+import {+ type SdkComponent,+ MATURITY_META,+ formatPrice,+} from "@portal/api/sdkComponents";+import "@portal/views/Components.css";++interface ComponentCardProps {+ component: SdkComponent;+ /** False when the component sits above the active tier — renders locked. */+ unlocked: boolean;+ onOpen: (component: SdkComponent) => void;+}++/** A single catalogue tile: name, maturity, description, price and frameworks. */+export function ComponentCard({+ component,+ unlocked,+ onOpen,+}: ComponentCardProps) {+ const maturity = MATURITY_META[component.maturity];++ return (+ <Card+ interactive+ padding="default"+ className={"portal-components__card" + (unlocked ? "" : " is-locked")}+ role="button"+ tabIndex={0}+ aria-label={`Open ${component.name} component`}+ onClick={() => onOpen(component)}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onOpen(component);+ }+ }}+ >+ <div className="portal-components__card-head">+ <h3 className="portal-components__card-name">{component.name}</h3>+ <StatusBadge tone={maturity.tone} size="sm" showDot={false}>+ {maturity.label}+ </StatusBadge>+ {!unlocked && (+ <span className="portal-components__lock" aria-label="Locked">+ 🔒+ </span>+ )}+ </div>++ <p className="portal-components__card-desc">{component.description}</p>++ <div className="portal-components__card-meta">+ <span className="portal-components__price">+ {formatPrice(component.pricing)}+ </span>+ <span className="portal-components__pkg">+ @stirling/{component.package}+ </span>+ </div>++ <div className="portal-components__frameworks">+ {component.frameworks.map((fw) => (+ <Chip key={fw} size="sm" tone="neutral">+ {fw}+ </Chip>+ ))}+ </div>+ </Card>+ );+}diff --git a/frontend/portal/src/components/catalogue/ComponentDetailModal.stories.tsx b/frontend/portal/src/components/catalogue/ComponentDetailModal.stories.tsxnew file mode 100644index 0000000000..7a8be30dde--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentDetailModal.stories.tsx@@ -0,0 +1,27 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { componentsFor } from "@portal/mocks/sdkComponents";+import { ComponentDetailModal } from "@portal/components/catalogue/ComponentDetailModal";++const PRO = componentsFor("pro");+const VIEWER = PRO.find((c) => c.id === "viewer")!;+const TOOLKIT = PRO.find((c) => c.id === "toolkit")!;++const meta: Meta<typeof ComponentDetailModal> = {+ title: "Portal/Components/ComponentDetailModal",+ component: ComponentDetailModal,+ parameters: { layout: "fullscreen" },+ args: { component: VIEWER, unlocked: true, onClose: () => {} },+};+export default meta;+type Story = StoryObj<typeof ComponentDetailModal>;++export const Unlocked: Story = {};++/** Enterprise-only component opened on a lower tier — shows the upgrade nudge. */+export const Locked: Story = {+ args: { component: TOOLKIT, unlocked: false },+};++export const Closed: Story = {+ args: { component: null },+};diff --git a/frontend/portal/src/components/catalogue/ComponentDetailModal.tsx b/frontend/portal/src/components/catalogue/ComponentDetailModal.tsxnew file mode 100644index 0000000000..d9f8627a38--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentDetailModal.tsx@@ -0,0 +1,203 @@+import { useState } from "react";+import {+ Banner,+ Button,+ Chip,+ CodeBlock,+ Modal,+ StatTile,+ StatusBadge,+ Tabs,+} from "@shared/components";+import {+ type SdkComponent,+ MATURITY_META,+ formatPrice,+} from "@portal/api/sdkComponents";+import { ComponentPropsTable } from "@portal/components/catalogue/ComponentPropsTable";+import "@portal/views/Components.css";++type DetailTab = "overview" | "code" | "props" | "pricing";++const TABS: { key: DetailTab; label: string }[] = [+ { key: "overview", label: "Overview" },+ { key: "code", label: "Code" },+ { key: "props", label: "Props / API" },+ { key: "pricing", label: "Pricing" },+];++interface ComponentDetailModalProps {+ component: SdkComponent | null;+ /** False when the open component sits above the active tier. */+ unlocked: boolean;+ onClose: () => void;+}++/**+ * Detail overlay for a catalogue component: a live-preview placeholder plus+ * Overview / Code / Props / Pricing tabs. Locked components swap the install+ * CTA for an upgrade nudge.+ */+export function ComponentDetailModal({+ component,+ unlocked,+ onClose,+}: ComponentDetailModalProps) {+ const [tab, setTab] = useState<DetailTab>("overview");++ // Reset to the first tab whenever a new component is opened.+ const open = component !== null;+ if (!component) {+ return (+ <Modal open={false} onClose={onClose} ariaLabel="Component detail" />+ );+ }++ const maturity = MATURITY_META[component.maturity];+ const npm = `@stirling/${component.package}`;++ return (+ <Modal+ key={component.id}+ open={open}+ onClose={() => {+ onClose();+ setTab("overview");+ }}+ width="xl"+ title={+ <span className="portal-components__modal-title">+ {component.name}+ <StatusBadge tone={maturity.tone} size="sm" showDot={false}>+ {maturity.label}+ </StatusBadge>+ </span>+ }+ subtitle={npm}+ footer={+ unlocked ? (+ <div className="portal-components__modal-footer">+ <span className="portal-components__price">+ {formatPrice(component.pricing)}+ </span>+ <Button+ size="sm"+ // TODO(backend): open the package quickstart / provision a+ // publishable key scoped to this component.+ onClick={() => onClose()}+ >+ Add to project+ </Button>+ </div>+ ) : (+ <Button+ size="sm"+ accent="purple"+ // TODO(backend): route to the upgrade / contact-sales flow.+ onClick={() => onClose()}+ >+ Upgrade to unlock+ </Button>+ )+ }+ >+ {!unlocked && (+ <Banner+ tone="warning"+ title="Not available on your plan"+ description={`${component.name} is included from the ${component.minTier} plan. Upgrade to embed it.`}+ />+ )}++ {/* Live-preview sandbox — a styled placeholder until a real host mounts. */}+ <div className="portal-components__preview" aria-hidden>+ {/* TODO(backend)/host: mount the live <Sandbox> here, booting the+ component against a demo document and the dev's publishable key. */}+ <span className="portal-components__preview-badge">Live preview</span>+ <span className="portal-components__preview-note">+ Interactive sandbox renders here+ </span>+ </div>++ <Tabs<DetailTab>+ className="portal-components__tabs"+ items={TABS}+ activeKey={tab}+ onChange={setTab}+ variant="underline"+ ariaLabel="Component detail sections"+ />++ <div className="portal-components__tab-body">+ {tab === "overview" && (+ <div className="portal-components__overview">+ <p className="portal-components__overview-desc">+ {component.description}+ </p>+ <div className="portal-components__frameworks">+ {component.frameworks.map((fw) => (+ <Chip key={fw} size="sm" tone="blue">+ {fw}+ </Chip>+ ))}+ </div>+ <div className="portal-components__stat-grid">+ <StatTile label="Maturity" value={maturity.label} />+ <StatTile label="Price" value={formatPrice(component.pricing)} />+ <StatTile+ label="Free quota"+ value={+ component.pricing.freeQuota > 0+ ? `${component.pricing.freeQuota.toLocaleString()} / mo`+ : "None"+ }+ />+ <StatTile+ label="Embeds (30d)"+ value={component.embeds30d.toLocaleString()}+ />+ </div>+ </div>+ )}++ {tab === "code" && (+ <div className="portal-components__code">+ <CodeBlock code={component.install} lang="bash" caption="Install" />+ <CodeBlock+ code={component.usage}+ lang="typescript"+ caption="Usage"+ />+ </div>+ )}++ {tab === "props" && <ComponentPropsTable props={component.props} />}++ {tab === "pricing" && (+ <div className="portal-components__pricing">+ <div className="portal-components__stat-grid">+ <StatTile+ label="Per action"+ value={formatPrice(component.pricing)}+ />+ <StatTile label="Billed on" value={component.pricing.unit} />+ <StatTile+ label="Free quota"+ value={+ component.pricing.freeQuota > 0+ ? `${component.pricing.freeQuota.toLocaleString()} / mo`+ : "None"+ }+ />+ </div>+ <p className="portal-components__pricing-note">+ Metered per {component.pricing.unit}. Usage beyond the monthly+ free quota is billed to your account and itemised under Usage+ & Billing.+ </p>+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/frontend/portal/src/components/catalogue/ComponentGrid.stories.tsx b/frontend/portal/src/components/catalogue/ComponentGrid.stories.tsxnew file mode 100644index 0000000000..b11c302b60--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentGrid.stories.tsx@@ -0,0 +1,24 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { componentsFor } from "@portal/mocks/sdkComponents";+import { ComponentGrid } from "@portal/components/catalogue/ComponentGrid";++const meta: Meta<typeof ComponentGrid> = {+ title: "Portal/Components/ComponentGrid",+ component: ComponentGrid,+ parameters: { layout: "padded" },+ args: { components: componentsFor("pro"), tier: "pro", onOpen: () => {} },+};+export default meta;+type Story = StoryObj<typeof ComponentGrid>;++export const Pro: Story = {};++/** Free locks every paid component — the whole grid shows upgrade nudges. */+export const Free: Story = {+ args: { components: componentsFor("free"), tier: "free" },+};++/** Enterprise unlocks the enterprise-only Beta components. */+export const Enterprise: Story = {+ args: { components: componentsFor("enterprise"), tier: "enterprise" },+};diff --git a/frontend/portal/src/components/catalogue/ComponentGrid.tsx b/frontend/portal/src/components/catalogue/ComponentGrid.tsxnew file mode 100644index 0000000000..140f71c07f--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentGrid.tsx@@ -0,0 +1,30 @@+import { type SdkComponent, isUnlocked } from "@portal/api/sdkComponents";+import type { Tier } from "@portal/contexts/TierContext";+import { ComponentCard } from "@portal/components/catalogue/ComponentCard";+import "@portal/views/Components.css";++interface ComponentGridProps {+ components: SdkComponent[];+ tier: Tier;+ onOpen: (component: SdkComponent) => void;+}++/** Responsive grid of catalogue cards; locks components above the tier. */+export function ComponentGrid({+ components,+ tier,+ onOpen,+}: ComponentGridProps) {+ return (+ <div className="portal-components__grid">+ {components.map((c) => (+ <ComponentCard+ key={c.id}+ component={c}+ unlocked={isUnlocked(c, tier)}+ onOpen={onOpen}+ />+ ))}+ </div>+ );+}diff --git a/frontend/portal/src/components/catalogue/ComponentPropsTable.stories.tsx b/frontend/portal/src/components/catalogue/ComponentPropsTable.stories.tsxnew file mode 100644index 0000000000..7ac11e6593--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentPropsTable.stories.tsx@@ -0,0 +1,16 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { componentsFor } from "@portal/mocks/sdkComponents";+import { ComponentPropsTable } from "@portal/components/catalogue/ComponentPropsTable";++const VIEWER = componentsFor("pro").find((c) => c.id === "viewer")!;++const meta: Meta<typeof ComponentPropsTable> = {+ title: "Portal/Components/ComponentPropsTable",+ component: ComponentPropsTable,+ parameters: { layout: "padded" },+ args: { props: VIEWER.props },+};+export default meta;+type Story = StoryObj<typeof ComponentPropsTable>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/catalogue/ComponentPropsTable.tsx b/frontend/portal/src/components/catalogue/ComponentPropsTable.tsxnew file mode 100644index 0000000000..03f8e46925--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentPropsTable.tsx@@ -0,0 +1,58 @@+import { useMemo } from "react";+import { Chip, Table, type TableColumn } from "@shared/components";+import type { ComponentProp } from "@portal/api/sdkComponents";+import "@portal/views/Components.css";++interface ComponentPropsTableProps {+ props: ComponentProp[];+}++/** Small Props/API reference shown under the detail modal's Props tab. */+export function ComponentPropsTable({ props: rows }: ComponentPropsTableProps) {+ const columns = useMemo<TableColumn<ComponentProp>[]>(+ () => [+ {+ key: "name",+ header: "Prop",+ render: (p) => (+ <span className="portal-components__prop-name">{p.name}</span>+ ),+ },+ {+ key: "type",+ header: "Type",+ render: (p) => (+ <code className="portal-components__prop-type">{p.type}</code>+ ),+ },+ {+ key: "required",+ header: "Required",+ render: (p) =>+ p.required ? (+ <Chip size="sm" tone="amber">+ required+ </Chip>+ ) : (+ <span className="portal-components__muted">optional</span>+ ),+ },+ {+ key: "description",+ header: "Description",+ render: (p) => (+ <span className="portal-components__prop-desc">{p.description}</span>+ ),+ },+ ],+ [],+ );++ return (+ <Table<ComponentProp>+ columns={columns}+ rows={rows}+ rowKey={(p) => p.name}+ />+ );+}diff --git a/frontend/portal/src/components/catalogue/ComponentsSummaryStrip.tsx b/frontend/portal/src/components/catalogue/ComponentsSummaryStrip.tsxnew file mode 100644index 0000000000..8cad2c51ae--- /dev/null+++ b/frontend/portal/src/components/catalogue/ComponentsSummaryStrip.tsx@@ -0,0 +1,40 @@+import { MetricCard, MetricStrip } from "@shared/components";+import type { ComponentsResponse } from "@portal/api/sdkComponents";++/**+ * Labels are product copy — they describe what each metric IS, not its value,+ * so the strip's structure stays stable across loading / empty / ready states.+ * Only values flow from the API.+ */+const KPI_LABELS = [+ "Components GA",+ "In beta",+ "Embeds this month",+ "Component spend (MTD)",+] as const;++interface ComponentsSummaryStripProps {+ data: ComponentsResponse | null;+ loading: boolean;+}++export function ComponentsSummaryStrip({+ data,+ loading,+}: ComponentsSummaryStripProps) {+ const s = loading ? undefined : data?.summary;+ const values: (string | number)[] = [+ s?.gaCount ?? "—",+ s?.betaCount ?? "—",+ s ? s.embedsThisMonth.toLocaleString() : "—",+ s ? `$${s.spendThisMonth.toLocaleString()}` : "—",+ ];++ return (+ <MetricStrip>+ {KPI_LABELS.map((label, i) => (+ <MetricCard key={label} label={label} value={values[i]} />+ ))}+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/documents/DocumentAudit.stories.tsx b/frontend/portal/src/components/documents/DocumentAudit.stories.tsxnew file mode 100644index 0000000000..204b1d1e61--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentAudit.stories.tsx@@ -0,0 +1,29 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { documentsFor } from "@portal/mocks/documents";+import { DocumentAudit } from "@portal/components/documents/DocumentAudit";+import "@portal/views/Documents.css";++const DOC = documentsFor("pro")[0];++const meta: Meta<typeof DocumentAudit> = {+ title: "Portal/Documents/DocumentAudit",+ component: DocumentAudit,+ parameters: { layout: "padded" },+ args: { doc: DOC },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "36rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DocumentAudit>;++export const Default: Story = {};++/** A document whose lifecycle reached approval. */+export const Approved: Story = {+ args: { doc: documentsFor("pro").find((d) => d.status === "processed")! },+};diff --git a/frontend/portal/src/components/documents/DocumentAudit.tsx b/frontend/portal/src/components/documents/DocumentAudit.tsxnew file mode 100644index 0000000000..1d5949ec2b--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentAudit.tsx@@ -0,0 +1,36 @@+import { StatusBadge } from "@shared/components";+import {+ DOC_AUDIT_LABEL,+ DOC_AUDIT_TONE,+ type ReviewDocument,+} from "@portal/api/documents";++/** Lifecycle timeline for a single document, oldest first. */+export function DocumentAudit({ doc }: { doc: ReviewDocument }) {+ if (doc.audit.length === 0) {+ return <p className="portal-documents__muted">No events recorded yet.</p>;+ }+ return (+ <ol className="portal-documents__timeline">+ {doc.audit.map((event) => (+ <li key={event.id} className="portal-documents__timeline-item">+ <span className="portal-documents__timeline-dot" aria-hidden />+ <div className="portal-documents__timeline-body">+ <div className="portal-documents__timeline-head">+ <StatusBadge tone={DOC_AUDIT_TONE[event.kind]} size="sm">+ {DOC_AUDIT_LABEL[event.kind]}+ </StatusBadge>+ <span className="portal-documents__timeline-time">+ {event.time}+ </span>+ </div>+ <p className="portal-documents__timeline-detail">{event.detail}</p>+ <span className="portal-documents__timeline-actor">+ {event.actor}+ </span>+ </div>+ </li>+ ))}+ </ol>+ );+}diff --git a/frontend/portal/src/components/documents/DocumentDrawer.stories.tsx b/frontend/portal/src/components/documents/DocumentDrawer.stories.tsxnew file mode 100644index 0000000000..41d5382dea--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentDrawer.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { documentsFor } from "@portal/mocks/documents";+import { DocumentDrawer } from "@portal/components/documents/DocumentDrawer";+import "@portal/views/Documents.css";++const ALL = documentsFor("enterprise");+const NON_SENSITIVE = ALL.find((d) => !d.sensitive)!;+const SENSITIVE = ALL.find((d) => d.sensitive)!;++const meta: Meta<typeof DocumentDrawer> = {+ title: "Portal/Documents/DocumentDrawer",+ component: DocumentDrawer,+ parameters: { layout: "fullscreen" },+ args: { onClose: () => {} },+};+export default meta;+type Story = StoryObj<typeof DocumentDrawer>;++/** Standard document — all sub-tabs visible, content shown. */+export const Default: Story = {+ args: { doc: NON_SENSITIVE },+};++/**+ * Sensitive document — opens with the zero-standing-access banner; the+ * Extractions tab stays masked until access is requested. On the enterprise+ * tier the banner carries the four-eyes note.+ */+export const Sensitive: Story = {+ args: { doc: SENSITIVE },+};diff --git a/frontend/portal/src/components/documents/DocumentDrawer.tsx b/frontend/portal/src/components/documents/DocumentDrawer.tsxnew file mode 100644index 0000000000..195b97c258--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentDrawer.tsx@@ -0,0 +1,112 @@+import { useEffect, useState } from "react";+import { Drawer, StatusBadge, Tabs, type TabItem } from "@shared/components";+import {+ DOCUMENT_STATUS_LABEL,+ DOCUMENT_STATUS_TONE,+ type ReviewDocument,+} from "@portal/api/documents";+import { useTier } from "@portal/contexts/TierContext";+import { ELEVATION_WINDOW_SECONDS } from "@portal/components/documents/format";+import { DocumentOverview } from "@portal/components/documents/DocumentOverview";+import { DocumentExtractions } from "@portal/components/documents/DocumentExtractions";+import { DocumentAudit } from "@portal/components/documents/DocumentAudit";+import { ElevationBanner } from "@portal/components/documents/ElevationBanner";++type SubTab = "overview" | "extractions" | "audit";++const SUB_TABS: TabItem<SubTab>[] = [+ { key: "overview", label: "Overview" },+ { key: "extractions", label: "Extractions" },+ { key: "audit", label: "Audit" },+];++interface DocumentDrawerProps {+ /** Selected document, or null when the drawer is closed. */+ doc: ReviewDocument | null;+ onClose: () => void;+}++/**+ * Detail panel for a queued document. Sub-tabs split overview, extracted+ * fields, and the audit timeline. Sensitive documents gate their content+ * behind a client-side timed elevation; enterprise adds a four-eyes note.+ */+export function DocumentDrawer({ doc, onClose }: DocumentDrawerProps) {+ const { tier } = useTier();+ const fourEyes = tier === "enterprise";++ const [tab, setTab] = useState<SubTab>("overview");+ // Seconds remaining on the active elevation grant; null means no grant.+ const [secondsLeft, setSecondsLeft] = useState<number | null>(null);++ // Reset tab and any active grant whenever a different document opens — a+ // grant is scoped to the document it was requested for.+ useEffect(() => {+ setTab("overview");+ setSecondsLeft(null);+ }, [doc?.id]);++ // Tick the countdown down to expiry, then drop the grant.+ useEffect(() => {+ if (secondsLeft === null) return;+ if (secondsLeft <= 0) {+ setSecondsLeft(null);+ return;+ }+ const timer = setTimeout(() => setSecondsLeft((s) => (s ?? 1) - 1), 1000);+ return () => clearTimeout(timer);+ }, [secondsLeft]);++ if (!doc) return null;++ function requestAccess() {+ // TODO(backend): POST /v1/documents/{id}/elevation — request a time-boxed+ // grant (and, on enterprise, trigger the four-eyes peer notification).+ // The grant + countdown are simulated client-side until that exists.+ setSecondsLeft(ELEVATION_WINDOW_SECONDS);+ }++ const unlocked = secondsLeft !== null;++ return (+ <Drawer+ open+ onClose={onClose}+ width="lg"+ title={doc.name}+ subtitle={`${doc.type} · ${doc.source}`}+ >+ <div className="portal-documents__drawer">+ <div className="portal-documents__drawer-status">+ <StatusBadge tone={DOCUMENT_STATUS_TONE[doc.status]} size="sm">+ {DOCUMENT_STATUS_LABEL[doc.status]}+ </StatusBadge>+ </div>++ {doc.sensitive && (+ <ElevationBanner+ secondsLeft={secondsLeft}+ fourEyes={fourEyes}+ onRequest={requestAccess}+ />+ )}++ <Tabs<SubTab>+ items={SUB_TABS}+ activeKey={tab}+ onChange={setTab}+ variant="underline"+ ariaLabel="Document detail sections"+ />++ <div className="portal-documents__drawer-panel">+ {tab === "overview" && <DocumentOverview doc={doc} />}+ {tab === "extractions" && (+ <DocumentExtractions doc={doc} unlocked={unlocked} />+ )}+ {tab === "audit" && <DocumentAudit doc={doc} />}+ </div>+ </div>+ </Drawer>+ );+}diff --git a/frontend/portal/src/components/documents/DocumentExtractions.stories.tsx b/frontend/portal/src/components/documents/DocumentExtractions.stories.tsxnew file mode 100644index 0000000000..a729289915--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentExtractions.stories.tsx@@ -0,0 +1,45 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { documentsFor } from "@portal/mocks/documents";+import { DocumentExtractions } from "@portal/components/documents/DocumentExtractions";+import "@portal/views/Documents.css";++const ALL = documentsFor("enterprise");+const NON_SENSITIVE = ALL.find((d) => !d.sensitive)!;+const SENSITIVE = ALL.find((d) => d.sensitive)!;+const NO_AMOUNT = ALL.find((d) =>+ d.extractions.some((e) => e.confidence === 0),+)!;++const meta: Meta<typeof DocumentExtractions> = {+ title: "Portal/Documents/DocumentExtractions",+ component: DocumentExtractions,+ parameters: { layout: "padded" },+ args: { doc: NON_SENSITIVE, unlocked: false },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "36rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DocumentExtractions>;++/** Per-field table with mixed confidence tones. */+export const Default: Story = {};++/** A field that failed to extract sits at 0% confidence. */+export const LowConfidence: Story = {+ args: { doc: NO_AMOUNT },+};++/** Sensitive doc with no active grant — content stays masked. */+export const Masked: Story = {+ args: { doc: SENSITIVE, unlocked: false },+};++/** Same sensitive doc once a timed elevation is active. */+export const Unlocked: Story = {+ args: { doc: SENSITIVE, unlocked: true },+};diff --git a/frontend/portal/src/components/documents/DocumentExtractions.tsx b/frontend/portal/src/components/documents/DocumentExtractions.tsxnew file mode 100644index 0000000000..a990113af9--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentExtractions.tsx@@ -0,0 +1,73 @@+import { StatusBadge, Table, type TableColumn } from "@shared/components";+import { type Extraction, type ReviewDocument } from "@portal/api/documents";+import {+ confidencePct,+ confidenceTone,+} from "@portal/components/documents/format";++const cols: TableColumn<Extraction>[] = [+ {+ key: "field",+ header: "Field",+ render: (e) => <span className="portal-documents__field">{e.field}</span>,+ },+ {+ key: "value",+ header: "Value",+ render: (e) => <span className="portal-documents__mono">{e.value}</span>,+ },+ {+ key: "confidence",+ header: "Confidence",+ align: "right",+ width: "7rem",+ render: (e) => (+ <StatusBadge+ tone={confidenceTone(e.confidence)}+ size="sm"+ showDot={false}+ >+ {confidencePct(e.confidence)}+ </StatusBadge>+ ),+ },+];++interface DocumentExtractionsProps {+ doc: ReviewDocument;+ /**+ * Whether sensitive content may be shown. A sensitive doc renders its fields+ * only once a timed elevation is active; the gate UI itself lives in the+ * drawer so it can sit above all sub-tabs.+ */+ unlocked: boolean;+}++/** Per-field extraction table, gated behind elevation for sensitive docs. */+export function DocumentExtractions({+ doc,+ unlocked,+}: DocumentExtractionsProps) {+ if (doc.sensitive && !unlocked) {+ return (+ <div className="portal-documents__masked">+ <span className="portal-documents__masked-icon" aria-hidden>+ 🔒+ </span>+ <p className="portal-documents__masked-text">+ Extracted fields are hidden. Request timed access to view this+ document's content.+ </p>+ </div>+ );+ }++ return (+ <Table<Extraction>+ columns={cols}+ rows={doc.extractions}+ rowKey={(e) => e.field}+ empty="No fields were extracted from this document."+ />+ );+}diff --git a/frontend/portal/src/components/documents/DocumentOverview.stories.tsx b/frontend/portal/src/components/documents/DocumentOverview.stories.tsxnew file mode 100644index 0000000000..deaa6e28be--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentOverview.stories.tsx@@ -0,0 +1,24 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { documentsFor } from "@portal/mocks/documents";+import { DocumentOverview } from "@portal/components/documents/DocumentOverview";+import "@portal/views/Documents.css";++const DOC = documentsFor("pro")[0];++const meta: Meta<typeof DocumentOverview> = {+ title: "Portal/Documents/DocumentOverview",+ component: DocumentOverview,+ parameters: { layout: "padded" },+ args: { doc: DOC },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "36rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DocumentOverview>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/documents/DocumentOverview.tsx b/frontend/portal/src/components/documents/DocumentOverview.tsxnew file mode 100644index 0000000000..4ec3cac227--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentOverview.tsx@@ -0,0 +1,22 @@+import { StatTile } from "@shared/components";+import {+ DOCUMENT_STATUS_LABEL,+ type ReviewDocument,+} from "@portal/api/documents";+import { confidencePct } from "@portal/components/documents/format";++/** Key fields for the selected document — status, source, confidence. */+export function DocumentOverview({ doc }: { doc: ReviewDocument }) {+ return (+ <div className="portal-documents__overview">+ <div className="portal-documents__stat-grid">+ <StatTile label="Status" value={DOCUMENT_STATUS_LABEL[doc.status]} />+ <StatTile label="Type" value={doc.type} />+ <StatTile label="Confidence" value={confidencePct(doc.confidence)} />+ <StatTile label="Fields extracted" value={doc.fieldsExtracted} />+ <StatTile label="Source" value={doc.source} />+ <StatTile label="Received" value={doc.time} />+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/documents/DocumentsSummaryStrip.stories.tsx b/frontend/portal/src/components/documents/DocumentsSummaryStrip.stories.tsxnew file mode 100644index 0000000000..1bab1092be--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentsSummaryStrip.stories.tsx@@ -0,0 +1,26 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { summaryFor } from "@portal/mocks/documents";+import { DocumentsSummaryStrip } from "@portal/components/documents/DocumentsSummaryStrip";+import "@portal/views/Documents.css";++const meta: Meta<typeof DocumentsSummaryStrip> = {+ title: "Portal/Documents/DocumentsSummaryStrip",+ component: DocumentsSummaryStrip,+ parameters: { layout: "padded" },+ args: { summary: summaryFor("enterprise"), loading: false },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "78rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DocumentsSummaryStrip>;++export const Default: Story = {};++export const Loading: Story = {+ args: { summary: null, loading: true },+};diff --git a/frontend/portal/src/components/documents/DocumentsSummaryStrip.tsx b/frontend/portal/src/components/documents/DocumentsSummaryStrip.tsxnew file mode 100644index 0000000000..8aed83eed4--- /dev/null+++ b/frontend/portal/src/components/documents/DocumentsSummaryStrip.tsx@@ -0,0 +1,46 @@+import { MetricCard, MetricStrip, Skeleton } from "@shared/components";+import type { DocumentsSummary } from "@portal/api/documents";+import { confidencePct } from "@portal/components/documents/format";++interface DocumentsSummaryStripProps {+ summary: DocumentsSummary | null;+ loading: boolean;+}++/** KPI strip across the top of the review queue. */+export function DocumentsSummaryStrip({+ summary,+ loading,+}: DocumentsSummaryStripProps) {+ if (loading && !summary) {+ return (+ <MetricStrip>+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} height="5.5rem" />+ ))}+ </MetricStrip>+ );+ }+ if (!summary) return null;++ return (+ <MetricStrip>+ <MetricCard+ label="In queue"+ value={summary.totalInQueue.toLocaleString()}+ />+ <MetricCard+ label="Needs review"+ value={summary.needsReview.toLocaleString()}+ />+ <MetricCard+ label="Avg confidence"+ value={confidencePct(summary.avgConfidence)}+ />+ <MetricCard+ label="Processed today"+ value={summary.processedToday.toLocaleString()}+ />+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/documents/ElevationBanner.stories.tsx b/frontend/portal/src/components/documents/ElevationBanner.stories.tsxnew file mode 100644index 0000000000..bcb1f26496--- /dev/null+++ b/frontend/portal/src/components/documents/ElevationBanner.stories.tsx@@ -0,0 +1,37 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ElevationBanner } from "@portal/components/documents/ElevationBanner";+import { ELEVATION_WINDOW_SECONDS } from "@portal/components/documents/format";+import "@portal/views/Documents.css";++const meta: Meta<typeof ElevationBanner> = {+ title: "Portal/Documents/ElevationBanner",+ component: ElevationBanner,+ parameters: { layout: "padded" },+ args: { secondsLeft: null, fourEyes: false, onRequest: () => {} },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "40rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ElevationBanner>;++/** No grant yet — offers the request affordance. */+export const Locked: Story = {};++/** No grant, enterprise four-eyes note. */+export const LockedFourEyes: Story = {+ args: { fourEyes: true },+};++/** Active grant counting down. */+export const Granted: Story = {+ args: { secondsLeft: ELEVATION_WINDOW_SECONDS - 1 },+};++export const GrantedFourEyes: Story = {+ args: { secondsLeft: ELEVATION_WINDOW_SECONDS - 1, fourEyes: true },+};diff --git a/frontend/portal/src/components/documents/ElevationBanner.tsx b/frontend/portal/src/components/documents/ElevationBanner.tsxnew file mode 100644index 0000000000..b279ab76d6--- /dev/null+++ b/frontend/portal/src/components/documents/ElevationBanner.tsx@@ -0,0 +1,55 @@+import { Banner, Button } from "@shared/components";+import { formatCountdown } from "@portal/components/documents/format";++interface ElevationBannerProps {+ /** Seconds left on the active grant, or null when no grant is active. */+ secondsLeft: number | null;+ /** True for tiers with the four-eyes elevation flow (enterprise). */+ fourEyes: boolean;+ onRequest: () => void;+}++/**+ * Zero-standing-access affordance for a sensitive document. With no active+ * grant it offers a "Request access" button; once granted it counts down the+ * remaining window. The grant is client-side only — see the view for the+ * backend TODO.+ */+export function ElevationBanner({+ secondsLeft,+ fourEyes,+ onRequest,+}: ElevationBannerProps) {+ if (secondsLeft !== null) {+ return (+ <Banner+ tone="success"+ icon={<span aria-hidden>⏱</span>}+ title={`Access expires in ${formatCountdown(secondsLeft)}`}+ description={+ fourEyes+ ? "Temporary grant — a peer reviewer was notified (four-eyes)."+ : "Temporary grant — access is logged and time-boxed."+ }+ />+ );+ }++ return (+ <Banner+ tone="warning"+ icon={<span aria-hidden>🔒</span>}+ title="Sensitive document"+ description={+ fourEyes+ ? "Content is gated by zero-standing-access. Requesting starts a time-boxed grant and notifies a peer reviewer (four-eyes)."+ : "Content is gated by zero-standing-access. Requesting starts a time-boxed grant."+ }+ action={+ <Button size="sm" onClick={onRequest}>+ Request access+ </Button>+ }+ />+ );+}diff --git a/frontend/portal/src/components/documents/ReviewQueue.stories.tsx b/frontend/portal/src/components/documents/ReviewQueue.stories.tsxnew file mode 100644index 0000000000..2d1d37d88e--- /dev/null+++ b/frontend/portal/src/components/documents/ReviewQueue.stories.tsx@@ -0,0 +1,55 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { ReviewQueue } from "@portal/components/documents/ReviewQueue";+import "@portal/views/Documents.css";++const meta: Meta<typeof ReviewQueue> = {+ title: "Portal/Documents/ReviewQueue",+ component: ReviewQueue,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "78rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ReviewQueue>;++/** Live queue served by the default MSW handler (drives off the toolbar tier). */+export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/documents", async () => {+ await delay("infinite");+ return HttpResponse.json({ summary: {}, documents: [] });+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/documents", () =>+ HttpResponse.json({+ summary: {+ totalInQueue: 0,+ needsReview: 0,+ avgConfidence: 0,+ processedToday: 0,+ },+ documents: [],+ }),+ ),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/documents/ReviewQueue.tsx b/frontend/portal/src/components/documents/ReviewQueue.tsxnew file mode 100644index 0000000000..43210a11ff--- /dev/null+++ b/frontend/portal/src/components/documents/ReviewQueue.tsx@@ -0,0 +1,115 @@+import { useMemo, useState } from "react";+import { EmptyState, Skeleton, Tabs, type TabItem } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchDocuments,+ type DocumentStatus,+ type DocumentsResponse,+ type ReviewDocument,+} from "@portal/api/documents";+import { DocumentsSummaryStrip } from "@portal/components/documents/DocumentsSummaryStrip";+import { ReviewQueueTable } from "@portal/components/documents/ReviewQueueTable";+import { DocumentDrawer } from "@portal/components/documents/DocumentDrawer";++type QueueFilter = "all" | "needs-review" | "processed" | "archived";++/** Which document statuses each filter pill admits. */+const FILTER_STATUSES: Record<QueueFilter, DocumentStatus[] | null> = {+ all: null,+ // "Needs review" surfaces both routed-for-review and flagged docs — the two+ // states that demand a human decision.+ "needs-review": ["needs-review", "flagged"],+ processed: ["processed"],+ archived: ["archived"],+};++function countFor(docs: ReviewDocument[], filter: QueueFilter): number {+ const statuses = FILTER_STATUSES[filter];+ if (statuses === null) return docs.length;+ return docs.filter((d) => statuses.includes(d.status)).length;+}++/**+ * The review/approval queue: KPI strip, status filter pills, the document+ * stream table, and a detail drawer. The primary Documents surface.+ */+export function ReviewQueue() {+ const { tier } = useTier();+ const state = useAsync<DocumentsResponse>(() => fetchDocuments(tier), [tier]);+ const { data, loading } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const [filter, setFilter] = useState<QueueFilter>("all");+ const [selectedId, setSelectedId] = useState<string | null>(null);++ const documents = useMemo(() => data?.documents ?? [], [data]);++ const rows = useMemo(() => {+ const statuses = FILTER_STATUSES[filter];+ if (statuses === null) return documents;+ return documents.filter((d) => statuses.includes(d.status));+ }, [documents, filter]);++ const selected = documents.find((d) => d.id === selectedId) ?? null;++ const filterItems: TabItem<QueueFilter>[] = [+ { key: "all", label: "All", count: countFor(documents, "all") },+ {+ key: "needs-review",+ label: "Needs review",+ count: countFor(documents, "needs-review"),+ },+ {+ key: "processed",+ label: "Processed",+ count: countFor(documents, "processed"),+ },+ {+ key: "archived",+ label: "Archived",+ count: countFor(documents, "archived"),+ },+ ];++ return (+ <div className="portal-documents__queue">+ <DocumentsSummaryStrip+ summary={data?.summary ?? null}+ loading={loading}+ />++ <Tabs<QueueFilter>+ items={filterItems}+ activeKey={filter}+ onChange={setFilter}+ variant="pill"+ ariaLabel="Filter documents by status"+ />++ {isLoading && (+ <div className="portal-documents__table-skeleton" aria-hidden>+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} height="3rem" />+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ title="No documents in the queue"+ description="As sources feed documents into your pipelines they'll appear here for review."+ />+ )}++ {!isLoading && !isEmpty && (+ <ReviewQueueTable+ documents={rows}+ onRowClick={(d) => setSelectedId(d.id)}+ />+ )}++ <DocumentDrawer doc={selected} onClose={() => setSelectedId(null)} />+ </div>+ );+}diff --git a/frontend/portal/src/components/documents/ReviewQueueTable.stories.tsx b/frontend/portal/src/components/documents/ReviewQueueTable.stories.tsxnew file mode 100644index 0000000000..bf0f6bb640--- /dev/null+++ b/frontend/portal/src/components/documents/ReviewQueueTable.stories.tsx@@ -0,0 +1,37 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { documentsFor } from "@portal/mocks/documents";+import { ReviewQueueTable } from "@portal/components/documents/ReviewQueueTable";+import "@portal/views/Documents.css";++const DOCS = documentsFor("enterprise");++const meta: Meta<typeof ReviewQueueTable> = {+ title: "Portal/Documents/ReviewQueueTable",+ component: ReviewQueueTable,+ parameters: { layout: "padded" },+ args: { documents: DOCS, onRowClick: () => {} },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "78rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ReviewQueueTable>;++export const Default: Story = {};++/** Only the rows demanding a decision. */+export const NeedsReview: Story = {+ args: {+ documents: DOCS.filter(+ (d) => d.status === "needs-review" || d.status === "flagged",+ ),+ },+};++export const Empty: Story = {+ args: { documents: [] },+};diff --git a/frontend/portal/src/components/documents/ReviewQueueTable.tsx b/frontend/portal/src/components/documents/ReviewQueueTable.tsxnew file mode 100644index 0000000000..9c6d56a78f--- /dev/null+++ b/frontend/portal/src/components/documents/ReviewQueueTable.tsx@@ -0,0 +1,112 @@+import { useMemo } from "react";+import {+ ProgressBar,+ StatusBadge,+ Table,+ type TableColumn,+} from "@shared/components";+import {+ DOCUMENT_STATUS_LABEL,+ DOCUMENT_STATUS_TONE,+ type ReviewDocument,+} from "@portal/api/documents";+import {+ confidencePct,+ confidenceTone,+} from "@portal/components/documents/format";++interface ReviewQueueTableProps {+ documents: ReviewDocument[];+ onRowClick: (doc: ReviewDocument) => void;+}++/** The document stream — one row per document awaiting a review decision. */+export function ReviewQueueTable({+ documents,+ onRowClick,+}: ReviewQueueTableProps) {+ const columns = useMemo<TableColumn<ReviewDocument>[]>(+ () => [+ {+ key: "name",+ header: "Name",+ render: (d) => (+ <div className="portal-documents__name-cell">+ <span className="portal-documents__name">{d.name}</span>+ {d.sensitive && (+ <span+ className="portal-documents__lock"+ title="Sensitive — access required"+ aria-label="Sensitive"+ >+ 🔒+ </span>+ )}+ </div>+ ),+ },+ { key: "type", header: "Type", render: (d) => d.type },+ {+ key: "status",+ header: "Status",+ render: (d) => (+ <StatusBadge tone={DOCUMENT_STATUS_TONE[d.status]} size="sm">+ {DOCUMENT_STATUS_LABEL[d.status]}+ </StatusBadge>+ ),+ },+ {+ key: "source",+ header: "Source",+ render: (d) => (+ <span className="portal-documents__muted">{d.source}</span>+ ),+ },+ {+ key: "confidence",+ header: "Confidence",+ width: "9rem",+ render: (d) => (+ <div className="portal-documents__confidence">+ <ProgressBar value={d.confidence} height={6} />+ <span+ className={`portal-documents__confidence-pct portal-documents__confidence-pct--${confidenceTone(+ d.confidence,+ )}`}+ >+ {confidencePct(d.confidence)}+ </span>+ </div>+ ),+ },+ {+ key: "fields",+ header: "Fields",+ align: "right",+ render: (d) => (+ <span className="portal-documents__mono">{d.fieldsExtracted}</span>+ ),+ },+ {+ key: "time",+ header: "Time",+ align: "right",+ render: (d) => (+ <span className="portal-documents__muted">{d.time}</span>+ ),+ },+ ],+ [],+ );++ return (+ <Table<ReviewDocument>+ className="portal-documents__table"+ columns={columns}+ rows={documents}+ rowKey={(d) => d.id}+ onRowClick={onRowClick}+ empty="No documents match this filter."+ />+ );+}diff --git a/frontend/portal/src/components/documents/format.ts b/frontend/portal/src/components/documents/format.tsnew file mode 100644index 0000000000..d9591a3487--- /dev/null+++ b/frontend/portal/src/components/documents/format.ts@@ -0,0 +1,28 @@+import type { StatusTone } from "@shared/components";++/** Format a 0–1 confidence fraction as a whole-percent string. */+export function confidencePct(n: number): string {+ return `${Math.round(n * 100)}%`;+}++/**+ * Tone for a confidence value. The bands match the review thresholds: below+ * 60% is unreliable (danger), 60–85% warrants a glance (warning), above is+ * trusted (success).+ */+export function confidenceTone(n: number): StatusTone {+ if (n < 0.6) return "danger";+ if (n < 0.85) return "warning";+ return "success";+}++/** Window a freshly granted elevation stays valid, in seconds. */+export const ELEVATION_WINDOW_SECONDS = 15 * 60;++/** Format remaining elevation seconds as M:SS for the countdown banner. */+export function formatCountdown(totalSeconds: number): string {+ const safe = Math.max(0, totalSeconds);+ const minutes = Math.floor(safe / 60);+ const seconds = safe % 60;+ return `${minutes}:${seconds.toString().padStart(2, "0")}`;+}diff --git a/frontend/portal/src/components/editor-admin/CredentialRotationCard.stories.tsx b/frontend/portal/src/components/editor-admin/CredentialRotationCard.stories.tsxnew file mode 100644index 0000000000..29bcdeeb2d--- /dev/null+++ b/frontend/portal/src/components/editor-admin/CredentialRotationCard.stories.tsx@@ -0,0 +1,37 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { CredentialRotationCard } from "@portal/components/editor-admin/CredentialRotationCard";+import "@portal/views/EditorAdmin.css";++const meta: Meta<typeof CredentialRotationCard> = {+ title: "Portal/EditorAdmin/CredentialRotationCard",+ component: CredentialRotationCard,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "40rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof CredentialRotationCard>;++export const Default: Story = {+ args: {+ serviceToken: {+ masked: "svc_live_••••••••••••7b21",+ lastRotated: "34 days ago",+ },+ },+};++/** Press "Rotate" in the story to see the post-rotation warning banner. */+export const RecentlyRotated: Story = {+ args: {+ serviceToken: {+ masked: "svc_live_••••••••••••7b21",+ lastRotated: "2 days ago",+ },+ },+};diff --git a/frontend/portal/src/components/editor-admin/CredentialRotationCard.tsx b/frontend/portal/src/components/editor-admin/CredentialRotationCard.tsxnew file mode 100644index 0000000000..07dfda569a--- /dev/null+++ b/frontend/portal/src/components/editor-admin/CredentialRotationCard.tsx@@ -0,0 +1,66 @@+import { useState } from "react";+import { Banner, Button, Card, StatTile } from "@shared/components";+import type { DeploymentSummary } from "@portal/api/editorDeploy";++interface Props {+ serviceToken: DeploymentSummary["serviceToken"];+}++/**+ * Rotation control for the deployment's service token — the credential+ * instances use to authenticate back to the org. Rotation is a demo shell:+ * it flashes a warning that running instances must pick up the new value, but+ * there's no submit endpoint yet.+ */+export function CredentialRotationCard({ serviceToken }: Props) {+ const [rotating, setRotating] = useState(false);+ const [rotated, setRotated] = useState(false);++ function rotate() {+ // TODO(backend): POST /v1/editor/deployment/rotate → mints a new service+ // token and revokes the old one after a grace window.+ setRotating(true);+ setTimeout(() => {+ setRotating(false);+ setRotated(true);+ }, 700);+ }++ return (+ <Card padding="default" className="portal-editor__panel">+ <div className="portal-editor__panel-head">+ <div>+ <h3 className="portal-editor__panel-title">Service token</h3>+ <p className="portal-editor__panel-sub">+ Instances authenticate to the org with this credential. Rotate it on+ a schedule or immediately after a suspected leak.+ </p>+ </div>+ </div>++ <div className="portal-editor__token-row">+ <StatTile label="Current token" value={serviceToken.masked} />+ <StatTile label="Last rotated" value={serviceToken.lastRotated} />+ </div>++ {rotated && (+ <Banner+ tone="warning"+ title="Rotate running instances"+ description="A new token was issued. Update each self-hosted instance's STIRLING_SERVICE_TOKEN within the 24h grace window or they'll drop offline."+ />+ )}++ <div className="portal-editor__panel-actions">+ <Button+ variant="outline"+ accent="amber"+ loading={rotating}+ onClick={rotate}+ >+ Rotate service token+ </Button>+ </div>+ </Card>+ );+}diff --git a/frontend/portal/src/components/editor-admin/DeploymentSummaryStrip.stories.tsx b/frontend/portal/src/components/editor-admin/DeploymentSummaryStrip.stories.tsxnew file mode 100644index 0000000000..1dd63dc0a2--- /dev/null+++ b/frontend/portal/src/components/editor-admin/DeploymentSummaryStrip.stories.tsx@@ -0,0 +1,24 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildEditorDeploymentResponse } from "@portal/mocks/editorDeploy";+import { DeploymentSummaryStrip } from "@portal/components/editor-admin/DeploymentSummaryStrip";+import "@portal/views/EditorAdmin.css";++const meta: Meta<typeof DeploymentSummaryStrip> = {+ title: "Portal/EditorAdmin/DeploymentSummaryStrip",+ component: DeploymentSummaryStrip,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof DeploymentSummaryStrip>;++export const Pro: Story = {+ args: { summary: buildEditorDeploymentResponse("pro").summary },+};++export const Enterprise: Story = {+ args: { summary: buildEditorDeploymentResponse("enterprise").summary },+};++export const Loading: Story = {+ args: { loading: true },+};diff --git a/frontend/portal/src/components/editor-admin/DeploymentSummaryStrip.tsx b/frontend/portal/src/components/editor-admin/DeploymentSummaryStrip.tsxnew file mode 100644index 0000000000..9491de67aa--- /dev/null+++ b/frontend/portal/src/components/editor-admin/DeploymentSummaryStrip.tsx@@ -0,0 +1,35 @@+import { MetricCard, MetricStrip, Skeleton } from "@shared/components";+import type { DeploymentSummary } from "@portal/api/editorDeploy";++interface Props {+ summary?: DeploymentSummary;+ loading?: boolean;+}++/** Top-of-page metric strip summarising the org's Editor deployment health. */+export function DeploymentSummaryStrip({ summary, loading }: Props) {+ if (loading || !summary) {+ return (+ <MetricStrip>+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} height="5.5rem" />+ ))}+ </MetricStrip>+ );+ }++ return (+ <MetricStrip>+ {summary.metrics.map((m) => (+ <MetricCard+ key={m.label}+ label={m.label}+ value={m.value}+ delta={m.delta}+ deltaDirection={m.deltaDirection}+ description={m.description}+ />+ ))}+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/editor-admin/DeploymentTargets.stories.tsx b/frontend/portal/src/components/editor-admin/DeploymentTargets.stories.tsxnew file mode 100644index 0000000000..68383a2e82--- /dev/null+++ b/frontend/portal/src/components/editor-admin/DeploymentTargets.stories.tsx@@ -0,0 +1,48 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildEditorDeploymentResponse } from "@portal/mocks/editorDeploy";+import { TierProvider } from "@portal/contexts/TierContext";+import { DeploymentTargets } from "@portal/components/editor-admin/DeploymentTargets";+import "@portal/views/EditorAdmin.css";++const meta: Meta<typeof DeploymentTargets> = {+ title: "Portal/EditorAdmin/DeploymentTargets",+ component: DeploymentTargets,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof DeploymentTargets>;++/** Free: only Managed Cloud runs; Docker + K8s are locked behind a paywall. */+export const Free: Story = {+ args: { targets: buildEditorDeploymentResponse("free").targets },+ decorators: [+ (S) => (+ <TierProvider initialTier="free">+ <S />+ </TierProvider>+ ),+ ],+};++/** Pro: Docker running, Kubernetes available but not yet deployed. */+export const Pro: Story = {+ args: { targets: buildEditorDeploymentResponse("pro").targets },+ decorators: [+ (S) => (+ <TierProvider initialTier="pro">+ <S />+ </TierProvider>+ ),+ ],+};++export const Enterprise: Story = {+ args: { targets: buildEditorDeploymentResponse("enterprise").targets },+ decorators: [+ (S) => (+ <TierProvider initialTier="enterprise">+ <S />+ </TierProvider>+ ),+ ],+};diff --git a/frontend/portal/src/components/editor-admin/DeploymentTargets.tsx b/frontend/portal/src/components/editor-admin/DeploymentTargets.tsxnew file mode 100644index 0000000000..6c326fb59b--- /dev/null+++ b/frontend/portal/src/components/editor-admin/DeploymentTargets.tsx@@ -0,0 +1,102 @@+import { Button, Card, CodeBlock, StatusBadge } from "@shared/components";+import { TARGET_META, type DeploymentTarget } from "@portal/api/editorDeploy";+import { useTier } from "@portal/contexts/TierContext";++const STATE_BADGE: Record<+ DeploymentTarget["state"],+ { label: string; tone: "success" | "info" | "neutral" }+> = {+ running: { label: "Running", tone: "success" },+ available: { label: "Available", tone: "info" },+ locked: { label: "Locked", tone: "neutral" },+};++/** Upgrade-nudge copy for a target gated behind a higher tier. */+function lockCopy(target: DeploymentTarget): string {+ return target.requiresTier === "enterprise"+ ? "On-prem and Kubernetes self-hosting are part of Enterprise."+ : "Self-hosting with Docker and Kubernetes unlocks on a paid plan.";+}++interface Props {+ targets: DeploymentTarget[];+ /** Invoked from a locked target's upgrade nudge. */+ onUpgrade?: () => void;+}++/**+ * The three deployment targets (Managed Cloud / Docker / Kubernetes). Unlocked+ * targets show their install/run snippet; locked ones swap it for an upgrade+ * nudge so the value of the higher tier is visible inline.+ */+export function DeploymentTargets({ targets, onUpgrade }: Props) {+ const { tier } = useTier();++ return (+ <div className="portal-editor__targets">+ {targets.map((t) => {+ const meta = TARGET_META[t.kind];+ const badge = STATE_BADGE[t.state];+ const locked = t.state === "locked";+ return (+ <Card+ key={t.kind}+ padding="default"+ className="portal-editor__target"+ >+ <div className="portal-editor__target-head">+ <span+ className={`portal-editor__target-icon portal-editor__target-icon--${meta.tone}`}+ aria-hidden+ >+ {meta.icon}+ </span>+ <div className="portal-editor__target-titles">+ <h3 className="portal-editor__target-name">{t.label}</h3>+ <p className="portal-editor__target-tagline">{t.tagline}</p>+ </div>+ <StatusBadge+ tone={badge.tone}+ size="sm"+ pulse={t.state === "running"}+ >+ {badge.label}+ </StatusBadge>+ </div>++ {t.state === "running" && (+ <p className="portal-editor__target-meta">+ v{t.runningVersion} · {t.instanceCount}{" "}+ {t.instanceCount === 1 ? "instance" : "instances"}+ </p>+ )}++ {locked ? (+ <div className="portal-editor__lock">+ <p className="portal-editor__lock-copy">{lockCopy(t)}</p>+ <Button+ size="sm"+ variant="outline"+ accent={t.requiresTier === "enterprise" ? "purple" : "blue"}+ onClick={onUpgrade}+ disabled={tier === "enterprise"}+ >+ {t.requiresTier === "enterprise"+ ? "Talk to sales"+ : "Upgrade plan"}+ </Button>+ </div>+ ) : (+ <CodeBlock+ code={t.snippet}+ lang={t.snippetLang}+ caption={t.label}+ maxHeight={180}+ />+ )}+ </Card>+ );+ })}+ </div>+ );+}diff --git a/frontend/portal/src/components/editor-admin/InstanceHealthTable.stories.tsx b/frontend/portal/src/components/editor-admin/InstanceHealthTable.stories.tsxnew file mode 100644index 0000000000..940cac5eb0--- /dev/null+++ b/frontend/portal/src/components/editor-admin/InstanceHealthTable.stories.tsx@@ -0,0 +1,26 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildEditorDeploymentResponse } from "@portal/mocks/editorDeploy";+import { InstanceHealthTable } from "@portal/components/editor-admin/InstanceHealthTable";+import "@portal/views/EditorAdmin.css";++const meta: Meta<typeof InstanceHealthTable> = {+ title: "Portal/EditorAdmin/InstanceHealthTable",+ component: InstanceHealthTable,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof InstanceHealthTable>;++/** Pro: Managed Cloud + two Docker edge nodes, one on a stale version. */+export const Pro: Story = {+ args: { instances: buildEditorDeploymentResponse("pro").instances },+};++/** Enterprise: adds the K8s fleet and an offline air-gapped node. */+export const Enterprise: Story = {+ args: { instances: buildEditorDeploymentResponse("enterprise").instances },+};++export const Empty: Story = {+ args: { instances: [] },+};diff --git a/frontend/portal/src/components/editor-admin/InstanceHealthTable.tsx b/frontend/portal/src/components/editor-admin/InstanceHealthTable.tsxnew file mode 100644index 0000000000..90f45b5562--- /dev/null+++ b/frontend/portal/src/components/editor-admin/InstanceHealthTable.tsx@@ -0,0 +1,92 @@+import {+ Card,+ Chip,+ EmptyState,+ StatusBadge,+ Table,+ type TableColumn,+} from "@shared/components";+import {+ INSTANCE_STATUS_LABEL,+ INSTANCE_STATUS_TONE,+ TARGET_META,+ type EditorInstance,+} from "@portal/api/editorDeploy";++const TARGET_LABEL: Record<EditorInstance["target"], string> = {+ cloud: "Cloud",+ docker: "Docker",+ kubernetes: "K8s",+};++const cols: TableColumn<EditorInstance>[] = [+ {+ key: "host",+ header: "Host",+ render: (i) => (+ <div className="portal-editor__cell-stack">+ <span className="portal-editor__cell-strong">{i.host}</span>+ <span className="portal-editor__cell-muted">+ <Chip size="sm" tone={TARGET_META[i.target].tone}>+ {TARGET_LABEL[i.target]}+ </Chip>+ </span>+ </div>+ ),+ },+ {+ key: "version",+ header: "Version",+ render: (i) => <code className="portal-editor__mono">{i.version}</code>,+ },+ {+ key: "region",+ header: "Region",+ render: (i) => <span className="portal-editor__mono">{i.region}</span>,+ },+ {+ key: "status",+ header: "Status",+ render: (i) => (+ <StatusBadge+ tone={INSTANCE_STATUS_TONE[i.status]}+ size="sm"+ pulse={i.status === "healthy"}+ >+ {INSTANCE_STATUS_LABEL[i.status]}+ </StatusBadge>+ ),+ },+ {+ key: "lastSeen",+ header: "Last seen",+ render: (i) => <span className="portal-editor__muted">{i.lastSeen}</span>,+ },+ {+ key: "activeUsers",+ header: "Active users",+ align: "right",+ render: (i) => <span className="portal-editor__mono">{i.activeUsers}</span>,+ },+];++interface Props {+ instances: EditorInstance[];+}++/** Live health for every Editor instance reporting in to the org. */+export function InstanceHealthTable({ instances }: Props) {+ return (+ <Card padding="none">+ {instances.length === 0 ? (+ <EmptyState+ size="compact"+ title="No instances reporting"+ description="Deploy a target and pair it to see live instance health here."+ />+ ) : (+ <Table columns={cols} rows={instances} rowKey={(i) => i.id} />+ )}+ </Card>+ );+}diff --git a/frontend/portal/src/components/editor-admin/OfflineActivationCard.stories.tsx b/frontend/portal/src/components/editor-admin/OfflineActivationCard.stories.tsxnew file mode 100644index 0000000000..4f2f94bfb7--- /dev/null+++ b/frontend/portal/src/components/editor-admin/OfflineActivationCard.stories.tsx@@ -0,0 +1,28 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { OfflineActivationCard } from "@portal/components/editor-admin/OfflineActivationCard";+import "@portal/views/EditorAdmin.css";++const meta: Meta<typeof OfflineActivationCard> = {+ title: "Portal/EditorAdmin/OfflineActivationCard",+ component: OfflineActivationCard,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "40rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof OfflineActivationCard>;++/** Enterprise: bundle generation is live. */+export const Available: Story = {+ args: { available: true },+};++/** Free / Pro: locked behind an upgrade nudge. */+export const Locked: Story = {+ args: { available: false },+};diff --git a/frontend/portal/src/components/editor-admin/OfflineActivationCard.tsx b/frontend/portal/src/components/editor-admin/OfflineActivationCard.tsxnew file mode 100644index 0000000000..cd7370cbe2--- /dev/null+++ b/frontend/portal/src/components/editor-admin/OfflineActivationCard.tsx@@ -0,0 +1,83 @@+import { useState } from "react";+import { Banner, Button, Card } from "@shared/components";++interface Props {+ /** Enterprise-only. When false the card renders an upgrade nudge. */+ available: boolean;+ onUpgrade?: () => void;+}++/**+ * Air-gapped / offline activation. Networks with no outbound path can't pair+ * live, so this generates a signed activation bundle to carry in by hand.+ * Enterprise-only; lower tiers see an upgrade nudge. Generation is a demo+ * shell with no submit endpoint yet.+ */+export function OfflineActivationCard({ available, onUpgrade }: Props) {+ const [generating, setGenerating] = useState(false);+ const [generated, setGenerated] = useState(false);++ function generate() {+ // TODO(backend): POST /v1/editor/deployment/offline-bundle → streams a+ // signed .stirlingpkg activation bundle for an air-gapped install.+ setGenerating(true);+ setTimeout(() => {+ setGenerating(false);+ setGenerated(true);+ }, 900);+ }++ return (+ <Card padding="default" accent="purple" className="portal-editor__panel">+ <div className="portal-editor__panel-head">+ <div>+ <h3 className="portal-editor__panel-title">+ Air-gapped activation+ <span className="portal-editor__enterprise-tag">Enterprise</span>+ </h3>+ <p className="portal-editor__panel-sub">+ Generate a signed activation bundle for an offline or on-prem+ install with no outbound network path. Transfer it to the instance+ and apply it during first-run setup.+ </p>+ </div>+ </div>++ {!available ? (+ <div className="portal-editor__lock">+ <p className="portal-editor__lock-copy">+ Offline and on-prem activation is part of Enterprise.+ </p>+ <Button+ variant="outline"+ accent="purple"+ size="sm"+ onClick={onUpgrade}+ >+ Talk to sales+ </Button>+ </div>+ ) : (+ <>+ {generated && (+ <Banner+ tone="success"+ title="Bundle ready"+ description="activation-acme-3.2.1.stirlingpkg is signed and ready to transfer. It activates one instance and expires in 14 days."+ />+ )}+ <div className="portal-editor__panel-actions">+ <Button+ variant="outline"+ accent="purple"+ loading={generating}+ onClick={generate}+ >+ Generate offline bundle+ </Button>+ </div>+ </>+ )}+ </Card>+ );+}diff --git a/frontend/portal/src/components/editor-admin/PairingPanel.stories.tsx b/frontend/portal/src/components/editor-admin/PairingPanel.stories.tsxnew file mode 100644index 0000000000..fce1446e97--- /dev/null+++ b/frontend/portal/src/components/editor-admin/PairingPanel.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildEditorDeploymentResponse } from "@portal/mocks/editorDeploy";+import { PairingPanel } from "@portal/components/editor-admin/PairingPanel";+import "@portal/views/EditorAdmin.css";++const meta: Meta<typeof PairingPanel> = {+ title: "Portal/EditorAdmin/PairingPanel",+ component: PairingPanel,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof PairingPanel>;++/** Pro: token + short code usable, IaC locked behind Enterprise. */+export const Pro: Story = {+ args: { pairings: buildEditorDeploymentResponse("pro").pairings },+};++/** Enterprise: all three methods unlocked, including the IaC module snippet. */+export const Enterprise: Story = {+ args: { pairings: buildEditorDeploymentResponse("enterprise").pairings },+};diff --git a/frontend/portal/src/components/editor-admin/PairingPanel.tsx b/frontend/portal/src/components/editor-admin/PairingPanel.tsxnew file mode 100644index 0000000000..0ddcc31050--- /dev/null+++ b/frontend/portal/src/components/editor-admin/PairingPanel.tsx@@ -0,0 +1,101 @@+import { useState } from "react";+import { Button, Card, Chip, CodeBlock } from "@shared/components";+import type { PairingMethod, PairingOption } from "@portal/api/editorDeploy";++const METHOD_ICON: Record<PairingMethod, string> = {+ token: "🔑",+ shortcode: "📺",+ iac: "🧱",+};++interface Props {+ pairings: PairingOption[];+ onUpgrade?: () => void;+}++/**+ * Pairing options for connecting a self-hosted editor to the org — a long-lived+ * pairing token, a TV-style short code, and IaC provisioning. The+ * generate/rotate affordance is a demo shell: it shows transient feedback but+ * has no submit endpoint yet.+ */+export function PairingPanel({ pairings, onUpgrade }: Props) {+ // Tracks which option just got a (mock) rotate so we can flash confirmation.+ const [rotated, setRotated] = useState<PairingMethod | null>(null);++ function rotate(method: PairingMethod) {+ // TODO(backend): POST /v1/editor/pairings { method } → returns a freshly+ // minted token / short code / IaC reference.+ setRotated(method);+ setTimeout(() => setRotated((m) => (m === method ? null : m)), 1800);+ }++ return (+ <div className="portal-editor__pairings">+ {pairings.map((p) => {+ const isCode = p.method === "iac";+ return (+ <Card+ key={p.method}+ padding="default"+ className="portal-editor__pairing"+ >+ <div className="portal-editor__pairing-head">+ <span className="portal-editor__pairing-icon" aria-hidden>+ {METHOD_ICON[p.method]}+ </span>+ <div className="portal-editor__pairing-titles">+ <h3 className="portal-editor__pairing-name">{p.label}</h3>+ <p className="portal-editor__pairing-desc">{p.description}</p>+ </div>+ </div>++ {p.locked ? (+ <div className="portal-editor__lock">+ <p className="portal-editor__lock-copy">+ IaC provisioning is part of Enterprise.+ </p>+ <Button+ size="sm"+ variant="outline"+ accent="purple"+ onClick={onUpgrade}+ >+ Talk to sales+ </Button>+ </div>+ ) : (+ <>+ {isCode ? (+ <CodeBlock code={p.value} lang="plain" maxHeight={80} />+ ) : (+ <div className="portal-editor__pairing-value">+ <code>{p.value}</code>+ </div>+ )}+ <div className="portal-editor__pairing-foot">+ {p.expires && (+ <Chip size="sm" tone="neutral">+ {p.expires}+ </Chip>+ )}+ <Button+ size="sm"+ variant="outline"+ onClick={() => rotate(p.method)}+ >+ {rotated === p.method+ ? "Generated ✓"+ : p.method === "shortcode"+ ? "Generate new code"+ : "Rotate"}+ </Button>+ </div>+ </>+ )}+ </Card>+ );+ })}+ </div>+ );+}diff --git a/frontend/portal/src/components/icons.tsx b/frontend/portal/src/components/icons.tsxindex 0018850c57..67051cab1f 100644--- a/frontend/portal/src/components/icons.tsx+++ b/frontend/portal/src/components/icons.tsx@@ -200,3 +200,46 @@ export function SendIcon(props: IconProps) {</Svg>);}++export function UsersIcon(props: IconProps) {+ return (+ <Svg {...props}>+ <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />+ <circle cx="9" cy="7" r="4" />+ <path d="M22 21v-2a4 4 0 0 0-3-3.87" />+ <path d="M16 3.13a4 4 0 0 1 0 7.75" />+ </Svg>+ );+}++export function PoliciesIcon(props: IconProps) {+ return (+ <Svg {...props}>+ <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />+ <path d="m9 12 2 2 4-4" />+ </Svg>+ );+}++export function ComponentsIcon(props: IconProps) {+ return (+ <Svg {...props}>+ <rect x="3" y="3" width="7" height="7" rx="1" />+ <rect x="14" y="3" width="7" height="7" rx="1" />+ <rect x="3" y="14" width="7" height="7" rx="1" />+ <rect x="14" y="14" width="7" height="7" rx="1" />+ </Svg>+ );+}++export function AgentBuilderIcon(props: IconProps) {+ return (+ <Svg {...props}>+ <rect x="3" y="11" width="18" height="10" rx="2" />+ <circle cx="12" cy="5" r="2" />+ <path d="M12 7v4" />+ <line x1="8" y1="16" x2="8" y2="16" />+ <line x1="16" y1="16" x2="16" y2="16" />+ </Svg>+ );+}diff --git a/frontend/portal/src/components/infrastructure/ModelsTab.stories.tsx b/frontend/portal/src/components/infrastructure/ModelsTab.stories.tsxnew file mode 100644index 0000000000..c69fd63988--- /dev/null+++ b/frontend/portal/src/components/infrastructure/ModelsTab.stories.tsx@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ModelsTab } from "@portal/components/infrastructure/ModelsTab";+import "@portal/views/Infrastructure.css";++// Data is served by the registered MSW infrastructure handler; the tier global+// (toolbar) drives which catalogue + routing slice each story renders.+const meta = {+ title: "Infrastructure/ModelsTab",+ component: ModelsTab,+ parameters: { layout: "padded" },+} satisfies Meta<typeof ModelsTab>;++export default meta;++type Story = StoryObj<typeof meta>;++/** Pro: full managed catalogue plus routing control. */+export const Pro: Story = {+ globals: { tier: "pro" },+};++/** Free: two managed models, no routing (upgrade nudge). */+export const Free: Story = {+ globals: { tier: "free" },+};++/** Enterprise: adds bring-your-own / on-prem models and per-region pinning. */+export const Enterprise: Story = {+ globals: { tier: "enterprise" },+};diff --git a/frontend/portal/src/components/infrastructure/ModelsTab.tsx b/frontend/portal/src/components/infrastructure/ModelsTab.tsxnew file mode 100644index 0000000000..f807941a6b--- /dev/null+++ b/frontend/portal/src/components/infrastructure/ModelsTab.tsx@@ -0,0 +1,244 @@+import {+ Banner,+ Card,+ Chip,+ EmptyState,+ MetricCard,+ ProgressBar,+ Select,+ StatusBadge,+ Table,+ type SelectOption,+ type TableColumn,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchModels,+ type ModelEntry,+ type ModelsResponse,+ type RoutingRule,+} from "@portal/api/infrastructure";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import { TableSkeleton } from "@portal/components/infrastructure/TableSkeleton";+import {+ MODEL_LABEL,+ MODEL_PROVIDER_LABEL,+ MODEL_TONE,+ MODEL_TYPE_LABEL,+ MODEL_TYPE_TONE,+ modelCost,+ pct,+} from "@portal/components/infrastructure/infraFormat";++const modelCols: TableColumn<ModelEntry>[] = [+ {+ key: "name",+ header: "Model",+ render: (m) => (+ <div className="portal-infra__cell-stack">+ <span className="portal-infra__cell-strong">{m.name}</span>+ <Chip tone="neutral" size="sm">+ {MODEL_PROVIDER_LABEL[m.provider]}+ </Chip>+ </div>+ ),+ },+ {+ key: "type",+ header: "Type",+ render: (m) => (+ <Chip tone={MODEL_TYPE_TONE[m.type]} size="sm">+ {MODEL_TYPE_LABEL[m.type]}+ </Chip>+ ),+ },+ {+ key: "status",+ header: "Status",+ render: (m) => (+ <StatusBadge+ tone={MODEL_TONE[m.status]}+ size="sm"+ pulse={m.status === "active"}+ >+ {MODEL_LABEL[m.status]}+ </StatusBadge>+ ),+ },+ {+ key: "load",+ header: "Load",+ width: "9rem",+ render: (m) => (+ <div className="portal-infra__load">+ <ProgressBar value={m.load} thresholded height={6} />+ <span className="portal-infra__load-pct">{pct(m.load)}</span>+ </div>+ ),+ },+ {+ key: "latency",+ header: "Latency",+ align: "right",+ render: (m) => <span className="portal-infra__mono">{m.latencyMs} ms</span>,+ },+ {+ key: "cost",+ header: "Cost",+ align: "right",+ render: (m) => (+ <span className="portal-infra__mono">+ {modelCost(m.cost, m.costUnit)}+ </span>+ ),+ },+ {+ key: "version",+ header: "Version",+ render: (m) => <code className="portal-infra__cell-code">{m.version}</code>,+ },+];++export function ModelsTab() {+ const { tier } = useTier();+ const state = useAsync<ModelsResponse>(() => fetchModels(tier), [tier]);+ const { data } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ // Free has no routing control: the catalogue is read-only and the routing+ // table is replaced by an upgrade nudge.+ const canRoute = tier !== "free";++ // Routing overrides are interactive but unbacked — assigning a model just+ // moves local UI state until the routing endpoint exists.+ // TODO(backend): PUT /v1/infrastructure/models/routing { rules }+ const modelOptions: SelectOption[] =+ data?.models+ .filter((m) => m.status !== "disabled")+ .map((m) => ({ value: m.id, label: m.name })) ?? [];++ const routingCols: TableColumn<RoutingRule>[] = [+ {+ key: "operation",+ header: "Operation",+ render: (r) => (+ <div className="portal-infra__cell-stack">+ <span className="portal-infra__cell-strong">{r.operation}</span>+ {r.isDefault && (+ <Chip tone="blue" size="sm">+ Default+ </Chip>+ )}+ </div>+ ),+ },+ { key: "docType", header: "Document type", render: (r) => r.docType },+ {+ key: "modelId",+ header: "Routed to",+ width: "16rem",+ render: (r) => (+ <Select+ inputSize="sm"+ options={modelOptions}+ defaultValue={r.modelId}+ aria-label={`Model for ${r.operation}`}+ />+ ),+ },+ ];++ return (+ <div className="portal-infra__stack">+ <SectionHeader+ title="Models"+ sub="The model catalogue and routing that powers document processing across your workspace."+ />++ {data && (+ <section className="portal-infra__metrics">+ <MetricCard label="Active models" value={data.summary.activeModels} />+ <MetricCard+ label="Avg latency"+ value={`${data.summary.avgLatencyMs} ms`}+ />+ <MetricCard+ label="Monthly model spend"+ value={+ data.summary.monthlySpend > 0+ ? `$${data.summary.monthlySpend.toLocaleString()}`+ : "Included"+ }+ />+ </section>+ )}++ <section>+ <SectionHeader+ title="Catalogue"+ sub={+ tier === "enterprise"+ ? "Managed, bring-your-own, and on-prem models — with per-region pinning available."+ : "Managed models available to your workspace, with live latency and cost."+ }+ />+ <Card padding="none">+ {isLoading && <TableSkeleton rows={4} cols={7} />}+ {isEmpty && (+ <EmptyState+ size="compact"+ title="No models available"+ description="Models in your workspace's catalogue appear here."+ />+ )}+ {!isEmpty && data && data.models.length > 0 && (+ <Table+ columns={modelCols}+ rows={data.models}+ rowKey={(m) => m.id}+ />+ )}+ </Card>+ </section>++ {tier === "enterprise" && (+ <Banner+ tone="info"+ title="Bring your own model"+ description="Register an on-prem or self-hosted model and pin it to a region for data-residency-bound processing."+ />+ )}++ <section>+ <SectionHeader+ title="Routing rules"+ sub={+ canRoute+ ? "Which model handles each operation. The default applies when no narrower rule matches."+ : "Route operations to specific models — available on paid plans."+ }+ />+ {canRoute ? (+ <Card padding="none">+ {isLoading && <TableSkeleton rows={4} cols={3} />}+ {!isEmpty && data && (+ <Table+ columns={routingCols}+ rows={data.routing}+ rowKey={(r) => r.id}+ empty="No routing rules configured."+ />+ )}+ </Card>+ ) : (+ <Banner+ tone="info"+ title="Model routing is a paid feature"+ description="Upgrade to Pro to control which model handles each operation and document type."+ />+ )}+ </section>+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsx b/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsxindex a0a732b953..324c841043 100644--- a/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsx+++ b/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsx@@ -20,6 +20,18 @@ type Story = StoryObj<typeof SecurityTab>;export const Default: Story = {};+// Enterprise unlocks HYOK key custody (with a live rotate affordance) and the+// full attested compliance set, including PCI in-scope.+export const Enterprise: Story = {+ globals: { tier: "enterprise" },+};++// Free runs on Stirling-managed keys (rotate disabled, upgrade nudge) and a+// trimmed attestation set with HIPAA/PCI not-applicable.+export const Free: Story = {+ globals: { tier: "free" },+};+export const Loading: Story = {parameters: {msw: {diff --git a/frontend/portal/src/components/infrastructure/SecurityTab.tsx b/frontend/portal/src/components/infrastructure/SecurityTab.tsxindex 081e8f24ed..1ca703e013 100644--- a/frontend/portal/src/components/infrastructure/SecurityTab.tsx+++ b/frontend/portal/src/components/infrastructure/SecurityTab.tsx@@ -1,7 +1,9 @@import { useState } from "react";import {Banner,+ Button,Card,+ Chip,EmptyState,RadioGroup,Skeleton,@@ -20,8 +22,12 @@ import {} from "@portal/api/infrastructure";import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";import {+ ATTESTATION_LABEL,+ ATTESTATION_TONE,CERT_LABEL,CERT_TONE,+ KEY_MODE_LABEL,+ KEY_MODE_TONE,} from "@portal/components/infrastructure/infraFormat";const ACCESS_OPTS: RadioOption<AccessPolicy>[] = [@@ -146,6 +152,74 @@ export function SecurityTab() {</Card></section>+ <section>+ <SectionHeader+ title="Encryption key management"+ sub="Custody of the keys that encrypt documents at rest — who can decrypt, and how keys rotate."+ />+ <Card padding="loose" className="portal-infra__keymgmt">+ <div className="portal-infra__keymgmt-head">+ <div className="portal-infra__keymgmt-title">+ <span className="portal-infra__cell-strong">+ {data.keyManagement.provider}+ </span>+ <StatusBadge+ tone={KEY_MODE_TONE[data.keyManagement.mode]}+ size="sm"+ >+ {KEY_MODE_LABEL[data.keyManagement.mode]}+ </StatusBadge>+ </div>+ {/* Rotation is a privileged backend action; disabled where Stirling+ holds the keys (managed tiers can't rotate customer keys). */}+ <Button+ variant="outline"+ size="sm"+ disabled={!data.keyManagement.customerManaged}+ onClick={() => {+ // TODO(backend): POST /v1/infrastructure/security/keys/rotate+ }}+ >+ Rotate key+ </Button>+ </div>++ <dl className="portal-infra__kv">+ <div className="portal-infra__kv-wide">+ <dt>Key identifier</dt>+ <dd>+ <code className="portal-infra__cell-code">+ {data.keyManagement.keyId}+ </code>+ </dd>+ </div>+ <div>+ <dt>Algorithm</dt>+ <dd className="portal-infra__mono">+ {data.keyManagement.algorithm}+ </dd>+ </div>+ <div>+ <dt>Last rotated</dt>+ <dd>{data.keyManagement.lastRotated}</dd>+ </div>+ <div>+ <dt>Rotation policy</dt>+ <dd>{data.keyManagement.rotationPolicy}</dd>+ </div>+ </dl>++ {!data.keyManagement.customerManaged && (+ <Banner+ tone="info"+ className="portal-infra__banner"+ title="Keys are managed by Stirling on your plan"+ description="Bring-your-own-key (BYOK) and hold-your-own-key (HYOK) custody are available on Enterprise. Upgrade to supply keys from your own KMS."+ />+ )}+ </Card>+ </section>+<section><SectionHeadertitle="Compliance"@@ -166,6 +240,45 @@ export function SecurityTab() {</div></section>+ <section>+ <SectionHeader+ title="Compliance attestations"+ sub="Framework-by-framework audit posture, with reports available on attested controls."+ />+ <div className="portal-infra__attestations">+ {data.attestations.map((a) => (+ <Card+ key={a.id}+ padding="default"+ className="portal-infra__attestation"+ >+ <div className="portal-infra__cert-head">+ <span className="portal-infra__cell-strong">{a.name}</span>+ <StatusBadge tone={ATTESTATION_TONE[a.status]} size="sm">+ {ATTESTATION_LABEL[a.status]}+ </StatusBadge>+ </div>+ <Chip tone="neutral" size="sm">+ {a.framework}+ </Chip>+ <p className="portal-infra__cert-detail">{a.detail}</p>+ {a.reportUrl ? (+ <a+ className="portal-infra__attestation-link"+ href={a.reportUrl}+ // TODO(backend): GET /v1/infrastructure/security/reports/:id+ onClick={(e) => e.preventDefault()}+ >+ View report →+ </a>+ ) : (+ <span className="portal-infra__muted">No report available</span>+ )}+ </Card>+ ))}+ </div>+ </section>+<section><SectionHeadertitle="IP allowlist"diff --git a/frontend/portal/src/components/infrastructure/infraFormat.ts b/frontend/portal/src/components/infrastructure/infraFormat.tsindex cf3e799952..11d2c3c22c 100644--- a/frontend/portal/src/components/infrastructure/infraFormat.ts+++ b/frontend/portal/src/components/infrastructure/infraFormat.ts@@ -1,10 +1,16 @@-import type { StatusTone } from "@shared/components";+import type { ChipTone, StatusTone } from "@shared/components";import type {ApiKeyStatus,+ AttestationStatus,AuditCategory,AuditStatus,CertStatus,DeploymentStatus,+ KeyMode,+ ModelCostUnit,+ ModelProvider,+ ModelStatus,+ ModelType,RegionStatus,} from "@portal/api/infrastructure";@@ -62,6 +68,31 @@ export const CERT_LABEL: Record<CertStatus, string> = {"not-started": "Not started",};+export const KEY_MODE_LABEL: Record<KeyMode, string> = {+ managed: "Stirling-managed",+ byok: "BYOK",+ hyok: "HYOK",+};++export const KEY_MODE_TONE: Record<KeyMode, StatusTone> = {+ managed: "info",+ byok: "purple",+ // HYOK is the strongest posture (Stirling never sees plaintext) → success.+ hyok: "success",+};++export const ATTESTATION_LABEL: Record<AttestationStatus, string> = {+ attested: "Attested",+ "in-scope": "In scope",+ "not-applicable": "N/A",+};++export const ATTESTATION_TONE: Record<AttestationStatus, StatusTone> = {+ attested: "success",+ "in-scope": "warning",+ "not-applicable": "neutral",+};+export const AUDIT_TONE: Record<AuditStatus, StatusTone> = {success: "success",warning: "warning",@@ -84,3 +115,43 @@ export const AUDIT_CAT_TONE: Record<AuditCategory, StatusTone> = {processing: "success",security: "warning",};++export const MODEL_TONE: Record<ModelStatus, StatusTone> = {+ active: "success",+ degraded: "warning",+ disabled: "neutral",+};++export const MODEL_LABEL: Record<ModelStatus, string> = {+ active: "Active",+ degraded: "Degraded",+ disabled: "Disabled",+};++export const MODEL_TYPE_LABEL: Record<ModelType, string> = {+ extraction: "Extraction",+ classification: "Classification",+ ocr: "OCR",+ llm: "LLM",+};++export const MODEL_TYPE_TONE: Record<ModelType, ChipTone> = {+ extraction: "blue",+ classification: "purple",+ ocr: "green",+ llm: "amber",+};++export const MODEL_PROVIDER_LABEL: Record<ModelProvider, string> = {+ stirling: "Stirling",+ openai: "OpenAI",+ anthropic: "Anthropic",+ "on-prem": "On-prem",+};++/** Render a model's cost with the unit it's billed against. */+export function modelCost(cost: number, unit: ModelCostUnit): string {+ if (cost === 0) return "Included";+ const price = `$${cost.toFixed(unit === "per-call" ? 3 : 2)}`;+ return unit === "per-call" ? `${price}/call` : `${price}/1k`;+}diff --git a/frontend/portal/src/components/pipelines/DeployedPipelinesTable.stories.tsx b/frontend/portal/src/components/pipelines/DeployedPipelinesTable.stories.tsxnew file mode 100644index 0000000000..3dc731a47a--- /dev/null+++ b/frontend/portal/src/components/pipelines/DeployedPipelinesTable.stories.tsx@@ -0,0 +1,32 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { DeployedPipelinesTable } from "@portal/components/pipelines/DeployedPipelinesTable";+import {+ DEGRADED_PIPELINE,+ HEALTHY_PIPELINE,+} from "@portal/components/pipelines/storyFixtures";+import "@portal/views/Pipelines.css";++const meta: Meta<typeof DeployedPipelinesTable> = {+ title: "Portal/Pipelines/DeployedPipelinesTable",+ component: DeployedPipelinesTable,+ parameters: { layout: "padded" },+ args: { onRowClick: () => {} },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DeployedPipelinesTable>;++/** A healthy pipeline at bound and one degraded below its golden-set bound. */+export const Default: Story = {+ args: { pipelines: [HEALTHY_PIPELINE, DEGRADED_PIPELINE] },+};++export const Empty: Story = {+ args: { pipelines: [] },+};diff --git a/frontend/portal/src/components/pipelines/DeployedPipelinesTable.tsx b/frontend/portal/src/components/pipelines/DeployedPipelinesTable.tsxnew file mode 100644index 0000000000..0ad463c3a1--- /dev/null+++ b/frontend/portal/src/components/pipelines/DeployedPipelinesTable.tsx@@ -0,0 +1,100 @@+import { useMemo } from "react";+import { StatusBadge, Table, type TableColumn } from "@shared/components";+import type { Pipeline } from "@portal/api/pipelines";+import { compact, goldenTone, pct } from "@portal/components/pipelines/format";++interface DeployedPipelinesTableProps {+ pipelines: Pipeline[];+ onRowClick: (p: Pipeline) => void;+}++/**+ * Dense roster of the deployed fleet that puts golden-set reliability up front.+ * The card list below it carries the full per-pipeline story; this table is the+ * scannable "is anything below its bound?" view across the whole fleet.+ */+export function DeployedPipelinesTable({+ pipelines,+ onRowClick,+}: DeployedPipelinesTableProps) {+ const columns = useMemo<TableColumn<Pipeline>[]>(+ () => [+ {+ key: "name",+ header: "Pipeline",+ render: (p) => (+ <div className="portal-pipelines__roster-name">+ <strong>{p.name}</strong>+ <span className="portal-pipelines__roster-route">+ {p.source} → {p.destination}+ </span>+ </div>+ ),+ },+ {+ key: "status",+ header: "Health",+ render: (p) => (+ <StatusBadge+ tone={p.status === "degraded" ? "warning" : "success"}+ size="sm"+ pulse={p.status === "degraded"}+ >+ {p.status === "degraded" ? "Degraded" : "Healthy"}+ </StatusBadge>+ ),+ },+ {+ key: "golden",+ header: "Golden set",+ width: "11rem",+ render: (p) => {+ const tone = goldenTone(p.golden);+ const rate = p.golden.total ? p.golden.passing / p.golden.total : 0;+ return (+ <div className="portal-pipelines__roster-golden">+ <StatusBadge tone={tone} size="sm">+ {p.golden.passing}/{p.golden.total}+ </StatusBadge>+ <span+ className="portal-pipelines__roster-rate"+ title={`Bound: ${pct(p.golden.threshold, 0)}`}+ >+ {pct(rate, 1)}+ </span>+ </div>+ );+ },+ },+ {+ key: "docs",+ header: "Docs / 24h",+ align: "right",+ render: (p) => (+ <span className="portal-pipelines__roster-num">+ {compact(p.metrics.docs24h)}+ </span>+ ),+ },+ {+ key: "version",+ header: "Version",+ align: "right",+ render: (p) => (+ <span className="portal-pipelines__roster-version">{p.version}</span>+ ),+ },+ ],+ [],+ );++ return (+ <Table<Pipeline>+ className="portal-pipelines__roster"+ columns={columns}+ rows={pipelines}+ rowKey={(p) => p.id}+ onRowClick={onRowClick}+ />+ );+}diff --git a/frontend/portal/src/components/pipelines/PromotedPipelines.stories.tsx b/frontend/portal/src/components/pipelines/PromotedPipelines.stories.tsxnew file mode 100644index 0000000000..bf52ce686f--- /dev/null+++ b/frontend/portal/src/components/pipelines/PromotedPipelines.stories.tsx@@ -0,0 +1,26 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PromotedPipelines } from "@portal/components/pipelines/PromotedPipelines";+import { PROMOTED_PIPELINES } from "@portal/components/pipelines/storyFixtures";+import "@portal/views/Pipelines.css";++const meta: Meta<typeof PromotedPipelines> = {+ title: "Portal/Pipelines/PromotedPipelines",+ component: PromotedPipelines,+ parameters: { layout: "padded" },+ args: { promoted: PROMOTED_PIPELINES },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PromotedPipelines>;++export const Default: Story = {};++export const Empty: Story = {+ args: { promoted: [] },+};diff --git a/frontend/portal/src/components/pipelines/PromotedPipelines.tsx b/frontend/portal/src/components/pipelines/PromotedPipelines.tsxnew file mode 100644index 0000000000..a05112fc58--- /dev/null+++ b/frontend/portal/src/components/pipelines/PromotedPipelines.tsx@@ -0,0 +1,136 @@+import { useMemo, useState } from "react";+import {+ Button,+ StatusBadge,+ type StatusTone,+ Table,+ type TableColumn,+} from "@shared/components";+import {+ promoteToPolicy,+ type PromotedPipeline,+ type PromotedStatus,+} from "@portal/api/pipelines";++const STATUS_TONE: Record<PromotedStatus, StatusTone> = {+ deployed: "success",+ staged: "info",+ review: "warning",+};++const STATUS_LABEL: Record<PromotedStatus, string> = {+ deployed: "Deployed",+ staged: "Staged",+ review: "Needs review",+};++/** Per-row promote-to-policy lifecycle, kept local until a backend exists. */+type PromoteState = "idle" | "pending" | "done";++interface PromotedPipelinesProps {+ promoted: PromotedPipeline[];+}++/**+ * Flows that started as Editor watch-folder automations and were promoted into+ * the portal. Each keeps a pointer back to the watch folder it grew from, and+ * offers a one-click path to lift its rules into a fleet-wide org policy.+ */+export function PromotedPipelines({ promoted }: PromotedPipelinesProps) {+ // Promote submits have no backend yet, so reflect acceptance per row locally.+ const [promoteState, setPromoteState] = useState<+ Record<string, PromoteState>+ >({});++ const onPromote = async (p: PromotedPipeline) => {+ setPromoteState((s) => ({ ...s, [p.id]: "pending" }));+ try {+ // TODO(backend): POST /v1/pipelines/{id}/promote-to-policy — stubbed,+ // resolves against the mock handler; treat success as accepted.+ await promoteToPolicy(p.id);+ setPromoteState((s) => ({ ...s, [p.id]: "done" }));+ } catch {+ setPromoteState((s) => ({ ...s, [p.id]: "idle" }));+ }+ };++ const columns = useMemo<TableColumn<PromotedPipeline>[]>(+ () => [+ {+ key: "name",+ header: "Pipeline",+ render: (p) => (+ <div className="portal-pipelines__promoted-name">+ <strong>{p.name}</strong>+ <span className="portal-pipelines__promoted-when">+ {p.promotedAt}+ </span>+ </div>+ ),+ },+ {+ key: "docType",+ header: "Source doc type",+ render: (p) => (+ <span className="portal-pipelines__promoted-muted">+ {p.sourceDocType}+ </span>+ ),+ },+ {+ key: "watchFolder",+ header: "Watch folder",+ render: (p) => (+ <code className="portal-pipelines__promoted-folder">+ {p.watchFolder}+ </code>+ ),+ },+ {+ key: "status",+ header: "Status",+ render: (p) => (+ <StatusBadge tone={STATUS_TONE[p.status]} size="sm">+ {STATUS_LABEL[p.status]}+ </StatusBadge>+ ),+ },+ {+ key: "promote",+ header: "",+ align: "right",+ width: "11rem",+ render: (p) => {+ const state = promoteState[p.id] ?? "idle";+ if (state === "done") {+ return (+ <StatusBadge tone="success" size="sm">+ Policy created+ </StatusBadge>+ );+ }+ return (+ <Button+ variant="outline"+ size="sm"+ loading={state === "pending"}+ onClick={() => onPromote(p)}+ >+ Promote to policy+ </Button>+ );+ },+ },+ ],+ [promoteState],+ );++ return (+ <Table<PromotedPipeline>+ className="portal-pipelines__promoted"+ columns={columns}+ rows={promoted}+ rowKey={(p) => p.id}+ />+ );+}diff --git a/frontend/portal/src/components/pipelines/format.ts b/frontend/portal/src/components/pipelines/format.tsindex ac38f33ec3..02267eb8b5 100644--- a/frontend/portal/src/components/pipelines/format.ts+++ b/frontend/portal/src/components/pipelines/format.ts@@ -1,3 +1,6 @@+import type { GoldenSet } from "@portal/api/pipelines";+import type { StatusTone } from "@shared/components";+/** Fraction → percentage string (0.004 → "0.40%"). */export const pct = (n: number, digits = 1) => `${(n * 100).toFixed(digits)}%`;@@ -7,3 +10,17 @@ export const compact = (n: number) =>notation: "compact",maximumFractionDigits: 1,}).format(n);++/**+ * Golden-set reliability tone, judged against the pipeline's own pass-rate+ * bound. At/above bound is green; a small slip under is amber; a clear miss is+ * danger — so a row's reliability reads from colour alone.+ */+export function goldenTone(golden: GoldenSet): StatusTone {+ if (golden.total === 0) return "neutral";+ const rate = golden.passing / golden.total;+ if (rate >= golden.threshold) return "success";+ // Within five points of the bound is a warning; further off is a hard miss.+ if (rate >= golden.threshold - 0.05) return "warning";+ return "danger";+}diff --git a/frontend/portal/src/components/pipelines/storyFixtures.ts b/frontend/portal/src/components/pipelines/storyFixtures.tsindex 39458ce4d8..1973edbae1 100644--- a/frontend/portal/src/components/pipelines/storyFixtures.ts+++ b/frontend/portal/src/components/pipelines/storyFixtures.ts@@ -1,4 +1,4 @@-import type { Pipeline } from "@portal/api/pipelines";+import type { Pipeline, PromotedPipeline } from "@portal/api/pipelines";/** Sample pipelines shared by the Pipelines component stories. */@@ -33,7 +33,7 @@ export const HEALTHY_PIPELINE: Pipeline = {},{ key: "route", label: "Route / Store", ops: ["Primary store", "Notify"] },],- golden: { passing: 42, total: 42, lastRun: "1h ago" },+ golden: { passing: 42, total: 42, lastRun: "1h ago", threshold: 0.95 },drift: [],};@@ -54,7 +54,7 @@ export const DEGRADED_PIPELINE: Pipeline = {p95LatencyMs: 740,uptime: 0.9962,},- golden: { passing: 24, total: 28, lastRun: "47m ago" },+ golden: { passing: 24, total: 28, lastRun: "47m ago", threshold: 0.9 },drift: [{field: "procedure_codes",@@ -72,3 +72,31 @@ export const DEGRADED_PIPELINE: Pipeline = {},],};++/** Sample watch-folder-promoted flows for the PromotedPipelines stories. */+export const PROMOTED_PIPELINES: PromotedPipeline[] = [+ {+ id: "pl-promo-statements",+ name: "Bank Statement Normalizer",+ sourceDocType: "Bank statement",+ watchFolder: "~/StirlingWatch/statements-in",+ status: "deployed",+ promotedAt: "promoted 3d ago",+ },+ {+ id: "pl-promo-receipts",+ name: "Receipt Splitter",+ sourceDocType: "Expense receipt",+ watchFolder: "~/StirlingWatch/receipts",+ status: "staged",+ promotedAt: "promoted 11h ago",+ },+ {+ id: "pl-promo-onboarding",+ name: "New-Hire Packet Sorter",+ sourceDocType: "Onboarding packet",+ watchFolder: "\\\\hr-share\\NewHireScans",+ status: "review",+ promotedAt: "promoted 2h ago",+ },+];diff --git a/frontend/portal/src/components/policies/CatalogueSummary.stories.tsx b/frontend/portal/src/components/policies/CatalogueSummary.stories.tsxnew file mode 100644index 0000000000..75acb1cd2d--- /dev/null+++ b/frontend/portal/src/components/policies/CatalogueSummary.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { PoliciesResponse } from "@portal/api/policies";+import { CatalogueSummary } from "@portal/components/policies/CatalogueSummary";++const RESPONSE: PoliciesResponse = {+ summary: { active: 1, paused: 0, categories: 5, docsEnforced: 4821 },+ catalogue: [],+};++const meta: Meta<typeof CatalogueSummary> = {+ title: "Portal/Policies/CatalogueSummary",+ component: CatalogueSummary,+ parameters: { layout: "padded" },+ args: { data: RESPONSE, loading: false },+};+export default meta;+type Story = StoryObj<typeof CatalogueSummary>;++export const Default: Story = {};++/** No data yet — every tile shows the em-dash placeholder. */+export const Loading: Story = { args: { data: null, loading: true } };diff --git a/frontend/portal/src/components/policies/CatalogueSummary.tsx b/frontend/portal/src/components/policies/CatalogueSummary.tsxnew file mode 100644index 0000000000..005696da91--- /dev/null+++ b/frontend/portal/src/components/policies/CatalogueSummary.tsx@@ -0,0 +1,40 @@+import { MetricCard, MetricStrip } from "@shared/components";+import type { PoliciesResponse } from "@portal/api/policies";++interface CatalogueSummaryProps {+ data: PoliciesResponse | null;+ loading: boolean;+}++/**+ * Summary strip above the catalogue. Labels are product copy (they describe+ * what each metric is, not its value) so the strip's structure stays stable+ * across loading / ready states; only the values flow from the API.+ */+export function CatalogueSummary({ data, loading }: CatalogueSummaryProps) {+ const s = loading ? undefined : data?.summary;+ return (+ <MetricStrip>+ <MetricCard+ label="Active policies"+ value={s ? s.active : "—"}+ description="Enforcing on upload/export"+ />+ <MetricCard+ label="Paused"+ value={s ? s.paused : "—"}+ description="Configured but not firing"+ />+ <MetricCard+ label="Categories"+ value={s ? s.categories : "—"}+ description="Available to configure"+ />+ <MetricCard+ label="Docs enforced"+ value={s ? s.docsEnforced.toLocaleString() : "—"}+ description="Across active policies"+ />+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/policies/PolicyCategoryCard.stories.tsx b/frontend/portal/src/components/policies/PolicyCategoryCard.stories.tsxnew file mode 100644index 0000000000..139a88daaf--- /dev/null+++ b/frontend/portal/src/components/policies/PolicyCategoryCard.stories.tsx@@ -0,0 +1,48 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import {+ POLICY_CATEGORIES,+ POLICY_CONFIG,+ decorateForStory,+} from "@portal/components/policies/storyFixtures";+import { PolicyCategoryCard } from "@portal/components/policies/PolicyCategoryCard";++const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;+const compliance = POLICY_CATEGORIES.find((c) => c.id === "compliance")!;++const meta: Meta<typeof PolicyCategoryCard> = {+ title: "Portal/Policies/PolicyCategoryCard",+ component: PolicyCategoryCard,+ parameters: { layout: "padded" },+ args: { onOpen: () => {} },+};+export default meta;+type Story = StoryObj<typeof PolicyCategoryCard>;++/** A configured, active policy — shows live stats. */+export const Configured: Story = {+ args: {+ entry: {+ category: security,+ config: POLICY_CONFIG.security,+ policy: decorateForStory("security"),+ },+ },+};++/** Not yet set up — shows the rule chips + "Set up" affordance. */+export const NotSetUp: Story = {+ args: {+ entry: { category: security, config: POLICY_CONFIG.security, policy: null },+ },+};++/** Coming-soon category — locked and inert. */+export const ComingSoon: Story = {+ args: {+ entry: {+ category: compliance,+ config: POLICY_CONFIG.compliance,+ policy: null,+ },+ },+};diff --git a/frontend/portal/src/components/policies/PolicyCategoryCard.tsx b/frontend/portal/src/components/policies/PolicyCategoryCard.tsxnew file mode 100644index 0000000000..38e06a357a--- /dev/null+++ b/frontend/portal/src/components/policies/PolicyCategoryCard.tsx@@ -0,0 +1,100 @@+import { Card, Chip, StatusBadge, StatTile } from "@shared/components";+import type { CatalogueEntry } from "@portal/api/policies";+import { policyIcon } from "@portal/components/policies/policyIcons";+import "@portal/views/Policies.css";++interface PolicyCategoryCardProps {+ entry: CatalogueEntry;+ onOpen: (entry: CatalogueEntry) => void;+}++/**+ * One card per policy category. Configured categories show the live status ++ * stats and open the detail panel; unconfigured ones show the summary + a+ * "Set up" affordance; coming-soon categories render locked and inert.+ */+export function PolicyCategoryCard({ entry, onOpen }: PolicyCategoryCardProps) {+ const { category, config, policy } = entry;+ const comingSoon = category.comingSoon === true;+ const openable = !comingSoon;+ const status = policy?.state.status;++ return (+ <Card+ className={+ "portal-policies__card" ++ (comingSoon ? " portal-policies__card--locked" : "")+ }+ interactive={openable}+ onClick={openable ? () => onOpen(entry) : undefined}+ role={openable ? "button" : undefined}+ tabIndex={openable ? 0 : undefined}+ onKeyDown={+ openable+ ? (e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onOpen(entry);+ }+ }+ : undefined+ }+ >+ <header className="portal-policies__card-head">+ <span+ className={`portal-policies__cat-icon portal-policies__cat-icon--${category.tone}`}+ aria-hidden+ >+ {policyIcon(category.icon)}+ </span>+ <div className="portal-policies__card-titles">+ <h2 className="portal-policies__card-title">{category.label}</h2>+ <span className="portal-policies__card-blurb">{category.desc}</span>+ </div>+ {comingSoon ? (+ <Chip tone="neutral" size="sm">+ Coming soon+ </Chip>+ ) : policy ? (+ <StatusBadge+ tone={status === "paused" ? "warning" : "success"}+ size="sm"+ pulse={status !== "paused"}+ >+ {status === "paused" ? "Paused" : "Active"}+ </StatusBadge>+ ) : (+ <Chip tone="blue" size="sm">+ Not set up+ </Chip>+ )}+ </header>++ <p className="portal-policies__card-summary">{config.summary}</p>++ {policy ? (+ <footer className="portal-policies__card-stats">+ <StatTile+ label="Docs enforced"+ value={policy.stats.enforced.toLocaleString()}+ />+ <StatTile label="Data processed" value={policy.stats.dataProcessed} />+ <StatTile label="Active" value={policy.stats.activeFor} />+ </footer>+ ) : (+ <footer className="portal-policies__card-foot">+ <div className="portal-policies__card-rules">+ {config.rules.slice(0, 3).map((rule) => (+ <Chip key={rule} tone="neutral" size="sm">+ {rule}+ </Chip>+ ))}+ </div>+ {!comingSoon && (+ <span className="portal-policies__card-cta">Set up →</span>+ )}+ </footer>+ )}+ </Card>+ );+}diff --git a/frontend/portal/src/components/policies/PolicyDetailPanel.stories.tsx b/frontend/portal/src/components/policies/PolicyDetailPanel.stories.tsxnew file mode 100644index 0000000000..215c319ba4--- /dev/null+++ b/frontend/portal/src/components/policies/PolicyDetailPanel.stories.tsx@@ -0,0 +1,45 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { decorateForStory } from "@portal/components/policies/storyFixtures";+import { PolicyDetailPanel } from "@portal/components/policies/PolicyDetailPanel";++const meta: Meta<typeof PolicyDetailPanel> = {+ title: "Portal/Policies/PolicyDetailPanel",+ component: PolicyDetailPanel,+ parameters: { layout: "fullscreen" },+ args: {+ onClose: () => {},+ onEdit: () => {},+ onRun: () => {},+ onTogglePause: () => {},+ onDelete: () => {},+ },+};+export default meta;+type Story = StoryObj<typeof PolicyDetailPanel>;++/** An active built-in policy — Delete is hidden (default policies aren't deletable). */+export const Active: Story = {+ args: { policy: decorateForStory("security") },+};++/** A paused policy — the action reads "Resume". */+export const Paused: Story = {+ args: {+ policy: {+ ...decorateForStory("security"),+ state: { ...decorateForStory("security").state, status: "paused" },+ },+ },+};++/** A custom (deletable) policy with no runs yet — empty activity feed. */+export const CustomNoActivity: Story = {+ args: {+ policy: {+ ...decorateForStory("security"),+ state: { ...decorateForStory("security").state, isDefault: false },+ activity: [],+ stats: { enforced: 0, dataProcessed: "0 B", activeFor: "—" },+ },+ },+};diff --git a/frontend/portal/src/components/policies/PolicyDetailPanel.tsx b/frontend/portal/src/components/policies/PolicyDetailPanel.tsxnew file mode 100644index 0000000000..da0fa06e39--- /dev/null+++ b/frontend/portal/src/components/policies/PolicyDetailPanel.tsx@@ -0,0 +1,206 @@+import {+ Banner,+ Button,+ Card,+ Chip,+ EmptyState,+ Modal,+ StatTile,+ StatusBadge,+} from "@shared/components";+import { humanizeEndpoint, type DecoratedPolicy } from "@portal/api/policies";+import { policyIcon } from "@portal/components/policies/policyIcons";+import "@portal/views/Policies.css";++interface PolicyDetailPanelProps {+ /** The configured policy being viewed, or null when closed. */+ policy: DecoratedPolicy | null;+ /** Whether a lifecycle action (run/pause/delete) is in flight. */+ busy?: boolean;+ onClose: () => void;+ onEdit: () => void;+ onRun: () => void;+ onTogglePause: () => void;+ onDelete: () => void;+}++const ACTIVITY_TONE = {+ enforced: "success",+ flagged: "warning",+ processing: "info",+} as const;++/**+ * Narrative view for a configured policy: the enforced tool chain, recent+ * activity, summary stats, and the lifecycle actions (run now, pause/resume,+ * delete). Built-in (default) policies hide Delete — they're configurable but+ * not deletable, matching the backend.+ */+export function PolicyDetailPanel({+ policy,+ busy = false,+ onClose,+ onEdit,+ onRun,+ onTogglePause,+ onDelete,+}: PolicyDetailPanelProps) {+ if (!policy) return null;+ const { category, config, state, steps, stats, activity } = policy;+ const isPaused = state.status === "paused";+ const canDelete = state.isDefault !== true;+ const enforceItems = steps.length > 0 ? steps.map((s) => s.operation) : [];++ return (+ <Modal+ open+ onClose={onClose}+ width="lg"+ title={+ <span className="portal-policies__wizard-title">+ <span+ className={`portal-policies__cat-icon portal-policies__cat-icon--${category.tone}`}+ aria-hidden+ >+ {policyIcon(category.icon)}+ </span>+ {category.label} policy+ </span>+ }+ subtitle={config.summary}+ footer={+ <div className="portal-policies__detail-foot">+ {canDelete && (+ <Button+ variant="ghost"+ accent="red"+ size="sm"+ onClick={onDelete}+ disabled={busy}+ style={{ marginRight: "auto" }}+ >+ Delete+ </Button>+ )}+ <Button+ variant="outline"+ size="sm"+ onClick={onRun}+ disabled={busy}+ style={canDelete ? undefined : { marginRight: "auto" }}+ >+ Run now+ </Button>+ <Button+ variant="outline"+ size="sm"+ onClick={onTogglePause}+ disabled={busy}+ >+ {isPaused ? "Resume" : "Pause"}+ </Button>+ <Button size="sm" onClick={onEdit} disabled={busy}>+ Edit settings+ </Button>+ </div>+ }+ >+ <div className="portal-policies__detail-status">+ <StatusBadge tone={isPaused ? "warning" : "success"} pulse={!isPaused}>+ {isPaused ? "Paused" : "Active"}+ </StatusBadge>+ <span className="portal-policies__detail-meta">+ Runs on {state.runOn ?? "upload"} · output{" "}+ {state.outputMode === "new_file"+ ? "as a new file"+ : "as a new version"}+ </span>+ </div>++ <h3 className="portal-policies__wizard-heading">Enforces</h3>+ <Card padding="default">+ {enforceItems.length > 0 ? (+ <div className="portal-policies__enforce-flow">+ {enforceItems.map((op, i) => (+ <span key={op} className="portal-policies__enforce-item">+ {i > 0 && (+ <span className="portal-policies__enforce-arrow" aria-hidden>+ →+ </span>+ )}+ <Chip tone="blue" size="sm">+ {humanizeEndpoint(op)}+ </Chip>+ </span>+ ))}+ </div>+ ) : (+ <div className="portal-policies__enforce-flow">+ {config.rules.map((rule) => (+ <Chip key={rule} tone="neutral" size="sm">+ {rule}+ </Chip>+ ))}+ </div>+ )}+ <p className="portal-policies__enforce-note">+ {config.scopeLabel} · originals stay untouched, the enforced version+ is saved alongside.+ </p>+ </Card>++ <h3 className="portal-policies__wizard-heading">Recent activity</h3>+ {activity.length > 0 ? (+ <Card padding="none">+ {activity.map((item, i) => (+ <div+ key={`${item.doc}-${i}`}+ className="portal-policies__activity-row"+ >+ <span+ className={`portal-policies__activity-dot portal-policies__activity-dot--${ACTIVITY_TONE[item.status]}`}+ aria-hidden+ />+ <span className="portal-policies__activity-text">+ <span className="portal-policies__activity-doc">+ {item.doc}+ </span>+ <span className="portal-policies__activity-action">+ {item.action}+ </span>+ </span>+ <span className="portal-policies__activity-time">+ {item.time}+ </span>+ </div>+ ))}+ </Card>+ ) : (+ <Card padding="default">+ <EmptyState+ size="compact"+ title="No activity yet"+ description="Documents will appear here once this policy runs."+ />+ </Card>+ )}++ <Card padding="none" className="portal-policies__detail-stats">+ <StatTile+ label="Docs enforced"+ value={stats.enforced.toLocaleString()}+ />+ <StatTile label="Data processed" value={stats.dataProcessed} />+ <StatTile label="Active" value={stats.activeFor} />+ </Card>++ {state.scopeTypes.length > 0 && (+ <Banner+ tone="neutral"+ title="Scoped"+ description={`Limited to: ${state.scopeTypes.join(", ")}`}+ />+ )}+ </Modal>+ );+}diff --git a/frontend/portal/src/components/policies/PolicyFieldRow.stories.tsx b/frontend/portal/src/components/policies/PolicyFieldRow.stories.tsxnew file mode 100644index 0000000000..e6a8a4bb4d--- /dev/null+++ b/frontend/portal/src/components/policies/PolicyFieldRow.stories.tsx@@ -0,0 +1,72 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { PolicyField } from "@portal/api/policies";+import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";++const meta: Meta<typeof PolicyFieldRow> = {+ title: "Portal/Policies/PolicyFieldRow",+ component: PolicyFieldRow,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof PolicyFieldRow>;++/** Renders the field and keeps its value in local state, exercising onChange. */+function Controlled({ field }: { field: PolicyField }) {+ const [value, setValue] = useState(field.value);+ return <PolicyFieldRow field={field} value={value} onChange={setValue} />;+}++export const Toggle: Story = {+ render: () => (+ <Controlled+ field={{+ key: "auditTrail",+ label: "Audit trail",+ type: "toggle",+ value: true,+ }}+ />+ ),+};++export const Select: Story = {+ render: () => (+ <Controlled+ field={{+ key: "keepFor",+ label: "Keep for",+ type: "select",+ value: "7 years",+ options: ["30 days", "1 year", "7 years", "Indefinite"],+ }}+ />+ ),+};++export const Chips: Story = {+ render: () => (+ <Controlled+ field={{+ key: "frameworks",+ label: "Frameworks",+ type: "chips",+ value: ["HIPAA"],+ options: ["HIPAA", "GDPR", "SOC 2", "FedRAMP"],+ }}+ />+ ),+};++export const Text: Story = {+ render: () => (+ <Controlled+ field={{+ key: "webhookUrl",+ label: "Webhook URL",+ type: "text",+ value: "",+ }}+ />+ ),+};diff --git a/frontend/portal/src/components/policies/PolicyFieldRow.tsx b/frontend/portal/src/components/policies/PolicyFieldRow.tsxnew file mode 100644index 0000000000..7cfd295072--- /dev/null+++ b/frontend/portal/src/components/policies/PolicyFieldRow.tsx@@ -0,0 +1,88 @@+import {+ Chip,+ FormField,+ Input,+ Select,+ ToggleSwitch,+} from "@shared/components";+import type { PolicyField } from "@portal/api/policies";+import "@portal/views/Policies.css";++interface PolicyFieldRowProps {+ field: PolicyField;+ /** Effective current value (override or definition default). */+ value: boolean | string | string[];+ onChange: (value: boolean | string | string[]) => void;+}++/**+ * Renders one policy setting from the catalogue's `PolicyField`, dispatching on+ * `type`: toggle → ToggleSwitch, select → Select, chips → multi-select Chips,+ * text → Input. Controlled — the setup flow owns the value.+ */+export function PolicyFieldRow({+ field,+ value,+ onChange,+}: PolicyFieldRowProps) {+ if (field.type === "toggle") {+ return (+ <div className="portal-policies__toggle-row">+ <ToggleSwitch+ checked={Boolean(value)}+ onChange={onChange}+ label={field.label}+ />+ </div>+ );+ }++ 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 (+ <FormField label={field.label}>+ <div className="portal-policies__field-chips">+ {(field.options ?? []).map((opt) => (+ <Chip+ key={opt}+ tone={selected.includes(opt) ? "blue" : "neutral"}+ size="sm"+ onClick={() => toggle(opt)}+ >+ {opt}+ </Chip>+ ))}+ </div>+ </FormField>+ );+ }++ if (field.type === "select") {+ return (+ <FormField label={field.label}>+ <Select+ inputSize="sm"+ value={typeof value === "string" ? value : ""}+ options={(field.options ?? []).map((o) => ({ value: o, label: o }))}+ onChange={(e) => onChange(e.target.value)}+ />+ </FormField>+ );+ }++ return (+ <FormField label={field.label}>+ <Input+ inputSize="sm"+ value={typeof value === "string" ? value : ""}+ onChange={(e) => onChange(e.target.value)}+ />+ </FormField>+ );+}diff --git a/frontend/portal/src/components/policies/PolicySetupWizard.stories.tsx b/frontend/portal/src/components/policies/PolicySetupWizard.stories.tsxnew file mode 100644index 0000000000..275a8c9d15--- /dev/null+++ b/frontend/portal/src/components/policies/PolicySetupWizard.stories.tsx@@ -0,0 +1,39 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import {+ POLICY_CATEGORIES,+ POLICY_CONFIG,+ decorateForStory,+} from "@portal/components/policies/storyFixtures";+import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";++const security = POLICY_CATEGORIES.find((c) => c.id === "security")!;++const meta: Meta<typeof PolicySetupWizard> = {+ title: "Portal/Policies/PolicySetupWizard",+ component: PolicySetupWizard,+ parameters: { layout: "fullscreen" },+ args: {+ onClose: () => {},+ onSubmit: async () => {},+ },+};+export default meta;+type Story = StoryObj<typeof PolicySetupWizard>;++/** First-time setup — seeded from the category's preset tool chain. */+export const Create: Story = {+ args: {+ entry: { category: security, config: POLICY_CONFIG.security, policy: null },+ },+};++/** Editing a configured policy — pre-filled from its saved steps + settings. */+export const Edit: Story = {+ args: {+ entry: {+ category: security,+ config: POLICY_CONFIG.security,+ policy: decorateForStory("security"),+ },+ },+};diff --git a/frontend/portal/src/components/policies/PolicySetupWizard.tsx b/frontend/portal/src/components/policies/PolicySetupWizard.tsxnew file mode 100644index 0000000000..35df6b8a3d--- /dev/null+++ b/frontend/portal/src/components/policies/PolicySetupWizard.tsx@@ -0,0 +1,461 @@+import { useMemo, useState } from "react";+import {+ Banner,+ Button,+ Card,+ Chip,+ FormField,+ Input,+ Modal,+ Select,+ Tabs,+ ToggleSwitch,+} from "@shared/components";+import {+ POLICY_DOC_TYPES,+ POLICY_SOURCES,+ humanizeEndpoint,+ type CatalogueEntry,+ type PipelineStep,+ type PolicySetupResult,+} from "@portal/api/policies";+import { PolicyFieldRow } from "@portal/components/policies/PolicyFieldRow";+import { policyIcon } from "@portal/components/policies/policyIcons";+import "@portal/views/Policies.css";++interface PolicySetupWizardProps {+ /** The category being configured, or null when closed. */+ entry: CatalogueEntry | null;+ onClose: () => void;+ /**+ * Fires on submit with the collected settings + built pipeline steps. May be+ * async; if it rejects the wizard re-enables submit and surfaces the failure.+ */+ onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;+}++type Step = "workflow" | "settings";++/** A configurable tool in the workflow step: whether it runs + its params. */+interface ToolState {+ operation: string;+ enabled: boolean;+ parameters: Record<string, unknown>;+}++/** Resolve each field's effective value: saved override, else definition default. */+function resolveFieldValues(+ entry: CatalogueEntry,+): Record<string, boolean | string | string[]> {+ const saved = entry.policy?.state.fieldValues ?? {};+ const out: Record<string, boolean | string | string[]> = {};+ for (const f of entry.config.fields) out[f.key] = saved[f.key] ?? f.value;+ return out;+}++/**+ * Seed the workflow's tools. A configured policy's saved steps win (so editing+ * round-trips); otherwise the category preset's default chain. Each preset step+ * starts enabled — the user toggles tools off in the workflow.+ */+function seedTools(entry: CatalogueEntry): ToolState[] {+ const source = entry.policy?.steps?.length+ ? entry.policy.steps+ : entry.config.defaultOperations;+ return source.map((s) => ({+ operation: s.operation,+ enabled: true,+ parameters: s.parameters,+ }));+}++/**+ * The real "set up a policy" flow, mirroring the editor wizard: a Workflow step+ * (the tool chain — toggle which tools run) and a Settings step (policy fields,+ * sources, scope, reviewer, output/run). Submitting builds the pipeline steps+ * (each `operation` an endpoint path) and persists via the real POST.+ */+export function PolicySetupWizard({+ entry,+ onClose,+ onSubmit,+}: PolicySetupWizardProps) {+ // Re-key the wizard on the opened category so all state resets cleanly when a+ // different category is opened (avoids stale field values bleeding across).+ return entry ? (+ <PolicySetupWizardBody+ key={entry.category.id}+ entry={entry}+ onClose={onClose}+ onSubmit={onSubmit}+ />+ ) : null;+}++function PolicySetupWizardBody({+ entry,+ onClose,+ onSubmit,+}: {+ entry: CatalogueEntry;+ onClose: () => void;+ onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;+}) {+ const { category, config, policy } = entry;+ const isEdit = policy != null;++ const [step, setStep] = useState<Step>("workflow");+ const [tools, setTools] = useState<ToolState[]>(() => seedTools(entry));+ const [fieldValues, setFieldValues] = useState(() =>+ resolveFieldValues(entry),+ );+ const [sources, setSources] = useState<string[]>(+ policy?.state.sources.length ? policy.state.sources : ["editor"],+ );+ const [scopeNarrow, setScopeNarrow] = useState(+ (policy?.state.scopeTypes.length ?? 0) > 0,+ );+ const [scopeTypes, setScopeTypes] = useState<string[]>(+ policy?.state.scopeTypes ?? [],+ );+ const [reviewerEmail, setReviewerEmail] = useState(+ policy?.state.reviewerEmail ?? "[email protected]",+ );+ const [outputMode, setOutputMode] = useState<"new_file" | "new_version">(+ policy?.state.outputMode ?? "new_version",+ );+ const [outputName, setOutputName] = useState(policy?.state.outputName ?? "");+ const [outputNamePosition, setOutputNamePosition] = useState<+ "prefix" | "suffix" | "auto-number"+ >("suffix");+ const [runOn, setRunOn] = useState<"upload" | "export">(+ policy?.state.runOn ?? "upload",+ );++ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const enabledTools = useMemo(() => tools.filter((tl) => tl.enabled), [tools]);++ function patchTool(operation: string, patch: Partial<ToolState>) {+ setTools((prev) =>+ prev.map((tl) => (tl.operation === operation ? { ...tl, ...patch } : tl)),+ );+ }++ function toggleSource(id: string) {+ setSources((prev) =>+ prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id],+ );+ }++ function toggleScopeType(dt: string) {+ setScopeTypes((prev) =>+ prev.includes(dt) ? prev.filter((d) => d !== dt) : [...prev, dt],+ );+ }++ async function submit() {+ if (submitting) return;+ if (enabledTools.length === 0) {+ setError("Enable at least one tool in the workflow first.");+ setStep("workflow");+ return;+ }+ setError(null);+ setSubmitting(true);+ const steps: PipelineStep[] = enabledTools.map((tl) => ({+ operation: tl.operation,+ parameters: tl.parameters,+ }));+ try {+ await onSubmit(entry, {+ fieldValues,+ sources,+ scopeTypes: scopeNarrow ? scopeTypes : [],+ reviewerEmail,+ outputMode,+ outputName: outputName.trim(),+ outputNamePosition,+ runOn,+ steps,+ });+ } catch {+ setSubmitting(false);+ setError("Couldn't save the policy. Please try again.");+ }+ }++ const docTypesEnabled = category.providesClassification === true;++ return (+ <Modal+ open+ onClose={onClose}+ width="lg"+ title={+ <span className="portal-policies__wizard-title">+ <span+ className={`portal-policies__cat-icon portal-policies__cat-icon--${category.tone}`}+ aria-hidden+ >+ {policyIcon(category.icon)}+ </span>+ {isEdit+ ? `Edit ${category.label} policy`+ : `Set up ${category.label} policy`}+ </span>+ }+ subtitle={config.summary}+ footer={+ <div className="portal-policies__wizard-foot">+ <Button variant="ghost" size="sm" onClick={onClose}>+ Cancel+ </Button>+ {step === "workflow" ? (+ <Button+ size="sm"+ style={{ marginLeft: "auto" }}+ onClick={() => setStep("settings")}+ >+ Continue+ </Button>+ ) : (+ <>+ <Button+ variant="outline"+ size="sm"+ style={{ marginLeft: "auto" }}+ onClick={() => setStep("workflow")}+ >+ Back+ </Button>+ <Button size="sm" onClick={submit} loading={submitting}>+ {isEdit ? "Save changes" : "Enable policy"}+ </Button>+ </>+ )}+ </div>+ }+ >+ <Tabs+ variant="underline"+ ariaLabel="Setup steps"+ activeKey={step}+ onChange={(k) => setStep(k as Step)}+ items={[+ { key: "workflow", label: "Workflow" },+ { key: "settings", label: "Settings" },+ ]}+ />++ {error && (+ <Banner+ tone="danger"+ description={error}+ className="portal-policies__wizard-banner"+ />+ )}++ {step === "workflow" && (+ <div className="portal-policies__wizard-section">+ <p className="portal-policies__wizard-desc">+ The sequence of tools this policy runs on each document. Each tool+ is a Stirling endpoint; toggle the ones this policy should enforce.+ </p>+ {tools.map((tl) => (+ <Card key={tl.operation} padding="tight">+ <div className="portal-policies__tool-head">+ <span className="portal-policies__tool-name">+ {humanizeEndpoint(tl.operation)}+ </span>+ <code className="portal-policies__tool-endpoint">+ {tl.operation}+ </code>+ <ToggleSwitch+ size="sm"+ checked={tl.enabled}+ onChange={(checked) =>+ patchTool(tl.operation, { enabled: checked })+ }+ label=""+ />+ </div>+ </Card>+ ))}+ </div>+ )}++ {step === "settings" && (+ <div className="portal-policies__wizard-section">+ {config.fields.length > 0 && (+ <>+ <h3 className="portal-policies__wizard-heading">Settings</h3>+ <div className="portal-policies__fields">+ {config.fields.map((field) => (+ <PolicyFieldRow+ key={field.key}+ field={field}+ value={fieldValues[field.key]}+ onChange={(v) =>+ setFieldValues((prev) => ({ ...prev, [field.key]: v }))+ }+ />+ ))}+ </div>+ </>+ )}++ <h3 className="portal-policies__wizard-heading">Sources</h3>+ <div className="portal-policies__sources">+ {POLICY_SOURCES.map((src) => (+ <button+ key={src.id}+ type="button"+ className={+ "portal-policies__source" ++ (sources.includes(src.id)+ ? " portal-policies__source--on"+ : "")+ }+ onClick={() => toggleSource(src.id)}+ >+ <span className="portal-policies__source-icon" aria-hidden>+ {policyIcon(src.icon)}+ </span>+ <span className="portal-policies__source-text">+ <span className="portal-policies__source-label">+ {src.label}+ </span>+ <span className="portal-policies__source-desc">+ {src.desc}+ </span>+ </span>+ </button>+ ))}+ </div>++ <h3 className="portal-policies__wizard-heading">Document types</h3>+ {!docTypesEnabled ? (+ <Banner+ tone="neutral"+ title="All document types"+ description="Set up an Ingestion (classification) policy to narrow this to specific document types."+ />+ ) : (+ <Card padding="tight">+ <div className="portal-policies__doctypes-head">+ <span>+ {scopeTypes.length === 0+ ? "All document types"+ : `${scopeTypes.length} selected`}+ </span>+ <button+ type="button"+ className="portal-policies__link"+ onClick={() => setScopeNarrow((v) => !v)}+ >+ {scopeNarrow ? "Clear" : "Narrow"}+ </button>+ </div>+ {scopeNarrow && (+ <div className="portal-policies__doctypes">+ {POLICY_DOC_TYPES.map((dt) => (+ <Chip+ key={dt}+ tone={scopeTypes.includes(dt) ? "blue" : "neutral"}+ size="sm"+ onClick={() => toggleScopeType(dt)}+ >+ {dt}+ </Chip>+ ))}+ </div>+ )}+ </Card>+ )}++ <h3 className="portal-policies__wizard-heading">Output & run</h3>+ <div className="portal-policies__fields">+ <FormField+ label="Run on"+ helperText="When the policy fires: on upload, or before export."+ >+ <Select+ inputSize="sm"+ value={runOn}+ onChange={(e) =>+ setRunOn(e.target.value as "upload" | "export")+ }+ options={[+ { value: "upload", label: "Upload" },+ { value: "export", label: "Export" },+ ]}+ />+ </FormField>+ <FormField label="Output as">+ <Select+ inputSize="sm"+ value={outputMode}+ onChange={(e) => {+ const mode = e.target.value as "new_file" | "new_version";+ setOutputMode(mode);+ // Auto-number only applies to separate new files.+ if (+ mode === "new_version" &&+ outputNamePosition === "auto-number"+ ) {+ setOutputNamePosition("suffix");+ }+ }}+ options={[+ { value: "new_version", label: "New version" },+ { value: "new_file", label: "New file" },+ ]}+ />+ </FormField>+ <FormField label="Filename rule">+ <div className="portal-policies__name-row">+ <Select+ inputSize="sm"+ value={outputNamePosition}+ onChange={(e) =>+ setOutputNamePosition(+ e.target.value as "prefix" | "suffix" | "auto-number",+ )+ }+ options={[+ { value: "prefix", label: "Prefix" },+ { value: "suffix", label: "Suffix" },+ ...(outputMode === "new_file"+ ? [{ value: "auto-number", label: "Auto-number" }]+ : []),+ ]}+ />+ {outputNamePosition !== "auto-number" && (+ <Input+ inputSize="sm"+ value={outputName}+ placeholder="Text to add (optional)"+ onChange={(e) => setOutputName(e.target.value)}+ />+ )}+ </div>+ </FormField>+ <FormField+ label="Reviewer email"+ helperText="Low-confidence enforcements are routed here for review."+ >+ <Input+ inputSize="sm"+ type="email"+ value={reviewerEmail}+ onChange={(e) => setReviewerEmail(e.target.value)}+ />+ </FormField>+ </div>+ </div>+ )}+ </Modal>+ );+}diff --git a/frontend/portal/src/components/policies/policyIcons.ts b/frontend/portal/src/components/policies/policyIcons.tsnew file mode 100644index 0000000000..5ab6113b49--- /dev/null+++ b/frontend/portal/src/components/policies/policyIcons.ts@@ -0,0 +1,25 @@+/**+ * Glyphs for the policy catalogue's string icon keys. The catalogue model+ * carries semantic keys (e.g. "shield", "layers") rather than React nodes so+ * the data stays portable; the portal owns the rendering and maps each key to a+ * glyph here.+ */+export const POLICY_ICON_GLYPHS: Record<string, string> = {+ layers: "▤",+ shield: "🛡",+ check: "✓",+ route: "⇉",+ clock: "⏲",+ // Source icons.+ file: "▢",+ device: "▣",+ globe: "◍",+ cloud: "☁",+ mail: "✉",+ folder: "▤",+};++/** Resolve an icon key to its glyph, falling back to a neutral dot. */+export function policyIcon(key: string): string {+ return POLICY_ICON_GLYPHS[key] ?? "•";+}diff --git a/frontend/portal/src/components/policies/storyFixtures.ts b/frontend/portal/src/components/policies/storyFixtures.tsnew file mode 100644index 0000000000..ec1c3ddffe--- /dev/null+++ b/frontend/portal/src/components/policies/storyFixtures.ts@@ -0,0 +1,40 @@+/**+ * Shared fixtures for the policy component stories — a configured, decorated+ * policy built straight from the catalogue + seed data, so stories render the+ * same shapes the MSW handlers serve without standing up the whole API.+ */+import {+ POLICY_CATEGORIES,+ POLICY_CONFIG,+ seedRuntime,+ type DecoratedPolicy,+} from "@portal/mocks/policies";++export { POLICY_CATEGORIES, POLICY_CONFIG };++/** A decorated, active policy for a category, mirroring the handler's decorate(). */+export function decorateForStory(categoryId: string): DecoratedPolicy {+ const category = POLICY_CATEGORIES.find((c) => c.id === categoryId)!;+ const config = POLICY_CONFIG[categoryId];+ const rt = seedRuntime().pol_security_default;+ return {+ category,+ config,+ state: {+ configured: true,+ status: "active",+ sources: ["editor"],+ scopeTypes: [],+ reviewerEmail: rt.reviewerEmail,+ fieldValues: {},+ outputMode: "new_version",+ outputName: "",+ runOn: "upload",+ backendId: "pol_story",+ isDefault: true,+ },+ steps: config.defaultOperations,+ stats: rt.stats,+ activity: rt.activity,+ };+}diff --git a/frontend/portal/src/components/users/AccessControls.stories.tsx b/frontend/portal/src/components/users/AccessControls.stories.tsxnew file mode 100644index 0000000000..45f69ec8a3--- /dev/null+++ b/frontend/portal/src/components/users/AccessControls.stories.tsx@@ -0,0 +1,26 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { accessFor } from "@portal/mocks/users";+import { AccessControls } from "@portal/components/users/AccessControls";++const meta: Meta<typeof AccessControls> = {+ title: "Portal/Users/AccessControls",+ component: AccessControls,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof AccessControls>;++/** Free: seat limit + upgrade nudge only. */+export const Free: Story = {+ args: { access: accessFor("free") },+};++/** Pro: adds self-service MFA + session toggles. */+export const Pro: Story = {+ args: { access: accessFor("pro") },+};++/** Enterprise: SSO/SAML, SCIM provisioning and enforced MFA. */+export const Enterprise: Story = {+ args: { access: accessFor("enterprise") },+};diff --git a/frontend/portal/src/components/users/AccessControls.tsx b/frontend/portal/src/components/users/AccessControls.tsxnew file mode 100644index 0000000000..ede0720e94--- /dev/null+++ b/frontend/portal/src/components/users/AccessControls.tsx@@ -0,0 +1,171 @@+import { useState } from "react";+import {+ Banner,+ Button,+ Card,+ ProgressBar,+ StatTile,+ StatusBadge,+ ToggleSwitch,+} from "@shared/components";+import type { AccessControls as Access } from "@portal/api/users";+import { seatsLabel } from "@portal/components/users/format";+import "@portal/views/Users.css";++interface AccessControlsProps {+ access: Access;+}++/**+ * Access posture for the org, scaling by tier:+ * free — seat limit + upgrade nudge only+ * pro — adds self-service MFA + session timeout toggles+ * enterprise — adds SSO/SAML, SCIM provisioning and enforced MFA+ *+ * Toggles hold local state only; persisting them is a backend wiring task.+ */+export function AccessControls({ access }: AccessControlsProps) {+ const [mfaEnforced, setMfaEnforced] = useState(access.mfaEnforced ?? false);+ const [shortSessions, setShortSessions] = useState(false);++ const seatPct =+ access.seatLimit === null+ ? 0+ : Math.min(1, access.seatsUsed / access.seatLimit);++ return (+ <section className="portal-users__access">+ <header className="portal-users__section-head">+ <h2 className="portal-users__section-title">Access & security</h2>+ <p className="portal-users__section-sub">+ Seats, authentication and provisioning for your organization.+ </p>+ </header>++ <div className="portal-users__access-grid">+ {/* Seats — shown on every tier. */}+ <Card padding="default">+ <div className="portal-users__access-card-head">+ <h3 className="portal-users__access-card-title">Seats</h3>+ <span className="portal-users__muted">+ {seatsLabel(access.seatsUsed, access.seatLimit)}+ </span>+ </div>+ {access.seatLimit === null ? (+ <p className="portal-users__access-note">+ Your plan includes unlimited seats.+ </p>+ ) : (+ <ProgressBar+ value={seatPct}+ thresholded+ label={`${access.seatsUsed} of ${access.seatLimit} seats used`}+ />+ )}+ </Card>++ {/* Pro+: MFA + sessions self-service. */}+ {access.mfaAvailable && (+ <Card padding="default">+ <h3 className="portal-users__access-card-title">Authentication</h3>+ <div className="portal-users__toggle-rows">+ <div className="portal-users__toggle-row">+ <ToggleSwitch+ checked={mfaEnforced}+ onChange={(v) => {+ setMfaEnforced(v);+ // TODO(backend): PATCH /v1/users/access { mfaEnforced }+ }}+ label="Require MFA"+ description={+ access.mfaEnforced+ ? "Enforced org-wide on this plan."+ : "Members must set up a second factor to sign in."+ }+ disabled={access.mfaEnforced}+ />+ </div>+ <div className="portal-users__toggle-row">+ <ToggleSwitch+ checked={shortSessions}+ onChange={(v) => {+ setShortSessions(v);+ // TODO(backend): PATCH /v1/users/access { sessionTimeout }+ }}+ label="Short-lived sessions"+ description={`Sign members out after inactivity (currently ${access.sessionTimeout}).`}+ />+ </div>+ </div>+ </Card>+ )}++ {/* Enterprise: SSO. */}+ {access.sso && (+ <Card padding="default">+ <div className="portal-users__access-card-head">+ <h3 className="portal-users__access-card-title">SSO / SAML</h3>+ <StatusBadge+ tone={access.sso.status === "connected" ? "success" : "neutral"}+ size="sm"+ >+ {access.sso.status === "connected"+ ? "Connected"+ : "Not configured"}+ </StatusBadge>+ </div>+ <div className="portal-users__access-stats">+ <StatTile label="Provider" value={access.sso.provider} />+ <StatTile+ label="Domains"+ value={access.sso.domains.join(", ") || "—"}+ />+ </div>+ <Button variant="ghost" size="sm">+ Manage connection+ </Button>+ </Card>+ )}++ {/* Enterprise: SCIM provisioning. */}+ {access.scim && (+ <Card padding="default">+ <div className="portal-users__access-card-head">+ <h3 className="portal-users__access-card-title">+ SCIM provisioning+ </h3>+ <StatusBadge+ tone={access.scim.enabled ? "success" : "neutral"}+ size="sm"+ >+ {access.scim.enabled ? "Active" : "Off"}+ </StatusBadge>+ </div>+ <div className="portal-users__access-stats">+ <StatTile label="Directory" value={access.scim.directory} />+ <StatTile label="Last sync" value={access.scim.lastSync} />+ </div>+ <p className="portal-users__access-note">+ Members are created, updated and deactivated automatically from+ your identity provider.+ </p>+ </Card>+ )}+ </div>++ {/* Free: upgrade nudge spans the section. */}+ {access.upgradeHint && (+ <Banner+ tone="info"+ title="Unlock team access controls"+ description={access.upgradeHint}+ action={+ <Button size="sm" accent="purple">+ Upgrade plan+ </Button>+ }+ />+ )}+ </section>+ );+}diff --git a/frontend/portal/src/components/users/InviteMemberModal.stories.tsx b/frontend/portal/src/components/users/InviteMemberModal.stories.tsxnew file mode 100644index 0000000000..cffa89d54d--- /dev/null+++ b/frontend/portal/src/components/users/InviteMemberModal.stories.tsx@@ -0,0 +1,16 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";++const meta: Meta<typeof InviteMemberModal> = {+ title: "Portal/Users/InviteMemberModal",+ component: InviteMemberModal,+ parameters: { layout: "fullscreen" },+ args: { open: true, onClose: () => {} },+};+export default meta;+type Story = StoryObj<typeof InviteMemberModal>;++/** Email + role; Send invite validates locally then closes (demo shell). */+export const Open: Story = {};++export const Closed: Story = { args: { open: false } };diff --git a/frontend/portal/src/components/users/InviteMemberModal.tsx b/frontend/portal/src/components/users/InviteMemberModal.tsxnew file mode 100644index 0000000000..78f0b7590e--- /dev/null+++ b/frontend/portal/src/components/users/InviteMemberModal.tsx@@ -0,0 +1,94 @@+import { useState } from "react";+import { Button, FormField, Input, Modal, Select } from "@shared/components";+import { type RoleId, ROLES } from "@portal/api/users";+import "@portal/views/Users.css";++interface InviteMemberModalProps {+ open: boolean;+ onClose: () => void;+}++const ROLE_SELECT_OPTIONS = ROLES.map((r) => ({+ value: r.id,+ label: r.label,+}));++/** Org Owner is reserved for transfer flows — invites default to Developer. */+const DEFAULT_ROLE: RoleId = "developer";++const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++/**+ * Invite-by-email shell. Submitting validates locally then closes without+ * sending — wiring the submit to the backend dispatches the invitation.+ */+export function InviteMemberModal({ open, onClose }: InviteMemberModalProps) {+ const [email, setEmail] = useState("");+ const [role, setRole] = useState<RoleId>(DEFAULT_ROLE);+ const [touched, setTouched] = useState(false);++ const emailValid = EMAIL_RE.test(email.trim());+ const error =+ touched && !emailValid ? "Enter a valid email address" : undefined;++ function close() {+ onClose();+ // Reset for the next open, after the close transition has finished.+ setTimeout(() => {+ setEmail("");+ setRole(DEFAULT_ROLE);+ setTouched(false);+ }, 200);+ }++ function submit() {+ setTouched(true);+ if (!emailValid) return;+ // TODO(backend): POST /v1/users/invitations { email, role } — send the+ // invite, then close on success and refetch the members list.+ close();+ }++ return (+ <Modal+ open={open}+ onClose={close}+ width="sm"+ title="Invite member"+ subtitle="They'll receive an email to join your organization."+ footer={+ <div className="portal-users__modal-footer">+ <Button variant="ghost" size="sm" onClick={close}>+ Cancel+ </Button>+ <Button size="sm" onClick={submit} disabled={touched && !emailValid}>+ Send invite+ </Button>+ </div>+ }+ >+ <div className="portal-users__invite-body">+ <FormField label="Email" error={error} required>+ <Input+ type="email"+ placeholder="[email protected]"+ value={email}+ invalid={!!error}+ onChange={(e) => setEmail(e.target.value)}+ onBlur={() => setTouched(true)}+ />+ </FormField>+ <FormField+ label="Role"+ helperText="Determines what the member can do once they join."+ >+ <Select+ options={ROLE_SELECT_OPTIONS}+ value={role}+ onChange={(e) => setRole(e.target.value as RoleId)}+ />+ </FormField>+ </div>+ </Modal>+ );+}diff --git a/frontend/portal/src/components/users/MembersTable.stories.tsx b/frontend/portal/src/components/users/MembersTable.stories.tsxnew file mode 100644index 0000000000..2420622609--- /dev/null+++ b/frontend/portal/src/components/users/MembersTable.stories.tsx@@ -0,0 +1,29 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { membersFor } from "@portal/mocks/users";+import { MembersTable } from "@portal/components/users/MembersTable";++const meta: Meta<typeof MembersTable> = {+ title: "Portal/Users/MembersTable",+ component: MembersTable,+ parameters: { layout: "padded" },+ args: {+ members: membersFor("pro"),+ onChangeRole: () => {},+ onSuspend: () => {},+ onRemove: () => {},+ },+};+export default meta;+type Story = StoryObj<typeof MembersTable>;++/** Pro roster: active members plus an invited and a suspended account. */+export const Default: Story = {};++/** Enterprise adds a Team Owner and a second pending invite. */+export const Enterprise: Story = {+ args: { members: membersFor("enterprise") },+};++export const Free: Story = {+ args: { members: membersFor("free") },+};diff --git a/frontend/portal/src/components/users/MembersTable.tsx b/frontend/portal/src/components/users/MembersTable.tsxnew file mode 100644index 0000000000..2d15727758--- /dev/null+++ b/frontend/portal/src/components/users/MembersTable.tsx@@ -0,0 +1,142 @@+import { useMemo } from "react";+import { Menu } from "@mantine/core";+import {+ Avatar,+ Chip,+ StatusBadge,+ Table,+ type TableColumn,+} from "@shared/components";+import {+ type Member,+ type RoleId,+ MEMBER_STATUS_TONE,+ ROLE_LABEL,+ ROLE_TONE,+} from "@portal/api/users";+import { avatarToneForRole } from "@portal/components/users/format";+import "@portal/views/Users.css";++interface MembersTableProps {+ members: Member[];+ /** Row actions. Each submits to the backend via the view's handlers. */+ onChangeRole: (member: Member, role: RoleId) => void;+ onSuspend: (member: Member) => void;+ onRemove: (member: Member) => void;+}++/** Roles a member can be reassigned to, in catalogue order. */+const ROLE_OPTIONS = Object.keys(ROLE_LABEL) as RoleId[];++export function MembersTable({+ members,+ onChangeRole,+ onSuspend,+ onRemove,+}: MembersTableProps) {+ const columns = useMemo<TableColumn<Member>[]>(+ () => [+ {+ key: "name",+ header: "Member",+ render: (m) => (+ <div className="portal-users__member-cell">+ <Avatar+ name={m.name}+ src={m.avatarUrl}+ size="sm"+ tone={avatarToneForRole(m.role)}+ />+ <div className="portal-users__member-text">+ <strong>{m.name}</strong>+ {/* Invited rows seed the name with the email, so don't repeat it. */}+ {m.email !== m.name && (+ <span className="portal-users__muted">{m.email}</span>+ )}+ </div>+ </div>+ ),+ },+ {+ key: "role",+ header: "Role",+ render: (m) => (+ <Chip tone={ROLE_TONE[m.role]} size="sm">+ {ROLE_LABEL[m.role]}+ </Chip>+ ),+ },+ {+ key: "status",+ header: "Status",+ render: (m) => (+ <StatusBadge+ tone={MEMBER_STATUS_TONE[m.status]}+ size="sm"+ pulse={m.status === "active"}+ >+ {m.status}+ </StatusBadge>+ ),+ },+ {+ key: "lastActive",+ header: "Last active",+ render: (m) => (+ <span className="portal-users__muted">{m.lastActive}</span>+ ),+ },+ {+ key: "actions",+ header: "",+ align: "right",+ width: "3rem",+ render: (m) => (+ // Mantine Menu owns the focus trap + roving arrow-key navigation that+ // a row-action menu needs; SUI has no equivalent.+ <Menu position="bottom-end" withinPortal shadow="md" width={200}>+ <Menu.Target>+ <button+ type="button"+ className="portal-users__row-action"+ aria-label={`Actions for ${m.name}`}+ onClick={(e) => e.stopPropagation()}+ >+ ⋯+ </button>+ </Menu.Target>+ <Menu.Dropdown>+ <Menu.Label>Change role</Menu.Label>+ {ROLE_OPTIONS.map((role) => (+ <Menu.Item+ key={role}+ disabled={role === m.role}+ onClick={() => onChangeRole(m, role)}+ >+ {ROLE_LABEL[role]}+ </Menu.Item>+ ))}+ <Menu.Divider />+ {m.status !== "suspended" && (+ <Menu.Item onClick={() => onSuspend(m)}>Suspend</Menu.Item>+ )}+ <Menu.Item color="red" onClick={() => onRemove(m)}>+ Remove from org+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ ),+ },+ ],+ [onChangeRole, onSuspend, onRemove],+ );++ return (+ <Table<Member>+ className="portal-users__table"+ columns={columns}+ rows={members}+ rowKey={(m) => m.id}+ />+ );+}diff --git a/frontend/portal/src/components/users/RolesGrid.stories.tsx b/frontend/portal/src/components/users/RolesGrid.stories.tsxnew file mode 100644index 0000000000..386e61fc99--- /dev/null+++ b/frontend/portal/src/components/users/RolesGrid.stories.tsx@@ -0,0 +1,15 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ROLES } from "@portal/mocks/users";+import { RolesGrid } from "@portal/components/users/RolesGrid";++const meta: Meta<typeof RolesGrid> = {+ title: "Portal/Users/RolesGrid",+ component: RolesGrid,+ parameters: { layout: "padded" },+ args: { roles: ROLES },+};+export default meta;+type Story = StoryObj<typeof RolesGrid>;++/** The five org roles, most → least privileged. */+export const Default: Story = {};diff --git a/frontend/portal/src/components/users/RolesGrid.tsx b/frontend/portal/src/components/users/RolesGrid.tsxnew file mode 100644index 0000000000..8c7ca7a8d5--- /dev/null+++ b/frontend/portal/src/components/users/RolesGrid.tsx@@ -0,0 +1,39 @@+import { Card, Chip } from "@shared/components";+import type { Role } from "@portal/api/users";+import "@portal/views/Users.css";++interface RolesGridProps {+ roles: Role[];+}++/** Reference catalogue of the org roles and what each one can do. */+export function RolesGrid({ roles }: RolesGridProps) {+ return (+ <section className="portal-users__roles">+ <header className="portal-users__section-head">+ <h2 className="portal-users__section-title">Roles</h2>+ <p className="portal-users__section-sub">+ Every role exists on every plan — what each one can do is fixed across+ the org.+ </p>+ </header>+ <div className="portal-users__roles-grid">+ {roles.map((role) => (+ <Card key={role.id} padding="default" className="portal-users__role">+ <div className="portal-users__role-head">+ <Chip tone={role.tone} size="sm">+ {role.label}+ </Chip>+ </div>+ <p className="portal-users__role-summary">{role.summary}</p>+ <ul className="portal-users__role-perms">+ {role.permissions.map((perm) => (+ <li key={perm}>{perm}</li>+ ))}+ </ul>+ </Card>+ ))}+ </div>+ </section>+ );+}diff --git a/frontend/portal/src/components/users/UsersSummaryStrip.stories.tsx b/frontend/portal/src/components/users/UsersSummaryStrip.stories.tsxnew file mode 100644index 0000000000..d1e44ff72b--- /dev/null+++ b/frontend/portal/src/components/users/UsersSummaryStrip.stories.tsx@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildUsersResponse } from "@portal/mocks/users";+import { UsersSummaryStrip } from "@portal/components/users/UsersSummaryStrip";++const meta: Meta<typeof UsersSummaryStrip> = {+ title: "Portal/Users/UsersSummaryStrip",+ component: UsersSummaryStrip,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof UsersSummaryStrip>;++export const Pro: Story = {+ args: { data: buildUsersResponse("pro"), loading: false },+};++/** Enterprise shows unlimited seats. */+export const Enterprise: Story = {+ args: { data: buildUsersResponse("enterprise"), loading: false },+};++/** Free sits near its seat ceiling. */+export const Free: Story = {+ args: { data: buildUsersResponse("free"), loading: false },+};++/** Loading collapses every card to the placeholder dash. */+export const Loading: Story = {+ args: { data: null, loading: true },+};diff --git a/frontend/portal/src/components/users/UsersSummaryStrip.tsx b/frontend/portal/src/components/users/UsersSummaryStrip.tsxnew file mode 100644index 0000000000..95f0e83d92--- /dev/null+++ b/frontend/portal/src/components/users/UsersSummaryStrip.tsx@@ -0,0 +1,35 @@+import { MetricCard, MetricStrip } from "@shared/components";+import type { UsersResponse } from "@portal/api/users";+import { seatsLabel } from "@portal/components/users/format";++/**+ * KPI labels are product copy — they describe what each metric IS, not its+ * value. They stay client-side so the strip's structure is stable across+ * loading / empty / ready states; only the values flow from the API.+ */+const KPI_LABELS = ["Members", "Pending invites", "Seats used"] as const;++interface UsersSummaryStripProps {+ data: UsersResponse | null;+ loading: boolean;+}++export function UsersSummaryStrip({ data, loading }: UsersSummaryStripProps) {+ const summary = loading ? undefined : data?.summary;++ const values: Record<(typeof KPI_LABELS)[number], string | number> = {+ Members: summary?.totalMembers ?? "—",+ "Pending invites": summary?.pendingInvites ?? "—",+ "Seats used": summary+ ? seatsLabel(summary.seatsUsed, summary.seatLimit)+ : "—",+ };++ return (+ <MetricStrip>+ {KPI_LABELS.map((label) => (+ <MetricCard key={label} label={label} value={values[label]} />+ ))}+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/users/format.ts b/frontend/portal/src/components/users/format.tsnew file mode 100644index 0000000000..d88b985d57--- /dev/null+++ b/frontend/portal/src/components/users/format.ts@@ -0,0 +1,16 @@+import type { AvatarTone } from "@shared/components";+import type { RoleId } from "@portal/api/users";+import { ROLE_TONE } from "@portal/api/users";++/** Seats used / limit as display copy; null limit → "Unlimited". */+export function seatsLabel(used: number, limit: number | null): string {+ return limit === null ? `${used} · Unlimited` : `${used} / ${limit}`;+}++/**+ * Avatar tone for a member, keyed off their role so the roster reads as a+ * legend for the role catalogue. Falls back to neutral for unknown roles.+ */+export function avatarToneForRole(role: RoleId): AvatarTone {+ return (ROLE_TONE[role] ?? "neutral") as AvatarTone;+}diff --git a/frontend/portal/src/contexts/ViewContext.tsx b/frontend/portal/src/contexts/ViewContext.tsxindex 28aa118e5d..a8eff0fee4 100644--- a/frontend/portal/src/contexts/ViewContext.tsx+++ b/frontend/portal/src/contexts/ViewContext.tsx@@ -4,9 +4,13 @@ import { useLocation, useNavigate } from "react-router-dom";export type ViewId =| "home"| "editor"+ | "users"| "sources"+ | "agent-builder"+ | "policies"| "pipelines"| "documents"+ | "components"| "infrastructure"| "usage"| "docs"@@ -15,9 +19,13 @@ export type ViewId =export const VIEW_LABELS: Record<ViewId, string> = {home: "Home",editor: "Editor",+ users: "Users",sources: "Sources",+ "agent-builder": "Agent Builder",+ policies: "Policies",pipelines: "Pipelines",documents: "Documents",+ components: "Components",infrastructure: "Infrastructure",usage: "Usage & Billing",docs: "Developer Docs",@@ -27,9 +35,13 @@ export const VIEW_LABELS: Record<ViewId, string> = {export const VIEW_PATHS: Record<ViewId, string> = {home: "/",editor: "/editor",+ users: "/users",sources: "/sources",+ "agent-builder": "/agent-builder",+ policies: "/policies",pipelines: "/pipelines",documents: "/documents",+ components: "/components",infrastructure: "/infrastructure",usage: "/usage",docs: "/docs",@@ -55,11 +67,9 @@ interface ViewContextValue {}/**- * Backwards-compatible facade over react-router. Components keep using- * useView()/setActiveView the way they did before; URLs are now real.- *- * No <ViewProvider> wrapper exists any more — the router is the provider.- * App.tsx wraps its children in <BrowserRouter>.+ * Facade over react-router so components navigate by `ViewId` (activeView /+ * setActiveView) while URLs stay the source of truth. There is no+ * <ViewProvider> — the router is the provider; App.tsx supplies <BrowserRouter>.*/export function useView(): ViewContextValue {const { pathname } = useLocation();diff --git a/frontend/portal/src/mocks/agents.ts b/frontend/portal/src/mocks/agents.tsnew file mode 100644index 0000000000..60a10ebb74--- /dev/null+++ b/frontend/portal/src/mocks/agents.ts@@ -0,0 +1,510 @@+/**+ * Agent Builder fixtures and the types api/agents.ts shares with them.+ *+ * An "agent" here is an AI agent that classifies, extracts from, and routes+ * documents. The builder is its lifecycle surface: scenarios (named test+ * cases), tool-access governance, an eval / golden set, and version history.+ *+ * api/agents.ts imports the types; the MSW handlers serve this fixture data+ * over the intercepted httpJson() calls. Components never reach into this+ * module directly. Once a real backend exists the handlers stop being+ * registered and these fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";++/* ──────────────────────────────────────────────────────────────────────── */+/* Domain types */+/* ──────────────────────────────────────────────────────────────────────── */++export type AgentStatus = "draft" | "published";++/**+ * Tool-access posture. `broad` lets the agent call any tool it can reach;+ * `restricted` is allow-by-default minus an explicit deny list (the governance+ * mode enterprise tenants use to fence agents away from sensitive tools).+ */+export type ToolMode = "broad" | "restricted";++/** A named test case describing expected agent behaviour for a kind of input. */+export interface Scenario {+ id: string;+ name: string;+ /** What the agent is expected to do for this input. */+ expectation: string;+ /** Whether this scenario is currently exercised by the eval run. */+ enabled: boolean;+}++/** A single golden-set check with its last-run outcome. */+export interface EvalCase {+ id: string;+ name: string;+ /** Last observed pass/fail; null when the case has never been run. */+ passing: boolean | null;+ /** Mean latency of the last run in milliseconds. */+ latencyMs: number;+}++export interface AgentVersion {+ /** Display label, e.g. "v3" or "v2-draft". */+ version: string;+ status: AgentStatus;+ /** ISO timestamp the version was created. */+ createdAt: string;+ author: string;+ /** One-line change summary. */+ note: string;+}++export interface Agent {+ id: string;+ name: string;+ /** One-line role description shown under the name in the selector. */+ role: string;+ status: AgentStatus;+ /** Current working version, e.g. "v3" or "v2-draft". */+ version: string;+ model: string;+ scenarios: Scenario[];+ toolMode: ToolMode;+ /** Tools the agent may not call when `toolMode` is "restricted". */+ deniedTools: string[];+ /** Count of golden-set cases currently passing. */+ evalsPassing: number;+ /** Total golden-set cases. */+ evalsTotal: number;+ evalCases: EvalCase[];+ versions: AgentVersion[];+}++export interface AgentsSummary {+ /** Agents in the "published" state. */+ activeAgents: number;+ /** Total agents regardless of status. */+ totalAgents: number;+ /** Mean eval pass-rate across all agents, 0..1. */+ avgPassRate: number;+ /** Total scenarios across all agents. */+ totalScenarios: number;+ /** Latest published version label across the fleet, e.g. "v3". */+ latestPublished: string;+}++export interface AgentsResponse {+ summary: AgentsSummary;+ agents: Agent[];+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Presentation metadata (chip tone per status). Product copy, client-side. */+/* ──────────────────────────────────────────────────────────────────────── */++export const AGENT_STATUS_TONE: Record<AgentStatus, "success" | "neutral"> = {+ published: "success",+ draft: "neutral",+};++/**+ * Catalogue of tools an agent can be granted or denied. Surfaced as the chip+ * palette in restricted mode so the deny list is picked from a known set+ * rather than free-typed.+ */+export const TOOL_CATALOGUE = [+ "extract.fields",+ "classify.document",+ "route.pipeline",+ "lookup.crm",+ "send.email",+ "write.audit",+ "read.pii",+ "invoke.webhook",+] as const;++/* ──────────────────────────────────────────────────────────────────────── */+/* Fixture builders */+/* ──────────────────────────────────────────────────────────────────────── */++const CONTRACT_ROUTER: Agent = {+ id: "agent-contract-router",+ name: "Contract Router",+ role: "Classifies inbound contracts and routes to the right review queue",+ status: "published",+ version: "v3",+ model: "claude-opus-4.1",+ toolMode: "restricted",+ deniedTools: ["send.email", "read.pii"],+ evalsPassing: 23,+ evalsTotal: 24,+ scenarios: [+ {+ id: "sc-cr-1",+ name: "New customer file",+ expectation: "Route to onboarding queue and tag as net-new account",+ enabled: true,+ },+ {+ id: "sc-cr-2",+ name: "Renewal with price change",+ expectation: "Flag the delta and route to legal for redline review",+ enabled: true,+ },+ {+ id: "sc-cr-3",+ name: "Non-standard liability clause",+ expectation: "Escalate to senior counsel rather than auto-approving",+ enabled: true,+ },+ ],+ evalCases: [+ {+ id: "ec-cr-1",+ name: "MSA — standard terms",+ passing: true,+ latencyMs: 1840,+ },+ {+ id: "ec-cr-2",+ name: "MSA — capped liability",+ passing: true,+ latencyMs: 2010,+ },+ {+ id: "ec-cr-3",+ name: "Order form — multi-year",+ passing: true,+ latencyMs: 1620,+ },+ {+ id: "ec-cr-4",+ name: "DPA — cross-border transfer",+ passing: false,+ latencyMs: 2440,+ },+ ],+ versions: [+ {+ version: "v3",+ status: "published",+ createdAt: "2026-05-28T14:12:00Z",+ author: "[email protected]",+ note: "Added cross-border DPA detection",+ },+ {+ version: "v2",+ status: "published",+ createdAt: "2026-04-09T09:30:00Z",+ author: "[email protected]",+ note: "Tightened renewal price-change routing",+ },+ {+ version: "v1",+ status: "published",+ createdAt: "2026-02-15T16:45:00Z",+ author: "[email protected]",+ note: "Initial publish",+ },+ ],+};++const INVOICE_AGENT: Agent = {+ id: "agent-invoice",+ name: "Invoice Agent",+ role: "Extracts line items and routes invoices into the AP pipeline",+ status: "published",+ version: "v5",+ model: "claude-sonnet-4.5",+ toolMode: "broad",+ deniedTools: [],+ evalsPassing: 31,+ evalsTotal: 32,+ scenarios: [+ {+ id: "sc-inv-1",+ name: "Multi-page invoice",+ expectation: "Extract all line items across pages into one record",+ enabled: true,+ },+ {+ id: "sc-inv-2",+ name: "Foreign currency total",+ expectation: "Preserve original currency and attach FX note",+ enabled: true,+ },+ {+ id: "sc-inv-3",+ name: "Missing PO number",+ expectation: "Route to manual matching rather than auto-posting",+ enabled: false,+ },+ ],+ evalCases: [+ { id: "ec-inv-1", name: "Single-page USD", passing: true, latencyMs: 980 },+ { id: "ec-inv-2", name: "Multi-page EUR", passing: true, latencyMs: 1320 },+ {+ id: "ec-inv-3",+ name: "Handwritten total",+ passing: true,+ latencyMs: 1510,+ },+ {+ id: "ec-inv-4",+ name: "No PO reference",+ passing: false,+ latencyMs: 1100,+ },+ ],+ versions: [+ {+ version: "v5",+ status: "published",+ createdAt: "2026-06-01T11:00:00Z",+ author: "[email protected]",+ note: "FX note extraction for foreign-currency invoices",+ },+ {+ version: "v4",+ status: "published",+ createdAt: "2026-05-10T08:20:00Z",+ author: "[email protected]",+ note: "Multi-page line-item stitching",+ },+ ],+};++const KYC_AGENT: Agent = {+ id: "agent-kyc",+ name: "KYC Agent",+ role: "Verifies identity documents and flags compliance gaps",+ status: "draft",+ version: "v2-draft",+ model: "claude-sonnet-4.5",+ toolMode: "restricted",+ deniedTools: ["send.email", "invoke.webhook"],+ evalsPassing: 14,+ evalsTotal: 20,+ scenarios: [+ {+ id: "sc-kyc-1",+ name: "KYC question",+ expectation: "Answer from the verified document set, never invent facts",+ enabled: true,+ },+ {+ id: "sc-kyc-2",+ name: "Expired identity document",+ expectation: "Mark verification as failed and request a fresh document",+ enabled: true,+ },+ {+ id: "sc-kyc-3",+ name: "Compliance escalation",+ expectation: "Escalate sanctions-list hits to the compliance officer",+ enabled: true,+ },+ ],+ evalCases: [+ { id: "ec-kyc-1", name: "Valid passport", passing: true, latencyMs: 2200 },+ { id: "ec-kyc-2", name: "Expired licence", passing: true, latencyMs: 2050 },+ {+ id: "ec-kyc-3",+ name: "Sanctions-list match",+ passing: false,+ latencyMs: 2600,+ },+ {+ id: "ec-kyc-4",+ name: "Mismatched name fields",+ passing: false,+ latencyMs: 2310,+ },+ ],+ versions: [+ {+ version: "v2-draft",+ status: "draft",+ createdAt: "2026-06-12T13:40:00Z",+ author: "[email protected]",+ note: "Sanctions-list escalation path (in review)",+ },+ {+ version: "v1",+ status: "published",+ createdAt: "2026-03-22T10:15:00Z",+ author: "[email protected]",+ note: "Initial publish",+ },+ ],+};++/**+ * Enterprise-only agent — governance-heavy and exercised against a larger+ * golden set than the base tenants get, so it only appears for that tier.+ */+const COMPLIANCE_SWEEP: Agent = {+ id: "agent-compliance-sweep",+ name: "Compliance Sweep",+ role: "Audits processed documents against retention and PII policy",+ status: "published",+ version: "v4",+ model: "claude-opus-4.1",+ toolMode: "restricted",+ deniedTools: ["send.email", "route.pipeline", "invoke.webhook"],+ evalsPassing: 58,+ evalsTotal: 60,+ scenarios: [+ {+ id: "sc-cs-1",+ name: "Over-retention detection",+ expectation: "Flag documents held past their retention window",+ enabled: true,+ },+ {+ id: "sc-cs-2",+ name: "Unredacted PII",+ expectation: "Quarantine and write an audit entry, never auto-delete",+ enabled: true,+ },+ ],+ evalCases: [+ {+ id: "ec-cs-1",+ name: "Expired retention",+ passing: true,+ latencyMs: 3100,+ },+ { id: "ec-cs-2", name: "SSN in free text", passing: true, latencyMs: 2900 },+ {+ id: "ec-cs-3",+ name: "Redacted re-share",+ passing: true,+ latencyMs: 2700,+ },+ {+ id: "ec-cs-4",+ name: "Cross-region copy",+ passing: false,+ latencyMs: 3300,+ },+ ],+ versions: [+ {+ version: "v4",+ status: "published",+ createdAt: "2026-06-03T15:05:00Z",+ author: "[email protected]",+ note: "Cross-region copy detection",+ },+ {+ version: "v3",+ status: "published",+ createdAt: "2026-05-01T12:00:00Z",+ author: "[email protected]",+ note: "Retention-window policy refresh",+ },+ {+ version: "v2",+ status: "published",+ createdAt: "2026-03-14T09:00:00Z",+ author: "[email protected]",+ note: "PII quarantine workflow",+ },+ {+ version: "v1",+ status: "published",+ createdAt: "2026-01-20T08:00:00Z",+ author: "[email protected]",+ note: "Initial publish",+ },+ ],+};++/**+ * On the free tier a single starter agent ships as a draft so the surface has+ * something to render, but with an empty golden set and no version history —+ * evals and version governance are paid capabilities.+ */+const STARTER_AGENT: Agent = {+ id: "agent-starter",+ name: "Starter Classifier",+ role: "Sorts uploads into a handful of document types",+ status: "draft",+ version: "v1-draft",+ model: "claude-haiku-4.5",+ toolMode: "broad",+ deniedTools: [],+ evalsPassing: 0,+ evalsTotal: 0,+ scenarios: [+ {+ id: "sc-st-1",+ name: "Unknown document type",+ expectation: "Fall back to the inbox queue instead of guessing",+ enabled: true,+ },+ ],+ evalCases: [],+ versions: [+ {+ version: "v1-draft",+ status: "draft",+ createdAt: "2026-06-14T17:30:00Z",+ author: "[email protected]",+ note: "Draft — not yet published",+ },+ ],+};++const PRO_AGENTS: Agent[] = [CONTRACT_ROUTER, INVOICE_AGENT, KYC_AGENT];++/**+ * Trim an agent to the free-tier shape: drop the eval golden set and collapse+ * version history to the current version, mirroring the capability gating the+ * KPI strip advertises.+ */+function toFreeShape(agent: Agent): Agent {+ return {+ ...agent,+ status: "draft",+ evalsPassing: 0,+ evalsTotal: 0,+ evalCases: [],+ versions: agent.versions.slice(0, 1),+ };+}++/** Agents for a given tier. */+export function agentsFor(tier: Tier): Agent[] {+ if (tier === "free") return [toFreeShape(STARTER_AGENT)];+ if (tier === "enterprise") return [...PRO_AGENTS, COMPLIANCE_SWEEP];+ return PRO_AGENTS;+}++function summaryFor(agents: Agent[]): AgentsSummary {+ const published = agents.filter((a) => a.status === "published");+ const totalScenarios = agents.reduce((n, a) => n + a.scenarios.length, 0);++ // Pass-rate is meaningless without a golden set, so average only over agents+ // that actually have eval cases — free tenants land at 0.+ const withEvals = agents.filter((a) => a.evalsTotal > 0);+ const avgPassRate =+ withEvals.length === 0+ ? 0+ : withEvals.reduce((sum, a) => sum + a.evalsPassing / a.evalsTotal, 0) /+ withEvals.length;++ const latestPublished = published.length > 0 ? published[0].version : "—";++ return {+ activeAgents: published.length,+ totalAgents: agents.length,+ avgPassRate,+ totalScenarios,+ latestPublished,+ };+}++export function buildAgentsResponse(tier: Tier): AgentsResponse {+ const agents = agentsFor(tier);+ return { summary: summaryFor(agents), agents };+}diff --git a/frontend/portal/src/mocks/documents.ts b/frontend/portal/src/mocks/documents.tsnew file mode 100644index 0000000000..49b524887c--- /dev/null+++ b/frontend/portal/src/mocks/documents.ts@@ -0,0 +1,559 @@+/**+ * Document review-queue fixtures and the types api/documents.ts shares with them.+ *+ * A "document" here is a single item flowing through the org's pipelines and+ * waiting on a review/approval decision. Each carries its extracted fields, an+ * audit timeline, and a `sensitive` flag that gates whether its content is+ * shown directly or behind a zero-standing-access elevation request.+ *+ * api/documents.ts imports the types; the MSW handlers serve the fixture data+ * over the intercepted httpJson() calls. Components never reach into this+ * module directly. Once a real backend exists the handlers stop being+ * registered and these fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";+import type { StatusTone } from "@shared/components";++/* ──────────────────────────────────────────────────────────────────────── */+/* Domain types */+/* ──────────────────────────────────────────────────────────────────────── */++export type DocumentStatus =+ | "processed"+ | "flagged"+ | "needs-review"+ | "archived";++/** A single field pulled out of the document by extraction. */+export interface Extraction {+ field: string;+ value: string;+ /** Per-field confidence 0..1. */+ confidence: number;+}++export type DocAuditKind =+ | "ingested"+ | "extracted"+ | "flagged"+ | "reviewed"+ | "approved"+ | "archived"+ | "elevation";++/** One event in a document's lifecycle, newest last. */+export interface DocAuditEvent {+ id: string;+ kind: DocAuditKind;+ /** Relative-time string, e.g. "2m ago". */+ time: string;+ actor: string;+ detail: string;+}++export interface ReviewDocument {+ id: string;+ name: string;+ /** Document type label, e.g. "Invoice", "Contract". */+ type: string;+ status: DocumentStatus;+ /** Originating source name. */+ source: string;+ /** Overall extraction confidence 0..1. */+ confidence: number;+ /** Count of extracted fields (matches extractions.length). */+ fieldsExtracted: number;+ /** Relative-time string, e.g. "4m ago". */+ time: string;+ /**+ * When true, content sits behind a zero-standing-access wall. The viewer+ * sees a "Request access" affordance instead of the extractions until a+ * timed elevation is granted.+ */+ sensitive: boolean;+ extractions: Extraction[];+ audit: DocAuditEvent[];+}++export interface DocumentsSummary {+ /** Total documents currently in the queue. */+ totalInQueue: number;+ needsReview: number;+ /** Mean extraction confidence across the queue, 0..1. */+ avgConfidence: number;+ processedToday: number;+}++export interface DocumentsResponse {+ summary: DocumentsSummary;+ documents: ReviewDocument[];+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Presentation metadata (label + chip tone) */+/* Lives client-side — product copy, not data. Re-exported via api/. */+/* ──────────────────────────────────────────────────────────────────────── */++export const DOCUMENT_STATUS_LABEL: Record<DocumentStatus, string> = {+ processed: "Processed",+ flagged: "Flagged",+ "needs-review": "Needs review",+ archived: "Archived",+};++export const DOCUMENT_STATUS_TONE: Record<DocumentStatus, StatusTone> = {+ processed: "success",+ flagged: "danger",+ "needs-review": "warning",+ archived: "neutral",+};++export const DOC_AUDIT_LABEL: Record<DocAuditKind, string> = {+ ingested: "Ingested",+ extracted: "Extracted",+ flagged: "Flagged",+ reviewed: "Reviewed",+ approved: "Approved",+ archived: "Archived",+ elevation: "Elevation",+};++export const DOC_AUDIT_TONE: Record<DocAuditKind, StatusTone> = {+ ingested: "info",+ extracted: "info",+ flagged: "danger",+ reviewed: "warning",+ approved: "success",+ archived: "neutral",+ elevation: "purple",+};++/* ──────────────────────────────────────────────────────────────────────── */+/* Fixture builders */+/* ──────────────────────────────────────────────────────────────────────── */++/**+ * Pro-tier queue. A spread of statuses, types, sources, and confidences plus+ * deliberate edge cases: a 100%-confidence clean processed doc, a flagged+ * low-confidence outlier, and a doc with zero extracted fields.+ */+const PRO_DOCS: ReviewDocument[] = [+ {+ id: "doc-inv-8841",+ name: "ACME-INV-8841.pdf",+ type: "Invoice",+ status: "needs-review",+ source: "[email protected]",+ confidence: 0.82,+ fieldsExtracted: 6,+ time: "3m ago",+ sensitive: false,+ extractions: [+ { field: "Vendor", value: "Globex Supplies Ltd", confidence: 0.98 },+ { field: "Invoice no.", value: "INV-8841", confidence: 0.99 },+ { field: "Invoice date", value: "2026-06-12", confidence: 0.94 },+ { field: "Due date", value: "2026-07-12", confidence: 0.88 },+ { field: "Total", value: "$12,480.00", confidence: 0.71 },+ { field: "PO number", value: "PO-2231 (unverified)", confidence: 0.42 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "4m ago",+ actor: "[email protected]",+ detail: "Received via email inbox",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "4m ago",+ actor: "Invoice Extractor",+ detail: "6 fields extracted · 82% mean confidence",+ },+ {+ id: "a3",+ kind: "flagged",+ time: "3m ago",+ actor: "Invoice Extractor",+ detail: "PO number below 50% confidence — routed to review",+ },+ ],+ },+ {+ id: "doc-receipt-3320",+ name: "expense-receipt-3320.jpg",+ type: "Receipt",+ status: "processed",+ source: "Stirling Desktop — Reviewer pool",+ confidence: 1.0,+ fieldsExtracted: 4,+ time: "11m ago",+ sensitive: false,+ extractions: [+ { field: "Merchant", value: "Blue Bottle Coffee", confidence: 1.0 },+ { field: "Date", value: "2026-06-15", confidence: 1.0 },+ { field: "Amount", value: "$8.50", confidence: 1.0 },+ { field: "Category", value: "Meals", confidence: 1.0 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "12m ago",+ actor: "[email protected]",+ detail: "Uploaded from desktop app",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "12m ago",+ actor: "Invoice Extractor",+ detail: "4 fields extracted · 100% mean confidence",+ },+ {+ id: "a3",+ kind: "approved",+ time: "11m ago",+ actor: "Invoice Extractor",+ detail: "Auto-approved — all fields above threshold",+ },+ ],+ },+ {+ id: "doc-contract-7712",+ name: "MSA-Globex-2026.pdf",+ type: "Contract",+ status: "needs-review",+ source: "SharePoint — Legal",+ confidence: 0.76,+ fieldsExtracted: 5,+ // Sensitive: legal contract behind zero-standing-access. Content is hidden+ // until a timed elevation is granted.+ sensitive: true,+ time: "27m ago",+ extractions: [+ { field: "Counterparty", value: "Globex Corporation", confidence: 0.95 },+ { field: "Effective date", value: "2026-07-01", confidence: 0.9 },+ { field: "Term", value: "36 months", confidence: 0.84 },+ { field: "Auto-renewal", value: "Yes — 12 months", confidence: 0.61 },+ { field: "Governing law", value: "Delaware", confidence: 0.49 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "31m ago",+ actor: "SharePoint — Legal",+ detail: "Synced from Contracts / Inbound",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "30m ago",+ actor: "Contract Router",+ detail: "5 fields extracted · 76% mean confidence",+ },+ {+ id: "a3",+ kind: "flagged",+ time: "27m ago",+ actor: "Contract Router",+ detail: "Governing-law clause ambiguous — routed to legal review",+ },+ ],+ },+ {+ id: "doc-claim-1190",+ name: "claim-1190-intake.pdf",+ type: "Claim",+ status: "flagged",+ source: "S3 — claims-intake",+ confidence: 0.38,+ fieldsExtracted: 3,+ // Edge case: low-confidence outlier that failed to parse a scanned form.+ sensitive: false,+ time: "44m ago",+ extractions: [+ { field: "Claimant", value: "(illegible)", confidence: 0.21 },+ { field: "Policy no.", value: "POL-44120", confidence: 0.66 },+ { field: "Claim amount", value: "(not found)", confidence: 0.0 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "46m ago",+ actor: "S3 — claims-intake",+ detail: "Picked up from intake bucket",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "45m ago",+ actor: "KYC Processor",+ detail: "3 fields extracted · 38% mean confidence",+ },+ {+ id: "a3",+ kind: "flagged",+ time: "44m ago",+ actor: "KYC Processor",+ detail: "Scan quality too low — manual re-key required",+ },+ ],+ },+ {+ id: "doc-w9-0042",+ name: "vendor-W9-globex.pdf",+ type: "Tax form",+ status: "processed",+ source: "Acme Production",+ confidence: 0.93,+ fieldsExtracted: 5,+ sensitive: true,+ time: "1h ago",+ extractions: [+ { field: "Legal name", value: "Globex Supplies Ltd", confidence: 0.97 },+ { field: "TIN", value: "••-•••4821", confidence: 0.91 },+ { field: "Entity type", value: "LLC", confidence: 0.95 },+ {+ field: "Address",+ value: "44 Industrial Way, Springfield",+ confidence: 0.9,+ },+ { field: "Signature", value: "Present", confidence: 0.92 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "1h ago",+ actor: "Acme Production",+ detail: "Uploaded via POST /v1/extract",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "1h ago",+ actor: "KYC Processor",+ detail: "5 fields extracted · 93% mean confidence",+ },+ {+ id: "a3",+ kind: "approved",+ time: "58m ago",+ actor: "[email protected]",+ detail: "Reviewed and approved",+ },+ ],+ },+ {+ id: "doc-po-6610",+ name: "purchase-order-6610.pdf",+ type: "Purchase order",+ status: "archived",+ source: "Nightly archive reprocess",+ confidence: 0.88,+ fieldsExtracted: 4,+ sensitive: false,+ time: "8h ago",+ extractions: [+ { field: "Supplier", value: "Initech", confidence: 0.92 },+ { field: "PO number", value: "PO-6610", confidence: 0.99 },+ { field: "Line items", value: "7", confidence: 0.85 },+ { field: "Total", value: "$3,210.00", confidence: 0.78 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "8h ago",+ actor: "Nightly archive reprocess",+ detail: "Reprocessed from archive bucket",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "8h ago",+ actor: "Invoice Extractor",+ detail: "4 fields extracted · 88% mean confidence",+ },+ {+ id: "a3",+ kind: "archived",+ time: "8h ago",+ actor: "system",+ detail: "Retention policy — archived after approval",+ },+ ],+ },+];++/**+ * Enterprise-only additions — deeper queue with more sensitive items so the+ * zero-standing-access elevation flow has something to gate, plus richer+ * audit trails.+ */+const ENTERPRISE_EXTRA: ReviewDocument[] = [+ {+ id: "doc-kyc-5523",+ name: "onboarding-passport-5523.pdf",+ type: "KYC document",+ status: "needs-review",+ source: "S3 — claims-intake",+ confidence: 0.79,+ fieldsExtracted: 6,+ sensitive: true,+ time: "9m ago",+ extractions: [+ { field: "Full name", value: "Maria L. Vance", confidence: 0.96 },+ { field: "Document type", value: "Passport", confidence: 0.99 },+ { field: "Document no.", value: "••••••742", confidence: 0.83 },+ { field: "Date of birth", value: "1989-03-14", confidence: 0.88 },+ { field: "Nationality", value: "United Kingdom", confidence: 0.94 },+ { field: "Expiry", value: "2029-11-02", confidence: 0.55 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "10m ago",+ actor: "S3 — claims-intake",+ detail: "Picked up from intake bucket",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "10m ago",+ actor: "KYC Processor",+ detail: "6 fields extracted · 79% mean confidence",+ },+ {+ id: "a3",+ kind: "flagged",+ time: "9m ago",+ actor: "Compliance Sweep",+ detail: "PII present — four-eyes review required before release",+ },+ ],+ },+ {+ id: "doc-dpa-2207",+ name: "DPA-globex-amendment.pdf",+ type: "Contract",+ status: "flagged",+ source: "SharePoint — Legal",+ confidence: 0.84,+ fieldsExtracted: 5,+ sensitive: true,+ time: "1h ago",+ extractions: [+ { field: "Counterparty", value: "Globex Corporation", confidence: 0.95 },+ { field: "Data categories", value: "PII, financial", confidence: 0.81 },+ { field: "Sub-processors", value: "3 listed", confidence: 0.77 },+ { field: "SCC version", value: "2021/914", confidence: 0.9 },+ { field: "Breach window", value: "72 hours", confidence: 0.76 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "1h ago",+ actor: "SharePoint — Legal",+ detail: "Synced from Contracts / Inbound",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "1h ago",+ actor: "Contract Router",+ detail: "5 fields extracted · 84% mean confidence",+ },+ {+ id: "a3",+ kind: "flagged",+ time: "1h ago",+ actor: "Compliance Sweep",+ detail: "Sub-processor list changed — escalated to DPO",+ },+ ],+ },+ {+ id: "doc-coi-9001",+ name: "certificate-of-insurance-9001.pdf",+ type: "Compliance",+ status: "processed",+ source: "Compliance Sweep",+ confidence: 0.96,+ fieldsExtracted: 5,+ sensitive: false,+ time: "2h ago",+ extractions: [+ { field: "Insured", value: "Acme Corp", confidence: 0.98 },+ { field: "Carrier", value: "Liberty Mutual", confidence: 0.97 },+ { field: "Policy no.", value: "CGL-77120", confidence: 0.95 },+ { field: "Coverage", value: "$2,000,000", confidence: 0.96 },+ { field: "Expiry", value: "2027-01-31", confidence: 0.94 },+ ],+ audit: [+ {+ id: "a1",+ kind: "ingested",+ time: "2h ago",+ actor: "Compliance Sweep",+ detail: "Pulled for COI compliance check",+ },+ {+ id: "a2",+ kind: "extracted",+ time: "2h ago",+ actor: "Compliance Sweep",+ detail: "5 fields extracted · 96% mean confidence",+ },+ {+ id: "a3",+ kind: "approved",+ time: "2h ago",+ actor: "[email protected]",+ detail: "Coverage verified — approved",+ },+ ],+ },+];++/** Documents for a given tier. Free is a slim queue; enterprise is the deepest. */+export function documentsFor(tier: Tier): ReviewDocument[] {+ if (tier === "free") {+ // Free keeps a simple, non-sensitive queue — no elevation flow to exercise.+ return PRO_DOCS.filter((d) => !d.sensitive).slice(0, 3);+ }+ if (tier === "enterprise") return [...ENTERPRISE_EXTRA, ...PRO_DOCS];+ return PRO_DOCS;+}++/** Summary strip derived from the tier's queue so the KPIs always reconcile. */+export function summaryFor(tier: Tier): DocumentsSummary {+ const docs = documentsFor(tier);+ const needsReview = docs.filter((d) => d.status === "needs-review").length;+ const avgConfidence =+ docs.length === 0+ ? 0+ : docs.reduce((sum, d) => sum + d.confidence, 0) / docs.length;+ // "Processed today" approximates same-day throughput from the visible queue;+ // a real backend would count against an actual calendar boundary.+ const processedToday = docs.filter(+ (d) => d.status === "processed" || d.status === "archived",+ ).length;+ return {+ totalInQueue: docs.length,+ needsReview,+ avgConfidence,+ processedToday,+ };+}++export function buildDocumentsResponse(tier: Tier): DocumentsResponse {+ return { summary: summaryFor(tier), documents: documentsFor(tier) };+}diff --git a/frontend/portal/src/mocks/editorDeploy.ts b/frontend/portal/src/mocks/editorDeploy.tsnew file mode 100644index 0000000000..d4bbbac678--- /dev/null+++ b/frontend/portal/src/mocks/editorDeploy.ts@@ -0,0 +1,393 @@+/**+ * Editor deployment fixtures and the types api/editorDeploy.ts shares with them.+ *+ * This surface manages the org's deployment of the Stirling PDF *Editor* product+ * from the portal — where it runs (Managed Cloud / Docker / Kubernetes), how+ * self-hosted instances pair back to the org, the health of each running+ * instance, and the service credential / offline-activation lifecycle.+ *+ * api/editorDeploy.ts imports the types; the MSW handlers serve this fixture+ * data over the intercepted httpJson() calls. Components never reach into this+ * module directly. Once a real backend exists the handlers stop being registered+ * and these fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";++/* ──────────────────────────────────────────────────────────────────────── */+/* Deployment targets */+/* ──────────────────────────────────────────────────────────────────────── */++/** Where an Editor deployment can run. */+export type TargetKind = "cloud" | "docker" | "kubernetes";++/**+ * Whether a target is usable on the current tier and, if so, whether the org+ * has actually stood it up. `locked` targets render an upgrade nudge instead of+ * a runnable snippet.+ */+export type TargetState = "running" | "available" | "locked";++export interface DeploymentTarget {+ kind: TargetKind;+ label: string;+ /** One-line positioning shown under the title. */+ tagline: string;+ state: TargetState;+ /** Minimum tier that unlocks this target — drives the upgrade nudge copy. */+ requiresTier: Tier;+ /** Install / run snippet for the target's CodeBlock. */+ snippet: string;+ /** Language hint for the CodeBlock chrome. */+ snippetLang: "bash" | "plain";+ /** Populated only when `state === "running"`. */+ runningVersion?: string;+ /** Count of instances currently reporting in for this target. */+ instanceCount?: number;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Pairing */+/* ──────────────────────────────────────────────────────────────────────── */++/** How a self-hosted editor connects itself to the org. */+export type PairingMethod = "token" | "shortcode" | "iac";++export interface PairingOption {+ method: PairingMethod;+ label: string;+ description: string;+ /** Minimum tier that unlocks this method. */+ requiresTier: Tier;+ /**+ * The current secret/handle to display. A long-lived pairing token, a+ * TV-style short code, or an IaC reference (e.g. a Terraform module input).+ * Pre-masked for token display — never carries the real secret.+ */+ value: string;+ /** Short codes expire fast; tokens rotate on demand. Relative-time string. */+ expires?: string;+ /** Whether this option is currently usable on the active tier. */+ locked: boolean;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Running instances (deployment health) */+/* ──────────────────────────────────────────────────────────────────────── */++export type InstanceStatus = "healthy" | "degraded" | "offline" | "pairing";++export interface EditorInstance {+ id: string;+ /** Human host label, e.g. "edge-fra-01" or "Managed Cloud (us-east-1)". */+ host: string;+ target: TargetKind;+ version: string;+ region: string;+ status: InstanceStatus;+ /** Relative-time string, e.g. "12s ago". */+ lastSeen: string;+ activeUsers: number;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Summary metric strip */+/* ──────────────────────────────────────────────────────────────────────── */++export interface DeploymentSummaryMetric {+ label: string;+ value: string | number;+ delta?: number;+ deltaDirection?: "up" | "down" | "flat";+ description?: string;+}++export interface DeploymentSummary {+ metrics: DeploymentSummaryMetric[];+ /** Masked service token + its rotation age, shown by the rotation card. */+ serviceToken: { masked: string; lastRotated: string };+ /** Air-gapped activation is enterprise-only; gate the card on this flag. */+ offlineActivationAvailable: boolean;+}++export interface EditorDeploymentResponse {+ summary: DeploymentSummary;+ targets: DeploymentTarget[];+ pairings: PairingOption[];+ instances: EditorInstance[];+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Presentation metadata (lives client-side — product copy, not data) */+/* ──────────────────────────────────────────────────────────────────────── */++export interface TargetMeta {+ icon: string;+ tone: "neutral" | "blue" | "purple";+}++export const TARGET_META: Record<TargetKind, TargetMeta> = {+ cloud: { icon: "☁", tone: "blue" },+ docker: { icon: "▣", tone: "neutral" },+ kubernetes: { icon: "⎈", tone: "purple" },+};++export const INSTANCE_STATUS_TONE: Record<+ InstanceStatus,+ "success" | "warning" | "danger" | "info" | "neutral"+> = {+ healthy: "success",+ degraded: "warning",+ offline: "danger",+ pairing: "info",+};++export const INSTANCE_STATUS_LABEL: Record<InstanceStatus, string> = {+ healthy: "Healthy",+ degraded: "Degraded",+ offline: "Offline",+ pairing: "Pairing",+};++/* ──────────────────────────────────────────────────────────────────────── */+/* Snippet builders */+/* ──────────────────────────────────────────────────────────────────────── */++const DOCKER_SNIPPET = `docker run -d --name stirling-editor \\+ -p 8080:8080 \\+ -e STIRLING_ORG_PAIRING_TOKEN="$PAIRING_TOKEN" \\+ -e STIRLING_REGION="us-east-1" \\+ -v stirling-data:/var/lib/stirling \\+ stirlingpdf/editor:3.2.1`;++const HELM_SNIPPET = `helm repo add stirling https://charts.stirlingpdf.com+helm install editor stirling/editor \\+ --namespace stirling --create-namespace \\+ --set org.pairingToken="$PAIRING_TOKEN" \\+ --set image.tag=3.2.1 \\+ --set replicaCount=3`;++const CLOUD_SNIPPET = `# Managed Cloud is provisioned for you — no install step.+# Point your users at the org workspace URL:+https://app.stirlingpdf.com/o/acme/editor`;++/* ──────────────────────────────────────────────────────────────────────── */+/* Tier-aware fixture assembly */+/* ──────────────────────────────────────────────────────────────────────── */++function targetsFor(tier: Tier): DeploymentTarget[] {+ const cloud: DeploymentTarget = {+ kind: "cloud",+ label: "Managed Cloud",+ tagline: "Stirling-hosted, zero-ops. Available on every plan.",+ state: "running",+ requiresTier: "free",+ snippet: CLOUD_SNIPPET,+ snippetLang: "plain",+ runningVersion: "3.2.1",+ instanceCount: 1,+ };++ const dockerUnlocked = tier === "pro" || tier === "enterprise";+ const docker: DeploymentTarget = {+ kind: "docker",+ label: "Docker",+ tagline: "Single-container self-host for a VM or on-prem box.",+ state: dockerUnlocked ? "running" : "locked",+ requiresTier: "pro",+ snippet: DOCKER_SNIPPET,+ snippetLang: "bash",+ ...(dockerUnlocked ? { runningVersion: "3.2.1", instanceCount: 2 } : {}),+ };++ const k8sUnlocked = tier === "pro" || tier === "enterprise";+ const k8s: DeploymentTarget = {+ kind: "kubernetes",+ label: "Kubernetes",+ tagline: "Helm chart with autoscaling for production fleets.",+ // Pro can run K8s but this org has only stood up Docker so far — shows the+ // "available, not yet deployed" state distinct from a tier lock.+ state: k8sUnlocked+ ? tier === "enterprise"+ ? "running"+ : "available"+ : "locked",+ requiresTier: "pro",+ snippet: HELM_SNIPPET,+ snippetLang: "bash",+ ...(tier === "enterprise"+ ? { runningVersion: "3.2.1", instanceCount: 3 }+ : {}),+ };++ return [cloud, docker, k8s];+}++function pairingsFor(tier: Tier): PairingOption[] {+ const iacUnlocked = tier === "enterprise";+ return [+ {+ method: "token",+ label: "Pairing token",+ description:+ "Long-lived secret injected as STIRLING_ORG_PAIRING_TOKEN. Rotate if it leaks.",+ requiresTier: "free",+ value: "pair_live_••••••••••••••3f9a",+ expires: "Rotates manually",+ locked: false,+ },+ {+ method: "shortcode",+ label: "Short code",+ description:+ "TV-style code for pairing a fresh instance from its first-run screen.",+ requiresTier: "free",+ value: "WXYZ-7Q4K",+ expires: "Expires in 9m",+ locked: false,+ },+ {+ method: "iac",+ label: "IaC provisioning",+ description:+ "Terraform / Pulumi module input so instances pair on apply — no manual token handling.",+ requiresTier: "enterprise",+ value: iacUnlocked+ ? 'module "stirling_editor" { org_id = "acme" }'+ : "Enterprise only",+ locked: !iacUnlocked,+ },+ ];+}++function instancesFor(tier: Tier): EditorInstance[] {+ const managed: EditorInstance = {+ id: "inst-cloud-1",+ host: "Managed Cloud",+ target: "cloud",+ version: "3.2.1",+ region: "us-east-1",+ status: "healthy",+ lastSeen: "8s ago",+ activeUsers: 41,+ };++ if (tier === "free") return [managed];++ const pro: EditorInstance[] = [+ managed,+ {+ id: "inst-docker-1",+ host: "edge-iad-01",+ target: "docker",+ version: "3.2.1",+ region: "us-east-1",+ status: "healthy",+ lastSeen: "21s ago",+ activeUsers: 12,+ },+ {+ // Edge case: an instance running a stale version and reporting degraded+ // health — exercises the warning tone and a version-drift signal.+ id: "inst-docker-2",+ host: "edge-fra-01",+ target: "docker",+ version: "3.1.4",+ region: "eu-central-1",+ status: "degraded",+ lastSeen: "3m ago",+ activeUsers: 7,+ },+ ];++ if (tier === "pro") return pro;++ // enterprise — adds a K8s fleet plus an offline air-gapped node and one that+ // dropped off the network.+ return [+ ...pro,+ {+ id: "inst-k8s-1",+ host: "prod-eks/editor-7c9",+ target: "kubernetes",+ version: "3.2.1",+ region: "us-west-2",+ status: "healthy",+ lastSeen: "5s ago",+ activeUsers: 88,+ },+ {+ id: "inst-k8s-2",+ host: "prod-eks/editor-7c9",+ target: "kubernetes",+ version: "3.2.1",+ region: "ap-southeast-1",+ status: "healthy",+ lastSeen: "11s ago",+ activeUsers: 54,+ },+ {+ id: "inst-airgap-1",+ host: "scif-node-a (air-gapped)",+ target: "docker",+ version: "3.2.0",+ region: "on-prem",+ status: "offline",+ lastSeen: "Offline activation · 2d",+ activeUsers: 0,+ },+ ];+}++function summaryFor(+ tier: Tier,+ instances: EditorInstance[],+): DeploymentSummary {+ const live = instances.filter((i) => i.status !== "offline");+ const activeUsers = instances.reduce((s, i) => s + i.activeUsers, 0);+ const versions = new Set(live.map((i) => i.version));++ return {+ metrics: [+ {+ label: "Running instances",+ value: live.length,+ description: `${instances.length} total`,+ },+ {+ label: "Active users",+ value: activeUsers,+ delta: tier === "enterprise" ? 0.18 : 0.07,+ deltaDirection: "up",+ },+ {+ label: "Version spread",+ value: versions.size === 1 ? "Aligned" : `${versions.size} versions`,+ deltaDirection: versions.size === 1 ? "flat" : "down",+ description: versions.size === 1 ? "All on 3.2.1" : "Drift detected",+ },+ {+ label: "Latest release",+ value: "3.2.1",+ description: "Editor build",+ },+ ],+ serviceToken: {+ masked: "svc_live_••••••••••••7b21",+ lastRotated: tier === "enterprise" ? "11 days ago" : "34 days ago",+ },+ offlineActivationAvailable: tier === "enterprise",+ };+}++export function buildEditorDeploymentResponse(+ tier: Tier,+): EditorDeploymentResponse {+ const instances = instancesFor(tier);+ return {+ summary: summaryFor(tier, instances),+ targets: targetsFor(tier),+ pairings: pairingsFor(tier),+ instances,+ };+}diff --git a/frontend/portal/src/mocks/handlers/agents.ts b/frontend/portal/src/mocks/handlers/agents.tsnew file mode 100644index 0000000000..a5b054c57e--- /dev/null+++ b/frontend/portal/src/mocks/handlers/agents.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildAgentsResponse } from "@portal/mocks/agents";++export const agentsHandlers = [+ http.get("/v1/agents", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildAgentsResponse(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/documents.ts b/frontend/portal/src/mocks/handlers/documents.tsnew file mode 100644index 0000000000..0f072aa1bd--- /dev/null+++ b/frontend/portal/src/mocks/handlers/documents.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildDocumentsResponse } from "@portal/mocks/documents";++export const documentsHandlers = [+ http.get("/v1/documents", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildDocumentsResponse(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/editorDeploy.ts b/frontend/portal/src/mocks/handlers/editorDeploy.tsnew file mode 100644index 0000000000..3fcc126d70--- /dev/null+++ b/frontend/portal/src/mocks/handlers/editorDeploy.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildEditorDeploymentResponse } from "@portal/mocks/editorDeploy";++export const editorDeployHandlers = [+ http.get("/v1/editor/deployment", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildEditorDeploymentResponse(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/endpoints.ts b/frontend/portal/src/mocks/handlers/endpoints.tsdeleted file mode 100644index 0596b3bea1..0000000000--- a/frontend/portal/src/mocks/handlers/endpoints.ts+++ /dev/null@@ -1,15 +0,0 @@-import { http, HttpResponse, delay } from "msw";-import { VERTICALS } from "@shared/data/endpoints";--export const endpointsHandlers = [- http.get("/v1/endpoints", async ({ request }) => {- await delay(120);- const url = new URL(request.url);- const verticalKey = url.searchParams.get("vertical");- if (verticalKey) {- const v = VERTICALS.find((x) => x.key === verticalKey);- return HttpResponse.json(v ? v.endpoints : []);- }- return HttpResponse.json(VERTICALS);- }),-];diff --git a/frontend/portal/src/mocks/handlers/index.ts b/frontend/portal/src/mocks/handlers/index.tsindex 3ed6279f03..43948b9788 100644--- a/frontend/portal/src/mocks/handlers/index.ts+++ b/frontend/portal/src/mocks/handlers/index.ts@@ -1,5 +1,4 @@import { assistantHandlers } from "@portal/mocks/handlers/assistant";-import { endpointsHandlers } from "@portal/mocks/handlers/endpoints";import { homeHandlers } from "@portal/mocks/handlers/home";import { notificationsHandlers } from "@portal/mocks/handlers/notifications";import { opsHandlers } from "@portal/mocks/handlers/ops";@@ -10,6 +9,12 @@ import { infrastructureHandlers } from "@portal/mocks/handlers/infrastructure";import { usageHandlers } from "@portal/mocks/handlers/usage";import { docsHandlers } from "@portal/mocks/handlers/docs";import { settingsHandlers } from "@portal/mocks/handlers/settings";+import { usersHandlers } from "@portal/mocks/handlers/users";+import { agentsHandlers } from "@portal/mocks/handlers/agents";+import { policiesHandlers } from "@portal/mocks/handlers/policies";+import { documentsHandlers } from "@portal/mocks/handlers/documents";+import { sdkComponentsHandlers } from "@portal/mocks/handlers/sdkComponents";+import { editorDeployHandlers } from "@portal/mocks/handlers/editorDeploy";export const handlers = [...homeHandlers,@@ -17,13 +22,18 @@ export const handlers = [...notificationsHandlers,...assistantHandlers,...searchHandlers,- ...endpointsHandlers,...pipelinesHandlers,...sourcesHandlers,...infrastructureHandlers,...usageHandlers,...docsHandlers,...settingsHandlers,+ ...usersHandlers,+ ...agentsHandlers,+ ...policiesHandlers,+ ...documentsHandlers,+ ...sdkComponentsHandlers,+ ...editorDeployHandlers,];export { resetNotificationsStore } from "@portal/mocks/handlers/notifications";diff --git a/frontend/portal/src/mocks/handlers/infrastructure.ts b/frontend/portal/src/mocks/handlers/infrastructure.tsindex 5262eb4ff0..3b3029cb2a 100644--- a/frontend/portal/src/mocks/handlers/infrastructure.ts+++ b/frontend/portal/src/mocks/handlers/infrastructure.ts@@ -3,6 +3,7 @@ import type { Tier } from "@portal/contexts/TierContext";import {apiKeysFor,auditLogFor,+ modelsResponseFor,recentDeploymentsFor,regionsFor,securityFor,@@ -34,6 +35,11 @@ export const infrastructureHandlers = [return HttpResponse.json(securityFor(tierFrom(request)));}),+ http.get("/v1/infrastructure/models", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(modelsResponseFor(tierFrom(request)));+ }),+http.get("/v1/infrastructure/storage", async ({ request }) => {await delay(120);return HttpResponse.json(storageFor(tierFrom(request)));diff --git a/frontend/portal/src/mocks/handlers/pipelines.ts b/frontend/portal/src/mocks/handlers/pipelines.tsindex 9e28f8d417..c947564652 100644--- a/frontend/portal/src/mocks/handlers/pipelines.ts+++ b/frontend/portal/src/mocks/handlers/pipelines.ts@@ -9,4 +9,12 @@ export const pipelinesHandlers = [const tier = (url.searchParams.get("tier") ?? "pro") as Tier;return HttpResponse.json(pipelinesFor(tier));}),++ // Accepts the promote-to-policy submit so the UI can resolve. The real+ // backend would create a policy from the pipeline's stages; here it just+ // acknowledges. See TODO(backend) on api/pipelines.ts promoteToPolicy.+ http.post("/v1/pipelines/:id/promote-to-policy", async () => {+ await delay(120);+ return HttpResponse.json({ ok: true });+ }),];diff --git a/frontend/portal/src/mocks/handlers/policies.ts b/frontend/portal/src/mocks/handlers/policies.tsnew file mode 100644index 0000000000..521fcaf8d9--- /dev/null+++ b/frontend/portal/src/mocks/handlers/policies.ts@@ -0,0 +1,183 @@+import { http, HttpResponse, delay } from "msw";+import {+ POLICY_CATEGORIES,+ POLICY_CONFIG,+ seedPolicies,+ seedRuntime,+ emptyRuntime,+ type CatalogueEntry,+ type DecoratedPolicy,+ type PoliciesResponse,+ type PoliciesSummary,+ type Policy,+ type PolicyRowStatus,+ type PolicyRuntime,+ type PolicyState,+} from "@portal/mocks/policies";++/**+ * The portal exercises the REAL policy API base — `/api/v1/policies`, NOT the+ * portal's usual `/v1/...` — so this surface is plug-and-play against the live+ * backend (drop MSW and the same calls hit Stirling). These handlers mutate an+ * in-memory store, so create/delete/run behave like a real backend within a+ * session (see the notifications handler for the same stateful pattern).+ */++/** Configured policies, keyed by backend id (the source of truth). */+let store: Policy[] = seedPolicies();+/** Runtime extras the wire record doesn't carry (scope, stats, activity). */+let runtime: Record<string, PolicyRuntime> = seedRuntime();++export function resetPoliciesStore(+ seed?: Policy[],+ seedRt?: Record<string, PolicyRuntime>,+): void {+ store = seed ? [...seed] : seedPolicies();+ runtime = seedRt ? { ...seedRt } : seedRuntime();+}++let idCounter = 0;+function nextId(categoryId: string): string {+ idCounter += 1;+ return `pol_${categoryId}_${Date.now().toString(36)}_${idCounter}`;+}++/** Derive the display status from the wire `enabled` flag. */+function rowStatus(policy: Policy): PolicyRowStatus {+ return policy.enabled ? "active" : "paused";+}++/** Build the decorated runtime view the catalogue/detail consumes. */+function decorate(policy: Policy): DecoratedPolicy | null {+ const category = POLICY_CATEGORIES.find((c) => c.id === policy.categoryId);+ const config = POLICY_CONFIG[policy.categoryId];+ if (!category || !config) return null;+ const rt = runtime[policy.id] ?? emptyRuntime();+ const status = rowStatus(policy);+ const state: PolicyState = {+ configured: true,+ status: status === "paused" ? "paused" : "active",+ sources: policy.sources.map((s) => s.source),+ scopeTypes: rt.scopeTypes,+ reviewerEmail: rt.reviewerEmail,+ fieldValues: rt.fieldValues,+ outputMode: policy.output.mode,+ outputName: policy.output.name,+ runOn: policy.trigger?.event ?? "upload",+ backendId: policy.id,+ isDefault: rt.isDefault,+ };+ return {+ category,+ config,+ state,+ steps: policy.steps,+ stats: rt.stats,+ activity: rt.activity,+ };+}++/** The full catalogue response: every category, each with its policy (or null). */+function buildResponse(): PoliciesResponse {+ const byCategory = new Map<string, Policy>();+ for (const p of store) byCategory.set(p.categoryId, p);++ const catalogue: CatalogueEntry[] = POLICY_CATEGORIES.map((category) => {+ const policy = byCategory.get(category.id);+ return {+ category,+ config: POLICY_CONFIG[category.id],+ policy: policy ? decorate(policy) : null,+ };+ });++ const active = store.filter((p) => p.enabled).length;+ const paused = store.filter((p) => !p.enabled).length;+ const docsEnforced = store+ .filter((p) => p.enabled)+ .reduce((sum, p) => sum + (runtime[p.id]?.stats.enforced ?? 0), 0);+ const summary: PoliciesSummary = {+ active,+ paused,+ categories: POLICY_CATEGORIES.length,+ docsEnforced,+ };++ return { summary, catalogue };+}++export const policiesHandlers = [+ // List — the catalogue (categories + configs + configured policies).+ http.get("/api/v1/policies", async () => {+ await delay(120);+ return HttpResponse.json(buildResponse());+ }),++ // Get one stored policy by id (the raw wire record).+ http.get("/api/v1/policies/:id", async ({ params }) => {+ await delay(120);+ const policy = store.find((p) => p.id === params.id);+ if (!policy) return new HttpResponse(null, { status: 404 });+ return HttpResponse.json(policy);+ }),++ // Create or update — a blank id is assigned (create) or matched (update).+ // One policy per category: a create for a category that already has one+ // replaces it, matching the editor's "one policy per category, ever".+ http.post("/api/v1/policies", async ({ request }) => {+ await delay(120);+ const incoming = (await request.json()) as Policy;+ const existing = incoming.id+ ? store.find((p) => p.id === incoming.id)+ : store.find((p) => p.categoryId === incoming.categoryId);+ const id = existing?.id ?? nextId(incoming.categoryId);+ const saved: Policy = {+ ...incoming,+ id,+ owner: existing?.owner ?? "[email protected]",+ };+ store = existing+ ? store.map((p) => (p.id === id ? saved : p))+ : [...store, saved];+ // Seed runtime for a brand-new policy so the detail panel has somewhere to+ // read from; an update keeps whatever runtime it already had.+ if (!runtime[id]) runtime[id] = emptyRuntime();+ return HttpResponse.json(saved);+ }),++ // Delete a stored policy by id.+ http.delete("/api/v1/policies/:id", async ({ params }) => {+ await delay(120);+ const id = String(params.id);+ const existed = store.some((p) => p.id === id);+ if (!existed) return new HttpResponse(null, { status: 404 });+ store = store.filter((p) => p.id !== id);+ delete runtime[id];+ return new HttpResponse(null, { status: 204 });+ }),++ // Run a stored policy now. The real endpoint is multipart (files) and returns+ // a run id; the portal has no files, so the mock just acknowledges with a run+ // id and nudges the activity feed so the run is visible.+ http.post("/api/v1/policies/:id/run", async ({ params }) => {+ await delay(120);+ const id = String(params.id);+ const policy = store.find((p) => p.id === id);+ if (!policy) return new HttpResponse(null, { status: 404 });+ const rt = runtime[id] ?? emptyRuntime();+ runtime[id] = {+ ...rt,+ activity: [+ {+ doc: "manual-run.pdf",+ action: "Enforcing…",+ time: "just now",+ status: "processing",+ },+ ...rt.activity,+ ],+ };+ const runId = `run_${Date.now().toString(36)}`;+ return HttpResponse.json({ status: true, fileId: runId, message: null });+ }),+];diff --git a/frontend/portal/src/mocks/handlers/sdkComponents.ts b/frontend/portal/src/mocks/handlers/sdkComponents.tsnew file mode 100644index 0000000000..9cceaefdd7--- /dev/null+++ b/frontend/portal/src/mocks/handlers/sdkComponents.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildComponentsResponse } from "@portal/mocks/sdkComponents";++export const sdkComponentsHandlers = [+ http.get("/v1/components", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildComponentsResponse(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/users.ts b/frontend/portal/src/mocks/handlers/users.tsnew file mode 100644index 0000000000..76a5e7796b--- /dev/null+++ b/frontend/portal/src/mocks/handlers/users.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildUsersResponse } from "@portal/mocks/users";++export const usersHandlers = [+ http.get("/v1/users", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildUsersResponse(tier));+ }),+];diff --git a/frontend/portal/src/mocks/home.ts b/frontend/portal/src/mocks/home.tsindex 13b5f731fc..229da46fa2 100644--- a/frontend/portal/src/mocks/home.ts+++ b/frontend/portal/src/mocks/home.ts@@ -214,6 +214,72 @@ export const REGION_HEALTH: RegionHealth[] = [},];+/**+ * Starter pipelines offered by the Home fork wizard. Forking clones one of+ * these templates as the seed for a new developer pipeline. Every template+ * runs the same four canonical stages (Ingest → Validate → Secure → Store);+ * the fixtures differ only in framing copy and which document types they target.+ */+export interface PipelineTemplate {+ id: string;+ /** Display name shown on the template chip and the ready-state header. */+ name: string;+ /** One-line description of what the forked pipeline does. */+ blurb: string;+ /** Document types this template is tuned for. */+ docTypes: string[];+ accent: "blue" | "purple" | "green" | "amber";+}++export const PIPELINE_TEMPLATES: PipelineTemplate[] = [+ {+ id: "coi-compliance",+ name: "COI Compliance",+ blurb: "Validate certificates of insurance against carrier requirements.",+ docTypes: ["Certificates of insurance", "Loss runs"],+ accent: "blue",+ },+ {+ id: "accounts-payable",+ name: "Accounts Payable",+ blurb: "Extract line items, match POs, and flag duplicate invoices.",+ docTypes: ["Invoices", "Purchase orders"],+ accent: "green",+ },+ {+ id: "contract-review",+ name: "Contract Review",+ blurb: "Classify clauses, redact PII, and route to the right reviewer.",+ docTypes: ["MSAs", "DPAs", "NDAs"],+ accent: "purple",+ },+ {+ id: "prior-authorization",+ name: "Prior Authorization",+ blurb: "Read auth requests, check coverage, and assemble payer packets.",+ docTypes: ["Auth requests", "Clinical notes"],+ accent: "amber",+ },+];++/**+ * The four canonical stages every forked pipeline runs. Fixed and ordered —+ * the wizard's build animation lights them up left-to-right.+ */+export interface PipelineStage {+ key: string;+ label: string;+ /** What the stage does, shown under the label in the ready-state grid. */+ detail: string;+}++export const PIPELINE_STAGES: PipelineStage[] = [+ { key: "ingest", label: "Ingest", detail: "Accept, normalize, deduplicate" },+ { key: "validate", label: "Validate", detail: "Classify and check schema" },+ { key: "secure", label: "Secure", detail: "Redact PII, encrypt at rest" },+ { key: "store", label: "Store", detail: "Emit JSON, persist, notify" },+];+export interface OnboardingStep {id: string;title: string;diff --git a/frontend/portal/src/mocks/infrastructure.ts b/frontend/portal/src/mocks/infrastructure.tsindex a6f945d313..98e06994a7 100644--- a/frontend/portal/src/mocks/infrastructure.ts+++ b/frontend/portal/src/mocks/infrastructure.ts@@ -281,11 +281,56 @@ export interface IpAllowEntry {added: string;}+/**+ * Where encryption keys live. Mirrors the {@link AccessPolicy} posture but is+ * surfaced separately because the key *custody model* (who can decrypt) is the+ * detail security teams scrutinise:+ * - `managed` — Stirling-owned KMS keys; zero key ops on the customer side.+ * - `byok` — customer key, but Stirling can use it to decrypt while processing.+ * - `hyok` — key never leaves the customer KMS; Stirling holds only ciphertext.+ */+export type KeyMode = "managed" | "byok" | "hyok";++export interface KeyManagement {+ mode: KeyMode;+ /** Human-readable provider, e.g. "Stirling KMS" or "AWS KMS (customer)". */+ provider: string;+ /** ARN-style identifier for the active key. */+ keyId: string;+ /** Encryption algorithm in force. */+ algorithm: string;+ /** Relative last-rotation time, e.g. "32 days ago". */+ lastRotated: string;+ /** Rotation cadence summary, e.g. "Automatic · every 90 days". */+ rotationPolicy: string;+ /**+ * Whether the customer may switch key custody (BYOK/HYOK). Stirling-managed+ * tiers see the posture but cannot change provider — only enterprise can.+ */+ customerManaged: boolean;+}++export type AttestationStatus = "attested" | "in-scope" | "not-applicable";++export interface ComplianceAttestation {+ id: string;+ name: string;+ /** Framework family / short descriptor shown under the name. */+ framework: string;+ status: AttestationStatus;+ /** Coverage or audit detail, e.g. "Type II · audited Apr 2026". */+ detail: string;+ /** Stub link to the downloadable report; null when none is available. */+ reportUrl: string | null;+}+export interface SecurityConfig {accessPolicy: AccessPolicy;dataResidency: DataResidency;certs: ComplianceCert[];ipAllowlist: IpAllowEntry[];+ keyManagement: KeyManagement;+ attestations: ComplianceAttestation[];}const CERTS_FULL: ComplianceCert[] = [@@ -366,6 +411,118 @@ const IP_ALLOWLIST: IpAllowEntry[] = [},];+// Stirling-managed key custody — what free/pro tiers run on. No key ops on the+// customer side, so the provider/key fields describe Stirling's own KMS.+const KEY_MANAGED: KeyManagement = {+ mode: "managed",+ provider: "Stirling KMS",+ keyId: "arn:stirling:kms:us-east-1:platform/cmk-default",+ algorithm: "AES-256-GCM",+ lastRotated: "32 days ago",+ rotationPolicy: "Automatic · every 90 days",+ customerManaged: false,+};++const KEY_HYOK: KeyManagement = {+ mode: "hyok",+ provider: "AWS CloudHSM (customer)",+ keyId: "arn:aws:kms:eu-west-1:418xxxx:key/2a7e-hyok",+ algorithm: "AES-256-GCM · external key store",+ lastRotated: "5 days ago",+ rotationPolicy: "Customer-controlled · keys never leave your HSM",+ customerManaged: true,+};++// Full attestation set an enterprise contract is covered by.+const ATTESTATIONS_FULL: ComplianceAttestation[] = [+ {+ id: "soc2",+ name: "SOC 2 Type II",+ framework: "AICPA Trust Services",+ status: "attested",+ detail: "Type II · audited Apr 2026 · Coalfire",+ reportUrl: "/v1/infrastructure/security/reports/soc2",+ },+ {+ id: "iso27001",+ name: "ISO 27001",+ framework: "ISO/IEC 27001:2022",+ status: "attested",+ detail: "Cert #IS-774201 · valid to 2027",+ reportUrl: "/v1/infrastructure/security/reports/iso27001",+ },+ {+ id: "hipaa",+ name: "HIPAA",+ framework: "US healthcare · PHI",+ status: "attested",+ detail: "BAA signed · PHI-eligible workloads",+ reportUrl: "/v1/infrastructure/security/reports/hipaa",+ },+ {+ id: "gdpr",+ name: "GDPR",+ framework: "EU data protection",+ status: "attested",+ detail: "EU SCCs · DPA on file · EU residency",+ reportUrl: "/v1/infrastructure/security/reports/gdpr",+ },+ {+ id: "pci",+ name: "PCI DSS",+ framework: "Payment card data",+ status: "in-scope",+ detail: "SAQ-D in progress · QSA assessment Q3",+ reportUrl: null,+ },+];++// What lower tiers can claim: the platform-inherited attestations only. HIPAA+// and PCI require a paid contract + signed paperwork, so they read as+// not-applicable until the customer upgrades.+const ATTESTATIONS_FREE: ComplianceAttestation[] = [+ {+ id: "soc2",+ name: "SOC 2 Type II",+ framework: "AICPA Trust Services",+ status: "attested",+ detail: "Inherited — Stirling platform",+ reportUrl: "/v1/infrastructure/security/reports/soc2",+ },+ {+ id: "iso27001",+ name: "ISO 27001",+ framework: "ISO/IEC 27001:2022",+ status: "attested",+ detail: "Inherited — Stirling platform",+ reportUrl: "/v1/infrastructure/security/reports/iso27001",+ },+ {+ id: "gdpr",+ name: "GDPR",+ framework: "EU data protection",+ status: "in-scope",+ detail: "Standard EU processing terms",+ reportUrl: null,+ },+ {+ id: "hipaa",+ name: "HIPAA",+ framework: "US healthcare · PHI",+ status: "not-applicable",+ detail: "Requires a paid plan + signed BAA",+ reportUrl: null,+ },+ {+ id: "pci",+ name: "PCI DSS",+ framework: "Payment card data",+ status: "not-applicable",+ detail: "Requires an enterprise contract",+ reportUrl: null,+ },+];+export function securityFor(tier: Tier): SecurityConfig {if (tier === "free") {return {@@ -373,6 +530,8 @@ export function securityFor(tier: Tier): SecurityConfig {dataResidency: "us",certs: CERTS_FREE,ipAllowlist: [],+ keyManagement: KEY_MANAGED,+ attestations: ATTESTATIONS_FREE,};}if (tier === "pro") {@@ -381,6 +540,9 @@ export function securityFor(tier: Tier): SecurityConfig {dataResidency: "us",certs: CERTS_FULL,ipAllowlist: IP_ALLOWLIST.slice(0, 2),+ // Pro stays on Stirling-managed keys; BYOK/HYOK is an enterprise lever.+ keyManagement: KEY_MANAGED,+ attestations: ATTESTATIONS_FREE,};}return {@@ -388,6 +550,8 @@ export function securityFor(tier: Tier): SecurityConfig {dataResidency: "eu",certs: CERTS_FULL,ipAllowlist: IP_ALLOWLIST,+ keyManagement: KEY_HYOK,+ attestations: ATTESTATIONS_FULL,};}@@ -626,6 +790,252 @@ export interface AuditLogResponse {events: AuditEvent[];}+/* ──────────────────────────────────────────────────────────────────────── */+/* Models */+/* ──────────────────────────────────────────────────────────────────────── */++export type ModelProvider = "stirling" | "openai" | "anthropic" | "on-prem";+export type ModelType = "extraction" | "classification" | "ocr" | "llm";+export type ModelStatus = "active" | "degraded" | "disabled";++/** Whether a model's cost is billed per 1k documents or per individual call. */+export type ModelCostUnit = "per-1k-docs" | "per-call";++export interface ModelEntry {+ id: string;+ name: string;+ provider: ModelProvider;+ type: ModelType;+ status: ModelStatus;+ /** Median inference latency, ms. */+ latencyMs: number;+ /** Cost in USD for the model's billing unit (see {@link costUnit}). */+ cost: number;+ costUnit: ModelCostUnit;+ version: string;+ /** Share of capacity this model is currently absorbing (0–1). */+ load: number;+ /** True for customer-registered bring-your-own / on-prem models. */+ managed: boolean;+}++/** A binding from a processing operation (optionally a doc-type) to a model. */+export interface RoutingRule {+ id: string;+ /** The operation or pipeline stage this rule governs. */+ operation: string;+ /** Doc-type scope, or "All document types" for a catch-all. */+ docType: string;+ /** id of the {@link ModelEntry} this operation routes to. */+ modelId: string;+ modelName: string;+ /** Marks the fallback rule applied when no narrower rule matches. */+ isDefault: boolean;+}++export interface ModelsSummary {+ activeModels: number;+ /** Capacity-weighted average latency across active models, ms. */+ avgLatencyMs: number;+ /** Projected monthly model spend, USD. */+ monthlySpend: number;+}++export interface ModelsResponse {+ summary: ModelsSummary;+ models: ModelEntry[];+ routing: RoutingRule[];+}++const MODELS_ALL: ModelEntry[] = [+ {+ id: "m-extract-v3",+ name: "Stirling Extract",+ provider: "stirling",+ type: "extraction",+ status: "active",+ latencyMs: 142,+ cost: 0.9,+ costUnit: "per-1k-docs",+ version: "v3.4.2",+ load: 0.71,+ managed: true,+ },+ {+ id: "m-classify-v2",+ name: "Stirling Classify",+ provider: "stirling",+ type: "classification",+ status: "active",+ latencyMs: 61,+ cost: 0.4,+ costUnit: "per-1k-docs",+ version: "v2.8.0",+ load: 0.48,+ managed: true,+ },+ {+ id: "m-ocr-tess",+ name: "Stirling OCR",+ provider: "stirling",+ type: "ocr",+ status: "active",+ latencyMs: 318,+ cost: 1.2,+ costUnit: "per-1k-docs",+ version: "v3.1.0",+ load: 0.55,+ managed: true,+ },+ {+ id: "m-gpt4o",+ name: "GPT-4o",+ provider: "openai",+ type: "llm",+ status: "active",+ latencyMs: 880,+ cost: 0.012,+ costUnit: "per-call",+ version: "2026-05",+ load: 0.33,+ managed: true,+ },+ {+ id: "m-claude-sonnet",+ name: "Claude Sonnet 4.5",+ provider: "anthropic",+ type: "llm",+ status: "degraded",+ latencyMs: 1240,+ cost: 0.009,+ costUnit: "per-call",+ version: "2026-04",+ load: 0.21,+ managed: true,+ },+ {+ id: "m-onprem-ocr",+ name: "On-prem OCR (Tesseract)",+ provider: "on-prem",+ type: "ocr",+ status: "active",+ latencyMs: 502,+ cost: 0,+ costUnit: "per-1k-docs",+ version: "byo-1.2",+ load: 0.12,+ managed: false,+ },+ // Registered but parked: a customer LLM weight kept warm without traffic.+ {+ id: "m-onprem-llm",+ name: "On-prem Llama 3 70B",+ provider: "on-prem",+ type: "llm",+ status: "disabled",+ latencyMs: 0,+ cost: 0,+ costUnit: "per-call",+ version: "byo-0.9",+ load: 0,+ managed: false,+ },+];++export function modelsFor(tier: Tier): ModelEntry[] {+ // Free sees only the two managed Stirling models it can actually use.+ if (tier === "free")+ return MODELS_ALL.filter(+ (m) => m.id === "m-extract-v3" || m.id === "m-classify-v2",+ );+ // Pro gets the full managed catalogue but no bring-your-own / on-prem models.+ if (tier === "pro") return MODELS_ALL.filter((m) => m.managed);+ return MODELS_ALL;+}++const ROUTING_ALL: RoutingRule[] = [+ {+ id: "r-extract",+ operation: "Field extraction",+ docType: "Invoices",+ modelId: "m-extract-v3",+ modelName: "Stirling Extract",+ isDefault: false,+ },+ {+ id: "r-classify",+ operation: "Document classification",+ docType: "All document types",+ modelId: "m-classify-v2",+ modelName: "Stirling Classify",+ isDefault: false,+ },+ {+ id: "r-ocr",+ operation: "Text recognition",+ docType: "Scanned PDFs",+ modelId: "m-ocr-tess",+ modelName: "Stirling OCR",+ isDefault: false,+ },+ {+ id: "r-summarize",+ operation: "Summarisation",+ docType: "Contracts",+ modelId: "m-gpt4o",+ modelName: "GPT-4o",+ isDefault: false,+ },+ // Catch-all: any operation without a narrower rule falls back here.+ {+ id: "r-default",+ operation: "Default",+ docType: "All document types",+ modelId: "m-extract-v3",+ modelName: "Stirling Extract",+ isDefault: true,+ },+];++export function routingFor(tier: Tier): RoutingRule[] {+ // Free has no routing control — the table is locked behind an upgrade nudge,+ // so there are no rules to surface.+ if (tier === "free") return [];+ if (tier === "pro") return ROUTING_ALL.filter((r) => r.modelId !== "m-gpt4o");+ return ROUTING_ALL;+}++export function modelsResponseFor(tier: Tier): ModelsResponse {+ const models = modelsFor(tier);+ const active = models.filter((m) => m.status === "active");++ // Average latency is capacity-weighted so a barely-used model doesn't skew+ // the headline; falls back to a plain mean when nothing is taking load.+ const totalLoad = active.reduce((sum, m) => sum + m.load, 0);+ const avgLatencyMs =+ totalLoad > 0+ ? Math.round(+ active.reduce((sum, m) => sum + m.latencyMs * m.load, 0) / totalLoad,+ )+ : active.length > 0+ ? Math.round(+ active.reduce((sum, m) => sum + m.latencyMs, 0) / active.length,+ )+ : 0;++ const monthlySpend = tier === "free" ? 0 : tier === "pro" ? 1840 : 6120;++ return {+ summary: {+ activeModels: active.length,+ avgLatencyMs,+ monthlySpend,+ },+ models,+ routing: routingFor(tier),+ };+}+export function auditLogFor(tier: Tier): AuditLogResponse {const events =tier === "free"diff --git a/frontend/portal/src/mocks/pipelines.ts b/frontend/portal/src/mocks/pipelines.tsindex b50d2688dd..3183581f53 100644--- a/frontend/portal/src/mocks/pipelines.ts+++ b/frontend/portal/src/mocks/pipelines.ts@@ -49,6 +49,13 @@ export interface GoldenSet {total: number;/** Last time the set was run. */lastRun: string;+ /**+ * Minimum pass rate (fraction) this pipeline must hold to be considered+ * reliable. A pipeline below its own bound is amber/red at a glance — the+ * bound is per-pipeline because a clause-risk pipeline tolerates less slack+ * than a high-volume extraction one.+ */+ threshold: number;}/** A single field whose shape has drifted from the inferred schema. */@@ -140,7 +147,7 @@ const COI_COMPLIANCE: Pipeline = {["Redact PII", "Encryption at rest"],["Primary store", "Processing manifest"],),- golden: { passing: 36, total: 36, lastRun: "2h ago" },+ golden: { passing: 36, total: 36, lastRun: "2h ago", threshold: 0.95 },drift: [],};@@ -167,7 +174,8 @@ const PRIOR_AUTH: Pipeline = {["Redact PII", "PII/PHI enforcement", "Encryption at rest"],["Conditional routing", "Human review"],),- golden: { passing: 24, total: 28, lastRun: "47m ago" },+ // Below its own 0.90 bound (24/28 ≈ 0.857) — the at-a-glance reliability miss.+ golden: { passing: 24, total: 28, lastRun: "47m ago", threshold: 0.9 },drift: [{field: "procedure_codes",@@ -209,7 +217,7 @@ const INVOICE_AP: Pipeline = {["Redact PII", "Encryption at rest"],["Primary store", "Mirror to bucket", "Notify"],),- golden: { passing: 41, total: 42, lastRun: "1h ago" },+ golden: { passing: 41, total: 42, lastRun: "1h ago", threshold: 0.95 },drift: [{field: "tax",@@ -244,7 +252,7 @@ const CONTRACT_REVIEW: Pipeline = {["Redact PII", "Confidentiality mark", "Signed outputs"],["Human review", "Flag"],),- golden: { passing: 31, total: 33, lastRun: "5h ago" },+ golden: { passing: 31, total: 33, lastRun: "5h ago", threshold: 0.95 },drift: [],};@@ -272,7 +280,7 @@ const KYC_PROCESSOR: Pipeline = {["Field-aware redact", "Attribution watermark", "Encryption at rest"],["Compliance archive", "Processing manifest", "Notify"],),- golden: { passing: 52, total: 54, lastRun: "31m ago" },+ golden: { passing: 52, total: 54, lastRun: "31m ago", threshold: 0.95 },drift: [{field: "document_number",@@ -304,15 +312,86 @@ const ENTERPRISE_EVALS: EvalsNote = {"Prior Auth v3.2.0-rc and Invoice v2.9.0-rc are mirroring live traffic in shadow; KYC v4.1.0 is in a comparative run against v4.0.3. The Contract Review v2.0.0 candidate is blocked — it regressed 3 golden cases on clause-risk scoring, so the comparative run is held until the candidate is re-cut. No promotion happens until a candidate clears its golden set and the comparative delta stays inside bounds.",};+/**+ * A pipeline that began life as an Editor watch-folder flow and was promoted+ * into the portal. These are the on-ramp from ad-hoc desktop automation to a+ * governed, deployed pipeline — they keep a pointer back to the watch folder+ * they grew out of so the lineage stays visible.+ */+export interface PromotedPipeline {+ id: string;+ name: string;+ /** Doc type the originating watch-folder flow was built around. */+ sourceDocType: string;+ /** The Editor watch folder this was promoted from. */+ watchFolder: string;+ /** Where the promotion sits in its lifecycle. */+ status: PromotedStatus;+ /** When the promotion landed. */+ promotedAt: string;+}++/**+ * A promoted flow is `deployed` once it runs in the portal, `staged` while it+ * mirrors the watch folder without taking over, and `review` when it needs a+ * human to confirm the flow before it goes live.+ */+export type PromotedStatus = "deployed" | "staged" | "review";+export interface PipelinesResponse {pipelines: Pipeline[];/** Present for enterprise only. */evals: EvalsNote | null;+ /** Flows promoted up from Editor watch folders. Empty on free. */+ promoted: PromotedPipeline[];}+/* ──────────────────────────────────────────────────────────────────────── */+/* Promoted-from-Editor fixtures */+/* ──────────────────────────────────────────────────────────────────────── */++const PROMOTED_PRO: PromotedPipeline[] = [+ {+ id: "pl-promo-statements",+ name: "Bank Statement Normalizer",+ sourceDocType: "Bank statement",+ watchFolder: "~/StirlingWatch/statements-in",+ status: "deployed",+ promotedAt: "promoted 3d ago",+ },+ {+ id: "pl-promo-receipts",+ name: "Receipt Splitter",+ sourceDocType: "Expense receipt",+ watchFolder: "~/StirlingWatch/receipts",+ status: "staged",+ promotedAt: "promoted 11h ago",+ },+];++const PROMOTED_ENTERPRISE: PromotedPipeline[] = [+ ...PROMOTED_PRO,+ {+ id: "pl-promo-claims",+ name: "Claims Intake Splitter",+ sourceDocType: "Insurance claim",+ watchFolder: "\\\\fileserver\\ClaimsDropbox",+ status: "deployed",+ promotedAt: "promoted 6d ago",+ },+ {+ id: "pl-promo-onboarding",+ name: "New-Hire Packet Sorter",+ sourceDocType: "Onboarding packet",+ watchFolder: "\\\\hr-share\\NewHireScans",+ status: "review",+ promotedAt: "promoted 2h ago",+ },+];+export function pipelinesFor(tier: Tier): PipelinesResponse {if (tier === "free") {- return { pipelines: [], evals: null };+ return { pipelines: [], evals: null, promoted: [] };}if (tier === "enterprise") {return {@@ -324,11 +403,13 @@ export function pipelinesFor(tier: Tier): PipelinesResponse {CONTRACT_REVIEW,],evals: ENTERPRISE_EVALS,+ promoted: PROMOTED_ENTERPRISE,};}// proreturn {pipelines: [COI_COMPLIANCE, INVOICE_AP, PRIOR_AUTH],evals: null,+ promoted: PROMOTED_PRO,};}diff --git a/frontend/portal/src/mocks/policies.ts b/frontend/portal/src/mocks/policies.tsnew file mode 100644index 0000000000..ccf28345ec--- /dev/null+++ b/frontend/portal/src/mocks/policies.ts@@ -0,0 +1,612 @@+/**+ * Policies fixtures and the canonical TS model the portal shares with them.+ *+ * The model mirrors the editor + backend policy contract so the portal's+ * "set up a policy" flow is plug-and-play against the real `/api/v1/policies`+ * API. A policy is a stored automation: an ordered chain of tool steps (each+ * step's `operation` is a Stirling endpoint path) plus an output destination,+ * fired automatically by a trigger (editor upload/export) over a set of+ * sources. The catalogue groups policies by category, each category carrying a+ * `PolicyConfigDef` (summary, rules, fields, default tool chain) the setup flow+ * builds from.+ *+ * The wire types (`Policy`, `PipelineStep`) match the backend records exactly;+ * the catalogue + decorated state shapes (`PolicyConfigDef`, `PolicyField`,+ * `PolicyState`, …) are lifted from the editor's `types/policies.ts`, with+ * ReactNode icons replaced by string icon keys (the portal renders its own).+ *+ * api/policies.ts re-exports these types; the MSW handlers serve the fixture+ * data over intercepted httpJson() calls. Components never reach in here.+ */++/* ──────────────────────────────────────────────────────────────────────── */+/* Backend wire model — matches Policy.java / PipelineStep.java exactly */+/* ──────────────────────────────────────────────────────────────────────── */++/**+ * A single tool invocation in a policy's pipeline. `operation` is a Stirling+ * endpoint path (e.g. `/api/v1/security/auto-redact`); `parameters` are the+ * scalar form fields that endpoint accepts. `fileParameters` binds a tool's+ * named file field to an asset key in a run's supporting-file store.+ */+export interface PipelineStep {+ operation: string;+ parameters: Record<string, unknown>;+ fileParameters?: Record<string, string>;+}++/** When a policy fires automatically. A null trigger means manual-only. */+export interface TriggerConfig {+ /** The editor event the policy runs on. */+ event: "upload" | "export";+}++/** Where a policy's documents come from (a connected source). */+export interface InputSpec {+ /** Source id from {@link POLICY_SOURCES}. */+ source: string;+}++/** How a run's result is delivered. */+export interface OutputSpec {+ /** A separate new file, or a new version of the input the policy ran on. */+ mode: "new_file" | "new_version";+ /** Rename rule for the output; empty keeps the input filename. */+ name: string;+ namePosition: "prefix" | "suffix" | "auto-number";+}++/**+ * The stored policy record — the exact JSON body the backend returns from+ * `GET /api/v1/policies` and accepts on `POST /api/v1/policies`. The portal+ * decorates this with catalogue + runtime data for display (see {@link decorate}).+ */+export interface Policy {+ /** Blank on create; the backend assigns one and returns it. */+ id: string;+ name: string;+ /** Server-assigned owner; the client never forges it. */+ owner?: string;+ /** Whether the trigger fires automatically. Pausing flips this. */+ enabled: boolean;+ trigger: TriggerConfig | null;+ sources: InputSpec[];+ steps: PipelineStep[];+ output: OutputSpec;+ /** The category this policy belongs to. Drives catalogue grouping. */+ categoryId: string;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Catalogue model — lifted from editor types/policies.ts */+/* ──────────────────────────────────────────────────────────────────────── */++export type PolicyStatus = "default" | "active" | "paused";++/** Derived display status for a card/detail. */+export type PolicyRowStatus = "active" | "paused" | "setup";++/** A configurable field within a policy's settings. */+export type PolicyFieldType = "toggle" | "select" | "chips" | "text";++export interface PolicyField {+ label: string;+ key: string;+ type: PolicyFieldType;+ /** Default value: boolean (toggle), string (select/text), string[] (chips). */+ value: boolean | string | string[];+ /** Options for select/chips. */+ options?: string[];+}++/**+ * Static definition of a policy category. The editor's `icon: ReactNode` is+ * replaced by a string `icon` key the portal resolves to its own glyph.+ */+export interface PolicyCategory {+ id: string;+ label: string;+ /** Icon key the portal renders (not a component — the portal owns glyphs). */+ icon: string;+ /** Visual tone for the category's icon chip. */+ tone: "neutral" | "blue" | "purple" | "green" | "amber" | "red";+ /** Long description shown in the setup flow. */+ desc: string;+ /** Drives the "Set up Classification" affordance (doc-type narrowing). */+ providesClassification?: boolean;+ /** Locked "Coming soon" — can't be opened or configured. */+ comingSoon?: boolean;+}++/** The narrative + field configuration backing a category. */+export interface PolicyConfigDef {+ /** One-line summary of what the policy enforces. */+ summary: string;+ /** Pipeline-like rule chips shown in the "Enforces" section. */+ rules: string[];+ /** Human label for the scope this policy applies to. */+ scopeLabel: string;+ /** Editable policy-level settings fields. */+ fields: PolicyField[];+ /**+ * The preset pipeline a new policy is seeded with — the real, editable tool+ * steps (each `operation` is a Stirling endpoint path, matching the backend's+ * PipelineStep). The setup flow starts from these.+ */+ defaultOperations: PipelineStep[];+}++/** A source a policy can run over (setup "Sources" step). */+export interface PolicySource {+ id: string;+ label: string;+ desc: string;+ /** Icon key the portal renders. */+ icon: string;+}++/** Three-up summary stats shown at the foot of a configured policy's detail. */+export interface PolicyStats {+ /** Documents enforced. */+ enforced: number;+ /** Human-formatted data-processed figure, e.g. "2.3 GB". */+ dataProcessed: string;+ /** Human-formatted active-for figure, e.g. "12d", or "—" when idle. */+ activeFor: string;+}++/** An entry in a policy's recent-activity feed. */+export interface PolicyActivityItem {+ /** Document the policy acted on. */+ doc: string;+ /** What the policy did, e.g. "Redacted 4 PII matches • 2 pages". */+ action: string;+ /** Relative timestamp, e.g. "2h ago". */+ time: string;+ /** "enforced" (clean), "flagged" (needs review), "processing" (running). */+ status: "enforced" | "flagged" | "processing";+}++/**+ * The collected settings the setup flow gathers and the detail panel reads —+ * the editor's `PolicyState`, minus the local-cache bookkeeping (folderId etc).+ */+export interface PolicyState {+ configured: boolean;+ status: PolicyStatus;+ /** Selected sources (ids from {@link POLICY_SOURCES}). */+ sources: string[];+ /** When non-empty, narrows the policy to these document types. */+ scopeTypes: string[];+ /** Email low-confidence enforcements are routed to. */+ reviewerEmail: string;+ /** Saved field values, keyed by field key (overrides the definition default). */+ fieldValues: Record<string, boolean | string | string[]>;+ /** How a run's output is delivered. Defaults to "new_version". */+ outputMode?: "new_file" | "new_version";+ /** Rename rule for the output. Empty keeps the input filename. */+ outputName?: string;+ /** When the policy runs. Defaults to "upload". */+ runOn?: "upload" | "export";+ /** Backend record id once persisted; used to update/delete/run it. */+ backendId?: string;+ /** A shipped catalogue policy (configurable but not deletable). */+ isDefault?: boolean;+}++/** What the setup flow hands back on submit — collected settings + built steps. */+export interface PolicySetupResult {+ fieldValues: Record<string, boolean | string | string[]>;+ sources: string[];+ scopeTypes: string[];+ reviewerEmail: string;+ outputMode: "new_file" | "new_version";+ outputName: string;+ outputNamePosition: "prefix" | "suffix" | "auto-number";+ runOn: "upload" | "export";+ /** The configured tool chain as backend pipeline steps. */+ steps: PipelineStep[];+}++/**+ * A configured policy as the catalogue view consumes it: the wire record plus+ * the catalogue's category/config and derived runtime data. The handlers build+ * this from the in-memory store + fixtures.+ */+export interface DecoratedPolicy {+ category: PolicyCategory;+ config: PolicyConfigDef;+ state: PolicyState;+ /** The policy's configured steps (drives the detail "Enforces" flow). */+ steps: PipelineStep[];+ stats: PolicyStats;+ activity: PolicyActivityItem[];+}++/** Catalogue strip totals shown above the cards. */+export interface PoliciesSummary {+ /** Policies currently active (enabled). */+ active: number;+ /** Policies configured but paused. */+ paused: number;+ /** Categories available to configure. */+ categories: number;+ /** Documents enforced across all active policies. */+ docsEnforced: number;+}++/** The `GET /api/v1/policies` response, in the portal's catalogue shape. */+export interface PoliciesResponse {+ summary: PoliciesSummary;+ /** Every catalogue category, each with its definition + (optional) state. */+ catalogue: CatalogueEntry[];+}++/** One catalogue row: a category, its definition, and its current state. */+export interface CatalogueEntry {+ category: PolicyCategory;+ config: PolicyConfigDef;+ /** The configured policy's runtime view, or null when not yet set up. */+ policy: DecoratedPolicy | null;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Tool → endpoint registry */+/* Maps a frontend tool id to its Stirling endpoint path. The setup flow's */+/* pipeline steps carry endpoint paths (the backend's PipelineStep contract), */+/* so this is the seam that keeps the preset chains plug-and-play. */+/* ──────────────────────────────────────────────────────────────────────── */++export const TOOL_ENDPOINTS: Record<string, string> = {+ redact: "/api/v1/security/auto-redact",+ sanitize: "/api/v1/security/sanitize-pdf",+ watermark: "/api/v1/security/add-watermark",+ ocr: "/api/v1/misc/ocr-pdf",+ flatten: "/api/v1/misc/flatten",+ compress: "/api/v1/misc/compress-pdf",+};++/** A friendly label for an endpoint path (for the detail "Enforces" chips). */+export const ENDPOINT_LABELS: Record<string, string> = {+ "/api/v1/security/auto-redact": "Redact PII",+ "/api/v1/security/sanitize-pdf": "Remove JavaScript",+ "/api/v1/security/add-watermark": "Watermark",+ "/api/v1/misc/ocr-pdf": "OCR",+ "/api/v1/misc/flatten": "Flatten",+ "/api/v1/misc/compress-pdf": "Compress",+};++/** "/api/v1/security/auto-redact" → "Auto Redact" — fallback humanisation. */+export function humanizeEndpoint(path: string): string {+ if (ENDPOINT_LABELS[path]) return ENDPOINT_LABELS[path];+ const last = path.split("/").filter(Boolean).pop() ?? path;+ return last+ .replace(/-/g, " ")+ .replace(/\b\w/g, (c) => c.toUpperCase())+ .trim();+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Catalogue definitions — categories, configs, sources, doc types */+/* Modelled on the editor's policyDefinitions. PII redact regexes are the */+/* precise patterns the /auto-redact endpoint matches (wordsToRedact). */+/* ──────────────────────────────────────────────────────────────────────── */++/** PII regexes seeded into a Security policy's redact step (SSN + cards). */+const DEFAULT_PII_PATTERNS: string[] = [+ "\\b(?!000|666|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0000)\\d{4}\\b", // SSN+ "\\b(?:4\\d{12}(?:\\d{3})?|5[1-5]\\d{14}|3[47]\\d{13}|6(?:011|5\\d{2})\\d{12})\\b", // cards+];++export const POLICY_CATEGORIES: PolicyCategory[] = [+ {+ id: "ingestion",+ label: "Ingestion",+ icon: "layers",+ tone: "blue",+ desc: "Classify documents, extract structured data, enforce naming conventions, and normalize pages.",+ providesClassification: true,+ comingSoon: true,+ },+ {+ id: "security",+ label: "Security",+ icon: "shield",+ tone: "purple",+ desc: "Detect PII, redact, strip active content, and watermark documents.",+ },+ {+ id: "compliance",+ label: "Compliance",+ icon: "check",+ tone: "amber",+ desc: "Enforce HIPAA, GDPR, SOC 2, or FedRAMP requirements on every document.",+ comingSoon: true,+ },+ {+ id: "routing",+ label: "Routing",+ icon: "route",+ tone: "green",+ desc: "Auto-route documents to the right team, folder, or system.",+ comingSoon: true,+ },+ {+ id: "retention",+ label: "Retention",+ icon: "clock",+ tone: "neutral",+ desc: "Set how long documents are kept, when to archive, and when to delete.",+ comingSoon: true,+ },+];++export const POLICY_CONFIG: Record<string, PolicyConfigDef> = {+ ingestion: {+ summary:+ "Classifies documents, extracts structured data, enforces naming, and normalizes pages.",+ rules: ["Classify", "Extract", "Name", "Normalize"],+ scopeLabel: "All documents",+ defaultOperations: [+ { operation: TOOL_ENDPOINTS.ocr, parameters: {} },+ { operation: TOOL_ENDPOINTS.flatten, parameters: {} },+ ],+ fields: [+ {+ label: "Min confidence",+ key: "minConfidence",+ type: "select",+ value: "80%",+ options: ["60%", "70%", "80%", "90%", "95%"],+ },+ {+ label: "Below threshold",+ key: "belowThreshold",+ type: "select",+ value: "Flag for review",+ options: ["Flag for review", "Route to bucket", "Hold"],+ },+ ],+ },+ security: {+ summary:+ "Detects and redacts PII, strips active content (JavaScript), and watermarks documents.",+ rules: ["Redact PII", "Remove JavaScript"],+ scopeLabel: "All documents",+ // Default chain: redact PII (flattened to image so text is truly removed) ++ // strip JavaScript. Watermark is offered in the designer but off by default.+ defaultOperations: [+ {+ operation: TOOL_ENDPOINTS.redact,+ parameters: {+ mode: "automatic",+ useRegex: true,+ convertPDFToImage: true,+ wordsToRedact: DEFAULT_PII_PATTERNS,+ },+ },+ {+ operation: TOOL_ENDPOINTS.sanitize,+ parameters: {+ removeJavaScript: true,+ removeEmbeddedFiles: false,+ removeMetadata: false,+ removeLinks: false,+ removeFonts: false,+ },+ },+ ],+ // The tool chain is configured per-tool in the designer (redact / sanitize /+ // watermark); no separate policy-level fields.+ fields: [],+ },+ compliance: {+ summary:+ "Validates documents against regulatory frameworks before they leave the system.",+ rules: ["Framework scan", "Enforce action", "Audit trail"],+ scopeLabel: "All documents",+ defaultOperations: [+ { operation: TOOL_ENDPOINTS.sanitize, parameters: {} },+ { operation: TOOL_ENDPOINTS.flatten, parameters: {} },+ ],+ fields: [+ {+ label: "Frameworks",+ key: "frameworks",+ type: "chips",+ value: ["HIPAA"],+ options: ["HIPAA", "GDPR", "SOC 2", "FedRAMP", "PCI DSS", "ISO 27001"],+ },+ {+ label: "When non-compliant",+ key: "onViolation",+ type: "select",+ value: "Flag for review",+ options: [+ "Flag for review",+ "Block export",+ "Auto-redact PHI",+ "Quarantine document",+ ],+ },+ { label: "Audit trail", key: "auditTrail", type: "toggle", value: true },+ { label: "Access log", key: "accessLog", type: "toggle", value: true },+ ],+ },+ routing: {+ summary:+ "Routes documents to the right destination based on type and classification.",+ rules: ["Auto-classify", "Route to folder", "Webhook notify"],+ scopeLabel: "All documents",+ defaultOperations: [{ operation: TOOL_ENDPOINTS.compress, parameters: {} }],+ fields: [+ {+ label: "Destination",+ key: "destination",+ type: "select",+ value: "Documents",+ options: ["Documents", "S3 bucket", "SharePoint", "Webhook"],+ },+ { label: "Webhook URL", key: "webhookUrl", type: "text", value: "" },+ { label: "Notify on route", key: "notify", type: "toggle", value: false },+ ],+ },+ retention: {+ summary:+ "Enforces how long documents are kept, when to archive, and when to delete.",+ rules: ["Retention hold", "Auto-archive", "Deletion block"],+ scopeLabel: "All documents",+ defaultOperations: [{ operation: TOOL_ENDPOINTS.compress, parameters: {} }],+ fields: [+ {+ label: "Keep for",+ key: "keepFor",+ type: "select",+ value: "7 years",+ options: ["30 days", "1 year", "3 years", "7 years", "Indefinite"],+ },+ {+ label: "Archive after",+ key: "archiveAfter",+ type: "select",+ value: "Never",+ options: ["30 days", "90 days", "1 year", "Never"],+ },+ {+ label: "Immutable hold",+ key: "immutableHold",+ type: "toggle",+ value: false,+ },+ ],+ },+};++export const POLICY_SOURCES: PolicySource[] = [+ {+ id: "editor",+ label: "Editor",+ desc: "Documents you save or export in Stirling",+ icon: "file",+ },+ {+ id: "device",+ label: "Entire device",+ desc: "All PDFs on this machine, retroactively",+ icon: "device",+ },+ {+ id: "sharepoint",+ label: "SharePoint",+ desc: "Connected SharePoint libraries",+ icon: "globe",+ },+ {+ id: "dropbox",+ label: "Dropbox",+ desc: "Connected Dropbox folders",+ icon: "cloud",+ },+ {+ id: "gmail",+ label: "Gmail",+ desc: "PDF attachments in email",+ icon: "mail",+ },+ {+ id: "gdrive",+ label: "Google Drive",+ desc: "Connected Drive folders",+ icon: "folder",+ },+];++export const POLICY_DOC_TYPES: string[] = [+ "Contracts",+ "Invoices",+ "Tax documents",+ "HR records",+ "Insurance",+ "Medical / PHI",+ "Legal filings",+ "Financial reports",+];++/* ──────────────────────────────────────────────────────────────────────── */+/* Seed policies — a few configured policies in the wire shape, so the store */+/* behaves like a backend that already has policies set up. */+/* ──────────────────────────────────────────────────────────────────────── */++/** The shipped default policies the handlers seed the store with. */+export function seedPolicies(): Policy[] {+ return [+ {+ id: "pol_security_default",+ name: "Security Policy",+ owner: "[email protected]",+ enabled: true,+ trigger: { event: "upload" },+ sources: [{ source: "editor" }],+ steps: POLICY_CONFIG.security.defaultOperations,+ output: { mode: "new_version", name: "", namePosition: "suffix" },+ categoryId: "security",+ },+ ];+}++/**+ * Per-policy runtime extras keyed by policy id — the parts the wire record+ * doesn't carry (collected field values, scope, derived stats + activity).+ * In a real backend these would be derived server-side from the user's files.+ */+export interface PolicyRuntime {+ scopeTypes: string[];+ reviewerEmail: string;+ fieldValues: Record<string, boolean | string | string[]>;+ stats: PolicyStats;+ activity: PolicyActivityItem[];+ isDefault?: boolean;+}++export function seedRuntime(): Record<string, PolicyRuntime> {+ return {+ pol_security_default: {+ scopeTypes: [],+ reviewerEmail: "[email protected]",+ fieldValues: {},+ isDefault: true,+ stats: { enforced: 4821, dataProcessed: "2.3 GB", activeFor: "34d" },+ activity: [+ {+ doc: "Q2-vendor-agreement.pdf",+ action: "Redacted 6 PII matches • JavaScript stripped",+ time: "12m ago",+ status: "enforced",+ },+ {+ doc: "patient-intake-0481.pdf",+ action: "Low-confidence match — routed for review",+ time: "1h ago",+ status: "flagged",+ },+ {+ doc: "invoice-7782.pdf",+ action: "Enforcing…",+ time: "just now",+ status: "processing",+ },+ ],+ },+ };+}++/** Empty stats/activity for a freshly-configured policy with no runs yet. */+export function emptyRuntime(reviewerEmail = "[email protected]"): PolicyRuntime {+ return {+ scopeTypes: [],+ reviewerEmail,+ fieldValues: {},+ stats: { enforced: 0, dataProcessed: "0 B", activeFor: "—" },+ activity: [],+ };+}diff --git a/frontend/portal/src/mocks/sdkComponents.ts b/frontend/portal/src/mocks/sdkComponents.tsnew file mode 100644index 0000000000..b5c5d0c060--- /dev/null+++ b/frontend/portal/src/mocks/sdkComponents.ts@@ -0,0 +1,522 @@+/**+ * Components surface fixtures and the types api/sdkComponents.ts shares with them.+ *+ * "Components" are embeddable React/Vue/Vanilla SDK widgets a developer drops+ * into their own product — a PDF Viewer, an E-Sign flow, an AI Review panel —+ * each metered per action (per render, per review, per signature). Every+ * component carries its npm package, maturity, supported frameworks, per-action+ * price, an install/usage snippet, and its key props.+ *+ * api/sdkComponents.ts imports the types; the MSW handlers serve the fixture+ * data over the intercepted httpJson() calls. Components never reach into this+ * module directly. Once a real backend exists the handlers stop being+ * registered and these fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";++/* ──────────────────────────────────────────────────────────────────────── */+/* Types */+/* ──────────────────────────────────────────────────────────────────────── */++export type ComponentMaturity = "ga" | "beta";++export type Framework = "React" | "Vue" | "Vanilla";++/** The action a component bills against — surfaces in the price unit label. */+export type BillingUnit =+ | "render"+ | "review"+ | "approval"+ | "signature"+ | "check"+ | "event"+ | "session";++export interface ComponentProp {+ name: string;+ /** TypeScript-ish type expression, shown verbatim in the API table. */+ type: string;+ required: boolean;+ description: string;+}++export interface ComponentPricing {+ /** Price per billed action in USD. */+ pricePerAction: number;+ unit: BillingUnit;+ /** Free-tier monthly allowance before metering kicks in; 0 = none. */+ freeQuota: number;+}++export interface SdkComponent {+ id: string;+ name: string;+ /** Package suffix — full name is `@stirling/<package>`. */+ package: string;+ description: string;+ maturity: ComponentMaturity;+ frameworks: Framework[];+ pricing: ComponentPricing;+ /** Install command (npm). */+ install: string;+ /** Minimal usage snippet shown under the Code tab. */+ usage: string;+ props: ComponentProp[];+ /**+ * Embeds attributed to this component over the trailing 30 days — drives the+ * per-card usage line. Zero for never-embedded components.+ */+ embeds30d: number;+ /**+ * Tier at which the component becomes available. Components above the active+ * tier render locked with an upgrade nudge. `pro` is the default floor.+ */+ minTier: Tier;+}++export interface ComponentsSummary {+ /** Count of GA (production-ready) components available to the tier. */+ gaCount: number;+ /** Count of Beta components available to the tier. */+ betaCount: number;+ /** Total embeds across all components this month. */+ embedsThisMonth: number;+ /** Month-to-date spend attributed to component actions, in USD. */+ spendThisMonth: number;+}++export interface ComponentsResponse {+ summary: ComponentsSummary;+ components: SdkComponent[];+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Presentation metadata (client-side product copy, not data) */+/* ──────────────────────────────────────────────────────────────────────── */++export interface MaturityMeta {+ label: string;+ tone: "success" | "info";+}++export const MATURITY_META: Record<ComponentMaturity, MaturityMeta> = {+ ga: { label: "GA", tone: "success" },+ beta: { label: "Beta", tone: "info" },+};++/** Human label for a billing unit, e.g. "render" → "/render". */+export const BILLING_UNIT_LABEL: Record<BillingUnit, string> = {+ render: "render",+ review: "review",+ approval: "approval",+ signature: "signature",+ check: "check",+ event: "event",+ session: "session",+};++/** Format a price as the per-action string shown on cards, e.g. "$0.04 / review". */+export function formatPrice(pricing: ComponentPricing): string {+ return `$${pricing.pricePerAction.toFixed(2)} / ${BILLING_UNIT_LABEL[pricing.unit]}`;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Fixtures */+/* ──────────────────────────────────────────────────────────────────────── */++/**+ * The catalogue. Authored once, then filtered/repriced per tier so a dev can+ * see tier variation (locked Beta components on free, enterprise discounts).+ */+const CATALOGUE: SdkComponent[] = [+ {+ id: "viewer",+ name: "Viewer",+ package: "viewer",+ description:+ "Drop-in PDF viewer with text selection, search, thumbnails and lazy page rendering. The cheapest, highest-volume primitive.",+ maturity: "ga",+ frameworks: ["React", "Vue", "Vanilla"],+ pricing: { pricePerAction: 0.01, unit: "render", freeQuota: 1000 },+ install: "npm install @stirling/viewer",+ usage: `import { Viewer } from "@stirling/viewer";++export function DocumentPage({ fileUrl }: { fileUrl: string }) {+ return (+ <Viewer+ src={fileUrl}+ apiKey={process.env.STIRLING_KEY}+ onRender={(p) => console.log("rendered page", p.page)}+ />+ );+}`,+ props: [+ {+ name: "src",+ type: "string | Blob",+ required: true,+ description: "Document URL or in-memory blob to render.",+ },+ {+ name: "apiKey",+ type: "string",+ required: true,+ description: "Publishable key used to meter renders.",+ },+ {+ name: "initialPage",+ type: "number",+ required: false,+ description: "Page to open on first render. Defaults to 1.",+ },+ {+ name: "onRender",+ type: "(e: RenderEvent) => void",+ required: false,+ description: "Fires per rendered page — one billed render each.",+ },+ ],+ embeds30d: 184200,+ minTier: "pro",+ },+ {+ id: "review",+ name: "Review",+ package: "review",+ description:+ "AI-assisted document review panel — surfaces extracted fields, risks and suggested redactions for a human to accept or reject.",+ maturity: "ga",+ frameworks: ["React", "Vue"],+ pricing: { pricePerAction: 0.04, unit: "review", freeQuota: 50 },+ install: "npm install @stirling/review",+ usage: `import { Review } from "@stirling/review";++export function ReviewPane({ docId }: { docId: string }) {+ return (+ <Review+ documentId={docId}+ pipeline="invoice-v3"+ apiKey={process.env.STIRLING_KEY}+ onComplete={(r) => save(r.fields)}+ />+ );+}`,+ props: [+ {+ name: "documentId",+ type: "string",+ required: true,+ description: "Id of an ingested document to review.",+ },+ {+ name: "pipeline",+ type: "string",+ required: true,+ description: "Pipeline whose extraction schema drives the panel.",+ },+ {+ name: "onComplete",+ type: "(r: ReviewResult) => void",+ required: false,+ description: "Called when the reviewer submits — bills one review.",+ },+ ],+ embeds30d: 42800,+ minTier: "pro",+ },+ {+ id: "confidence",+ name: "Confidence",+ package: "confidence",+ description:+ "Inline confidence overlay — paints per-field certainty heatmaps over extracted values so reviewers triage low-confidence fields first.",+ maturity: "ga",+ frameworks: ["React", "Vue", "Vanilla"],+ pricing: { pricePerAction: 0.02, unit: "check", freeQuota: 200 },+ install: "npm install @stirling/confidence",+ usage: `import { Confidence } from "@stirling/confidence";++export function FieldOverlay({ result }: { result: ExtractResult }) {+ return <Confidence fields={result.fields} threshold={0.85} />;+}`,+ props: [+ {+ name: "fields",+ type: "ExtractedField[]",+ required: true,+ description: "Fields with per-value confidence scores.",+ },+ {+ name: "threshold",+ type: "number",+ required: false,+ description: "Highlight fields below this 0..1 score. Defaults to 0.8.",+ },+ ],+ embeds30d: 31500,+ minTier: "pro",+ },+ {+ id: "approval",+ name: "Approval",+ package: "approval",+ description:+ "Routable approval flow — assign reviewers, collect sign-offs and enforce approval order before a document advances.",+ maturity: "ga",+ frameworks: ["React", "Vue"],+ pricing: { pricePerAction: 0.1, unit: "approval", freeQuota: 0 },+ install: "npm install @stirling/approval",+ usage: `import { Approval } from "@stirling/approval";++export function ApprovalGate({ docId }: { docId: string }) {+ return (+ <Approval+ documentId={docId}+ approvers={["[email protected]", "[email protected]"]}+ order="sequential"+ onApproved={() => advance(docId)}+ />+ );+}`,+ props: [+ {+ name: "documentId",+ type: "string",+ required: true,+ description: "Document the approval gate guards.",+ },+ {+ name: "approvers",+ type: "string[]",+ required: true,+ description: "Ordered list of approver email addresses.",+ },+ {+ name: "order",+ type: '"sequential" | "parallel"',+ required: false,+ description: "Routing mode. Defaults to sequential.",+ },+ ],+ embeds30d: 9600,+ minTier: "pro",+ },+ {+ id: "esign",+ name: "E-Sign",+ package: "esign",+ description:+ "Legally-binding e-signature ceremony — signer fields, audit-grade consent capture and a tamper-evident completion certificate.",+ maturity: "ga",+ frameworks: ["React", "Vue", "Vanilla"],+ pricing: { pricePerAction: 0.35, unit: "signature", freeQuota: 0 },+ install: "npm install @stirling/esign",+ usage: `import { ESign } from "@stirling/esign";++export function SignFlow({ docId }: { docId: string }) {+ return (+ <ESign+ documentId={docId}+ signers={[{ email: "[email protected]", role: "signer" }]}+ onSigned={(cert) => store(cert.certificateUrl)}+ />+ );+}`,+ props: [+ {+ name: "documentId",+ type: "string",+ required: true,+ description: "Document to be signed.",+ },+ {+ name: "signers",+ type: "Signer[]",+ required: true,+ description: "Ordered signers with email + role.",+ },+ {+ name: "onSigned",+ type: "(c: Certificate) => void",+ required: false,+ description: "Fires on completion — bills one signature per signer.",+ },+ ],+ embeds30d: 5400,+ minTier: "pro",+ },+ {+ id: "audit-trail",+ name: "Audit Trail",+ package: "audit-trail",+ description:+ "Read-only event timeline for a document — every render, edit, approval and signature, exportable as a compliance-grade ledger.",+ maturity: "ga",+ frameworks: ["React", "Vue"],+ pricing: { pricePerAction: 0.01, unit: "event", freeQuota: 500 },+ install: "npm install @stirling/audit-trail",+ usage: `import { AuditTrail } from "@stirling/audit-trail";++export function History({ docId }: { docId: string }) {+ return <AuditTrail documentId={docId} export="pdf" />;+}`,+ props: [+ {+ name: "documentId",+ type: "string",+ required: true,+ description: "Document whose events are shown.",+ },+ {+ name: "export",+ type: '"pdf" | "csv" | false',+ required: false,+ description: "Enable a ledger export button. Defaults to false.",+ },+ ],+ embeds30d: 14200,+ minTier: "pro",+ },+ {+ id: "markup",+ name: "Markup",+ package: "markup",+ description:+ "Collaborative annotation layer — highlights, comments, stamps and freehand drawing synced live across reviewers.",+ maturity: "beta",+ frameworks: ["React", "Vue"],+ pricing: { pricePerAction: 0.03, unit: "session", freeQuota: 25 },+ install: "npm install @stirling/markup@beta",+ usage: `import { Markup } from "@stirling/markup";++export function AnnotateLayer({ docId }: { docId: string }) {+ return (+ <Markup+ documentId={docId}+ collaborative+ tools={["highlight", "comment", "stamp"]}+ />+ );+}`,+ props: [+ {+ name: "documentId",+ type: "string",+ required: true,+ description: "Document to annotate.",+ },+ {+ name: "collaborative",+ type: "boolean",+ required: false,+ description: "Enable live multi-user sync. Defaults to false.",+ },+ {+ name: "tools",+ type: "MarkupTool[]",+ required: false,+ description: "Visible annotation tools. Defaults to all.",+ },+ ],+ embeds30d: 2100,+ minTier: "pro",+ },+ {+ id: "toolkit",+ name: "Toolkit",+ package: "toolkit",+ description:+ "Headless operations toolkit — merge, split, redact, compress and convert exposed as composable hooks with no UI of its own.",+ maturity: "beta",+ frameworks: ["React", "Vue", "Vanilla"],+ pricing: { pricePerAction: 0.05, unit: "event", freeQuota: 0 },+ install: "npm install @stirling/toolkit@beta",+ usage: `import { useToolkit } from "@stirling/toolkit";++export function MergeButton({ files }: { files: File[] }) {+ const { merge } = useToolkit({ apiKey: process.env.STIRLING_KEY });+ return <button onClick={() => merge(files)}>Merge</button>;+}`,+ props: [+ {+ name: "apiKey",+ type: "string",+ required: true,+ description: "Publishable key used to meter operations.",+ },+ {+ name: "operations",+ type: "Operation[]",+ required: false,+ description: "Restrict the toolkit to a subset of operations.",+ },+ ],+ // Beta + enterprise-only: still gated to design partners, never embedded+ // on lower tiers.+ embeds30d: 0,+ minTier: "enterprise",+ },+];++/* ──────────────────────────────────────────────────────────────────────── */+/* Tier shaping */+/* ──────────────────────────────────────────────────────────────────────── */++const TIER_RANK: Record<Tier, number> = { free: 0, pro: 1, enterprise: 2 };++/**+ * Enterprise negotiates volume pricing — renders and reviews come in cheaper.+ * Applied as a flat per-tier multiplier so the catalogue stays single-sourced.+ */+function priceFor(component: SdkComponent, tier: Tier): ComponentPricing {+ if (tier !== "enterprise") return component.pricing;+ return {+ ...component.pricing,+ pricePerAction: Number((component.pricing.pricePerAction * 0.8).toFixed(3)),+ };+}++/**+ * The catalogue for a tier. Every component is returned at every tier so the+ * grid is browsable — the view locks the ones above the tier and shows an+ * upgrade nudge. Pricing is re-stamped per tier.+ */+export function componentsFor(tier: Tier): SdkComponent[] {+ return CATALOGUE.map((c) => ({ ...c, pricing: priceFor(c, tier) }));+}++/** Whether a component is usable at the given tier (vs locked/upgrade). */+export function isUnlocked(component: SdkComponent, tier: Tier): boolean {+ return TIER_RANK[tier] >= TIER_RANK[component.minTier];+}++export function summaryFor(tier: Tier): ComponentsSummary {+ const components = componentsFor(tier);+ const unlocked = components.filter((c) => isUnlocked(c, tier));+ const gaCount = unlocked.filter((c) => c.maturity === "ga").length;+ const betaCount = unlocked.filter((c) => c.maturity === "beta").length;++ if (tier === "free") {+ // Free hasn't embedded anything yet — the strip reads as a cold start.+ return { gaCount, betaCount, embedsThisMonth: 0, spendThisMonth: 0 };+ }++ const embedsThisMonth = unlocked.reduce((sum, c) => sum + c.embeds30d, 0);+ // Spend = embeds beyond the free quota, billed at the tier price.+ const spendThisMonth = unlocked.reduce((sum, c) => {+ const billable = Math.max(0, c.embeds30d - c.pricing.freeQuota);+ return sum + billable * c.pricing.pricePerAction;+ }, 0);++ return {+ gaCount,+ betaCount,+ embedsThisMonth,+ spendThisMonth: Number(spendThisMonth.toFixed(2)),+ };+}++export function buildComponentsResponse(tier: Tier): ComponentsResponse {+ return { summary: summaryFor(tier), components: componentsFor(tier) };+}diff --git a/frontend/portal/src/mocks/settings.ts b/frontend/portal/src/mocks/settings.tsindex 7cd2afe98e..be98a3fb07 100644--- a/frontend/portal/src/mocks/settings.ts+++ b/frontend/portal/src/mocks/settings.ts@@ -23,6 +23,39 @@ export interface NotificationDefault {enabled: boolean;}+/** A device/browser with an active session, shown under Admin → Security. */+export interface ActiveSession {+ id: string;+ device: string;+ location: string;+ lastActive: string;+ /** The session viewing this modal — can't be revoked from here. */+ current: boolean;+}++/**+ * Org-wide authentication posture. SSO/SCIM are enterprise capabilities; lower+ * tiers see them as locked rows with an upgrade nudge.+ */+export interface SecuritySettings {+ mfaEnforced: boolean;+ ssoEnabled: boolean;+ scimEnabled: boolean;+ /** Idle timeout before re-auth, in minutes. */+ sessionTimeoutMins: number;+ activeSessions: ActiveSession[];+}++/** An opt-in early-access feature flag. */+export interface BetaFeature {+ id: string;+ label: string;+ description: string;+ enabled: boolean;+ /** Gated to enterprise — rendered locked below it. */+ enterpriseOnly?: boolean;+}+/*** Server snapshot of the account + workspace the modal opens onto. Editable* fields seed local form state; `planLabel` / `seats` are read-only context.@@ -44,6 +77,10 @@ export interface SettingsSnapshot {/** Per-category notification toggles, server-default on/off. */notifications: NotificationDefault[];regions: RegionOption[];+ /** Org-wide authentication + session posture (Admin scope). */+ security: SecuritySettings;+ /** Opt-in early-access features (Admin scope). */+ betaFeatures: BetaFeature[];}const REGIONS: RegionOption[] = [@@ -89,6 +126,75 @@ function notificationsFor(tier: Tier): NotificationDefault[] {];}+/** Session timeout shortens as the plan's security posture tightens. */+const SESSION_TIMEOUT_MINS: Record<Tier, number> = {+ free: 1440,+ pro: 720,+ enterprise: 480,+};++function securityFor(tier: Tier): SecuritySettings {+ const base: ActiveSession[] = [+ {+ id: "sess-current",+ device: "Chrome · macOS",+ location: "London, UK",+ lastActive: "Active now",+ current: true,+ },+ ];+ if (tier !== "free") {+ base.push({+ id: "sess-cli",+ device: "Stirling CLI · CI runner",+ location: "eu-west-1",+ lastActive: "12 min ago",+ current: false,+ });+ }+ if (tier === "enterprise") {+ base.push({+ id: "sess-mobile",+ device: "Safari · iPhone",+ location: "London, UK",+ lastActive: "3 h ago",+ current: false,+ });+ }+ return {+ // Enterprise tenants enforce MFA + SSO/SCIM org-wide by default.+ mfaEnforced: tier === "enterprise",+ ssoEnabled: tier === "enterprise",+ scimEnabled: tier === "enterprise",+ sessionTimeoutMins: SESSION_TIMEOUT_MINS[tier],+ activeSessions: base,+ };+}++function betaFeaturesFor(tier: Tier): BetaFeature[] {+ return [+ {+ id: "pipeline-canary",+ label: "Pipeline canary rollouts",+ description: "Shadow-run a new pipeline version before promoting it.",+ enabled: false,+ },+ {+ id: "component-sandboxes",+ label: "Live component sandboxes",+ description: "Interactive previews for embeddable components.",+ enabled: tier !== "free",+ },+ {+ id: "agent-evals-v2",+ label: "Agent evals v2",+ description: "Richer golden-set scoring with regression diffs.",+ enabled: tier === "enterprise",+ enterpriseOnly: true,+ },+ ];+}+export function buildSettingsSnapshot(tier: Tier): SettingsSnapshot {return {profile: {@@ -105,5 +211,7 @@ export function buildSettingsSnapshot(tier: Tier): SettingsSnapshot {},notifications: notificationsFor(tier),regions: REGIONS,+ security: securityFor(tier),+ betaFeatures: betaFeaturesFor(tier),};}diff --git a/frontend/portal/src/mocks/users.ts b/frontend/portal/src/mocks/users.tsnew file mode 100644index 0000000000..2c42cc04c7--- /dev/null+++ b/frontend/portal/src/mocks/users.ts@@ -0,0 +1,399 @@+/**+ * Users fixtures and the types api/users.ts shares with them.+ *+ * "Users" is the people surface of the org: team members and their access.+ * A member has a role (which governs what they can do), a status, and activity.+ * Alongside the roster sit the role catalogue (a reference grid) and the+ * tier-scoped access controls (seat limits, MFA, sessions, SSO/SCIM).+ *+ * api/users.ts imports the types; the MSW handlers serve the fixture data over+ * the intercepted httpJson() calls. Components never reach into this module+ * directly. Once a real backend exists the handlers stop being registered and+ * these fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";++/* ──────────────────────────────────────────────────────────────────────── */+/* Roles & members */+/* ──────────────────────────────────────────────────────────────────────── */++/** The five org roles, most → least privileged. Order is meaningful: it drives+ * the role select and the reference grid. */+export type RoleId =+ | "org_owner"+ | "team_owner"+ | "developer"+ | "reviewer"+ | "viewer";++export type MemberStatus = "active" | "invited" | "suspended";++export interface Member {+ id: string;+ name: string;+ email: string;+ role: RoleId;+ status: MemberStatus;+ /** Relative-time string, e.g. "4m ago". Invited members read "—". */+ lastActive: string;+ /** Optional avatar image; falls back to initials when absent. */+ avatarUrl?: string;+}++export interface Role {+ id: RoleId;+ label: string;+ /** One-line summary of what the role can do. */+ summary: string;+ /** Concrete permission bullets shown in the reference grid. */+ permissions: string[];+ tone: "purple" | "blue" | "green" | "amber" | "neutral";+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Access controls (tier-scoped) */+/* ──────────────────────────────────────────────────────────────────────── */++/**+ * Access posture for the org, shaped by tier. Free exposes only the seat limit+ * and an upgrade nudge; pro adds session/MFA self-service; enterprise adds+ * SSO/SAML, SCIM provisioning, enforced MFA and a session policy. Fields are+ * optional so the panel renders whatever the tier returns.+ */+export interface AccessControls {+ tier: Tier;+ /** Seats consumed by active + invited members. */+ seatsUsed: number;+ /** Total seats on the plan; null = unlimited (enterprise). */+ seatLimit: number | null;+ /** Free only: copy for the upgrade nudge. */+ upgradeHint?: string;+ /** Pro+: end-user MFA available (self-service, not enforced). */+ mfaAvailable?: boolean;+ /** Enterprise: MFA enforced org-wide. */+ mfaEnforced?: boolean;+ /** Pro+: idle session timeout, e.g. "30 days" / "12 hours". */+ sessionTimeout?: string;+ /** Enterprise: SSO connection summary. */+ sso?: {+ provider: string;+ status: "connected" | "not_configured";+ /** Email domains that auto-route to SSO. */+ domains: string[];+ };+ /** Enterprise: SCIM directory provisioning. */+ scim?: {+ enabled: boolean;+ /** Where the directory syncs from, e.g. "Okta". */+ directory: string;+ lastSync: string;+ };+}++export interface UsersSummary {+ totalMembers: number;+ pendingInvites: number;+ seatsUsed: number;+ /** null = unlimited. */+ seatLimit: number | null;+}++export interface UsersResponse {+ summary: UsersSummary;+ members: Member[];+ roles: Role[];+ access: AccessControls;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Presentation metadata — product copy, lives client-side */+/* ──────────────────────────────────────────────────────────────────────── */++export const MEMBER_STATUS_TONE: Record<+ MemberStatus,+ "success" | "warning" | "danger" | "neutral" | "info"+> = {+ active: "success",+ invited: "info",+ suspended: "danger",+};++/* ──────────────────────────────────────────────────────────────────────── */+/* Role catalogue */+/* The same five roles exist on every tier — what varies is who can fill */+/* them and how access is enforced, not the role definitions themselves. */+/* ──────────────────────────────────────────────────────────────────────── */++export const ROLES: Role[] = [+ {+ id: "org_owner",+ label: "Org Owner",+ summary: "Full governance over the organization, billing and members.",+ permissions: [+ "Manage billing & plan",+ "Add, suspend and remove members",+ "Configure SSO, SCIM and security policy",+ "Everything Team Owner can do",+ ],+ tone: "purple",+ },+ {+ id: "team_owner",+ label: "Team Owner",+ summary: "Team-scoped admin — manage members and pipelines for a team.",+ permissions: [+ "Invite & manage team members",+ "Create and deploy pipelines",+ "View team usage & audit log",+ "No org billing or SSO access",+ ],+ tone: "blue",+ },+ {+ id: "developer",+ label: "Developer",+ summary: "Build and operate pipelines, agents and integrations.",+ permissions: [+ "Create & edit pipelines",+ "Manage API keys, agents and webhooks",+ "Run and debug document jobs",+ "Read team audit log",+ ],+ tone: "green",+ },+ {+ id: "reviewer",+ label: "Reviewer",+ summary: "Approve or reject documents routed for human review.",+ permissions: [+ "Approve / reject review tasks",+ "Annotate and redact documents",+ "Read assigned pipelines",+ "No pipeline or key management",+ ],+ tone: "amber",+ },+ {+ id: "viewer",+ label: "Viewer",+ summary: "Read-only access to documents and dashboards.",+ permissions: [+ "View documents & results",+ "View dashboards & usage",+ "Export permitted reports",+ "No write access",+ ],+ tone: "neutral",+ },+];++export const ROLE_LABEL: Record<RoleId, string> = Object.fromEntries(+ ROLES.map((r) => [r.id, r.label]),+) as Record<RoleId, string>;++export const ROLE_TONE: Record<RoleId, Role["tone"]> = Object.fromEntries(+ ROLES.map((r) => [r.id, r.tone]),+) as Record<RoleId, Role["tone"]>;++/* ──────────────────────────────────────────────────────────────────────── */+/* Member fixtures */+/* ──────────────────────────────────────────────────────────────────────── */++/** Pro org: a small team, one pending invite, one suspended account. */+const PRO_MEMBERS: Member[] = [+ {+ id: "usr-you",+ name: "You",+ email: "[email protected]",+ role: "org_owner",+ status: "active",+ lastActive: "just now",+ },+ {+ id: "usr-priya",+ name: "Priya Nair",+ email: "[email protected]",+ role: "developer",+ status: "active",+ lastActive: "8m ago",+ },+ {+ id: "usr-marcus",+ name: "Marcus Webb",+ email: "[email protected]",+ role: "developer",+ status: "active",+ lastActive: "1h ago",+ },+ {+ id: "usr-dana",+ name: "Dana Osei",+ email: "[email protected]",+ role: "reviewer",+ status: "active",+ lastActive: "yesterday",+ },+ {+ // Pending invite: no activity yet and occupies a seat until accepted.+ id: "usr-invite-1",+ name: "[email protected]",+ email: "[email protected]",+ role: "viewer",+ status: "invited",+ lastActive: "—",+ },+ {+ // Suspended: retains the seat but cannot sign in until reinstated.+ id: "usr-leo",+ name: "Leo Fischer",+ email: "[email protected]",+ role: "developer",+ status: "suspended",+ lastActive: "12 days ago",+ },+];++/** Enterprise adds a Team Owner, more seats in use, and a second pending invite. */+const ENTERPRISE_EXTRA: Member[] = [+ {+ id: "usr-aisha",+ name: "Aisha Rahman",+ email: "[email protected]",+ role: "team_owner",+ status: "active",+ lastActive: "3m ago",+ },+ {+ id: "usr-tom",+ name: "Tom Becker",+ email: "[email protected]",+ role: "reviewer",+ status: "active",+ lastActive: "26m ago",+ },+ {+ id: "usr-nadia",+ name: "Nadia Costa",+ email: "[email protected]",+ role: "viewer",+ status: "active",+ lastActive: "2h ago",+ },+ {+ id: "usr-invite-2",+ name: "[email protected]",+ email: "[email protected]",+ role: "reviewer",+ status: "invited",+ lastActive: "—",+ },+];++/** Free tier: a solo workspace approaching its seat ceiling. */+const FREE_MEMBERS: Member[] = [+ {+ id: "usr-you",+ name: "You",+ email: "[email protected]",+ role: "org_owner",+ status: "active",+ lastActive: "just now",+ },+ {+ id: "usr-jess",+ name: "Jess Allen",+ email: "[email protected]",+ role: "developer",+ status: "active",+ lastActive: "3h ago",+ },+];++export function membersFor(tier: Tier): Member[] {+ if (tier === "free") return FREE_MEMBERS;+ if (tier === "enterprise") return [...PRO_MEMBERS, ...ENTERPRISE_EXTRA];+ return PRO_MEMBERS;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Access controls per tier */+/* ──────────────────────────────────────────────────────────────────────── */++function seatLimitFor(tier: Tier): number | null {+ if (tier === "free") return 3;+ if (tier === "pro") return 10;+ return null; // enterprise: unlimited+}++export function accessFor(tier: Tier): AccessControls {+ const members = membersFor(tier);+ // Both active and invited members hold a seat; suspended accounts do too,+ // matching how most seat-based plans bill until an account is removed.+ const seatsUsed = members.length;+ const seatLimit = seatLimitFor(tier);++ if (tier === "free") {+ return {+ tier,+ seatsUsed,+ seatLimit,+ upgradeHint:+ "Free workspaces cap at 3 seats with member-level roles only. Upgrade to add MFA, sessions and unlimited seats.",+ };+ }++ if (tier === "enterprise") {+ return {+ tier,+ seatsUsed,+ seatLimit,+ mfaAvailable: true,+ mfaEnforced: true,+ sessionTimeout: "12 hours",+ sso: {+ provider: "Okta (SAML 2.0)",+ status: "connected",+ domains: ["acme.com"],+ },+ scim: {+ enabled: true,+ directory: "Okta",+ lastSync: "6m ago",+ },+ };+ }++ // pro+ return {+ tier,+ seatsUsed,+ seatLimit,+ mfaAvailable: true,+ mfaEnforced: false,+ sessionTimeout: "30 days",+ };+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Summary + response builder */+/* ──────────────────────────────────────────────────────────────────────── */++export function summaryFor(tier: Tier): UsersSummary {+ const members = membersFor(tier);+ return {+ totalMembers: members.filter((m) => m.status !== "invited").length,+ pendingInvites: members.filter((m) => m.status === "invited").length,+ seatsUsed: members.length,+ seatLimit: seatLimitFor(tier),+ };+}++export function buildUsersResponse(tier: Tier): UsersResponse {+ return {+ summary: summaryFor(tier),+ members: membersFor(tier),+ roles: ROLES,+ access: accessFor(tier),+ };+}diff --git a/frontend/portal/src/views/AgentBuilder.css b/frontend/portal/src/views/AgentBuilder.cssnew file mode 100644index 0000000000..e4be384bf9--- /dev/null+++ b/frontend/portal/src/views/AgentBuilder.css@@ -0,0 +1,458 @@+.portal-agents {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-agents__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-agents__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-agents__sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* Two-column layout: selector rail + builder */+.portal-agents__layout {+ display: grid;+ grid-template-columns: 17rem 1fr;+ gap: 1.25rem;+ align-items: start;+}++@media (max-width: 56rem) {+ .portal-agents__layout {+ grid-template-columns: 1fr;+ }+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Selector rail */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__selector {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-agents__selector-item {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ text-align: left;+ padding: 0.75rem 0.875rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ cursor: pointer;+ transition:+ border-color var(--motion-fast),+ background var(--motion-fast);+}++.portal-agents__selector-item:hover {+ background: var(--color-bg-hover);+}++.portal-agents__selector-item.is-selected {+ border-color: var(--color-blue);+ background: var(--color-blue-light);+ box-shadow: 0 0 0 1px var(--color-blue) inset;+}++.portal-agents__selector-main {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-agents__selector-name {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-agents__selector-role {+ font-size: 0.6875rem;+ line-height: 1.4;+ color: var(--color-text-4);+}++.portal-agents__selector-meta {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-agents__selector-version,+.portal-agents__builder-version,+.portal-agents__builder-model,+.portal-agents__version-tag {+ font-family: var(--font-mono);+ font-size: 0.6875rem;+ color: var(--color-text-3);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Builder panel */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__builder {+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ box-shadow: var(--shadow-sm);+ padding: 1.25rem;+ display: flex;+ flex-direction: column;+ gap: 1.125rem;+}++.portal-agents__builder-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-agents__builder-title {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-agents__builder-sub {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-agents__builder-meta {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ flex-shrink: 0;+}++.portal-agents__builder-model {+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+ padding: 0.125rem 0.375rem;+}++/* Shared panel body */+.portal-agents__panel {+ display: flex;+ flex-direction: column;+ gap: 1.125rem;+}++.portal-agents__detail-section {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-agents__detail-heading {+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-text-5);+ font-weight: 600;+}++.portal-agents__chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++.portal-agents__hint {+ margin: 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-agents__muted {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++.portal-agents__mono {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-2);+}++.portal-agents__stat-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.875rem;+}++.portal-agents__stat-grid--two {+ grid-template-columns: repeat(2, minmax(0, 14rem));+}++/* Bars (eval pass-rate) */+.portal-agents__bar-row {+ display: flex;+ flex-direction: column;+ gap: 0.4375rem;+}++.portal-agents__bar-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-agents__bar-head strong {+ font-size: 0.8125rem;+ color: var(--color-text-1);+ font-family: var(--font-mono);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Scenarios */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__scenarios {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-agents__scenario {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.75rem 0.875rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-agents__scenario-text {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-agents__scenario-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-agents__scenario-head strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-agents__scenario-expect {+ font-size: 0.75rem;+ line-height: 1.45;+ color: var(--color-text-3);+}++.portal-agents__scenario-add {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ padding-top: 0.25rem;+ border-top: 1px dashed var(--color-border-light);+}++.portal-agents__scenario-form {+ display: grid;+ grid-template-columns: 1fr 1.5fr auto;+ align-items: end;+ gap: 0.625rem;+}++@media (max-width: 48rem) {+ .portal-agents__scenario-form {+ grid-template-columns: 1fr;+ }+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Tools */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__tool-mode {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ padding: 0.875rem 1rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Evals */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__eval-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+ flex-wrap: wrap;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Versions */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__versions {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-agents__version {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.75rem 0.875rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-agents__version-main {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-agents__version-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-agents__version-tag {+ font-size: 0.8125rem;+ color: var(--color-text-1);+ font-weight: 600;+}++.portal-agents__version-note {+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-agents__version-meta {+ font-size: 0.6875rem;+ color: var(--color-text-5);+}++.portal-agents__version-actions {+ flex-shrink: 0;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Bootstrap dialog */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-agents__bootstrap {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-agents__bootstrap-lead {+ margin: 0;+ font-size: 0.875rem;+ line-height: 1.55;+ color: var(--color-text-2);+}++.portal-agents__dropzone {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.5rem;+ padding: 1.75rem 1rem;+ text-align: center;+ background: var(--color-bg-subtle);+ border: 1px dashed var(--color-border);+ border-radius: var(--radius-lg);+ cursor: pointer;+ transition:+ border-color var(--motion-fast),+ background var(--motion-fast);+}++.portal-agents__dropzone:hover {+ border-color: var(--color-blue);+ background: var(--color-blue-light);+}++.portal-agents__dropzone-input {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ white-space: nowrap;+ border: 0;+}++.portal-agents__dropzone-icon {+ font-size: 1.5rem;+ color: var(--color-text-3);+}++.portal-agents__dropzone-text {+ font-size: 0.8125rem;+ color: var(--color-text-3);+}++.portal-agents__dialog-footer {+ display: flex;+ justify-content: space-between;+ gap: 0.5rem;+ width: 100%;+}diff --git a/frontend/portal/src/views/AgentBuilder.tsx b/frontend/portal/src/views/AgentBuilder.tsxnew file mode 100644index 0000000000..9de002a922--- /dev/null+++ b/frontend/portal/src/views/AgentBuilder.tsx@@ -0,0 +1,98 @@+import { useState } from "react";+import { Button, EmptyState, Skeleton } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import { fetchAgents, type AgentsResponse } from "@portal/api/agents";+import { AgentKpiStrip } from "@portal/components/agent-builder/AgentKpiStrip";+import { AgentSelector } from "@portal/components/agent-builder/AgentSelector";+import { AgentBuilderPanel } from "@portal/components/agent-builder/AgentBuilderPanel";+import { BootstrapDialog } from "@portal/components/agent-builder/BootstrapDialog";+import "@portal/views/AgentBuilder.css";++export function AgentBuilder() {+ const { tier } = useTier();+ const state = useAsync<AgentsResponse>(() => fetchAgents(tier), [tier]);+ const { data, loading } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [bootstrapOpen, setBootstrapOpen] = useState(false);++ const agents = data?.agents ?? [];+ // Default the selection to the first agent once data lands, but honour an+ // explicit pick. Recomputed each render so a tier change re-points cleanly.+ const selected = agents.find((a) => a.id === selectedId) ?? agents[0] ?? null;++ // Enterprise unlocks restricted-tools governance and deep version history.+ const governanceUnlocked = tier === "enterprise";++ return (+ <div className="portal-agents">+ <header className="portal-agents__head">+ <div>+ <h1 className="portal-agents__title">Agent Builder</h1>+ <p className="portal-agents__sub">+ Design, test and ship the AI agents that classify, extract from and+ route your documents. Define scenarios, fence tool access, run a+ golden set, and publish a version.+ </p>+ </div>+ <Button+ onClick={() => setBootstrapOpen(true)}+ leadingIcon={<span aria-hidden>⇪</span>}+ >+ Bootstrap from document+ </Button>+ </header>++ <AgentKpiStrip summary={data?.summary ?? null} loading={loading} />++ {isLoading && (+ <div className="portal-agents__layout">+ <div className="portal-agents__selector" aria-hidden>+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} height="4rem" />+ ))}+ </div>+ <div className="portal-agents__builder" aria-hidden>+ <Skeleton height="18rem" />+ </div>+ </div>+ )}++ {isEmpty && (+ <EmptyState+ title="No agents yet"+ description="Bootstrap an agent from a sample document to seed its scenarios and extraction schema, then refine and publish."+ actions={+ <Button onClick={() => setBootstrapOpen(true)}>+ Bootstrap from document+ </Button>+ }+ />+ )}++ {!isLoading && !isEmpty && selected && (+ <div className="portal-agents__layout">+ <AgentSelector+ agents={agents}+ selectedId={selected.id}+ onSelect={setSelectedId}+ />+ <AgentBuilderPanel+ // Remount on selection change so each panel re-seeds its local+ // edit state from the freshly selected agent.+ key={selected.id}+ agent={selected}+ governanceUnlocked={governanceUnlocked}+ />+ </div>+ )}++ <BootstrapDialog+ open={bootstrapOpen}+ onClose={() => setBootstrapOpen(false)}+ />+ </div>+ );+}diff --git a/frontend/portal/src/views/Components.css b/frontend/portal/src/views/Components.cssnew file mode 100644index 0000000000..c37cc7924a--- /dev/null+++ b/frontend/portal/src/views/Components.css@@ -0,0 +1,244 @@+.portal-components {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-components__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-components__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-components__sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Catalogue grid */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-components__grid,+.portal-components__grid-skeleton {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr));+ gap: 1rem;+}++.portal-components__card {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ cursor: pointer;+ height: 100%;+}++/* Locked cards read as available-but-gated: dimmed, never disabled. */+.portal-components__card.is-locked {+ opacity: 0.7;+}++.portal-components__card-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-components__card-name {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-components__lock {+ margin-left: auto;+ font-size: 0.875rem;+ line-height: 1;+}++.portal-components__card-desc {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ flex: 1;+}++.portal-components__card-meta {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: 0.5rem;+}++.portal-components__price {+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-components__pkg {+ font-family: var(--font-mono);+ font-size: 0.6875rem;+ color: var(--color-text-4);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.portal-components__frameworks {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Detail modal */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-components__modal-title {+ display: inline-flex;+ align-items: center;+ gap: 0.625rem;+}++.portal-components__modal-footer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ width: 100%;+}++/* Live-preview sandbox placeholder */+.portal-components__preview {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 0.375rem;+ min-height: 9rem;+ margin-bottom: 1rem;+ border: 1px dashed var(--color-border-strong, var(--color-border));+ border-radius: var(--radius-lg);+ background: repeating-linear-gradient(+ 45deg,+ var(--color-bg-subtle),+ var(--color-bg-subtle) 10px,+ var(--color-surface) 10px,+ var(--color-surface) 20px+ );+}++.portal-components__preview-badge {+ font-size: 0.6875rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-blue);+ padding: 0.1875rem 0.5rem;+ border-radius: var(--radius-sm);+ background: var(--color-blue-light);+}++.portal-components__preview-note {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-components__tabs {+ margin-bottom: 1rem;+}++.portal-components__tab-body {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ min-height: 12rem;+}++.portal-components__overview {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-components__overview-desc {+ margin: 0;+ font-size: 0.875rem;+ line-height: 1.55;+ color: var(--color-text-2);+}++.portal-components__code {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+}++.portal-components__stat-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.875rem;+}++@media (max-width: 48rem) {+ .portal-components__stat-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}++.portal-components__pricing {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-components__pricing-note {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.55;+ color: var(--color-text-3);+}++/* Props table cells */+.portal-components__prop-name {+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-components__prop-type {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-blue);+}++.portal-components__prop-desc {+ font-size: 0.8125rem;+ color: var(--color-text-3);+}++.portal-components__muted {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}diff --git a/frontend/portal/src/views/Components.tsx b/frontend/portal/src/views/Components.tsxnew file mode 100644index 0000000000..b8c67a1527--- /dev/null+++ b/frontend/portal/src/views/Components.tsx@@ -0,0 +1,88 @@+import { useState } from "react";+import { Banner, EmptyState, Skeleton } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchComponents,+ isUnlocked,+ type ComponentsResponse,+ type SdkComponent,+} from "@portal/api/sdkComponents";+import { ComponentsSummaryStrip } from "@portal/components/catalogue/ComponentsSummaryStrip";+import { ComponentGrid } from "@portal/components/catalogue/ComponentGrid";+import { ComponentDetailModal } from "@portal/components/catalogue/ComponentDetailModal";+import "@portal/views/Components.css";++export function Components() {+ const { tier } = useTier();+ const state = useAsync<ComponentsResponse>(+ () => fetchComponents(tier),+ [tier],+ );+ const { data, loading } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const [openId, setOpenId] = useState<string | null>(null);++ const components = data?.components ?? [];+ const open = components.find((c) => c.id === openId) ?? null;+ const hasLocked = components.some((c) => !isUnlocked(c, tier));++ function handleOpen(component: SdkComponent) {+ setOpenId(component.id);+ }++ return (+ <div className="portal-components">+ <header className="portal-components__head">+ <div>+ <h1 className="portal-components__title">Components</h1>+ <p className="portal-components__sub">+ Embeddable SDK widgets you drop into your own app — a viewer, an+ e-sign flow, an AI review panel. Each is metered per action. Click a+ card for install, usage and props.+ </p>+ </div>+ </header>++ <ComponentsSummaryStrip data={data} loading={loading} />++ {tier === "free" && hasLocked && (+ <Banner+ tone="info"+ title="Some components need a paid plan"+ description="GA components are available on Pay-as-you-go; a few Beta components are enterprise-only. Locked cards show an upgrade nudge."+ />+ )}++ {isLoading && (+ <div className="portal-components__grid-skeleton" aria-hidden>+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} height="11rem" />+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ title="No components available"+ description="The component catalogue could not be loaded. Try again shortly."+ />+ )}++ {!isLoading && !isEmpty && components.length > 0 && (+ <ComponentGrid+ components={components}+ tier={tier}+ onOpen={handleOpen}+ />+ )}++ <ComponentDetailModal+ component={open}+ unlocked={open ? isUnlocked(open, tier) : false}+ onClose={() => setOpenId(null)}+ />+ </div>+ );+}diff --git a/frontend/portal/src/views/Documents.css b/frontend/portal/src/views/Documents.cssindex 202a734ac8..a655289567 100644--- a/frontend/portal/src/views/Documents.css+++ b/frontend/portal/src/views/Documents.css@@ -1,5 +1,225 @@.portal-documents {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;padding: 1.5rem;- max-width: 78rem;+ max-width: 84rem;margin: 0 auto;}++/* Header */+.portal-documents__head {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.portal-documents__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-documents__sub {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* Review queue layout */+.portal-documents__queue {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+}++.portal-documents__table-skeleton {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++/* Table cells */+.portal-documents__name-cell {+ display: flex;+ align-items: center;+ gap: 0.4375rem;+ min-width: 0;+}++.portal-documents__name {+ font-weight: 600;+ color: var(--color-text-1);+ overflow: hidden;+ text-overflow: ellipsis;+}++.portal-documents__lock {+ font-size: 0.75rem;+ line-height: 1;+ flex-shrink: 0;+}++.portal-documents__muted {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++.portal-documents__mono {+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-documents__confidence {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-documents__confidence-pct {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ white-space: nowrap;+}++.portal-documents__confidence-pct--success {+ color: var(--color-green-dark);+}+.portal-documents__confidence-pct--warning {+ color: var(--color-amber-dark);+}+.portal-documents__confidence-pct--danger {+ color: var(--color-red);+}++/* Drawer body */+.portal-documents__drawer {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-documents__drawer-status {+ display: flex;+}++.portal-documents__drawer-panel {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}++/* Overview stat grid */+.portal-documents__stat-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.875rem;+}++.portal-documents__field {+ font-weight: 500;+ color: var(--color-text-1);+}++/* Masked / sensitive placeholder */+.portal-documents__masked {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.625rem;+ padding: 2rem 1rem;+ text-align: center;+ background: var(--color-bg-subtle);+ border: 1px dashed var(--color-border);+ border-radius: var(--radius-lg);+}++.portal-documents__masked-icon {+ font-size: 1.5rem;+}++.portal-documents__masked-text {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--color-text-3);+ max-width: 22rem;+}++/* Audit timeline */+.portal-documents__timeline {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0;+}++.portal-documents__timeline-item {+ position: relative;+ display: flex;+ gap: 0.75rem;+ padding: 0 0 1rem 0;+}++.portal-documents__timeline-item:last-child {+ padding-bottom: 0;+}++.portal-documents__timeline-dot {+ position: relative;+ flex-shrink: 0;+ width: 0.5rem;+ height: 0.5rem;+ margin-top: 0.375rem;+ border-radius: 50%;+ background: var(--color-blue);+}++/* Connecting line between successive timeline dots. */+.portal-documents__timeline-item:not(:last-child)+ .portal-documents__timeline-dot::after {+ content: "";+ position: absolute;+ left: 50%;+ top: 0.75rem;+ transform: translateX(-50%);+ width: 1px;+ height: calc(100% + 1rem);+ background: var(--color-border);+}++.portal-documents__timeline-body {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-documents__timeline-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-documents__timeline-time {+ font-size: 0.6875rem;+ color: var(--color-text-5);+}++.portal-documents__timeline-detail {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--color-text-2);+ line-height: 1.45;+}++.portal-documents__timeline-actor {+ font-family: var(--font-mono);+ font-size: 0.6875rem;+ color: var(--color-text-4);+}diff --git a/frontend/portal/src/views/Documents.tsx b/frontend/portal/src/views/Documents.tsxindex c4bd89f312..95a3b4521c 100644--- a/frontend/portal/src/views/Documents.tsx+++ b/frontend/portal/src/views/Documents.tsx@@ -1,15 +1,22 @@-import { DocumentTypeGrid } from "@portal/components/DocumentTypeGrid";+import { ReviewQueue } from "@portal/components/documents/ReviewQueue";import "@portal/views/Documents.css";/**- * Full document-type catalogue — the exhaustive per-vertical endpoint list.- * Home only teases four use cases (see PopularUseCases); the complete,- * tab-filterable grid lives here on its own surface.+ * Documents surface — the review/approval queue: documents flowing through the+ * org's pipelines awaiting a decision, with filters, a detail drawer, and+ * zero-standing-access elevation for sensitive files.*/export function Documents() {return (<div className="portal-documents">- <DocumentTypeGrid />+ <header className="portal-documents__head">+ <h1 className="portal-documents__title">Documents</h1>+ <p className="portal-documents__sub">+ Review and approve documents moving through your pipelines.+ </p>+ </header>++ <ReviewQueue /></div>);}diff --git a/frontend/portal/src/views/EditorAdmin.css b/frontend/portal/src/views/EditorAdmin.cssnew file mode 100644index 0000000000..92dc1d384e--- /dev/null+++ b/frontend/portal/src/views/EditorAdmin.css@@ -0,0 +1,328 @@+.portal-editor {+ display: flex;+ flex-direction: column;+ gap: 1.5rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-editor__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-editor__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-editor__sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 52rem;+}++/* Section headings */+.portal-editor__section-head {+ margin-bottom: 0.875rem;+}++.portal-editor__section-title {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-editor__section-sub {+ margin: 0.1875rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-4);+ max-width: 52rem;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Deployment targets */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-editor__targets {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 1rem;+ align-items: start;+}++@media (max-width: 64rem) {+ .portal-editor__targets {+ grid-template-columns: 1fr;+ }+}++.portal-editor__target {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}++.portal-editor__target-head {+ display: flex;+ align-items: flex-start;+ gap: 0.625rem;+}++.portal-editor__target-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ flex-shrink: 0;+ border-radius: var(--radius-md);+ font-size: 1rem;+}++.portal-editor__target-icon--neutral {+ background: var(--color-bg-subtle);+ color: var(--color-text-3);+}+.portal-editor__target-icon--blue {+ background: var(--color-blue-light);+ color: var(--color-blue);+}+.portal-editor__target-icon--purple {+ background: var(--color-purple-light);+ color: var(--color-purple);+}++.portal-editor__target-titles {+ flex: 1;+ min-width: 0;+}++.portal-editor__target-name {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-editor__target-tagline {+ margin: 0.1875rem 0 0;+ font-size: 0.75rem;+ line-height: 1.45;+ color: var(--color-text-4);+}++.portal-editor__target-meta {+ margin: 0;+ font-size: 0.75rem;+ font-family: var(--font-mono);+ color: var(--color-text-3);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Upgrade nudge (shared by locked targets / pairings / offline card) */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-editor__lock {+ display: flex;+ flex-direction: column;+ align-items: flex-start;+ gap: 0.625rem;+ padding: 0.875rem;+ background: var(--color-bg-subtle);+ border: 1px dashed var(--color-border);+ border-radius: var(--radius-md);+}++.portal-editor__lock-copy {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.45;+ color: var(--color-text-3);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Pairing */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-editor__pairings {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 1rem;+ align-items: start;+}++@media (max-width: 64rem) {+ .portal-editor__pairings {+ grid-template-columns: 1fr;+ }+}++.portal-editor__pairing {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}++.portal-editor__pairing-head {+ display: flex;+ align-items: flex-start;+ gap: 0.625rem;+}++.portal-editor__pairing-icon {+ font-size: 1.125rem;+ line-height: 1.4;+}++.portal-editor__pairing-titles {+ flex: 1;+ min-width: 0;+}++.portal-editor__pairing-name {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-editor__pairing-desc {+ margin: 0.1875rem 0 0;+ font-size: 0.75rem;+ line-height: 1.45;+ color: var(--color-text-4);+}++.portal-editor__pairing-value {+ padding: 0.625rem 0.75rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-editor__pairing-value code {+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ color: var(--color-text-1);+ word-break: break-all;+}++.portal-editor__pairing-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-top: auto;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Instance health table cells */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-editor__cell-stack {+ display: flex;+ flex-direction: column;+ gap: 0.3125rem;+ min-width: 0;+}++.portal-editor__cell-strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-editor__cell-muted {+ display: flex;+}++.portal-editor__mono {+ font-family: var(--font-mono);+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-editor__muted {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Operations row (rotation + offline activation) */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-editor__ops {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 1rem;+ align-items: start;+}++@media (max-width: 64rem) {+ .portal-editor__ops {+ grid-template-columns: 1fr;+ }+}++.portal-editor__panel {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-editor__panel-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 0.75rem;+}++.portal-editor__panel-title {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-editor__panel-sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-4);+}++.portal-editor__enterprise-tag {+ font-size: 0.625rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ padding: 0.125rem 0.4375rem;+ border-radius: var(--radius-sm);+ background: var(--color-purple-light);+ color: var(--color-purple);+}++.portal-editor__token-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 0.875rem;+}++.portal-editor__panel-actions {+ display: flex;+ gap: 0.5rem;+}diff --git a/frontend/portal/src/views/EditorAdmin.tsx b/frontend/portal/src/views/EditorAdmin.tsxnew file mode 100644index 0000000000..f7e5ac3227--- /dev/null+++ b/frontend/portal/src/views/EditorAdmin.tsx@@ -0,0 +1,109 @@+import { Skeleton } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useView } from "@portal/contexts/ViewContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchEditorDeployment,+ type EditorDeploymentResponse,+} from "@portal/api/editorDeploy";+import { DeploymentSummaryStrip } from "@portal/components/editor-admin/DeploymentSummaryStrip";+import { DeploymentTargets } from "@portal/components/editor-admin/DeploymentTargets";+import { PairingPanel } from "@portal/components/editor-admin/PairingPanel";+import { InstanceHealthTable } from "@portal/components/editor-admin/InstanceHealthTable";+import { CredentialRotationCard } from "@portal/components/editor-admin/CredentialRotationCard";+import { OfflineActivationCard } from "@portal/components/editor-admin/OfflineActivationCard";+import "@portal/views/EditorAdmin.css";++/** Title + sub-line for a section block on this page. */+function SectionHead({ title, sub }: { title: string; sub: string }) {+ return (+ <header className="portal-editor__section-head">+ <h2 className="portal-editor__section-title">{title}</h2>+ <p className="portal-editor__section-sub">{sub}</p>+ </header>+ );+}++/**+ * Editor deployment management. Deploy the Stirling PDF Editor product to a+ * target (Managed Cloud / Docker / Kubernetes), pair self-hosted instances back+ * to the org, watch instance health, and run credential / offline-activation+ * lifecycle tasks. Reached from Infrastructure → Deployments, not the sidebar.+ */+export function EditorAdmin() {+ const { tier } = useTier();+ const { setActiveView } = useView();+ const state = useAsync<EditorDeploymentResponse>(+ () => fetchEditorDeployment(tier),+ [tier],+ );+ const { data } = state;+ const { isLoading } = useSectionFlags(state);++ // Lower tiers nudge toward Usage & Billing to upgrade; the snippet shows the+ // value of the higher tier inline before the user gets there.+ const goUpgrade = () => setActiveView("usage");++ return (+ <div className="portal-editor">+ <header className="portal-editor__head">+ <div>+ <h1 className="portal-editor__title">Editor deployment</h1>+ <p className="portal-editor__sub">+ Deploy the Stirling PDF Editor, pair self-hosted instances to your+ org, and operate the running fleet — targets, health, credentials,+ and offline activation in one place.+ </p>+ </div>+ </header>++ <DeploymentSummaryStrip summary={data?.summary} loading={isLoading} />++ <section>+ <SectionHead+ title="Deployment targets"+ sub="Where the Editor runs. Copy a snippet to stand up a self-hosted instance, or use Managed Cloud with no ops."+ />+ {isLoading || !data ? (+ <div className="portal-editor__targets">+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} height="14rem" />+ ))}+ </div>+ ) : (+ <DeploymentTargets targets={data.targets} onUpgrade={goUpgrade} />+ )}+ </section>++ <section>+ <SectionHead+ title="Pairing"+ sub="Connect a self-hosted editor to this org. Generate a token, hand off a short code, or wire it through IaC."+ />+ {data && (+ <PairingPanel pairings={data.pairings} onUpgrade={goUpgrade} />+ )}+ </section>++ <section>+ <SectionHead+ title="Instance health"+ sub="Every Editor instance reporting in — version, region, status, last seen, and active users."+ />+ {data && <InstanceHealthTable instances={data.instances} />}+ </section>++ <section className="portal-editor__ops">+ {data && (+ <CredentialRotationCard serviceToken={data.summary.serviceToken} />+ )}+ {data && (+ <OfflineActivationCard+ available={data.summary.offlineActivationAvailable}+ onUpgrade={goUpgrade}+ />+ )}+ </section>+ </div>+ );+}diff --git a/frontend/portal/src/views/Home.tsx b/frontend/portal/src/views/Home.tsxindex d3da4ee073..7d6af37f94 100644--- a/frontend/portal/src/views/Home.tsx+++ b/frontend/portal/src/views/Home.tsx@@ -26,6 +26,9 @@ import { PopularUseCases } from "@portal/components/PopularUseCases";import { UsageAreaChart } from "@portal/components/UsageAreaChart";import { RecentActivity } from "@portal/components/RecentActivity";import { SingleOpRunner } from "@portal/components/SingleOpRunner";+import { ProcessingStatusStrip } from "@portal/components/ProcessingStatusStrip";+import { PolicySummary } from "@portal/components/PolicySummary";+import { PipelineForkWizard } from "@portal/components/PipelineForkWizard";import "@portal/views/Home.css";/* ──────────────────────────────────────────────────────────────────────── */@@ -508,6 +511,7 @@ export function Home() {return (<div className="portal-home"><WelcomeCarousel onTryOp={() => setRunnerOpen(true)} />+ <ProcessingStatusStrip />{tier === "free" && (<>@@ -516,6 +520,8 @@ export function Home() {<FreeOnboarding onTryOp={() => setRunnerOpen(true)} /><QuickActions onTryOp={() => setRunnerOpen(true)} /></div>+ <PolicySummary />+ <PipelineForkWizard /><ProductGrid /><PopularUseCases /></>@@ -529,6 +535,8 @@ export function Home() {<RecentActivity /><QuickActions onTryOp={() => setRunnerOpen(true)} /></div>+ <PolicySummary />+ <PipelineForkWizard /><ProductGrid /><PopularUseCases /></>@@ -543,6 +551,8 @@ export function Home() {<RecentActivity /><QuickActions onTryOp={() => setRunnerOpen(true)} /></div>+ <PolicySummary />+ <PipelineForkWizard /><ProductGrid /><PopularUseCases /></>diff --git a/frontend/portal/src/views/Infrastructure.css b/frontend/portal/src/views/Infrastructure.cssindex 0e9c7c7f58..fd893694d3 100644--- a/frontend/portal/src/views/Infrastructure.css+++ b/frontend/portal/src/views/Infrastructure.css@@ -9,6 +9,12 @@/* View header */.portal-infra__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}+.portal-infra__head-text {display: flex;flex-direction: column;gap: 0.25rem;@@ -286,6 +292,60 @@line-height: 1.4;}+/* Encryption key management */+.portal-infra__keymgmt-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ margin-bottom: 1rem;+}++.portal-infra__keymgmt-title {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ min-width: 0;+}++/* Compliance attestations — same grid rhythm as certs, but each card stacks+ a framework chip + report link, so it needs a little more vertical room. */+.portal-infra__attestations {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.75rem;+}++@media (max-width: 60rem) {+ .portal-infra__attestations {+ grid-template-columns: repeat(2, 1fr);+ }+}++@media (max-width: 36rem) {+ .portal-infra__attestations {+ grid-template-columns: 1fr;+ }+}++.portal-infra__attestation {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ align-items: flex-start;+}++.portal-infra__attestation-link {+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-blue);+ text-decoration: none;+}++.portal-infra__attestation-link:hover {+ text-decoration: underline;+}+/* ── Storage ────────────────────────────────────────────────────────────── */.portal-infra__usage-head {display: flex;diff --git a/frontend/portal/src/views/Infrastructure.tsx b/frontend/portal/src/views/Infrastructure.tsxindex a9712d30b7..dedec21a43 100644--- a/frontend/portal/src/views/Infrastructure.tsx+++ b/frontend/portal/src/views/Infrastructure.tsx@@ -1,33 +1,52 @@import { useState } from "react";-import { Tabs, type TabItem } from "@shared/components";+import { Button, Tabs, type TabItem } from "@shared/components";+import { useView } from "@portal/contexts/ViewContext";import { DeploymentsTab } from "@portal/components/infrastructure/DeploymentsTab";import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";import { SecurityTab } from "@portal/components/infrastructure/SecurityTab";+import { ModelsTab } from "@portal/components/infrastructure/ModelsTab";import { StorageTab } from "@portal/components/infrastructure/StorageTab";import { AuditTab } from "@portal/components/infrastructure/AuditTab";import "@portal/views/Infrastructure.css";-type InfraTab = "deployments" | "api-keys" | "security" | "storage" | "audit";+type InfraTab =+ | "deployments"+ | "api-keys"+ | "security"+ | "models"+ | "storage"+ | "audit";const TABS: TabItem<InfraTab>[] = [{ key: "deployments", label: "Deployments" },{ key: "api-keys", label: "API Keys" },{ key: "security", label: "Security" },+ { key: "models", label: "Models" },{ key: "storage", label: "Storage" },{ key: "audit", label: "Audit Logs" },];export function Infrastructure() {const [tab, setTab] = useState<InfraTab>("deployments");+ const { setActiveView } = useView();return (<div className="portal-infra"><header className="portal-infra__head">- <h1 className="portal-infra__title">Infrastructure</h1>- <p className="portal-infra__sub">- Deployments, credentials, security posture, storage, and the audit- trail for your Stirling workspace.- </p>+ <div className="portal-infra__head-text">+ <h1 className="portal-infra__title">Infrastructure</h1>+ <p className="portal-infra__sub">+ Deployments, credentials, security posture, storage, and the audit+ trail for your Stirling workspace.+ </p>+ </div>+ <Button+ variant="outline"+ size="sm"+ onClick={() => setActiveView("editor")}+ >+ Manage Editor deployment+ </Button></header><Tabs<InfraTab>@@ -42,6 +61,7 @@ export function Infrastructure() {{tab === "deployments" && <DeploymentsTab />}{tab === "api-keys" && <ApiKeysTab />}{tab === "security" && <SecurityTab />}+ {tab === "models" && <ModelsTab />}{tab === "storage" && <StorageTab />}{tab === "audit" && <AuditTab />}</div>diff --git a/frontend/portal/src/views/Pipelines.css b/frontend/portal/src/views/Pipelines.cssindex 645ac144b0..abae938dd2 100644--- a/frontend/portal/src/views/Pipelines.css+++ b/frontend/portal/src/views/Pipelines.css@@ -516,3 +516,88 @@.portal-pipelines__composer-step.is-done {color: var(--color-green-dark);}++/* ──────────────────────────────────────────────────────────────────────── */+/* Roster + promoted sections */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-pipelines__section {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.portal-pipelines__section-h {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-pipelines__section-sub {+ margin: -0.25rem 0 0.25rem;+ font-size: 0.75rem;+ color: var(--color-text-4);+ max-width: 46rem;+}++/* Golden-set roster table */+.portal-pipelines__roster-name,+.portal-pipelines__promoted-name {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.portal-pipelines__roster-name strong,+.portal-pipelines__promoted-name strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-pipelines__roster-route,+.portal-pipelines__promoted-when {+ font-size: 0.6875rem;+ color: var(--color-text-4);+}++.portal-pipelines__roster-golden {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-pipelines__roster-rate {+ font-size: 0.6875rem;+ color: var(--color-text-4);+ font-variant-numeric: tabular-nums;+}++.portal-pipelines__roster-num,+.portal-pipelines__roster-version {+ font-variant-numeric: tabular-nums;+ color: var(--color-text-2);+}++.portal-pipelines__roster-version {+ font-family: var(--font-mono);+ font-size: 0.75rem;+}++/* Promoted-from-Editor table */+.portal-pipelines__promoted-muted {+ color: var(--color-text-3);+ font-size: 0.8125rem;+}++.portal-pipelines__promoted-folder {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-3);+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-sm);+ padding: 0.0625rem 0.375rem;+}diff --git a/frontend/portal/src/views/Pipelines.tsx b/frontend/portal/src/views/Pipelines.tsxindex f4297045a5..80f2677a08 100644--- a/frontend/portal/src/views/Pipelines.tsx+++ b/frontend/portal/src/views/Pipelines.tsx@@ -13,10 +13,12 @@ import {type Pipeline,type PipelinesResponse,} from "@portal/api/pipelines";+import { DeployedPipelinesTable } from "@portal/components/pipelines/DeployedPipelinesTable";import { PipelineCard } from "@portal/components/pipelines/PipelineCard";import { PipelineComposer } from "@portal/components/pipelines/PipelineComposer";import { PipelineDetail } from "@portal/components/pipelines/PipelineDetail";import { PipelineListSkeleton } from "@portal/components/pipelines/PipelineListSkeleton";+import { PromotedPipelines } from "@portal/components/pipelines/PromotedPipelines";import "@portal/views/Pipelines.css";export function Pipelines() {@@ -30,6 +32,7 @@ export function Pipelines() {const pipelines = data?.pipelines ?? [];const evals = data?.evals ?? null;+ const promoted = data?.promoted ?? [];const isEmpty = !isLoading && pipelines.length === 0;const fleetHealthy = useMemo(@@ -94,6 +97,22 @@ export function Pipelines() {/>)}+ {pipelines.length > 0 && (+ <section className="portal-pipelines__section">+ <h2 className="portal-pipelines__section-h">+ Golden-set reliability+ </h2>+ <p className="portal-pipelines__section-sub">+ Pass rate against each pipeline's golden set, judged against its own+ bound. Anything below bound shows amber or red.+ </p>+ <DeployedPipelinesTable+ pipelines={pipelines}+ onRowClick={setSelected}+ />+ </section>+ )}+{pipelines.length > 0 && (<div className="portal-pipelines__list">{pipelines.map((p) => (@@ -102,6 +121,19 @@ export function Pipelines() {</div>)}+ {promoted.length > 0 && (+ <section className="portal-pipelines__section">+ <h2 className="portal-pipelines__section-h">+ Promoted from the Editor+ </h2>+ <p className="portal-pipelines__section-sub">+ Watch-folder flows built in the Editor and promoted into the portal.+ Promote one to a policy to apply its rules fleet-wide.+ </p>+ <PromotedPipelines promoted={promoted} />+ </section>+ )}+<Draweropen={selected !== null}onClose={() => setSelected(null)}diff --git a/frontend/portal/src/views/Placeholder.css b/frontend/portal/src/views/Placeholder.cssdeleted file mode 100644index 0bc1f0c8ec..0000000000--- a/frontend/portal/src/views/Placeholder.css+++ /dev/null@@ -1,33 +0,0 @@-.portal-placeholder {- display: flex;- justify-content: center;- padding: 3rem 1.5rem;-}--.portal-placeholder__card {- max-width: 36rem;- text-align: center;-}--.portal-placeholder__eyebrow {- font-size: 0.75rem;- font-weight: 600;- text-transform: uppercase;- letter-spacing: 0.08em;- color: var(--color-blue);- margin-bottom: 0.5rem;-}--.portal-placeholder__title {- margin: 0 0 0.75rem;- font-size: 1.5rem;- font-weight: 700;- color: var(--color-text-1);-}--.portal-placeholder__copy {- margin: 0;- font-size: 0.9375rem;- line-height: 1.55;- color: var(--color-text-3);-}diff --git a/frontend/portal/src/views/Placeholder.stories.tsx b/frontend/portal/src/views/Placeholder.stories.tsxdeleted file mode 100644index dcd37a982d..0000000000--- a/frontend/portal/src/views/Placeholder.stories.tsx+++ /dev/null@@ -1,26 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { Placeholder } from "@portal/views/Placeholder";--const meta: Meta<typeof Placeholder> = {- title: "Portal/Views/Placeholder",- component: Placeholder,- parameters: { layout: "fullscreen" },-};-export default meta;-type Story = StoryObj<typeof Placeholder>;--export const Sources: Story = {- args: { view: "sources", phase: "Phase 5 — Sources & Agents" },-};-export const Documents: Story = {- args: { view: "documents", phase: "Phase 6 — Documents" },-};-export const Infrastructure: Story = {- args: { view: "infrastructure", phase: "Phase 7 — Infrastructure" },-};-export const Editor: Story = {- args: { view: "editor", phase: "Phase 8 — Editor" },-};-export const Settings: Story = {- args: { view: "settings", phase: "Settings — modal overlay" },-};diff --git a/frontend/portal/src/views/Placeholder.tsx b/frontend/portal/src/views/Placeholder.tsxdeleted file mode 100644index 6110c2b1ca..0000000000--- a/frontend/portal/src/views/Placeholder.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { Card } from "@shared/components";-import { VIEW_LABELS, type ViewId } from "@portal/contexts/ViewContext";-import "@portal/views/Placeholder.css";--interface PlaceholderProps {- view: ViewId;- phase?: string;-}--export function Placeholder({ view, phase }: PlaceholderProps) {- return (- <div className="portal-placeholder">- <Card padding="loose" className="portal-placeholder__card">- <div className="portal-placeholder__eyebrow">- {phase ?? "Coming soon"}- </div>- <h1 className="portal-placeholder__title">{VIEW_LABELS[view]}</h1>- <p className="portal-placeholder__copy">- This surface is part of the build plan but hasn’t been wired up- yet. The shell, theme, and tier behaviour around it are already live —- you can switch views from the sidebar, flip the theme, and change tier- to see how the chrome reacts.- </p>- </Card>- </div>- );-}diff --git a/frontend/portal/src/views/Policies.css b/frontend/portal/src/views/Policies.cssnew file mode 100644index 0000000000..d40df402bd--- /dev/null+++ b/frontend/portal/src/views/Policies.css@@ -0,0 +1,443 @@+.portal-policies {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-policies__head {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.portal-policies__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-policies__sub {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* Category grid */+.portal-policies__grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.875rem;+}++@media (max-width: 56rem) {+ .portal-policies__grid {+ grid-template-columns: 1fr;+ }+}++/* Category card */+.portal-policies__card {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+}++.portal-policies__card--locked {+ opacity: 0.7;+}++.portal-policies__card-head {+ display: flex;+ align-items: flex-start;+ gap: 0.625rem;+}++.portal-policies__cat-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 2rem;+ height: 2rem;+ flex-shrink: 0;+ border-radius: var(--radius-md);+ font-size: 1rem;+}++.portal-policies__cat-icon--neutral {+ background: var(--color-bg-subtle);+ color: var(--color-text-3);+}+.portal-policies__cat-icon--blue {+ background: var(--color-blue-light);+ color: var(--color-blue);+}+.portal-policies__cat-icon--purple {+ background: var(--color-purple-light);+ color: var(--color-purple);+}+.portal-policies__cat-icon--green {+ background: var(--color-green-light);+ color: var(--color-green-dark);+}+.portal-policies__cat-icon--amber {+ background: var(--color-amber-light);+ color: var(--color-amber-dark);+}+.portal-policies__cat-icon--red {+ background: var(--color-red-light);+ color: var(--color-red);+}++.portal-policies__card-titles {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+ flex: 1;+}++.portal-policies__card-title {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-policies__card-blurb {+ font-size: 0.75rem;+ color: var(--color-text-4);+ line-height: 1.4;+}++.portal-policies__card-summary {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-2);+}++.portal-policies__card-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-top: auto;+ flex-wrap: wrap;+}++.portal-policies__card-rules {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++.portal-policies__card-cta {+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-blue);+}++/* Configured-card stat footer */+.portal-policies__card-stats {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.5rem;+ margin-top: auto;+ padding-top: 0.75rem;+ border-top: 1px solid var(--color-border-light);+}++/* Wizard + detail shared chrome */+.portal-policies__wizard-title {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-policies__wizard-foot,+.portal-policies__detail-foot {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ width: 100%;+}++.portal-policies__wizard-banner {+ margin-top: 0.75rem;+}++.portal-policies__wizard-section {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ margin-top: 1rem;+}++.portal-policies__wizard-desc {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+}++.portal-policies__wizard-heading {+ margin: 0.75rem 0 0;+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-text-5);+ font-weight: 600;+}++.portal-policies__fields {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}++.portal-policies__toggle-row {+ padding: 0.25rem 0;+}++.portal-policies__field-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++/* Workflow step — tool rows */+.portal-policies__tool-head {+ display: flex;+ align-items: center;+ gap: 0.625rem;+}++.portal-policies__tool-name {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-policies__tool-endpoint {+ flex: 1;+ min-width: 0;+ font-family: var(--font-mono, monospace);+ font-size: 0.6875rem;+ color: var(--color-text-4);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* Sources picker */+.portal-policies__sources {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.5rem;+}++@media (max-width: 40rem) {+ .portal-policies__sources {+ grid-template-columns: 1fr;+ }+}++.portal-policies__source {+ display: flex;+ align-items: flex-start;+ gap: 0.5rem;+ padding: 0.625rem;+ text-align: left;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+ cursor: pointer;+ transition:+ border-color var(--motion-fast),+ background var(--motion-fast);+}++.portal-policies__source:hover {+ background: var(--color-bg-hover);+}++.portal-policies__source--on {+ border-color: var(--color-blue);+ background: var(--color-blue-light);+}++.portal-policies__source-icon {+ font-size: 1rem;+ line-height: 1.2;+ color: var(--color-text-3);+}++.portal-policies__source-text {+ display: flex;+ flex-direction: column;+ gap: 0.0625rem;+ min-width: 0;+}++.portal-policies__source-label {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-policies__source-desc {+ font-size: 0.6875rem;+ color: var(--color-text-4);+ line-height: 1.4;+}++/* Doc-type scope */+.portal-policies__doctypes-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-policies__doctypes {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+ margin-top: 0.625rem;+}++.portal-policies__link {+ border: none;+ background: none;+ padding: 0;+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-blue);+ cursor: pointer;+}++/* Output filename row */+.portal-policies__name-row {+ display: flex;+ gap: 0.5rem;+}++.portal-policies__name-row .sui-input {+ flex: 1;+}++/* Detail panel */+.portal-policies__detail-status {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ margin-bottom: 0.25rem;+}++.portal-policies__detail-meta {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-policies__enforce-flow {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.375rem;+}++.portal-policies__enforce-item {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}++.portal-policies__enforce-arrow {+ color: var(--color-text-5);+ font-size: 0.75rem;+}++.portal-policies__enforce-note {+ margin: 0.75rem 0 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+ line-height: 1.5;+}++/* Activity feed */+.portal-policies__activity-row {+ display: flex;+ align-items: flex-start;+ gap: 0.625rem;+ padding: 0.625rem 0.875rem;+}++.portal-policies__activity-row + .portal-policies__activity-row {+ border-top: 1px solid var(--color-border-light);+}++.portal-policies__activity-dot {+ width: 0.5rem;+ height: 0.5rem;+ flex-shrink: 0;+ margin-top: 0.375rem;+ border-radius: 50%;+}++.portal-policies__activity-dot--success {+ background: var(--color-green);+}+.portal-policies__activity-dot--warning {+ background: var(--color-amber);+}+.portal-policies__activity-dot--info {+ background: var(--color-blue);+}++.portal-policies__activity-text {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ flex: 1;+ min-width: 0;+}++.portal-policies__activity-doc {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-policies__activity-action {+ font-size: 0.75rem;+ color: var(--color-text-3);+}++.portal-policies__activity-time {+ font-size: 0.6875rem;+ color: var(--color-text-5);+ white-space: nowrap;+}++/* Detail stats footer */+.portal-policies__detail-stats {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ margin-top: 1rem;+}++.portal-policies__detail-stats .sui-stat {+ padding: 0.875rem 1rem;+}++.portal-policies__detail-stats .sui-stat + .sui-stat {+ border-left: 1px solid var(--color-border-light);+}diff --git a/frontend/portal/src/views/Policies.tsx b/frontend/portal/src/views/Policies.tsxnew file mode 100644index 0000000000..39dfd4725b--- /dev/null+++ b/frontend/portal/src/views/Policies.tsx@@ -0,0 +1,183 @@+import { useCallback, useState } from "react";+import { Skeleton } from "@shared/components";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ deletePolicy,+ fetchPolicies,+ runPolicy,+ savePolicy,+ type CatalogueEntry,+ type PoliciesResponse,+ type Policy,+ type PolicySetupResult,+} from "@portal/api/policies";+import { CatalogueSummary } from "@portal/components/policies/CatalogueSummary";+import { PolicyCategoryCard } from "@portal/components/policies/PolicyCategoryCard";+import { PolicyDetailPanel } from "@portal/components/policies/PolicyDetailPanel";+import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";+import "@portal/views/Policies.css";++/**+ * Translate the setup flow's collected result into the backend `Policy` wire+ * record (Policy.java): the tool chain becomes the ordered pipeline `steps`,+ * the run event becomes the `trigger`, and the output settings become `output`.+ * Reuses the existing record's id on edit so the POST updates in place.+ */+function toWirePolicy(+ entry: CatalogueEntry,+ result: PolicySetupResult,+): Policy {+ return {+ id: entry.policy?.state.backendId ?? "",+ name: `${entry.category.label} Policy`,+ enabled: entry.policy ? entry.policy.state.status !== "paused" : true,+ trigger: { event: result.runOn },+ sources: result.sources.map((source) => ({ source })),+ steps: result.steps,+ output: {+ mode: result.outputMode,+ name: result.outputName,+ namePosition: result.outputNamePosition,+ },+ categoryId: entry.category.id,+ };+}++export function Policies() {+ // The catalogue is refetched after every mutation by bumping this counter,+ // so the cards/detail reflect the in-memory store the handlers maintain.+ const [version, setVersion] = useState(0);+ const state = useAsync<PoliciesResponse>(() => fetchPolicies(), [version]);+ const { data, loading } = state;+ const { isLoading } = useSectionFlags(state);++ // The category whose detail panel is open (configured), and the one whose+ // setup wizard is open. Both reference a catalogue entry.+ const [detail, setDetail] = useState<CatalogueEntry | null>(null);+ const [wizard, setWizard] = useState<CatalogueEntry | null>(null);+ const [busy, setBusy] = useState(false);++ const catalogue = data?.catalogue ?? [];+ const refetch = useCallback(() => setVersion((v) => v + 1), []);++ // Open the detail panel for configured categories, the wizard otherwise.+ function openEntry(entry: CatalogueEntry) {+ if (entry.policy) setDetail(entry);+ else setWizard(entry);+ }++ async function handleSubmit(+ entry: CatalogueEntry,+ result: PolicySetupResult,+ ) {+ await savePolicy(toWirePolicy(entry, result));+ setWizard(null);+ setDetail(null);+ refetch();+ }++ async function runLifecycle(action: () => Promise<unknown>) {+ if (busy) return;+ setBusy(true);+ try {+ await action();+ setDetail(null);+ refetch();+ } finally {+ setBusy(false);+ }+ }++ function handleRun() {+ const id = detail?.policy?.state.backendId;+ if (id) void runLifecycle(() => runPolicy(id));+ }++ function handleTogglePause() {+ const entry = detail;+ const policy = entry?.policy;+ if (!entry || !policy?.state.backendId) return;+ // Pause/resume is a re-save with the enabled flag flipped (the backend has+ // no dedicated endpoint — every mutation routes through POST /policies).+ void runLifecycle(() =>+ savePolicy({+ id: policy.state.backendId!,+ name: `${entry.category.label} Policy`,+ enabled: policy.state.status === "paused",+ trigger: { event: policy.state.runOn ?? "upload" },+ sources: policy.state.sources.map((source) => ({ source })),+ steps: policy.steps,+ output: {+ mode: policy.state.outputMode ?? "new_version",+ name: policy.state.outputName ?? "",+ namePosition: "suffix",+ },+ categoryId: entry.category.id,+ }),+ );+ }++ function handleDelete() {+ const id = detail?.policy?.state.backendId;+ if (id) void runLifecycle(() => deletePolicy(id));+ }++ // Reopen the wizard for the policy currently shown in the detail panel.+ function handleEdit() {+ if (detail) {+ setWizard(detail);+ setDetail(null);+ }+ }++ return (+ <div className="portal-policies">+ <header className="portal-policies__head">+ <h1 className="portal-policies__title">Policies</h1>+ <p className="portal-policies__sub">+ Standing automations that enforce a tool pipeline on every document.+ Each policy fires on upload or export, runs its tool chain, and saves+ the enforced version alongside the original.+ </p>+ </header>++ <CatalogueSummary data={data} loading={loading} />++ {isLoading && (+ <div className="portal-policies__grid" aria-hidden>+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} height="11rem" />+ ))}+ </div>+ )}++ {!isLoading && catalogue.length > 0 && (+ <div className="portal-policies__grid">+ {catalogue.map((entry) => (+ <PolicyCategoryCard+ key={entry.category.id}+ entry={entry}+ onOpen={openEntry}+ />+ ))}+ </div>+ )}++ <PolicyDetailPanel+ policy={detail?.policy ?? null}+ busy={busy}+ onClose={() => setDetail(null)}+ onEdit={handleEdit}+ onRun={handleRun}+ onTogglePause={handleTogglePause}+ onDelete={handleDelete}+ />++ <PolicySetupWizard+ entry={wizard}+ onClose={() => setWizard(null)}+ onSubmit={handleSubmit}+ />+ </div>+ );+}diff --git a/frontend/portal/src/views/Sources.css b/frontend/portal/src/views/Sources.cssindex 4849c0485d..7c5a594c0b 100644--- a/frontend/portal/src/views/Sources.css+++ b/frontend/portal/src/views/Sources.css@@ -15,6 +15,12 @@gap: 1rem;}+.portal-sources__actions {+ display: flex;+ gap: 0.5rem;+ flex-shrink: 0;+}+.portal-sources__title {margin: 0;font-size: 1.375rem;diff --git a/frontend/portal/src/views/Sources.tsx b/frontend/portal/src/views/Sources.tsxindex b40016ebfb..051391de23 100644--- a/frontend/portal/src/views/Sources.tsx+++ b/frontend/portal/src/views/Sources.tsx@@ -1,8 +1,10 @@import { useState } from "react";import { Button, EmptyState, Skeleton } from "@shared/components";import { useTier } from "@portal/contexts/TierContext";+import { useView } from "@portal/contexts/ViewContext";import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";import { fetchSources, type SourcesResponse } from "@portal/api/sources";+import { AgentBuilderIcon } from "@portal/components/icons";import { KpiStrip } from "@portal/components/sources/KpiStrip";import { SourcesTable } from "@portal/components/sources/SourcesTable";import { SourceDetailCard } from "@portal/components/sources/SourceDetailCard";@@ -11,6 +13,7 @@ import "@portal/views/Sources.css";export function Sources() {const { tier } = useTier();+ const { setActiveView } = useView();const state = useAsync<SourcesResponse>(() => fetchSources(tier), [tier]);const { data, loading } = state;const { isLoading, isEmpty } = useSectionFlags(state);@@ -31,12 +34,21 @@ export function Sources() {webhooks, connectors and more. Click a row for type-specific detail.</p></div>- <Button- onClick={() => setWizardOpen(true)}- leadingIcon={<span aria-hidden>+</span>}- >- Connect source- </Button>+ <div className="portal-sources__actions">+ <Button+ variant="outline"+ onClick={() => setActiveView("agent-builder")}+ leadingIcon={<AgentBuilderIcon size={16} />}+ >+ Agent Builder+ </Button>+ <Button+ onClick={() => setWizardOpen(true)}+ leadingIcon={<span aria-hidden>+</span>}+ >+ Connect source+ </Button>+ </div></header><KpiStrip data={data} loading={loading} />diff --git a/frontend/portal/src/views/Users.css b/frontend/portal/src/views/Users.cssnew file mode 100644index 0000000000..e33bbfa794--- /dev/null+++ b/frontend/portal/src/views/Users.css@@ -0,0 +1,255 @@+.portal-users {+ display: flex;+ flex-direction: column;+ gap: 1.75rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-users__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-users__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-users__sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* Shared section heads (roles, access) */+.portal-users__section-head {+ margin-bottom: 0.875rem;+}++.portal-users__section-title {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-users__section-sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ color: var(--color-text-3);+}++.portal-users__muted {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Members table */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-users__member-cell {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ min-width: 0;+}++.portal-users__member-text {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.portal-users__member-text strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-users__row-action {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: var(--radius-md);+ border: 1px solid transparent;+ background: transparent;+ color: var(--color-text-4);+ font-size: 1.125rem;+ line-height: 1;+ cursor: pointer;+ transition:+ background var(--motion-fast),+ color var(--motion-fast),+ border-color var(--motion-fast);+}++.portal-users__row-action:hover {+ background: var(--color-bg-hover);+ border-color: var(--color-border);+ color: var(--color-text-1);+}++.portal-users__table-skeleton {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Roles grid */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-users__roles-grid {+ display: grid;+ grid-template-columns: repeat(5, 1fr);+ gap: 0.875rem;+}++@media (max-width: 72rem) {+ .portal-users__roles-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}++@media (max-width: 40rem) {+ .portal-users__roles-grid {+ grid-template-columns: 1fr;+ }+}++.portal-users__role {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.portal-users__role-head {+ display: flex;+}++.portal-users__role-summary {+ margin: 0;+ font-size: 0.75rem;+ line-height: 1.45;+ color: var(--color-text-2);+}++.portal-users__role-perms {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}++.portal-users__role-perms li {+ position: relative;+ padding-left: 0.875rem;+ font-size: 0.6875rem;+ line-height: 1.4;+ color: var(--color-text-3);+}++.portal-users__role-perms li::before {+ content: "";+ position: absolute;+ left: 0;+ top: 0.4375rem;+ width: 0.25rem;+ height: 0.25rem;+ border-radius: 50%;+ background: var(--color-text-5);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Access & security */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-users__access {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-users__access-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.875rem;+}++@media (max-width: 52rem) {+ .portal-users__access-grid {+ grid-template-columns: 1fr;+ }+}++.portal-users__access-card-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-bottom: 0.75rem;+}++.portal-users__access-card-title {+ margin: 0;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-users__access-note {+ margin: 0.5rem 0 0;+ font-size: 0.75rem;+ line-height: 1.45;+ color: var(--color-text-4);+}++.portal-users__access-stats {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.75rem;+ margin: 0.75rem 0 0.875rem;+}++.portal-users__toggle-rows {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+ margin-top: 0.75rem;+}++.portal-users__toggle-row {+ display: flex;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Invite modal */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-users__invite-body {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-users__modal-footer {+ display: flex;+ justify-content: flex-end;+ gap: 0.5rem;+ width: 100%;+}diff --git a/frontend/portal/src/views/Users.tsx b/frontend/portal/src/views/Users.tsxnew file mode 100644index 0000000000..97dbb4b8a3--- /dev/null+++ b/frontend/portal/src/views/Users.tsx@@ -0,0 +1,100 @@+import { useState } from "react";+import { Button, EmptyState, Skeleton } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchUsers,+ type Member,+ type RoleId,+ type UsersResponse,+} from "@portal/api/users";+import { UsersSummaryStrip } from "@portal/components/users/UsersSummaryStrip";+import { MembersTable } from "@portal/components/users/MembersTable";+import { RolesGrid } from "@portal/components/users/RolesGrid";+import { AccessControls } from "@portal/components/users/AccessControls";+import { InviteMemberModal } from "@portal/components/users/InviteMemberModal";+import "@portal/views/Users.css";++export function Users() {+ const { tier } = useTier();+ const state = useAsync<UsersResponse>(() => fetchUsers(tier), [tier]);+ const { data, loading } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const [inviteOpen, setInviteOpen] = useState(false);++ const members = data?.members ?? [];++ // Row actions are non-functional shells until the backend exists; each logs+ // the intended request so the wiring point is obvious.+ function changeRole(member: Member, role: RoleId) {+ // TODO(backend): PATCH /v1/users/{id} { role }+ void member;+ void role;+ }+ function suspend(member: Member) {+ // TODO(backend): PATCH /v1/users/{id} { status: "suspended" }+ void member;+ }+ function remove(member: Member) {+ // TODO(backend): DELETE /v1/users/{id}+ void member;+ }++ return (+ <div className="portal-users">+ <header className="portal-users__head">+ <div>+ <h1 className="portal-users__title">Users</h1>+ <p className="portal-users__sub">+ The people in your organization and the access they hold — roles,+ status and security controls.+ </p>+ </div>+ <Button+ onClick={() => setInviteOpen(true)}+ leadingIcon={<span aria-hidden>+</span>}+ >+ Invite member+ </Button>+ </header>++ <UsersSummaryStrip data={data} loading={loading} />++ {isLoading && (+ <div className="portal-users__table-skeleton" aria-hidden>+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} height="3rem" />+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ title="No members yet"+ description="Invite your team to start collaborating on documents and pipelines."+ actions={+ <Button onClick={() => setInviteOpen(true)}>Invite member</Button>+ }+ />+ )}++ {!isLoading && !isEmpty && members.length > 0 && (+ <MembersTable+ members={members}+ onChangeRole={changeRole}+ onSuspend={suspend}+ onRemove={remove}+ />+ )}++ {data && <RolesGrid roles={data.roles} />}+ {data && <AccessControls access={data.access} />}++ <InviteMemberModal+ open={inviteOpen}+ onClose={() => setInviteOpen(false)}+ />+ </div>+ );+}diff --git a/frontend/shared/components/SettingsShell.css b/frontend/shared/components/SettingsShell.cssnew file mode 100644index 0000000000..5e56a7934e--- /dev/null+++ b/frontend/shared/components/SettingsShell.css@@ -0,0 +1,170 @@+.sui-settings-shell {+ display: flex;+ height: min(80vh, 36rem);+ min-height: 22rem;+}++/* Left navigation rail */+.sui-settings-shell__nav {+ width: 14rem;+ flex-shrink: 0;+ overflow-y: auto;+ padding: 1rem 0.75rem;+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ background: var(--color-bg-subtle);+ border-right: 1px solid var(--color-border-light);+}++.sui-settings-shell__group {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+}++.sui-settings-shell__group-title {+ padding: 0 0.5rem;+ margin-bottom: 0.25rem;+ font-size: 0.6875rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--color-text-4);+}++.sui-settings-shell__item {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ width: 100%;+ padding: 0.4rem 0.5rem;+ border: none;+ border-radius: var(--radius-sm);+ background: none;+ text-align: left;+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--color-text-2);+ cursor: pointer;+ transition:+ background var(--motion-fast),+ color var(--motion-fast);+}+.sui-settings-shell__item:hover:not(:disabled) {+ background: var(--color-bg-hover);+ color: var(--color-text-1);+}+.sui-settings-shell__item.is-active {+ background: var(--color-bg-hover);+ color: var(--color-text-1);+ box-shadow: inset 2px 0 0 var(--color-blue);+}+.sui-settings-shell__item:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++.sui-settings-shell__item-icon {+ display: inline-flex;+ flex-shrink: 0;+ color: currentColor;+}+.sui-settings-shell__item-label {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sui-settings-shell__item-badge {+ flex-shrink: 0;+}++/* Right content pane */+.sui-settings-shell__content {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ background: var(--color-surface);+}++.sui-settings-shell__header {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.875rem 1.25rem;+ border-bottom: 1px solid var(--color-border-light);+}+.sui-settings-shell__title {+ font-size: 1rem;+ font-weight: 650;+ color: var(--color-text-1);+}+.sui-settings-shell__header-actions {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}+.sui-settings-shell__close {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border: none;+ border-radius: var(--radius-sm);+ background: none;+ color: var(--color-text-3);+ cursor: pointer;+ transition:+ background var(--motion-fast),+ color var(--motion-fast);+}+.sui-settings-shell__close:hover {+ background: var(--color-bg-hover);+ color: var(--color-text-1);+}++.sui-settings-shell__body {+ flex: 1;+ overflow-y: auto;+ padding: 1.25rem;+}++.sui-settings-shell__footer {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 0.75rem;+ padding: 0.75rem 1.25rem;+ border-top: 1px solid var(--color-border-light);+}++/* On a phone the rail collapses to a horizontal strip above the content. */+@media (max-width: 40rem) {+ .sui-settings-shell {+ flex-direction: column;+ height: 100%;+ }+ .sui-settings-shell__nav {+ width: 100%;+ flex-direction: row;+ flex-wrap: wrap;+ gap: 0.25rem;+ border-right: none;+ border-bottom: 1px solid var(--color-border-light);+ }+ .sui-settings-shell__group {+ flex-direction: row;+ flex-wrap: wrap;+ gap: 0.25rem;+ }+ .sui-settings-shell__group-title {+ display: none;+ }+}diff --git a/frontend/shared/components/SettingsShell.stories.tsx b/frontend/shared/components/SettingsShell.stories.tsxnew file mode 100644index 0000000000..eb69c18ad3--- /dev/null+++ b/frontend/shared/components/SettingsShell.stories.tsx@@ -0,0 +1,76 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import {+ SettingsShell,+ type SettingsNavSection,+} from "@shared/components/SettingsShell";+import { Button } from "@shared/components/Button";++const SECTIONS: SettingsNavSection[] = [+ {+ title: "Account",+ items: [+ { key: "profile", label: "Profile" },+ { key: "appearance", label: "Appearance" },+ { key: "notifications", label: "Notifications" },+ ],+ },+ {+ title: "Workspace",+ items: [{ key: "general", label: "General" }],+ },+ {+ title: "Admin",+ items: [+ { key: "auth", label: "Authentication" },+ { key: "sessions", label: "Active sessions" },+ { key: "beta", label: "Early access", badge: "New" },+ ],+ },+];++const LABELS: Record<string, string> = {+ profile: "Profile",+ appearance: "Appearance",+ notifications: "Notifications",+ general: "General",+ auth: "Authentication",+ sessions: "Active sessions",+ beta: "Early access",+};++const meta: Meta<typeof SettingsShell> = {+ title: "Shared/SettingsShell",+ component: SettingsShell,+ parameters: { layout: "fullscreen" },+};+export default meta;++type Story = StoryObj<typeof SettingsShell>;++export const Default: Story = {+ render: () => {+ const [active, setActive] = useState("profile");+ return (+ <div style={{ height: "36rem", border: "1px solid var(--color-border)" }}>+ <SettingsShell+ sections={SECTIONS}+ activeKey={active}+ onSelect={setActive}+ title={LABELS[active]}+ onClose={() => {}}+ footer={+ <>+ <Button variant="ghost">Cancel</Button>+ <Button variant="gradient">Save changes</Button>+ </>+ }+ >+ <p style={{ color: "var(--color-text-3)" }}>+ Content for the “{LABELS[active]}” section renders here.+ </p>+ </SettingsShell>+ </div>+ );+ },+};diff --git a/frontend/shared/components/SettingsShell.tsx b/frontend/shared/components/SettingsShell.tsxnew file mode 100644index 0000000000..9dafcb14f4--- /dev/null+++ b/frontend/shared/components/SettingsShell.tsx@@ -0,0 +1,137 @@+import type { ReactNode } from "react";+import "@shared/components/SettingsShell.css";++export interface SettingsNavItem {+ key: string;+ label: string;+ /** Optional leading glyph. */+ icon?: ReactNode;+ /** Optional trailing badge (e.g. a plan gate or count). */+ badge?: ReactNode;+ disabled?: boolean;+}++export interface SettingsNavSection {+ /** Uppercase group heading above its items. */+ title: string;+ items: SettingsNavItem[];+}++export interface SettingsShellProps {+ sections: SettingsNavSection[];+ activeKey: string;+ onSelect: (key: string) => void;+ /** Heading for the content pane — usually the active item's label. */+ title: ReactNode;+ /** Renders a close button at the top-right of the content header. */+ onClose?: () => void;+ /** Extra header controls (e.g. a search field) left of the close button. */+ headerActions?: ReactNode;+ /** Sticky footer, e.g. Save / Cancel. */+ footer?: ReactNode;+ /** Active section content. */+ children: ReactNode;+ className?: string;+}++/**+ * Two-pane settings layout: a grouped left navigation rail and a content pane+ * with a sticky header (active title + actions) and an optional sticky footer.+ *+ * Layout chrome only — the caller owns section state and renders the active+ * panel as `children`. Host it inside any modal/dialog frame (it fills its+ * container's height and scrolls the two panes independently). Shared so the+ * portal and the editor can present account settings the same way.+ */+export function SettingsShell({+ sections,+ activeKey,+ onSelect,+ title,+ onClose,+ headerActions,+ footer,+ children,+ className,+}: SettingsShellProps) {+ return (+ <div+ className={["sui-settings-shell", className ?? ""]+ .filter(Boolean)+ .join(" ")}+ >+ <nav className="sui-settings-shell__nav" aria-label="Settings sections">+ {sections.map((section) => (+ <div key={section.title} className="sui-settings-shell__group">+ <span className="sui-settings-shell__group-title">+ {section.title}+ </span>+ {section.items.map((item) => (+ <button+ key={item.key}+ type="button"+ className={+ "sui-settings-shell__item" ++ (item.key === activeKey ? " is-active" : "")+ }+ aria-current={item.key === activeKey ? "page" : undefined}+ disabled={item.disabled}+ onClick={() => onSelect(item.key)}+ >+ {item.icon && (+ <span className="sui-settings-shell__item-icon" aria-hidden>+ {item.icon}+ </span>+ )}+ <span className="sui-settings-shell__item-label">+ {item.label}+ </span>+ {item.badge && (+ <span className="sui-settings-shell__item-badge">+ {item.badge}+ </span>+ )}+ </button>+ ))}+ </div>+ ))}+ </nav>++ <div className="sui-settings-shell__content">+ <header className="sui-settings-shell__header">+ <span className="sui-settings-shell__title">{title}</span>+ <div className="sui-settings-shell__header-actions">+ {headerActions}+ {onClose && (+ <button+ type="button"+ className="sui-settings-shell__close"+ onClick={onClose}+ aria-label="Close"+ >+ <svg+ viewBox="0 0 24 24"+ width="16"+ height="16"+ fill="none"+ stroke="currentColor"+ strokeWidth={1.75}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ >+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ )}+ </div>+ </header>++ <div className="sui-settings-shell__body">{children}</div>++ {footer && <div className="sui-settings-shell__footer">{footer}</div>}+ </div>+ </div>+ );+}diff --git a/frontend/shared/components/index.ts b/frontend/shared/components/index.tsindex 82dd4dd159..fd2846a7cc 100644--- a/frontend/shared/components/index.ts+++ b/frontend/shared/components/index.ts@@ -10,6 +10,7 @@ export * from "@shared/components/CodeBlock";export * from "@shared/components/SectionDivider";export * from "@shared/components/Card";export * from "@shared/components/Modal";+export * from "@shared/components/SettingsShell";// Layoutexport * from "@shared/components/Stack";