#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: full mock-driven surfaces, demonolithed components, backend-ready mocks (#6686)
Reece Browne96accea9840f
diff --git a/frontend/portal/MOCKS.md b/frontend/portal/MOCKS.mdnew file mode 100644index 0000000000..fd3d832f9e--- /dev/null+++ b/frontend/portal/MOCKS.md@@ -0,0 +1,76 @@+# Portal data layer — mock backend & handover++The portal is **mock-driven**. Every screen fetches real HTTP requests through a+thin typed API layer; in dev and Storybook those requests are intercepted by+[MSW](https://mswjs.io/) and answered with fixture data. Pointing the portal at a+**real backend** is a matter of *not registering MSW* — no component or API-layer+code changes.++## The three layers++```+view (useAsync) ──► api/<surface>.ts ──► httpJson(fetch) ──► MSW handler (dev) ──► fixture builder+ (the contract) └► real backend (prod) ─┘+```++1. **`api/<surface>.ts`** — thin, typed `httpJson` wrappers. **This is the backend+ contract.** Each function documents its endpoint (method, path, query params)+ and its response type. Nothing else in the app issues fetches.+2. **`mocks/handlers/<surface>.ts`** — MSW handlers that answer those endpoints+ with `mocks/<surface>.ts` fixtures. Registered in `mocks/handlers/index.ts`.+3. **`mocks/<surface>.ts`** — fixture builders **and the canonical TS types**+ (re-exported through `api/<surface>.ts`, so consumers import types from `api/`).++`api/http.ts` is the single `fetch` wrapper (sets headers, throws `HttpError` on+non-2xx). Views consume via `useAsync()` + `useSectionFlags()` (`hooks/useAsync.ts`).++## Conventions (consistent across every surface)++- **Tier**: tier-specific endpoints take `?tier=free|pro|enterprise`. The view+ passes `useTier().tier` and refetches on change (`useAsync(fn, [tier])`).+- **Latency**: handlers `await delay(120)` to exercise loading/skeleton states.+- **Read-only today**: surfaces are GET-driven. The few writes (mark-all-read,+ op run) exist; composer "Deploy", connect-source wizard, and create-key are+ **demo shells** (local state, no submit endpoint yet) — wire these to real+ POSTs during backend integration.++## Swapping in a real backend++1. Stop registering MSW (`mocks/browser.ts` / the dev bootstrap) — or gate it on+ an env flag (it's already dev-only via `import.meta.env.DEV`).+2. Make `httpJson` hit your API origin (add a `baseURL`/proxy in `api/http.ts`).+3. Match the response shapes in `api/<surface>.ts` (the exported types are the spec).+4. Delete `mocks/` once parity is confirmed. Optionally relocate the types from+ `mocks/<surface>.ts` into `api/` (or a `types/` module) so they no longer live+ beside fixtures — purely cosmetic; the `api/` re-exports already shield consumers.++## Endpoint catalogue++| Surface | Method & path | Query | API fn | Response type |+|---|---|---|---|---|+| Home | `GET /v1/home/kpis` | `tier` | `fetchHomeKpis` | `KpiEntry[]` |+| Home | `GET /v1/analytics/usage` | — | `fetchUsageSeries` | `UsageSeriesResponse` |+| 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` |+| Sources | `GET /v1/sources` | `tier` | `fetchSources` | `SourcesResponse` |+| 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/storage` | `tier` | `fetchStorage` | `StorageConfig` |+| Infrastructure | `GET /v1/infrastructure/audit-log` | `tier` | `fetchAuditLog` | `AuditLogResponse` |+| Usage & Billing | `GET /v1/billing/usage` | — | `fetchBillingUsage` | `UsageSeriesResponse` |+| Usage & Billing | `GET /v1/billing/summary` | `tier` | `fetchBillingSummary` | `BillingSummary` |+| 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[]` |+| 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` | — | — | — |+| Assistant | `GET /v1/assistant/suggestions` · `POST /v1/assistant/messages` | — | — | — |+| Search | `GET /v1/search/quick-actions` | — | — | — |++> Catalogue generated from `mocks/handlers/*.ts`. The `api/<surface>.ts` JSDoc on+> each function is the authoritative per-endpoint reference.diff --git a/frontend/portal/UI_CONVENTIONS.md b/frontend/portal/UI_CONVENTIONS.mdnew file mode 100644index 0000000000..c4d51b5819--- /dev/null+++ b/frontend/portal/UI_CONVENTIONS.md@@ -0,0 +1,62 @@+# Portal UI conventions — SUI vs Mantine++The portal has two component sources. The rule:++> **Simple, presentational, brand-defining UI → our SUI design system+> (`@shared/components`). Complex, stateful, or accessibility-hard widgets →+> Mantine.** Don't reinvent what Mantine already does well; do own the look of+> the simple, high-frequency pieces.++Both are theme-bound: `MantineProvider` in `App.tsx` is wired to the portal's+`ThemeProvider` (`mantineTheme.ts` maps the brand palette), so Mantine widgets+follow the same light/dark switch and brand colours as SUI. **The provider is+intentional** — it exists precisely so we can drop Mantine widgets in where they+earn their keep.++## Use SUI (`@shared/components`) — our own style+Layout and presentational primitives we want full brand control over and that+are cheap to own:++`Button` · `Card` · `StatusBadge` / `MethodBadge` · `Chip` · `MetricCard` ·+`MetricStrip` · `StatTile` · `ProgressBar` · `Avatar` · `Banner` · `Skeleton` ·+`Spinner` · `EmptyState` · `NavItem` · `PanelHeader` · `SectionDivider` ·+`Stack` / `Inline` · `Table` (static/presentational) · `CodeBlock` ·+`FormField` (label/help/error layout) · simple `Tabs`.++## Use Mantine — don't reinvent+Anything that needs portals, focus traps, ARIA keyboard patterns, or is just a+solved hard problem:++- **Overlays**: `Modal`, `Drawer`, `Popover` (focus trap, scroll lock, escape, focus restore)+- **Menus**: `Menu` (roving arrow-key navigation)+- **Selects**: `Select` / `MultiSelect` / `Combobox` / `Autocomplete` (keyboard + filtering)+- **Dates**: `@mantine/dates` `DatePicker` / `DatePickerInput` (e.g. billing period range)+- **Files**: `@mantine/dropzone` `Dropzone` (connect-source upload, op-runner sample drop)+- **Progress UX**: `Stepper` (multi-step wizards), `Notifications`, `Tooltip`+- Hooks: prefer `@mantine/hooks` (`useDisclosure`, `useClickOutside`, `useHotkeys`, …) over hand-rolling.++## Why+Mantine is mature and battle-tested for accessibility. A review of the+hand-rolled SUI overlays found real gaps — `Dropdown` has no arrow-key+navigation, `Modal`/`Drawer` mishandle focus when there are no focusable+children, `Toast` uses `role="alert"` for every tone — exactly the things+Mantine gets right. Owning those is wasted effort and an a11y liability.++## Known migrations (hand-rolled today → should be Mantine)+These shipped as SUI primitives during the initial build and should move to+Mantine equivalents (fixes the a11y findings above):++| Today (SUI) | → Mantine |+|---|---|+| `Dropdown` (menus: tier switcher, app switcher, notifications) | `Menu` |+| `Modal` (composer, wizards, settings, create-key) | `Modal` |+| `Drawer` (pipeline detail) | `Drawer` |+| `Toast` | `notifications` |+| _new need:_ billing date range | `@mantine/dates` |+| _new need:_ file upload | `@mantine/dropzone` |++Keep `Tabs` SUI for the simple in-page switchers; only reach for more if a true+tabpanel/roving-focus contract is needed.++> Migrating overlays touches visible chrome and behaviour, so do it deliberately+> (with eyes on the result), not as a blind sweep.diff --git a/frontend/portal/src/App.tsx b/frontend/portal/src/App.tsxindex f51868e645..b01beade82 100644--- a/frontend/portal/src/App.tsx+++ b/frontend/portal/src/App.tsx@@ -9,6 +9,7 @@ import { AppShell } from "@portal/components/AppShell";import { AssistantButton } from "@portal/components/AssistantButton";import { AssistantPanel } from "@portal/components/AssistantPanel";import { SearchModal } from "@portal/components/SearchModal";+import { SettingsModal } from "@portal/components/SettingsModal";import { ViewRouter } from "@portal/ViewRouter";/**@@ -52,6 +53,12 @@ function GlobalShortcuts() {return null;}+/** Bridges the Settings modal's open/close props to UIContext state. */+function SettingsHost() {+ const { settingsOpen, closeSettings } = useUI();+ return <SettingsModal open={settingsOpen} onClose={closeSettings} />;+}+export function App() {return (<ThemeProvider>@@ -66,6 +73,7 @@ export function App() {<AssistantButton /><AssistantPanel /><SearchModal />+ <SettingsHost /></UIProvider></BrowserRouter></TierProvider>diff --git a/frontend/portal/src/ViewRouter.tsx b/frontend/portal/src/ViewRouter.tsxindex f8e0005e50..3051f74362 100644--- a/frontend/portal/src/ViewRouter.tsx+++ b/frontend/portal/src/ViewRouter.tsx@@ -1,65 +1,24 @@import { Navigate, Route, Routes } from "react-router-dom";import { Home } from "@portal/views/Home";import { Documents } from "@portal/views/Documents";-import { Placeholder } from "@portal/views/Placeholder";-import { VIEW_PATHS, type ViewId } from "@portal/contexts/ViewContext";--const PLACEHOLDER_PHASES: Partial<Record<ViewId, string>> = {- editor: "Phase 8 — Editor",- sources: "Phase 5 — Sources & Agents",- pipelines: "Phase 4 — Pipelines",- infrastructure: "Phase 7 — Infrastructure",- usage: "Phase 8 — Usage & Billing",- docs: "Phase 8 — Developer Docs",- settings: "Settings — modal overlay",-};+import { Pipelines } from "@portal/views/Pipelines";+import { Sources } from "@portal/views/Sources";+import { Infrastructure } from "@portal/views/Infrastructure";+import { Usage } from "@portal/views/Usage";+import { DeveloperDocs } from "@portal/views/DeveloperDocs";+import { VIEW_PATHS } from "@portal/contexts/ViewContext";export function ViewRouter() {return (<Routes><Route path={VIEW_PATHS.home} element={<Home />} />- <Route- path={VIEW_PATHS.pipelines}- element={- <Placeholder view="pipelines" phase={PLACEHOLDER_PHASES.pipelines} />- }- />- <Route- path={VIEW_PATHS.editor}- element={- <Placeholder view="editor" phase={PLACEHOLDER_PHASES.editor} />- }- />- <Route- path={VIEW_PATHS.sources}- element={- <Placeholder view="sources" phase={PLACEHOLDER_PHASES.sources} />- }- />+ <Route path={VIEW_PATHS.pipelines} element={<Pipelines />} />+ <Route path={VIEW_PATHS.sources} element={<Sources />} /><Route path={VIEW_PATHS.documents} element={<Documents />} />- <Route- path={VIEW_PATHS.infrastructure}- element={- <Placeholder- view="infrastructure"- phase={PLACEHOLDER_PHASES.infrastructure}- />- }- />- <Route- path={VIEW_PATHS.usage}- element={<Placeholder view="usage" phase={PLACEHOLDER_PHASES.usage} />}- />- <Route- path={VIEW_PATHS.docs}- element={<Placeholder view="docs" phase={PLACEHOLDER_PHASES.docs} />}- />- <Route- path={VIEW_PATHS.settings}- element={- <Placeholder view="settings" phase={PLACEHOLDER_PHASES.settings} />- }- />+ <Route path={VIEW_PATHS.infrastructure} element={<Infrastructure />} />+ <Route path={VIEW_PATHS.usage} element={<Usage />} />+ <Route path={VIEW_PATHS.docs} element={<DeveloperDocs />} />+ {/* Settings is a modal overlay, not a route (see AppShell + UIContext). */}{/* Unknown paths land on Home. */}<Route path="*" element={<Navigate to={VIEW_PATHS.home} replace />} /></Routes>diff --git a/frontend/portal/src/api/docs.ts b/frontend/portal/src/api/docs.tsnew file mode 100644index 0000000000..cc4a625016--- /dev/null+++ b/frontend/portal/src/api/docs.ts@@ -0,0 +1,27 @@+import { httpJson } from "@portal/api/http";+import type { Tier } from "@portal/contexts/TierContext";+import type { DocsContent, DocsNavSection } from "@portal/mocks/docs";++export type {+ AgentSkill,+ ApiErrorRow,+ CodeSample,+ DocsContent,+ DocsNavItem,+ DocsNavSection,+ EmbedComponent,+ Playbook,+ RateLimit,+ Sdk,+ SdkStatus,+} from "@portal/mocks/docs";++/** GET /v1/docs/nav — the docs nav tree. */+export async function fetchDocsNav(): Promise<DocsNavSection[]> {+ return httpJson<DocsNavSection[]>("/v1/docs/nav");+}++/** GET /v1/docs/content — the tier-scaled reference content. */+export async function fetchDocsContent(tier: Tier): Promise<DocsContent> {+ return httpJson<DocsContent>(`/v1/docs/content?tier=${tier}`);+}diff --git a/frontend/portal/src/api/infrastructure.ts b/frontend/portal/src/api/infrastructure.tsnew file mode 100644index 0000000000..0154ae6a40--- /dev/null+++ b/frontend/portal/src/api/infrastructure.ts@@ -0,0 +1,70 @@+import { httpJson } from "@portal/api/http";+import type { Tier } from "@portal/contexts/TierContext";+import type {+ ApiKey,+ AuditLogResponse,+ DeploymentRegion,+ RecentDeployment,+ SecurityConfig,+ StorageConfig,+} from "@portal/mocks/infrastructure";++export type {+ AccessPolicy,+ ApiKey,+ ApiKeyPermission,+ ApiKeyStatus,+ AuditCategory,+ AuditEvent,+ AuditLogResponse,+ AuditStatus,+ AuditSummary,+ CertStatus,+ ComplianceCert,+ DataResidency,+ DeploymentRegion,+ DeploymentStatus,+ IpAllowEntry,+ RecentDeployment,+ RegionStatus,+ RetentionWindow,+ SecurityConfig,+ StorageConfig,+ StorageProvider,+} from "@portal/mocks/infrastructure";++export interface DeploymentsResponse {+ regions: DeploymentRegion[];+ recent: RecentDeployment[];+}++const q = (tier: Tier) => `?tier=${encodeURIComponent(tier)}`;++/** GET /v1/infrastructure/deployments?tier=… */+export async function fetchDeployments(+ tier: Tier,+): Promise<DeploymentsResponse> {+ return httpJson<DeploymentsResponse>(+ `/v1/infrastructure/deployments${q(tier)}`,+ );+}++/** GET /v1/infrastructure/api-keys?tier=… */+export async function fetchApiKeys(tier: Tier): Promise<ApiKey[]> {+ return httpJson<ApiKey[]>(`/v1/infrastructure/api-keys${q(tier)}`);+}++/** GET /v1/infrastructure/security?tier=… */+export async function fetchSecurity(tier: Tier): Promise<SecurityConfig> {+ return httpJson<SecurityConfig>(`/v1/infrastructure/security${q(tier)}`);+}++/** GET /v1/infrastructure/storage?tier=… */+export async function fetchStorage(tier: Tier): Promise<StorageConfig> {+ return httpJson<StorageConfig>(`/v1/infrastructure/storage${q(tier)}`);+}++/** GET /v1/infrastructure/audit-log?tier=… */+export async function fetchAuditLog(tier: Tier): Promise<AuditLogResponse> {+ return httpJson<AuditLogResponse>(`/v1/infrastructure/audit-log${q(tier)}`);+}diff --git a/frontend/portal/src/api/pipelines.ts b/frontend/portal/src/api/pipelines.tsnew file mode 100644index 0000000000..d3a250f31e--- /dev/null+++ b/frontend/portal/src/api/pipelines.ts@@ -0,0 +1,22 @@+import { httpJson } from "@portal/api/http";+import type { PipelinesResponse } from "@portal/mocks/pipelines";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ EvalsNote,+ GoldenSet,+ Pipeline,+ PipelineMetrics,+ PipelinesResponse,+ PipelineStatus,+ SchemaDrift,+ StageKey,+ StageSummary,+} from "@portal/mocks/pipelines";++/** GET /v1/pipelines?tier=… — the deployed fleet plus tier-specific extras. */+export async function fetchPipelines(tier: Tier): Promise<PipelinesResponse> {+ return httpJson<PipelinesResponse>(+ `/v1/pipelines?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/settings.ts b/frontend/portal/src/api/settings.tsnew file mode 100644index 0000000000..e6e850359a--- /dev/null+++ b/frontend/portal/src/api/settings.ts@@ -0,0 +1,16 @@+import { httpJson } from "@portal/api/http";+import type { SettingsSnapshot } from "@portal/mocks/settings";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ NotificationDefault,+ RegionOption,+ SettingsSnapshot,+} from "@portal/mocks/settings";++/** GET /v1/settings?tier=… — the account + workspace snapshot the modal edits. */+export async function fetchSettings(tier: Tier): Promise<SettingsSnapshot> {+ return httpJson<SettingsSnapshot>(+ `/v1/settings?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/sources.ts b/frontend/portal/src/api/sources.tsnew file mode 100644index 0000000000..cbc2c7cba6--- /dev/null+++ b/frontend/portal/src/api/sources.ts@@ -0,0 +1,25 @@+import { httpJson } from "@portal/api/http";+import type { SourcesResponse } from "@portal/mocks/sources";+import type { Tier } from "@portal/contexts/TierContext";++export type {+ AgentDetail,+ ApiClientDetail,+ BasicDetail,+ Source,+ SourceDetail,+ SourceStatus,+ SourceType,+ SourceTypeMeta,+ SourcesKpi,+ SourcesResponse,+ WebhookDetail,+} from "@portal/mocks/sources";+export { SOURCE_STATUS_TONE, SOURCE_TYPE_META } from "@portal/mocks/sources";++/** GET /v1/sources?tier=… — KPI strip + the sources table for the tier. */+export async function fetchSources(tier: Tier): Promise<SourcesResponse> {+ return httpJson<SourcesResponse>(+ `/v1/sources?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/api/usage.ts b/frontend/portal/src/api/usage.tsnew file mode 100644index 0000000000..6e80d8312c--- /dev/null+++ b/frontend/portal/src/api/usage.ts@@ -0,0 +1,44 @@+import { httpJson } from "@portal/api/http";+import type { Tier } from "@portal/contexts/TierContext";+import type {+ BillingHistoryRow,+ BillingSummary,+ PlanOption,+ UsageSeriesResponse,+} from "@portal/mocks/usage";++export type {+ BillingHistoryRow,+ BillingSummary,+ InvoiceStatus,+ PlanOption,+ UsagePoint,+ UsageSeriesResponse,+} from "@portal/mocks/usage";+export { OVERAGE_RATE } from "@portal/mocks/usage";++/** GET /v1/billing/usage — 30-day docs-processed series. */+export async function fetchBillingUsage(): Promise<UsageSeriesResponse> {+ return httpJson<UsageSeriesResponse>("/v1/billing/usage");+}++/** GET /v1/billing/summary?tier=… — KPI strip + current-plan figures. */+export async function fetchBillingSummary(tier: Tier): Promise<BillingSummary> {+ return httpJson<BillingSummary>(+ `/v1/billing/summary?tier=${encodeURIComponent(tier)}`,+ );+}++/** GET /v1/billing/plans — available plan catalogue. */+export async function fetchPlanOptions(): Promise<PlanOption[]> {+ return httpJson<PlanOption[]>("/v1/billing/plans");+}++/** GET /v1/billing/history?tier=… — invoice / line-item history. */+export async function fetchBillingHistory(+ tier: Tier,+): Promise<BillingHistoryRow[]> {+ return httpJson<BillingHistoryRow[]>(+ `/v1/billing/history?tier=${encodeURIComponent(tier)}`,+ );+}diff --git a/frontend/portal/src/components/SettingsModal.css b/frontend/portal/src/components/SettingsModal.cssnew file mode 100644index 0000000000..c43e0655a5--- /dev/null+++ b/frontend/portal/src/components/SettingsModal.css@@ -0,0 +1,257 @@+/* 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;+}++.portal-settings__section {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++/* Footer note pushes the action buttons to the right. */+.portal-settings__footer-note {+ margin-right: auto;+ align-self: center;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* ── Profile identity row ─────────────────────────────────────────────── */+.portal-settings__identity {+ display: flex;+ align-items: center;+ gap: 0.875rem;+ padding: 0.875rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-lg);+}++.portal-settings__identity-meta {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+ flex: 1 1 auto;+}++.portal-settings__identity-name {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-settings__identity-email {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++/* ── Preference groups ────────────────────────────────────────────────── */+.portal-settings__group {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+}++.portal-settings__group + .portal-settings__group {+ padding-top: 1rem;+ border-top: 1px solid var(--color-border-light);+}++.portal-settings__group-head {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+}++.portal-settings__group-title {+ margin: 0;+ font-size: 0.875rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-settings__group-sub {+ margin: 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* ── Theme picker ─────────────────────────────────────────────────────── */+.portal-settings__theme {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.625rem;+}++.portal-settings__theme-card {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.75rem;+ text-align: left;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+ transition:+ border-color var(--motion-fast),+ background var(--motion-fast),+ box-shadow var(--motion-fast);+}++.portal-settings__theme-card:hover {+ border-color: var(--color-border-strong, var(--color-border));+ background: var(--color-bg-hover);+}++.portal-settings__theme-card.is-active {+ border-color: var(--color-blue);+ box-shadow: 0 0 0 1px var(--color-blue);+}++.portal-settings__theme-swatch {+ display: inline-flex;+ flex-direction: column;+ gap: 2px;+ width: 2.25rem;+ height: 2.25rem;+ padding: 4px;+ border-radius: var(--radius-sm);+ border: 1px solid var(--color-border);+ flex: 0 0 auto;+}++.portal-settings__theme-swatch span {+ border-radius: 2px;+}++.portal-settings__theme-swatch span:first-child {+ flex: 0 0 35%;+}++.portal-settings__theme-swatch span:last-child {+ flex: 1 1 auto;+}++.portal-settings__theme-swatch--light {+ background: #ffffff;+}+.portal-settings__theme-swatch--light span:first-child {+ background: #cbd5e1;+}+.portal-settings__theme-swatch--light span:last-child {+ background: #eef2f7;+}++.portal-settings__theme-swatch--dark {+ background: #0f172a;+}+.portal-settings__theme-swatch--dark span:first-child {+ background: #475569;+}+.portal-settings__theme-swatch--dark span:last-child {+ background: #1e293b;+}++.portal-settings__theme-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+}++.portal-settings__theme-text strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-settings__theme-text span {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* ── Notification rows ────────────────────────────────────────────────── */+.portal-settings__notifs {+ display: flex;+ flex-direction: column;+}++.portal-settings__notif-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ padding: 0.75rem 0;+}++.portal-settings__notif-row + .portal-settings__notif-row {+ border-top: 1px solid var(--color-border-light);+}++.portal-settings__notif-text {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.portal-settings__notif-text strong {+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--color-text-1);+}++.portal-settings__notif-text span {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* ── Workspace plan card ──────────────────────────────────────────────── */+.portal-settings__plan {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ padding: 0.875rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-lg);+}++.portal-settings__plan-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+}++.portal-settings__plan-label {+ font-size: 0.8125rem;+ color: var(--color-text-3);+}++.portal-settings__plan-value {+ font-size: 0.8125rem;+ font-weight: 500;+ color: var(--color-text-1);+}++@media (max-width: 40rem) {+ .portal-settings__theme {+ grid-template-columns: 1fr;+ }+}diff --git a/frontend/portal/src/components/SettingsModal.tsx b/frontend/portal/src/components/SettingsModal.tsxnew file mode 100644index 0000000000..3d3450d144--- /dev/null+++ b/frontend/portal/src/components/SettingsModal.tsx@@ -0,0 +1,471 @@+import { useEffect, useMemo, useState } from "react";+import {+ Avatar,+ Button,+ FormField,+ Input,+ Modal,+ Select,+ Skeleton,+ StatusBadge,+ Tabs,+ ToggleSwitch,+ type SelectOption,+ type TabItem,+} from "@shared/components";+import { useTier } 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 "@portal/components/SettingsModal.css";++type SettingsTab = "profile" | "preferences" | "workspace";++interface SettingsModalProps {+ open: boolean;+ onClose: () => void;+}++/** Display copy for each notification category, keyed by the snapshot id. */+const NOTIFICATION_COPY: Record<+ string,+ { label: string; description: string }+> = {+ "pipeline-failures": {+ label: "Pipeline failures",+ description: "A run errors out or a step times out.",+ },+ "pipeline-success": {+ label: "Pipeline completions",+ description: "Every successful pipeline run finishes.",+ },+ "usage-alerts": {+ label: "Usage & quota alerts",+ description: "You approach a plan limit or rate cap.",+ },+ "weekly-digest": {+ label: "Weekly digest",+ description: "A Monday summary of volume and health.",+ },+ "security-alerts": {+ label: "Security alerts",+ description: "New API keys, sign-ins, or permission changes.",+ },+ "product-updates": {+ label: "Product updates",+ description: "New operations, sources, and release notes.",+ },+};++const TABS: TabItem<SettingsTab>[] = [+ { key: "profile", label: "Profile" },+ { key: "preferences", label: "Preferences" },+ { key: "workspace", label: "Workspace" },+];++const THEME_OPTIONS: { value: Theme; label: string; hint: string }[] = [+ { value: "light", label: "Light", hint: "Bright surfaces" },+ { value: "dark", label: "Dark", hint: "Dim surfaces" },+];++/**+ * 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.+ */+export function SettingsModal({ open, onClose }: SettingsModalProps) {+ const { tier } = useTier();+ const { theme, setTheme } = useTheme();+ const [tab, setTab] = useState<SettingsTab>("profile");++ const { data: snapshot, loading } = useAsync<SettingsSnapshot>(+ () => fetchSettings(tier),+ [tier],+ );++ // Editable copies seeded from the snapshot. Re-seed whenever a fresh snapshot+ // arrives (tier switch) or the modal is re-opened, so edits never leak across+ // sessions or stack on stale values.+ const [name, setName] = useState("");+ const [email, setEmail] = useState("");+ const [workspaceName, setWorkspaceName] = useState("");+ const [region, setRegion] = useState("");+ const [notifications, setNotifications] = useState<Record<string, boolean>>(+ {},+ );++ useEffect(() => {+ if (!snapshot) return;+ setName(snapshot.profile.name);+ setEmail(snapshot.profile.email);+ setWorkspaceName(snapshot.workspace.name);+ setRegion(snapshot.workspace.region);+ setNotifications(+ Object.fromEntries(snapshot.notifications.map((n) => [n.id, n.enabled])),+ );+ }, [snapshot]);++ useEffect(() => {+ if (open) setTab("profile");+ }, [open]);++ const regionOptions = useMemo<SelectOption[]>(() => {+ if (!snapshot) return [];+ return snapshot.regions.map((r) => ({+ value: r.value,+ label:+ r.enterpriseOnly && tier !== "enterprise"+ ? `${r.label} · Enterprise`+ : r.label,+ disabled: r.enterpriseOnly && tier !== "enterprise",+ }));+ }, [snapshot, tier]);++ const isLoading = loading && !snapshot;++ return (+ <Modal+ open={open}+ onClose={onClose}+ width="lg"+ title="Settings"+ subtitle="Manage your profile, preferences, and workspace."+ 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" && (+ <ProfilePanel+ loading={isLoading}+ name={name}+ email={email}+ role={snapshot?.profile.role}+ avatarUrl={snapshot?.profile.avatarUrl ?? undefined}+ onName={setName}+ onEmail={setEmail}+ />+ )}++ {tab === "preferences" && (+ <PreferencesPanel+ loading={isLoading}+ notifications={notifications}+ order={snapshot?.notifications.map((n) => n.id) ?? []}+ onToggle={(id, value) =>+ setNotifications((prev) => ({ ...prev, [id]: value }))+ }+ theme={theme}+ onTheme={setTheme}+ />+ )}++ {tab === "workspace" && (+ <WorkspacePanel+ loading={isLoading}+ workspaceName={workspaceName}+ onWorkspaceName={setWorkspaceName}+ region={region}+ onRegion={setRegion}+ regionOptions={regionOptions}+ planLabel={snapshot?.workspace.planLabel}+ seats={snapshot?.workspace.seats}+ />+ )}+ </div>+ </Modal>+ );+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Profile */+/* ──────────────────────────────────────────────────────────────────────── */++function ProfilePanel({+ loading,+ name,+ email,+ role,+ avatarUrl,+ onName,+ onEmail,+}: {+ loading: boolean;+ name: string;+ email: string;+ role?: string;+ avatarUrl?: string;+ onName: (v: string) => void;+ onEmail: (v: string) => void;+}) {+ if (loading) {+ return (+ <div className="portal-settings__section">+ <div className="portal-settings__identity">+ <Skeleton width="3.5rem" height="3.5rem" shape="circle" />+ <div className="portal-settings__identity-meta">+ <Skeleton width="9rem" />+ <Skeleton width="12rem" height="0.625rem" />+ </div>+ </div>+ <Skeleton height="3rem" />+ <Skeleton height="3rem" />+ </div>+ );+ }++ return (+ <div className="portal-settings__section">+ <div className="portal-settings__identity">+ <Avatar+ src={avatarUrl}+ name={name || "Account"}+ size="lg"+ tone="blue"+ />+ <div className="portal-settings__identity-meta">+ <div className="portal-settings__identity-name">+ {name || "Account"}+ {role && (+ <StatusBadge tone="info" size="sm" showDot={false}>+ {role}+ </StatusBadge>+ )}+ </div>+ <span className="portal-settings__identity-email">{email}</span>+ </div>+ <Button variant="outline" size="sm" disabled>+ Change photo+ </Button>+ </div>++ <FormField label="Full name">+ <Input+ value={name}+ onChange={(e) => onName(e.target.value)}+ placeholder="Your name"+ />+ </FormField>++ <FormField+ label="Email"+ helperText="Used for sign-in and notification delivery."+ >+ <Input+ type="email"+ value={email}+ onChange={(e) => onEmail(e.target.value)}+ placeholder="[email protected]"+ />+ </FormField>+ </div>+ );+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Preferences */+/* ──────────────────────────────────────────────────────────────────────── */++function PreferencesPanel({+ loading,+ notifications,+ order,+ onToggle,+ theme,+ onTheme,+}: {+ loading: boolean;+ notifications: Record<string, boolean>;+ order: string[];+ onToggle: (id: string, value: boolean) => void;+ theme: Theme;+ onTheme: (theme: Theme) => void;+}) {+ return (+ <div className="portal-settings__section">+ <div className="portal-settings__group">+ <div className="portal-settings__group-head">+ <h3 className="portal-settings__group-title">Appearance</h3>+ <p className="portal-settings__group-sub">+ Choose how the portal looks on this device.+ </p>+ </div>+ <div+ className="portal-settings__theme"+ role="radiogroup"+ aria-label="Theme"+ >+ {THEME_OPTIONS.map((opt) => (+ <button+ key={opt.value}+ type="button"+ role="radio"+ aria-checked={theme === opt.value}+ className={+ "portal-settings__theme-card" ++ (theme === opt.value ? " is-active" : "")+ }+ onClick={() => onTheme(opt.value)}+ >+ <span+ className={`portal-settings__theme-swatch portal-settings__theme-swatch--${opt.value}`}+ aria-hidden+ >+ <span />+ <span />+ </span>+ <span className="portal-settings__theme-text">+ <strong>{opt.label}</strong>+ <span>{opt.hint}</span>+ </span>+ </button>+ ))}+ </div>+ </div>++ <div className="portal-settings__group">+ <div className="portal-settings__group-head">+ <h3 className="portal-settings__group-title">Notifications</h3>+ <p className="portal-settings__group-sub">+ Pick which events reach your inbox.+ </p>+ </div>++ {loading && (+ <div className="portal-settings__notifs">+ {Array.from({ length: 4 }).map((_, i) => (+ <div key={i} className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <Skeleton width="9rem" />+ <Skeleton width="14rem" height="0.625rem" />+ </div>+ <Skeleton width="2.25rem" height="1.25rem" shape="rect" />+ </div>+ ))}+ </div>+ )}++ {!loading && (+ <div className="portal-settings__notifs">+ {order.map((id) => {+ const copy = NOTIFICATION_COPY[id];+ if (!copy) return null;+ return (+ <div key={id} className="portal-settings__notif-row">+ <div className="portal-settings__notif-text">+ <strong>{copy.label}</strong>+ <span>{copy.description}</span>+ </div>+ <ToggleSwitch+ checked={notifications[id] ?? false}+ onChange={(v) => onToggle(id, v)}+ />+ </div>+ );+ })}+ </div>+ )}+ </div>+ </div>+ );+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Workspace */+/* ──────────────────────────────────────────────────────────────────────── */++function WorkspacePanel({+ loading,+ workspaceName,+ onWorkspaceName,+ region,+ onRegion,+ regionOptions,+ planLabel,+ seats,+}: {+ loading: boolean;+ workspaceName: string;+ onWorkspaceName: (v: string) => void;+ region: string;+ onRegion: (v: string) => void;+ regionOptions: SelectOption[];+ planLabel?: string;+ seats?: { used: number; total: number };+}) {+ if (loading) {+ return (+ <div className="portal-settings__section">+ <Skeleton height="3rem" />+ <Skeleton height="3rem" />+ <Skeleton height="4rem" />+ </div>+ );+ }++ return (+ <div className="portal-settings__section">+ <FormField label="Workspace name">+ <Input+ value={workspaceName}+ onChange={(e) => onWorkspaceName(e.target.value)}+ placeholder="Workspace name"+ />+ </FormField>++ <FormField+ label="Data residency region"+ helperText="Where documents are processed and stored at rest."+ >+ <Select+ value={region}+ onChange={(e) => onRegion(e.target.value)}+ options={regionOptions}+ />+ </FormField>++ <div className="portal-settings__plan">+ <div className="portal-settings__plan-row">+ <span className="portal-settings__plan-label">Plan</span>+ <StatusBadge tone="purple" size="sm">+ {planLabel ?? "—"}+ </StatusBadge>+ </div>+ {seats && (+ <div className="portal-settings__plan-row">+ <span className="portal-settings__plan-label">Seats</span>+ <span className="portal-settings__plan-value">+ {seats.used} of {seats.total} used+ </span>+ </div>+ )}+ <Button variant="outline" size="sm" disabled>+ Manage billing+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/Sidebar.css b/frontend/portal/src/components/Sidebar.cssindex e422d92edf..c61f8e5c97 100644--- a/frontend/portal/src/components/Sidebar.css+++ b/frontend/portal/src/components/Sidebar.css@@ -20,31 +20,55 @@border-bottom: 1px solid var(--color-sidebar-divider);}-.portal-sidebar__wordmark {+/* Editor "Stirling PDF" wordmark logo (theme-switched in Sidebar.tsx) */+.portal-sidebar__brand {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+}+.portal-sidebar__brand-logo {+ height: 1.5rem;+ 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-weight: 700;- color: var(--color-logo-text);- letter-spacing: 0.02em;+ color: var(--color-text-3);+ letter-spacing: 0.01em;}-.portal-sidebar__workspace {+/* App switcher (down-arrow → Portal / Editor) */+.portal-sidebar__app-switch {margin-left: auto;+ display: flex;+}+.portal-sidebar__app-switch-btn {display: inline-flex;align-items: center;justify-content: center;width: 1.25rem;height: 1.25rem;+ border: none;+ background: none;+ cursor: pointer;border-radius: var(--radius-sm);color: var(--color-text-4);transition:background var(--motion-fast),color var(--motion-fast);}-.portal-sidebar__workspace:hover {+.portal-sidebar__app-switch-btn:hover {background: var(--color-bg-hover);color: var(--color-text-2);}+.portal-sidebar__app-icon {+ width: 1rem;+ height: 1.0625rem;+ display: block;+}/* Nav body */.portal-sidebar__nav {diff --git a/frontend/portal/src/components/Sidebar.tsx b/frontend/portal/src/components/Sidebar.tsxindex 5196c677c5..4897193f36 100644--- a/frontend/portal/src/components/Sidebar.tsx+++ b/frontend/portal/src/components/Sidebar.tsx@@ -1,11 +1,16 @@-import { NavItem } from "@shared/components";+import { Dropdown, NavItem } from "@shared/components";import { useView, type ViewId } from "@portal/contexts/ViewContext";import { useTier } from "@portal/contexts/TierContext";+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,- EditorIcon,SourcesIcon,PipelinesIcon,DocumentsIcon,@@ -17,6 +22,12 @@ 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.+const EDITOR_URL = import.meta.env.DEV ? "http://localhost:5180/" : "/";+interface NavEntry {id: ViewId;label: string;@@ -28,7 +39,6 @@ const GROUP_PRIMARY: NavEntry[] = [];const GROUP_OPERATIONAL: NavEntry[] = [- { id: "editor", label: "Editor", icon: <EditorIcon /> },{ id: "sources", label: "Sources", icon: <SourcesIcon /> },{ id: "pipelines", label: "Pipelines", icon: <PipelinesIcon /> },{ id: "documents", label: "Documents", icon: <DocumentsIcon /> },@@ -44,22 +54,6 @@ const GROUP_PLATFORM: NavEntry[] = [{ id: "docs", label: "Developer Docs", icon: <DocsIcon /> },];-function StirlingMark() {- // The Stirling brand mark — two stacked parallelograms in the brand blues.- return (- <svg- width="22"- height="22"- viewBox="0 0 22 22"- aria-hidden- role="presentation"- >- <path d="M5 4 L20 4 L17 11 L2 11 Z" fill="var(--color-blue)" />- <path d="M5 11 L17 11 L14 18 L2 18 Z" fill="var(--color-blue-border)" />- </svg>- );-}-function UsageFooter() {const { tier } = useTier();// Read the same endpoint Home's KPI strip uses so the doc count here can't@@ -117,6 +111,8 @@ function UsageFooter() {export function Sidebar() {const { activeView, setActiveView } = useView();+ const { theme } = useTheme();+ const { openSettings } = useUI();function renderGroup(entries: NavEntry[]) {return entries.map((entry) => (@@ -134,15 +130,54 @@ export function Sidebar() {return (<aside className="portal-sidebar" aria-label="Primary navigation"><div className="portal-sidebar__logo">- <StirlingMark />- <span className="portal-sidebar__wordmark">Stirling</span>- <button- type="button"- className="portal-sidebar__workspace"- aria-label="Switch workspace"- >- <ChevronDownIcon size={14} />- </button>+ <span className="portal-sidebar__brand">+ <img+ className="portal-sidebar__brand-logo"+ src={theme === "dark" ? wordmarkDark : wordmarkLight}+ alt="Stirling PDF"+ />+ <span className="portal-sidebar__logo-suffix">portal</span>+ </span>++ <Dropdown.Root align="end" className="portal-sidebar__app-switch">+ <Dropdown.Trigger>+ <button+ type="button"+ className="portal-sidebar__app-switch-btn"+ aria-label="Switch app"+ >+ <ChevronDownIcon size={14} />+ </button>+ </Dropdown.Trigger>+ <Dropdown.Menu width="11rem">+ <Dropdown.Item+ active+ leading={+ <img+ className="portal-sidebar__app-icon"+ src={theme === "dark" ? markDark : markLight}+ alt=""+ />+ }+ >+ Portal+ </Dropdown.Item>+ <Dropdown.Item+ onSelect={() => {+ window.location.href = EDITOR_URL;+ }}+ leading={+ <img+ className="portal-sidebar__app-icon"+ src={theme === "dark" ? markDark : markLight}+ alt=""+ />+ }+ >+ Editor+ </Dropdown.Item>+ </Dropdown.Menu>+ </Dropdown.Root></div><nav className="portal-sidebar__nav">@@ -164,8 +199,7 @@ export function Sidebar() {id="settings"label="Settings"icon={<SettingsIcon />}- isActive={activeView === "settings"}- onClick={(id) => setActiveView(id as ViewId)}+ onClick={() => openSettings()}/><UsageFooter /></div>diff --git a/frontend/portal/src/components/docs/AuthenticationSection.stories.tsx b/frontend/portal/src/components/docs/AuthenticationSection.stories.tsxnew file mode 100644index 0000000000..6fa96e4555--- /dev/null+++ b/frontend/portal/src/components/docs/AuthenticationSection.stories.tsx@@ -0,0 +1,20 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { AuthenticationSection } from "@portal/components/docs/AuthenticationSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof AuthenticationSection> = {+ title: "Portal/DeveloperDocs/AuthenticationSection",+ component: AuthenticationSection,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof AuthenticationSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/AuthenticationSection.tsx b/frontend/portal/src/components/docs/AuthenticationSection.tsxnew file mode 100644index 0000000000..b6f782305c--- /dev/null+++ b/frontend/portal/src/components/docs/AuthenticationSection.tsx@@ -0,0 +1,33 @@+import { Chip, CodeBlock } from "@shared/components";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function AuthenticationSection() {+ return (+ <DocsSection+ id="authentication"+ eyebrow="GETTING STARTED"+ title="Authentication"+ lead="All requests authenticate with a bearer token. Keys are scoped per environment and never expire unless rotated."+ >+ <CodeBlock+ lang="http"+ caption="every request"+ code={`Authorization: Bearer sk_live_8f2c...e10`}+ />+ <div className="portal-docs__keytable">+ <div className="portal-docs__keyrow">+ <Chip tone="green" size="sm" showDot>+ sk_live_+ </Chip>+ <span>Production keys — billed, rate-limited per your plan.</span>+ </div>+ <div className="portal-docs__keyrow">+ <Chip tone="amber" size="sm" showDot>+ sk_test_+ </Chip>+ <span>Sandbox keys — free, return synthetic fixtures.</span>+ </div>+ </div>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/ComponentsSection.stories.tsx b/frontend/portal/src/components/docs/ComponentsSection.stories.tsxnew file mode 100644index 0000000000..b4dedb366c--- /dev/null+++ b/frontend/portal/src/components/docs/ComponentsSection.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { ComponentsSection } from "@portal/components/docs/ComponentsSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof ComponentsSection> = {+ title: "Portal/DeveloperDocs/ComponentsSection",+ component: ComponentsSection,+ parameters: { layout: "padded" },+ args: { components: docsContentFor("pro").components },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ComponentsSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/ComponentsSection.tsx b/frontend/portal/src/components/docs/ComponentsSection.tsxnew file mode 100644index 0000000000..b25f5e5164--- /dev/null+++ b/frontend/portal/src/components/docs/ComponentsSection.tsx@@ -0,0 +1,43 @@+import { Card, Chip, CodeBlock } from "@shared/components";+import type { EmbedComponent } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function ComponentsSection({+ components,+}: {+ components: EmbedComponent[];+}) {+ return (+ <DocsSection+ id="component-library"+ eyebrow="COMPONENTS"+ title="Drop-in viewers"+ lead="Embeddable UI for review queues and document inspection. Bring your own styles or use the shipped theme."+ >+ <div className="portal-docs__component-grid">+ {components.map((c) => (+ <Card key={c.name} padding="default">+ <div className="portal-docs__component-head">+ <code className="portal-docs__component-name">{c.name}</code>+ <Chip tone="purple" size="sm">+ {c.tag}+ </Chip>+ </div>+ <p className="portal-docs__component-blurb">{c.blurb}</p>+ </Card>+ ))}+ </div>+ <CodeBlock+ lang="typescript"+ caption="embed the viewer"+ code={`import { DocumentViewer } from "@stirling/react";++<DocumentViewer+ documentId={doc.id}+ endpoint="/v1/invoice"+ onFieldEdit={(field, value) => save(field, value)}+/>`}+ />+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/DocsNav.stories.tsx b/frontend/portal/src/components/docs/DocsNav.stories.tsxnew file mode 100644index 0000000000..cbe474b102--- /dev/null+++ b/frontend/portal/src/components/docs/DocsNav.stories.tsx@@ -0,0 +1,41 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildDocsNav } from "@portal/mocks/docs";+import { DocsNav, DocsNavSkeleton } from "@portal/components/docs/DocsNav";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof DocsNav> = {+ title: "Portal/DeveloperDocs/DocsNav",+ component: DocsNav,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "15rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DocsNav>;++const sections = buildDocsNav();++export const Default: Story = {+ render: () => {+ const [active, setActive] = useState("quickstart");+ return <DocsNav sections={sections} active={active} onSelect={setActive} />;+ },+};++/** Webhooks ("Beta") and Agent skills ("New") exercise both badge tones. */+export const BadgedLeafActive: Story = {+ render: () => {+ const [active, setActive] = useState("skill-catalog");+ return <DocsNav sections={sections} active={active} onSelect={setActive} />;+ },+};++export const Loading: StoryObj = {+ render: () => <DocsNavSkeleton />,+};diff --git a/frontend/portal/src/components/docs/DocsNav.tsx b/frontend/portal/src/components/docs/DocsNav.tsxnew file mode 100644index 0000000000..d666d1789b--- /dev/null+++ b/frontend/portal/src/components/docs/DocsNav.tsx@@ -0,0 +1,72 @@+import { Skeleton, StatusBadge } from "@shared/components";+import type { DocsNavSection } from "@portal/api/docs";++/** Left-hand documentation nav tree; each leaf selects an in-page section. */+export function DocsNav({+ sections,+ active,+ onSelect,+}: {+ sections: DocsNavSection[];+ active: string;+ onSelect: (id: string) => void;+}) {+ return (+ <nav className="portal-docs__nav" aria-label="Documentation">+ {sections.map((section) => (+ <div key={section.id} className="portal-docs__nav-group">+ <div className="portal-docs__nav-head">+ <span className="portal-docs__nav-icon" aria-hidden>+ {section.icon}+ </span>+ {section.label}+ </div>+ <ul className="portal-docs__nav-list">+ {section.items.map((item) => {+ const isActive = item.id === active;+ return (+ <li key={item.id}>+ <button+ type="button"+ className={+ "portal-docs__nav-link" + (isActive ? " is-active" : "")+ }+ aria-current={isActive ? "page" : undefined}+ onClick={() => onSelect(item.id)}+ >+ <span className="portal-docs__nav-label">{item.label}</span>+ {item.badge && (+ <StatusBadge+ tone={item.badge === "New" ? "success" : "info"}+ size="sm"+ >+ {item.badge}+ </StatusBadge>+ )}+ </button>+ </li>+ );+ })}+ </ul>+ </div>+ ))}+ </nav>+ );+}++export function DocsNavSkeleton() {+ return (+ <nav className="portal-docs__nav" aria-hidden>+ {Array.from({ length: 4 }).map((_, gi) => (+ <div key={gi} className="portal-docs__nav-group">+ <Skeleton width="7rem" height="0.75rem" />+ <div className="portal-docs__nav-list">+ {Array.from({ length: 3 }).map((_, li) => (+ <Skeleton key={li} width="80%" height="0.875rem" />+ ))}+ </div>+ </div>+ ))}+ </nav>+ );+}diff --git a/frontend/portal/src/components/docs/DocsSection.stories.tsx b/frontend/portal/src/components/docs/DocsSection.stories.tsxnew file mode 100644index 0000000000..b48109cb2c--- /dev/null+++ b/frontend/portal/src/components/docs/DocsSection.stories.tsx@@ -0,0 +1,32 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { Card } from "@shared/components";+import { DocsSection } from "@portal/components/docs/DocsSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof DocsSection> = {+ title: "Portal/DeveloperDocs/DocsSection",+ component: DocsSection,+ parameters: { layout: "padded" },+ args: {+ id: "example",+ eyebrow: "API REFERENCE",+ title: "Section heading",+ lead: "A short lead paragraph introducing the section's content.",+ children: <Card padding="default">Section body</Card>,+ },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DocsSection>;++export const Default: Story = {};++export const WithoutLead: Story = {+ args: { lead: undefined },+};diff --git a/frontend/portal/src/components/docs/DocsSection.tsx b/frontend/portal/src/components/docs/DocsSection.tsxnew file mode 100644index 0000000000..9ae2898d10--- /dev/null+++ b/frontend/portal/src/components/docs/DocsSection.tsx@@ -0,0 +1,25 @@+import type { ReactNode } from "react";++/** Eyebrow + title + lead heading wrapper shared by every docs content pane. */+export function DocsSection({+ id,+ eyebrow,+ title,+ lead,+ children,+}: {+ id: string;+ eyebrow: string;+ title: string;+ lead?: string;+ children: ReactNode;+}) {+ return (+ <section id={id} className="portal-docs__section">+ <div className="portal-docs__section-eyebrow">{eyebrow}</div>+ <h1 className="portal-docs__section-title">{title}</h1>+ {lead && <p className="portal-docs__section-lead">{lead}</p>}+ {children}+ </section>+ );+}diff --git a/frontend/portal/src/components/docs/EndpointReferenceSection.stories.tsx b/frontend/portal/src/components/docs/EndpointReferenceSection.stories.tsxnew file mode 100644index 0000000000..c8a34f59a1--- /dev/null+++ b/frontend/portal/src/components/docs/EndpointReferenceSection.stories.tsx@@ -0,0 +1,20 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { EndpointReferenceSection } from "@portal/components/docs/EndpointReferenceSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof EndpointReferenceSection> = {+ title: "Portal/DeveloperDocs/EndpointReferenceSection",+ component: EndpointReferenceSection,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof EndpointReferenceSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/EndpointReferenceSection.tsx b/frontend/portal/src/components/docs/EndpointReferenceSection.tsxnew file mode 100644index 0000000000..622786fc12--- /dev/null+++ b/frontend/portal/src/components/docs/EndpointReferenceSection.tsx@@ -0,0 +1,72 @@+import { useMemo, useState } from "react";+import {+ MethodBadge,+ Tabs,+ type HttpMethod,+ type TabItem,+} from "@shared/components";+import { VERTICALS, ALL_ENDPOINTS } from "@shared/data/endpoints";+import { DocsSection } from "@portal/components/docs/DocsSection";++type VerticalFilter = "all" | (typeof VERTICALS)[number]["key"];++export function EndpointReferenceSection() {+ const [filter, setFilter] = useState<VerticalFilter>("all");++ const tabItems: TabItem<VerticalFilter>[] = [+ { key: "all", label: "All", count: ALL_ENDPOINTS.length },+ ...VERTICALS.map<TabItem<VerticalFilter>>((v) => ({+ key: v.key,+ label: v.label,+ count: v.endpoints.length,+ dotColor: v.color,+ accentColor: v.color,+ })),+ ];++ const shown = useMemo(+ () =>+ filter === "all" ? VERTICALS : VERTICALS.filter((v) => v.key === filter),+ [filter],+ );++ return (+ <DocsSection+ id="endpoints"+ eyebrow="API REFERENCE"+ title="Endpoints"+ lead="Every document type is a typed endpoint. POST a file, receive schema-validated JSON. Filter by vertical below."+ >+ <Tabs+ items={tabItems}+ activeKey={filter}+ onChange={setFilter}+ ariaLabel="Filter endpoints by vertical"+ />+ <div className="portal-docs__endpoints">+ {shown.map((v) => (+ <div key={v.key} className="portal-docs__endpoint-group">+ <div className="portal-docs__endpoint-grouphead">+ <span+ className="portal-docs__endpoint-dot"+ style={{ background: v.color }}+ aria-hidden+ />+ {v.label}+ </div>+ {v.endpoints.map((e) => (+ <div key={e.endpoint} className="portal-docs__endpoint-row">+ <MethodBadge method={"POST" as HttpMethod} />+ <code className="portal-docs__endpoint-path">{e.endpoint}</code>+ <span className="portal-docs__endpoint-name">{e.name}</span>+ <span className="portal-docs__endpoint-fields">+ {Object.keys(e.schema).length} fields+ </span>+ </div>+ ))}+ </div>+ ))}+ </div>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/ErrorsSection.stories.tsx b/frontend/portal/src/components/docs/ErrorsSection.stories.tsxnew file mode 100644index 0000000000..2437bc75bd--- /dev/null+++ b/frontend/portal/src/components/docs/ErrorsSection.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { ErrorsSection } from "@portal/components/docs/ErrorsSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof ErrorsSection> = {+ title: "Portal/DeveloperDocs/ErrorsSection",+ component: ErrorsSection,+ parameters: { layout: "padded" },+ args: { errors: docsContentFor("pro").errors },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ErrorsSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/ErrorsSection.tsx b/frontend/portal/src/components/docs/ErrorsSection.tsxnew file mode 100644index 0000000000..861afe7f77--- /dev/null+++ b/frontend/portal/src/components/docs/ErrorsSection.tsx@@ -0,0 +1,38 @@+import { CodeBlock, StatusBadge } from "@shared/components";+import type { ApiErrorRow } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function ErrorsSection({ errors }: { errors: ApiErrorRow[] }) {+ return (+ <DocsSection+ id="errors"+ eyebrow="API REFERENCE"+ title="Errors"+ lead="Errors return a stable machine-readable code plus a human message. The 4xx body always includes a request_id for support."+ >+ <div className="portal-docs__errors">+ {errors.map((e) => (+ <div key={e.code} className="portal-docs__error-row">+ <StatusBadge+ tone={e.tone === "red" ? "danger" : "warning"}+ size="sm"+ >+ {e.code}+ </StatusBadge>+ <span>{e.meaning}</span>+ </div>+ ))}+ </div>+ <CodeBlock+ lang="json"+ caption="422 Unprocessable Entity"+ code={`{+ "error": "schema_validation_failed",+ "message": "Field 'total' could not be located",+ "request_id": "req_3f8a91c2",+ "endpoint": "/v1/invoice"+}`}+ />+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/GettingStartedSection.stories.tsx b/frontend/portal/src/components/docs/GettingStartedSection.stories.tsxnew file mode 100644index 0000000000..18e8b3a289--- /dev/null+++ b/frontend/portal/src/components/docs/GettingStartedSection.stories.tsx@@ -0,0 +1,24 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { GettingStartedSection } from "@portal/components/docs/GettingStartedSection";+import "@portal/views/DeveloperDocs.css";++const { quickstartSamples, quickstartResponse } = docsContentFor("pro");++const meta: Meta<typeof GettingStartedSection> = {+ title: "Portal/DeveloperDocs/GettingStartedSection",+ component: GettingStartedSection,+ parameters: { layout: "padded" },+ args: { samples: quickstartSamples, response: quickstartResponse },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof GettingStartedSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/GettingStartedSection.tsx b/frontend/portal/src/components/docs/GettingStartedSection.tsxnew file mode 100644index 0000000000..e6eea61dfb--- /dev/null+++ b/frontend/portal/src/components/docs/GettingStartedSection.tsx@@ -0,0 +1,66 @@+import { Card, CodeBlock } from "@shared/components";+import type { CodeSample } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";+import { LangSnippet } from "@portal/components/docs/LangSnippet";++export function GettingStartedSection({+ samples,+ response,+}: {+ samples: CodeSample[];+ response: string;+}) {+ return (+ <DocsSection+ id="quickstart"+ eyebrow="GETTING STARTED"+ title="Quickstart"+ lead="Send your first document to a typed endpoint and get structured JSON back in three steps. No model training, no prompt engineering."+ >+ <ol className="portal-docs__steps">+ <li className="portal-docs__step">+ <span className="portal-docs__step-mark">1</span>+ <div className="portal-docs__step-body">+ <h3>Issue an API key</h3>+ <p>+ Create a scoped key from the Infrastructure tab. Keys carry rate+ limits and an optional IP allowlist. Export it into your shell:+ </p>+ <CodeBlock+ lang="bash"+ code={`export STIRLING_API_KEY="sk_live_8f2c...e10"`}+ />+ </div>+ </li>+ <li className="portal-docs__step">+ <span className="portal-docs__step-mark">2</span>+ <div className="portal-docs__step-body">+ <h3>Send a document</h3>+ <p>+ POST a file to any typed endpoint. The endpoint determines the+ schema you get back — here, the invoice extractor.+ </p>+ <LangSnippet samples={samples} caption="extract an invoice" />+ </div>+ </li>+ <li className="portal-docs__step">+ <span className="portal-docs__step-mark">3</span>+ <div className="portal-docs__step-body">+ <h3>Read the structured result</h3>+ <p>+ Every response is validated against the endpoint schema, with a+ confidence score and per-field provenance.+ </p>+ <CodeBlock lang="json" code={response} caption="200 OK" />+ </div>+ </li>+ </ol>++ <Card className="portal-docs__callout" accent="blue" padding="loose">+ <strong>Next:</strong> wire the same call into a pipeline to chain+ validation, redaction, and delivery — or expose it to an agent over MCP.+ See <em>Playbooks</em> for copy-paste recipes.+ </Card>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/LangSnippet.stories.tsx b/frontend/portal/src/components/docs/LangSnippet.stories.tsxnew file mode 100644index 0000000000..ea3d64d585--- /dev/null+++ b/frontend/portal/src/components/docs/LangSnippet.stories.tsx@@ -0,0 +1,28 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { LangSnippet } from "@portal/components/docs/LangSnippet";+import "@portal/views/DeveloperDocs.css";++const { quickstartSamples } = docsContentFor("pro");++const meta: Meta<typeof LangSnippet> = {+ title: "Portal/DeveloperDocs/LangSnippet",+ component: LangSnippet,+ parameters: { layout: "padded" },+ args: { samples: quickstartSamples, caption: "extract an invoice" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof LangSnippet>;++export const Default: Story = {};++export const SingleLanguage: Story = {+ args: { samples: quickstartSamples.slice(0, 1), caption: undefined },+};diff --git a/frontend/portal/src/components/docs/LangSnippet.tsx b/frontend/portal/src/components/docs/LangSnippet.tsxnew file mode 100644index 0000000000..1d68fc8b66--- /dev/null+++ b/frontend/portal/src/components/docs/LangSnippet.tsx@@ -0,0 +1,27 @@+import { useState } from "react";+import { CodeBlock, Tabs, type TabItem } from "@shared/components";+import type { CodeSample } from "@portal/api/docs";++/** Tabbed multi-language snippet; CodeBlock owns per-language copy. */+export function LangSnippet({+ samples,+ caption,+}: {+ samples: CodeSample[];+ caption?: string;+}) {+ const [active, setActive] = useState(samples[0]?.key ?? "");+ const current = samples.find((s) => s.key === active) ?? samples[0];+ const items: TabItem<string>[] = samples.map((s) => ({+ key: s.key,+ label: s.label,+ }));+ return (+ <div className="portal-docs__snippet">+ <Tabs items={items} activeKey={active} onChange={setActive} />+ {current && (+ <CodeBlock code={current.code} lang={current.lang} caption={caption} />+ )}+ </div>+ );+}diff --git a/frontend/portal/src/components/docs/PlaybooksSection.stories.tsx b/frontend/portal/src/components/docs/PlaybooksSection.stories.tsxnew file mode 100644index 0000000000..a914b22781--- /dev/null+++ b/frontend/portal/src/components/docs/PlaybooksSection.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { PlaybooksSection } from "@portal/components/docs/PlaybooksSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof PlaybooksSection> = {+ title: "Portal/DeveloperDocs/PlaybooksSection",+ component: PlaybooksSection,+ parameters: { layout: "padded" },+ args: { playbooks: docsContentFor("pro").playbooks },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PlaybooksSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/PlaybooksSection.tsx b/frontend/portal/src/components/docs/PlaybooksSection.tsxnew file mode 100644index 0000000000..0d1df02565--- /dev/null+++ b/frontend/portal/src/components/docs/PlaybooksSection.tsx@@ -0,0 +1,42 @@+import { Button, Card, Chip } from "@shared/components";+import type { Playbook } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function PlaybooksSection({ playbooks }: { playbooks: Playbook[] }) {+ return (+ <DocsSection+ id="recipes"+ eyebrow="PLAYBOOKS"+ title="Recipes"+ lead="End-to-end patterns that chain sources, operations, and destinations. Each maps to a pipeline you can clone."+ >+ <div className="portal-docs__playbook-grid">+ {playbooks.map((p) => (+ <Card key={p.title} accent={p.accent} padding="loose" interactive>+ <h3 className="portal-docs__playbook-title">{p.title}</h3>+ <p className="portal-docs__playbook-blurb">{p.blurb}</p>+ <div className="portal-docs__playbook-flow">+ {p.steps.map((step, i) => (+ <span key={step} className="portal-docs__playbook-step">+ <Chip size="sm" tone="neutral">+ {step}+ </Chip>+ {i < p.steps.length - 1 && (+ <span className="portal-docs__playbook-arrow" aria-hidden>+ →+ </span>+ )}+ </span>+ ))}+ </div>+ {/* TODO(backend): POST /v1/pipelines/clone-from-playbook to seed a+ draft pipeline from this recipe, then route to the composer. */}+ <Button variant="outline" accent={p.accent} size="sm">+ Clone recipe+ </Button>+ </Card>+ ))}+ </div>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/RateLimitsSection.stories.tsx b/frontend/portal/src/components/docs/RateLimitsSection.stories.tsxnew file mode 100644index 0000000000..e2a5b0bf60--- /dev/null+++ b/frontend/portal/src/components/docs/RateLimitsSection.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { RateLimitsSection } from "@portal/components/docs/RateLimitsSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof RateLimitsSection> = {+ title: "Portal/DeveloperDocs/RateLimitsSection",+ component: RateLimitsSection,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof RateLimitsSection>;++export const Free: Story = {+ args: { rateLimit: docsContentFor("free").rateLimit },+};++export const Pro: Story = {+ args: { rateLimit: docsContentFor("pro").rateLimit },+};++export const Enterprise: Story = {+ args: { rateLimit: docsContentFor("enterprise").rateLimit },+};diff --git a/frontend/portal/src/components/docs/RateLimitsSection.tsx b/frontend/portal/src/components/docs/RateLimitsSection.tsxnew file mode 100644index 0000000000..9c9e1eff42--- /dev/null+++ b/frontend/portal/src/components/docs/RateLimitsSection.tsx@@ -0,0 +1,38 @@+import { Card, CodeBlock } from "@shared/components";+import type { RateLimit } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function RateLimitsSection({ rateLimit }: { rateLimit: RateLimit }) {+ return (+ <DocsSection+ id="rate-limits"+ eyebrow="GETTING STARTED"+ title="Rate limits & quotas"+ lead="Limits scale with your plan. A 429 response includes a Retry-After header; the SDKs back off automatically."+ >+ <div className="portal-docs__limits">+ <Card padding="default">+ <div className="portal-docs__limit-label">Requests / minute</div>+ <div className="portal-docs__limit-value">{rateLimit.rpm}</div>+ </Card>+ <Card padding="default">+ <div className="portal-docs__limit-label">Burst</div>+ <div className="portal-docs__limit-value">{rateLimit.burst}</div>+ </Card>+ <Card padding="default">+ <div className="portal-docs__limit-label">Concurrency</div>+ <div className="portal-docs__limit-value">+ {rateLimit.concurrency}+ </div>+ </Card>+ </div>+ <CodeBlock+ lang="http"+ caption="429 Too Many Requests"+ code={`HTTP/1.1 429 Too Many Requests+Retry-After: 2+X-RateLimit-Remaining: 0`}+ />+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/SdksSection.stories.tsx b/frontend/portal/src/components/docs/SdksSection.stories.tsxnew file mode 100644index 0000000000..b7e76c63dd--- /dev/null+++ b/frontend/portal/src/components/docs/SdksSection.stories.tsx@@ -0,0 +1,29 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { SdksSection } from "@portal/components/docs/SdksSection";+import "@portal/views/DeveloperDocs.css";++const { sdks } = docsContentFor("pro");++const meta: Meta<typeof SdksSection> = {+ title: "Portal/DeveloperDocs/SdksSection",+ component: SdksSection,+ parameters: { layout: "padded" },+ args: { sdks },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof SdksSection>;++/** Full matrix — GA clients carry no badge; Beta and Deprecated are flagged. */+export const Default: Story = {};++export const GaOnly: Story = {+ args: { sdks: sdks.filter((s) => s.status === "ga") },+};diff --git a/frontend/portal/src/components/docs/SdksSection.tsx b/frontend/portal/src/components/docs/SdksSection.tsxnew file mode 100644index 0000000000..22a64297a3--- /dev/null+++ b/frontend/portal/src/components/docs/SdksSection.tsx@@ -0,0 +1,44 @@+import { Card, CodeBlock, StatusBadge } from "@shared/components";+import type { Sdk, SdkStatus } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";++/** GA clients carry no badge; only non-stable maturity is called out. */+const STATUS_BADGE: Partial<+ Record<SdkStatus, { label: string; tone: "info" | "warning" }>+> = {+ beta: { label: "Beta", tone: "info" },+ deprecated: { label: "Deprecated", tone: "warning" },+};++export function SdksSection({ sdks }: { sdks: Sdk[] }) {+ return (+ <DocsSection+ id="sdk-overview"+ eyebrow="SDKS"+ title="Official SDKs"+ lead="First-party clients with typed responses, automatic retries, and streaming uploads. All track the same endpoint catalogue."+ >+ <div className="portal-docs__sdk-grid">+ {sdks.map((sdk) => {+ const badge = STATUS_BADGE[sdk.status];+ return (+ <Card key={sdk.name} padding="default" interactive>+ <div className="portal-docs__sdk-head">+ <span className="portal-docs__sdk-icon" aria-hidden>+ {sdk.icon}+ </span>+ <h3 className="portal-docs__sdk-name">{sdk.name}</h3>+ {badge && (+ <StatusBadge tone={badge.tone} size="sm">+ {badge.label}+ </StatusBadge>+ )}+ </div>+ <CodeBlock lang={sdk.lang} code={sdk.install} maxHeight={80} />+ </Card>+ );+ })}+ </div>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/SkillsSection.stories.tsx b/frontend/portal/src/components/docs/SkillsSection.stories.tsxnew file mode 100644index 0000000000..2bec0fc448--- /dev/null+++ b/frontend/portal/src/components/docs/SkillsSection.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { docsContentFor } from "@portal/mocks/docs";+import { SkillsSection } from "@portal/components/docs/SkillsSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof SkillsSection> = {+ title: "Portal/DeveloperDocs/SkillsSection",+ component: SkillsSection,+ parameters: { layout: "padded" },+ args: { skills: docsContentFor("pro").skills },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof SkillsSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/SkillsSection.tsx b/frontend/portal/src/components/docs/SkillsSection.tsxnew file mode 100644index 0000000000..d3ababf943--- /dev/null+++ b/frontend/portal/src/components/docs/SkillsSection.tsx@@ -0,0 +1,29 @@+import { Card } from "@shared/components";+import type { AgentSkill } from "@portal/api/docs";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function SkillsSection({ skills }: { skills: AgentSkill[] }) {+ return (+ <DocsSection+ id="skill-catalog"+ eyebrow="SKILLS"+ title="Agent skills"+ lead="Bundled, named capabilities your agent invokes as a single tool. Each skill is a deterministic op chain with evals attached."+ >+ <div className="portal-docs__skill-grid">+ {skills.map((s) => (+ <Card key={s.name} padding="default" interactive>+ <div className="portal-docs__skill-head">+ <span className="portal-docs__skill-glyph" aria-hidden>+ ✷+ </span>+ <h3 className="portal-docs__skill-name">{s.name}</h3>+ </div>+ <p className="portal-docs__skill-blurb">{s.blurb}</p>+ <code className="portal-docs__skill-ops">{s.ops}</code>+ </Card>+ ))}+ </div>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/docs/WebhooksSection.stories.tsx b/frontend/portal/src/components/docs/WebhooksSection.stories.tsxnew file mode 100644index 0000000000..34e352dfc2--- /dev/null+++ b/frontend/portal/src/components/docs/WebhooksSection.stories.tsx@@ -0,0 +1,20 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { WebhooksSection } from "@portal/components/docs/WebhooksSection";+import "@portal/views/DeveloperDocs.css";++const meta: Meta<typeof WebhooksSection> = {+ title: "Portal/DeveloperDocs/WebhooksSection",+ component: WebhooksSection,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "46rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof WebhooksSection>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/docs/WebhooksSection.tsx b/frontend/portal/src/components/docs/WebhooksSection.tsxnew file mode 100644index 0000000000..b33fd87956--- /dev/null+++ b/frontend/portal/src/components/docs/WebhooksSection.tsx@@ -0,0 +1,33 @@+import { Card, CodeBlock } from "@shared/components";+import { DocsSection } from "@portal/components/docs/DocsSection";++export function WebhooksSection() {+ return (+ <DocsSection+ id="webhooks"+ eyebrow="API REFERENCE"+ title="Webhooks"+ lead="Subscribe to document.processed, pipeline.completed, and quota.threshold events. Payloads are signed with HMAC-SHA256."+ >+ <CodeBlock+ lang="json"+ caption="document.processed"+ code={`{+ "event": "document.processed",+ "id": "evt_91ac3f",+ "created": "2026-06-15T09:31:04Z",+ "data": {+ "endpoint": "/v1/invoice",+ "document_id": "doc_77b2",+ "confidence": 0.98+ }+}`}+ />+ <Card className="portal-docs__callout" accent="amber" padding="loose">+ Verify the <code>Stirling-Signature</code> header against your signing+ secret before trusting a payload. SDKs ship a{" "}+ <code>verifyWebhook()</code> helper.+ </Card>+ </DocsSection>+ );+}diff --git a/frontend/portal/src/components/infrastructure/ApiKeyCard.stories.tsx b/frontend/portal/src/components/infrastructure/ApiKeyCard.stories.tsxnew file mode 100644index 0000000000..23c06bae3a--- /dev/null+++ b/frontend/portal/src/components/infrastructure/ApiKeyCard.stories.tsx@@ -0,0 +1,68 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ApiKeyCard } from "@portal/components/infrastructure/ApiKeyCard";+import type { ApiKey } from "@portal/api/infrastructure";+import "@portal/views/Infrastructure.css";++const BASE: ApiKey = {+ id: "key-1",+ name: "Production · ingest",+ prefix: "sk_live_a3f8…",+ created: "Mar 2, 2026",+ lastUsed: "2m ago",+ status: "active",+ rateLimit: 1200,+ permissions: ["Read", "Write"],+ allowedIps: ["52.14.0.0/16", "18.221.0.0/16"],+ usageToday: 84210,+ usageMonth: 2410933,+};++const meta: Meta<typeof ApiKeyCard> = {+ title: "Portal/Infrastructure/ApiKeyCard",+ component: ApiKeyCard,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "44rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ApiKeyCard>;++export const Active: Story = { args: { apiKey: BASE } };++export const RotateSoon: Story = {+ args: {+ apiKey: {+ ...BASE,+ name: "Ops · admin (legacy)",+ status: "rotate-soon",+ permissions: ["Read", "Write", "Admin"],+ allowedIps: ["203.0.113.7/32"],+ usageToday: 0,+ },+ },+};++export const Revoked: Story = {+ args: {+ apiKey: {+ ...BASE,+ name: "Sandbox · webhook tester",+ prefix: "sk_test_2c4a…",+ status: "revoked",+ lastUsed: "never",+ permissions: ["Read"],+ allowedIps: [],+ usageToday: 0,+ usageMonth: 0,+ },+ },+};++export const NoIpAllowlist: Story = {+ args: { apiKey: { ...BASE, allowedIps: [] } },+};diff --git a/frontend/portal/src/components/infrastructure/ApiKeyCard.tsx b/frontend/portal/src/components/infrastructure/ApiKeyCard.tsxnew file mode 100644index 0000000000..d0a7e3fe3c--- /dev/null+++ b/frontend/portal/src/components/infrastructure/ApiKeyCard.tsx@@ -0,0 +1,97 @@+import { useState } from "react";+import { Card, Chip, StatusBadge } from "@shared/components";+import type { ApiKey } from "@portal/api/infrastructure";+import {+ KEY_LABEL,+ KEY_TONE,+} from "@portal/components/infrastructure/infraFormat";++/** Collapsible row for a single API key: header summary + expandable detail grid. */+export function ApiKeyCard({ apiKey }: { apiKey: ApiKey }) {+ const [open, setOpen] = useState(false);+ return (+ <Card padding="default" className="portal-infra__key">+ <button+ type="button"+ className="portal-infra__key-head"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ >+ <span className="portal-infra__key-id">+ <span className="portal-infra__cell-strong">{apiKey.name}</span>+ <code className="portal-infra__cell-code">{apiKey.prefix}</code>+ </span>+ <span className="portal-infra__key-head-right">+ <StatusBadge tone={KEY_TONE[apiKey.status]} size="sm">+ {KEY_LABEL[apiKey.status]}+ </StatusBadge>+ <span+ className={"portal-infra__chevron" + (open ? " is-open" : "")}+ aria-hidden+ >+ ›+ </span>+ </span>+ </button>++ {open && (+ <div className="portal-infra__key-body">+ <dl className="portal-infra__kv">+ <div>+ <dt>Created</dt>+ <dd>{apiKey.created}</dd>+ </div>+ <div>+ <dt>Last used</dt>+ <dd>{apiKey.lastUsed}</dd>+ </div>+ <div>+ <dt>Rate limit</dt>+ <dd className="portal-infra__mono">+ {apiKey.rateLimit.toLocaleString()} req/min+ </dd>+ </div>+ <div>+ <dt>Usage today</dt>+ <dd className="portal-infra__mono">+ {apiKey.usageToday.toLocaleString()}+ </dd>+ </div>+ <div>+ <dt>Usage this month</dt>+ <dd className="portal-infra__mono">+ {apiKey.usageMonth.toLocaleString()}+ </dd>+ </div>+ <div>+ <dt>Permissions</dt>+ <dd className="portal-infra__chips">+ {apiKey.permissions.map((p) => (+ <Chip key={p} tone="blue" size="sm">+ {p}+ </Chip>+ ))}+ </dd>+ </div>+ <div className="portal-infra__kv-wide">+ <dt>Allowed IPs</dt>+ <dd className="portal-infra__chips">+ {apiKey.allowedIps.length === 0 ? (+ <span className="portal-infra__muted">+ Any IP (no allowlist)+ </span>+ ) : (+ apiKey.allowedIps.map((ip) => (+ <Chip key={ip} tone="neutral" size="sm">+ <span className="portal-infra__mono">{ip}</span>+ </Chip>+ ))+ )}+ </dd>+ </div>+ </dl>+ </div>+ )}+ </Card>+ );+}diff --git a/frontend/portal/src/components/infrastructure/ApiKeysTab.stories.tsx b/frontend/portal/src/components/infrastructure/ApiKeysTab.stories.tsxnew file mode 100644index 0000000000..7743dd4fdf--- /dev/null+++ b/frontend/portal/src/components/infrastructure/ApiKeysTab.stories.tsx@@ -0,0 +1,44 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof ApiKeysTab> = {+ title: "Portal/Infrastructure/ApiKeysTab",+ component: ApiKeysTab,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "60rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ApiKeysTab>;++export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/api-keys", async () => {+ await delay("infinite");+ return HttpResponse.json([]);+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/api-keys", () => HttpResponse.json([])),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/infrastructure/ApiKeysTab.tsx b/frontend/portal/src/components/infrastructure/ApiKeysTab.tsxnew file mode 100644index 0000000000..f81ba468cc--- /dev/null+++ b/frontend/portal/src/components/infrastructure/ApiKeysTab.tsx@@ -0,0 +1,61 @@+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 { fetchApiKeys, type ApiKey } from "@portal/api/infrastructure";+import { ApiKeyCard } from "@portal/components/infrastructure/ApiKeyCard";+import { CreateKeyModal } from "@portal/components/infrastructure/CreateKeyModal";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";++export function ApiKeysTab() {+ const { tier } = useTier();+ const [modalOpen, setModalOpen] = useState(false);+ const state = useAsync<ApiKey[]>(() => fetchApiKeys(tier), [tier]);+ const { data: keys } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ return (+ <div className="portal-infra__stack">+ <div className="portal-infra__bar">+ <SectionHeader+ title="API keys"+ sub="Scoped credentials with per-key rate limits, permissions, and IP allowlists."+ />+ <Button+ variant="gradient"+ size="sm"+ onClick={() => setModalOpen(true)}+ leadingIcon={<span aria-hidden>+</span>}+ >+ Create key+ </Button>+ </div>++ {isLoading && (+ <div className="portal-infra__stack" aria-hidden>+ {Array.from({ length: 3 }).map((_, i) => (+ <Skeleton key={i} height="3.25rem" />+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ size="compact"+ title="No API keys yet"+ description="Create a scoped key to start calling the Stirling API."+ />+ )}++ {keys && keys.length > 0 && (+ <div className="portal-infra__keys">+ {keys.map((k) => (+ <ApiKeyCard key={k.id} apiKey={k} />+ ))}+ </div>+ )}++ <CreateKeyModal open={modalOpen} onClose={() => setModalOpen(false)} />+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/AuditTab.stories.tsx b/frontend/portal/src/components/infrastructure/AuditTab.stories.tsxnew file mode 100644index 0000000000..d4aefcd197--- /dev/null+++ b/frontend/portal/src/components/infrastructure/AuditTab.stories.tsx@@ -0,0 +1,49 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { AuditTab } from "@portal/components/infrastructure/AuditTab";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof AuditTab> = {+ title: "Portal/Infrastructure/AuditTab",+ component: AuditTab,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof AuditTab>;++export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/audit-log", async () => {+ await delay("infinite");+ return HttpResponse.json({ summary: {}, events: [] });+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/audit-log", () =>+ HttpResponse.json({+ summary: { totalEvents: 0, processing: 0, elevation: 0, config: 0 },+ events: [],+ }),+ ),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/infrastructure/AuditTab.tsx b/frontend/portal/src/components/infrastructure/AuditTab.tsxnew file mode 100644index 0000000000..7bedf71cc6--- /dev/null+++ b/frontend/portal/src/components/infrastructure/AuditTab.tsx@@ -0,0 +1,150 @@+import { useMemo, useState } from "react";+import {+ Card,+ EmptyState,+ MetricCard,+ StatusBadge,+ Table,+ Tabs,+ type TabItem,+ type TableColumn,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchAuditLog,+ type AuditCategory,+ type AuditEvent,+ type AuditLogResponse,+} from "@portal/api/infrastructure";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import { TableSkeleton } from "@portal/components/infrastructure/TableSkeleton";+import {+ AUDIT_CAT_LABEL,+ AUDIT_CAT_TONE,+ AUDIT_TONE,+ titleCase,+} from "@portal/components/infrastructure/infraFormat";++type AuditFilter = "all" | AuditCategory;++const AUDIT_FILTERS: TabItem<AuditFilter>[] = [+ { key: "all", label: "All" },+ { key: "auth", label: "Auth" },+ { key: "config", label: "Config" },+ { key: "elevation", label: "Elevation" },+ { key: "processing", label: "Processing" },+ { key: "security", label: "Security" },+];++const cols: TableColumn<AuditEvent>[] = [+ {+ key: "timestamp",+ header: "Timestamp",+ render: (e) => <span className="portal-infra__mono">{e.timestamp}</span>,+ },+ {+ key: "event",+ header: "Event",+ render: (e) => (+ <div className="portal-infra__event">+ <StatusBadge tone={AUDIT_CAT_TONE[e.category]} size="sm">+ {AUDIT_CAT_LABEL[e.category]}+ </StatusBadge>+ <span>{e.action}</span>+ </div>+ ),+ },+ {+ key: "actor",+ header: "Actor",+ render: (e) => <span className="portal-infra__mono">{e.actor}</span>,+ },+ { key: "target", header: "Target", render: (e) => e.target },+ {+ key: "status",+ header: "Status",+ render: (e) => (+ <StatusBadge tone={AUDIT_TONE[e.status]} size="sm">+ {titleCase(e.status)}+ </StatusBadge>+ ),+ },+ {+ key: "latency",+ header: "Latency",+ align: "right",+ render: (e) => <span className="portal-infra__mono">{e.latencyMs} ms</span>,+ },+];++export function AuditTab() {+ const { tier } = useTier();+ const [filter, setFilter] = useState<AuditFilter>("all");+ const state = useAsync<AuditLogResponse>(() => fetchAuditLog(tier), [tier]);+ const { data } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const rows = useMemo(() => {+ if (!data) return [];+ if (filter === "all") return data.events;+ return data.events.filter((e) => e.category === filter);+ }, [data, filter]);++ return (+ <div className="portal-infra__stack">+ <SectionHeader+ title="Audit logs"+ sub="Every authentication, configuration, and processing event across your workspace."+ />++ {data && (+ <section className="portal-infra__metrics">+ <MetricCard+ label="Total events · 24h"+ value={data.summary.totalEvents.toLocaleString()}+ />+ <MetricCard+ label="Processing"+ value={data.summary.processing.toLocaleString()}+ />+ <MetricCard+ label="Elevation"+ value={data.summary.elevation.toLocaleString()}+ />+ <MetricCard+ label="Config"+ value={data.summary.config.toLocaleString()}+ />+ </section>+ )}++ <Tabs<AuditFilter>+ items={AUDIT_FILTERS}+ activeKey={filter}+ onChange={setFilter}+ variant="pill"+ ariaLabel="Filter audit events by category"+ />++ <Card padding="none">+ {isLoading && <TableSkeleton rows={6} cols={6} />}+ {isEmpty && (+ <EmptyState+ size="compact"+ title="No audit events"+ description="Workspace activity will appear here as it happens."+ />+ )}+ {!isEmpty && data && (+ <Table+ columns={cols}+ rows={rows}+ rowKey={(e) => e.id}+ empty="No events in this category."+ />+ )}+ </Card>+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/CreateKeyModal.stories.tsx b/frontend/portal/src/components/infrastructure/CreateKeyModal.stories.tsxnew file mode 100644index 0000000000..f5e21035a6--- /dev/null+++ b/frontend/portal/src/components/infrastructure/CreateKeyModal.stories.tsx@@ -0,0 +1,16 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { CreateKeyModal } from "@portal/components/infrastructure/CreateKeyModal";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof CreateKeyModal> = {+ title: "Portal/Infrastructure/CreateKeyModal",+ component: CreateKeyModal,+ parameters: { layout: "fullscreen" },+ args: { open: true, onClose: () => console.log("close") },+};+export default meta;+type Story = StoryObj<typeof CreateKeyModal>;++export const Form: Story = {};++export const Closed: Story = { args: { open: false } };diff --git a/frontend/portal/src/components/infrastructure/CreateKeyModal.tsx b/frontend/portal/src/components/infrastructure/CreateKeyModal.tsxnew file mode 100644index 0000000000..3c3c8aa528--- /dev/null+++ b/frontend/portal/src/components/infrastructure/CreateKeyModal.tsx@@ -0,0 +1,137 @@+import { useState } from "react";+import {+ Banner,+ Button,+ Checkbox,+ CodeBlock,+ FormField,+ Input,+ Modal,+} from "@shared/components";+import type { ApiKeyPermission } from "@portal/api/infrastructure";++const PERMISSION_OPTS: ApiKeyPermission[] = ["Read", "Write", "Admin"];++// Shown once after a key is created. TODO(backend): use the one-time secret+// returned by POST /v1/infrastructure/api-keys — it is never persisted server-side.+const DEMO_NEW_KEY_SECRET = "sk_live_demo_key_rotate_in_prod";++export function CreateKeyModal({+ open,+ onClose,+}: {+ open: boolean;+ onClose: () => void;+}) {+ const [name, setName] = useState("");+ const [perms, setPerms] = useState<ApiKeyPermission[]>(["Read"]);+ const [ips, setIps] = useState("");+ const [created, setCreated] = useState(false);++ function reset() {+ setName("");+ setPerms(["Read"]);+ setIps("");+ setCreated(false);+ }++ function close() {+ onClose();+ // Defer reset so the modal doesn't flash empty during its close transition.+ setTimeout(reset, 200);+ }++ function togglePerm(p: ApiKeyPermission) {+ setPerms((prev) =>+ prev.includes(p) ? prev.filter((x) => x !== p) : [...prev, p],+ );+ }++ function createKey() {+ // TODO(backend): POST /v1/infrastructure/api-keys { name, perms, ips }+ // and render the one-time secret from the response instead of the fixture.+ setCreated(true);+ }++ return (+ <Modal+ open={open}+ onClose={close}+ width="md"+ title={created ? "Key created" : "Create API key"}+ subtitle={+ created+ ? "Copy this secret now — it won't be shown again."+ : "Scope the key to the minimum it needs. You can rotate or revoke at any time."+ }+ footer={+ created ? (+ <Button variant="gradient" onClick={close}>+ Done+ </Button>+ ) : (+ <div className="portal-infra__modal-actions">+ <Button variant="ghost" onClick={close}>+ Cancel+ </Button>+ <Button+ variant="gradient"+ disabled={name.trim() === "" || perms.length === 0}+ onClick={createKey}+ >+ Create key+ </Button>+ </div>+ )+ }+ >+ {created ? (+ <div className="portal-infra__stack">+ <CodeBlock+ code={DEMO_NEW_KEY_SECRET}+ lang="bash"+ caption="Secret key"+ />+ <Banner+ tone="warning"+ description="Store this in a secrets manager. Stirling only ever stores a hash — there is no way to recover it later."+ />+ </div>+ ) : (+ <div className="portal-infra__form">+ <FormField label="Key name" required>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder="e.g. Production · ingest"+ />+ </FormField>++ <FormField label="Permissions">+ <div className="portal-infra__perm-row">+ {PERMISSION_OPTS.map((p) => (+ <Checkbox+ key={p}+ label={p}+ checked={perms.includes(p)}+ onChange={() => togglePerm(p)}+ />+ ))}+ </div>+ </FormField>++ <FormField+ label="IP allowlist"+ helperText="Comma-separated CIDR ranges. Leave blank to allow any IP."+ >+ <Input+ value={ips}+ onChange={(e) => setIps(e.target.value)}+ placeholder="52.14.0.0/16, 203.0.113.7/32"+ />+ </FormField>+ </div>+ )}+ </Modal>+ );+}diff --git a/frontend/portal/src/components/infrastructure/DeploymentsTab.stories.tsx b/frontend/portal/src/components/infrastructure/DeploymentsTab.stories.tsxnew file mode 100644index 0000000000..de559bd344--- /dev/null+++ b/frontend/portal/src/components/infrastructure/DeploymentsTab.stories.tsx@@ -0,0 +1,46 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { DeploymentsTab } from "@portal/components/infrastructure/DeploymentsTab";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof DeploymentsTab> = {+ title: "Portal/Infrastructure/DeploymentsTab",+ component: DeploymentsTab,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof DeploymentsTab>;++export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/deployments", async () => {+ await delay("infinite");+ return HttpResponse.json({ regions: [], recent: [] });+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/deployments", () =>+ HttpResponse.json({ regions: [], recent: [] }),+ ),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/infrastructure/DeploymentsTab.tsx b/frontend/portal/src/components/infrastructure/DeploymentsTab.tsxnew file mode 100644index 0000000000..49195016b7--- /dev/null+++ b/frontend/portal/src/components/infrastructure/DeploymentsTab.tsx@@ -0,0 +1,206 @@+import {+ Card,+ Chip,+ EmptyState,+ ProgressBar,+ StatusBadge,+ Table,+ type TableColumn,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchDeployments,+ type DeploymentsResponse,+ type DeploymentRegion,+ type RecentDeployment,+} from "@portal/api/infrastructure";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import { TableSkeleton } from "@portal/components/infrastructure/TableSkeleton";+import {+ DEPLOY_LABEL,+ DEPLOY_TONE,+ pct,+ REGION_TONE,+ titleCase,+} from "@portal/components/infrastructure/infraFormat";++const regionCols: TableColumn<DeploymentRegion>[] = [+ {+ key: "name",+ header: "Region",+ render: (r) => (+ <div className="portal-infra__cell-stack">+ <span className="portal-infra__cell-strong">{r.name}</span>+ <code className="portal-infra__cell-code">{r.code}</code>+ </div>+ ),+ },+ {+ key: "latency",+ header: "Latency",+ align: "right",+ render: (r) => <span className="portal-infra__mono">{r.latencyMs} ms</span>,+ },+ {+ key: "load",+ header: "Load",+ width: "9rem",+ render: (r) => (+ <div className="portal-infra__load">+ <ProgressBar value={r.load} thresholded height={6} />+ <span className="portal-infra__load-pct">{pct(r.load)}</span>+ </div>+ ),+ },+ {+ key: "status",+ header: "Status",+ render: (r) => (+ <StatusBadge+ tone={REGION_TONE[r.status]}+ size="sm"+ pulse={r.status === "healthy"}+ >+ {titleCase(r.status)}+ </StatusBadge>+ ),+ },+ {+ key: "version",+ header: "Version",+ render: (r) => <code className="portal-infra__cell-code">{r.version}</code>,+ },+ {+ key: "uptime",+ header: "Uptime",+ align: "right",+ render: (r) => (+ <span className="portal-infra__mono">{pct(r.uptime, 3)}</span>+ ),+ },+ {+ key: "instances",+ header: "Instances",+ align: "right",+ render: (r) => <span className="portal-infra__mono">{r.instances}</span>,+ },+ {+ key: "throughput",+ header: "Throughput",+ align: "right",+ render: (r) => (+ <span className="portal-infra__mono">+ {r.throughput.toLocaleString()}/min+ </span>+ ),+ },+ {+ key: "p99",+ header: "P99",+ align: "right",+ render: (r) => <span className="portal-infra__mono">{r.p99Ms} ms</span>,+ },+];++const deployCols: TableColumn<RecentDeployment>[] = [+ {+ key: "version",+ header: "Version",+ render: (d) => <code className="portal-infra__cell-code">{d.version}</code>,+ },+ {+ key: "environment",+ header: "Environment",+ render: (d) => (+ <Chip+ tone={+ d.environment === "production"+ ? "blue"+ : d.environment === "canary"+ ? "purple"+ : "neutral"+ }+ size="sm"+ >+ {d.environment}+ </Chip>+ ),+ },+ { key: "product", header: "Product", render: (d) => d.product },+ {+ key: "status",+ header: "Status",+ render: (d) => (+ <StatusBadge tone={DEPLOY_TONE[d.status]} size="sm">+ {DEPLOY_LABEL[d.status]}+ </StatusBadge>+ ),+ },+ {+ key: "deployedBy",+ header: "Deployed by",+ render: (d) => <span className="portal-infra__mono">{d.deployedBy}</span>,+ },+ {+ key: "timestamp",+ header: "When",+ align: "right",+ render: (d) => <span className="portal-infra__muted">{d.timestamp}</span>,+ },+];++export function DeploymentsTab() {+ const { tier } = useTier();+ const state = useAsync<DeploymentsResponse>(+ () => fetchDeployments(tier),+ [tier],+ );+ const { data } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ return (+ <div className="portal-infra__stack">+ <section>+ <SectionHeader+ title="Regions"+ sub="Live health for every deployed Stirling region — latency, load, and rollout version."+ />+ <Card padding="none">+ {isLoading && <TableSkeleton rows={3} cols={9} />}+ {isEmpty && (+ <EmptyState+ size="compact"+ title="No regions deployed"+ description="Deployed regions appear here once your workspace is provisioned."+ />+ )}+ {!isEmpty && data && data.regions.length > 0 && (+ <Table+ columns={regionCols}+ rows={data.regions}+ rowKey={(r) => r.code}+ />+ )}+ </Card>+ </section>++ <section>+ <SectionHeader+ title="Recent deployments"+ sub="The latest rollouts across products and environments."+ />+ <Card padding="none">+ {isLoading && <TableSkeleton rows={4} cols={6} />}+ {data && data.recent.length > 0 && (+ <Table+ columns={deployCols}+ rows={data.recent}+ rowKey={(d) => d.id}+ />+ )}+ </Card>+ </section>+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/SectionHeader.stories.tsx b/frontend/portal/src/components/infrastructure/SectionHeader.stories.tsxnew file mode 100644index 0000000000..b7f9a83019--- /dev/null+++ b/frontend/portal/src/components/infrastructure/SectionHeader.stories.tsx@@ -0,0 +1,22 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof SectionHeader> = {+ title: "Portal/Infrastructure/SectionHeader",+ component: SectionHeader,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof SectionHeader>;++export const Default: Story = {+ args: {+ title: "Regions",+ sub: "Live health for every deployed Stirling region — latency, load, and rollout version.",+ },+};++export const ShortSub: Story = {+ args: { title: "API keys", sub: "Scoped credentials." },+};diff --git a/frontend/portal/src/components/infrastructure/SectionHeader.tsx b/frontend/portal/src/components/infrastructure/SectionHeader.tsxnew file mode 100644index 0000000000..fa2ba6d0b5--- /dev/null+++ b/frontend/portal/src/components/infrastructure/SectionHeader.tsx@@ -0,0 +1,9 @@+/** Title + sub-line heading shared by every Infrastructure section. */+export function SectionHeader({ title, sub }: { title: string; sub: string }) {+ return (+ <header className="portal-infra__section-head">+ <h2 className="portal-infra__section-title">{title}</h2>+ <p className="portal-infra__section-sub">{sub}</p>+ </header>+ );+}diff --git a/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsx b/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsxnew file mode 100644index 0000000000..a0a732b953--- /dev/null+++ b/frontend/portal/src/components/infrastructure/SecurityTab.stories.tsx@@ -0,0 +1,46 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { SecurityTab } from "@portal/components/infrastructure/SecurityTab";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof SecurityTab> = {+ title: "Portal/Infrastructure/SecurityTab",+ component: SecurityTab,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof SecurityTab>;++export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/security", async () => {+ await delay("infinite");+ return HttpResponse.json(null);+ }),+ ],+ },+ },+};++export const Unavailable: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/security", () =>+ HttpResponse.json(null, { status: 503 }),+ ),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/infrastructure/SecurityTab.tsx b/frontend/portal/src/components/infrastructure/SecurityTab.tsxnew file mode 100644index 0000000000..081e8f24ed--- /dev/null+++ b/frontend/portal/src/components/infrastructure/SecurityTab.tsx@@ -0,0 +1,197 @@+import { useState } from "react";+import {+ Banner,+ Card,+ EmptyState,+ RadioGroup,+ Skeleton,+ StatusBadge,+ Table,+ type RadioOption,+ type TableColumn,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchSecurity,+ type AccessPolicy,+ type DataResidency,+ type SecurityConfig,+} from "@portal/api/infrastructure";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import {+ CERT_LABEL,+ CERT_TONE,+} from "@portal/components/infrastructure/infraFormat";++const ACCESS_OPTS: RadioOption<AccessPolicy>[] = [+ {+ value: "stirling",+ label: "Stirling-held keys",+ description:+ "Stirling manages encryption keys. Simplest — zero key ops on your side.",+ },+ {+ value: "byok",+ label: "Bring your own key (BYOK)",+ description:+ "Supply a key from your own KMS. Stirling encrypts with it but can still read.",+ },+ {+ value: "hyok",+ label: "Hold your own key (HYOK)",+ description: "Keys never leave your KMS. Stirling holds only ciphertext.",+ },+];++const RESIDENCY_OPTS: RadioOption<DataResidency>[] = [+ { value: "us", label: "United States", description: "us-east-1 · us-west-2" },+ {+ value: "eu",+ label: "European Union",+ description: "eu-west-1 · GDPR data boundary",+ },+ { value: "apac", label: "Asia Pacific", description: "ap-southeast-1" },+];++const ipCols: TableColumn<SecurityConfig["ipAllowlist"][number]>[] = [+ { key: "label", header: "Label", render: (e) => e.label },+ {+ key: "cidr",+ header: "CIDR",+ render: (e) => <code className="portal-infra__cell-code">{e.cidr}</code>,+ },+ {+ key: "addedBy",+ header: "Added by",+ render: (e) => <span className="portal-infra__mono">{e.addedBy}</span>,+ },+ {+ key: "added",+ header: "Added",+ align: "right",+ render: (e) => <span className="portal-infra__muted">{e.added}</span>,+ },+];++export function SecurityTab() {+ const { tier } = useTier();+ const state = useAsync<SecurityConfig>(() => fetchSecurity(tier), [tier]);+ const { data } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ // Local mirrors so the radios are interactive without a backend round-trip,+ // seeded from the fetched config once it lands.+ // TODO(backend): PATCH /v1/infrastructure/security { accessPolicy, dataResidency }+ const [access, setAccess] = useState<AccessPolicy | null>(null);+ const [residency, setResidency] = useState<DataResidency | null>(null);++ const accessValue = access ?? data?.accessPolicy ?? "stirling";+ const residencyValue = residency ?? data?.dataResidency ?? "us";++ if (isLoading) {+ return (+ <div className="portal-infra__stack" aria-hidden>+ <Skeleton height="11rem" />+ <Skeleton height="7rem" />+ </div>+ );+ }++ if (isEmpty || !data) {+ return (+ <EmptyState+ size="compact"+ title="Security posture unavailable"+ description="Your workspace's security configuration will appear here."+ />+ );+ }++ return (+ <div className="portal-infra__stack">+ <section className="portal-infra__split">+ <Card padding="loose">+ <SectionHeader+ title="Document access policy"+ sub="Controls who can decrypt processed documents at rest."+ />+ <RadioGroup+ name="access-policy"+ value={accessValue}+ onChange={setAccess}+ options={ACCESS_OPTS}+ />+ {accessValue === "hyok" && (+ <Banner+ tone="success"+ className="portal-infra__banner"+ title="Stirling cannot decrypt your documents"+ description="With HYOK, encryption keys never leave your KMS. Stirling stores and processes only ciphertext you can revoke at any time."+ />+ )}+ </Card>++ <Card padding="loose">+ <SectionHeader+ title="Data residency"+ sub="Where documents are stored and processed."+ />+ <RadioGroup+ name="data-residency"+ value={residencyValue}+ onChange={setResidency}+ options={RESIDENCY_OPTS}+ />+ </Card>+ </section>++ <section>+ <SectionHeader+ title="Compliance"+ sub="Attestations and certifications covering the Stirling platform."+ />+ <div className="portal-infra__certs">+ {data.certs.map((c) => (+ <Card key={c.id} padding="default" className="portal-infra__cert">+ <div className="portal-infra__cert-head">+ <span className="portal-infra__cell-strong">{c.name}</span>+ <StatusBadge tone={CERT_TONE[c.status]} size="sm">+ {CERT_LABEL[c.status]}+ </StatusBadge>+ </div>+ <p className="portal-infra__cert-detail">{c.detail}</p>+ </Card>+ ))}+ </div>+ </section>++ <section>+ <SectionHeader+ title="IP allowlist"+ sub={+ tier === "free"+ ? "Restrict API access to known IP ranges — available on paid plans."+ : "API access is restricted to these CIDR ranges."+ }+ />+ {tier === "free" ? (+ <Banner+ tone="info"+ title="IP allowlisting is a paid feature"+ description="Upgrade to Pro to restrict API access to specific networks."+ />+ ) : (+ <Card padding="none">+ <Table+ columns={ipCols}+ rows={data.ipAllowlist}+ rowKey={(e) => e.id}+ empty="No IP ranges configured — all IPs allowed."+ />+ </Card>+ )}+ </section>+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/StorageTab.stories.tsx b/frontend/portal/src/components/infrastructure/StorageTab.stories.tsxnew file mode 100644index 0000000000..57bcdbff79--- /dev/null+++ b/frontend/portal/src/components/infrastructure/StorageTab.stories.tsx@@ -0,0 +1,80 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { StorageTab } from "@portal/components/infrastructure/StorageTab";+import type { StorageConfig } from "@portal/api/infrastructure";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof StorageTab> = {+ title: "Portal/Infrastructure/StorageTab",+ component: StorageTab,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "72rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof StorageTab>;++export const Default: Story = {};++const OVER_CAP: StorageConfig = {+ usedGb: 1920,+ quotaGb: 2000,+ retention: "180",+ providers: [+ {+ id: "stirling",+ name: "Stirling Cloud",+ kind: "stirling",+ connected: true,+ detail: "Primary vault · us-east-1",+ usedGb: 1532,+ },+ {+ id: "s3",+ name: "Amazon S3",+ kind: "s3",+ connected: true,+ detail: "s3://acme-prod-archive · WORM",+ usedGb: 388,+ },+ {+ id: "azure",+ name: "Azure Blob",+ kind: "azure",+ connected: false,+ detail: "Not connected",+ usedGb: 0,+ },+ ],+};++// Quota nearly exhausted — exercises the danger threshold on the usage bar.+export const OverThreshold: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/storage", () =>+ HttpResponse.json(OVER_CAP),+ ),+ ],+ },+ },+};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/infrastructure/storage", async () => {+ await delay("infinite");+ return HttpResponse.json(null);+ }),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/infrastructure/StorageTab.tsx b/frontend/portal/src/components/infrastructure/StorageTab.tsxnew file mode 100644index 0000000000..348983ac65--- /dev/null+++ b/frontend/portal/src/components/infrastructure/StorageTab.tsx@@ -0,0 +1,186 @@+import { useState } from "react";+import {+ Button,+ Card,+ EmptyState,+ FormField,+ ProgressBar,+ Select,+ Skeleton,+ StatusBadge,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchStorage,+ type RetentionWindow,+ type StorageConfig,+} from "@portal/api/infrastructure";+import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";+import { pct } from "@portal/components/infrastructure/infraFormat";++const RETENTION_OPTS = [+ { value: "30", label: "30 days" },+ { value: "60", label: "60 days" },+ { value: "90", label: "90 days" },+ { value: "180", label: "180 days" },+ { value: "never", label: "Never delete" },+];++const PROVIDER_GLYPH: Record<+ StorageConfig["providers"][number]["kind"],+ string+> = {+ stirling: "◆",+ s3: "▣",+ azure: "▤",+};++/** Storage fills past this fraction of quota are surfaced in red. */+const USAGE_DANGER_FRAC = 0.8;++export function StorageTab() {+ const { tier } = useTier();+ const state = useAsync<StorageConfig>(() => fetchStorage(tier), [tier]);+ const { data } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ // TODO(backend): PATCH /v1/infrastructure/storage { retention }+ const [retention, setRetention] = useState<RetentionWindow | null>(null);+ const retentionValue = retention ?? data?.retention ?? "90";++ if (isLoading) {+ return (+ <div className="portal-infra__stack" aria-hidden>+ <Skeleton height="6rem" />+ <Skeleton height="9rem" />+ </div>+ );+ }++ if (isEmpty || !data) {+ return (+ <EmptyState+ size="compact"+ title="No storage configured"+ description="Connected storage and usage appear here."+ />+ );+ }++ const usedFrac = data.quotaGb > 0 ? data.usedGb / data.quotaGb : 0;+ const overThreshold = usedFrac > USAGE_DANGER_FRAC;++ return (+ <div className="portal-infra__stack">+ <section>+ <SectionHeader+ title="Total usage"+ sub="Storage consumed across all connected providers."+ />+ <Card padding="loose">+ <div className="portal-infra__usage-head">+ <span className="portal-infra__usage-value">+ {data.usedGb.toLocaleString()} GB+ <span className="portal-infra__muted">+ {" "}+ / {data.quotaGb.toLocaleString()} GB+ </span>+ </span>+ <StatusBadge tone={overThreshold ? "danger" : "success"} size="sm">+ {pct(usedFrac)} used+ </StatusBadge>+ </div>+ <ProgressBar+ value={usedFrac}+ height={10}+ color={+ overThreshold+ ? "linear-gradient(90deg, var(--color-red), color-mix(in srgb, var(--color-red) 70%, white))"+ : "linear-gradient(90deg, var(--color-green), color-mix(in srgb, var(--color-green) 70%, white))"+ }+ label="Storage used"+ />+ </Card>+ </section>++ <section className="portal-infra__split">+ <Card padding="loose">+ <SectionHeader+ title="Connected providers"+ sub="Where processed artifacts are written."+ />+ <ul className="portal-infra__providers">+ {data.providers.map((p) => (+ <li key={p.id} className="portal-infra__provider">+ <span className="portal-infra__provider-glyph" aria-hidden>+ {PROVIDER_GLYPH[p.kind]}+ </span>+ <span className="portal-infra__provider-text">+ <span className="portal-infra__cell-strong">{p.name}</span>+ <span className="portal-infra__muted">{p.detail}</span>+ </span>+ {p.connected ? (+ <span className="portal-infra__provider-meta">+ <span className="portal-infra__mono">{p.usedGb} GB</span>+ <StatusBadge tone="success" size="sm">+ Connected+ </StatusBadge>+ </span>+ ) : (+ // TODO(backend): launch the provider OAuth/credential flow,+ // then POST /v1/infrastructure/storage/providers/{id}/connect+ <Button variant="outline" size="sm">+ Connect+ </Button>+ )}+ </li>+ ))}+ </ul>+ </Card>++ <Card padding="loose">+ <SectionHeader+ title="Retention"+ sub="How long artifacts are kept before lifecycle deletion."+ />+ <FormField label="Default retention window">+ <Select+ options={RETENTION_OPTS}+ value={retentionValue}+ onChange={(e) => setRetention(e.target.value as RetentionWindow)}+ />+ </FormField>++ <div className="portal-infra__lifecycle">+ <div className="portal-infra__lifecycle-stage is-active">+ <span className="portal-infra__lifecycle-dot" />+ <span className="portal-infra__lifecycle-label">Active</span>+ <span className="portal-infra__muted">+ 0–{retentionValue === "never" ? "∞" : retentionValue}d+ </span>+ </div>+ <span className="portal-infra__lifecycle-arrow" aria-hidden>+ →+ </span>+ <div className="portal-infra__lifecycle-stage">+ <span className="portal-infra__lifecycle-dot" />+ <span className="portal-infra__lifecycle-label">Archived</span>+ <span className="portal-infra__muted">cold storage</span>+ </div>+ <span className="portal-infra__lifecycle-arrow" aria-hidden>+ →+ </span>+ <div className="portal-infra__lifecycle-stage">+ <span className="portal-infra__lifecycle-dot" />+ <span className="portal-infra__lifecycle-label">Deleted</span>+ <span className="portal-infra__muted">+ {retentionValue === "never" ? "never" : "purged"}+ </span>+ </div>+ </div>+ </Card>+ </section>+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/TableSkeleton.stories.tsx b/frontend/portal/src/components/infrastructure/TableSkeleton.stories.tsxnew file mode 100644index 0000000000..61e817ab90--- /dev/null+++ b/frontend/portal/src/components/infrastructure/TableSkeleton.stories.tsx@@ -0,0 +1,23 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { Card } from "@shared/components";+import { TableSkeleton } from "@portal/components/infrastructure/TableSkeleton";+import "@portal/views/Infrastructure.css";++const meta: Meta<typeof TableSkeleton> = {+ title: "Portal/Infrastructure/TableSkeleton",+ component: TableSkeleton,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <Card padding="none" style={{ maxWidth: "60rem" }}>+ <S />+ </Card>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof TableSkeleton>;++export const Regions: Story = { args: { rows: 3, cols: 9 } };++export const AuditLog: Story = { args: { rows: 6, cols: 6 } };diff --git a/frontend/portal/src/components/infrastructure/TableSkeleton.tsx b/frontend/portal/src/components/infrastructure/TableSkeleton.tsxnew file mode 100644index 0000000000..6414b2c5ff--- /dev/null+++ b/frontend/portal/src/components/infrastructure/TableSkeleton.tsx@@ -0,0 +1,16 @@+import { Skeleton } from "@shared/components";++/** Placeholder grid shown inside a table card while rows are loading. */+export function TableSkeleton({ rows, cols }: { rows: number; cols: number }) {+ return (+ <div className="portal-infra__table-skel" aria-hidden>+ {Array.from({ length: rows }).map((_, r) => (+ <div key={r} className="portal-infra__table-skel-row">+ {Array.from({ length: cols }).map((_, c) => (+ <Skeleton key={c} height="0.75rem" />+ ))}+ </div>+ ))}+ </div>+ );+}diff --git a/frontend/portal/src/components/infrastructure/infraFormat.ts b/frontend/portal/src/components/infrastructure/infraFormat.tsnew file mode 100644index 0000000000..cf3e799952--- /dev/null+++ b/frontend/portal/src/components/infrastructure/infraFormat.ts@@ -0,0 +1,86 @@+import type { StatusTone } from "@shared/components";+import type {+ ApiKeyStatus,+ AuditCategory,+ AuditStatus,+ CertStatus,+ DeploymentStatus,+ RegionStatus,+} from "@portal/api/infrastructure";++/** Format a 0–1 fraction as a percentage string. */+export function pct(n: number, digits = 0): string {+ return `${(n * 100).toFixed(digits)}%`;+}++/** Capitalise the first letter of a lower-case status word. */+export function titleCase(word: string): string {+ return word[0].toUpperCase() + word.slice(1);+}++export const REGION_TONE: Record<RegionStatus, StatusTone> = {+ healthy: "success",+ degraded: "warning",+ down: "danger",+};++export const DEPLOY_TONE: Record<DeploymentStatus, StatusTone> = {+ live: "success",+ rolling: "info",+ "rolled-back": "warning",+ queued: "neutral",+};++export const DEPLOY_LABEL: Record<DeploymentStatus, string> = {+ live: "Live",+ rolling: "Rolling out",+ "rolled-back": "Rolled back",+ queued: "Queued",+};++export const KEY_TONE: Record<ApiKeyStatus, StatusTone> = {+ active: "success",+ revoked: "danger",+ "rotate-soon": "warning",+};++export const KEY_LABEL: Record<ApiKeyStatus, string> = {+ active: "Active",+ revoked: "Revoked",+ "rotate-soon": "Rotate soon",+};++export const CERT_TONE: Record<CertStatus, StatusTone> = {+ certified: "success",+ "in-progress": "warning",+ "not-started": "neutral",+};++export const CERT_LABEL: Record<CertStatus, string> = {+ certified: "Certified",+ "in-progress": "In progress",+ "not-started": "Not started",+};++export const AUDIT_TONE: Record<AuditStatus, StatusTone> = {+ success: "success",+ warning: "warning",+ danger: "danger",+ info: "info",+};++export const AUDIT_CAT_LABEL: Record<AuditCategory, string> = {+ auth: "Auth",+ config: "Config",+ elevation: "Elevation",+ processing: "Processing",+ security: "Security",+};++export const AUDIT_CAT_TONE: Record<AuditCategory, StatusTone> = {+ auth: "info",+ config: "neutral",+ elevation: "purple",+ processing: "success",+ security: "warning",+};diff --git a/frontend/portal/src/components/pipelines/PipelineCard.stories.tsx b/frontend/portal/src/components/pipelines/PipelineCard.stories.tsxnew file mode 100644index 0000000000..0df2755352--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineCard.stories.tsx@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PipelineCard } from "@portal/components/pipelines/PipelineCard";+import {+ DEGRADED_PIPELINE,+ HEALTHY_PIPELINE,+} from "@portal/components/pipelines/storyFixtures";++const meta: Meta<typeof PipelineCard> = {+ title: "Portal/Pipelines/PipelineCard",+ component: PipelineCard,+ parameters: { layout: "padded" },+ args: { onOpen: () => console.log("open") },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "52rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PipelineCard>;++export const Healthy: Story = {+ args: { pipeline: HEALTHY_PIPELINE },+};++export const DegradedWithDrift: Story = {+ args: { pipeline: DEGRADED_PIPELINE },+};diff --git a/frontend/portal/src/components/pipelines/PipelineCard.tsx b/frontend/portal/src/components/pipelines/PipelineCard.tsxnew file mode 100644index 0000000000..77fa31dc6d--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineCard.tsx@@ -0,0 +1,109 @@+import { Card, StatTile, StatusBadge } from "@shared/components";+import type { Pipeline, StageSummary } from "@portal/api/pipelines";+import {+ STAGE_ACCENT,+ STAGE_COLOR_VAR,+} from "@portal/components/pipelines/stageAccent";+import { compact, pct } from "@portal/components/pipelines/format";++/** Compact five-dot stage indicator: a lit dot per stage that has ops. */+function StageDots({ stages }: { stages: StageSummary[] }) {+ return (+ <span className="portal-pipelines__stage-dots" aria-hidden>+ {stages.map((s) => (+ <span+ key={s.key}+ className="portal-pipelines__stage-dot"+ style={{+ background: s.ops.length+ ? STAGE_COLOR_VAR[STAGE_ACCENT[s.key]]+ : "var(--color-border)",+ }}+ title={`${s.label}: ${s.ops.length} op${s.ops.length === 1 ? "" : "s"}`}+ />+ ))}+ </span>+ );+}++export interface PipelineCardProps {+ pipeline: Pipeline;+ onOpen: (p: Pipeline) => void;+}++/** Row in the deployed fleet: health, source→stages→destination rail, 24h metrics. */+export function PipelineCard({ pipeline, onOpen }: PipelineCardProps) {+ const m = pipeline.metrics;+ const degraded = pipeline.status === "degraded";+ const errorTone =+ m.errorRate >= 0.02+ ? "danger"+ : m.errorRate >= 0.01+ ? "warning"+ : "default";+ const driftCount = pipeline.drift.length;++ return (+ <Card+ padding="loose"+ interactive+ className="portal-pipelines__card"+ onClick={() => onOpen(pipeline)}+ >+ <div className="portal-pipelines__card-head">+ <div className="portal-pipelines__card-titles">+ <h3 className="portal-pipelines__card-title">{pipeline.name}</h3>+ <p className="portal-pipelines__card-blurb">{pipeline.blurb}</p>+ </div>+ <StatusBadge+ tone={degraded ? "warning" : "success"}+ size="sm"+ pulse={degraded}+ >+ {degraded ? "Degraded" : "Healthy"}+ </StatusBadge>+ </div>++ <div className="portal-pipelines__card-rail">+ <span className="portal-pipelines__rail-chip">{pipeline.source}</span>+ <span className="portal-pipelines__rail-arrow" aria-hidden>+ →+ </span>+ <StageDots stages={pipeline.stages} />+ <span className="portal-pipelines__rail-arrow" aria-hidden>+ →+ </span>+ <span className="portal-pipelines__rail-chip">+ {pipeline.destination}+ </span>+ </div>++ <div className="portal-pipelines__metrics">+ <StatTile label="Docs / 24h" value={compact(m.docs24h)} />+ <StatTile label="Throughput" value={`${m.throughputPerMin}/min`} />+ <StatTile+ label="Error rate"+ value={pct(m.errorRate, 2)}+ tone={errorTone}+ />+ <StatTile label="P95 latency" value={`${m.p95LatencyMs} ms`} />+ <StatTile label="Uptime" value={pct(m.uptime, 2)} />+ </div>++ <div className="portal-pipelines__card-foot">+ <span className="portal-pipelines__card-version">+ {pipeline.version} · {pipeline.regions.join(", ")}+ </span>+ <span className="portal-pipelines__card-golden">+ Golden {pipeline.golden.passing}/{pipeline.golden.total}+ {driftCount > 0 && (+ <span className="portal-pipelines__card-drift">+ {" · "}+ {driftCount} drift{driftCount > 1 ? "s" : ""}+ </span>+ )}+ </span>+ </div>+ </Card>+ );+}diff --git a/frontend/portal/src/components/pipelines/PipelineComposer.stories.tsx b/frontend/portal/src/components/pipelines/PipelineComposer.stories.tsxnew file mode 100644index 0000000000..34a992f0ea--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineComposer.stories.tsx@@ -0,0 +1,25 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PipelineComposer } from "@portal/components/pipelines/PipelineComposer";++const meta: Meta<typeof PipelineComposer> = {+ title: "Portal/Pipelines/PipelineComposer",+ component: PipelineComposer,+ parameters: { layout: "fullscreen" },+ args: { open: true, onClose: () => console.log("close") },+ decorators: [+ (S) => (+ <div style={{ minHeight: "100vh", background: "var(--color-bg)" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PipelineComposer>;++/** Opens on the source step; step through Operations and Routing in the footer. */+export const Open: Story = {};++export const Closed: Story = {+ args: { open: false },+};diff --git a/frontend/portal/src/components/pipelines/PipelineComposer.tsx b/frontend/portal/src/components/pipelines/PipelineComposer.tsxnew file mode 100644index 0000000000..a2934a88fd--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineComposer.tsx@@ -0,0 +1,345 @@+import { useState } from "react";+import { Button, Chip, Modal } from "@shared/components";+import {+ DESTINATION_OPTIONS,+ PIPELINE_OPS,+ PIPELINE_AGENTS,+ SOURCE_OPTIONS,+ type OpKind,+ type PipelineOp,+} from "@shared/data/ops";+import {+ OP_KIND_ACCENT,+ STAGE_COLOR_VAR,+} from "@portal/components/pipelines/stageAccent";++const COMPOSER_STEPS = ["Source", "Operations", "Routing"] as const;++const OP_KIND_LABEL: Record<OpKind, string> = {+ ingest: "Ingest",+ validate: "Validate",+ modify: "Modify",+ secure: "Secure",+ store: "Route / Store",+ alert: "Alerts",+};++/** Selectable ops in the picker — excludes pipeline-only structural ops. */+const PICKER_OPS: Record<OpKind, PipelineOp[]> = (() => {+ const out = {} as Record<OpKind, PipelineOp[]>;+ for (const kind of Object.keys(PIPELINE_OPS) as OpKind[]) {+ out[kind] = PIPELINE_OPS[kind].filter((op) => !op.pipelineOnly);+ }+ return out;+})();++function lookupPickerOp(id: string): PipelineOp | null {+ for (const kind of Object.keys(PICKER_OPS) as OpKind[]) {+ const found = PICKER_OPS[kind].find((op) => op.id === id);+ if (found) return found;+ }+ return null;+}++export interface PipelineComposerProps {+ open: boolean;+ onClose: () => void;+}++/** Three-step wizard: pick a source, compose the op chain, route the output. */+export function PipelineComposer({ open, onClose }: PipelineComposerProps) {+ const [step, setStep] = useState(0);+ const [source, setSource] = useState<string>("upload");+ const [selectedOps, setSelectedOps] = useState<string[]>([+ "extract",+ "validate",+ "redact",+ ]);+ const [destination, setDestination] = useState<string>("vault");+ const [notifyEmail, setNotifyEmail] = useState(true);+ const [notifyWebhook, setNotifyWebhook] = useState(false);+ const [reviewQueue, setReviewQueue] = useState(true);++ function reset() {+ setStep(0);+ setSource("upload");+ setSelectedOps(["extract", "validate", "redact"]);+ setDestination("vault");+ setNotifyEmail(true);+ setNotifyWebhook(false);+ setReviewQueue(true);+ }++ function close() {+ onClose();+ // Defer reset so it doesn't flash mid-close-animation.+ setTimeout(reset, 0);+ }++ function deploy() {+ // TODO(backend): POST /v1/pipelines { source, ops: selectedOps, destination, alerts }+ close();+ }++ function toggleOp(id: string) {+ setSelectedOps((prev) =>+ prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],+ );+ }++ function applyAgent(ops: string[]) {+ // A bundle lists its full op set, but structural rails (retention,+ // residency, access policy) aren't user-chainable picker ops — add only+ // ops that exist in the picker so every chain chip resolves to a label.+ const pickable = ops.filter((id) => lookupPickerOp(id) !== null);+ setSelectedOps((prev) => Array.from(new Set([...prev, ...pickable])));+ }++ const isLast = step === COMPOSER_STEPS.length - 1;+ const canAdvance = step === 1 ? selectedOps.length > 0 : true;++ return (+ <Modal+ open={open}+ onClose={close}+ width="xl"+ title="New pipeline"+ subtitle="Pick a source, compose the operation chain, then route the output."+ footer={+ <>+ <div className="portal-pipelines__composer-steps" aria-hidden>+ {COMPOSER_STEPS.map((label, i) => (+ <span+ key={label}+ className={+ "portal-pipelines__composer-step" ++ (i === step ? " is-active" : i < step ? " is-done" : "")+ }+ >+ {i + 1}. {label}+ </span>+ ))}+ </div>+ <Button variant="ghost" onClick={close}>+ Cancel+ </Button>+ {step > 0 && (+ <Button variant="outline" onClick={() => setStep((s) => s - 1)}>+ Back+ </Button>+ )}+ {isLast ? (+ <Button+ variant="gradient"+ onClick={deploy}+ trailingIcon={<span aria-hidden>→</span>}+ >+ Deploy pipeline+ </Button>+ ) : (+ <Button+ variant="gradient"+ onClick={() => setStep((s) => s + 1)}+ disabled={!canAdvance}+ trailingIcon={<span aria-hidden>→</span>}+ >+ Continue+ </Button>+ )}+ </>+ }+ >+ <div className="portal-pipelines__composer">+ {step === 0 && (+ <div className="portal-pipelines__composer-body">+ <div className="portal-pipelines__composer-grid">+ <button+ type="button"+ className={+ "portal-pipelines__option" ++ (source === "any" ? " is-selected" : "")+ }+ onClick={() => setSource("any")}+ >+ <span className="portal-pipelines__option-label">+ Any source+ </span>+ <span className="portal-pipelines__option-desc">+ Accept documents from every connected channel+ </span>+ </button>+ {SOURCE_OPTIONS.map((opt) => (+ <button+ key={opt.id}+ type="button"+ className={+ "portal-pipelines__option" ++ (source === opt.id ? " is-selected" : "")+ }+ onClick={() => setSource(opt.id)}+ >+ <span className="portal-pipelines__option-label">+ {opt.label}+ </span>+ <span className="portal-pipelines__option-desc">+ {opt.desc}+ </span>+ </button>+ ))}+ </div>+ </div>+ )}++ {step === 1 && (+ <div className="portal-pipelines__composer-body">+ <div className="portal-pipelines__chain">+ <span className="portal-pipelines__chain-label">+ Operation chain ({selectedOps.length})+ </span>+ <div className="portal-pipelines__chain-chips">+ {selectedOps.length === 0 ? (+ <span className="portal-pipelines__chain-empty">+ Add operations from the library below.+ </span>+ ) : (+ selectedOps.map((id) => {+ const op = lookupPickerOp(id);+ const accent = op ? OP_KIND_ACCENT[op.kind] : "purple";+ return (+ <Chip+ key={id}+ tone={accent}+ size="sm"+ onRemove={() => toggleOp(id)}+ >+ {op?.label ?? id}+ </Chip>+ );+ })+ )}+ </div>+ </div>++ <div className="portal-pipelines__agents">+ <span className="portal-pipelines__agents-label">+ Quick-add bundles+ </span>+ <div className="portal-pipelines__agents-row">+ {PIPELINE_AGENTS.map((agent) => (+ <Chip+ key={agent.id}+ tone="neutral"+ size="sm"+ onClick={() => applyAgent(agent.ops)}+ >+ + {agent.label}+ </Chip>+ ))}+ </div>+ </div>++ <div className="portal-pipelines__library">+ {(Object.keys(PICKER_OPS) as OpKind[]).map((kind) => (+ <div key={kind} className="portal-pipelines__library-group">+ <div className="portal-pipelines__library-head">+ <span+ className="portal-pipelines__library-pip"+ style={{+ background: STAGE_COLOR_VAR[OP_KIND_ACCENT[kind]],+ }}+ aria-hidden+ />+ {OP_KIND_LABEL[kind]}+ </div>+ <div className="portal-pipelines__library-chips">+ {PICKER_OPS[kind].map((op) => {+ const on = selectedOps.includes(op.id);+ return (+ <Chip+ key={op.id}+ tone={on ? OP_KIND_ACCENT[kind] : "neutral"}+ size="sm"+ onClick={() => toggleOp(op.id)}+ >+ {on ? "✓ " : ""}+ {op.label}+ </Chip>+ );+ })}+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {step === 2 && (+ <div className="portal-pipelines__composer-body">+ <span className="portal-pipelines__chain-label">Destination</span>+ <div className="portal-pipelines__composer-grid">+ {DESTINATION_OPTIONS.map((opt) => (+ <button+ key={opt.id}+ type="button"+ className={+ "portal-pipelines__option" ++ (destination === opt.id ? " is-selected" : "")+ }+ onClick={() => setDestination(opt.id)}+ >+ <span className="portal-pipelines__option-label">+ {opt.label}+ </span>+ <span className="portal-pipelines__option-desc">+ {opt.desc}+ </span>+ </button>+ ))}+ </div>++ <span className="portal-pipelines__chain-label">Alerts</span>+ <div className="portal-pipelines__alerts">+ <label className="portal-pipelines__alert">+ <input+ type="checkbox"+ checked={notifyEmail}+ onChange={(e) => setNotifyEmail(e.target.checked)}+ />+ <span>+ <strong>Email on failure</strong>+ <span>+ Notify the on-call list when error rate trips its bound+ </span>+ </span>+ </label>+ <label className="portal-pipelines__alert">+ <input+ type="checkbox"+ checked={notifyWebhook}+ onChange={(e) => setNotifyWebhook(e.target.checked)}+ />+ <span>+ <strong>Webhook on completion</strong>+ <span>POST a run summary to a URL you control</span>+ </span>+ </label>+ <label className="portal-pipelines__alert">+ <input+ type="checkbox"+ checked={reviewQueue}+ onChange={(e) => setReviewQueue(e.target.checked)}+ />+ <span>+ <strong>Route low-confidence to review</strong>+ <span>+ Send docs under the confidence bound to a human queue+ </span>+ </span>+ </label>+ </div>+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/frontend/portal/src/components/pipelines/PipelineDetail.stories.tsx b/frontend/portal/src/components/pipelines/PipelineDetail.stories.tsxnew file mode 100644index 0000000000..a7c6c7763e--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineDetail.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PipelineDetail } from "@portal/components/pipelines/PipelineDetail";+import {+ DEGRADED_PIPELINE,+ HEALTHY_PIPELINE,+} from "@portal/components/pipelines/storyFixtures";++const meta: Meta<typeof PipelineDetail> = {+ title: "Portal/Pipelines/PipelineDetail",+ component: PipelineDetail,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "32rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PipelineDetail>;++/** Clean golden set, no drift. */+export const Healthy: Story = {+ args: { pipeline: HEALTHY_PIPELINE },+};++/** Failing golden cases plus warning- and info-severity schema drift. */+export const DegradedWithDrift: Story = {+ args: { pipeline: DEGRADED_PIPELINE },+};diff --git a/frontend/portal/src/components/pipelines/PipelineDetail.tsx b/frontend/portal/src/components/pipelines/PipelineDetail.tsxnew file mode 100644index 0000000000..3336750ec5--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineDetail.tsx@@ -0,0 +1,146 @@+import {+ Chip,+ EmptyState,+ ProgressBar,+ StatTile,+ StatusBadge,+} from "@shared/components";+import type { Pipeline, SchemaDrift } from "@portal/api/pipelines";+import {+ STAGE_ACCENT,+ STAGE_COLOR_VAR,+} from "@portal/components/pipelines/stageAccent";+import { compact, pct } from "@portal/components/pipelines/format";++function DriftRow({ drift }: { drift: SchemaDrift }) {+ return (+ <li className="portal-pipelines__drift">+ <span+ className="portal-pipelines__drift-dot"+ style={{+ background:+ drift.severity === "warning"+ ? "var(--color-amber)"+ : "var(--color-blue)",+ }}+ aria-hidden+ />+ <div className="portal-pipelines__drift-text">+ <code className="portal-pipelines__drift-field">{drift.field}</code>+ <span className="portal-pipelines__drift-note">{drift.note}</span>+ </div>+ <div className="portal-pipelines__drift-meta">+ <span>+ {drift.confidenceDelta > 0 ? "+" : ""}+ {drift.confidenceDelta.toFixed(2)} conf+ </span>+ <span>{drift.affectedDocs} docs</span>+ </div>+ </li>+ );+}++export interface PipelineDetailProps {+ pipeline: Pipeline;+}++/** Drawer body: 24h metrics, the five stages, golden-set health, and schema drift. */+export function PipelineDetail({ pipeline }: PipelineDetailProps) {+ const m = pipeline.metrics;+ const goldenRatio = pipeline.golden.total+ ? pipeline.golden.passing / pipeline.golden.total+ : 0;+ const goldenClean = pipeline.golden.passing === pipeline.golden.total;++ return (+ <div className="portal-pipelines__detail">+ <section className="portal-pipelines__detail-metrics">+ <StatTile label="Docs / 24h" value={compact(m.docs24h)} />+ <StatTile label="Throughput" value={`${m.throughputPerMin}/min`} />+ <StatTile label="Error rate" value={pct(m.errorRate, 2)} />+ <StatTile label="P95 latency" value={`${m.p95LatencyMs} ms`} />+ <StatTile label="Uptime" value={pct(m.uptime, 2)} />+ </section>++ <section className="portal-pipelines__detail-section">+ <h3 className="portal-pipelines__detail-h">Pipeline stages</h3>+ <p className="portal-pipelines__detail-sub">+ Every document flows through five stages between {pipeline.source} and{" "}+ {pipeline.destination}.+ </p>+ <div className="portal-pipelines__stages">+ {pipeline.stages.map((stage) => {+ const accent = STAGE_ACCENT[stage.key];+ return (+ <div key={stage.key} className="portal-pipelines__stage">+ <div className="portal-pipelines__stage-head">+ <span+ className="portal-pipelines__stage-pip"+ style={{ background: STAGE_COLOR_VAR[accent] }}+ aria-hidden+ />+ <span className="portal-pipelines__stage-name">+ {stage.label}+ </span>+ </div>+ <div className="portal-pipelines__stage-chips">+ {stage.ops.length === 0 ? (+ <span className="portal-pipelines__stage-empty">+ No ops+ </span>+ ) : (+ stage.ops.map((op) => (+ <Chip key={op} tone={accent} size="sm">+ {op}+ </Chip>+ ))+ )}+ </div>+ </div>+ );+ })}+ </div>+ </section>++ <section className="portal-pipelines__detail-section">+ <h3 className="portal-pipelines__detail-h">Golden-set validation</h3>+ <div className="portal-pipelines__golden">+ <div className="portal-pipelines__golden-head">+ <StatusBadge tone={goldenClean ? "success" : "warning"} size="sm">+ {pipeline.golden.passing} of {pipeline.golden.total} passing+ </StatusBadge>+ <span className="portal-pipelines__golden-when">+ last run {pipeline.golden.lastRun}+ </span>+ </div>+ <ProgressBar+ value={goldenRatio}+ color={+ goldenClean+ ? "var(--color-green)"+ : "linear-gradient(90deg, var(--color-amber), color-mix(in srgb, var(--color-amber) 70%, white))"+ }+ label={`Golden set ${pipeline.golden.passing} of ${pipeline.golden.total} passing`}+ />+ </div>+ </section>++ <section className="portal-pipelines__detail-section">+ <h3 className="portal-pipelines__detail-h">Schema drift</h3>+ {pipeline.drift.length === 0 ? (+ <EmptyState+ size="compact"+ title="No drift detected"+ description="Every document in the last 24h matched its inferred schema."+ />+ ) : (+ <ul className="portal-pipelines__drift-list">+ {pipeline.drift.map((d) => (+ <DriftRow key={d.field} drift={d} />+ ))}+ </ul>+ )}+ </section>+ </div>+ );+}diff --git a/frontend/portal/src/components/pipelines/PipelineListSkeleton.stories.tsx b/frontend/portal/src/components/pipelines/PipelineListSkeleton.stories.tsxnew file mode 100644index 0000000000..ae16b352f7--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineListSkeleton.stories.tsx@@ -0,0 +1,19 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PipelineListSkeleton } from "@portal/components/pipelines/PipelineListSkeleton";++const meta: Meta<typeof PipelineListSkeleton> = {+ title: "Portal/Pipelines/PipelineListSkeleton",+ component: PipelineListSkeleton,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "52rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PipelineListSkeleton>;++export const Default: Story = {};diff --git a/frontend/portal/src/components/pipelines/PipelineListSkeleton.tsx b/frontend/portal/src/components/pipelines/PipelineListSkeleton.tsxnew file mode 100644index 0000000000..8900ff6990--- /dev/null+++ b/frontend/portal/src/components/pipelines/PipelineListSkeleton.tsx@@ -0,0 +1,19 @@+import { Card, Skeleton } from "@shared/components";++/** Placeholder fleet while the deployed pipelines load. */+export function PipelineListSkeleton() {+ return (+ <div className="portal-pipelines__list" aria-hidden>+ {Array.from({ length: 3 }).map((_, i) => (+ <Card key={i} padding="loose" className="portal-pipelines__card">+ <div className="portal-pipelines__card-head">+ <Skeleton width="11rem" height="1.1rem" />+ <Skeleton width="5rem" height="1.1rem" />+ </div>+ <Skeleton width="80%" height="0.75rem" />+ <Skeleton height="3rem" />+ </Card>+ ))}+ </div>+ );+}diff --git a/frontend/portal/src/components/pipelines/format.ts b/frontend/portal/src/components/pipelines/format.tsnew file mode 100644index 0000000000..ac38f33ec3--- /dev/null+++ b/frontend/portal/src/components/pipelines/format.ts@@ -0,0 +1,9 @@+/** Fraction → percentage string (0.004 → "0.40%"). */+export const pct = (n: number, digits = 1) => `${(n * 100).toFixed(digits)}%`;++/** Compact count for dense metric tiles (28941 → "28.9K"). */+export const compact = (n: number) =>+ new Intl.NumberFormat(undefined, {+ notation: "compact",+ maximumFractionDigits: 1,+ }).format(n);diff --git a/frontend/portal/src/components/pipelines/stageAccent.ts b/frontend/portal/src/components/pipelines/stageAccent.tsnew file mode 100644index 0000000000..ee668a7af6--- /dev/null+++ b/frontend/portal/src/components/pipelines/stageAccent.ts@@ -0,0 +1,35 @@+import type { StageKey } from "@portal/api/pipelines";+import type { OpKind } from "@shared/data/ops";++/**+ * Fixed accent per stage so the chip row reads the same across every pipeline.+ * Each value is also a valid {@link import("@shared/components").ChipTone}, so+ * it doubles as the chip tone wherever a stage colour is rendered.+ */+export type StageAccent = "green" | "blue" | "amber" | "red" | "purple";++export const STAGE_ACCENT: Record<StageKey, StageAccent> = {+ ingest: "green",+ validate: "blue",+ modify: "amber",+ secure: "red",+ route: "purple",+};++/** Op-kind accent mirrors the stage palette; alerts share the route colour. */+export const OP_KIND_ACCENT: Record<OpKind, StageAccent> = {+ ingest: "green",+ validate: "blue",+ modify: "amber",+ secure: "red",+ store: "purple",+ alert: "purple",+};++export const STAGE_COLOR_VAR: Record<StageAccent, string> = {+ green: "var(--color-green)",+ blue: "var(--color-blue)",+ amber: "var(--color-amber)",+ red: "var(--color-red)",+ purple: "var(--color-purple)",+};diff --git a/frontend/portal/src/components/pipelines/storyFixtures.ts b/frontend/portal/src/components/pipelines/storyFixtures.tsnew file mode 100644index 0000000000..39458ce4d8--- /dev/null+++ b/frontend/portal/src/components/pipelines/storyFixtures.ts@@ -0,0 +1,74 @@+import type { Pipeline } from "@portal/api/pipelines";++/** Sample pipelines shared by the Pipelines component stories. */++export const HEALTHY_PIPELINE: Pipeline = {+ id: "pl-invoice-ap",+ name: "Invoice → AP",+ blurb: "Invoice extraction → three-way match → Postgres",+ status: "healthy",+ source: "S3 bucket watch",+ destination: "Database",+ version: "v2.8.0",+ regions: ["us-east-1", "eu-west-1", "ap-southeast-1"],+ metrics: {+ docs24h: 53120,+ throughputPerMin: 41,+ errorRate: 0.006,+ p95LatencyMs: 358,+ uptime: 0.9997,+ },+ stages: [+ { key: "ingest", label: "Ingest", ops: ["Parse", "Classify", "Extract"] },+ {+ key: "validate",+ label: "Validate",+ ops: ["Schema validate", "Confidence bounds"],+ },+ { key: "modify", label: "Modify", ops: ["PDF → CSV"] },+ {+ key: "secure",+ label: "Secure",+ ops: ["Redact PII", "Encryption at rest"],+ },+ { key: "route", label: "Route / Store", ops: ["Primary store", "Notify"] },+ ],+ golden: { passing: 42, total: 42, lastRun: "1h ago" },+ drift: [],+};++export const DEGRADED_PIPELINE: Pipeline = {+ ...HEALTHY_PIPELINE,+ id: "pl-prior-auth",+ name: "Prior Auth Router",+ blurb: "Prior-authorization intake → medical-necessity gate → payer webhook",+ status: "degraded",+ source: "Inbound webhook",+ destination: "Outbound webhook",+ version: "v3.1.0",+ regions: ["us-east-1"],+ metrics: {+ docs24h: 11204,+ throughputPerMin: 9,+ errorRate: 0.031,+ p95LatencyMs: 740,+ uptime: 0.9962,+ },+ golden: { passing: 24, total: 28, lastRun: "47m ago" },+ drift: [+ {+ field: "procedure_codes",+ note: "New CPT modifier suffix not seen in prior examples",+ confidenceDelta: -0.07,+ severity: "warning",+ affectedDocs: 18,+ },+ {+ field: "payer",+ note: "Two payers now emit a merged-entity name",+ confidenceDelta: -0.03,+ severity: "info",+ affectedDocs: 6,+ },+ ],+};diff --git a/frontend/portal/src/components/sources/AgentPanel.stories.tsx b/frontend/portal/src/components/sources/AgentPanel.stories.tsxnew file mode 100644index 0000000000..5289d0c623--- /dev/null+++ b/frontend/portal/src/components/sources/AgentPanel.stories.tsx@@ -0,0 +1,44 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { AgentDetail } from "@portal/api/sources";+import { AgentPanel } from "@portal/components/sources/AgentPanel";++const meta: Meta<typeof AgentPanel> = {+ title: "Portal/Sources/AgentPanel",+ component: AgentPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "48rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof AgentPanel>;++const healthy: AgentDetail = {+ kind: "agent",+ model: "claude-sonnet-4.5",+ calls24h: 1342,+ errorRate: 0.004,+ confidence: 0.962,+ escalations24h: 11,+ assignedPipelines: ["Invoice v3", "AP Routing"],+ scopes: ["documents:read", "pipelines:invoke", "extract:write"],+};++export const Healthy: Story = { args: { d: healthy } };++/** Error rate over the 5% alarm threshold flips the badge and bar to danger/amber. */+export const Degraded: Story = {+ args: {+ d: {+ ...healthy,+ model: "claude-opus-4.1",+ errorRate: 0.071,+ confidence: 0.883,+ escalations24h: 34,+ },+ },+};diff --git a/frontend/portal/src/components/sources/AgentPanel.tsx b/frontend/portal/src/components/sources/AgentPanel.tsxnew file mode 100644index 0000000000..3c33927886--- /dev/null+++ b/frontend/portal/src/components/sources/AgentPanel.tsx@@ -0,0 +1,85 @@+import {+ Button,+ Chip,+ ProgressBar,+ StatTile,+ StatusBadge,+} from "@shared/components";+import type { AgentDetail } from "@portal/api/sources";+import { pct } from "@portal/components/sources/format";+import "@portal/views/Sources.css";++export function AgentPanel({ d }: { d: AgentDetail }) {+ const errorTone =+ d.errorRate >= 0.05+ ? "danger"+ : d.errorRate >= 0.02+ ? "warning"+ : "success";+ return (+ <div className="portal-sources__detail">+ <div className="portal-sources__stat-grid">+ <StatTile label="Model" value={<code>{d.model}</code>} />+ <StatTile label="Calls / 24h" value={d.calls24h.toLocaleString()} />+ <StatTile+ label="Error rate"+ value={+ <StatusBadge tone={errorTone} size="sm">+ {pct(d.errorRate)}+ </StatusBadge>+ }+ />+ <StatTile label="Escalations / 24h" value={d.escalations24h} />+ </div>++ <div className="portal-sources__bar-row">+ <div className="portal-sources__bar-head">+ <span>Mean confidence</span>+ <strong>{pct(d.confidence)}</strong>+ </div>+ <ProgressBar+ value={d.confidence}+ color={+ d.confidence >= 0.93 ? "var(--color-green)" : "var(--color-amber)"+ }+ label="Mean output confidence"+ />+ </div>++ <div className="portal-sources__detail-section">+ <span className="portal-sources__detail-heading">+ Assigned pipelines+ </span>+ <div className="portal-sources__chips">+ {d.assignedPipelines.map((p) => (+ <Chip key={p} tone="blue" size="sm">+ {p}+ </Chip>+ ))}+ </div>+ </div>++ <div className="portal-sources__detail-section">+ <span className="portal-sources__detail-heading">Scopes</span>+ <div className="portal-sources__chips">+ {d.scopes.map((s) => (+ <Chip key={s} tone="neutral" size="sm">+ {s}+ </Chip>+ ))}+ </div>+ </div>++ {/* TODO(backend): wire to GET /v1/sources/{id}/eval-runs and+ POST /v1/sources/{id}/pause — currently inert demo controls. */}+ <div className="portal-sources__detail-actions">+ <Button size="sm" variant="outline">+ View eval runs+ </Button>+ <Button size="sm" variant="ghost">+ Pause agent+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/sources/ApiClientPanel.stories.tsx b/frontend/portal/src/components/sources/ApiClientPanel.stories.tsxnew file mode 100644index 0000000000..7c67e90784--- /dev/null+++ b/frontend/portal/src/components/sources/ApiClientPanel.stories.tsx@@ -0,0 +1,52 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { ApiClientDetail } from "@portal/api/sources";+import { ApiClientPanel } from "@portal/components/sources/ApiClientPanel";++const meta: Meta<typeof ApiClientPanel> = {+ title: "Portal/Sources/ApiClientPanel",+ component: ApiClientPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "48rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof ApiClientPanel>;++const active: ApiClientDetail = {+ kind: "apiclient",+ maskedKey: "sk_live_••••••••••••4f9a",+ rateLimit: "600 req/min",+ rateUsedPct: 0.42,+ endpoints: [+ { method: "POST", path: "/v1/extract", calls24h: 1820 },+ { method: "POST", path: "/v1/redact", calls24h: 740 },+ { method: "GET", path: "/v1/documents/{id}", calls24h: 380 },+ ],+ createdBy: "[email protected]",+ lastRotated: "23 days ago",+};++export const Active: Story = { args: { d: active } };++/** Rate window near its ceiling pushes the thresholded bar into the warning band. */+export const NearLimit: Story = {+ args: { d: { ...active, rateUsedPct: 0.93 } },+};++/** A revoked key: never rotated, no traffic, masked label flags the state. */+export const Revoked: Story = {+ args: {+ d: {+ ...active,+ maskedKey: "sk_live_••••••••••••0000 (revoked)",+ rateUsedPct: 0,+ lastRotated: "never",+ endpoints: active.endpoints.map((e) => ({ ...e, calls24h: 0 })),+ },+ },+};diff --git a/frontend/portal/src/components/sources/ApiClientPanel.tsx b/frontend/portal/src/components/sources/ApiClientPanel.tsxnew file mode 100644index 0000000000..2a2a52caac--- /dev/null+++ b/frontend/portal/src/components/sources/ApiClientPanel.tsx@@ -0,0 +1,61 @@+import { Button, Chip, ProgressBar, StatTile } from "@shared/components";+import type { ApiClientDetail } from "@portal/api/sources";+import { pct } from "@portal/components/sources/format";+import "@portal/views/Sources.css";++export function ApiClientPanel({ d }: { d: ApiClientDetail }) {+ return (+ <div className="portal-sources__detail">+ <div className="portal-sources__stat-grid">+ <StatTile label="Secret key" value={<code>{d.maskedKey}</code>} />+ <StatTile label="Rate limit" value={d.rateLimit} />+ <StatTile label="Created by" value={d.createdBy} />+ <StatTile label="Last rotated" value={d.lastRotated} />+ </div>++ <div className="portal-sources__bar-row">+ <div className="portal-sources__bar-head">+ <span>Rate-limit window</span>+ <strong>{pct(d.rateUsedPct)} used</strong>+ </div>+ <ProgressBar+ value={d.rateUsedPct}+ thresholded+ label="Rate-limit usage"+ />+ </div>++ <div className="portal-sources__detail-section">+ <span className="portal-sources__detail-heading">Top endpoints</span>+ <div className="portal-sources__endpoints">+ {d.endpoints.map((e) => (+ <div key={e.path} className="portal-sources__endpoint">+ <Chip+ tone={e.method === "GET" ? "green" : "blue"}+ size="sm"+ className="portal-sources__method"+ >+ {e.method}+ </Chip>+ <code className="portal-sources__endpoint-path">{e.path}</code>+ <span className="portal-sources__endpoint-calls">+ {e.calls24h.toLocaleString()} / 24h+ </span>+ </div>+ ))}+ </div>+ </div>++ {/* TODO(backend): wire to POST /v1/sources/{id}/rotate-key and+ DELETE /v1/sources/{id} — currently inert demo controls. */}+ <div className="portal-sources__detail-actions">+ <Button size="sm" variant="outline" accent="amber">+ Rotate key+ </Button>+ <Button size="sm" variant="ghost" accent="red">+ Revoke+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/sources/ConnectWizard.stories.tsx b/frontend/portal/src/components/sources/ConnectWizard.stories.tsxnew file mode 100644index 0000000000..a78fb0ef15--- /dev/null+++ b/frontend/portal/src/components/sources/ConnectWizard.stories.tsx@@ -0,0 +1,16 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { ConnectWizard } from "@portal/components/sources/ConnectWizard";++const meta: Meta<typeof ConnectWizard> = {+ title: "Portal/Sources/ConnectWizard",+ component: ConnectWizard,+ parameters: { layout: "fullscreen" },+ args: { open: true, onClose: () => {} },+};+export default meta;+type Story = StoryObj<typeof ConnectWizard>;++/** Opens on the type-picker step; Continue/Back walk through the three steps. */+export const Open: Story = {};++export const Closed: Story = { args: { open: false } };diff --git a/frontend/portal/src/components/sources/ConnectWizard.tsx b/frontend/portal/src/components/sources/ConnectWizard.tsxnew file mode 100644index 0000000000..1c6471cc83--- /dev/null+++ b/frontend/portal/src/components/sources/ConnectWizard.tsx@@ -0,0 +1,146 @@+import { useState } from "react";+import { Button, CodeBlock, Modal, StatTile } from "@shared/components";+import { type Source, SOURCE_TYPE_META } from "@portal/api/sources";+import "@portal/views/Sources.css";++const WIZARD_STEPS = ["Choose type", "Configure", "Review & connect"] as const;++const CONNECT_SNIPPET = `curl https://api.stirlingpdf.com/v1/extract \\+ -H "Authorization: Bearer sk_live_••••" \\+ -F "[email protected]" \\+ -F "pipeline=invoice-v3"`;++interface ConnectWizardProps {+ open: boolean;+ onClose: () => void;+}++/**+ * Guided shell for connecting a new source. The final step is a demo stub that+ * closes without provisioning — wiring it to the backend creates the source.+ */+export function ConnectWizard({ open, onClose }: ConnectWizardProps) {+ const [step, setStep] = useState(0);+ const [type, setType] = useState<Source["type"]>("agent");++ function close() {+ onClose();+ // Reset for the next open, after the close transition has finished.+ setTimeout(() => {+ setStep(0);+ setType("agent");+ }, 200);+ }++ const isLast = step === WIZARD_STEPS.length - 1;++ function advance() {+ if (isLast) {+ // TODO(backend): POST /v1/sources { type, pipeline, region } — provision+ // the source, then close on success.+ close();+ } else {+ setStep((s) => s + 1);+ }+ }++ return (+ <Modal+ open={open}+ onClose={close}+ width="lg"+ title="Connect a source"+ subtitle={`Step ${step + 1} of ${WIZARD_STEPS.length} · ${WIZARD_STEPS[step]}`}+ footer={+ <div className="portal-sources__wizard-footer">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => (step === 0 ? close() : setStep((s) => s - 1))}+ >+ {step === 0 ? "Cancel" : "Back"}+ </Button>+ <Button+ size="sm"+ onClick={advance}+ trailingIcon={!isLast ? <span aria-hidden>→</span> : undefined}+ >+ {isLast ? "Connect source" : "Continue"}+ </Button>+ </div>+ }+ >+ <ol className="portal-sources__steps" aria-hidden>+ {WIZARD_STEPS.map((label, i) => (+ <li+ key={label}+ className={+ "portal-sources__step" ++ (i === step ? " is-active" : i < step ? " is-done" : "")+ }+ >+ <span className="portal-sources__step-mark">+ {i < step ? "✓" : i + 1}+ </span>+ {label}+ </li>+ ))}+ </ol>++ {step === 0 && (+ <div className="portal-sources__type-grid">+ {(Object.keys(SOURCE_TYPE_META) as Source["type"][]).map((t) => {+ const meta = SOURCE_TYPE_META[t];+ return (+ <button+ key={t}+ type="button"+ className={+ "portal-sources__type-card" ++ (type === t ? " is-selected" : "")+ }+ onClick={() => setType(t)}+ >+ <span className="portal-sources__type-icon" aria-hidden>+ {meta.icon}+ </span>+ <span className="portal-sources__type-name">{meta.label}</span>+ </button>+ );+ })}+ </div>+ )}++ {step === 1 && (+ <div className="portal-sources__wizard-body">+ <p className="portal-sources__wizard-lead">+ Configure your <strong>{SOURCE_TYPE_META[type].label}</strong>.+ Point it at Stirling and attach a default pipeline — every document+ this source ingests runs through it automatically.+ </p>+ <CodeBlock code={CONNECT_SNIPPET} caption="quickstart.sh" />+ <p className="portal-sources__wizard-note">+ Scopes, rate limits and IP allowlists can be tuned after the source+ is connected.+ </p>+ </div>+ )}++ {step === 2 && (+ <div className="portal-sources__wizard-body">+ <p className="portal-sources__wizard-lead">+ Ready to connect a new{" "}+ <strong>{SOURCE_TYPE_META[type].label}</strong>. It starts paused so+ you can verify the first few documents before going live.+ </p>+ <div className="portal-sources__stat-grid">+ <StatTile label="Type" value={SOURCE_TYPE_META[type].label} />+ <StatTile label="Default pipeline" value="Redact & Flatten" />+ <StatTile label="Initial state" value="Paused" />+ <StatTile label="Region" value="us-east-1" />+ </div>+ </div>+ )}+ </Modal>+ );+}diff --git a/frontend/portal/src/components/sources/KpiStrip.stories.tsx b/frontend/portal/src/components/sources/KpiStrip.stories.tsxnew file mode 100644index 0000000000..36c290b50b--- /dev/null+++ b/frontend/portal/src/components/sources/KpiStrip.stories.tsx@@ -0,0 +1,29 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { buildSourcesResponse } from "@portal/mocks/sources";+import { KpiStrip } from "@portal/components/sources/KpiStrip";++const meta: Meta<typeof KpiStrip> = {+ title: "Portal/Sources/KpiStrip",+ component: KpiStrip,+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof KpiStrip>;++export const Pro: Story = {+ args: { data: buildSourcesResponse("pro"), loading: false },+};++export const Enterprise: Story = {+ args: { data: buildSourcesResponse("enterprise"), loading: false },+};++/** Loading collapses every card to the placeholder dash. */+export const Loading: Story = {+ args: { data: null, loading: true },+};++/** Free tier reports zeros and a "connect a source" prompt. */+export const Free: Story = {+ args: { data: buildSourcesResponse("free"), loading: false },+};diff --git a/frontend/portal/src/components/sources/KpiStrip.tsx b/frontend/portal/src/components/sources/KpiStrip.tsxnew file mode 100644index 0000000000..de319d05ac--- /dev/null+++ b/frontend/portal/src/components/sources/KpiStrip.tsx@@ -0,0 +1,39 @@+import { MetricCard, MetricStrip } from "@shared/components";+import type { SourcesResponse } from "@portal/api/sources";++/**+ * KPI labels are product copy — they describe what each metric IS, not its+ * current value. They stay client-side so the strip's structure is stable+ * across loading / empty / ready states; only values + deltas flow from the API.+ */+const KPI_LABELS = [+ "Agents active",+ "Scenarios",+ "Eval pass rate (7d)",+ "Docs / 24h",+] as const;++interface KpiStripProps {+ data: SourcesResponse | null;+ loading: boolean;+}++export function KpiStrip({ data, loading }: KpiStripProps) {+ return (+ <MetricStrip>+ {KPI_LABELS.map((label, i) => {+ const k = loading ? undefined : data?.kpis[i];+ return (+ <MetricCard+ key={label}+ label={label}+ value={k?.value ?? "—"}+ delta={k?.delta}+ deltaDirection={k?.deltaDirection}+ description={k?.description}+ />+ );+ })}+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/sources/SourceDetailCard.stories.tsx b/frontend/portal/src/components/sources/SourceDetailCard.stories.tsxnew file mode 100644index 0000000000..83f5171ecc--- /dev/null+++ b/frontend/portal/src/components/sources/SourceDetailCard.stories.tsx@@ -0,0 +1,28 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { Source } from "@portal/api/sources";+import { sourcesFor } from "@portal/mocks/sources";+import { SourceDetailCard } from "@portal/components/sources/SourceDetailCard";++const ENTERPRISE = sourcesFor("enterprise");+const byType = (type: Source["type"]) =>+ ENTERPRISE.find((s) => s.type === type)!;++const meta: Meta<typeof SourceDetailCard> = {+ title: "Portal/Sources/SourceDetailCard",+ component: SourceDetailCard,+ parameters: { layout: "padded" },+ args: { onClose: () => {} },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "56rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof SourceDetailCard>;++export const Agent: Story = { args: { source: byType("agent") } };+export const Webhook: Story = { args: { source: byType("webhook") } };+export const Connector: Story = { args: { source: byType("connector") } };diff --git a/frontend/portal/src/components/sources/SourceDetailCard.tsx b/frontend/portal/src/components/sources/SourceDetailCard.tsxnew file mode 100644index 0000000000..d7f8b70e99--- /dev/null+++ b/frontend/portal/src/components/sources/SourceDetailCard.tsx@@ -0,0 +1,40 @@+import { type Source, SOURCE_TYPE_META } from "@portal/api/sources";+import { SourceDetailPanel } from "@portal/components/sources/SourceDetailPanel";+import "@portal/views/Sources.css";++interface SourceDetailCardProps {+ source: Source;+ onClose: () => void;+}++/** Expanded type-specific detail for the selected table row. */+export function SourceDetailCard({ source, onClose }: SourceDetailCardProps) {+ const meta = SOURCE_TYPE_META[source.type];+ return (+ <section className="portal-sources__expanded">+ <header className="portal-sources__expanded-head">+ <span+ className={`portal-sources__type-dot portal-sources__type-dot--${meta.tone}`}+ aria-hidden+ >+ {meta.icon}+ </span>+ <div>+ <h2 className="portal-sources__expanded-title">{source.name}</h2>+ <span className="portal-sources__expanded-sub">+ {meta.label} · owned by {source.owner}+ </span>+ </div>+ <button+ type="button"+ className="portal-sources__expanded-close"+ onClick={onClose}+ aria-label="Close detail"+ >+ ×+ </button>+ </header>+ <SourceDetailPanel source={source} />+ </section>+ );+}diff --git a/frontend/portal/src/components/sources/SourceDetailPanel.stories.tsx b/frontend/portal/src/components/sources/SourceDetailPanel.stories.tsxnew file mode 100644index 0000000000..2581771ea3--- /dev/null+++ b/frontend/portal/src/components/sources/SourceDetailPanel.stories.tsx@@ -0,0 +1,29 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { Source } from "@portal/api/sources";+import { sourcesFor } from "@portal/mocks/sources";+import { SourceDetailPanel } from "@portal/components/sources/SourceDetailPanel";++const ENTERPRISE = sourcesFor("enterprise");+const byType = (type: Source["type"]) =>+ ENTERPRISE.find((s) => s.type === type)!;++const meta: Meta<typeof SourceDetailPanel> = {+ title: "Portal/Sources/SourceDetailPanel",+ component: SourceDetailPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "48rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof SourceDetailPanel>;++export const Agent: Story = { args: { source: byType("agent") } };+export const ApiClient: Story = { args: { source: byType("apiclient") } };+export const Webhook: Story = { args: { source: byType("webhook") } };+/** "basic" covers editor, connector, email, desktop and batch sources. */+export const Basic: Story = { args: { source: byType("connector") } };diff --git a/frontend/portal/src/components/sources/SourceDetailPanel.tsx b/frontend/portal/src/components/sources/SourceDetailPanel.tsxnew file mode 100644index 0000000000..1938eb609b--- /dev/null+++ b/frontend/portal/src/components/sources/SourceDetailPanel.tsx@@ -0,0 +1,34 @@+import { StatTile } from "@shared/components";+import type { BasicDetail, Source } from "@portal/api/sources";+import { AgentPanel } from "@portal/components/sources/AgentPanel";+import { ApiClientPanel } from "@portal/components/sources/ApiClientPanel";+import { WebhookPanel } from "@portal/components/sources/WebhookPanel";+import "@portal/views/Sources.css";++/** Generic key/value grid for the simpler source types (editor, connector, …). */+function BasicPanel({ rows }: { rows: BasicDetail["rows"] }) {+ return (+ <div className="portal-sources__detail">+ <div className="portal-sources__stat-grid">+ {rows.map((r) => (+ <StatTile key={r.label} label={r.label} value={r.value} />+ ))}+ </div>+ </div>+ );+}++/** Renders the detail payload for a source, dispatched on its discriminant. */+export function SourceDetailPanel({ source }: { source: Source }) {+ const { detail } = source;+ switch (detail.kind) {+ case "agent":+ return <AgentPanel d={detail} />;+ case "apiclient":+ return <ApiClientPanel d={detail} />;+ case "webhook":+ return <WebhookPanel d={detail} />;+ case "basic":+ return <BasicPanel rows={detail.rows} />;+ }+}diff --git a/frontend/portal/src/components/sources/SourcesTable.stories.tsx b/frontend/portal/src/components/sources/SourcesTable.stories.tsxnew file mode 100644index 0000000000..7d7ea6fdc8--- /dev/null+++ b/frontend/portal/src/components/sources/SourcesTable.stories.tsx@@ -0,0 +1,25 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { sourcesFor } from "@portal/mocks/sources";+import { SourcesTable } from "@portal/components/sources/SourcesTable";++const PRO = sourcesFor("pro");++const meta: Meta<typeof SourcesTable> = {+ title: "Portal/Sources/SourcesTable",+ component: SourcesTable,+ parameters: { layout: "padded" },+ args: { sources: PRO, expandedId: null, onRowClick: () => {} },+};+export default meta;+type Story = StoryObj<typeof SourcesTable>;++export const Default: Story = {};++/** A row with an open detail panel rotates its caret. */+export const RowExpanded: Story = {+ args: { expandedId: PRO[1].id },+};++export const Enterprise: Story = {+ args: { sources: sourcesFor("enterprise") },+};diff --git a/frontend/portal/src/components/sources/SourcesTable.tsx b/frontend/portal/src/components/sources/SourcesTable.tsxnew file mode 100644index 0000000000..97eb687d1e--- /dev/null+++ b/frontend/portal/src/components/sources/SourcesTable.tsx@@ -0,0 +1,113 @@+import { useMemo } from "react";+import { Chip, StatusBadge, Table, type TableColumn } from "@shared/components";+import {+ type Source,+ SOURCE_STATUS_TONE,+ SOURCE_TYPE_META,+} from "@portal/api/sources";+import "@portal/views/Sources.css";++interface SourcesTableProps {+ sources: Source[];+ /** Id of the row whose detail panel is open, drives the caret state. */+ expandedId: string | null;+ onRowClick: (source: Source) => void;+}++export function SourcesTable({+ sources,+ expandedId,+ onRowClick,+}: SourcesTableProps) {+ const columns = useMemo<TableColumn<Source>[]>(+ () => [+ {+ key: "name",+ header: "Source",+ render: (s) => {+ const meta = SOURCE_TYPE_META[s.type];+ return (+ <div className="portal-sources__name-cell">+ <span+ className={`portal-sources__type-dot portal-sources__type-dot--${meta.tone}`}+ aria-hidden+ >+ {meta.icon}+ </span>+ <div className="portal-sources__name-text">+ <strong>{s.name}</strong>+ <Chip tone={meta.tone} size="sm">+ {meta.label}+ </Chip>+ </div>+ </div>+ );+ },+ },+ {+ key: "status",+ header: "Status",+ render: (s) => (+ <StatusBadge+ tone={SOURCE_STATUS_TONE[s.status]}+ size="sm"+ pulse={s.status === "active"}+ >+ {s.status}+ </StatusBadge>+ ),+ },+ {+ key: "docs24h",+ header: "Docs / 24h",+ align: "right",+ render: (s) => s.docs24h.toLocaleString(),+ },+ {+ key: "docs30d",+ header: "Docs / 30d",+ align: "right",+ render: (s) => s.docs30d.toLocaleString(),+ },+ {+ key: "lastEvent",+ header: "Last event",+ render: (s) => (+ <span className="portal-sources__muted">{s.lastEvent}</span>+ ),+ },+ {+ key: "owner",+ header: "Owner",+ render: (s) => <span className="portal-sources__muted">{s.owner}</span>,+ },+ {+ key: "expand",+ header: "",+ align: "right",+ width: "2.5rem",+ render: (s) => (+ <span+ className={+ "portal-sources__caret" + (expandedId === s.id ? " is-open" : "")+ }+ aria-hidden+ >+ ▸+ </span>+ ),+ },+ ],+ [expandedId],+ );++ return (+ <Table<Source>+ className="portal-sources__table"+ columns={columns}+ rows={sources}+ rowKey={(s) => s.id}+ onRowClick={onRowClick}+ />+ );+}diff --git a/frontend/portal/src/components/sources/WebhookPanel.stories.tsx b/frontend/portal/src/components/sources/WebhookPanel.stories.tsxnew file mode 100644index 0000000000..673fc08a92--- /dev/null+++ b/frontend/portal/src/components/sources/WebhookPanel.stories.tsx@@ -0,0 +1,51 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import type { WebhookDetail } from "@portal/api/sources";+import { WebhookPanel } from "@portal/components/sources/WebhookPanel";++const meta: Meta<typeof WebhookPanel> = {+ title: "Portal/Sources/WebhookPanel",+ component: WebhookPanel,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "48rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof WebhookPanel>;++const healthy: WebhookDetail = {+ kind: "webhook",+ url: "https://hooks.acme.com/stirling/ingest",+ authType: "HMAC-SHA256",+ successRate: 0.991,+ retries24h: 3,+ recentDeliveries: [+ { event: "document.processed", status: 200, time: "9m ago" },+ { event: "pipeline.completed", status: 200, time: "22m ago" },+ { event: "document.processed", status: 503, time: "1h ago" },+ ],+};++export const Healthy: Story = { args: { d: healthy } };++/** Below the 95% floor: success badge goes danger, retries spike, 5xx deliveries. */+export const Failing: Story = {+ args: {+ d: {+ ...healthy,+ url: "https://erp.acme.com/inbound/stirling",+ authType: "Basic",+ successRate: 0.72,+ retries24h: 58,+ recentDeliveries: [+ { event: "document.processed", status: 502, time: "2m ago" },+ { event: "document.processed", status: 502, time: "5m ago" },+ { event: "pipeline.completed", status: 200, time: "9m ago" },+ ],+ },+ },+};diff --git a/frontend/portal/src/components/sources/WebhookPanel.tsx b/frontend/portal/src/components/sources/WebhookPanel.tsxnew file mode 100644index 0000000000..7dc6e0987f--- /dev/null+++ b/frontend/portal/src/components/sources/WebhookPanel.tsx@@ -0,0 +1,65 @@+import { Button, StatTile, StatusBadge } from "@shared/components";+import type { WebhookDetail } from "@portal/api/sources";+import { pct } from "@portal/components/sources/format";+import "@portal/views/Sources.css";++export function WebhookPanel({ d }: { d: WebhookDetail }) {+ const rateTone =+ d.successRate >= 0.99+ ? "success"+ : d.successRate >= 0.95+ ? "warning"+ : "danger";+ return (+ <div className="portal-sources__detail">+ <div className="portal-sources__stat-grid">+ <StatTile+ label="Endpoint URL"+ value={<code className="portal-sources__url">{d.url}</code>}+ />+ <StatTile label="Auth type" value={d.authType} />+ <StatTile+ label="Success rate"+ value={+ <StatusBadge tone={rateTone} size="sm">+ {pct(d.successRate)}+ </StatusBadge>+ }+ />+ <StatTile label="Retries / 24h" value={d.retries24h} />+ </div>++ <div className="portal-sources__detail-section">+ <span className="portal-sources__detail-heading">+ Recent deliveries+ </span>+ <div className="portal-sources__endpoints">+ {d.recentDeliveries.map((r, i) => (+ <div key={i} className="portal-sources__endpoint">+ <StatusBadge+ tone={r.status < 300 ? "success" : "danger"}+ size="sm"+ showDot={false}+ >+ {r.status}+ </StatusBadge>+ <code className="portal-sources__endpoint-path">{r.event}</code>+ <span className="portal-sources__endpoint-calls">{r.time}</span>+ </div>+ ))}+ </div>+ </div>++ {/* TODO(backend): wire to POST /v1/sources/{id}/test-event and+ GET /v1/sources/{id}/signing-secret — currently inert demo controls. */}+ <div className="portal-sources__detail-actions">+ <Button size="sm" variant="outline">+ Send test event+ </Button>+ <Button size="sm" variant="ghost">+ View signing secret+ </Button>+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/components/sources/format.ts b/frontend/portal/src/components/sources/format.tsnew file mode 100644index 0000000000..5ddbaaaaff--- /dev/null+++ b/frontend/portal/src/components/sources/format.ts@@ -0,0 +1,4 @@+/** Format a 0..1 ratio as a one-decimal percentage, e.g. 0.962 → "96.2%". */+export function pct(n: number): string {+ return `${(n * 100).toFixed(1)}%`;+}diff --git a/frontend/portal/src/components/usage/AvailablePlans.stories.tsx b/frontend/portal/src/components/usage/AvailablePlans.stories.tsxnew file mode 100644index 0000000000..4b172d0ad7--- /dev/null+++ b/frontend/portal/src/components/usage/AvailablePlans.stories.tsx@@ -0,0 +1,17 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { AvailablePlans } from "@portal/components/usage/AvailablePlans";+import { PLAN_OPTIONS } from "@portal/mocks/usage";++const meta: Meta<typeof AvailablePlans> = {+ title: "Portal/Usage/AvailablePlans",+ component: AvailablePlans,+ args: { plans: PLAN_OPTIONS, onSelect: () => {} },+};+export default meta;+type Story = StoryObj<typeof AvailablePlans>;++export const OnFree: Story = { args: { current: "free" } };++export const OnPro: Story = { args: { current: "pro" } };++export const OnEnterprise: Story = { args: { current: "enterprise" } };diff --git a/frontend/portal/src/components/usage/AvailablePlans.tsx b/frontend/portal/src/components/usage/AvailablePlans.tsxnew file mode 100644index 0000000000..adc8c18ad8--- /dev/null+++ b/frontend/portal/src/components/usage/AvailablePlans.tsx@@ -0,0 +1,36 @@+import type { Tier } from "@portal/contexts/TierContext";+import type { PlanOption } from "@portal/api/usage";+import { PlanCard } from "@portal/components/usage/PlanCard";+import "@portal/views/Usage.css";++/** The plan-catalogue grid, marking the caller's current tier. */+export function AvailablePlans({+ plans,+ current,+ onSelect,+}: {+ plans: PlanOption[];+ current: Tier;+ onSelect: (plan: PlanOption) => void;+}) {+ return (+ <section className="portal-usage__plans-block">+ <header className="portal-usage__section-head">+ <h2 className="portal-usage__section-title">Plans</h2>+ <p className="portal-usage__section-sub">+ Move up or down at any time — changes take effect next cycle.+ </p>+ </header>+ <div className="portal-usage__plans-grid">+ {plans.map((plan) => (+ <PlanCard+ key={plan.tier}+ plan={plan}+ isCurrent={plan.tier === current}+ onSelect={() => onSelect(plan)}+ />+ ))}+ </div>+ </section>+ );+}diff --git a/frontend/portal/src/components/usage/BillingHistoryTable.stories.tsx b/frontend/portal/src/components/usage/BillingHistoryTable.stories.tsxnew file mode 100644index 0000000000..c5144d62ef--- /dev/null+++ b/frontend/portal/src/components/usage/BillingHistoryTable.stories.tsx@@ -0,0 +1,41 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { BillingHistoryTable } from "@portal/components/usage/BillingHistoryTable";+import { buildBillingHistory } from "@portal/mocks/usage";++const meta: Meta<typeof BillingHistoryTable> = {+ title: "Portal/Usage/BillingHistoryTable",+ component: BillingHistoryTable,+};+export default meta;+type Story = StoryObj<typeof BillingHistoryTable>;++// Free: usage tally lines, no charges.+export const Free: Story = { globals: { tier: "free" } };++// Pro: platform fee + metered overage rows across cycles.+export const Pro: Story = { globals: { tier: "pro" } };++// Enterprise: committed draws plus a goodwill credit (negative amount).+export const Enterprise: Story = { globals: { tier: "enterprise" } };++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/billing/history", async () => {+ await delay("infinite");+ return HttpResponse.json(buildBillingHistory("pro"));+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [http.get("/v1/billing/history", () => HttpResponse.json([]))],+ },+ },+};diff --git a/frontend/portal/src/components/usage/BillingHistoryTable.tsx b/frontend/portal/src/components/usage/BillingHistoryTable.tsxnew file mode 100644index 0000000000..765fe7b545--- /dev/null+++ b/frontend/portal/src/components/usage/BillingHistoryTable.tsx@@ -0,0 +1,136 @@+import {+ Card,+ EmptyState,+ Skeleton,+ StatusBadge,+ Table,+ type StatusTone,+ type TableColumn,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchBillingHistory,+ type BillingHistoryRow,+ type InvoiceStatus,+} from "@portal/api/usage";+import { USD, formatBillingDate } from "@portal/components/usage/format";+import "@portal/views/Usage.css";++const STATUS_TONE: Record<InvoiceStatus, StatusTone> = {+ paid: "success",+ due: "warning",+ pending: "info",+ refunded: "neutral",+};++const STATUS_LABEL: Record<InvoiceStatus, string> = {+ paid: "Paid",+ due: "Due",+ pending: "Pending",+ refunded: "Refunded",+};++/** Invoice / line-item history for the current and prior billing cycles. */+export function BillingHistoryTable() {+ const { tier } = useTier();+ const state = useAsync<BillingHistoryRow[]>(+ () => fetchBillingHistory(tier),+ [tier],+ );+ const { data: rows } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const columns: TableColumn<BillingHistoryRow>[] = [+ {+ key: "date",+ header: "Date",+ render: (r) => (+ <span className="portal-usage__hist-date">+ {formatBillingDate(r.date)}+ </span>+ ),+ width: "9rem",+ },+ {+ key: "description",+ header: "Description",+ render: (r) => r.description,+ },+ {+ key: "docs",+ header: "Docs",+ align: "right",+ render: (r) => (r.docs > 0 ? r.docs.toLocaleString() : "—"),+ width: "8rem",+ },+ {+ key: "amount",+ header: "Amount",+ align: "right",+ render: (r) => (+ <span+ className={+ r.amount < 0+ ? "portal-usage__hist-credit"+ : "portal-usage__hist-amount"+ }+ >+ {r.amount < 0+ ? `−${USD.format(Math.abs(r.amount))}`+ : USD.format(r.amount)}+ </span>+ ),+ width: "8rem",+ },+ {+ key: "status",+ header: "Status",+ align: "right",+ render: (r) => (+ <StatusBadge tone={STATUS_TONE[r.status]} size="sm">+ {STATUS_LABEL[r.status]}+ </StatusBadge>+ ),+ width: "8rem",+ },+ ];++ return (+ <section className="portal-usage__hist-block">+ <header className="portal-usage__section-head">+ <h2 className="portal-usage__section-title">Billing history</h2>+ <p className="portal-usage__section-sub">+ Line items from the current and prior billing cycles.+ </p>+ </header>++ {isLoading && (+ <div className="portal-usage__hist-skeleton" aria-hidden>+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} height="2.5rem" />+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ size="compact"+ title="No billing history"+ description="Charges and credits appear here once your first cycle closes."+ />+ )}++ {rows && rows.length > 0 && (+ <Card padding="none">+ <Table+ columns={columns}+ rows={rows}+ rowKey={(r) => r.id}+ empty="No line items"+ />+ </Card>+ )}+ </section>+ );+}diff --git a/frontend/portal/src/components/usage/BillingKpiStrip.stories.tsx b/frontend/portal/src/components/usage/BillingKpiStrip.stories.tsxnew file mode 100644index 0000000000..84f50d95aa--- /dev/null+++ b/frontend/portal/src/components/usage/BillingKpiStrip.stories.tsx@@ -0,0 +1,34 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { BillingKpiStrip } from "@portal/components/usage/BillingKpiStrip";+import { buildBillingSummary } from "@portal/mocks/usage";++const meta: Meta<typeof BillingKpiStrip> = {+ title: "Portal/Usage/BillingKpiStrip",+ component: BillingKpiStrip,+};+export default meta;+type Story = StoryObj<typeof BillingKpiStrip>;++// The "remaining in plan" KPI replaces overage on free.+export const Free: Story = {+ args: { summary: buildBillingSummary("free") },+ globals: { tier: "free" },+};++// Pro surfaces metered overage cost + docs past cap.+export const Pro: Story = {+ args: { summary: buildBillingSummary("pro") },+ globals: { tier: "pro" },+};++// Enterprise swaps overage for commit utilisation.+export const Enterprise: Story = {+ args: { summary: buildBillingSummary("enterprise") },+ globals: { tier: "enterprise" },+};++// Summary still loading — every metric falls back to an em dash.+export const Loading: Story = {+ args: { summary: null },+ globals: { tier: "pro" },+};diff --git a/frontend/portal/src/components/usage/BillingKpiStrip.tsx b/frontend/portal/src/components/usage/BillingKpiStrip.tsxnew file mode 100644index 0000000000..58dd7258e2--- /dev/null+++ b/frontend/portal/src/components/usage/BillingKpiStrip.tsx@@ -0,0 +1,76 @@+import { MetricCard, MetricStrip } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { OVERAGE_RATE, type BillingSummary } from "@portal/api/usage";+import { USD, formatBillingDate } from "@portal/components/usage/format";+import "@portal/views/Usage.css";++/** Headline billing KPIs: docs processed, cost, the tier-relevant cap figure, and renewal. */+export function BillingKpiStrip({+ summary,+}: {+ summary: BillingSummary | null;+}) {+ const { tier } = useTier();++ // Overage is meaningless on free (gated) / enterprise (committed) — surface+ // the more relevant headline figure for those tiers instead.+ const overageCard =+ tier === "free"+ ? {+ label: "Remaining in plan",+ value: summary+ ? `${(summary.includedDocs - summary.docsThisPeriod).toLocaleString()}`+ : "—",+ description: "docs before cap",+ }+ : tier === "enterprise"+ ? {+ label: "Commit utilisation",+ value: summary+ ? `${Math.round((summary.docsThisPeriod / summary.includedDocs) * 100)}%`+ : "—",+ description: "of committed volume",+ }+ : {+ label: `Overage ($${OVERAGE_RATE.toFixed(2)}/doc)`,+ value: summary ? USD.format(summary.overageCost) : "—",+ description: summary+ ? `${summary.overageDocs.toLocaleString()} docs past cap`+ : undefined,+ };++ return (+ <MetricStrip>+ <MetricCard+ label="Docs this period"+ value={summary ? summary.docsThisPeriod.toLocaleString() : "—"}+ description={+ summary+ ? `of ${summary.includedDocs.toLocaleString()} included`+ : undefined+ }+ />+ <MetricCard+ label="Cost this month"+ value={summary ? USD.format(summary.costThisMonth) : "—"}+ description={+ summary && summary.monthlyFee > 0+ ? `incl. ${USD.format(summary.monthlyFee)} platform`+ : tier === "free"+ ? "free plan"+ : undefined+ }+ />+ <MetricCard+ label={overageCard.label}+ value={overageCard.value}+ description={overageCard.description}+ />+ <MetricCard+ label="Next billing date"+ value={summary ? formatBillingDate(summary.nextBillingDate) : "—"}+ description={tier === "free" ? "resets monthly" : "auto-charge"}+ />+ </MetricStrip>+ );+}diff --git a/frontend/portal/src/components/usage/CurrentPlanCard.stories.tsx b/frontend/portal/src/components/usage/CurrentPlanCard.stories.tsxnew file mode 100644index 0000000000..1c75228913--- /dev/null+++ b/frontend/portal/src/components/usage/CurrentPlanCard.stories.tsx@@ -0,0 +1,48 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { CurrentPlanCard } from "@portal/components/usage/CurrentPlanCard";+import { buildBillingSummary } from "@portal/mocks/usage";++const meta: Meta<typeof CurrentPlanCard> = {+ title: "Portal/Usage/CurrentPlanCard",+ component: CurrentPlanCard,+ args: { onUpgrade: () => {} },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "32rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof CurrentPlanCard>;++// Free, approaching the cap — warning banner + cap meter.+export const FreeApproachingCap: Story = {+ args: { summary: buildBillingSummary("free") },+ globals: { tier: "free" },+};++// Free, cap reached — danger banner, processing paused.+export const FreeCapReached: Story = {+ args: {+ summary: {+ ...buildBillingSummary("free"),+ docsThisPeriod: 500,+ capReached: true,+ },+ },+ globals: { tier: "free" },+};++// Pro pay-as-you-go breakdown with metered overage.+export const Pro: Story = {+ args: { summary: buildBillingSummary("pro") },+ globals: { tier: "pro" },+};++// Enterprise committed-volume breakdown.+export const Enterprise: Story = {+ args: { summary: buildBillingSummary("enterprise") },+ globals: { tier: "enterprise" },+};diff --git a/frontend/portal/src/components/usage/CurrentPlanCard.tsx b/frontend/portal/src/components/usage/CurrentPlanCard.tsxnew file mode 100644index 0000000000..23a3fa72e6--- /dev/null+++ b/frontend/portal/src/components/usage/CurrentPlanCard.tsx@@ -0,0 +1,173 @@+import {+ Banner,+ Button,+ Card,+ ProgressBar,+ StatusBadge,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { OVERAGE_RATE, type BillingSummary } from "@portal/api/usage";+import { USD } from "@portal/components/usage/format";+import "@portal/views/Usage.css";++function BreakdownRow({+ label,+ value,+ emphasis,+}: {+ label: string;+ value: string;+ emphasis?: boolean;+}) {+ return (+ <div+ className={+ "portal-usage__breakdown-row" ++ (emphasis ? " portal-usage__breakdown-row--total" : "")+ }+ >+ <span className="portal-usage__breakdown-label">{label}</span>+ <span className="portal-usage__breakdown-value">{value}</span>+ </div>+ );+}++/**+ * Current-plan summary card. The body adapts per tier: a cap meter + nudge on+ * free, a metered pay-as-you-go breakdown on pro, a committed-volume breakdown+ * on enterprise.+ */+export function CurrentPlanCard({+ summary,+ onUpgrade,+}: {+ summary: BillingSummary;+ onUpgrade: () => void;+}) {+ const { tier } = useTier();+ const usedRatio = summary.docsThisPeriod / summary.includedDocs;++ return (+ <Card padding="loose" className="portal-usage__plan-current">+ <div className="portal-usage__plan-current-head">+ <div>+ <span className="portal-usage__plan-eyebrow">Current plan</span>+ <h2 className="portal-usage__plan-name">{summary.planName}</h2>+ </div>+ <StatusBadge+ tone={+ tier === "enterprise"+ ? "purple"+ : tier === "pro"+ ? "info"+ : "neutral"+ }+ size="sm"+ >+ {tier === "free"+ ? "Free"+ : tier === "pro"+ ? "Pay-as-you-go"+ : "Committed"}+ </StatusBadge>+ </div>++ {tier === "free" && (+ <>+ <div className="portal-usage__cap">+ <div className="portal-usage__cap-row">+ <span>+ {summary.docsThisPeriod.toLocaleString()} /{" "}+ {summary.includedDocs.toLocaleString()} docs+ </span>+ <span className="portal-usage__cap-pct">+ {Math.round(usedRatio * 100)}%+ </span>+ </div>+ <ProgressBar+ value={usedRatio}+ thresholded+ height={8}+ label="Free plan usage"+ />+ </div>+ {summary.capReached ? (+ <Banner tone="danger" title="You've hit your free plan cap">+ New documents are paused until next cycle. Upgrade to keep+ processing without interruption.+ </Banner>+ ) : (+ <Banner tone="warning" title="Approaching your free plan cap">+ You're at {Math.round(usedRatio * 100)}% of 500 docs/month.+ Upgrade to pay-as-you-go to avoid a pause.+ </Banner>+ )}+ </>+ )}++ {tier === "pro" && (+ <div className="portal-usage__breakdown">+ <BreakdownRow+ label="Platform fee"+ value={USD.format(summary.monthlyFee)}+ />+ <BreakdownRow+ label="Included docs"+ value={`${summary.includedDocs.toLocaleString()}`}+ />+ <BreakdownRow+ label={`Overage · ${summary.overageDocs.toLocaleString()} docs @ $${OVERAGE_RATE.toFixed(2)}`}+ value={USD.format(summary.overageCost)}+ />+ <BreakdownRow+ label="Projected this month"+ value={USD.format(summary.costThisMonth)}+ emphasis+ />+ </div>+ )}++ {tier === "enterprise" && (+ <div className="portal-usage__breakdown">+ <BreakdownRow+ label="Committed volume"+ value={`${summary.includedDocs.toLocaleString()} docs/mo`}+ />+ <BreakdownRow+ label="Drawn this period"+ value={`${summary.docsThisPeriod.toLocaleString()} docs`}+ />+ <BreakdownRow+ label="Effective rate"+ value={`$${summary.overageRate.toFixed(3)} / doc`}+ />+ <BreakdownRow+ label="Monthly draw"+ value={USD.format(summary.monthlyFee)}+ emphasis+ />+ </div>+ )}++ <div className="portal-usage__plan-actions">+ {tier !== "enterprise" ? (+ <Button+ variant="gradient"+ accent={tier === "free" ? "blue" : "purple"}+ onClick={onUpgrade}+ >+ {tier === "free" ? "Upgrade plan" : "Talk to sales"}+ </Button>+ ) : (+ <Button variant="outline" accent="purple" onClick={onUpgrade}>+ Adjust commitment+ </Button>+ )}+ {/* TODO(backend): GET /v1/billing/invoices?format=pdf — bundle + download invoice PDFs. */}+ <Button variant="ghost" size="md">+ Download invoices+ </Button>+ </div>+ </Card>+ );+}diff --git a/frontend/portal/src/components/usage/PlanCard.stories.tsx b/frontend/portal/src/components/usage/PlanCard.stories.tsxnew file mode 100644index 0000000000..d27d94cc33--- /dev/null+++ b/frontend/portal/src/components/usage/PlanCard.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PlanCard } from "@portal/components/usage/PlanCard";+import { PLAN_OPTIONS } from "@portal/mocks/usage";++const [free, pro, enterprise] = PLAN_OPTIONS;++const meta: Meta<typeof PlanCard> = {+ title: "Portal/Usage/PlanCard",+ component: PlanCard,+ args: { onSelect: () => {} },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "20rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof PlanCard>;++export const Free: Story = { args: { plan: free, isCurrent: false } };++export const Pro: Story = { args: { plan: pro, isCurrent: false } };++export const Enterprise: Story = {+ args: { plan: enterprise, isCurrent: false },+};++// The active plan is outlined and its CTA disabled.+export const Current: Story = { args: { plan: pro, isCurrent: true } };diff --git a/frontend/portal/src/components/usage/PlanCard.tsx b/frontend/portal/src/components/usage/PlanCard.tsxnew file mode 100644index 0000000000..4c745e8a8f--- /dev/null+++ b/frontend/portal/src/components/usage/PlanCard.tsx@@ -0,0 +1,66 @@+import { Button, Card, StatusBadge } from "@shared/components";+import type { PlanOption } from "@portal/api/usage";+import "@portal/views/Usage.css";++/** A single plan in the catalogue grid; highlighted when it's the active plan. */+export function PlanCard({+ plan,+ isCurrent,+ onSelect,+}: {+ plan: PlanOption;+ isCurrent: boolean;+ onSelect: () => void;+}) {+ const accent = plan.tier === "enterprise" ? "purple" : "blue";+ return (+ <Card+ accent={plan.tier === "free" ? undefined : accent}+ padding="loose"+ className={+ "portal-usage__plan-card" ++ (isCurrent ? " portal-usage__plan-card--current" : "")+ }+ >+ <div className="portal-usage__plan-card-head">+ <h3 className="portal-usage__plan-card-name">{plan.name}</h3>+ {isCurrent && (+ <StatusBadge tone="success" size="sm">+ Current+ </StatusBadge>+ )}+ </div>+ <div className="portal-usage__plan-card-price">+ <span className="portal-usage__plan-card-amount">{plan.price}</span>+ <span className="portal-usage__plan-card-cadence">+ {plan.priceCadence}+ </span>+ </div>+ <p className="portal-usage__plan-card-blurb">{plan.blurb}</p>+ <ul className="portal-usage__plan-card-features">+ {plan.features.map((f) => (+ <li key={f}>+ <span aria-hidden className="portal-usage__plan-card-check">+ ✓+ </span>+ {f}+ </li>+ ))}+ </ul>+ <Button+ variant={isCurrent ? "outline" : "gradient"}+ accent={accent}+ size="sm"+ fullWidth+ disabled={isCurrent}+ onClick={onSelect}+ >+ {isCurrent+ ? "Your plan"+ : plan.tier === "enterprise"+ ? "Contact sales"+ : "Choose plan"}+ </Button>+ </Card>+ );+}diff --git a/frontend/portal/src/components/usage/SpendCapControl.stories.tsx b/frontend/portal/src/components/usage/SpendCapControl.stories.tsxnew file mode 100644index 0000000000..0a426166ea--- /dev/null+++ b/frontend/portal/src/components/usage/SpendCapControl.stories.tsx@@ -0,0 +1,41 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { SpendCapControl } from "@portal/components/usage/SpendCapControl";+import { buildBillingSummary } from "@portal/mocks/usage";++const meta: Meta<typeof SpendCapControl> = {+ title: "Portal/Usage/SpendCapControl",+ component: SpendCapControl,+ decorators: [+ (S) => (+ <div style={{ maxWidth: "28rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof SpendCapControl>;++// Free can't accrue spend — explanatory card, no slider.+export const Free: Story = {+ args: { summary: buildBillingSummary("free") },+ globals: { tier: "free" },+};++// Pro with a cap already set — interactive slider + projection meter.+export const ProCapEnabled: Story = {+ args: { summary: buildBillingSummary("pro") },+ globals: { tier: "pro" },+};++// Pro with no cap set — starts collapsed behind "Enable cap".+export const ProCapDisabled: Story = {+ args: { summary: { ...buildBillingSummary("pro"), spendCap: null } },+ globals: { tier: "pro" },+};++// Enterprise spend is contract-governed — read-only card.+export const Enterprise: Story = {+ args: { summary: buildBillingSummary("enterprise") },+ globals: { tier: "enterprise" },+};diff --git a/frontend/portal/src/components/usage/SpendCapControl.tsx b/frontend/portal/src/components/usage/SpendCapControl.tsxnew file mode 100644index 0000000000..1e5bf32ebe--- /dev/null+++ b/frontend/portal/src/components/usage/SpendCapControl.tsx@@ -0,0 +1,106 @@+import { useState } from "react";+import {+ Button,+ Card,+ ProgressBar,+ Slider,+ StatusBadge,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import type { BillingSummary } from "@portal/api/usage";+import { USD } from "@portal/components/usage/format";+import "@portal/views/Usage.css";++/**+ * Monthly spend-cap control. Only pay-as-you-go can accrue spend, so free and+ * enterprise render explanatory cards instead of the interactive slider.+ */+export function SpendCapControl({ summary }: { summary: BillingSummary }) {+ const { tier } = useTier();+ const [enabled, setEnabled] = useState(summary.spendCap !== null);+ const [cap, setCap] = useState(summary.spendCap ?? 1_000);++ if (tier === "free") {+ return (+ <Card padding="loose" className="portal-usage__cap-card">+ <h2 className="portal-usage__section-title">Spend cap</h2>+ <p className="portal-usage__section-sub">+ The free plan can't accrue spend — your usage is hard-capped at 500+ docs/month. Upgrade to pay-as-you-go to set a monthly spend cap.+ </p>+ </Card>+ );+ }++ if (tier === "enterprise") {+ return (+ <Card padding="loose" className="portal-usage__cap-card">+ <h2 className="portal-usage__section-title">Spend controls</h2>+ <p className="portal-usage__section-sub">+ Spend is governed by your committed-volume contract. Overage terms and+ alert thresholds are managed with your account team.+ </p>+ <div className="portal-usage__cap-meta">+ <StatusBadge tone="purple" size="sm">+ Committed contract+ </StatusBadge>+ <span>Overage billed at ${summary.overageRate.toFixed(3)}/doc</span>+ </div>+ </Card>+ );+ }++ const projected = summary.costThisMonth;+ const capRatio = enabled ? Math.min(projected / cap, 1) : 0;++ // TODO(backend): PUT /v1/billing/spend-cap { enabled, cap } — persist the cap+ // so processing pauses server-side when projected spend reaches the limit.+ return (+ <Card padding="loose" className="portal-usage__cap-card">+ <div className="portal-usage__cap-card-head">+ <div>+ <h2 className="portal-usage__section-title">Monthly spend cap</h2>+ <p className="portal-usage__section-sub">+ Pause processing automatically when spend reaches your limit.+ </p>+ </div>+ <Button+ variant={enabled ? "outline" : "gradient"}+ size="sm"+ onClick={() => setEnabled((v) => !v)}+ >+ {enabled ? "Disable cap" : "Enable cap"}+ </Button>+ </div>++ {enabled && (+ <>+ <div className="portal-usage__cap-slider">+ <Slider+ value={cap}+ min={500}+ max={10_000}+ step={250}+ onChange={setCap}+ formatValue={(v) => USD.format(v)}+ />+ </div>+ <div className="portal-usage__cap-row">+ <span>+ Projected {USD.format(projected)} of {USD.format(cap)} cap+ </span>+ <span className="portal-usage__cap-pct">+ {Math.round(capRatio * 100)}%+ </span>+ </div>+ <ProgressBar+ value={capRatio}+ thresholded+ height={8}+ label="Spend against cap"+ />+ </>+ )}+ </Card>+ );+}diff --git a/frontend/portal/src/components/usage/UpgradeModal.stories.tsx b/frontend/portal/src/components/usage/UpgradeModal.stories.tsxnew file mode 100644index 0000000000..511006d30a--- /dev/null+++ b/frontend/portal/src/components/usage/UpgradeModal.stories.tsx@@ -0,0 +1,28 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { UpgradeModal } from "@portal/components/usage/UpgradeModal";+import { PLAN_OPTIONS } from "@portal/mocks/usage";++const enterprisePlan =+ PLAN_OPTIONS.find((p) => p.tier === "enterprise") ?? null;++const meta: Meta<typeof UpgradeModal> = {+ title: "Portal/Usage/UpgradeModal",+ component: UpgradeModal,+ args: { open: true, onClose: () => {}, target: null },+};+export default meta;+type Story = StoryObj<typeof UpgradeModal>;++// Free user pushed to pay-as-you-go.+export const FromFree: Story = { args: { currentTier: "free" } };++// Pro user with no specific target — generic committed-pricing nudge.+export const FromPro: Story = { args: { currentTier: "pro" } };++// Pro user selecting the enterprise plan — sales-conversation copy.+export const ProToEnterprise: Story = {+ args: { currentTier: "pro", target: enterprisePlan },+};++// Enterprise user routed to their account team.+export const FromEnterprise: Story = { args: { currentTier: "enterprise" } };diff --git a/frontend/portal/src/components/usage/UpgradeModal.tsx b/frontend/portal/src/components/usage/UpgradeModal.tsxnew file mode 100644index 0000000000..0146a2aef7--- /dev/null+++ b/frontend/portal/src/components/usage/UpgradeModal.tsx@@ -0,0 +1,133 @@+import { Button, Modal } from "@shared/components";+import type { Tier } from "@portal/contexts/TierContext";+import type { PlanOption } from "@portal/api/usage";+import "@portal/views/Usage.css";++interface UpgradeCopy {+ title: string;+ subtitle: string;+ body: string;+ bullets: string[];+ cta: string;+ ctaAccent: "blue" | "purple";+}++/**+ * Modal copy is intent-driven, not just plan-driven: a free user who has hit+ * the cap sees urgency; a pro user is nudged toward a committed plan; an+ * enterprise user is routed to their account team for bespoke terms.+ */+function upgradeCopy(+ currentTier: Tier,+ target: PlanOption | null,+): UpgradeCopy {+ // Cap-reached: free user pushed to pay-as-you-go.+ if (currentTier === "free") {+ return {+ title: "Upgrade to keep processing",+ subtitle: "Pay-as-you-go · $0.05 / doc",+ body: "You're at the edge of the 500 doc/month free cap. Pay-as-you-go lifts the cap instantly — you only pay for what you process beyond the included 25,000 docs.",+ bullets: [+ "Lift the 500 doc/month cap immediately",+ "25,000 docs included, then $0.05/doc",+ "Unlimited pipelines, agents, and sources",+ "Set a monthly spend cap to stay in control",+ ],+ cta: "Switch to pay-as-you-go",+ ctaAccent: "blue",+ };+ }++ // Commit-recommend: pro user with overage nudged to a committed plan.+ if (currentTier === "pro") {+ if (target?.tier === "enterprise") {+ return {+ title: "Move to a committed plan",+ subtitle: "Enterprise · committed annual volume",+ body: "Your overage is consistent month over month. A committed-volume contract lowers your effective per-doc rate and unlocks dedicated regions, SSO, and a named CSM.",+ bullets: [+ "Lower effective rate vs metered overage",+ "Dedicated & on-prem region options",+ "SSO, audit-log export, signed DPA",+ "Named CSM and 99.99% SLA",+ ],+ cta: "Talk to sales",+ ctaAccent: "purple",+ };+ }+ return {+ title: "You're already on pay-as-you-go",+ subtitle: "Considering a committed plan?",+ body: "Pay-as-you-go scales with usage. If your volume is steady, a committed-volume contract typically lowers your effective per-doc rate.",+ bullets: [+ "Predictable monthly spend",+ "Lower effective per-doc rate at volume",+ "Volume discounts kick in past 1M docs/mo",+ ],+ cta: "Explore committed pricing",+ ctaAccent: "purple",+ };+ }++ // Bespoke-enterprise: route to account team.+ return {+ title: "Adjust your commitment",+ subtitle: "Enterprise · bespoke terms",+ body: "Your plan is governed by a committed-volume contract. Changes to committed volume, regions, or terms are handled with your account team — they'll model the right shape with you.",+ bullets: [+ "Re-model committed volume up or down",+ "Add dedicated or on-prem regions",+ "Adjust SLA, DPA, and overage terms",+ ],+ cta: "Contact your CSM",+ ctaAccent: "purple",+ };+}++/** Intent-aware plan-change / sales-conversation modal. */+export function UpgradeModal({+ open,+ onClose,+ currentTier,+ target,+}: {+ open: boolean;+ onClose: () => void;+ currentTier: Tier;+ target: PlanOption | null;+}) {+ const copy = upgradeCopy(currentTier, target);+ return (+ <Modal+ open={open}+ onClose={onClose}+ width="md"+ title={copy.title}+ subtitle={copy.subtitle}+ footer={+ <div className="portal-usage__modal-actions">+ <Button variant="ghost" onClick={onClose}>+ Not now+ </Button>+ {/* TODO(backend): POST /v1/billing/plan-change { tier } (or hand off to+ sales) — for now the CTA just dismisses the modal. */}+ <Button variant="gradient" accent={copy.ctaAccent} onClick={onClose}>+ {copy.cta}+ </Button>+ </div>+ }+ >+ <p className="portal-usage__modal-body">{copy.body}</p>+ <ul className="portal-usage__modal-bullets">+ {copy.bullets.map((b) => (+ <li key={b}>+ <span aria-hidden className="portal-usage__plan-card-check">+ ✓+ </span>+ {b}+ </li>+ ))}+ </ul>+ </Modal>+ );+}diff --git a/frontend/portal/src/components/usage/UsageChart.stories.tsx b/frontend/portal/src/components/usage/UsageChart.stories.tsxnew file mode 100644index 0000000000..51327a0db4--- /dev/null+++ b/frontend/portal/src/components/usage/UsageChart.stories.tsx@@ -0,0 +1,46 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse, delay } from "msw";+import { UsageChart } from "@portal/components/usage/UsageChart";+import { buildUsagePayload } from "@portal/mocks/usage";++const meta: Meta<typeof UsageChart> = {+ title: "Portal/Usage/UsageChart",+ component: UsageChart,+ parameters: { layout: "padded" },+ decorators: [+ (S) => (+ <div style={{ maxWidth: "60rem" }}>+ <S />+ </div>+ ),+ ],+};+export default meta;+type Story = StoryObj<typeof UsageChart>;++export const Default: Story = {};++export const Loading: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/billing/usage", async () => {+ await delay("infinite");+ return HttpResponse.json(buildUsagePayload());+ }),+ ],+ },+ },+};++export const Empty: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("/v1/billing/usage", () =>+ HttpResponse.json({ points: [], priorTotal: 0 }),+ ),+ ],+ },+ },+};diff --git a/frontend/portal/src/components/usage/UsageChart.tsx b/frontend/portal/src/components/usage/UsageChart.tsxnew file mode 100644index 0000000000..23838595ce--- /dev/null+++ b/frontend/portal/src/components/usage/UsageChart.tsx@@ -0,0 +1,49 @@+import { useMemo } from "react";+import { EmptyState, Skeleton } from "@shared/components";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import { fetchBillingUsage, type UsageSeriesResponse } from "@portal/api/usage";+import { UsageAreaChart } from "@portal/components/UsageAreaChart";+import "@portal/components/UsageAreaChart.css";++/** 30-day docs-processed area chart, with the period total and prior-period delta. */+export function UsageChart() {+ const state = useAsync<UsageSeriesResponse>(() => fetchBillingUsage(), []);+ const { data: usage } = state;+ const { isLoading } = useSectionFlags(state);++ const docs30d = useMemo(+ () => usage?.points.reduce((sum, p) => sum + p.value, 0) ?? 0,+ [usage],+ );+ const deltaPct = useMemo(() => {+ if (!usage || usage.priorTotal <= 0) return undefined;+ return (docs30d - usage.priorTotal) / usage.priorTotal;+ }, [usage, docs30d]);++ if (isLoading) {+ return (+ <div className="portal-chart">+ <Skeleton width="12rem" height="0.875rem" />+ <Skeleton width="7rem" height="1.75rem" />+ <Skeleton height="15rem" />+ </div>+ );+ }++ if (!usage || usage.points.length === 0) {+ return (+ <EmptyState+ title="No usage yet"+ description="Once documents are processed, your 30-day usage appears here."+ />+ );+ }++ return (+ <UsageAreaChart+ data={usage.points}+ totalValue={docs30d.toLocaleString()}+ deltaPct={deltaPct}+ />+ );+}diff --git a/frontend/portal/src/components/usage/format.ts b/frontend/portal/src/components/usage/format.tsnew file mode 100644index 0000000000..25497473d0--- /dev/null+++ b/frontend/portal/src/components/usage/format.ts@@ -0,0 +1,15 @@+/** Shared currency / date formatting for the Usage & Billing surface. */++export const USD = new Intl.NumberFormat(undefined, {+ style: "currency",+ currency: "USD",+ maximumFractionDigits: 2,+});++export function formatBillingDate(iso: string): string {+ return new Date(iso).toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ year: "numeric",+ });+}diff --git a/frontend/portal/src/contexts/UIContext.tsx b/frontend/portal/src/contexts/UIContext.tsxindex a2b5249f7c..8d0400e18d 100644--- a/frontend/portal/src/contexts/UIContext.tsx+++ b/frontend/portal/src/contexts/UIContext.tsx@@ -16,6 +16,11 @@ interface UIContextValue {openAssistant: () => void;closeAssistant: () => void;toggleAssistant: () => void;++ /** Settings is a modal overlay, not a route. */+ settingsOpen: boolean;+ openSettings: () => void;+ closeSettings: () => void;}const UIContext = createContext<UIContextValue | null>(null);@@ -23,6 +28,7 @@ const UIContext = createContext<UIContextValue | null>(null);export function UIProvider({ children }: { children: ReactNode }) {const [searchOpen, setSearchOpen] = useState(false);const [assistantOpen, setAssistantOpen] = useState(false);+ const [settingsOpen, setSettingsOpen] = useState(false);const value = useMemo<UIContextValue>(() => ({@@ -35,8 +41,12 @@ export function UIProvider({ children }: { children: ReactNode }) {openAssistant: () => setAssistantOpen(true),closeAssistant: () => setAssistantOpen(false),toggleAssistant: () => setAssistantOpen((o) => !o),++ settingsOpen,+ openSettings: () => setSettingsOpen(true),+ closeSettings: () => setSettingsOpen(false),}),- [searchOpen, assistantOpen],+ [searchOpen, assistantOpen, settingsOpen],);return <UIContext.Provider value={value}>{children}</UIContext.Provider>;diff --git a/frontend/portal/src/mocks/docs.ts b/frontend/portal/src/mocks/docs.tsnew file mode 100644index 0000000000..59e5e91d64--- /dev/null+++ b/frontend/portal/src/mocks/docs.ts@@ -0,0 +1,414 @@+/**+ * Developer Docs fixtures and the types api/docs.ts shares with them.+ * api/docs.ts imports the types; the MSW handlers in mocks/handlers/ serve the+ * fixture data over the intercepted httpJson() calls. Components never reach+ * into this module directly.+ *+ * Two payloads back the surface:+ * - the left-hand nav tree (`buildDocsNav`), and+ * - the data-driven reference content (`docsContentFor`) — code samples,+ * SDK matrix, embeddable components, playbooks, agent skills, the error+ * table, and the tier-scaled rate-limit grid.+ *+ * Rate limits scale with plan: free is throttled hard, pro lifts the ceiling,+ * enterprise is negotiated ("Custom"). The rest of the content is tier-neutral.+ *+ * Once a real backend exists the MSW handlers stop being registered and these+ * fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";+import type { CodeLang } from "@shared/components";++/* ──────────────────────────────────────────────────────────────────────── */+/* Navigation */+/* ──────────────────────────────────────────────────────────────────────── */++/** A leaf entry in the docs nav — maps 1:1 to a content section. */+export interface DocsNavItem {+ /** Stable id used as the in-page section anchor. */+ id: string;+ label: string;+ /** Optional badge shown to the right of the label (e.g. "New", "Beta"). */+ badge?: string;+}++/** A top-level grouping in the docs nav tree. */+export interface DocsNavSection {+ id: string;+ label: string;+ /** Single-glyph icon shown beside the section header. */+ icon: string;+ items: DocsNavItem[];+}++export function buildDocsNav(): DocsNavSection[] {+ return [+ {+ id: "getting-started",+ label: "Getting Started",+ icon: "▶",+ items: [+ { id: "quickstart", label: "Quickstart" },+ { id: "authentication", label: "Authentication" },+ { id: "rate-limits", label: "Rate limits & quotas" },+ ],+ },+ {+ id: "api-reference",+ label: "API Reference",+ icon: "{ }",+ items: [+ { id: "endpoints", label: "Endpoints" },+ { id: "errors", label: "Errors" },+ { id: "webhooks", label: "Webhooks", badge: "Beta" },+ ],+ },+ {+ id: "sdks",+ label: "SDKs",+ icon: "◇",+ items: [{ id: "sdk-overview", label: "Official SDKs" }],+ },+ {+ id: "components",+ label: "Components",+ icon: "▤",+ items: [{ id: "component-library", label: "Drop-in viewers" }],+ },+ {+ id: "playbooks",+ label: "Playbooks",+ icon: "✦",+ items: [{ id: "recipes", label: "Recipes" }],+ },+ {+ id: "skills",+ label: "Skills",+ icon: "✷",+ items: [{ id: "skill-catalog", label: "Agent skills", badge: "New" }],+ },+ ];+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Reference content */+/* ──────────────────────────────────────────────────────────────────────── */++/** One tab in a multi-language code snippet. */+export interface CodeSample {+ /** Stable key used as the snippet tab id. */+ key: string;+ label: string;+ lang: CodeLang;+ code: string;+}++/** Per-tier request ceilings rendered by the rate-limits section. */+export interface RateLimit {+ rpm: string;+ burst: string;+ concurrency: string;+}++/** A single HTTP status row in the error table. */+export interface ApiErrorRow {+ code: string;+ /** Severity colour — amber for recoverable, red for hard failures. */+ tone: "amber" | "red";+ meaning: string;+}++export type SdkStatus = "ga" | "beta" | "deprecated";++/** An official client library in the SDK matrix. */+export interface Sdk {+ name: string;+ /** Single-glyph icon shown beside the name. */+ icon: string;+ install: string;+ lang: CodeLang;+ status: SdkStatus;+}++/** An embeddable UI component in the drop-in viewer library. */+export interface EmbedComponent {+ name: string;+ blurb: string;+ /** Stack tag, e.g. "React" or "Web". */+ tag: string;+}++/** A copy-paste, end-to-end pipeline recipe. */+export interface Playbook {+ title: string;+ blurb: string;+ /** Ordered stages rendered as a chip flow. */+ steps: string[];+ accent: "blue" | "purple" | "green";+}++/** A bundled, named agent capability — a deterministic op chain. */+export interface AgentSkill {+ name: string;+ blurb: string;+ /** Op chain shown as a mono string, e.g. "extract · validate". */+ ops: string;+}++/** The complete data-driven docs payload for one tier. */+export interface DocsContent {+ quickstartSamples: CodeSample[];+ quickstartResponse: string;+ rateLimit: RateLimit;+ errors: ApiErrorRow[];+ sdks: Sdk[];+ components: EmbedComponent[];+ playbooks: Playbook[];+ skills: AgentSkill[];+}++const QUICKSTART_SAMPLES: CodeSample[] = [+ {+ key: "curl",+ label: "cURL",+ lang: "bash",+ code: `curl https://api.stirlingpdf.com/v1/invoice \\+ -H "Authorization: Bearer $STIRLING_API_KEY" \\+ -F "[email protected]"`,+ },+ {+ key: "python",+ label: "Python",+ lang: "python",+ code: `from stirling import Stirling++client = Stirling(api_key="sk_live_...")++result = client.extract(+ endpoint="/v1/invoice",+ file=open("invoice.pdf", "rb"),+)+print(result.fields["total"])`,+ },+ {+ key: "node",+ label: "Node",+ lang: "typescript",+ code: `import { Stirling } from "@stirling/sdk";++const client = new Stirling({ apiKey: process.env.STIRLING_API_KEY });++const result = await client.extract({+ endpoint: "/v1/invoice",+ file: await fs.readFile("invoice.pdf"),+});+console.log(result.fields.total);`,+ },+];++const QUICKSTART_RESPONSE = `{+ "endpoint": "/v1/invoice",+ "confidence": 0.98,+ "fields": {+ "vendor_name": "Northwind Traders",+ "invoice_number": "INV-20418",+ "date": "2026-05-31",+ "total": 4820.00,+ "payment_terms": "Net 30"+ },+ "pages": 2,+ "latency_ms": 412+}`;++const RATE_LIMITS: Record<Tier, RateLimit> = {+ free: { rpm: "60 / min", burst: "10", concurrency: "2" },+ pro: { rpm: "1,200 / min", burst: "200", concurrency: "25" },+ enterprise: { rpm: "Custom", burst: "Custom", concurrency: "Custom" },+};++const ERRORS: ApiErrorRow[] = [+ {+ code: "400",+ tone: "amber",+ meaning: "Malformed request or unsupported file type.",+ },+ { code: "401", tone: "red", meaning: "Missing or invalid API key." },+ {+ code: "402",+ tone: "amber",+ meaning: "Quota exhausted — upgrade or wait for reset.",+ },+ { code: "422", tone: "amber", meaning: "Document failed schema validation." },+ { code: "429", tone: "amber", meaning: "Rate limited. Honour Retry-After." },+ {+ code: "500",+ tone: "red",+ meaning: "Internal error — safe to retry with backoff.",+ },+];++const SDKS: Sdk[] = [+ {+ name: "Python",+ icon: "🐍",+ install: "pip install stirling",+ lang: "bash",+ status: "ga",+ },+ {+ name: "Node / TypeScript",+ icon: "⬢",+ install: "npm install @stirling/sdk",+ lang: "bash",+ status: "ga",+ },+ {+ name: "Go",+ icon: "◉",+ install: "go get github.com/stirling/stirling-go",+ lang: "bash",+ status: "ga",+ },+ {+ name: "Ruby",+ icon: "◆",+ install: "gem install stirling",+ lang: "bash",+ status: "ga",+ },+ {+ name: "Java",+ icon: "☕",+ install: "implementation 'com.stirling:sdk:1.x'",+ lang: "bash",+ status: "ga",+ },+ {+ name: ".NET",+ icon: "◈",+ install: "dotnet add package Stirling",+ lang: "bash",+ status: "beta",+ },+ // PHP client predates the typed-response rewrite; pinned, no new endpoints.+ {+ name: "PHP",+ icon: "🐘",+ install: "composer require stirling/stirling-php:^0.9",+ lang: "bash",+ status: "deprecated",+ },+];++const COMPONENTS: EmbedComponent[] = [+ {+ name: "<DocumentViewer />",+ blurb:+ "Render any extracted document with field overlays and confidence highlighting.",+ tag: "React",+ },+ {+ name: "<UploadDropzone />",+ blurb:+ "Drag-and-drop ingestion with client-side type detection and progress.",+ tag: "React",+ },+ {+ name: "<SchemaTable />",+ blurb: "Editable table bound to an endpoint schema with inline validation.",+ tag: "React",+ },+ {+ name: "Web component",+ blurb: "<stirling-viewer> custom element for non-React stacks.",+ tag: "Web",+ },+];++const PLAYBOOKS: Playbook[] = [+ {+ title: "Invoice → ERP sync",+ blurb:+ "Extract invoices from an inbox and post matched line items to your ledger.",+ steps: [+ "Email source",+ "Extract /v1/invoice",+ "Three-way match",+ "POST to ERP",+ ],+ accent: "blue",+ },+ {+ title: "PII redaction at scale",+ blurb:+ "Sweep a document set for PII and write redacted copies to cold storage.",+ steps: ["S3 source", "Detect PII", "Redact", "Store to bucket"],+ accent: "purple",+ },+ {+ title: "Compliance evidence pack",+ blurb:+ "Bundle SOC 2 and audit reports into a verified, timestamped archive.",+ steps: ["Batch upload", "Classify", "Validate schema", "Sign & archive"],+ accent: "green",+ },+ {+ title: "Agent document tool",+ blurb:+ "Expose extraction as an MCP tool your agent can call deterministically.",+ steps: ["Define tool", "Bind endpoint", "Run evals", "Ship to agent"],+ accent: "purple",+ },+];++const SKILLS: AgentSkill[] = [+ {+ name: "Extract & validate",+ blurb:+ "Pull structured fields and enforce the endpoint schema in one call.",+ ops: "extract · validate",+ },+ {+ name: "PII sweep",+ blurb:+ "Detect and redact personal data before a document leaves your tenant.",+ ops: "detect-pii · redact",+ },+ {+ name: "Trust & verify",+ blurb:+ "Check signatures, hashes, and tamper evidence on inbound documents.",+ ops: "verify-signature · checksum",+ },+ {+ name: "Compliance pack",+ blurb:+ "Classify, validate, and archive regulatory documents with an audit trail.",+ ops: "classify · validate · archive",+ },+ {+ name: "Format prep",+ blurb: "Normalise scans — deskew, OCR, and split — ahead of extraction.",+ ops: "ocr · deskew · split",+ },+ {+ name: "Summarise",+ blurb: "Generate a grounded summary with citations back to source pages.",+ ops: "summarise",+ },+];++/** The data-driven docs content for a tier — only rate limits vary by plan. */+export function docsContentFor(tier: Tier): DocsContent {+ return {+ quickstartSamples: QUICKSTART_SAMPLES,+ quickstartResponse: QUICKSTART_RESPONSE,+ rateLimit: RATE_LIMITS[tier],+ errors: ERRORS,+ sdks: SDKS,+ components: COMPONENTS,+ playbooks: PLAYBOOKS,+ skills: SKILLS,+ };+}diff --git a/frontend/portal/src/mocks/handlers/docs.ts b/frontend/portal/src/mocks/handlers/docs.tsnew file mode 100644index 0000000000..e6e688fdad--- /dev/null+++ b/frontend/portal/src/mocks/handlers/docs.ts@@ -0,0 +1,20 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildDocsNav, docsContentFor } from "@portal/mocks/docs";++function tierFrom(request: Request): Tier {+ const url = new URL(request.url);+ return (url.searchParams.get("tier") ?? "pro") as Tier;+}++export const docsHandlers = [+ http.get("/v1/docs/nav", async () => {+ await delay(120);+ return HttpResponse.json(buildDocsNav());+ }),++ http.get("/v1/docs/content", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(docsContentFor(tierFrom(request)));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/index.ts b/frontend/portal/src/mocks/handlers/index.tsindex 5f8afcf038..3ed6279f03 100644--- a/frontend/portal/src/mocks/handlers/index.ts+++ b/frontend/portal/src/mocks/handlers/index.ts@@ -4,6 +4,12 @@ import { homeHandlers } from "@portal/mocks/handlers/home";import { notificationsHandlers } from "@portal/mocks/handlers/notifications";import { opsHandlers } from "@portal/mocks/handlers/ops";import { searchHandlers } from "@portal/mocks/handlers/search";+import { pipelinesHandlers } from "@portal/mocks/handlers/pipelines";+import { sourcesHandlers } from "@portal/mocks/handlers/sources";+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";export const handlers = [...homeHandlers,@@ -12,6 +18,12 @@ export const handlers = [...assistantHandlers,...searchHandlers,...endpointsHandlers,+ ...pipelinesHandlers,+ ...sourcesHandlers,+ ...infrastructureHandlers,+ ...usageHandlers,+ ...docsHandlers,+ ...settingsHandlers,];export { resetNotificationsStore } from "@portal/mocks/handlers/notifications";diff --git a/frontend/portal/src/mocks/handlers/infrastructure.ts b/frontend/portal/src/mocks/handlers/infrastructure.tsnew file mode 100644index 0000000000..5262eb4ff0--- /dev/null+++ b/frontend/portal/src/mocks/handlers/infrastructure.ts@@ -0,0 +1,46 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import {+ apiKeysFor,+ auditLogFor,+ recentDeploymentsFor,+ regionsFor,+ securityFor,+ storageFor,+} from "@portal/mocks/infrastructure";++function tierFrom(request: Request): Tier {+ const url = new URL(request.url);+ return (url.searchParams.get("tier") ?? "pro") as Tier;+}++export const infrastructureHandlers = [+ http.get("/v1/infrastructure/deployments", async ({ request }) => {+ await delay(120);+ const tier = tierFrom(request);+ return HttpResponse.json({+ regions: regionsFor(tier),+ recent: recentDeploymentsFor(tier),+ });+ }),++ http.get("/v1/infrastructure/api-keys", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(apiKeysFor(tierFrom(request)));+ }),++ http.get("/v1/infrastructure/security", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(securityFor(tierFrom(request)));+ }),++ http.get("/v1/infrastructure/storage", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(storageFor(tierFrom(request)));+ }),++ http.get("/v1/infrastructure/audit-log", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(auditLogFor(tierFrom(request)));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/pipelines.ts b/frontend/portal/src/mocks/handlers/pipelines.tsnew file mode 100644index 0000000000..9e28f8d417--- /dev/null+++ b/frontend/portal/src/mocks/handlers/pipelines.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { pipelinesFor } from "@portal/mocks/pipelines";++export const pipelinesHandlers = [+ http.get("/v1/pipelines", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(pipelinesFor(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/settings.ts b/frontend/portal/src/mocks/handlers/settings.tsnew file mode 100644index 0000000000..8fdd4c02fa--- /dev/null+++ b/frontend/portal/src/mocks/handlers/settings.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildSettingsSnapshot } from "@portal/mocks/settings";++export const settingsHandlers = [+ http.get("/v1/settings", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildSettingsSnapshot(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/sources.ts b/frontend/portal/src/mocks/handlers/sources.tsnew file mode 100644index 0000000000..d44322e992--- /dev/null+++ b/frontend/portal/src/mocks/handlers/sources.ts@@ -0,0 +1,12 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import { buildSourcesResponse } from "@portal/mocks/sources";++export const sourcesHandlers = [+ http.get("/v1/sources", async ({ request }) => {+ await delay(120);+ const url = new URL(request.url);+ const tier = (url.searchParams.get("tier") ?? "pro") as Tier;+ return HttpResponse.json(buildSourcesResponse(tier));+ }),+];diff --git a/frontend/portal/src/mocks/handlers/usage.ts b/frontend/portal/src/mocks/handlers/usage.tsnew file mode 100644index 0000000000..82859349bc--- /dev/null+++ b/frontend/portal/src/mocks/handlers/usage.ts@@ -0,0 +1,35 @@+import { http, HttpResponse, delay } from "msw";+import type { Tier } from "@portal/contexts/TierContext";+import {+ buildBillingHistory,+ buildBillingSummary,+ buildUsagePayload,+ PLAN_OPTIONS,+} from "@portal/mocks/usage";++function tierFrom(request: Request): Tier {+ const url = new URL(request.url);+ return (url.searchParams.get("tier") ?? "pro") as Tier;+}++export const usageHandlers = [+ http.get("/v1/billing/usage", async () => {+ await delay(120);+ return HttpResponse.json(buildUsagePayload());+ }),++ http.get("/v1/billing/summary", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(buildBillingSummary(tierFrom(request)));+ }),++ http.get("/v1/billing/plans", async () => {+ await delay(120);+ return HttpResponse.json(PLAN_OPTIONS);+ }),++ http.get("/v1/billing/history", async ({ request }) => {+ await delay(120);+ return HttpResponse.json(buildBillingHistory(tierFrom(request)));+ }),+];diff --git a/frontend/portal/src/mocks/infrastructure.ts b/frontend/portal/src/mocks/infrastructure.tsnew file mode 100644index 0000000000..a6f945d313--- /dev/null+++ b/frontend/portal/src/mocks/infrastructure.ts@@ -0,0 +1,648 @@+/**+ * Infrastructure surface fixtures and the types api/infrastructure.ts shares+ * with them. api/infrastructure.ts imports the types; the MSW handlers in+ * mocks/handlers/ serve the fixture data over the intercepted httpJson() calls.+ * Components never reach into this module directly.+ *+ * Everything here is tier-scaled deterministically: free sees a single region+ * and a trimmed slice of every list, pro adds a second region and the IP+ * allowlist, enterprise unlocks the full topology + compliance posture.+ *+ * Once a real backend exists the MSW handlers stop being registered and these+ * fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";++/* ──────────────────────────────────────────────────────────────────────── */+/* Deployments */+/* ──────────────────────────────────────────────────────────────────────── */++export type RegionStatus = "healthy" | "degraded" | "down";++export interface DeploymentRegion {+ name: string;+ code: string;+ /** Median request latency, ms. */+ latencyMs: number;+ /** Current load as a fraction of provisioned capacity (0–1). */+ load: number;+ status: RegionStatus;+ /** Deployed Stirling engine version. */+ version: string;+ /** 30-day uptime as a fraction (0–1). */+ uptime: number;+ /** Running instance count. */+ instances: number;+ /** Sustained throughput, docs/min. */+ throughput: number;+ /** P99 latency, ms. */+ p99Ms: number;+}++export type DeploymentStatus = "live" | "rolling" | "rolled-back" | "queued";++export interface RecentDeployment {+ id: string;+ version: string;+ environment: "production" | "staging" | "canary";+ product: string;+ status: DeploymentStatus;+ deployedBy: string;+ timestamp: string;+}++const REGION_US_EAST: DeploymentRegion = {+ name: "US East (N. Virginia)",+ code: "us-east-1",+ latencyMs: 41,+ load: 0.62,+ status: "healthy",+ version: "v3.4.2",+ uptime: 0.99987,+ instances: 18,+ throughput: 2140,+ p99Ms: 287,+};++const REGION_US_WEST: DeploymentRegion = {+ name: "US West (Oregon)",+ code: "us-west-2",+ latencyMs: 53,+ load: 0.74,+ status: "healthy",+ version: "v3.4.2",+ uptime: 0.99971,+ instances: 12,+ throughput: 1480,+ p99Ms: 331,+};++const REGION_EU_WEST: DeploymentRegion = {+ name: "EU West (Ireland)",+ code: "eu-west-1",+ latencyMs: 68,+ load: 0.83,+ status: "degraded",+ version: "v3.4.1",+ uptime: 0.99924,+ instances: 9,+ throughput: 1120,+ p99Ms: 521,+};++// A region mid-incident: zero healthy instances, traffic drained away.+const REGION_AP_SOUTHEAST: DeploymentRegion = {+ name: "Asia Pacific (Singapore)",+ code: "ap-southeast-1",+ latencyMs: 0,+ load: 0,+ status: "down",+ version: "v3.4.1",+ uptime: 0.98612,+ instances: 0,+ throughput: 0,+ p99Ms: 0,+};++export function regionsFor(tier: Tier): DeploymentRegion[] {+ if (tier === "free") return [REGION_US_EAST];+ if (tier === "pro") return [REGION_US_EAST, REGION_US_WEST];+ return [REGION_US_EAST, REGION_US_WEST, REGION_EU_WEST, REGION_AP_SOUTHEAST];+}++const RECENT_DEPLOYMENTS_ALL: RecentDeployment[] = [+ {+ id: "dep-1",+ version: "v3.4.2",+ environment: "production",+ product: "Extraction engine",+ status: "live",+ deployedBy: "ci-bot",+ timestamp: "8m ago",+ },+ {+ id: "dep-2",+ version: "v3.4.2-rc4",+ environment: "canary",+ product: "Redaction service",+ status: "rolling",+ deployedBy: "maria.chen",+ timestamp: "34m ago",+ },+ {+ id: "dep-3",+ version: "v2.9.0",+ environment: "production",+ product: "API gateway",+ status: "live",+ deployedBy: "ci-bot",+ timestamp: "2h ago",+ },+ {+ id: "dep-4",+ version: "v3.4.1",+ environment: "staging",+ product: "OCR worker pool",+ status: "queued",+ deployedBy: "devon.park",+ timestamp: "3h ago",+ },+ {+ id: "dep-5",+ version: "v3.3.9",+ environment: "production",+ product: "Extraction engine",+ status: "rolled-back",+ deployedBy: "maria.chen",+ timestamp: "yesterday",+ },+ {+ id: "dep-6",+ version: "v3.3.8",+ environment: "production",+ product: "Webhook dispatcher",+ status: "live",+ deployedBy: "ci-bot",+ timestamp: "2d ago",+ },+];++export function recentDeploymentsFor(tier: Tier): RecentDeployment[] {+ if (tier === "free") return RECENT_DEPLOYMENTS_ALL.slice(0, 2);+ if (tier === "pro") return RECENT_DEPLOYMENTS_ALL.slice(0, 4);+ return RECENT_DEPLOYMENTS_ALL;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* API Keys */+/* ──────────────────────────────────────────────────────────────────────── */++export type ApiKeyStatus = "active" | "revoked" | "rotate-soon";+export type ApiKeyPermission = "Read" | "Write" | "Admin";++export interface ApiKey {+ id: string;+ name: string;+ /** Masked prefix shown in the list, e.g. "sk_live_a3f8…". */+ prefix: string;+ created: string;+ lastUsed: string;+ status: ApiKeyStatus;+ /** Requests/min ceiling. */+ rateLimit: number;+ permissions: ApiKeyPermission[];+ allowedIps: string[];+ usageToday: number;+ usageMonth: number;+}++const API_KEYS_ALL: ApiKey[] = [+ {+ id: "key-1",+ name: "Production · ingest",+ prefix: "sk_live_a3f8…",+ created: "Mar 2, 2026",+ lastUsed: "2m ago",+ status: "active",+ rateLimit: 1200,+ permissions: ["Read", "Write"],+ allowedIps: ["52.14.0.0/16", "18.221.0.0/16"],+ usageToday: 84210,+ usageMonth: 2410933,+ },+ {+ id: "key-2",+ name: "Analytics · read-only",+ prefix: "sk_live_77be…",+ created: "Jan 18, 2026",+ lastUsed: "41m ago",+ status: "active",+ rateLimit: 300,+ permissions: ["Read"],+ allowedIps: [],+ usageToday: 6120,+ usageMonth: 188400,+ },+ {+ id: "key-3",+ name: "Ops · admin (legacy)",+ prefix: "sk_live_d901…",+ created: "Aug 9, 2025",+ lastUsed: "6d ago",+ status: "rotate-soon",+ rateLimit: 600,+ permissions: ["Read", "Write", "Admin"],+ allowedIps: ["203.0.113.7/32"],+ usageToday: 0,+ usageMonth: 14200,+ },+ {+ id: "key-4",+ name: "Sandbox · webhook tester",+ prefix: "sk_test_2c4a…",+ created: "May 30, 2026",+ lastUsed: "never",+ status: "revoked",+ rateLimit: 60,+ permissions: ["Read"],+ allowedIps: [],+ usageToday: 0,+ usageMonth: 0,+ },+];++export function apiKeysFor(tier: Tier): ApiKey[] {+ if (tier === "free") return API_KEYS_ALL.slice(0, 1);+ if (tier === "pro") return API_KEYS_ALL.slice(0, 3);+ return API_KEYS_ALL;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Security */+/* ──────────────────────────────────────────────────────────────────────── */++export type AccessPolicy = "stirling" | "byok" | "hyok";+export type DataResidency = "us" | "eu" | "apac";+export type CertStatus = "certified" | "in-progress" | "not-started";++export interface ComplianceCert {+ id: string;+ name: string;+ status: CertStatus;+ detail: string;+}++export interface IpAllowEntry {+ id: string;+ label: string;+ cidr: string;+ addedBy: string;+ added: string;+}++export interface SecurityConfig {+ accessPolicy: AccessPolicy;+ dataResidency: DataResidency;+ certs: ComplianceCert[];+ ipAllowlist: IpAllowEntry[];+}++const CERTS_FULL: ComplianceCert[] = [+ {+ id: "soc2",+ name: "SOC 2 Type II",+ status: "certified",+ detail: "Audited Apr 2026 · Coalfire",+ },+ {+ id: "iso",+ name: "ISO 27001",+ status: "certified",+ detail: "Cert #IS-774201 · valid to 2027",+ },+ {+ id: "hipaa",+ name: "HIPAA",+ status: "certified",+ detail: "BAA available · PHI-eligible",+ },+ {+ id: "gdpr",+ name: "GDPR",+ status: "certified",+ detail: "EU SCCs · DPA on file",+ },+];++const CERTS_FREE: ComplianceCert[] = [+ {+ id: "soc2",+ name: "SOC 2 Type II",+ status: "certified",+ detail: "Inherited — Stirling platform",+ },+ {+ id: "iso",+ name: "ISO 27001",+ status: "certified",+ detail: "Inherited — Stirling platform",+ },+ {+ id: "hipaa",+ name: "HIPAA",+ status: "not-started",+ detail: "Requires a paid plan + BAA",+ },+ {+ id: "gdpr",+ name: "GDPR",+ status: "in-progress",+ detail: "Standard EU processing terms",+ },+];++const IP_ALLOWLIST: IpAllowEntry[] = [+ {+ id: "ip-1",+ label: "Corp VPN egress",+ cidr: "52.14.0.0/16",+ addedBy: "maria.chen",+ added: "Feb 11, 2026",+ },+ {+ id: "ip-2",+ label: "Data centre — IAD",+ cidr: "18.221.0.0/16",+ addedBy: "devon.park",+ added: "Jan 4, 2026",+ },+ {+ id: "ip-3",+ label: "On-call jump host",+ cidr: "203.0.113.7/32",+ addedBy: "maria.chen",+ added: "Dec 19, 2025",+ },+];++export function securityFor(tier: Tier): SecurityConfig {+ if (tier === "free") {+ return {+ accessPolicy: "stirling",+ dataResidency: "us",+ certs: CERTS_FREE,+ ipAllowlist: [],+ };+ }+ if (tier === "pro") {+ return {+ accessPolicy: "byok",+ dataResidency: "us",+ certs: CERTS_FULL,+ ipAllowlist: IP_ALLOWLIST.slice(0, 2),+ };+ }+ return {+ accessPolicy: "hyok",+ dataResidency: "eu",+ certs: CERTS_FULL,+ ipAllowlist: IP_ALLOWLIST,+ };+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Storage */+/* ──────────────────────────────────────────────────────────────────────── */++export type RetentionWindow = "30" | "60" | "90" | "180" | "never";++export interface StorageProvider {+ id: string;+ name: string;+ kind: "stirling" | "s3" | "azure";+ connected: boolean;+ detail: string;+ usedGb: number;+}++export interface StorageConfig {+ /** Total used storage, GB. */+ usedGb: number;+ /** Quota ceiling, GB. */+ quotaGb: number;+ retention: RetentionWindow;+ providers: StorageProvider[];+}++const PROVIDERS_FULL: StorageProvider[] = [+ {+ id: "stirling",+ name: "Stirling Cloud",+ kind: "stirling",+ connected: true,+ detail: "Primary vault · us-east-1",+ usedGb: 612,+ },+ {+ id: "s3",+ name: "Amazon S3",+ kind: "s3",+ connected: true,+ detail: "s3://acme-prod-archive · WORM",+ usedGb: 388,+ },+ {+ id: "azure",+ name: "Azure Blob",+ kind: "azure",+ connected: false,+ detail: "Not connected",+ usedGb: 0,+ },+];++export function storageFor(tier: Tier): StorageConfig {+ if (tier === "free") {+ return {+ usedGb: 4.2,+ quotaGb: 5,+ retention: "30",+ providers: [PROVIDERS_FULL[0]],+ };+ }+ if (tier === "pro") {+ return {+ usedGb: 318,+ quotaGb: 500,+ retention: "90",+ providers: [PROVIDERS_FULL[0], PROVIDERS_FULL[1]],+ };+ }+ return {+ usedGb: 1000,+ quotaGb: 2000,+ retention: "180",+ providers: PROVIDERS_FULL,+ };+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Audit Logs */+/* ──────────────────────────────────────────────────────────────────────── */++export type AuditCategory =+ | "auth"+ | "config"+ | "elevation"+ | "processing"+ | "security";++export type AuditStatus = "success" | "warning" | "danger" | "info";++export interface AuditEvent {+ id: string;+ timestamp: string;+ category: AuditCategory;+ action: string;+ actor: string;+ target: string;+ status: AuditStatus;+ latencyMs: number;+}++const AUDIT_EVENTS_ALL: AuditEvent[] = [+ {+ id: "a-1",+ timestamp: "10:42:18",+ category: "processing",+ action: "Pipeline run completed",+ actor: "ci-bot",+ target: "COI Compliance",+ status: "success",+ latencyMs: 412,+ },+ {+ id: "a-2",+ timestamp: "10:38:02",+ category: "auth",+ action: "API key authenticated",+ actor: "sk_live_a3f8…",+ target: "us-east-1 gateway",+ status: "success",+ latencyMs: 9,+ },+ {+ id: "a-3",+ timestamp: "10:31:55",+ category: "elevation",+ action: "Admin role assumed",+ actor: "maria.chen",+ target: "Security settings",+ status: "warning",+ latencyMs: 21,+ },+ {+ id: "a-4",+ timestamp: "10:24:40",+ category: "config",+ action: "Retention policy changed",+ actor: "devon.park",+ target: "30d → 90d",+ status: "info",+ latencyMs: 14,+ },+ {+ id: "a-5",+ timestamp: "10:19:07",+ category: "security",+ action: "IP allowlist updated",+ actor: "maria.chen",+ target: "203.0.113.7/32",+ status: "info",+ latencyMs: 11,+ },+ {+ id: "a-6",+ timestamp: "10:12:33",+ category: "auth",+ action: "Failed key authentication",+ actor: "sk_live_d901…",+ target: "us-west-2 gateway",+ status: "danger",+ latencyMs: 6,+ },+ {+ id: "a-7",+ timestamp: "10:04:51",+ category: "processing",+ action: "Redaction job queued",+ actor: "ci-bot",+ target: "Prior Auth batch",+ status: "success",+ latencyMs: 188,+ },+ {+ id: "a-8",+ timestamp: "09:58:12",+ category: "elevation",+ action: "Key rotation requested",+ actor: "devon.park",+ target: "Ops · admin (legacy)",+ status: "warning",+ latencyMs: 33,+ },+ {+ id: "a-9",+ timestamp: "09:51:44",+ category: "security",+ action: "Access policy set to HYOK",+ actor: "maria.chen",+ target: "Document encryption",+ status: "info",+ latencyMs: 27,+ },+ {+ id: "a-10",+ timestamp: "09:43:20",+ category: "config",+ action: "Region added",+ actor: "ci-bot",+ target: "eu-west-1",+ status: "success",+ latencyMs: 240,+ },+ {+ id: "a-11",+ timestamp: "09:36:08",+ category: "processing",+ action: "Schema drift flagged",+ actor: "extract-engine",+ target: "Invoice v3",+ status: "warning",+ latencyMs: 95,+ },+ {+ id: "a-12",+ timestamp: "09:28:55",+ category: "auth",+ action: "SSO session started",+ actor: "devon.park",+ target: "Okta · acme.com",+ status: "success",+ latencyMs: 18,+ },+];++export interface AuditSummary {+ totalEvents: number;+ processing: number;+ elevation: number;+ config: number;+}++export interface AuditLogResponse {+ summary: AuditSummary;+ events: AuditEvent[];+}++export function auditLogFor(tier: Tier): AuditLogResponse {+ const events =+ tier === "free"+ ? AUDIT_EVENTS_ALL.slice(0, 5)+ : tier === "pro"+ ? AUDIT_EVENTS_ALL.slice(0, 9)+ : AUDIT_EVENTS_ALL;++ // Headline counts reflect a full 24h window, not just the visible slice —+ // the table shows the most recent events, the metrics show the day's totals.+ const scale = tier === "free" ? 1 : tier === "pro" ? 21 : 86;+ const summary: AuditSummary = {+ totalEvents: events.length * scale,+ processing:+ events.filter((e) => e.category === "processing").length * scale,+ elevation: events.filter((e) => e.category === "elevation").length * scale,+ config: events.filter((e) => e.category === "config").length * scale,+ };+ return { summary, events };+}diff --git a/frontend/portal/src/mocks/pipelines.ts b/frontend/portal/src/mocks/pipelines.tsnew file mode 100644index 0000000000..b50d2688dd--- /dev/null+++ b/frontend/portal/src/mocks/pipelines.ts@@ -0,0 +1,334 @@+/**+ * Pipelines fixtures and the types api/pipelines.ts shares with them.+ * api/pipelines.ts imports the types; the MSW handlers in mocks/handlers/+ * serve the fixture data over the intercepted httpJson() calls. Components+ * never reach into this module directly.+ *+ * Fixtures are tier-shaped:+ * - free → empty (prompts "build your first pipeline")+ * - pro → a small deployed fleet+ * - enterprise → a larger fleet plus a shadow/comparative evals note+ */++import type { Tier } from "@portal/contexts/TierContext";++/** A deployed pipeline's live health. */+export type PipelineStatus = "healthy" | "degraded";++/** 24-hour rollup shown on the pipeline row. */+export interface PipelineMetrics {+ /** Docs processed in the trailing 24h. */+ docs24h: number;+ /** Sustained throughput, docs/min. */+ throughputPerMin: number;+ /** Error rate as a fraction (0.004 = 0.4%). */+ errorRate: number;+ /** P95 stage-to-store latency, ms. */+ p95LatencyMs: number;+ /** Uptime over the trailing 24h, as a fraction. */+ uptime: number;+}++/**+ * The five silent stages every pipeline passes a document through. The accent+ * is fixed per stage so the chip row reads the same across every pipeline:+ * Ingest=green, Validate=blue, Modify=amber, Secure=red, Route/Store=purple.+ */+export type StageKey = "ingest" | "validate" | "modify" | "secure" | "route";++export interface StageSummary {+ key: StageKey;+ label: string;+ /** Op labels active in this stage for this pipeline. */+ ops: string[];+}++/** Golden-set validation rollup. */+export interface GoldenSet {+ passing: number;+ total: number;+ /** Last time the set was run. */+ lastRun: string;+}++/** A single field whose shape has drifted from the inferred schema. */+export interface SchemaDrift {+ field: string;+ /** Human summary of what changed. */+ note: string;+ /** Confidence delta since the last known-good shape (negative = worse). */+ confidenceDelta: number;+ severity: "info" | "warning";+ /** Share of docs in the window that exhibited the drift. */+ affectedDocs: number;+}++export interface Pipeline {+ id: string;+ name: string;+ /** What the pipeline does, one line. */+ blurb: string;+ status: PipelineStatus;+ /** Source rail label (from SOURCE_OPTIONS). */+ source: string;+ /** Destination rail label (from DESTINATION_OPTIONS). */+ destination: string;+ /** Deployed version tag. */+ version: string;+ /** Regions the pipeline runs in. */+ regions: string[];+ metrics: PipelineMetrics;+ stages: StageSummary[];+ golden: GoldenSet;+ drift: SchemaDrift[];+}++const STAGE_LABEL: Record<StageKey, string> = {+ ingest: "Ingest",+ validate: "Validate",+ modify: "Modify",+ secure: "Secure",+ route: "Route / Store",+};++/** Build a five-stage summary from the per-stage op-label lists. */+function stages(+ ingest: string[],+ validate: string[],+ modify: string[],+ secure: string[],+ route: string[],+): StageSummary[] {+ const byKey: Record<StageKey, string[]> = {+ ingest,+ validate,+ modify,+ secure,+ route,+ };+ return (Object.keys(byKey) as StageKey[]).map((key) => ({+ key,+ label: STAGE_LABEL[key],+ ops: byKey[key],+ }));+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Tier fixtures */+/* ──────────────────────────────────────────────────────────────────────── */++const COI_COMPLIANCE: Pipeline = {+ id: "pl-coi",+ name: "COI Compliance",+ blurb: "Certificate-of-insurance intake → coverage-gap check → vault",+ status: "healthy",+ source: "Email intake",+ destination: "Stirling vault",+ version: "v3.4.1",+ regions: ["us-east-1", "eu-west-1"],+ metrics: {+ docs24h: 28941,+ throughputPerMin: 22,+ errorRate: 0.004,+ p95LatencyMs: 412,+ uptime: 0.9998,+ },+ stages: stages(+ ["OCR", "Classify", "Extract"],+ ["Schema validate", "Confidence bounds"],+ ["Compress"],+ ["Redact PII", "Encryption at rest"],+ ["Primary store", "Processing manifest"],+ ),+ golden: { passing: 36, total: 36, lastRun: "2h ago" },+ drift: [],+};++const PRIOR_AUTH: Pipeline = {+ id: "pl-prior-auth",+ name: "Prior Auth Router",+ blurb: "Prior-authorization intake → medical-necessity gate → payer webhook",+ status: "degraded",+ source: "Inbound webhook",+ destination: "Outbound webhook",+ version: "v3.1.0",+ regions: ["us-east-1"],+ metrics: {+ docs24h: 11204,+ throughputPerMin: 9,+ errorRate: 0.031,+ p95LatencyMs: 740,+ uptime: 0.9962,+ },+ stages: stages(+ ["OCR", "Classify", "Extract"],+ ["Schema validate", "Counterparty match", "Confidence bounds"],+ ["Convert"],+ ["Redact PII", "PII/PHI enforcement", "Encryption at rest"],+ ["Conditional routing", "Human review"],+ ),+ golden: { passing: 24, total: 28, lastRun: "47m ago" },+ drift: [+ {+ field: "procedure_codes",+ note: "New CPT modifier suffix not seen in prior examples",+ confidenceDelta: -0.07,+ severity: "warning",+ affectedDocs: 18,+ },+ {+ field: "payer",+ note: "Two payers now emit a merged-entity name",+ confidenceDelta: -0.03,+ severity: "info",+ affectedDocs: 6,+ },+ ],+};++const INVOICE_AP: Pipeline = {+ id: "pl-invoice-ap",+ name: "Invoice → AP",+ blurb: "Invoice extraction → three-way match → Postgres",+ status: "healthy",+ source: "S3 bucket watch",+ destination: "Database",+ version: "v2.8.0",+ regions: ["us-east-1", "eu-west-1", "ap-southeast-1"],+ metrics: {+ docs24h: 53120,+ throughputPerMin: 41,+ errorRate: 0.006,+ p95LatencyMs: 358,+ uptime: 0.9997,+ },+ stages: stages(+ ["Parse", "Classify", "Extract"],+ ["Schema validate", "Confidence bounds"],+ ["PDF → CSV"],+ ["Redact PII", "Encryption at rest"],+ ["Primary store", "Mirror to bucket", "Notify"],+ ),+ golden: { passing: 41, total: 42, lastRun: "1h ago" },+ drift: [+ {+ field: "tax",+ note: "EU reverse-charge invoices omit a line-level tax field",+ confidenceDelta: -0.02,+ severity: "info",+ affectedDocs: 4,+ },+ ],+};++const CONTRACT_REVIEW: Pipeline = {+ id: "pl-contract",+ name: "Contract Review",+ blurb: "Contract intake → clause-risk analysis → review queue",+ status: "healthy",+ source: "Upload API",+ destination: "Another pipeline",+ version: "v1.9.2",+ regions: ["eu-west-1"],+ metrics: {+ docs24h: 4380,+ throughputPerMin: 4,+ errorRate: 0.009,+ p95LatencyMs: 1280,+ uptime: 0.9991,+ },+ stages: stages(+ ["OCR", "Classify"],+ ["Contract analyzer", "Authenticity", "Confidence bounds"],+ ["Document summarizer"],+ ["Redact PII", "Confidentiality mark", "Signed outputs"],+ ["Human review", "Flag"],+ ),+ golden: { passing: 31, total: 33, lastRun: "5h ago" },+ drift: [],+};++const KYC_PROCESSOR: Pipeline = {+ id: "pl-kyc",+ name: "KYC Processor",+ blurb:+ "Identity-document intake → authenticity + sanctions → compliance archive",+ status: "healthy",+ source: "Scheduled import",+ destination: "Compliance archive",+ version: "v4.0.3",+ regions: ["us-east-1", "eu-west-1", "ap-southeast-1"],+ metrics: {+ docs24h: 19870,+ throughputPerMin: 15,+ errorRate: 0.005,+ p95LatencyMs: 503,+ uptime: 0.9999,+ },+ stages: stages(+ ["OCR", "Classify", "Extract"],+ ["Authenticity", "Tamper check", "Counterparty match"],+ ["Convert"],+ ["Field-aware redact", "Attribution watermark", "Encryption at rest"],+ ["Compliance archive", "Processing manifest", "Notify"],+ ),+ golden: { passing: 52, total: 54, lastRun: "31m ago" },+ drift: [+ {+ field: "document_number",+ note: "New passport series uses a 9-char alphanumeric format",+ confidenceDelta: -0.04,+ severity: "warning",+ affectedDocs: 11,+ },+ ],+};++/**+ * Enterprise-only evals note. Surfaced as a banner: shadow + comparative eval+ * runs gate every promotion, so the deployed fleet always trails a quietly+ * running candidate.+ */+export interface EvalsNote {+ /** Pipelines currently running a shadow eval against production traffic. */+ shadowCount: number;+ /** Comparative (champion/challenger) runs awaiting sign-off. */+ comparativeCount: number;+ detail: string;+}++const ENTERPRISE_EVALS: EvalsNote = {+ shadowCount: 2,+ comparativeCount: 2,+ detail:+ "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.",+};++export interface PipelinesResponse {+ pipelines: Pipeline[];+ /** Present for enterprise only. */+ evals: EvalsNote | null;+}++export function pipelinesFor(tier: Tier): PipelinesResponse {+ if (tier === "free") {+ return { pipelines: [], evals: null };+ }+ if (tier === "enterprise") {+ return {+ pipelines: [+ INVOICE_AP,+ COI_COMPLIANCE,+ PRIOR_AUTH,+ KYC_PROCESSOR,+ CONTRACT_REVIEW,+ ],+ evals: ENTERPRISE_EVALS,+ };+ }+ // pro+ return {+ pipelines: [COI_COMPLIANCE, INVOICE_AP, PRIOR_AUTH],+ evals: null,+ };+}diff --git a/frontend/portal/src/mocks/settings.ts b/frontend/portal/src/mocks/settings.tsnew file mode 100644index 0000000000..7cd2afe98e--- /dev/null+++ b/frontend/portal/src/mocks/settings.ts@@ -0,0 +1,109 @@+/**+ * Account-settings fixtures and the types api/settings.ts shares with them.+ * api/settings.ts imports the types; the MSW handlers in mocks/handlers/ serve+ * the fixture data over the intercepted httpJson() call. Components never reach+ * into this module directly.+ *+ * The shape is tier-aware: the workspace plan label, available regions, and+ * data-residency posture differ by tier, so the modal reflects what each plan+ * can actually configure.+ */++import type { Tier } from "@portal/contexts/TierContext";++export interface RegionOption {+ value: string;+ label: string;+ /** Enterprise-only residency regions are gated below higher tiers. */+ enterpriseOnly?: boolean;+}++export interface NotificationDefault {+ id: string;+ enabled: boolean;+}++/**+ * Server snapshot of the account + workspace the modal opens onto. Editable+ * fields seed local form state; `planLabel` / `seats` are read-only context.+ */+export interface SettingsSnapshot {+ profile: {+ name: string;+ email: string;+ role: string;+ /** Avatar image URL, or null to fall back to initials. */+ avatarUrl: string | null;+ };+ workspace: {+ name: string;+ region: string;+ planLabel: string;+ seats: { used: number; total: number };+ };+ /** Per-category notification toggles, server-default on/off. */+ notifications: NotificationDefault[];+ regions: RegionOption[];+}++const REGIONS: RegionOption[] = [+ { value: "us-east-1", label: "US East (N. Virginia)" },+ { value: "us-west-2", label: "US West (Oregon)" },+ { value: "eu-west-1", label: "EU West (Ireland)" },+ { value: "eu-central-1", label: "EU Central (Frankfurt)" },+ {+ value: "ap-southeast-2",+ label: "Asia Pacific (Sydney)",+ enterpriseOnly: true,+ },+ { value: "ca-central-1", label: "Canada (Central)", enterpriseOnly: true },+];++const PLAN_LABEL: Record<Tier, string> = {+ free: "Free Plan",+ pro: "Pay-as-you-go",+ enterprise: "Enterprise Plan",+};++const SEATS: Record<Tier, { used: number; total: number }> = {+ free: { used: 1, total: 1 },+ pro: { used: 4, total: 5 },+ enterprise: { used: 38, total: 50 },+};++const WORKSPACE_NAME: Record<Tier, string> = {+ free: "My Workspace",+ pro: "Acme Document Ops",+ enterprise: "Acme Corp — Global",+};++/** Notification categories shown in Preferences, with sensible per-tier defaults. */+function notificationsFor(tier: Tier): NotificationDefault[] {+ return [+ { id: "pipeline-failures", enabled: true },+ { id: "pipeline-success", enabled: tier !== "free" },+ { id: "usage-alerts", enabled: true },+ { id: "weekly-digest", enabled: tier === "free" },+ { id: "security-alerts", enabled: true },+ { id: "product-updates", enabled: false },+ ];+}++export function buildSettingsSnapshot(tier: Tier): SettingsSnapshot {+ return {+ profile: {+ name: "Reece Browne",+ email: "[email protected]",+ role: tier === "enterprise" ? "Org Admin" : "Owner",+ avatarUrl: null,+ },+ workspace: {+ name: WORKSPACE_NAME[tier],+ region: tier === "free" ? "us-east-1" : "eu-west-1",+ planLabel: PLAN_LABEL[tier],+ seats: SEATS[tier],+ },+ notifications: notificationsFor(tier),+ regions: REGIONS,+ };+}diff --git a/frontend/portal/src/mocks/sources.ts b/frontend/portal/src/mocks/sources.tsnew file mode 100644index 0000000000..d881043a33--- /dev/null+++ b/frontend/portal/src/mocks/sources.ts@@ -0,0 +1,545 @@+/**+ * Sources & Agents fixtures and the types api/sources.ts shares with them.+ *+ * A "source" is anything that feeds documents into Stirling — an interactive+ * editor session, an autonomous agent, an API client, a webhook, a storage+ * connector, an email inbox, a desktop app, or a batch job. Each carries a+ * type-specific detail payload surfaced when its table row is expanded.+ *+ * api/sources.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";++/* ──────────────────────────────────────────────────────────────────────── */+/* Source types */+/* ──────────────────────────────────────────────────────────────────────── */++export type SourceType =+ | "editor"+ | "agent"+ | "apiclient"+ | "webhook"+ | "connector"+ | "email"+ | "desktop"+ | "batch";++export type SourceStatus = "active" | "idle" | "degraded" | "paused" | "error";++/** Type-specific detail payloads, discriminated by `kind`. */++export interface AgentDetail {+ kind: "agent";+ model: string;+ /** Calls over the trailing 24h. */+ calls24h: number;+ errorRate: number;+ /** Mean output confidence 0..1. */+ confidence: number;+ escalations24h: number;+ /** Pipelines this agent is allowed to invoke. */+ assignedPipelines: string[];+ scopes: string[];+}++export interface ApiClientDetail {+ kind: "apiclient";+ /** Pre-masked for display — never carries the real secret. */+ maskedKey: string;+ rateLimit: string;+ /** Requests used against the current rate-limit window. */+ rateUsedPct: number;+ endpoints: { method: string; path: string; calls24h: number }[];+ createdBy: string;+ lastRotated: string;+}++export interface WebhookDetail {+ kind: "webhook";+ url: string;+ authType: "HMAC-SHA256" | "Bearer token" | "Basic" | "None";+ successRate: number;+ /** Recent deliveries, newest first. */+ recentDeliveries: { event: string; status: number; time: string }[];+ retries24h: number;+}++/** Generic key/value detail for the simpler source types. */+export interface BasicDetail {+ kind: "basic";+ rows: { label: string; value: string }[];+}++export type SourceDetail =+ | AgentDetail+ | ApiClientDetail+ | WebhookDetail+ | BasicDetail;++export interface Source {+ id: string;+ name: string;+ type: SourceType;+ status: SourceStatus;+ docs24h: number;+ docs30d: number;+ /** Relative-time string, e.g. "2m ago". */+ lastEvent: string;+ owner: string;+ detail: SourceDetail;+}++export interface SourcesKpi {+ value: string | number;+ delta?: number;+ deltaDirection?: "up" | "down" | "flat";+ description?: string;+}++export interface SourcesResponse {+ kpis: SourcesKpi[];+ sources: Source[];+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Per-type presentation metadata (icon + chip tone + label) */+/* Lives client-side — it's product copy, not data. Re-exported for the */+/* view via api/sources.ts. */+/* ──────────────────────────────────────────────────────────────────────── */++export interface SourceTypeMeta {+ label: string;+ icon: string;+ tone: "neutral" | "blue" | "purple" | "green" | "amber" | "red";+}++export const SOURCE_TYPE_META: Record<SourceType, SourceTypeMeta> = {+ editor: { label: "Editor", icon: "✎", tone: "neutral" },+ agent: { label: "Agent", icon: "◆", tone: "purple" },+ apiclient: { label: "API client", icon: "⌘", tone: "blue" },+ webhook: { label: "Webhook", icon: "⇄", tone: "green" },+ connector: { label: "Connector", icon: "⛁", tone: "amber" },+ email: { label: "Email inbox", icon: "✉", tone: "blue" },+ desktop: { label: "Desktop", icon: "▣", tone: "neutral" },+ batch: { label: "Batch job", icon: "≡", tone: "amber" },+};++export const SOURCE_STATUS_TONE: Record<+ SourceStatus,+ "success" | "warning" | "danger" | "neutral" | "info"+> = {+ active: "success",+ idle: "neutral",+ degraded: "warning",+ paused: "info",+ error: "danger",+};++/* ──────────────────────────────────────────────────────────────────────── */+/* Fixture builders */+/* ──────────────────────────────────────────────────────────────────────── */++function agentDetail(over: Partial<AgentDetail>): AgentDetail {+ return {+ kind: "agent",+ model: "claude-sonnet-4.5",+ calls24h: 0,+ errorRate: 0,+ confidence: 0.95,+ escalations24h: 0,+ assignedPipelines: [],+ scopes: [],+ ...over,+ };+}++const PRO_SOURCES: Source[] = [+ {+ id: "src-editor-1",+ name: "Web Editor — workspace",+ type: "editor",+ status: "active",+ docs24h: 38,+ docs30d: 642,+ lastEvent: "4m ago",+ owner: "[email protected]",+ detail: {+ kind: "basic",+ rows: [+ { label: "Session", value: "Browser · Chrome 126" },+ { label: "Active editors", value: "3 this week" },+ { label: "Default pipeline", value: "Redact & Flatten" },+ { label: "Region", value: "us-east-1" },+ ],+ },+ },+ {+ id: "src-agent-1",+ name: "Invoice Extractor",+ type: "agent",+ status: "active",+ docs24h: 1287,+ docs30d: 31840,+ lastEvent: "32s ago",+ owner: "[email protected]",+ detail: agentDetail({+ model: "claude-sonnet-4.5",+ calls24h: 1342,+ errorRate: 0.004,+ confidence: 0.962,+ escalations24h: 11,+ assignedPipelines: ["Invoice v3", "AP Routing"],+ scopes: ["documents:read", "pipelines:invoke", "extract:write"],+ }),+ },+ {+ id: "src-agent-2",+ name: "Contract Router",+ type: "agent",+ status: "degraded",+ docs24h: 412,+ docs30d: 9870,+ lastEvent: "6m ago",+ owner: "[email protected]",+ // Degraded: error rate over the 5% alarm threshold and confidence below the+ // green band, so the panel renders danger/amber tones.+ detail: agentDetail({+ model: "claude-opus-4.1",+ calls24h: 455,+ errorRate: 0.071,+ confidence: 0.883,+ escalations24h: 34,+ assignedPipelines: ["Contract Review", "DPA Classifier"],+ scopes: ["documents:read", "pipelines:invoke", "review:escalate"],+ }),+ },+ {+ id: "src-agent-3",+ name: "KYC Processor",+ type: "agent",+ status: "active",+ docs24h: 768,+ docs30d: 18420,+ lastEvent: "1m ago",+ owner: "[email protected]",+ detail: agentDetail({+ model: "claude-sonnet-4.5",+ calls24h: 802,+ errorRate: 0.012,+ confidence: 0.941,+ escalations24h: 7,+ assignedPipelines: ["KYC Onboarding"],+ scopes: ["documents:read", "pipelines:invoke", "pii:read"],+ }),+ },+ {+ id: "src-api-1",+ name: "Acme Production",+ type: "apiclient",+ status: "active",+ docs24h: 2940,+ docs30d: 71200,+ lastEvent: "11s ago",+ owner: "[email protected]",+ detail: {+ kind: "apiclient",+ maskedKey: "sk_live_••••••••••••4f9a",+ rateLimit: "600 req/min",+ rateUsedPct: 0.42,+ endpoints: [+ { method: "POST", path: "/v1/extract", calls24h: 1820 },+ { method: "POST", path: "/v1/redact", calls24h: 740 },+ { method: "GET", path: "/v1/documents/{id}", calls24h: 380 },+ ],+ createdBy: "[email protected]",+ lastRotated: "23 days ago",+ },+ },+ {+ id: "src-webhook-1",+ name: "Slack delivery hook",+ type: "webhook",+ status: "active",+ docs24h: 96,+ docs30d: 2310,+ lastEvent: "9m ago",+ owner: "[email protected]",+ detail: {+ kind: "webhook",+ url: "https://hooks.acme.com/stirling/ingest",+ authType: "HMAC-SHA256",+ successRate: 0.991,+ retries24h: 3,+ recentDeliveries: [+ { event: "document.processed", status: 200, time: "9m ago" },+ { event: "pipeline.completed", status: 200, time: "22m ago" },+ { event: "document.processed", status: 503, time: "1h ago" },+ ],+ },+ },+ {+ id: "src-webhook-err",+ name: "Legacy ERP callback",+ type: "webhook",+ status: "error",+ docs24h: 41,+ docs30d: 1180,+ lastEvent: "2m ago",+ owner: "[email protected]",+ // Endpoint is rejecting most deliveries — success rate below the 95% floor+ // drives the danger tone and the retry count climbs.+ detail: {+ kind: "webhook",+ url: "https://erp.acme.com/inbound/stirling",+ authType: "Basic",+ successRate: 0.72,+ retries24h: 58,+ recentDeliveries: [+ { event: "document.processed", status: 502, time: "2m ago" },+ { event: "document.processed", status: 502, time: "5m ago" },+ { event: "pipeline.completed", status: 200, time: "9m ago" },+ ],+ },+ },+ {+ id: "src-batch-1",+ name: "Nightly archive reprocess",+ type: "batch",+ status: "idle",+ docs24h: 0,+ docs30d: 48600,+ lastEvent: "8h ago",+ owner: "[email protected]",+ detail: {+ kind: "basic",+ rows: [+ { label: "Schedule", value: "Daily · 02:00 UTC" },+ { label: "Last run", value: "1,620 docs · 0 errors" },+ { label: "Source bucket", value: "s3://acme-archive/inbound" },+ { label: "Pipeline", value: "OCR & Index" },+ ],+ },+ },+];++const ENTERPRISE_EXTRA: Source[] = [+ {+ id: "src-connector-1",+ name: "SharePoint — Legal",+ type: "connector",+ status: "active",+ docs24h: 1840,+ docs30d: 44900,+ lastEvent: "2m ago",+ owner: "[email protected]",+ detail: {+ kind: "basic",+ rows: [+ { label: "Provider", value: "Microsoft SharePoint" },+ { label: "Sync", value: "Delta · every 5 min" },+ { label: "Watched library", value: "Contracts / Inbound" },+ { label: "Auth", value: "Azure AD app registration" },+ ],+ },+ },+ {+ id: "src-connector-2",+ name: "S3 — claims-intake",+ type: "connector",+ status: "active",+ docs24h: 5210,+ docs30d: 128400,+ lastEvent: "40s ago",+ owner: "[email protected]",+ detail: {+ kind: "basic",+ rows: [+ { label: "Provider", value: "AWS S3" },+ { label: "Bucket", value: "s3://acme-claims/intake" },+ { label: "Notification", value: "EventBridge → SQS" },+ { label: "Region", value: "us-east-1" },+ ],+ },+ },+ {+ id: "src-email-1",+ name: "[email protected]",+ type: "email",+ status: "active",+ docs24h: 318,+ docs30d: 7640,+ lastEvent: "14m ago",+ owner: "[email protected]",+ detail: {+ kind: "basic",+ rows: [+ { label: "Inbox", value: "[email protected]" },+ { label: "Attachments", value: "PDF only · max 25 MB" },+ { label: "Pipeline", value: "Invoice v3" },+ { label: "Spam filter", value: "Enabled · DKIM verified" },+ ],+ },+ },+ {+ id: "src-desktop-1",+ name: "Stirling Desktop — Reviewer pool",+ type: "desktop",+ status: "idle",+ docs24h: 47,+ docs30d: 1290,+ lastEvent: "3h ago",+ owner: "[email protected]",+ detail: {+ kind: "basic",+ rows: [+ { label: "App version", value: "Desktop 2.7.1" },+ { label: "Seats", value: "12 active devices" },+ { label: "Default pipeline", value: "Manual Review" },+ { label: "Offline queue", value: "Enabled" },+ ],+ },+ },+ {+ id: "src-agent-4",+ name: "Compliance Sweep",+ type: "agent",+ status: "active",+ docs24h: 2105,+ docs30d: 52300,+ lastEvent: "18s ago",+ owner: "[email protected]",+ detail: agentDetail({+ model: "claude-opus-4.1",+ calls24h: 2180,+ errorRate: 0.008,+ confidence: 0.957,+ escalations24h: 19,+ assignedPipelines: ["COI Compliance", "PII Sweep", "Retention Policy"],+ scopes: ["documents:read", "pipelines:invoke", "pii:read", "audit:write"],+ }),+ },+ {+ id: "src-webhook-2",+ name: "Datadog events hook",+ type: "webhook",+ status: "active",+ docs24h: 410,+ docs30d: 9800,+ lastEvent: "1m ago",+ owner: "[email protected]",+ detail: {+ kind: "webhook",+ url: "https://intake.datadoghq.com/stirling/events",+ authType: "Bearer token",+ successRate: 0.999,+ retries24h: 0,+ recentDeliveries: [+ { event: "pipeline.completed", status: 202, time: "1m ago" },+ { event: "agent.escalated", status: 202, time: "12m ago" },+ { event: "pipeline.failed", status: 202, time: "47m ago" },+ ],+ },+ },+ {+ id: "src-api-revoked",+ name: "Legacy ETL (revoked)",+ type: "apiclient",+ status: "error",+ docs24h: 0,+ docs30d: 3120,+ lastEvent: "5d ago",+ owner: "[email protected]",+ // Key was revoked after a leak; calls now 401 so 24h traffic is zero while+ // the 30d window still shows the pre-revocation volume.+ detail: {+ kind: "apiclient",+ maskedKey: "sk_live_••••••••••••0000 (revoked)",+ rateLimit: "300 req/min",+ rateUsedPct: 0,+ endpoints: [+ { method: "POST", path: "/v1/extract", calls24h: 0 },+ { method: "POST", path: "/v1/redact", calls24h: 0 },+ ],+ createdBy: "[email protected]",+ lastRotated: "never",+ },+ },+ {+ id: "src-api-2",+ name: "Partner Integration (read-only)",+ type: "apiclient",+ status: "paused",+ docs24h: 0,+ docs30d: 14200,+ lastEvent: "2d ago",+ owner: "[email protected]",+ detail: {+ kind: "apiclient",+ maskedKey: "sk_live_••••••••••••91c2",+ rateLimit: "120 req/min",+ rateUsedPct: 0,+ endpoints: [+ { method: "GET", path: "/v1/documents/{id}", calls24h: 0 },+ { method: "GET", path: "/v1/pipelines", calls24h: 0 },+ ],+ createdBy: "[email protected]",+ lastRotated: "61 days ago",+ },+ },+];++/** Sources for a given tier. Free is intentionally empty. */+export function sourcesFor(tier: Tier): Source[] {+ if (tier === "free") return [];+ if (tier === "enterprise") return [...PRO_SOURCES, ...ENTERPRISE_EXTRA];+ return PRO_SOURCES;+}++/**+ * KPI strip values. Pro sits below the eval pass-rate target, enterprise above —+ * the delta/direction differences let a dev see tier variation at a glance.+ */+export function kpisFor(tier: Tier): SourcesKpi[] {+ if (tier === "free") {+ return [+ { value: 0, description: "Connect a source to begin" },+ { value: 0 },+ { value: "—" },+ { value: 0 },+ ];+ }++ const sources = sourcesFor(tier);+ const agents = sources.filter((s) => s.type === "agent");+ const agentsActive = agents.filter((s) => s.status === "active").length;+ const docs24h = sources.reduce((sum, s) => sum + s.docs24h, 0);++ if (tier === "enterprise") {+ return [+ {+ value: agentsActive,+ delta: 0.25,+ description: `${agents.length} total`,+ },+ { value: 42, delta: 0.09, description: "Eval scenarios" },+ { value: "96.4%", deltaDirection: "up", delta: 0.012 },+ { value: docs24h.toLocaleString(), delta: 0.14 },+ ];+ }++ // pro+ return [+ { value: agentsActive, delta: 0.5, description: `${agents.length} total` },+ { value: 18, delta: 0.2, description: "Eval scenarios" },+ { value: "91.2%", deltaDirection: "flat", delta: 0 },+ { value: docs24h.toLocaleString(), delta: 0.16 },+ ];+}++export function buildSourcesResponse(tier: Tier): SourcesResponse {+ return { kpis: kpisFor(tier), sources: sourcesFor(tier) };+}diff --git a/frontend/portal/src/mocks/usage.ts b/frontend/portal/src/mocks/usage.tsnew file mode 100644index 0000000000..8fb6068549--- /dev/null+++ b/frontend/portal/src/mocks/usage.ts@@ -0,0 +1,341 @@+/**+ * Usage & Billing fixtures and the types api/usage.ts shares with them.+ * api/usage.ts imports the types; the MSW handlers in mocks/handlers/usage.ts+ * serve this fixture data over the intercepted httpJson() calls. Components+ * never reach into this module directly.+ *+ * Once a real billing backend exists, the MSW handlers stop being registered+ * and these fixtures can be deleted (or kept as test seeds).+ */++import type { Tier } from "@portal/contexts/TierContext";+import {+ buildUsageSeries,+ buildUsageSeriesResponse,+ type UsageSeriesResponse,+} from "@portal/mocks/home";++export type { UsagePoint, UsageSeriesResponse } from "@portal/mocks/home";++/** Per-doc rate charged once the free cap is exceeded (pay-as-you-go). */+export const OVERAGE_RATE = 0.05;++/** Documents included before overage / cap kicks in, per tier. */+export const TIER_DOC_CAP: Record<Tier, number> = {+ free: 500,+ pro: 25_000,+ enterprise: 2_000_000,+};++/* ──────────────────────────────────────────────────────────────────────── */+/* Billing summary (KPI strip + plan card) */+/* ──────────────────────────────────────────────────────────────────────── */++export interface BillingSummary {+ tier: Tier;+ /** Human plan name shown on the current-plan card. */+ planName: string;+ /** Docs processed in the current billing period. */+ docsThisPeriod: number;+ /** Included docs before overage / cap. */+ includedDocs: number;+ /** Cost accrued this month, in USD. */+ costThisMonth: number;+ /** Overage docs past the included cap (0 when under). */+ overageDocs: number;+ /** Overage cost this month, in USD. */+ overageCost: number;+ /** Per-doc overage rate, in USD. */+ overageRate: number;+ /** Fixed monthly platform fee, in USD (0 for free / usage-only). */+ monthlyFee: number;+ /** ISO date the next invoice closes. */+ nextBillingDate: string;+ /** Optional user-set hard spend cap for the month, in USD. */+ spendCap: number | null;+ /** True when the free plan's doc cap has been reached. */+ capReached: boolean;+}++/** Builds a deterministic billing summary for a tier from the usage series. */+export function buildBillingSummary(tier: Tier): BillingSummary {+ const docs30d = buildUsageSeries().reduce((sum, p) => sum + p.value, 0);+ const included = TIER_DOC_CAP[tier];+ const nextBillingDate = nextMonthFirst();++ if (tier === "free") {+ // Free is gated, not metered — show progress toward the hard cap. 463/500+ // sits in the "approaching cap" band that drives the upgrade nudge.+ const docs = 463;+ return {+ tier,+ planName: "Free",+ docsThisPeriod: docs,+ includedDocs: included,+ costThisMonth: 0,+ overageDocs: 0,+ overageCost: 0,+ overageRate: OVERAGE_RATE,+ monthlyFee: 0,+ nextBillingDate,+ spendCap: null,+ capReached: docs >= included,+ };+ }++ if (tier === "enterprise") {+ // Committed-volume contract — usage sits comfortably inside the commit.+ return {+ tier,+ planName: "Enterprise (committed)",+ docsThisPeriod: docs30d,+ includedDocs: included,+ costThisMonth: 18_000,+ overageDocs: 0,+ overageCost: 0,+ overageRate: 0.018,+ monthlyFee: 18_000,+ nextBillingDate,+ spendCap: null,+ capReached: false,+ };+ }++ // Pro: pay-as-you-go with a small platform fee + metered overage.+ const monthlyFee = 49;+ const overageDocs = Math.max(0, docs30d - included);+ const overageCost = +(overageDocs * OVERAGE_RATE).toFixed(2);+ return {+ tier,+ planName: "Pay-as-you-go",+ docsThisPeriod: docs30d,+ includedDocs: included,+ costThisMonth: +(monthlyFee + overageCost).toFixed(2),+ overageDocs,+ overageCost,+ overageRate: OVERAGE_RATE,+ monthlyFee,+ nextBillingDate,+ spendCap: 2_500,+ capReached: false,+ };+}++/** First day of next month, ISO (YYYY-MM-DD) — the next invoice close date. */+function nextMonthFirst(): string {+ const now = new Date();+ const next = new Date(now.getFullYear(), now.getMonth() + 1, 1);+ return next.toISOString().slice(0, 10);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Plan catalogue (current + available plan cards) */+/* ──────────────────────────────────────────────────────────────────────── */++export interface PlanOption {+ tier: Tier;+ name: string;+ /** Headline price line, e.g. "$0" or "$0.05 / doc". */+ price: string;+ /** Cadence sub-line under the price, e.g. "forever" or "+ $49/mo platform". */+ priceCadence: string;+ /** One-line positioning blurb. */+ blurb: string;+ /** Bullet feature list. */+ features: string[];+}++export const PLAN_OPTIONS: PlanOption[] = [+ {+ tier: "free",+ name: "Free",+ price: "$0",+ priceCadence: "forever",+ blurb: "Kick the tyres on a single project.",+ features: [+ "500 docs / month",+ "All single operations",+ "1 pipeline · 1 agent",+ "Community support",+ ],+ },+ {+ tier: "pro",+ name: "Pay-as-you-go",+ price: "$0.05",+ priceCadence: "per doc · + $49/mo platform",+ blurb: "Scale with usage, only pay for what you process.",+ features: [+ "25,000 docs included",+ "Unlimited pipelines & agents",+ "Overage at $0.05 / doc",+ "Email support · 99.9% SLA",+ ],+ },+ {+ tier: "enterprise",+ name: "Enterprise",+ price: "Custom",+ priceCadence: "committed annual volume",+ blurb: "Committed volume, bespoke terms, dedicated regions.",+ features: [+ "Committed-volume pricing",+ "Dedicated & on-prem regions",+ "SSO · audit log export · DPA",+ "Named CSM · 99.99% SLA",+ ],+ },+];++/* ──────────────────────────────────────────────────────────────────────── */+/* Billing history table */+/* ──────────────────────────────────────────────────────────────────────── */++export type InvoiceStatus = "paid" | "due" | "pending" | "refunded";++export interface BillingHistoryRow {+ id: string;+ /** ISO date the line item posted. */+ date: string;+ description: string;+ /** Docs attributed to the line item (0 for flat fees / credits). */+ docs: number;+ /** Amount in USD; negative for credits / refunds. */+ amount: number;+ status: InvoiceStatus;+}++export function buildBillingHistory(tier: Tier): BillingHistoryRow[] {+ if (tier === "free") {+ // Free has no charges — just the running tally line.+ return [+ {+ id: "bh-free-1",+ date: monthsAgo(0),+ description: "Free plan usage · 463 / 500 docs",+ docs: 463,+ amount: 0,+ status: "pending",+ },+ {+ id: "bh-free-2",+ date: monthsAgo(1),+ description: "Free plan usage · 500 / 500 docs (capped)",+ docs: 500,+ amount: 0,+ status: "paid",+ },+ ];+ }++ if (tier === "enterprise") {+ return [+ {+ id: "bh-ent-1",+ date: monthsAgo(0),+ description: "Committed volume · annual contract (monthly draw)",+ docs: 1_240_511,+ amount: 18_000,+ status: "pending",+ },+ {+ id: "bh-ent-2",+ date: monthsAgo(1),+ description: "Committed volume · annual contract (monthly draw)",+ docs: 1_188_204,+ amount: 18_000,+ status: "paid",+ },+ {+ id: "bh-ent-3",+ date: monthsAgo(1),+ description: "Dedicated region · ap-southeast-1 provisioning",+ docs: 0,+ amount: 4_500,+ status: "paid",+ },+ {+ id: "bh-ent-4",+ date: monthsAgo(2),+ description: "Committed volume · annual contract (monthly draw)",+ docs: 1_092_876,+ amount: 18_000,+ status: "paid",+ },+ {+ id: "bh-ent-5",+ date: monthsAgo(3),+ description: "Overage credit · region migration goodwill",+ docs: 0,+ amount: -1_200,+ status: "refunded",+ },+ ];+ }++ // Pro: platform fee + metered overage each cycle.+ const docs30d = buildUsageSeries().reduce((sum, p) => sum + p.value, 0);+ const overage = Math.max(0, docs30d - TIER_DOC_CAP.pro);+ return [+ {+ id: "bh-pro-1",+ date: monthsAgo(0),+ description: "Platform fee · current cycle",+ docs: 0,+ amount: 49,+ status: "due",+ },+ {+ id: "bh-pro-2",+ date: monthsAgo(0),+ description: `Document overage · ${overage.toLocaleString()} docs @ $0.05`,+ docs: overage,+ amount: +(overage * OVERAGE_RATE).toFixed(2),+ status: "due",+ },+ {+ id: "bh-pro-3",+ date: monthsAgo(1),+ description: "Platform fee · last cycle",+ docs: 0,+ amount: 49,+ status: "paid",+ },+ {+ id: "bh-pro-4",+ date: monthsAgo(1),+ description: "Document overage · 31,402 docs @ $0.05",+ docs: 31_402,+ amount: 1_570.1,+ status: "paid",+ },+ {+ id: "bh-pro-5",+ date: monthsAgo(2),+ description: "Platform fee · prior cycle",+ docs: 0,+ amount: 49,+ status: "paid",+ },+ {+ id: "bh-pro-6",+ date: monthsAgo(2),+ description: "Document overage · 18,945 docs @ $0.05",+ docs: 18_945,+ amount: 947.25,+ status: "paid",+ },+ ];+}++/** N whole months back from today, on the 1st, ISO (YYYY-MM-DD). */+function monthsAgo(n: number): string {+ const now = new Date();+ const d = new Date(now.getFullYear(), now.getMonth() - n, 1);+ return d.toISOString().slice(0, 10);+}++/** Full usage payload for the 30-day chart — the same series Home charts. */+export function buildUsagePayload(): UsageSeriesResponse {+ return buildUsageSeriesResponse();+}diff --git a/frontend/portal/src/views/DeveloperDocs.css b/frontend/portal/src/views/DeveloperDocs.cssnew file mode 100644index 0000000000..e023afeb69--- /dev/null+++ b/frontend/portal/src/views/DeveloperDocs.css@@ -0,0 +1,525 @@+.portal-docs {+ display: grid;+ grid-template-columns: 15rem minmax(0, 1fr);+ gap: 2rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+ align-items: start;+}++@media (max-width: 60rem) {+ .portal-docs {+ grid-template-columns: 1fr;+ gap: 1.25rem;+ }+}++/* ── Left nav ──────────────────────────────────────────────────────────── */++.portal-docs__sidebar {+ position: sticky;+ top: 1.5rem;+ align-self: start;+}++@media (max-width: 60rem) {+ .portal-docs__sidebar {+ position: static;+ }+}++.portal-docs__nav {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+}++.portal-docs__nav-group {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}++.portal-docs__nav-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.6875rem;+ font-weight: 700;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--color-text-4);+ padding: 0 0.5rem;+}++.portal-docs__nav-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.125rem;+ height: 1.125rem;+ font-size: 0.6875rem;+ border-radius: var(--radius-sm);+ background: var(--color-bg-subtle);+ color: var(--color-text-3);+}++.portal-docs__nav-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.0625rem;+}++.portal-docs__nav-link {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ width: 100%;+ padding: 0.375rem 0.5rem;+ border: none;+ background: transparent;+ border-radius: var(--radius-md);+ font-size: 0.8125rem;+ color: var(--color-text-3);+ cursor: pointer;+ text-align: left;+ transition:+ background var(--motion-fast),+ color var(--motion-fast);+}++.portal-docs__nav-link:hover {+ background: var(--color-bg-hover);+ color: var(--color-text-1);+}++.portal-docs__nav-link.is-active {+ background: var(--color-blue-light);+ color: var(--color-blue);+ font-weight: 600;+}++.portal-docs__nav-label {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* ── Content shell ─────────────────────────────────────────────────────── */++.portal-docs__content {+ min-width: 0;+}++.portal-docs__section {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-docs__section-eyebrow {+ font-size: 0.6875rem;+ font-weight: 700;+ letter-spacing: 0.08em;+ color: var(--color-blue);+}++.portal-docs__section-title {+ margin: 0;+ font-size: 1.75rem;+ font-weight: 700;+ line-height: 1.15;+ color: var(--color-text-1);+}++.portal-docs__section-lead {+ margin: 0;+ max-width: 46rem;+ font-size: 0.9375rem;+ line-height: 1.6;+ color: var(--color-text-3);+}++.portal-docs__callout {+ font-size: 0.875rem;+ line-height: 1.55;+ color: var(--color-text-2);+}++.portal-docs__callout code {+ font-family: var(--font-mono, monospace);+ font-size: 0.8125rem;+ background: var(--color-bg-subtle);+ padding: 0.0625rem 0.3125rem;+ border-radius: var(--radius-sm);+}++/* ── Quickstart steps ──────────────────────────────────────────────────── */++.portal-docs__steps {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 1.5rem;+}++.portal-docs__step {+ display: grid;+ grid-template-columns: 1.75rem minmax(0, 1fr);+ gap: 1rem;+}++.portal-docs__step-mark {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: var(--radius-pill);+ background: var(--color-blue);+ color: var(--color-text-on-accent);+ font-size: 0.8125rem;+ font-weight: 700;+}++.portal-docs__step-body {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+ min-width: 0;+}++.portal-docs__step-body h3 {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-docs__step-body p {+ margin: 0;+ font-size: 0.875rem;+ line-height: 1.55;+ color: var(--color-text-3);+}++.portal-docs__snippet {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++/* ── Auth ──────────────────────────────────────────────────────────────── */++.portal-docs__keytable {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.portal-docs__keyrow {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ font-size: 0.875rem;+ color: var(--color-text-3);+}++/* ── Rate limits ───────────────────────────────────────────────────────── */++.portal-docs__limits {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.75rem;+}++@media (max-width: 40rem) {+ .portal-docs__limits {+ grid-template-columns: 1fr;+ }+}++.portal-docs__limit-label {+ font-size: 0.75rem;+ color: var(--color-text-4);+ margin-bottom: 0.25rem;+}++.portal-docs__limit-value {+ font-size: 1.25rem;+ font-weight: 700;+ color: var(--color-text-1);+}++/* ── Endpoint reference ────────────────────────────────────────────────── */++.portal-docs__endpoints {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+}++.portal-docs__endpoint-group {+ display: flex;+ flex-direction: column;+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-lg);+ overflow: hidden;+}++.portal-docs__endpoint-grouphead {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.625rem 0.875rem;+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+ background: var(--color-bg-subtle);+ border-bottom: 1px solid var(--color-border-light);+}++.portal-docs__endpoint-dot {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 50%;+}++.portal-docs__endpoint-row {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding: 0.5rem 0.875rem;+ border-top: 1px solid var(--color-border-light);+ font-size: 0.8125rem;+}++.portal-docs__endpoint-row:first-of-type {+ border-top: none;+}++.portal-docs__endpoint-path {+ font-family: var(--font-mono, monospace);+ font-size: 0.8125rem;+ color: var(--color-text-1);+ min-width: 11rem;+}++.portal-docs__endpoint-name {+ color: var(--color-text-3);+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.portal-docs__endpoint-fields {+ font-size: 0.75rem;+ color: var(--color-text-4);+ white-space: nowrap;+}++@media (max-width: 40rem) {+ .portal-docs__endpoint-name {+ display: none;+ }+}++/* ── Errors ────────────────────────────────────────────────────────────── */++.portal-docs__errors {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-docs__error-row {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ font-size: 0.875rem;+ color: var(--color-text-3);+}++/* ── SDK grid ──────────────────────────────────────────────────────────── */++.portal-docs__sdk-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.875rem;+}++@media (max-width: 48rem) {+ .portal-docs__sdk-grid {+ grid-template-columns: 1fr;+ }+}++.portal-docs__sdk-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin-bottom: 0.625rem;+}++.portal-docs__sdk-icon {+ font-size: 1.125rem;+}++.portal-docs__sdk-name {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+ flex: 1;+}++/* ── Components ────────────────────────────────────────────────────────── */++.portal-docs__component-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.875rem;+}++@media (max-width: 48rem) {+ .portal-docs__component-grid {+ grid-template-columns: 1fr;+ }+}++.portal-docs__component-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+}++.portal-docs__component-name {+ font-family: var(--font-mono, monospace);+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-purple);+}++.portal-docs__component-blurb {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+}++/* ── Playbooks ─────────────────────────────────────────────────────────── */++.portal-docs__playbook-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.875rem;+}++@media (max-width: 48rem) {+ .portal-docs__playbook-grid {+ grid-template-columns: 1fr;+ }+}++.portal-docs__playbook-title {+ margin: 0 0 0.375rem;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-docs__playbook-blurb {+ margin: 0 0 0.875rem;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+}++.portal-docs__playbook-flow {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 0.375rem;+ margin-bottom: 0.875rem;+}++.portal-docs__playbook-step {+ display: inline-flex;+ align-items: center;+ gap: 0.375rem;+}++.portal-docs__playbook-arrow {+ color: var(--color-text-4);+ font-size: 0.75rem;+}++/* ── Skills ────────────────────────────────────────────────────────────── */++.portal-docs__skill-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.875rem;+}++@media (max-width: 60rem) {+ .portal-docs__skill-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}++@media (max-width: 40rem) {+ .portal-docs__skill-grid {+ grid-template-columns: 1fr;+ }+}++.portal-docs__skill-head {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+}++.portal-docs__skill-glyph {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.5rem;+ height: 1.5rem;+ border-radius: var(--radius-sm);+ background: var(--color-purple-light);+ color: var(--color-purple);+ font-size: 0.8125rem;+}++.portal-docs__skill-name {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-docs__skill-blurb {+ margin: 0 0 0.625rem;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+}++.portal-docs__skill-ops {+ font-family: var(--font-mono, monospace);+ font-size: 0.75rem;+ color: var(--color-text-4);+}diff --git a/frontend/portal/src/views/DeveloperDocs.tsx b/frontend/portal/src/views/DeveloperDocs.tsxnew file mode 100644index 0000000000..e7758a9440--- /dev/null+++ b/frontend/portal/src/views/DeveloperDocs.tsx@@ -0,0 +1,95 @@+import { useState } from "react";+import { EmptyState } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchDocsContent,+ fetchDocsNav,+ type DocsContent,+ type DocsNavSection,+} from "@portal/api/docs";+import { DocsNav, DocsNavSkeleton } from "@portal/components/docs/DocsNav";+import { GettingStartedSection } from "@portal/components/docs/GettingStartedSection";+import { AuthenticationSection } from "@portal/components/docs/AuthenticationSection";+import { RateLimitsSection } from "@portal/components/docs/RateLimitsSection";+import { EndpointReferenceSection } from "@portal/components/docs/EndpointReferenceSection";+import { ErrorsSection } from "@portal/components/docs/ErrorsSection";+import { WebhooksSection } from "@portal/components/docs/WebhooksSection";+import { SdksSection } from "@portal/components/docs/SdksSection";+import { ComponentsSection } from "@portal/components/docs/ComponentsSection";+import { PlaybooksSection } from "@portal/components/docs/PlaybooksSection";+import { SkillsSection } from "@portal/components/docs/SkillsSection";+import "@portal/views/DeveloperDocs.css";++/** Renders the content pane for the active nav leaf against fetched content. */+function DocsContentPane({+ active,+ content,+}: {+ active: string;+ content: DocsContent;+}) {+ switch (active) {+ case "authentication":+ return <AuthenticationSection />;+ case "rate-limits":+ return <RateLimitsSection rateLimit={content.rateLimit} />;+ case "endpoints":+ return <EndpointReferenceSection />;+ case "errors":+ return <ErrorsSection errors={content.errors} />;+ case "webhooks":+ return <WebhooksSection />;+ case "sdk-overview":+ return <SdksSection sdks={content.sdks} />;+ case "component-library":+ return <ComponentsSection components={content.components} />;+ case "recipes":+ return <PlaybooksSection playbooks={content.playbooks} />;+ case "skill-catalog":+ return <SkillsSection skills={content.skills} />;+ default:+ return (+ <GettingStartedSection+ samples={content.quickstartSamples}+ response={content.quickstartResponse}+ />+ );+ }+}++export function DeveloperDocs() {+ const { tier } = useTier();+ const [active, setActive] = useState("quickstart");++ const navState = useAsync<DocsNavSection[]>(() => fetchDocsNav(), []);+ const { data: nav } = navState;+ const { isLoading, isEmpty } = useSectionFlags(navState);++ const { data: content } = useAsync<DocsContent>(+ () => fetchDocsContent(tier),+ [tier],+ );++ return (+ <div className="portal-docs">+ <aside className="portal-docs__sidebar">+ {isLoading && <DocsNavSkeleton />}+ {isEmpty && (+ <EmptyState+ size="compact"+ title="Docs unavailable"+ description="The documentation index could not be loaded."+ />+ )}+ {nav && nav.length > 0 && (+ <DocsNav sections={nav} active={active} onSelect={setActive} />+ )}+ </aside>++ <main className="portal-docs__content">+ {content && <DocsContentPane active={active} content={content} />}+ </main>+ </div>+ );+}diff --git a/frontend/portal/src/views/Home.css b/frontend/portal/src/views/Home.cssindex 0f7b435aa3..c2f8bf6f23 100644--- a/frontend/portal/src/views/Home.css+++ b/frontend/portal/src/views/Home.css@@ -42,18 +42,7 @@color: var(--color-text-3);}-/* Metric strip */-.portal-home__metrics {- display: grid;- grid-template-columns: repeat(4, 1fr);- gap: 0.75rem;-}--@media (max-width: 50rem) {- .portal-home__metrics {- grid-template-columns: repeat(2, 1fr);- }-}+/* Metric strip now uses the shared <MetricStrip>. *//* Two-column dashboard row (activity + quick actions) */.portal-home__row {diff --git a/frontend/portal/src/views/Home.tsx b/frontend/portal/src/views/Home.tsxindex 9ccf7ea081..d3da4ee073 100644--- a/frontend/portal/src/views/Home.tsx+++ b/frontend/portal/src/views/Home.tsx@@ -4,6 +4,7 @@ import {Card,EmptyState,MetricCard,+ MetricStrip,Skeleton,StatusBadge,} from "@shared/components";@@ -365,7 +366,7 @@ function TierKpiStrip() {);return (- <section className="portal-home__metrics">+ <MetricStrip>{labels.map((spec, i) => {// useAsync keeps the previous tier's data during a refetch; ignore it// while loading so the new labels never pair with stale values.@@ -381,7 +382,7 @@ function TierKpiStrip() {/>);})}- </section>+ </MetricStrip>);}diff --git a/frontend/portal/src/views/Infrastructure.css b/frontend/portal/src/views/Infrastructure.cssnew file mode 100644index 0000000000..0e9c7c7f58--- /dev/null+++ b/frontend/portal/src/views/Infrastructure.css@@ -0,0 +1,428 @@+.portal-infra {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* View header */+.portal-infra__head {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+}++.portal-infra__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-infra__sub {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--color-text-4);+ max-width: 48rem;+}++.portal-infra__panel {+ display: flex;+ flex-direction: column;+}++/* Generic vertical stack used inside every tab */+.portal-infra__stack {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+}++.portal-infra__bar {+ display: flex;+ align-items: flex-end;+ justify-content: space-between;+ gap: 1rem;+}++/* Section headers */+.portal-infra__section-head {+ margin-bottom: 0.625rem;+}++.portal-infra__section-title {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-infra__section-sub {+ margin: 0.125rem 0 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* Two-column split */+.portal-infra__split {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 1rem;+ align-items: start;+}++@media (max-width: 60rem) {+ .portal-infra__split {+ grid-template-columns: 1fr;+ }+}++/* Shared cell styles */+.portal-infra__cell-stack {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+}++.portal-infra__cell-strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-infra__cell-code {+ font-family: var(--font-mono);+ font-size: 0.6875rem;+ color: var(--color-text-3);+ background: var(--color-bg-code);+ padding: 0.0625rem 0.3125rem;+ border-radius: var(--radius-sm);+ width: fit-content;+}++.portal-infra__mono {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-2);+}++.portal-infra__muted {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* Region load cell */+.portal-infra__load {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-infra__load-pct {+ font-family: var(--font-mono);+ font-size: 0.6875rem;+ color: var(--color-text-3);+ min-width: 2.25rem;+ text-align: right;+}++/* Metric strip (audit) */+.portal-infra__metrics {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.75rem;+}++@media (max-width: 50rem) {+ .portal-infra__metrics {+ grid-template-columns: repeat(2, 1fr);+ }+}++/* ── API keys ───────────────────────────────────────────────────────────── */+.portal-infra__keys {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.portal-infra__key {+ padding: 0 !important;+ overflow: hidden;+}++.portal-infra__key-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ width: 100%;+ padding: 0.875rem 1.125rem;+ background: transparent;+ text-align: left;+ transition: background var(--motion-fast);+}++.portal-infra__key-head:hover {+ background: var(--color-bg-hover);+}++.portal-infra__key-id {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-infra__key-head-right {+ display: flex;+ align-items: center;+ gap: 0.75rem;+}++.portal-infra__chevron {+ font-size: 1.125rem;+ color: var(--color-text-5);+ transition: transform var(--motion-fast);+ line-height: 1;+}++.portal-infra__chevron.is-open {+ transform: rotate(90deg);+}++.portal-infra__key-body {+ padding: 0 1.125rem 1.125rem;+ border-top: 1px solid var(--color-border-light);+}++.portal-infra__kv {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.875rem 1.25rem;+ margin: 1rem 0 0;+}++@media (max-width: 48rem) {+ .portal-infra__kv {+ grid-template-columns: repeat(2, 1fr);+ }+}++.portal-infra__kv-wide {+ grid-column: 1 / -1;+}++.portal-infra__kv dt {+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-text-5);+ margin-bottom: 0.25rem;+}++.portal-infra__kv dd {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-infra__chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++/* Modal form */+.portal-infra__form {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-infra__perm-row {+ display: flex;+ gap: 1.25rem;+ flex-wrap: wrap;+}++.portal-infra__modal-actions {+ display: flex;+ justify-content: flex-end;+ gap: 0.625rem;+}++/* ── Security ───────────────────────────────────────────────────────────── */+.portal-infra__banner {+ margin-top: 1rem;+}++.portal-infra__certs {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.75rem;+}++@media (max-width: 60rem) {+ .portal-infra__certs {+ grid-template-columns: repeat(2, 1fr);+ }+}++.portal-infra__cert-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-bottom: 0.375rem;+}++.portal-infra__cert-detail {+ margin: 0;+ font-size: 0.6875rem;+ color: var(--color-text-4);+ line-height: 1.4;+}++/* ── Storage ────────────────────────────────────────────────────────────── */+.portal-infra__usage-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ margin-bottom: 0.625rem;+}++.portal-infra__usage-value {+ font-size: 1.25rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-infra__usage-value .portal-infra__muted {+ font-size: 0.875rem;+ font-weight: 400;+}++.portal-infra__providers {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-infra__provider {+ display: grid;+ grid-template-columns: auto 1fr auto;+ align-items: center;+ gap: 0.75rem;+ padding: 0.625rem 0.75rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-infra__provider-glyph {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: var(--radius-md);+ background: var(--color-blue-light);+ color: var(--color-blue);+ font-size: 0.875rem;+}++.portal-infra__provider-text {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.portal-infra__provider-meta {+ display: flex;+ align-items: center;+ gap: 0.625rem;+}++/* Lifecycle timeline */+.portal-infra__lifecycle {+ display: flex;+ align-items: stretch;+ gap: 0.5rem;+ margin-top: 1rem;+}++.portal-infra__lifecycle-stage {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ padding: 0.625rem 0.75rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-infra__lifecycle-stage.is-active {+ background: var(--color-green-light);+ border-color: var(--color-green-border);+}++.portal-infra__lifecycle-dot {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 50%;+ background: var(--color-text-5);+}++.portal-infra__lifecycle-stage.is-active .portal-infra__lifecycle-dot {+ background: var(--color-green);+}++.portal-infra__lifecycle-label {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-infra__lifecycle-arrow {+ display: flex;+ align-items: center;+ color: var(--color-text-5);+ font-size: 0.875rem;+}++/* ── Audit ──────────────────────────────────────────────────────────────── */+.portal-infra__event {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-infra__event span {+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++/* ── Table skeleton ─────────────────────────────────────────────────────── */+.portal-infra__table-skel {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+ padding: 1rem 1.125rem;+}++.portal-infra__table-skel-row {+ display: grid;+ grid-auto-flow: column;+ grid-auto-columns: 1fr;+ gap: 1rem;+ align-items: center;+}diff --git a/frontend/portal/src/views/Infrastructure.tsx b/frontend/portal/src/views/Infrastructure.tsxnew file mode 100644index 0000000000..a9712d30b7--- /dev/null+++ b/frontend/portal/src/views/Infrastructure.tsx@@ -0,0 +1,50 @@+import { useState } from "react";+import { Tabs, type TabItem } from "@shared/components";+import { DeploymentsTab } from "@portal/components/infrastructure/DeploymentsTab";+import { ApiKeysTab } from "@portal/components/infrastructure/ApiKeysTab";+import { SecurityTab } from "@portal/components/infrastructure/SecurityTab";+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";++const TABS: TabItem<InfraTab>[] = [+ { key: "deployments", label: "Deployments" },+ { key: "api-keys", label: "API Keys" },+ { key: "security", label: "Security" },+ { key: "storage", label: "Storage" },+ { key: "audit", label: "Audit Logs" },+];++export function Infrastructure() {+ const [tab, setTab] = useState<InfraTab>("deployments");++ 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>+ </header>++ <Tabs<InfraTab>+ items={TABS}+ activeKey={tab}+ onChange={setTab}+ variant="underline"+ ariaLabel="Infrastructure sections"+ />++ <div className="portal-infra__panel">+ {tab === "deployments" && <DeploymentsTab />}+ {tab === "api-keys" && <ApiKeysTab />}+ {tab === "security" && <SecurityTab />}+ {tab === "storage" && <StorageTab />}+ {tab === "audit" && <AuditTab />}+ </div>+ </div>+ );+}diff --git a/frontend/portal/src/views/Pipelines.css b/frontend/portal/src/views/Pipelines.cssnew file mode 100644index 0000000000..645ac144b0--- /dev/null+++ b/frontend/portal/src/views/Pipelines.css@@ -0,0 +1,518 @@+.portal-pipelines {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-pipelines__header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-pipelines__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-pipelines__sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* Fleet summary chips */+.portal-pipelines__fleet {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.portal-pipelines__fleet-count {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* List */+.portal-pipelines__list {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}++.portal-pipelines__card {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+}++.portal-pipelines__card-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 0.75rem;+}++.portal-pipelines__card-title {+ margin: 0;+ font-size: 1.0625rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-pipelines__card-blurb {+ margin: 0.125rem 0 0;+ font-size: 0.8125rem;+ color: var(--color-text-3);+}++/* Source → stages → destination rail */+.portal-pipelines__card-rail {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ flex-wrap: wrap;+}++.portal-pipelines__rail-chip {+ font-size: 0.6875rem;+ font-weight: 500;+ color: var(--color-text-3);+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-pill);+ padding: 0.1875rem 0.5rem;+}++.portal-pipelines__rail-arrow {+ color: var(--color-text-5);+ font-size: 0.75rem;+}++.portal-pipelines__stage-dots {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+}++.portal-pipelines__stage-dot {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 50%;+}++/* Metric strip on the card */+.portal-pipelines__metrics {+ display: grid;+ grid-template-columns: repeat(5, 1fr);+ gap: 0.5rem;+ padding: 0.625rem 0;+ border-top: 1px solid var(--color-border-light);+ border-bottom: 1px solid var(--color-border-light);+}++@media (max-width: 50rem) {+ .portal-pipelines__metrics {+ grid-template-columns: repeat(2, 1fr);+ }+}++.portal-pipelines__card-foot {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ font-size: 0.6875rem;+ color: var(--color-text-4);+}++.portal-pipelines__card-version {+ font-family: var(--font-mono);+}++.portal-pipelines__card-golden {+ color: var(--color-text-3);+}++.portal-pipelines__card-drift {+ color: var(--color-amber-dark);+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Detail drawer */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-pipelines__detail {+ display: flex;+ flex-direction: column;+ gap: 1.5rem;+}++.portal-pipelines__detail-metrics {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 0.625rem;+ padding: 0.875rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-pipelines__detail-section {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.portal-pipelines__detail-h {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-pipelines__detail-sub {+ margin: -0.375rem 0 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* The five silent stages */+.portal-pipelines__stages {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-pipelines__stage {+ padding: 0.625rem 0.75rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+}++.portal-pipelines__stage-head {+ display: flex;+ align-items: center;+ gap: 0.4375rem;+ margin-bottom: 0.5rem;+}++.portal-pipelines__stage-pip {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 50%;+}++.portal-pipelines__stage-name {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-2);+}++.portal-pipelines__stage-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++.portal-pipelines__stage-empty {+ font-size: 0.75rem;+ color: var(--color-text-5);+ font-style: italic;+}++/* Golden set */+.portal-pipelines__golden {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding: 0.75rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-pipelines__golden-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+}++.portal-pipelines__golden-when {+ font-size: 0.6875rem;+ color: var(--color-text-4);+}++/* Schema drift */+.portal-pipelines__drift-list {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-pipelines__drift {+ display: grid;+ grid-template-columns: auto 1fr auto;+ align-items: center;+ gap: 0.625rem;+ padding: 0.625rem 0.75rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+}++.portal-pipelines__drift-dot {+ width: 0.5rem;+ height: 0.5rem;+ border-radius: 50%;+}++.portal-pipelines__drift-text {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+ min-width: 0;+}++.portal-pipelines__drift-field {+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-text-1);+ font-family: var(--font-mono);+}++.portal-pipelines__drift-note {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-pipelines__drift-meta {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 0.125rem;+ font-size: 0.6875rem;+ color: var(--color-text-4);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Composer modal */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-pipelines__composer {+ min-height: 22rem;+}++.portal-pipelines__composer-body {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-pipelines__composer-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.625rem;+}++@media (max-width: 44rem) {+ .portal-pipelines__composer-grid {+ grid-template-columns: 1fr;+ }+}++.portal-pipelines__option {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ padding: 0.75rem;+ 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-pipelines__option:hover {+ border-color: var(--color-border-hover);+ background: var(--color-bg-hover);+}++.portal-pipelines__option.is-selected {+ border-color: var(--color-blue);+ background: var(--color-blue-light);+}++.portal-pipelines__option-label {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-pipelines__option-desc {+ font-size: 0.6875rem;+ color: var(--color-text-4);+ line-height: 1.4;+}++/* Op chain summary */+.portal-pipelines__chain {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ padding: 0.75rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-pipelines__chain-label,+.portal-pipelines__agents-label {+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-text-3);+ text-transform: uppercase;+ letter-spacing: 0.03em;+}++.portal-pipelines__chain-chips,+.portal-pipelines__agents-row {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++.portal-pipelines__chain-empty {+ font-size: 0.75rem;+ color: var(--color-text-5);+ font-style: italic;+}++.portal-pipelines__agents {+ display: flex;+ flex-direction: column;+ gap: 0.4375rem;+}++/* Op library picker */+.portal-pipelines__library {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+ max-height: 19rem;+ overflow-y: auto;+ padding: 0.75rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+}++.portal-pipelines__library-group {+ display: flex;+ flex-direction: column;+ gap: 0.4375rem;+}++.portal-pipelines__library-head {+ display: flex;+ align-items: center;+ gap: 0.375rem;+ font-size: 0.75rem;+ font-weight: 600;+ color: var(--color-text-2);+}++.portal-pipelines__library-pip {+ width: 0.4375rem;+ height: 0.4375rem;+ border-radius: 50%;+}++.portal-pipelines__library-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++/* Routing alerts */+.portal-pipelines__alerts {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-pipelines__alert {+ display: grid;+ grid-template-columns: auto 1fr;+ align-items: start;+ gap: 0.625rem;+ padding: 0.625rem 0.75rem;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+ cursor: pointer;+}++.portal-pipelines__alert input {+ margin-top: 0.1875rem;+ accent-color: var(--color-blue);+}++.portal-pipelines__alert > span {+ display: flex;+ flex-direction: column;+ gap: 0.0625rem;+}++.portal-pipelines__alert strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-pipelines__alert span span {+ font-size: 0.6875rem;+ color: var(--color-text-4);+}++/* Composer step indicator in the footer */+.portal-pipelines__composer-steps {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ margin-right: auto;+}++.portal-pipelines__composer-step {+ font-size: 0.6875rem;+ font-weight: 500;+ color: var(--color-text-5);+}++.portal-pipelines__composer-step.is-active {+ color: var(--color-blue);+ font-weight: 600;+}++.portal-pipelines__composer-step.is-done {+ color: var(--color-green-dark);+}diff --git a/frontend/portal/src/views/Pipelines.tsx b/frontend/portal/src/views/Pipelines.tsxnew file mode 100644index 0000000000..f4297045a5--- /dev/null+++ b/frontend/portal/src/views/Pipelines.tsx@@ -0,0 +1,125 @@+import { useMemo, useState } from "react";+import {+ Banner,+ Button,+ Drawer,+ EmptyState,+ StatusBadge,+} from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import {+ fetchPipelines,+ type Pipeline,+ type PipelinesResponse,+} from "@portal/api/pipelines";+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 "@portal/views/Pipelines.css";++export function Pipelines() {+ const { tier } = useTier();+ const state = useAsync<PipelinesResponse>(() => fetchPipelines(tier), [tier]);+ const { data } = state;+ const { isLoading } = useSectionFlags(state);++ const [composerOpen, setComposerOpen] = useState(false);+ const [selected, setSelected] = useState<Pipeline | null>(null);++ const pipelines = data?.pipelines ?? [];+ const evals = data?.evals ?? null;+ const isEmpty = !isLoading && pipelines.length === 0;++ const fleetHealthy = useMemo(+ () => pipelines.filter((p) => p.status === "healthy").length,+ [pipelines],+ );++ return (+ <div className="portal-pipelines">+ <header className="portal-pipelines__header">+ <div>+ <h1 className="portal-pipelines__title">Pipelines</h1>+ <p className="portal-pipelines__sub">+ Document workflows composed from typed operations — deployed,+ versioned, and continuously validated against a golden set.+ </p>+ </div>+ <Button+ variant="gradient"+ onClick={() => setComposerOpen(true)}+ leadingIcon={<span aria-hidden>+</span>}+ >+ New pipeline+ </Button>+ </header>++ {!isLoading && pipelines.length > 0 && (+ <div className="portal-pipelines__fleet">+ <StatusBadge tone="success" size="sm">+ {fleetHealthy} healthy+ </StatusBadge>+ {fleetHealthy < pipelines.length && (+ <StatusBadge tone="warning" size="sm">+ {pipelines.length - fleetHealthy} degraded+ </StatusBadge>+ )}+ <span className="portal-pipelines__fleet-count">+ {pipelines.length} deployed+ </span>+ </div>+ )}++ {tier === "enterprise" && evals && (+ <Banner tone="info" title="Shadow + comparative evals active">+ {evals.shadowCount} pipeline{evals.shadowCount === 1 ? "" : "s"}{" "}+ running a shadow eval, {evals.comparativeCount} in a comparative run.{" "}+ {evals.detail}+ </Banner>+ )}++ {isLoading && <PipelineListSkeleton />}++ {isEmpty && (+ <EmptyState+ title="No pipelines yet"+ description="Compose your first document workflow from the typed operation library — pick a source, chain the ops, and route the output."+ actions={+ <Button variant="gradient" onClick={() => setComposerOpen(true)}>+ Build your first pipeline+ </Button>+ }+ />+ )}++ {pipelines.length > 0 && (+ <div className="portal-pipelines__list">+ {pipelines.map((p) => (+ <PipelineCard key={p.id} pipeline={p} onOpen={setSelected} />+ ))}+ </div>+ )}++ <Drawer+ open={selected !== null}+ onClose={() => setSelected(null)}+ width="lg"+ title={selected?.name}+ subtitle={+ selected+ ? `${selected.version} · ${selected.source} → ${selected.destination}`+ : undefined+ }+ >+ {selected && <PipelineDetail pipeline={selected} />}+ </Drawer>++ <PipelineComposer+ open={composerOpen}+ onClose={() => setComposerOpen(false)}+ />+ </div>+ );+}diff --git a/frontend/portal/src/views/Sources.css b/frontend/portal/src/views/Sources.cssnew file mode 100644index 0000000000..4849c0485d--- /dev/null+++ b/frontend/portal/src/views/Sources.css@@ -0,0 +1,427 @@+.portal-sources {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-sources__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-sources__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 650;+ color: var(--color-text-1);+}++.portal-sources__sub {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ line-height: 1.5;+ color: var(--color-text-3);+ max-width: 46rem;+}++/* Metric strip now uses the shared <MetricStrip>. */++/* Table cells */+.portal-sources__name-cell {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ min-width: 0;+}++.portal-sources__name-text {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-sources__name-text strong {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-sources__type-dot {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.875rem;+ height: 1.875rem;+ flex-shrink: 0;+ border-radius: var(--radius-md);+ font-size: 0.875rem;+}++.portal-sources__type-dot--neutral {+ background: var(--color-bg-subtle);+ color: var(--color-text-3);+}+.portal-sources__type-dot--blue {+ background: var(--color-blue-light);+ color: var(--color-blue);+}+.portal-sources__type-dot--purple {+ background: var(--color-purple-light);+ color: var(--color-purple);+}+.portal-sources__type-dot--green {+ background: var(--color-green-light);+ color: var(--color-green-dark);+}+.portal-sources__type-dot--amber {+ background: var(--color-amber-light);+ color: var(--color-amber-dark);+}+.portal-sources__type-dot--red {+ background: var(--color-red-light);+ color: var(--color-red);+}++.portal-sources__muted {+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++.portal-sources__caret {+ display: inline-block;+ color: var(--color-text-5);+ transition: transform var(--motion-fast);+}++.portal-sources__caret.is-open {+ transform: rotate(90deg);+ color: var(--color-blue);+}++/* Expanded detail panel */+.portal-sources__expanded {+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ border-radius: var(--radius-lg);+ box-shadow: var(--shadow-sm);+ padding: 1.25rem;+ animation: portal-sources-reveal var(--motion-fast) ease-out;+}++@keyframes portal-sources-reveal {+ from {+ opacity: 0;+ transform: translateY(-0.25rem);+ }+ to {+ opacity: 1;+ transform: translateY(0);+ }+}++.portal-sources__expanded-head {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ padding-bottom: 0.875rem;+ margin-bottom: 1rem;+ border-bottom: 1px solid var(--color-border-light);+}++.portal-sources__expanded-title {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-sources__expanded-sub {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-sources__expanded-close {+ margin-left: auto;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: var(--radius-md);+ border: 1px solid var(--color-border);+ background: var(--color-surface);+ color: var(--color-text-4);+ font-size: 1.125rem;+ line-height: 1;+ cursor: pointer;+ transition:+ background var(--motion-fast),+ color var(--motion-fast);+}++.portal-sources__expanded-close:hover {+ background: var(--color-bg-hover);+ color: var(--color-text-1);+}++/* Detail body */+.portal-sources__detail {+ display: flex;+ flex-direction: column;+ gap: 1.125rem;+}++.portal-sources__stat-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.875rem;+}++@media (max-width: 56rem) {+ .portal-sources__stat-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}++/* Stat tiles now use the shared <StatTile>. */++.portal-sources__url {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-2);+ word-break: break-all;+}++/* Bars */+.portal-sources__bar-row {+ display: flex;+ flex-direction: column;+ gap: 0.4375rem;+}++.portal-sources__bar-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-sources__bar-head strong {+ font-size: 0.8125rem;+ color: var(--color-text-1);+ font-family: var(--font-mono);+}++/* Detail sub-sections */+.portal-sources__detail-section {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-sources__detail-heading {+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-text-5);+ font-weight: 600;+}++.portal-sources__chips {+ display: flex;+ flex-wrap: wrap;+ gap: 0.375rem;+}++/* Endpoint / delivery rows */+.portal-sources__endpoints {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+}++.portal-sources__endpoint {+ display: grid;+ grid-template-columns: auto 1fr auto;+ align-items: center;+ gap: 0.625rem;+ padding: 0.4375rem 0.625rem;+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+ border-radius: var(--radius-md);+}++.portal-sources__method {+ font-family: var(--font-mono);+}++.portal-sources__endpoint-path {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-2);+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+}++.portal-sources__endpoint-calls {+ font-size: 0.6875rem;+ color: var(--color-text-4);+ white-space: nowrap;+ font-family: var(--font-mono);+}++.portal-sources__detail-actions {+ display: flex;+ gap: 0.5rem;+ padding-top: 0.25rem;+}++/* Table skeleton */+.portal-sources__table-skeleton {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++/* ──────────────────────────────────────────────────────────────────────── */+/* Connect wizard */+/* ──────────────────────────────────────────────────────────────────────── */++.portal-sources__steps {+ list-style: none;+ display: flex;+ gap: 0.5rem;+ margin: 0 0 1.25rem;+ padding: 0;+}++.portal-sources__step {+ display: flex;+ align-items: center;+ gap: 0.4375rem;+ flex: 1;+ font-size: 0.75rem;+ color: var(--color-text-4);+ padding: 0.5rem 0.625rem;+ border-radius: var(--radius-md);+ background: var(--color-bg-subtle);+ border: 1px solid var(--color-border-light);+}++.portal-sources__step.is-active {+ color: var(--color-text-1);+ font-weight: 600;+ border-color: color-mix(in srgb, var(--color-blue) 40%, transparent);+ background: var(--color-blue-light);+}++.portal-sources__step.is-done {+ color: var(--color-text-3);+}++.portal-sources__step-mark {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 1.25rem;+ height: 1.25rem;+ border-radius: 50%;+ font-size: 0.6875rem;+ font-weight: 600;+ background: var(--color-surface);+ border: 1px solid var(--color-border);+ color: var(--color-text-4);+}++.portal-sources__step.is-active .portal-sources__step-mark {+ background: var(--color-blue);+ border-color: var(--color-blue);+ color: var(--color-text-on-accent);+}++.portal-sources__step.is-done .portal-sources__step-mark {+ background: var(--color-green);+ border-color: var(--color-green);+ color: var(--color-text-on-accent);+}++.portal-sources__type-grid {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.625rem;+}++@media (max-width: 40rem) {+ .portal-sources__type-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}++.portal-sources__type-card {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 0.5rem;+ padding: 1rem 0.5rem;+ 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-sources__type-card:hover {+ border-color: var(--color-border-strong, var(--color-border));+ background: var(--color-bg-hover);+}++.portal-sources__type-card.is-selected {+ border-color: var(--color-blue);+ background: var(--color-blue-light);+ box-shadow: 0 0 0 1px var(--color-blue) inset;+}++.portal-sources__type-icon {+ font-size: 1.25rem;+ color: var(--color-text-2);+}++.portal-sources__type-name {+ font-size: 0.75rem;+ font-weight: 500;+ color: var(--color-text-1);+}++.portal-sources__wizard-body {+ display: flex;+ flex-direction: column;+ gap: 1rem;+}++.portal-sources__wizard-lead {+ margin: 0;+ font-size: 0.875rem;+ line-height: 1.55;+ color: var(--color-text-2);+}++.portal-sources__wizard-note {+ margin: 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-sources__wizard-footer {+ display: flex;+ justify-content: space-between;+ gap: 0.5rem;+ width: 100%;+}diff --git a/frontend/portal/src/views/Sources.tsx b/frontend/portal/src/views/Sources.tsxnew file mode 100644index 0000000000..b40016ebfb--- /dev/null+++ b/frontend/portal/src/views/Sources.tsx@@ -0,0 +1,82 @@+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 { fetchSources, type SourcesResponse } from "@portal/api/sources";+import { KpiStrip } from "@portal/components/sources/KpiStrip";+import { SourcesTable } from "@portal/components/sources/SourcesTable";+import { SourceDetailCard } from "@portal/components/sources/SourceDetailCard";+import { ConnectWizard } from "@portal/components/sources/ConnectWizard";+import "@portal/views/Sources.css";++export function Sources() {+ const { tier } = useTier();+ const state = useAsync<SourcesResponse>(() => fetchSources(tier), [tier]);+ const { data, loading } = state;+ const { isLoading, isEmpty } = useSectionFlags(state);++ const [expandedId, setExpandedId] = useState<string | null>(null);+ const [wizardOpen, setWizardOpen] = useState(false);++ const sources = data?.sources ?? [];+ const expanded = sources.find((s) => s.id === expandedId) ?? null;++ return (+ <div className="portal-sources">+ <header className="portal-sources__head">+ <div>+ <h1 className="portal-sources__title">Sources & Agents</h1>+ <p className="portal-sources__sub">+ Every place documents flow into Stirling — agents, API clients,+ 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>+ </header>++ <KpiStrip data={data} loading={loading} />++ {isLoading && (+ <div className="portal-sources__table-skeleton" aria-hidden>+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} height="3rem" />+ ))}+ </div>+ )}++ {isEmpty && (+ <EmptyState+ title="No sources connected yet"+ description="Connect an agent, API client, webhook, connector or inbox to start feeding documents into your pipelines."+ actions={+ <Button onClick={() => setWizardOpen(true)}>Connect source</Button>+ }+ />+ )}++ {!isLoading && !isEmpty && sources.length > 0 && (+ <SourcesTable+ sources={sources}+ expandedId={expandedId}+ onRowClick={(s) =>+ setExpandedId((cur) => (cur === s.id ? null : s.id))+ }+ />+ )}++ {expanded && (+ <SourceDetailCard+ source={expanded}+ onClose={() => setExpandedId(null)}+ />+ )}++ <ConnectWizard open={wizardOpen} onClose={() => setWizardOpen(false)} />+ </div>+ );+}diff --git a/frontend/portal/src/views/Usage.css b/frontend/portal/src/views/Usage.cssnew file mode 100644index 0000000000..bf39aeb105--- /dev/null+++ b/frontend/portal/src/views/Usage.css@@ -0,0 +1,340 @@+.portal-usage {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+ padding: 1.5rem;+ max-width: 84rem;+ margin: 0 auto;+}++/* Header */+.portal-usage__header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-usage__title {+ margin: 0;+ font-size: 1.375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-usage__subtitle {+ margin: 0.25rem 0 0;+ font-size: 0.8125rem;+ color: var(--color-text-4);+}++/* Two-column row: current plan + spend cap */+.portal-usage__row {+ display: grid;+ grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr);+ gap: 1rem;+ align-items: stretch;+}++@media (max-width: 60rem) {+ .portal-usage__row {+ grid-template-columns: 1fr;+ }+}++/* Section headers */+.portal-usage__section-head {+ margin-bottom: 0.875rem;+}++.portal-usage__section-title {+ margin: 0;+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-usage__section-sub {+ margin: 0.25rem 0 0;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* Current plan card */+.portal-usage__plan-current {+ display: flex;+ flex-direction: column;+ gap: 0.875rem;+}++.portal-usage__plan-current-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 0.75rem;+}++.portal-usage__plan-eyebrow {+ display: block;+ font-size: 0.6875rem;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-text-5);+}++.portal-usage__plan-name {+ margin: 0.125rem 0 0;+ font-size: 1.125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++/* Cap progress (free) */+.portal-usage__cap {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-usage__cap-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-usage__cap-pct {+ font-weight: 600;+ color: var(--color-text-1);+ font-variant-numeric: tabular-nums;+}++/* Breakdown rows (pro / enterprise) */+.portal-usage__breakdown {+ display: flex;+ flex-direction: column;+ gap: 0.125rem;+}++.portal-usage__breakdown-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ padding: 0.5rem 0;+ font-size: 0.8125rem;+ border-bottom: 1px solid var(--color-border-light);+}++.portal-usage__breakdown-row:last-child {+ border-bottom: none;+}++.portal-usage__breakdown-label {+ color: var(--color-text-3);+}++.portal-usage__breakdown-value {+ font-weight: 600;+ color: var(--color-text-1);+ font-variant-numeric: tabular-nums;+}++.portal-usage__breakdown-row--total {+ margin-top: 0.25rem;+ padding-top: 0.625rem;+ border-top: 1px solid var(--color-border);+ font-size: 0.875rem;+}++.portal-usage__breakdown-row--total .portal-usage__breakdown-label {+ color: var(--color-text-1);+ font-weight: 600;+}++.portal-usage__plan-actions {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ margin-top: auto;+}++/* Available plan cards */+.portal-usage__plans-grid {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0.875rem;+}++@media (max-width: 60rem) {+ .portal-usage__plans-grid {+ grid-template-columns: 1fr;+ }+}++.portal-usage__plan-card {+ display: flex;+ flex-direction: column;+ gap: 0.625rem;+}++.portal-usage__plan-card--current {+ outline: 1.5px solid color-mix(in srgb, var(--color-green) 45%, transparent);+ outline-offset: -1px;+}++.portal-usage__plan-card-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+}++.portal-usage__plan-card-name {+ margin: 0;+ font-size: 1rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-usage__plan-card-price {+ display: flex;+ align-items: baseline;+ gap: 0.375rem;+ flex-wrap: wrap;+}++.portal-usage__plan-card-amount {+ font-size: 1.5rem;+ font-weight: 700;+ color: var(--color-text-1);+}++.portal-usage__plan-card-cadence {+ font-size: 0.75rem;+ color: var(--color-text-4);+}++.portal-usage__plan-card-blurb {+ margin: 0;+ font-size: 0.8125rem;+ line-height: 1.45;+ color: var(--color-text-3);+}++.portal-usage__plan-card-features {+ list-style: none;+ margin: 0.25rem 0 0.75rem;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.4375rem;+ flex: 1;+}++.portal-usage__plan-card-features li {+ display: flex;+ align-items: flex-start;+ gap: 0.5rem;+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-usage__plan-card-check {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ width: 1rem;+ height: 1rem;+ margin-top: 0.0625rem;+ border-radius: 50%;+ background: var(--color-green-light);+ color: var(--color-green-dark);+ font-size: 0.625rem;+ font-weight: 700;+}++/* Spend-cap card */+.portal-usage__cap-card {+ display: flex;+ flex-direction: column;+ gap: 0.75rem;+}++.portal-usage__cap-card-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 0.75rem;+}++.portal-usage__cap-slider {+ margin: 0.25rem 0;+}++.portal-usage__cap-meta {+ display: flex;+ align-items: center;+ gap: 0.625rem;+ font-size: 0.75rem;+ color: var(--color-text-4);+}++/* Billing history */+.portal-usage__hist-date {+ font-variant-numeric: tabular-nums;+ color: var(--color-text-2);+}++.portal-usage__hist-amount {+ font-weight: 600;+ color: var(--color-text-1);+ font-variant-numeric: tabular-nums;+}++.portal-usage__hist-credit {+ font-weight: 600;+ color: var(--color-green-dark);+ font-variant-numeric: tabular-nums;+}++.portal-usage__hist-skeleton {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++/* Upgrade modal */+.portal-usage__modal-body {+ margin: 0 0 1rem;+ font-size: 0.875rem;+ line-height: 1.55;+ color: var(--color-text-2);+}++.portal-usage__modal-bullets {+ list-style: none;+ margin: 0;+ padding: 0;+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-usage__modal-bullets li {+ display: flex;+ align-items: flex-start;+ gap: 0.5rem;+ font-size: 0.8125rem;+ color: var(--color-text-2);+}++.portal-usage__modal-actions {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 0.625rem;+}diff --git a/frontend/portal/src/views/Usage.tsx b/frontend/portal/src/views/Usage.tsxnew file mode 100644index 0000000000..e46c17cf75--- /dev/null+++ b/frontend/portal/src/views/Usage.tsx@@ -0,0 +1,105 @@+import { useState } from "react";+import { Card, Skeleton, StatusBadge } from "@shared/components";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync } from "@portal/hooks/useAsync";+import {+ fetchBillingSummary,+ fetchPlanOptions,+ type BillingSummary,+ type PlanOption,+} from "@portal/api/usage";+import { UsageChart } from "@portal/components/usage/UsageChart";+import { BillingKpiStrip } from "@portal/components/usage/BillingKpiStrip";+import { CurrentPlanCard } from "@portal/components/usage/CurrentPlanCard";+import { SpendCapControl } from "@portal/components/usage/SpendCapControl";+import { AvailablePlans } from "@portal/components/usage/AvailablePlans";+import { BillingHistoryTable } from "@portal/components/usage/BillingHistoryTable";+import { UpgradeModal } from "@portal/components/usage/UpgradeModal";+import "@portal/views/Usage.css";++export function Usage() {+ const { tier } = useTier();+ const [modalOpen, setModalOpen] = useState(false);+ const [modalTarget, setModalTarget] = useState<PlanOption | null>(null);++ const summaryState = useAsync<BillingSummary>(+ () => fetchBillingSummary(tier),+ [tier],+ );+ const summary = summaryState.loading ? null : summaryState.data;++ const plansState = useAsync<PlanOption[]>(() => fetchPlanOptions(), []);+ const { data: plans } = plansState;++ function openUpgrade(target: PlanOption | null) {+ setModalTarget(target);+ setModalOpen(true);+ }++ return (+ <div className="portal-usage">+ <header className="portal-usage__header">+ <div>+ <h1 className="portal-usage__title">Usage & Billing</h1>+ <p className="portal-usage__subtitle">+ Your last 30 days of processing, plan, and charges.+ </p>+ </div>+ <StatusBadge+ tone={+ tier === "enterprise"+ ? "purple"+ : tier === "pro"+ ? "info"+ : "neutral"+ }+ size="md"+ >+ {summary?.planName ?? "—"}+ </StatusBadge>+ </header>++ <UsageChart />++ <BillingKpiStrip summary={summary} />++ <div className="portal-usage__row">+ {summary ? (+ <CurrentPlanCard+ summary={summary}+ onUpgrade={() => openUpgrade(null)}+ />+ ) : (+ <Card padding="loose">+ <Skeleton width="10rem" height="1.25rem" />+ <Skeleton height="9rem" />+ </Card>+ )}+ {summary ? (+ <SpendCapControl summary={summary} />+ ) : (+ <Card padding="loose">+ <Skeleton width="8rem" height="1.25rem" />+ <Skeleton height="5rem" />+ </Card>+ )}+ </div>++ {plans && plans.length > 0 && (+ // Any plan selection routes through the intent-aware upgrade modal; the+ // target plan drives whether the copy is an upgrade pitch or a+ // downgrade / sales conversation.+ <AvailablePlans plans={plans} current={tier} onSelect={openUpgrade} />+ )}++ <BillingHistoryTable />++ <UpgradeModal+ open={modalOpen}+ onClose={() => setModalOpen(false)}+ currentTier={tier}+ target={modalTarget}+ />+ </div>+ );+}diff --git a/frontend/shared/assets/stirling-mark-dark.svg b/frontend/shared/assets/stirling-mark-dark.svgnew file mode 100644index 0000000000..a6f82dd6f6--- /dev/null+++ b/frontend/shared/assets/stirling-mark-dark.svg@@ -0,0 +1,4 @@+<svg width="92" height="100" viewBox="0 0 92 100" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M0 50L60 0V46.5L0 96.5V50Z" fill="#E6E6E6" fill-opacity="0.4"/>+<path d="M32 53L92 3V49.5L32 99.5V53Z" fill="#E6E6E6" fill-opacity="0.7"/>+</svg>diff --git a/frontend/shared/assets/stirling-mark-light.svg b/frontend/shared/assets/stirling-mark-light.svgnew file mode 100644index 0000000000..62a5b38387--- /dev/null+++ b/frontend/shared/assets/stirling-mark-light.svg@@ -0,0 +1,4 @@+<svg width="92" height="100" viewBox="0 0 92 100" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M0 50L60 0V46.5L0 96.5V50Z" fill="#ACACAC" fill-opacity="0.3"/>+<path d="M32 53L92 3V49.5L32 99.5V53Z" fill="#FC9999" fill-opacity="0.5"/>+</svg>diff --git a/frontend/shared/assets/stirling-pdf-logo-dark.svg b/frontend/shared/assets/stirling-pdf-logo-dark.svgnew file mode 100644index 0000000000..ade6937870--- /dev/null+++ b/frontend/shared/assets/stirling-pdf-logo-dark.svg@@ -0,0 +1,4 @@+<svg width="118" height="26" viewBox="0 0 118 26" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M5.89479 22.2333C4.71702 22.2333 3.7059 22.0667 2.86146 21.7333C2.03924 21.4 1.4059 20.8111 0.96146 19.9667C0.517015 19.1222 0.294793 17.9333 0.294793 16.4V15.2333C0.983682 15.2333 1.66146 15.2333 2.32813 15.2333C2.99479 15.2333 3.66146 15.2333 4.32813 15.2333V16.7333C4.32813 17.5556 4.39479 18.1889 4.52813 18.6333C4.66146 19.0556 4.85035 19.3556 5.09479 19.5333C5.33924 19.6889 5.62813 19.7667 5.96146 19.7667C6.47257 19.7667 6.87257 19.5889 7.16146 19.2333C7.47257 18.8556 7.62813 18.1333 7.62813 17.0667C7.62813 16.2444 7.49479 15.6333 7.22813 15.2333C6.98368 14.8111 6.58368 14.4778 6.02813 14.2333C5.47257 13.9667 4.76146 13.6444 3.89479 13.2667C3.11702 12.9333 2.47257 12.5333 1.96146 12.0667C1.45035 11.6 1.07257 11.0111 0.828126 10.3C0.583682 9.58889 0.46146 8.72222 0.46146 7.7C0.46146 6.41111 0.628126 5.36667 0.96146 4.56667C1.31702 3.76667 1.89479 3.18889 2.69479 2.83333C3.51702 2.45556 4.61702 2.26667 5.99479 2.26667C7.77257 2.26667 9.12813 2.65556 10.0615 3.43333C11.017 4.18889 11.4948 5.33333 11.4948 6.86667V9.23333C10.8503 9.23333 10.2059 9.23333 9.56146 9.23333C8.93924 9.23333 8.29479 9.23333 7.62813 9.23333V8.03333C7.62813 7.03333 7.5059 6.33333 7.26146 5.93333C7.03924 5.53333 6.62813 5.33333 6.02813 5.33333C5.45035 5.33333 5.03924 5.51111 4.79479 5.86667C4.55035 6.22222 4.42813 6.8 4.42813 7.6C4.42813 8.33333 4.57257 8.91111 4.86146 9.33333C5.17257 9.73333 5.56146 10.0444 6.02813 10.2667C6.49479 10.4667 6.99479 10.6667 7.52813 10.8667C8.5059 11.2444 9.3059 11.6333 9.92813 12.0333C10.5503 12.4111 11.0059 12.9444 11.2948 13.6333C11.5837 14.3 11.7281 15.2667 11.7281 16.5333C11.7281 17.9556 11.4837 19.0889 10.9948 19.9333C10.5281 20.7556 9.85035 21.3444 8.96146 21.7C8.09479 22.0556 7.07257 22.2333 5.89479 22.2333ZM18.649 22.1C18.1378 22.1 17.6267 22.0556 17.1156 21.9667C16.6045 21.8778 16.149 21.7111 15.749 21.4667C15.349 21.2 15.0267 20.8333 14.7823 20.3667C14.5378 19.8778 14.4156 19.2333 14.4156 18.4333V7.73333H12.849V5.83333L14.749 5.5L15.2823 2.46667H18.2156V5.5H21.349V7.73333H18.2156V17.7667C18.2156 18.2333 18.3045 18.6556 18.4823 19.0333C18.6601 19.3889 19.0601 19.5667 19.6823 19.5667C19.9712 19.5667 20.3045 19.5556 20.6823 19.5333C21.0601 19.4889 21.2823 19.4667 21.349 19.4667V21.7667C21.2823 21.7667 20.9712 21.8222 20.4156 21.9333C19.8823 22.0444 19.2934 22.1 18.649 22.1ZM22.9938 22V5.5H26.7938V22H22.9938ZM24.8938 3.66667C24.4049 3.66667 23.9826 3.5 23.6271 3.16667C23.2715 2.81111 23.0938 2.4 23.0938 1.93333C23.0938 1.44444 23.2715 1.03333 23.6271 0.699999C23.9826 0.366666 24.4049 0.199999 24.8938 0.199999C25.3826 0.199999 25.8049 0.366666 26.1604 0.699999C26.5382 1.03333 26.7271 1.44444 26.7271 1.93333C26.7271 2.4 26.5382 2.81111 26.1604 3.16667C25.8049 3.5 25.3826 3.66667 24.8938 3.66667ZM29.3089 22V5.5H32.5422L32.8755 7.46667C33.0755 6.97778 33.3755 6.58889 33.7755 6.3C34.1755 5.98889 34.5977 5.77778 35.0422 5.66667C35.7755 5.35556 36.5422 5.27778 37.3422 5.43333V8.36667C37.2977 8.34444 37.12 8.32222 36.8089 8.3C36.52 8.25556 36.1866 8.25556 35.8089 8.3C35.4311 8.32222 35.1089 8.41111 34.8422 8.56667C34.2866 8.76667 33.8533 9.11111 33.5422 9.6C33.2533 10.0889 33.1089 10.6778 33.1089 11.3667V22H29.3089ZM38.6839 22V0.933333H42.4839V22H38.6839ZM44.999 22V5.5H48.799V22H44.999ZM46.899 3.66667C46.4101 3.66667 45.9878 3.5 45.6323 3.16667C45.2767 2.81111 45.099 2.4 45.099 1.93333C45.099 1.44444 45.2767 1.03333 45.6323 0.699999C45.9878 0.366666 46.4101 0.199999 46.899 0.199999C47.3878 0.199999 47.8101 0.366666 48.1656 0.699999C48.5434 1.03333 48.7323 1.44444 48.7323 1.93333C48.7323 2.4 48.5434 2.81111 48.1656 3.16667C47.8101 3.5 47.3878 3.66667 46.899 3.66667ZM51.3141 22V5.5H54.5474L54.8807 7.43333C55.0807 6.76667 55.4696 6.22222 56.0474 5.8C56.6474 5.37778 57.303 5.16667 58.0141 5.16667C59.0807 5.16667 59.8807 5.35556 60.4141 5.73333C60.9474 6.08889 61.303 6.6 61.4807 7.26667C61.6807 7.91111 61.7807 8.67778 61.7807 9.56667V22H57.9807V9.8C57.9807 9.53333 57.9696 9.28889 57.9474 9.06667C57.9252 8.82222 57.8585 8.61111 57.7474 8.43333C57.6585 8.25556 57.5252 8.12222 57.3474 8.03333C57.1696 7.92222 56.903 7.86667 56.5474 7.86667C56.2807 7.86667 56.0474 7.92222 55.8474 8.03333C55.6474 8.12222 55.4918 8.23333 55.3807 8.36667C55.2696 8.5 55.1807 8.62222 55.1141 8.73333V22H51.3141ZM68.976 25.9667C68.6649 25.9667 68.2872 25.9556 67.8427 25.9333C67.3983 25.9111 66.9538 25.8778 66.5094 25.8333C66.0872 25.7889 65.7205 25.7444 65.4094 25.7C65.1205 25.6778 64.9427 25.6556 64.876 25.6333V23.6C65.1649 23.6444 65.5983 23.6889 66.176 23.7333C66.7538 23.8 67.2427 23.8333 67.6427 23.8333C67.9983 23.8333 68.3316 23.8 68.6427 23.7333C68.976 23.6889 69.2649 23.5778 69.5094 23.4C69.776 23.2444 69.9872 23 70.1427 22.6667C70.2983 22.3556 70.376 21.9333 70.376 21.4V19.0333C70.2649 19.3 70.0983 19.6 69.876 19.9333C69.676 20.2444 69.376 20.5111 68.976 20.7333C68.576 20.9556 68.0094 21.0667 67.276 21.0667C66.7427 21.0667 66.2538 21.0111 65.8094 20.9C65.3872 20.7667 65.0205 20.5333 64.7094 20.2C64.4205 19.8444 64.1872 19.3444 64.0094 18.7C63.8316 18.0333 63.7427 17.1667 63.7427 16.1V9.36667C63.7427 7.96667 64.0316 6.92222 64.6094 6.23333C65.2094 5.52222 66.1094 5.16667 67.3094 5.16667C68.0205 5.16667 68.5872 5.25556 69.0094 5.43333C69.4538 5.61111 69.8094 5.86667 70.076 6.2C70.3427 6.51111 70.5538 6.87778 70.7094 7.3L70.2094 7.36667L70.776 5.5H74.176V19.5333C74.176 20.3333 74.0983 21.1222 73.9427 21.9C73.8094 22.6556 73.5649 23.3333 73.2094 23.9333C72.8538 24.5556 72.3316 25.0444 71.6427 25.4C70.976 25.7778 70.0872 25.9667 68.976 25.9667ZM68.9094 18.8C69.2872 18.8 69.576 18.7111 69.776 18.5333C69.9983 18.3333 70.1427 18.0667 70.2094 17.7333C70.2983 17.3778 70.3427 17.0111 70.3427 16.6333V8.46667C70.2983 8.35556 70.2205 8.24444 70.1094 8.13333C69.9983 8.02222 69.8427 7.92222 69.6427 7.83333C69.4649 7.74444 69.2094 7.7 68.876 7.7C68.4316 7.7 68.0983 7.83333 67.876 8.1C67.6538 8.34444 67.5427 8.81111 67.5427 9.5V17.1C67.5427 17.4778 67.5872 17.7889 67.676 18.0333C67.7649 18.2556 67.876 18.4222 68.0094 18.5333C68.1649 18.6444 68.3205 18.7222 68.476 18.7667C68.6316 18.7889 68.776 18.8 68.9094 18.8Z" fill="white"/>+<path d="M82.2425 22V2.3H89.2425C90.5536 2.3 91.5425 2.6 92.2091 3.2C92.898 3.77778 93.2425 4.58889 93.2425 5.63333V9.03333C93.2425 9.92222 93.1313 10.7556 92.9091 11.5333C92.6869 12.2889 92.2869 12.9 91.7091 13.3667C91.1313 13.8333 90.298 14.0667 89.2091 14.0667H86.2758V22H82.2425ZM86.2758 11.9333H87.7758C88.3091 11.9333 88.7091 11.6778 88.9758 11.1667C89.2425 10.6556 89.3758 9.81111 89.3758 8.63333V7.3C89.3758 6.25556 89.2647 5.51111 89.0425 5.06667C88.8202 4.62222 88.498 4.4 88.0758 4.4H86.2758V11.9333ZM95.3284 22V2.3H102.228C103.162 2.3 103.928 2.43333 104.528 2.7C105.151 2.96667 105.606 3.37778 105.895 3.93333C106.206 4.46667 106.362 5.14444 106.362 5.96667V17.7667C106.362 18.8556 106.173 19.7111 105.795 20.3333C105.417 20.9556 104.873 21.3889 104.162 21.6333C103.473 21.8778 102.651 22 101.695 22H95.3284ZM99.3617 20H101.062C101.506 20 101.851 19.8667 102.095 19.6C102.362 19.3333 102.495 18.8333 102.495 18.1V6.4C102.495 5.66667 102.362 5.16667 102.095 4.9C101.851 4.63333 101.506 4.5 101.062 4.5H99.3617V20ZM108.935 22V2.3H118.002V5.03333H112.968V10.3H117.235V13.3333H112.968V22H108.935Z" fill="#C56565"/>+</svg>diff --git a/frontend/shared/assets/stirling-pdf-logo-light.svg b/frontend/shared/assets/stirling-pdf-logo-light.svgnew file mode 100644index 0000000000..a4a1a1f87e--- /dev/null+++ b/frontend/shared/assets/stirling-pdf-logo-light.svg@@ -0,0 +1,4 @@+<svg width="118" height="26" viewBox="0 0 118 26" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M5.89479 22.2333C4.71702 22.2333 3.7059 22.0667 2.86146 21.7333C2.03924 21.4 1.4059 20.8111 0.96146 19.9667C0.517015 19.1222 0.294793 17.9333 0.294793 16.4V15.2333C0.983682 15.2333 1.66146 15.2333 2.32813 15.2333C2.99479 15.2333 3.66146 15.2333 4.32813 15.2333V16.7333C4.32813 17.5556 4.39479 18.1889 4.52813 18.6333C4.66146 19.0556 4.85035 19.3556 5.09479 19.5333C5.33924 19.6889 5.62813 19.7667 5.96146 19.7667C6.47257 19.7667 6.87257 19.5889 7.16146 19.2333C7.47257 18.8556 7.62813 18.1333 7.62813 17.0667C7.62813 16.2444 7.49479 15.6333 7.22813 15.2333C6.98368 14.8111 6.58368 14.4778 6.02813 14.2333C5.47257 13.9667 4.76146 13.6444 3.89479 13.2667C3.11702 12.9333 2.47257 12.5333 1.96146 12.0667C1.45035 11.6 1.07257 11.0111 0.828126 10.3C0.583682 9.58889 0.46146 8.72222 0.46146 7.7C0.46146 6.41111 0.628126 5.36667 0.96146 4.56667C1.31702 3.76667 1.89479 3.18889 2.69479 2.83333C3.51702 2.45556 4.61702 2.26667 5.99479 2.26667C7.77257 2.26667 9.12813 2.65556 10.0615 3.43333C11.017 4.18889 11.4948 5.33333 11.4948 6.86667V9.23333C10.8503 9.23333 10.2059 9.23333 9.56146 9.23333C8.93924 9.23333 8.29479 9.23333 7.62813 9.23333V8.03333C7.62813 7.03333 7.5059 6.33333 7.26146 5.93333C7.03924 5.53333 6.62813 5.33333 6.02813 5.33333C5.45035 5.33333 5.03924 5.51111 4.79479 5.86667C4.55035 6.22222 4.42813 6.8 4.42813 7.6C4.42813 8.33333 4.57257 8.91111 4.86146 9.33333C5.17257 9.73333 5.56146 10.0444 6.02813 10.2667C6.49479 10.4667 6.99479 10.6667 7.52813 10.8667C8.5059 11.2444 9.3059 11.6333 9.92813 12.0333C10.5503 12.4111 11.0059 12.9444 11.2948 13.6333C11.5837 14.3 11.7281 15.2667 11.7281 16.5333C11.7281 17.9556 11.4837 19.0889 10.9948 19.9333C10.5281 20.7556 9.85035 21.3444 8.96146 21.7C8.09479 22.0556 7.07257 22.2333 5.89479 22.2333ZM18.649 22.1C18.1378 22.1 17.6267 22.0556 17.1156 21.9667C16.6045 21.8778 16.149 21.7111 15.749 21.4667C15.349 21.2 15.0267 20.8333 14.7823 20.3667C14.5378 19.8778 14.4156 19.2333 14.4156 18.4333V7.73333H12.849V5.83333L14.749 5.5L15.2823 2.46667H18.2156V5.5H21.349V7.73333H18.2156V17.7667C18.2156 18.2333 18.3045 18.6556 18.4823 19.0333C18.6601 19.3889 19.0601 19.5667 19.6823 19.5667C19.9712 19.5667 20.3045 19.5556 20.6823 19.5333C21.0601 19.4889 21.2823 19.4667 21.349 19.4667V21.7667C21.2823 21.7667 20.9712 21.8222 20.4156 21.9333C19.8823 22.0444 19.2934 22.1 18.649 22.1ZM22.9938 22V5.5H26.7938V22H22.9938ZM24.8938 3.66667C24.4049 3.66667 23.9826 3.5 23.6271 3.16667C23.2715 2.81111 23.0938 2.4 23.0938 1.93333C23.0938 1.44444 23.2715 1.03333 23.6271 0.699999C23.9826 0.366666 24.4049 0.199999 24.8938 0.199999C25.3826 0.199999 25.8049 0.366666 26.1604 0.699999C26.5382 1.03333 26.7271 1.44444 26.7271 1.93333C26.7271 2.4 26.5382 2.81111 26.1604 3.16667C25.8049 3.5 25.3826 3.66667 24.8938 3.66667ZM29.3089 22V5.5H32.5422L32.8755 7.46667C33.0755 6.97778 33.3755 6.58889 33.7755 6.3C34.1755 5.98889 34.5977 5.77778 35.0422 5.66667C35.7755 5.35556 36.5422 5.27778 37.3422 5.43333V8.36667C37.2977 8.34444 37.12 8.32222 36.8089 8.3C36.52 8.25556 36.1866 8.25556 35.8089 8.3C35.4311 8.32222 35.1089 8.41111 34.8422 8.56667C34.2866 8.76667 33.8533 9.11111 33.5422 9.6C33.2533 10.0889 33.1089 10.6778 33.1089 11.3667V22H29.3089ZM38.6839 22V0.933333H42.4839V22H38.6839ZM44.999 22V5.5H48.799V22H44.999ZM46.899 3.66667C46.4101 3.66667 45.9878 3.5 45.6323 3.16667C45.2767 2.81111 45.099 2.4 45.099 1.93333C45.099 1.44444 45.2767 1.03333 45.6323 0.699999C45.9878 0.366666 46.4101 0.199999 46.899 0.199999C47.3878 0.199999 47.8101 0.366666 48.1656 0.699999C48.5434 1.03333 48.7323 1.44444 48.7323 1.93333C48.7323 2.4 48.5434 2.81111 48.1656 3.16667C47.8101 3.5 47.3878 3.66667 46.899 3.66667ZM51.3141 22V5.5H54.5474L54.8807 7.43333C55.0807 6.76667 55.4696 6.22222 56.0474 5.8C56.6474 5.37778 57.303 5.16667 58.0141 5.16667C59.0807 5.16667 59.8807 5.35556 60.4141 5.73333C60.9474 6.08889 61.303 6.6 61.4807 7.26667C61.6807 7.91111 61.7807 8.67778 61.7807 9.56667V22H57.9807V9.8C57.9807 9.53333 57.9696 9.28889 57.9474 9.06667C57.9252 8.82222 57.8585 8.61111 57.7474 8.43333C57.6585 8.25556 57.5252 8.12222 57.3474 8.03333C57.1696 7.92222 56.903 7.86667 56.5474 7.86667C56.2807 7.86667 56.0474 7.92222 55.8474 8.03333C55.6474 8.12222 55.4918 8.23333 55.3807 8.36667C55.2696 8.5 55.1807 8.62222 55.1141 8.73333V22H51.3141ZM68.976 25.9667C68.6649 25.9667 68.2872 25.9556 67.8427 25.9333C67.3983 25.9111 66.9538 25.8778 66.5094 25.8333C66.0872 25.7889 65.7205 25.7444 65.4094 25.7C65.1205 25.6778 64.9427 25.6556 64.876 25.6333V23.6C65.1649 23.6444 65.5983 23.6889 66.176 23.7333C66.7538 23.8 67.2427 23.8333 67.6427 23.8333C67.9983 23.8333 68.3316 23.8 68.6427 23.7333C68.976 23.6889 69.2649 23.5778 69.5094 23.4C69.776 23.2444 69.9872 23 70.1427 22.6667C70.2983 22.3556 70.376 21.9333 70.376 21.4V19.0333C70.2649 19.3 70.0983 19.6 69.876 19.9333C69.676 20.2444 69.376 20.5111 68.976 20.7333C68.576 20.9556 68.0094 21.0667 67.276 21.0667C66.7427 21.0667 66.2538 21.0111 65.8094 20.9C65.3872 20.7667 65.0205 20.5333 64.7094 20.2C64.4205 19.8444 64.1872 19.3444 64.0094 18.7C63.8316 18.0333 63.7427 17.1667 63.7427 16.1V9.36667C63.7427 7.96667 64.0316 6.92222 64.6094 6.23333C65.2094 5.52222 66.1094 5.16667 67.3094 5.16667C68.0205 5.16667 68.5872 5.25556 69.0094 5.43333C69.4538 5.61111 69.8094 5.86667 70.076 6.2C70.3427 6.51111 70.5538 6.87778 70.7094 7.3L70.2094 7.36667L70.776 5.5H74.176V19.5333C74.176 20.3333 74.0983 21.1222 73.9427 21.9C73.8094 22.6556 73.5649 23.3333 73.2094 23.9333C72.8538 24.5556 72.3316 25.0444 71.6427 25.4C70.976 25.7778 70.0872 25.9667 68.976 25.9667ZM68.9094 18.8C69.2872 18.8 69.576 18.7111 69.776 18.5333C69.9983 18.3333 70.1427 18.0667 70.2094 17.7333C70.2983 17.3778 70.3427 17.0111 70.3427 16.6333V8.46667C70.2983 8.35556 70.2205 8.24444 70.1094 8.13333C69.9983 8.02222 69.8427 7.92222 69.6427 7.83333C69.4649 7.74444 69.2094 7.7 68.876 7.7C68.4316 7.7 68.0983 7.83333 67.876 8.1C67.6538 8.34444 67.5427 8.81111 67.5427 9.5V17.1C67.5427 17.4778 67.5872 17.7889 67.676 18.0333C67.7649 18.2556 67.876 18.4222 68.0094 18.5333C68.1649 18.6444 68.3205 18.7222 68.476 18.7667C68.6316 18.7889 68.776 18.8 68.9094 18.8Z" fill="black"/>+<path d="M82.2425 22V2.3H89.2425C90.5536 2.3 91.5425 2.6 92.2091 3.2C92.898 3.77778 93.2425 4.58889 93.2425 5.63333V9.03333C93.2425 9.92222 93.1313 10.7556 92.9091 11.5333C92.6869 12.2889 92.2869 12.9 91.7091 13.3667C91.1313 13.8333 90.298 14.0667 89.2091 14.0667H86.2758V22H82.2425ZM86.2758 11.9333H87.7758C88.3091 11.9333 88.7091 11.6778 88.9758 11.1667C89.2425 10.6556 89.3758 9.81111 89.3758 8.63333V7.3C89.3758 6.25556 89.2647 5.51111 89.0425 5.06667C88.8202 4.62222 88.498 4.4 88.0758 4.4H86.2758V11.9333ZM95.3284 22V2.3H102.228C103.162 2.3 103.928 2.43333 104.528 2.7C105.151 2.96667 105.606 3.37778 105.895 3.93333C106.206 4.46667 106.362 5.14444 106.362 5.96667V17.7667C106.362 18.8556 106.173 19.7111 105.795 20.3333C105.417 20.9556 104.873 21.3889 104.162 21.6333C103.473 21.8778 102.651 22 101.695 22H95.3284ZM99.3617 20H101.062C101.506 20 101.851 19.8667 102.095 19.6C102.362 19.3333 102.495 18.8333 102.495 18.1V6.4C102.495 5.66667 102.362 5.16667 102.095 4.9C101.851 4.63333 101.506 4.5 101.062 4.5H99.3617V20ZM108.935 22V2.3H118.002V5.03333H112.968V10.3H117.235V13.3333H112.968V22H108.935Z" fill="#C56565"/>+</svg>diff --git a/frontend/shared/components/Drawer.tsx b/frontend/shared/components/Drawer.tsxindex add63fc20d..5e6561e6f8 100644--- a/frontend/shared/components/Drawer.tsx+++ b/frontend/shared/components/Drawer.tsx@@ -1,10 +1,8 @@-import { useEffect, useId, useRef, type ReactNode } from "react";+import { useEffect, useId, type ReactNode } from "react";import { createPortal } from "react-dom";+import { FocusTrap } from "@mantine/core";import "@shared/components/Drawer.css";-const FOCUSABLE_SELECTOR =- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';-export type DrawerSide = "right" | "left";export type DrawerWidth = "sm" | "md" | "lg";@@ -26,9 +24,10 @@ export interface DrawerProps {}/**- * Side drawer — sibling to {@link Modal}. Slides in from `side`, locks body- * scroll, closes on backdrop click or Escape. PipelineDetailDrawer, doc- * detail drawers, etc. should all sit on top of this primitive.+ * Side drawer — sibling to {@link Modal}, with our own brand shell. Tab focus+ * trapping, initial focus, and focus restoration on close are delegated to+ * Mantine's <FocusTrap>; we keep the slide-in chrome, scroll lock, and ESC /+ * backdrop dismissal.*/export function Drawer({open,@@ -44,7 +43,6 @@ export function Drawer({ariaLabel,children,}: DrawerProps) {- const dialogRef = useRef<HTMLElement | null>(null);const titleId = useId();useEffect(() => {@@ -65,40 +63,6 @@ export function Drawer({};}, [open]);- useEffect(() => {- if (!open) return;- const previouslyFocused = document.activeElement as HTMLElement | null;- const dialog = dialogRef.current;- const first = dialog?.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);- first?.focus();-- function onKey(e: KeyboardEvent) {- if (e.key !== "Tab" || !dialog) return;- const focusables =- dialog.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);- if (focusables.length === 0) {- e.preventDefault();- return;- }- const firstEl = focusables[0];- const lastEl = focusables[focusables.length - 1];- const active = document.activeElement;- if (e.shiftKey && active === firstEl) {- e.preventDefault();- lastEl.focus();- } else if (!e.shiftKey && active === lastEl) {- e.preventDefault();- firstEl.focus();- }- }-- document.addEventListener("keydown", onKey);- return () => {- document.removeEventListener("keydown", onKey);- previouslyFocused?.focus?.();- };- }, [open]);-if (!open) return null;function onBackdropClick() {@@ -114,57 +78,59 @@ export function Drawer({onClick={onBackdropClick}role="presentation"/>- <aside- ref={dialogRef}- className={[- "sui-drawer",- `sui-drawer--${side}`,- `sui-drawer--${width}`,- className ?? "",- ]- .filter(Boolean)- .join(" ")}- role="dialog"- aria-modal="true"- aria-labelledby={hasTitle ? titleId : undefined}- aria-label={!hasTitle ? ariaLabel : undefined}- >- {(title || subtitle) && (- <header className="sui-drawer__header">- <div className="sui-drawer__header-text">- {title && (- <div id={titleId} className="sui-drawer__title">- {title}- </div>- )}- {subtitle && <div className="sui-drawer__sub">{subtitle}</div>}- </div>- <button- type="button"- className="sui-drawer__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+ <FocusTrap active>+ <aside+ className={[+ "sui-drawer",+ `sui-drawer--${side}`,+ `sui-drawer--${width}`,+ className ?? "",+ ]+ .filter(Boolean)+ .join(" ")}+ role="dialog"+ aria-modal="true"+ aria-labelledby={hasTitle ? titleId : undefined}+ aria-label={!hasTitle ? ariaLabel : undefined}+ tabIndex={-1}+ >+ {(title || subtitle) && (+ <header className="sui-drawer__header">+ <div className="sui-drawer__header-text">+ {title && (+ <div id={titleId} className="sui-drawer__title">+ {title}+ </div>+ )}+ {subtitle && <div className="sui-drawer__sub">{subtitle}</div>}+ </div>+ <button+ type="button"+ className="sui-drawer__close"+ onClick={onClose}+ aria-label="Close">- <line x1="18" y1="6" x2="6" y2="18" />- <line x1="6" y1="6" x2="18" y2="18" />- </svg>- </button>- </header>- )}- <div className="sui-drawer__body">{children}</div>- {footer && <footer className="sui-drawer__footer">{footer}</footer>}- </aside>+ <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>+ </header>+ )}+ <div className="sui-drawer__body">{children}</div>+ {footer && <footer className="sui-drawer__footer">{footer}</footer>}+ </aside>+ </FocusTrap></>,document.body,);diff --git a/frontend/shared/components/MetricStrip.css b/frontend/shared/components/MetricStrip.cssnew file mode 100644index 0000000000..c222e61583--- /dev/null+++ b/frontend/shared/components/MetricStrip.css@@ -0,0 +1,11 @@+.sui-metric-strip {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0.75rem;+}++@media (max-width: 50rem) {+ .sui-metric-strip {+ grid-template-columns: repeat(2, 1fr);+ }+}diff --git a/frontend/shared/components/MetricStrip.stories.tsx b/frontend/shared/components/MetricStrip.stories.tsxnew file mode 100644index 0000000000..b2dfc0c689--- /dev/null+++ b/frontend/shared/components/MetricStrip.stories.tsx@@ -0,0 +1,24 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { MetricStrip } from "@shared/components/MetricStrip";+import { MetricCard } from "@shared/components/MetricCard";++const meta: Meta<typeof MetricStrip> = {+ title: "Layout/MetricStrip",+ component: MetricStrip,+ tags: ["autodocs"],+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof MetricStrip>;++/** Four-up KPI row; collapses to two columns below 50rem. */+export const Default: Story = {+ render: () => (+ <MetricStrip>+ <MetricCard label="Docs / 30d" value="48,210" delta={0.12} />+ <MetricCard label="Pipelines" value="12" delta={0.16} />+ <MetricCard label="Agents active" value="7" delta={0.4} />+ <MetricCard label="Eval pass rate" value="94.6%" delta={0.02} />+ </MetricStrip>+ ),+};diff --git a/frontend/shared/components/MetricStrip.tsx b/frontend/shared/components/MetricStrip.tsxnew file mode 100644index 0000000000..4b78200691--- /dev/null+++ b/frontend/shared/components/MetricStrip.tsx@@ -0,0 +1,24 @@+import type { ReactNode } from "react";+import "@shared/components/MetricStrip.css";++export interface MetricStripProps {+ children: ReactNode;+ className?: string;+}++/**+ * Responsive grid wrapper for a row of {@link MetricCard}s — the prototype's+ * "metric strip" (Home, Sources, Usage, Infrastructure all use it). Four-up on+ * wide screens, two-up below 50rem.+ */+export function MetricStrip({ children, className }: MetricStripProps) {+ return (+ <div+ className={["sui-metric-strip", className ?? ""]+ .filter(Boolean)+ .join(" ")}+ >+ {children}+ </div>+ );+}diff --git a/frontend/shared/components/Modal.tsx b/frontend/shared/components/Modal.tsxindex f12985a150..4ab65c9586 100644--- a/frontend/shared/components/Modal.tsx+++ b/frontend/shared/components/Modal.tsx@@ -1,5 +1,6 @@-import { useEffect, useId, useRef, type ReactNode } from "react";+import { useEffect, useId, type ReactNode } from "react";import { createPortal } from "react-dom";+import { FocusTrap } from "@mantine/core";import "@shared/components/Modal.css";export type ModalWidth = "sm" | "md" | "lg" | "xl";@@ -25,16 +26,12 @@ export interface ModalProps {children?: ReactNode;}-const FOCUSABLE_SELECTOR =- 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';-/**- * Portal-rendered modal. Backdrop fades in, dialog scales in. ESC and- * click-on-backdrop close by default. Each instance is self-contained — the- * caller owns the open state and the close handler.- *- * Focus is trapped inside the dialog while open and returned to the- * previously-focused element on close.+ * Portal-rendered modal with our own brand shell (header / body / footer,+ * width presets, backdrop). The hard part — trapping Tab focus inside the+ * dialog, initial focus, and restoring focus to the opener on close — is+ * delegated to Mantine's <FocusTrap> rather than hand-rolled. ESC and+ * backdrop click close by default; the caller owns the open state.*/export function Modal({open,@@ -49,7 +46,6 @@ export function Modal({className,children,}: ModalProps) {- const dialogRef = useRef<HTMLDivElement | null>(null);const titleId = useId();useEffect(() => {@@ -70,40 +66,6 @@ export function Modal({};}, [open]);- useEffect(() => {- if (!open) return;- const previouslyFocused = document.activeElement as HTMLElement | null;- const dialog = dialogRef.current;- const first = dialog?.querySelector<HTMLElement>(FOCUSABLE_SELECTOR);- first?.focus();-- function onKey(e: KeyboardEvent) {- if (e.key !== "Tab" || !dialog) return;- const focusables =- dialog.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR);- if (focusables.length === 0) {- e.preventDefault();- return;- }- const firstEl = focusables[0];- const lastEl = focusables[focusables.length - 1];- const active = document.activeElement;- if (e.shiftKey && active === firstEl) {- e.preventDefault();- lastEl.focus();- } else if (!e.shiftKey && active === lastEl) {- e.preventDefault();- firstEl.focus();- }- }-- document.addEventListener("keydown", onKey);- return () => {- document.removeEventListener("keydown", onKey);- previouslyFocused?.focus?.();- };- }, [open]);-if (!open) return null;function onBackdropClick() {@@ -118,53 +80,55 @@ export function Modal({onClick={onBackdropClick}role="presentation">- <div- ref={dialogRef}- className={["sui-modal", `sui-modal--${width}`, className ?? ""]- .filter(Boolean)- .join(" ")}- onClick={(e) => e.stopPropagation()}- role="dialog"- aria-modal="true"- aria-labelledby={hasTitle ? titleId : undefined}- aria-label={!hasTitle ? ariaLabel : undefined}- >- {(title || subtitle) && (- <header className="sui-modal__header">- <div className="sui-modal__header-text">- {title && (- <div id={titleId} className="sui-modal__title">- {title}- </div>- )}- {subtitle && <div className="sui-modal__sub">{subtitle}</div>}- </div>- <button- type="button"- className="sui-modal__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+ <FocusTrap active>+ <div+ className={["sui-modal", `sui-modal--${width}`, className ?? ""]+ .filter(Boolean)+ .join(" ")}+ onClick={(e) => e.stopPropagation()}+ role="dialog"+ aria-modal="true"+ aria-labelledby={hasTitle ? titleId : undefined}+ aria-label={!hasTitle ? ariaLabel : undefined}+ tabIndex={-1}+ >+ {(title || subtitle) && (+ <header className="sui-modal__header">+ <div className="sui-modal__header-text">+ {title && (+ <div id={titleId} className="sui-modal__title">+ {title}+ </div>+ )}+ {subtitle && <div className="sui-modal__sub">{subtitle}</div>}+ </div>+ <button+ type="button"+ className="sui-modal__close"+ onClick={onClose}+ aria-label="Close">- <line x1="18" y1="6" x2="6" y2="18" />- <line x1="6" y1="6" x2="18" y2="18" />- </svg>- </button>- </header>- )}- <div className="sui-modal__body">{children}</div>- {footer && <footer className="sui-modal__footer">{footer}</footer>}- </div>+ <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>+ </header>+ )}+ <div className="sui-modal__body">{children}</div>+ {footer && <footer className="sui-modal__footer">{footer}</footer>}+ </div>+ </FocusTrap></div>,document.body,);diff --git a/frontend/shared/components/StatTile.css b/frontend/shared/components/StatTile.cssnew file mode 100644index 0000000000..c29455fc72--- /dev/null+++ b/frontend/shared/components/StatTile.css@@ -0,0 +1,39 @@+.sui-stat {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.sui-stat__label {+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--color-text-5);+ font-weight: 600;+}++.sui-stat__value {+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--color-text-1);+ font-variant-numeric: tabular-nums;+}++.sui-stat__value--success {+ color: var(--color-green-dark);+}+.sui-stat__value--warning {+ color: var(--color-amber-dark);+}+.sui-stat__value--danger {+ color: var(--color-red);+}++/* Inline code in a value (masked keys, model ids, URLs) reads as mono meta. */+.sui-stat__value code {+ font-family: var(--font-mono);+ font-size: 0.75rem;+ color: var(--color-text-2);+ word-break: break-all;+}diff --git a/frontend/shared/components/StatTile.stories.tsx b/frontend/shared/components/StatTile.stories.tsxnew file mode 100644index 0000000000..1fcde52094--- /dev/null+++ b/frontend/shared/components/StatTile.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { StatTile } from "@shared/components/StatTile";++const meta: Meta<typeof StatTile> = {+ title: "Primitives/StatTile",+ component: StatTile,+ tags: ["autodocs"],+ parameters: { layout: "padded" },+ args: { label: "Error rate", value: "0.4%", tone: "default" },+ argTypes: {+ tone: {+ control: "inline-radio",+ options: ["default", "success", "warning", "danger"],+ },+ },+};+export default meta;+type Story = StoryObj<typeof StatTile>;++export const Playground: Story = {};++export const ToneRow: Story = {+ render: () => (+ <div style={{ display: "flex", gap: 32 }}>+ <StatTile label="Uptime" value="99.98%" tone="success" />+ <StatTile label="Error rate" value="1.4%" tone="warning" />+ <StatTile label="Error rate" value="6.2%" tone="danger" />+ <StatTile label="P95 latency" value="412 ms" />+ </div>+ ),+};diff --git a/frontend/shared/components/StatTile.tsx b/frontend/shared/components/StatTile.tsxnew file mode 100644index 0000000000..3143c44e2c--- /dev/null+++ b/frontend/shared/components/StatTile.tsx@@ -0,0 +1,38 @@+import type { ReactNode } from "react";+import "@shared/components/StatTile.css";++export type StatTileTone = "default" | "success" | "warning" | "danger";++export interface StatTileProps {+ label: ReactNode;+ value: ReactNode;+ /** Colours the value (e.g. error rate over threshold). */+ tone?: StatTileTone;+ className?: string;+}++/**+ * Compact label-over-value stat used inside detail panels, cards, and metric+ * grids (the small sibling of {@link MetricCard}). Value uses tabular figures+ * so columns of stats stay aligned.+ */+export function StatTile({+ label,+ value,+ tone = "default",+ className,+}: StatTileProps) {+ return (+ <div className={["sui-stat", className ?? ""].filter(Boolean).join(" ")}>+ <span className="sui-stat__label">{label}</span>+ <span+ className={+ "sui-stat__value" ++ (tone !== "default" ? ` sui-stat__value--${tone}` : "")+ }+ >+ {value}+ </span>+ </div>+ );+}diff --git a/frontend/shared/components/Table.css b/frontend/shared/components/Table.cssnew file mode 100644index 0000000000..3b17a6c44d--- /dev/null+++ b/frontend/shared/components/Table.css@@ -0,0 +1,61 @@+.sui-table-wrap {+ width: 100%;+ overflow-x: auto;+ border: 1px solid var(--color-border);+ border-radius: var(--radius-md);+ background: var(--color-surface);+}++.sui-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 0.8125rem;+}++.sui-table__th {+ text-align: left;+ font-weight: 600;+ color: var(--color-text-4);+ font-size: 0.6875rem;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ padding: 0.625rem 0.875rem;+ border-bottom: 1px solid var(--color-border);+ white-space: nowrap;+}+.sui-table__th--right,+.sui-table__td--right {+ text-align: right;+}+.sui-table__th--center,+.sui-table__td--center {+ text-align: center;+}++.sui-table__td {+ padding: 0.625rem 0.875rem;+ color: var(--color-text-2);+ border-bottom: 1px solid var(--color-border-light);+ vertical-align: middle;+}+.sui-table tbody tr:last-child .sui-table__td {+ border-bottom: none;+}++.sui-table__row--interactive {+ cursor: pointer;+ transition: background var(--motion-fast);+}+.sui-table__row--interactive:hover {+ background: var(--color-bg-hover);+}+.sui-table__row--interactive:focus-visible {+ outline: 0.125rem solid var(--color-blue);+ outline-offset: -0.125rem;+}++.sui-table__empty {+ padding: 2rem;+ text-align: center;+ color: var(--color-text-4);+}diff --git a/frontend/shared/components/Table.stories.tsx b/frontend/shared/components/Table.stories.tsxnew file mode 100644index 0000000000..0434dd67d4--- /dev/null+++ b/frontend/shared/components/Table.stories.tsx@@ -0,0 +1,109 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { Table, type TableColumn } from "@shared/components/Table";+import { StatusBadge } from "@shared/components/StatusBadge";++interface Region {+ id: string;+ name: string;+ code: string;+ status: "healthy" | "degraded";+ docs: number;+ latency: string;+}++const REGIONS: Region[] = [+ {+ id: "1",+ name: "US East",+ code: "us-east-1",+ status: "healthy",+ docs: 12481,+ latency: "41 ms",+ },+ {+ id: "2",+ name: "US West",+ code: "us-west-2",+ status: "healthy",+ docs: 8210,+ latency: "63 ms",+ },+ {+ id: "3",+ name: "EU West",+ code: "eu-west-1",+ status: "degraded",+ docs: 3044,+ latency: "190 ms",+ },+];++const COLUMNS: TableColumn<Region>[] = [+ { key: "name", header: "Region", render: (r) => r.name },+ {+ key: "code",+ header: "Code",+ render: (r) => (+ <code style={{ fontFamily: "var(--font-mono)" }}>{r.code}</code>+ ),+ },+ {+ key: "status",+ header: "Status",+ render: (r) => (+ <StatusBadge+ tone={r.status === "healthy" ? "success" : "warning"}+ size="sm"+ >+ {r.status}+ </StatusBadge>+ ),+ },+ {+ key: "docs",+ header: "Docs 24h",+ align: "right",+ render: (r) => r.docs.toLocaleString(),+ },+ { key: "latency", header: "P95", align: "right", render: (r) => r.latency },+];++const meta: Meta<typeof Table> = {+ title: "Compound/Table",+ component: Table,+ tags: ["autodocs"],+ parameters: { layout: "padded" },+};+export default meta;+type Story = StoryObj<typeof Table>;++/** Presentational table — columns own their cell renderers; pass pre-sorted rows. */+export const Basic: Story = {+ render: () => (+ <Table<Region> columns={COLUMNS} rows={REGIONS} rowKey={(r) => r.id} />+ ),+};++/** With `onRowClick`, rows become focusable + hoverable (keyboard: Enter/Space). */+export const Interactive: Story = {+ render: () => (+ <Table<Region>+ columns={COLUMNS}+ rows={REGIONS}+ rowKey={(r) => r.id}+ onRowClick={() => {}}+ />+ ),+};++/** Empty body slot. */+export const Empty: Story = {+ render: () => (+ <Table<Region>+ columns={COLUMNS}+ rows={[]}+ rowKey={(r) => r.id}+ empty="No regions deployed yet."+ />+ ),+};diff --git a/frontend/shared/components/Table.tsx b/frontend/shared/components/Table.tsxnew file mode 100644index 0000000000..6eb90b2d38--- /dev/null+++ b/frontend/shared/components/Table.tsx@@ -0,0 +1,106 @@+import type { ReactNode } from "react";+import "@shared/components/Table.css";++export interface TableColumn<T> {+ /** Stable column id. */+ key: string;+ header: ReactNode;+ /** Cell renderer for a row. */+ render: (row: T) => ReactNode;+ align?: "left" | "right" | "center";+ /** Optional fixed/min width (any CSS length). */+ width?: string;+}++export interface TableProps<T> {+ columns: TableColumn<T>[];+ rows: T[];+ /** Stable key per row. */+ rowKey: (row: T) => string;+ /** Makes rows interactive (hover + click + keyboard). */+ onRowClick?: (row: T) => void;+ /** Rendered in place of the body when there are no rows. */+ empty?: ReactNode;+ className?: string;+}++/**+ * Minimal data table primitive. Columns own their own cell renderers, so the+ * table stays presentational — callers pre-sort/filter and pass the rows they+ * want shown. Rows become focusable buttons-in-disguise when `onRowClick` is+ * set.+ */+export function Table<T>({+ columns,+ rows,+ rowKey,+ onRowClick,+ empty,+ className,+}: TableProps<T>) {+ const interactive = Boolean(onRowClick);+ return (+ <div+ className={["sui-table-wrap", className ?? ""].filter(Boolean).join(" ")}+ >+ <table className="sui-table">+ <thead>+ <tr>+ {columns.map((c) => (+ <th+ key={c.key}+ scope="col"+ className={`sui-table__th sui-table__th--${c.align ?? "left"}`}+ style={c.width ? { width: c.width } : undefined}+ >+ {c.header}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {rows.length === 0 ? (+ <tr>+ <td className="sui-table__empty" colSpan={columns.length}>+ {empty ?? "No data"}+ </td>+ </tr>+ ) : (+ rows.map((row) => (+ <tr+ key={rowKey(row)}+ className={+ interactive+ ? "sui-table__row sui-table__row--interactive"+ : "sui-table__row"+ }+ onClick={onRowClick ? () => onRowClick(row) : undefined}+ tabIndex={interactive ? 0 : undefined}+ role={interactive ? "button" : undefined}+ onKeyDown={+ interactive+ ? (e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ onRowClick?.(row);+ }+ }+ : undefined+ }+ >+ {columns.map((c) => (+ <td+ key={c.key}+ className={`sui-table__td sui-table__td--${c.align ?? "left"}`}+ >+ {c.render(row)}+ </td>+ ))}+ </tr>+ ))+ )}+ </tbody>+ </table>+ </div>+ );+}diff --git a/frontend/shared/components/index.ts b/frontend/shared/components/index.tsindex 1e1a26b30e..82dd4dd159 100644--- a/frontend/shared/components/index.ts+++ b/frontend/shared/components/index.ts@@ -14,6 +14,8 @@ export * from "@shared/components/Modal";// Layoutexport * from "@shared/components/Stack";export * from "@shared/components/Inline";+export * from "@shared/components/MetricStrip";+export * from "@shared/components/StatTile";// Feedbackexport * from "@shared/components/Spinner";@@ -28,6 +30,7 @@ export * from "@shared/components/Toast";export * from "@shared/components/Tabs";export * from "@shared/components/Dropdown";export * from "@shared/components/Drawer";+export * from "@shared/components/Table";// Formsexport * from "@shared/components/FormField";