@w6w/embed 0.2.21 → 0.2.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"lists.mjs","sources":["../src/lists/CallableKindList.tsx","../src/lists/FunctionList.tsx","../src/lists/EndpointList.tsx","../src/lists/WorkflowList.tsx","../src/lists/ReliabilityBoard.tsx","../src/lists/DocumentList.tsx","../src/lib/recent-activity.ts","../src/lists/ActivitySummary.tsx","../src/lists/RunHistory.tsx","../src/lists/Logs.tsx","../src/lists/vendor-history.ts","../src/lists/ServiceDetail.tsx","../src/lists/ConnectionDependents.tsx","../src/lists/ConnectionList.tsx","../src/lists/ConnectionDetail.tsx","../src/lists/ModelCatalog.tsx","../src/lists/ModelUsage.tsx","../src/lists/CredentialList.tsx","../src/lists/CredentialDetail.tsx","../src/lists/DataStoreView.tsx","../src/lists/DataStoreList.tsx"],"sourcesContent":["import { CallableList, type CallableListProps, type CallableListRow } from \"@w6w/ui\";\nimport { type ReactNode, useState } from \"react\";\nimport { ImportSpecModal } from \"../chrome/ImportSpecModal.tsx\";\nimport { type CallableKind, descriptorFor } from \"../lib/callable-descriptors.ts\";\nimport { type ArchivableRow, isRowArchived } from \"../lib/rail-settings.ts\";\nimport { endpointsKey } from \"../repos/endpoints.ts\";\nimport { functionsKey } from \"../repos/functions.ts\";\nimport { workflowsKey } from \"../repos/workflows.ts\";\n\n/**\n * The internal frame the three kind lists (`FunctionList`, `EndpointList`, `WorkflowList`) share:\n * ui's presentational `CallableList` filled with one kind's copy and test ids, the archived\n * decision, and the Import flow. Never re-exported from `./lists` — the public surface is the three\n * kind components.\n *\n * It renders the one `.w6w-embed-root` of the list (a kind's create modal rides in as `children`,\n * inside that root) and navigates nowhere: opening is `onOpen`/`getHref`, an imported row opens\n * through `onOpen` too.\n */\nexport function CallableKindList<Row extends { id: string } & ArchivableRow>(props: {\n kind: CallableKind;\n /** `undefined` while the list query has not answered. */\n rows: readonly Row[] | undefined;\n loading: boolean;\n /** Everything about a row except the id and the archived flag, which the frame owns. */\n toRow: (row: Row) => Omit<CallableListRow, \"id\" | \"archived\">;\n /** Only the Import flow reads it (the workflow list key); `null` means no project. */\n project: string | null;\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n getHref?: (id: string) => string;\n onCreate: () => void;\n creating?: boolean;\n error?: string | null;\n slots?: CallableListProps[\"slots\"];\n /** The kind's create modal. */\n children?: ReactNode;\n}) {\n const { kind } = props;\n const d = descriptorFor(kind);\n const [importing, setImporting] = useState(false);\n\n const rows: CallableListRow[] = (props.rows ?? []).map((row) => ({\n ...props.toRow(row),\n id: row.id,\n archived: isRowArchived(row),\n }));\n\n return (\n <div className=\"w6w-embed-root\">\n <CallableList\n rows={rows}\n title={d.listTitle}\n description={d.listDescription}\n emptyCopy={d.emptyCopy}\n newLabel={d.newLabel}\n openRowTitle={d.openRowTitle}\n testIds={{\n showArchived: d.showArchivedTestId,\n importOpen: d.importOpenTestId,\n archivedBadge: d.archivedBadgeTestId,\n }}\n loading={props.loading}\n error={props.error}\n onCreate={props.onCreate}\n creating={props.creating}\n onImport={() => setImporting(true)}\n onOpen={props.onOpen}\n getHref={props.getHref}\n slots={props.slots}\n />\n {importing && (\n <ImportSpecModal\n kind={kind}\n project={props.project ?? undefined}\n listKeys={{ functionsKey, endpointsKey, workflowsKey }}\n onOpenImported={(_kind, id) => props.onOpen?.(id)}\n onClose={() => setImporting(false)}\n />\n )}\n {props.children}\n </div>\n );\n}\n","import type { CallableListProps } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { FunctionIdentityModal } from \"../forms/CreateFunctionModal.tsx\";\nimport { newCallableId } from \"../lib/callable-descriptors.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport { type FunctionSummary, useFunctionsQuery } from \"../repos/functions.ts\";\nimport { CallableKindList } from \"./CallableKindList.tsx\";\n\nexport interface FunctionListProps {\n /** Project for Import only (the Functions list itself is account-wide). Omitted: the provider's. */\n project?: string | null;\n /** A row was clicked, or an import completed. Navigation is the host's. */\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n /** When set, each row is a real `<a href>`; a click still calls `onOpen`. */\n getHref?: (id: string) => string;\n /** A Function was created from the list's New button; receives the SERVER's id. */\n onCreated?: (id: string) => void;\n slots?: CallableListProps[\"slots\"];\n}\n\n/**\n * The account's Functions: rows from `GET /functions`, archived ones behind a Show-archived toggle,\n * a New button that creates a Function (create-first: the row is POSTed before any editor exists),\n * and Import. Never navigates — the host wires `onOpen` / `getHref` / `onCreated`.\n */\nexport function FunctionList(props: FunctionListProps) {\n const query = useFunctionsQuery();\n const project = useEditorProject(props.project);\n const [creatingId, setCreatingId] = useState<string | null>(null);\n\n return (\n <CallableKindList<FunctionSummary>\n kind=\"function\"\n rows={query.data}\n loading={query.isLoading}\n error={query.error ? String(query.error) : null}\n project={project}\n toRow={(row) => ({\n title: row.displayName || row.key,\n description: row.description,\n badges: row.valid ? null : <span className=\"w6w-callable-list-badge\">incomplete</span>,\n })}\n onOpen={props.onOpen}\n getHref={props.getHref}\n onCreate={() => setCreatingId(newCallableId(\"function\"))}\n slots={props.slots}\n >\n {creatingId !== null && (\n <FunctionIdentityModal\n newId={creatingId}\n takenKeys={(query.data ?? []).map((row) => row.key)}\n onClose={() => setCreatingId(null)}\n onCreated={(id) => {\n setCreatingId(null);\n props.onCreated?.(id);\n }}\n />\n )}\n </CallableKindList>\n );\n}\n","import type { CallableListProps } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { EndpointIdentityModal } from \"../forms/CreateEndpointModal.tsx\";\nimport { newCallableId } from \"../lib/callable-descriptors.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport { type EndpointSummary, isEndpointDraft, useEndpointsQuery } from \"../repos/endpoints.ts\";\nimport { CallableKindList } from \"./CallableKindList.tsx\";\n\nexport interface EndpointListProps {\n /** Project for Import only (the Endpoints list itself is account-wide). Omitted: the provider's. */\n project?: string | null;\n /** A row was clicked, or an import completed. Navigation is the host's. */\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n /** When set, each row is a real `<a href>`; a click still calls `onOpen`. */\n getHref?: (id: string) => string;\n /** An Endpoint was created from the list's New button; receives the SERVER's id. */\n onCreated?: (id: string) => void;\n slots?: CallableListProps[\"slots\"];\n}\n\n/**\n * The account's Endpoints: rows from `GET /endpoints`, archived ones behind a Show-archived toggle,\n * an \"Unfinished\" tag on drafts (no target yet), a New button that creates an Endpoint\n * (create-first: the row is POSTed before any editor exists), and Import. Never navigates — the\n * host wires `onOpen` / `getHref` / `onCreated`.\n */\nexport function EndpointList(props: EndpointListProps) {\n const query = useEndpointsQuery();\n const project = useEditorProject(props.project);\n const [creatingId, setCreatingId] = useState<string | null>(null);\n\n return (\n <CallableKindList<EndpointSummary>\n kind=\"endpoint\"\n rows={query.data}\n loading={query.isLoading}\n error={query.error ? String(query.error) : null}\n project={project}\n toRow={(row) => {\n return {\n // The draft tag sits INSIDE the title, after the name: ui `ListItem` puts `badges` in\n // a trailing `margin-left: auto` slot, which would strand it at the row's far edge.\n title: (\n <>\n <strong>{row.displayName || row.key}</strong>\n {isEndpointDraft(row) ? (\n <span\n className=\"tag warn\"\n data-testid=\"endpoint-draft\"\n title=\"No target configured yet — it cannot be invoked until one is set.\"\n >\n Unfinished\n </span>\n ) : null}\n </>\n ),\n description: row.description,\n };\n }}\n onOpen={props.onOpen}\n getHref={props.getHref}\n onCreate={() => setCreatingId(newCallableId(\"endpoint\"))}\n slots={props.slots}\n >\n {creatingId !== null && (\n <EndpointIdentityModal\n newId={creatingId}\n takenKeys={(query.data ?? []).map((row) => row.key)}\n onClose={() => setCreatingId(null)}\n onCreated={(id) => {\n setCreatingId(null);\n props.onCreated?.(id);\n }}\n />\n )}\n </CallableKindList>\n );\n}\n","import type { CallableListProps } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { newCallableId } from \"../lib/callable-descriptors.ts\";\nimport { blankDefinition } from \"../lib/workflow-blank.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type WorkflowSummary,\n useCreateWorkflowMutation,\n useWorkflowsQuery,\n} from \"../repos/workflows.ts\";\nimport { CallableKindList } from \"./CallableKindList.tsx\";\n\nexport interface WorkflowListProps {\n /** The project whose Workflows are listed and created. Omitted: the provider's project. */\n project?: string | null;\n /** A row was clicked, or an import completed. Navigation is the host's. */\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n /** When set, each row is a real `<a href>`; a click still calls `onOpen`. */\n getHref?: (id: string) => string;\n /** A blank Workflow was created from the list's New button; receives the SERVER's id. */\n onCreated?: (id: string) => void;\n slots?: CallableListProps[\"slots\"];\n}\n\n/**\n * A project's Workflows: rows from `GET /workflows`, archived ones behind a Show-archived toggle,\n * a New button that creates a blank Workflow (the row is POSTed before any editor exists), and\n * Import. With no project there is nothing to list and New refuses. Never navigates — the host\n * wires `onOpen` / `getHref` / `onCreated`.\n */\nexport function WorkflowList(props: WorkflowListProps) {\n const project = useEditorProject(props.project);\n const query = useWorkflowsQuery(project ?? undefined, project != null);\n const createMut = useCreateWorkflowMutation(project ?? undefined);\n const [createError, setCreateError] = useState<string | null>(null);\n\n return (\n <CallableKindList<WorkflowSummary>\n kind=\"workflow\"\n rows={query.data}\n loading={query.isLoading}\n error={createError ?? (query.error ? String(query.error) : null)}\n project={project}\n toRow={(row) => ({\n title: row.displayName || row.name,\n description: row.description,\n badges: (\n <>\n {row.tags.length > 0 && (\n <span className=\"wf-row-tags\">\n {row.tags.map((t) => (\n <span key={t} className=\"tag\">\n {t}\n </span>\n ))}\n </span>\n )}\n {row.status !== \"archived\" && (\n <span className={`badge wf-status ${row.status}`}>{row.status}</span>\n )}\n </>\n ),\n trailing: (\n <span className=\"wf-col wf-col-stats muted small\">\n {row.runCount} {row.runCount === 1 ? \"run\" : \"runs\"}\n </span>\n ),\n })}\n onOpen={props.onOpen}\n getHref={props.getHref}\n onCreate={() => {\n setCreateError(null);\n createMut.mutate(blankDefinition(newCallableId(\"workflow\")), {\n onSuccess: (res) => props.onCreated?.(res.workflow.id),\n onError: (e) => setCreateError(e instanceof Error ? e.message : String(e)),\n });\n }}\n creating={createMut.isPending}\n slots={props.slots}\n />\n );\n}\n","import { ReliabilityList, type ReliabilityListProps } from \"@w6w/ui\";\nimport type { MouseEvent, ReactElement } from \"react\";\nimport { useEmbedProject } from \"../project-context.ts\";\nimport { useProjectReliabilityQuery } from \"../repos/reliability.ts\";\n\nexport interface ReliabilityBoardProps {\n /** Omitted ⇒ the provider's project; `null`/`\"\"` ⇒ no request and a \"select a project\" note. */\n project?: string | null;\n variant?: \"full\" | \"compact\";\n /** DISPLAY cap passed to the list; never sent to the server (it would falsify \"x of y\"). */\n limit?: number;\n /** Window size in days: sent with both requests and labels the table column (default 30). */\n days?: number;\n showChart?: boolean;\n getHref?: (appId: string) => string;\n onOpen?: (appId: string, event: MouseEvent<Element>) => void;\n showAllHref?: string;\n onShowAll?: (event: MouseEvent<Element>) => void;\n slots?: ReliabilityListProps[\"slots\"];\n}\n\n/**\n * One project's service reliability: loads members then status in serial batches of at most ten\n * through `@w6w/embed/repos`, and draws it with `@w6w/ui`'s `ReliabilityList`. Icons come from the\n * rows themselves, so no app-catalog request is made.\n */\nexport function ReliabilityBoard({\n project,\n variant = \"full\",\n limit,\n days = 30,\n showChart,\n getHref,\n onOpen,\n showAllHref,\n onShowAll,\n slots,\n}: ReliabilityBoardProps): ReactElement {\n const provided = useEmbedProject().project;\n const resolved = project === undefined ? provided : project;\n const effective = resolved ? resolved : null;\n const query = useProjectReliabilityQuery(effective ?? undefined, days);\n\n let empty = slots?.empty;\n if (!effective) {\n empty = <p className=\"w6w-muted\">Select a project to see its reliability.</p>;\n } else if (query.isLoading) {\n empty = <p className=\"w6w-muted\">Loading…</p>;\n } else if (query.error) {\n empty = <div className=\"error\">{query.error.message}</div>;\n }\n\n return (\n <div className=\"w6w-embed-root\">\n <ReliabilityList\n services={effective ? (query.data?.services ?? []) : []}\n window={effective ? query.data?.window : undefined}\n days={days}\n compact={variant === \"compact\"}\n showChart={showChart}\n limit={limit}\n getHref={getHref}\n onOpen={onOpen}\n showAllHref={showAllHref}\n onShowAll={onShowAll}\n slots={{ ...slots, empty }}\n />\n </div>\n );\n}\n","import { DataTable, type DataTableColumn, DeleteButton, EditButton, EmptyState } from \"@w6w/ui\";\n/**\n * `<DocumentList>` — a project's documents (key -> free-form content), with in-place create, edit\n * and delete. No repository sync and no \"synced from\" markers: a host that wants them adds them\n * through the three row slots (`lead`, `sharedActions`, `footer`).\n */\nimport type { MouseEvent, ReactNode } from \"react\";\nimport { useState } from \"react\";\nimport { CallFromCodeButton } from \"../chrome/CallFromCodeButton.tsx\";\nimport { ConfirmModal } from \"../chrome/ConfirmModal.tsx\";\nimport { DocumentFormModal } from \"../forms/DocumentFormModal.tsx\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type DocWithProvenance,\n useDeleteDocumentMutation,\n useDocumentsQuery,\n} from \"../repos/documents.ts\";\n\n/** A per-row slot: called once per rendered row with that row's document. */\nexport type DocumentRowSlot = (doc: DocWithProvenance) => ReactNode;\n\nexport interface DocumentListRowSlots {\n /** Before the row's main text, inside the open control (e.g. a source icon). */\n lead?: DocumentRowSlot;\n /** The action group of a SHARED row (a shared row has no Edit or Delete). */\n sharedActions?: DocumentRowSlot;\n /** A full-width line under the row (e.g. a per-row error). */\n footer?: DocumentRowSlot;\n}\n\nexport interface DocumentListSlots {\n /** Replaces the section heading and its description (the Add button stays). `null`: none. */\n header?: ReactNode;\n /** Replaces the empty-state copy. `null`: nothing. */\n empty?: ReactNode;\n}\n\nexport interface DocumentListProps {\n /** Omitted: the provider's project. `null` or `\"\"`: none; nothing is read and writes refuse. */\n project?: string | null;\n /** The host decides what opening a row means; with `getHref` it may `preventDefault`. */\n onOpen?: (id: string, event: MouseEvent<Element>) => void;\n /** Given, a row's main area is a real `<a href>`; its click still calls `onOpen`. */\n getHref?: (id: string) => string;\n slots?: DocumentListSlots;\n rowSlots?: DocumentListRowSlots;\n}\n\n/** One-line preview of a document's content, safe against long bodies. */\nfunction preview(content: string): string {\n const s = content.replace(/\\s+/g, \" \").trim();\n return s.length > 80 ? `${s.slice(0, 80)}…` : s;\n}\n\nexport function DocumentList({ project, onOpen, getHref, slots, rowSlots }: DocumentListProps) {\n const p = useEditorProject(project);\n const docsQuery = useDocumentsQuery(p ?? undefined, p != null);\n const deleteMut = useDeleteDocumentMutation();\n const [modal, setModal] = useState<\n { mode: \"create\" } | { mode: \"edit\"; d: DocWithProvenance } | null\n >(null);\n const [pending, setPending] = useState<DocWithProvenance | null>(null);\n\n const header =\n slots?.header === undefined ? (\n <div>\n <h3>Documents</h3>\n <p className=\"muted small\">Each document is free-form content stored verbatim.</p>\n </div>\n ) : (\n slots.header\n );\n const empty =\n slots?.empty === undefined ? (\n <EmptyState testId=\"document-list-empty\">No documents yet.</EmptyState>\n ) : (\n slots.empty\n );\n\n const columns: DataTableColumn<DocWithProvenance>[] = [\n {\n key: \"key\",\n header: \"Document\",\n render: (d) => {\n const lead = rowSlots?.lead?.(d);\n return (\n <span style={{ display: \"flex\", alignItems: \"center\" }}>\n {lead}\n <span\n className=\"list-main\"\n style={{ marginLeft: lead != null ? \"var(--w6w-sp-2)\" : 0 }}\n >\n <strong className=\"list-name\" title={d.key}>\n {d.key}\n </strong>{\" \"}\n <span className=\"tag\">{d.format}</span>\n <div className=\"muted small list-preview\">\n <code>{preview(d.content)}</code>\n {d.description && <> · {d.description}</>}\n </div>\n </span>\n </span>\n );\n },\n },\n {\n key: \"actions\",\n header: \"\",\n align: \"right\",\n link: false,\n render: (d) => {\n const footer = rowSlots?.footer?.(d);\n return (\n // Clicks here must not reach the row's onOpen.\n // biome-ignore lint/a11y/useKeyWithClickEvents: propagation guard only; the buttons inside are the controls.\n <div onClick={(e) => e.stopPropagation()}>\n <div style={{ display: \"flex\", gap: \"var(--w6w-sp-1-5)\", justifyContent: \"flex-end\" }}>\n <CallFromCodeButton resource={{ kind: \"document\", key: d.key }} />\n {!d.shared ? (\n <>\n <EditButton\n label=\"Edit\"\n onClick={() => setModal({ mode: \"edit\", d })}\n data-testid={`document-edit-${d.id}`}\n />\n <DeleteButton\n label=\"Delete\"\n onClick={() => setPending(d)}\n disabled={deleteMut.isPending}\n data-testid={`document-delete-${d.id}`}\n />\n </>\n ) : (\n rowSlots?.sharedActions?.(d)\n )}\n </div>\n {footer != null && <div className=\"w6w-doc-footer\">{footer}</div>}\n </div>\n );\n },\n },\n ];\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n <div className=\"section-head\">\n {header}\n <button\n type=\"button\"\n className=\"btn\"\n disabled={p == null}\n onClick={() => setModal({ mode: \"create\" })}\n >\n + Add document\n </button>\n </div>\n\n <div className=\"card\">\n {docsQuery.isLoading && <p className=\"muted\">Loading…</p>}\n {docsQuery.data?.length === 0 && empty}\n {docsQuery.data != null && docsQuery.data.length > 0 && (\n <DataTable\n columns={columns}\n rows={docsQuery.data}\n rowKey={(d) => d.id}\n getRowHref={getHref ? (d) => getHref(d.id) : undefined}\n onRowClick={onOpen ? (d, e) => onOpen(d.id, e) : undefined}\n />\n )}\n </div>\n </section>\n\n {modal && (\n <DocumentFormModal\n initial={modal.mode === \"edit\" ? modal.d : undefined}\n project={p}\n onClose={() => setModal(null)}\n onSaved={() => setModal(null)}\n />\n )}\n\n {pending && (\n <ConfirmModal\n title=\"Delete document\"\n message={`Delete the document \"${pending.key}\"? This cannot be undone.`}\n confirmLabel=\"Delete\"\n onConfirm={() => {\n if (p != null) deleteMut.mutate({ id: pending.id, project: p });\n setPending(null);\n }}\n onClose={() => setPending(null)}\n />\n )}\n </div>\n );\n}\n","/**\n * The dashboard's recent-activity rows, decided — which variant a ledger row\n * renders as, what its title says, and where that title links (T1.2.1).\n *\n * **Data only, never JSX.** `components/RecentActivityTile.tsx` is `.tsx` and\n * cannot be loaded by `node --test` (`package.json`'s `test:unit` glob loads\n * only `.ts` under `src/{lib,api,repos}/__tests__/`), exactly the constraint\n * `src/lib/resource-descriptors.ts` documents for itself for the same reason.\n * So the label table, the kind→variant `Record`, the two name maps and the two\n * formatters live here and are driven for real by\n * `__tests__/recent-activity.test.ts`; only the `<ListItem>` and the `<Link>`\n * stay in the component.\n *\n * The one non-local import is `import type`, erased by Node's type stripping —\n * so this module still loads with no `repos/` (and no React) on its runtime\n * import graph, while the entry type stays the WIRE shape rather than a second,\n * drift-prone copy of it.\n */\nimport type { DashboardStats } from \"../repos/dashboard.ts\";\n\n/** One row of the dashboard's \"Recent activity\" list — the pinned wire shape\n * (`DashboardStats[\"recent\"][number]`, widened by T1.1.2). */\nexport type RecentActivityEntry = DashboardStats[\"recent\"][number];\n\n/** Human labels for the ledger `kind` domain (mirrors the server's `run_log.kind`). */\nexport const KIND_LABELS: Record<string, string> = {\n workflow: \"Workflow run\",\n workflow_step: \"Workflow step\",\n connection_test: \"Connection test\",\n node_debug: \"Node debug\",\n // The synchronous arms, which joined the ledger with `0065_invocations`.\n // Without these three the rollup would render raw column values.\n function: \"Function call\",\n endpoint: \"Endpoint call\",\n action: \"App action\",\n};\n\n/**\n * The seven ledger kinds this module KNOWS — the arms the two `Record`s below\n * name explicitly, so a kind added to `run_log.kind` is a compile error here\n * rather than a row silently rendering as another kind (the same reasoning\n * `RESOURCE_DESCRIPTORS` gives for its total `Record`).\n */\nexport type ActivityKind =\n | \"workflow\"\n | \"workflow_step\"\n | \"connection_test\"\n | \"node_debug\"\n | \"function\"\n | \"endpoint\"\n | \"action\";\n\n/**\n * The label for a ledger kind. An unrecognised kind falls back to the raw value:\n * `kind` is a wire field and a client can be older than the server that answered\n * it — a raw `\"schedule\"` reads better than a blank row.\n */\nexport function kindLabel(kind: string): string {\n return KIND_LABELS[kind] ?? kind;\n}\n\n/** Which tile a row renders as: today's row, or one of the three named ones. */\nexport type TileVariant = \"base\" | \"function\" | \"workflow\" | \"workflow_step\";\n\n/**\n * The kind→variant table. Only the kinds that HAVE a name (or, for a step, an\n * id) to link to move off the base tile — `workflow_step` joined them in R-1,\n * titled `{workflow name} - {step id}` (R-2); endpoint/action rows keep\n * today's look (DC-6). Every other arm is spelled out rather than left to a\n * default, so dropping or adding a kind is a visible edit here.\n */\nexport const TILE_VARIANT: Record<ActivityKind, TileVariant> = {\n workflow: \"workflow\",\n workflow_step: \"workflow_step\",\n connection_test: \"base\",\n node_debug: \"base\",\n function: \"function\",\n endpoint: \"base\",\n action: \"base\",\n};\n\nfunction isActivityKind(kind: string): kind is ActivityKind {\n return Object.hasOwn(TILE_VARIANT, kind);\n}\n\n/**\n * The tile a row renders as — the ONE dispatcher `RecentActivityTile` reads.\n * An unknown kind is the base tile, never a missing render: the same\n * older-client-than-server case {@link kindLabel} answers.\n */\nexport function tileVariantFor(kind: string): TileVariant {\n return isActivityKind(kind) ? TILE_VARIANT[kind] : \"base\";\n}\n\n/**\n * The list rows the two name maps are built from, structurally: the SDK's\n * `FunctionSummary`/`WorkflowSummary` satisfy these without a cast, and a\n * fixture in the unit test needs no SDK round trip.\n */\nexport interface FunctionNameRow {\n id: string;\n /** The callable name; `null` on a `WorkflowSummary`, never on a Function. */\n key?: string | null;\n displayName?: string | null;\n}\n\nexport interface WorkflowNameRow {\n id: string;\n /** The stable slug; every Workflow has one. */\n name?: string | null;\n displayName?: string | null;\n}\n\n/** `id → display label` for the two kinds whose rows carry a name. */\nexport interface ActivityNameMaps {\n functions: ReadonlyMap<string, string>;\n workflows: ReadonlyMap<string, string>;\n}\n\n/**\n * Build the two `id → name` maps a tile resolves its title through.\n *\n * Both lists are the ACCOUNT-scoped reads `useFunctionsQuery()`/\n * `useWorkflowsQuery()` already make (DC-1) — the dashboard's own\n * `recentForAccount` is account-wide, so a project-narrowed list here would\n * label most rows with a raw `fn_…`/`wf_…` id. A missing list (its query still\n * loading, or failed) is an empty map: the tile then falls back to today's\n * title rather than blocking the row.\n *\n * The label is `displayName || key` for a Function and `displayName || name`\n * for a Workflow (the server's own fallback order). A row carrying neither is\n * left OUT of the map rather than mapped to `\"\"`: \"in the map\" then means\n * exactly \"there is a name to link to\", which is the rule\n * {@link resolveTileTitle} reads.\n */\nexport function buildNameMaps(\n functions?: readonly FunctionNameRow[],\n workflows?: readonly WorkflowNameRow[],\n): ActivityNameMaps {\n const functionNames = new Map<string, string>();\n for (const row of functions ?? []) {\n const label = row.displayName || row.key;\n if (label) functionNames.set(row.id, label);\n }\n const workflowNames = new Map<string, string>();\n for (const row of workflows ?? []) {\n const label = row.displayName || row.name;\n if (label) workflowNames.set(row.id, label);\n }\n return { functions: functionNames, workflows: workflowNames };\n}\n\n/** The resource a tile title links to — a studio route kind plus its id. */\nexport interface ActivityTileTarget {\n kind: \"function\" | \"workflow\";\n id: string;\n}\n\nexport interface ResolvedTileTitle {\n /** What the title reads: the resolved name, else today's `summary`/kind label. */\n text: string;\n /** Where it links, or `null` for a plain, unlinked title. */\n target: ActivityTileTarget | null;\n}\n\n/**\n * The title of one row — the name-as-link rule.\n *\n * A `function`/`workflow` row links ONLY when its id resolves to a name in the\n * maps above. Every other case — a base-variant kind, a `null` id, or an id the\n * list did not carry — is today's plain title (`summary ?? kindLabel(kind)`)\n * with no target, so a failed or still-loading name lookup degrades to the id\n * the row already shows instead of a dead link.\n *\n * A `workflow_step` row (R-1) is the same rule plus the step's own id: a\n * resolved workflow name makes the link, exactly as it does on a `workflow`\n * row, and the title reads `{workflow name} - {step id}` — a spaced ASCII\n * hyphen-minus, R-2. The step id IS the step's name — `core/rfcs/workflow.md`'s\n * `id` is its machine name and the editor's \"Rename step\" rewrites exactly that\n * — so no definition is fetched and no `notes` is read. When the workflow does\n * NOT resolve the left side is the workflow id itself, then the row's `summary`,\n * then `\"Unknown workflow\"` — never the kind label, since a title reading\n * \"Workflow step\" is exactly what R-1 rejected — and the target is `null`: a\n * link only when the name resolved. An absent `stepId` leaves the title as just\n * that left side.\n */\nexport function resolveTileTitle(\n entry: RecentActivityEntry,\n names: ActivityNameMaps,\n): ResolvedTileTitle {\n const fallback = entry.summary ?? kindLabel(entry.kind);\n const variant = tileVariantFor(entry.kind);\n if (variant === \"function\" && entry.functionId !== null) {\n const label = names.functions.get(entry.functionId);\n if (label !== undefined)\n return { text: label, target: { kind: \"function\", id: entry.functionId } };\n }\n if (variant === \"workflow\" && entry.workflowId !== null) {\n const label = names.workflows.get(entry.workflowId);\n if (label !== undefined)\n return { text: label, target: { kind: \"workflow\", id: entry.workflowId } };\n }\n if (variant === \"workflow_step\") {\n const workflowId = entry.workflowId;\n const label = workflowId !== null ? names.workflows.get(workflowId) : undefined;\n const left = label ?? workflowId ?? entry.summary ?? \"Unknown workflow\";\n const links = label !== undefined && workflowId !== null;\n return {\n text: entry.stepId ? `${left} - ${entry.stepId}` : left,\n target: links ? { kind: \"workflow\", id: workflowId } : null,\n };\n }\n return { text: fallback, target: null };\n}\n\nconst pad2 = (n: number) => String(n).padStart(2, \"0\");\n\n/**\n * A row's timestamp in LOCAL time as `YYYY-MM-DD HH:mm:ss`, 24-hour and\n * zero-padded — the exact, sortable, unambiguous stamp a ledger row wants.\n *\n * `toLocaleString` is deliberately NOT reused (what this replaces): its output\n * is locale-dependent (\"Jan 5, 7:08 AM\", no seconds) and so unreadable as a\n * timestamp. The `get*` accessors, never the `getUTC*` ones, are what make this\n * the viewer's own wall clock. An unparseable value is returned unchanged —\n * better the raw string than `NaN-NaN-NaN`.\n */\nexport function formatTimestamp(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const date = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;\n return `${date} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;\n}\n\n/**\n * A duration in milliseconds, or `null` when there is nothing to show.\n *\n * Three magnitudes, three units, so the number stays readable at every scale:\n * sub-second in ms, sub-minute in seconds to one decimal, and minutes+seconds\n * above that. `null`/`undefined`/negative/non-finite are all \"unknown\" — the\n * ledger writes none of them on purpose, and a tile that renders `NaN s` is\n * worse than one that renders nothing (DC-2: historical rows simply omit it).\n */\nexport function formatDuration(ms: number | null | undefined): string | null {\n if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return null;\n if (ms < 1000) return `${Math.round(ms)} ms`;\n if (ms < 60_000) return `${(Math.floor(ms / 100) / 10).toFixed(1)} s`;\n return `${Math.floor(ms / 60_000)}m ${Math.floor((ms % 60_000) / 1000)}s`;\n}\n","import { ListItem } from \"@w6w/ui\";\nimport type { MouseEvent, ReactElement, ReactNode } from \"react\";\nimport { useMemo } from \"react\";\nimport {\n type ActivityNameMaps,\n type ActivityTileTarget,\n type RecentActivityEntry,\n type TileVariant,\n buildNameMaps,\n formatDuration,\n formatTimestamp,\n kindLabel,\n resolveTileTitle,\n tileVariantFor,\n} from \"../lib/recent-activity.ts\";\nimport { type DashboardStats, useDashboardStatsQuery } from \"../repos/dashboard.ts\";\nimport { useFunctionsQuery } from \"../repos/functions.ts\";\nimport { useWorkflowsQuery } from \"../repos/workflows.ts\";\n\nexport type { ActivityTileTarget };\n\nexport interface ActivitySummaryProps {\n /** Real `href` for a resolved name; given ⇒ the title is an `<a>` (middle-click, new tab). */\n getHref?: (target: ActivityTileTarget) => string;\n /** A click on a resolved name. Never `preventDefault`ed here: the host decides. */\n onOpen?: (target: ActivityTileTarget, event: MouseEvent<Element>) => void;\n slots?: {\n /** Above everything (after the error banner). */\n header?: ReactNode;\n /** A row of host actions under `header`. */\n actions?: ReactNode;\n /** Replaces the \"No runs yet…\" copy. */\n empty?: ReactNode;\n /** Between the two headline rows and \"Activity over time\" (Studio puts its board here). */\n betweenHeadlineAndSeries?: ReactNode;\n };\n}\n\n/** Start of the current local day, as an ISO string — the \"today\" window edge. */\nfunction startOfTodayIso(): string {\n const d = new Date();\n d.setHours(0, 0, 0, 0);\n return d.toISOString();\n}\n\n/**\n * Render a series bucket start as a label. FU-6: a `week` bucket is the Monday that\n * `date_trunc('week', …)` truncates to, so it must read as a week range (\"Week of Jul 21\"),\n * not a bare date, or a weekly chart's axis is misleading.\n */\nfunction formatBucketLabel(iso: string, bucket: \"day\" | \"week\"): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const day = d.toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" });\n return bucket === \"week\" ? `Week of ${day}` : day;\n}\n\n/** ✓ / ✗ / – status glyph for an outcome that may be unknown (`ok === null`). */\nfunction OutcomeMark({ ok }: { ok: boolean | null }) {\n if (ok === null) return <span className=\"muted\">–</span>;\n return <span className={ok ? \"ok\" : \"error\"}>{ok ? \"✓\" : \"✗\"}</span>;\n}\n\n/** A single headline stat card: a big count over a muted label. */\nfunction StatCard({ label, value }: { label: string; value: number }) {\n return (\n <div className=\"w6w-activity-card w6w-activity-stat\">\n <div className=\"w6w-activity-stat-value\">{value}</div>\n <div className=\"muted small\">{label}</div>\n </div>\n );\n}\n\n/** A titled row of headline stat cards for one time window. */\nfunction HeadlineRow({\n title,\n headline,\n loading,\n}: {\n title: string;\n headline: DashboardStats[\"headline\"] | undefined;\n loading: boolean;\n}) {\n const h = headline ?? { workflowRuns: 0, succeeded: 0, failed: 0 };\n return (\n <section className=\"w6w-activity-section\">\n <h3>{title}</h3>\n {loading ? (\n <p className=\"muted\">Loading…</p>\n ) : (\n <div className=\"w6w-activity-stats\">\n <StatCard label=\"Workflow runs\" value={h.workflowRuns} />\n <StatCard label=\"Succeeded\" value={h.succeeded} />\n <StatCard label=\"Failed\" value={h.failed} />\n </div>\n )}\n </section>\n );\n}\n\ntype LinkProps = Pick<ActivitySummaryProps, \"getHref\" | \"onOpen\">;\n\n/**\n * The row's title: the resolved resource NAME as a link — `<a href>` when `getHref` is given,\n * else a `<button>` when only `onOpen` is — or plain text when no name resolved or the host gave\n * neither. It sits INSIDE `ListItem`'s `title` slot, never `ListItem`'s own `href`/`onClick`.\n */\nfunction ActivityTitle({\n entry,\n names,\n getHref,\n onOpen,\n}: LinkProps & { entry: RecentActivityEntry; names: ActivityNameMaps }) {\n const { text, target } = resolveTileTitle(entry, names);\n if (target === null) return <>{text}</>;\n const click = onOpen ? (event: MouseEvent<Element>) => onOpen(target, event) : undefined;\n if (getHref) {\n return (\n <a href={getHref(target)} onClick={click}>\n {text}\n </a>\n );\n }\n if (click) {\n return (\n <button type=\"button\" className=\"w6w-activity-link\" onClick={click}>\n {text}\n </button>\n );\n }\n return <>{text}</>;\n}\n\n/** The base tile: status glyph, title over `\"<kind> · <local timestamp>\"`, duration on the right. */\nfunction BaseActivityTile({ entry, title }: { entry: RecentActivityEntry; title?: ReactNode }) {\n const duration = formatDuration(entry.durationMs);\n return (\n <ListItem\n icon={<OutcomeMark ok={entry.ok} />}\n title={title ?? entry.summary ?? kindLabel(entry.kind)}\n subtitle={`${kindLabel(entry.kind)} · ${formatTimestamp(entry.occurredAt)}`}\n trailing={duration === null ? undefined : <span className=\"muted small\">{duration}</span>}\n />\n );\n}\n\ntype TileProps = LinkProps & { entry: RecentActivityEntry; names: ActivityNameMaps };\n\n/** The `function`, `workflow` and `workflow_step` tiles differ only in which name `resolveTileTitle` reads. */\nfunction NamedActivityTile(props: TileProps) {\n return <BaseActivityTile entry={props.entry} title={<ActivityTitle {...props} />} />;\n}\n\n/** The one dispatcher: the variant table's arm for this row's kind. */\nconst TILES: Record<TileVariant, (props: TileProps) => ReactElement> = {\n base: (p) => <BaseActivityTile entry={p.entry} />,\n function: NamedActivityTile,\n workflow: NamedActivityTile,\n workflow_step: NamedActivityTile,\n};\n\nfunction RecentActivityTile(props: TileProps) {\n const Tile = TILES[tileVariantFor(props.entry.kind)];\n return <Tile {...props} />;\n}\n\n/**\n * The account's run statistics and recent activity: \"Today\" and \"Last 7 days\" headline cards,\n * \"Activity over time\" and \"Recent activity\". Account-scoped (no `project`); it never navigates —\n * opening a resolved name is the host's `onOpen` / `getHref`.\n *\n * Two `/dashboard/stats` requests, deliberately: `today` is `{ from: <local start of day>,\n * bucket: \"day\" }` and `week` is `{ bucket: \"week\" }`. The server's only buckets are `day|week`,\n * cut in the database's timezone, so no single request can cut at the viewer's local midnight.\n */\nexport function ActivitySummary({ getHref, onOpen, slots }: ActivitySummaryProps): ReactElement {\n const todayQuery = useDashboardStatsQuery(\"today\", { from: startOfTodayIso(), bucket: \"day\" });\n const weekQuery = useDashboardStatsQuery(\"week\", { bucket: \"week\" });\n\n // A row's title is the Function's/Workflow's own display name, resolved against these two\n // account-scoped lists. Both are deliberately UNSCOPED: the ledger is account-wide, so a\n // project-narrowed list would answer \"no name\" for every row outside the project. Neither\n // query's error is surfaced: a failed lookup just leaves the plain title.\n const functionsQuery = useFunctionsQuery();\n const workflowsQuery = useWorkflowsQuery();\n const names = useMemo(\n () => buildNameMaps(functionsQuery.data, workflowsQuery.data),\n [functionsQuery.data, workflowsQuery.data],\n );\n\n const error = todayQuery.error ?? weekQuery.error;\n const errorMessage = error ? (error as Error).message : null;\n\n const recent = weekQuery.data?.recent ?? [];\n const series = weekQuery.data?.series ?? [];\n const weekBucket = weekQuery.data?.range.bucket ?? \"week\";\n\n const nothingYet =\n !weekQuery.isLoading &&\n recent.length === 0 &&\n (weekQuery.data?.headline.workflowRuns ?? 0) === 0;\n\n return (\n <div className=\"w6w-embed-root\">\n {errorMessage && <div className=\"error\">{errorMessage}</div>}\n {slots?.header}\n {slots?.actions}\n\n <HeadlineRow\n title=\"Today\"\n headline={todayQuery.data?.headline}\n loading={todayQuery.isLoading}\n />\n <HeadlineRow\n title=\"Last 7 days\"\n headline={weekQuery.data?.headline}\n loading={weekQuery.isLoading}\n />\n\n {slots?.betweenHeadlineAndSeries}\n\n <section className=\"w6w-activity-section\">\n <h3>Activity over time</h3>\n <div className=\"w6w-activity-card\">\n {weekQuery.isLoading ? (\n <p className=\"muted\">Loading…</p>\n ) : series.length === 0 ? (\n <p className=\"muted\">No activity in this window yet.</p>\n ) : (\n <ul className=\"list\">\n {series.map((s) => (\n <li key={`${s.bucket}-${s.kind}-${String(s.ok)}`}>\n <span className=\"list-main\">\n <strong>{formatBucketLabel(s.bucket, weekBucket)}</strong>{\" \"}\n <span className=\"muted small\">{kindLabel(s.kind)}</span>\n </span>{\" \"}\n <OutcomeMark ok={s.ok} /> <span className=\"muted small\">{s.count}</span>\n </li>\n ))}\n </ul>\n )}\n </div>\n </section>\n\n <section>\n <h3 className=\"w6w-activity-h3\">Recent activity</h3>\n <div className=\"w6w-activity-card\">\n {weekQuery.isLoading ? (\n <p className=\"muted\">Loading…</p>\n ) : nothingYet ? (\n (slots?.empty ?? (\n <p className=\"muted\">No runs yet — activity shows up here once your workflows run.</p>\n ))\n ) : recent.length === 0 ? (\n <p className=\"muted\">No recent activity in this window.</p>\n ) : (\n <div className=\"list\">\n {recent.map((r) => (\n <RecentActivityTile\n key={r.id}\n entry={r}\n names={names}\n getHref={getHref}\n onOpen={onOpen}\n />\n ))}\n </div>\n )}\n </div>\n </section>\n </div>\n );\n}\n","import { type ReactElement, useState } from \"react\";\nimport { HistoryView, type HistoryViewProps } from \"../chrome/HistoryView.tsx\";\nimport {\n EMPTY_HISTORY_FILTERS,\n type HistoryFilters,\n type HistoryScope,\n} from \"../lib/history-query.ts\";\nimport { useEmbedProject } from \"../project-context.ts\";\n\nexport interface RunHistoryProps extends Partial<HistoryViewProps> {}\n\n/** A scope names a project when it carries `project` rather than `callable`. */\nfunction isProjectScope(scope: HistoryScope | null): boolean {\n return scope !== null && \"project\" in scope;\n}\n\n/**\n * The execution history: stats, filters, the paged list and the selected run's detail. A thin\n * wrapper over `chrome/HistoryView` (which owns the queries). `scope` omitted ⇒ the provider's\n * project (disabled while it is unresolved); `filters` omitted ⇒ held here, given ⇒ controlled by\n * the host. Never navigates.\n */\nexport function RunHistory(props: RunHistoryProps): ReactElement {\n const provided = useEmbedProject().project;\n const [own, setOwn] = useState<HistoryFilters>(EMPTY_HISTORY_FILTERS);\n\n const scope: HistoryScope | null =\n props.scope !== undefined ? props.scope : provided ? { project: provided } : null;\n const controlled = props.filters !== undefined;\n const filters = props.filters ?? own;\n\n const onFiltersChange = (next: HistoryFilters) => {\n if (!controlled) setOwn(next);\n props.onFiltersChange?.(next);\n };\n\n return (\n <div className=\"w6w-embed-root\">\n <HistoryView\n scope={scope}\n showKind={props.showKind ?? isProjectScope(scope)}\n filters={filters}\n onFiltersChange={onFiltersChange}\n onOpenInEditor={props.onOpenInEditor}\n />\n </div>\n );\n}\n","import type { ReactElement, ReactNode } from \"react\";\nimport { RunHistory, type RunHistoryProps } from \"./RunHistory.tsx\";\n\nexport interface LogsProps extends RunHistoryProps {\n /** The heading above the view. Defaults to `\"Logs\"`; `null` renders none (the host titles its\n * own page). */\n title?: ReactNode | null;\n}\n\n/**\n * The project's Logs: the most recent executions of every workflow, function and endpoint in the\n * provider's project, newest first, and the selected one's detail (input, output, error, a\n * workflow run's steps) opened in place. `RunHistory` under a heading — Studio's History page\n * mounts the same body — so every `RunHistory` prop applies, and with none of them it is\n * project-wide with filters held here. Never navigates; `onOpenInEditor` is the host's way into a\n * workflow run's editor.\n */\nexport function Logs({ title = \"Logs\", ...rest }: LogsProps): ReactElement {\n return (\n <div className=\"w6w-embed-root w6w-embed-logs\">\n {title !== null && <h2>{title}</h2>}\n <RunHistory {...rest} />\n </div>\n );\n}\n\n/** {@link Logs} under the name a host routing table tends to use for a page. */\nexport const LogsView = Logs;\nexport type LogsViewProps = LogsProps;\n","/**\n * Pure projections behind `ServiceDetail.tsx`'s `VendorPanel` and its\n * `<HistoryTimeline>` lane — split out so `node --test` can gate them\n * directly, same reason `src/lib/alias-rail.ts` and `src/repos/\n * reliability-uptime.ts` give: nothing here does I/O and nothing reads the\n * clock itself, so every value a caller sees was decided by an argument, not\n * a hidden `Date.now()`.\n *\n * Holds NO reliability logic (STRATEGY §5.1): a vendor's `state` and a\n * timeline entry's `state` are rendered exactly as they arrived. What lives\n * here is projection and formatting only — reshaping `timeline` into\n * `HistoryTimeline`'s `VendorIncidentBar[]`, and turning an open incident's\n * two timestamps into a readable age — never a re-decided verdict.\n */\nimport type {\n ReliabilityComponentReport,\n ReliabilityTimelineEntry,\n ReliabilityVendorStatus,\n} from \"@w6w/sdk/console\";\nimport type { VendorIncidentBar } from \"@w6w/ui\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * `vendor.timeline` → `HistoryTimeline`'s `incidents` prop.\n *\n * `undefined` and `[]` are DIFFERENT FACTS carried through unchanged, never\n * collapsed into each other: `undefined` means \"this vendor publishes no\n * incident history at all\" (Stripe, and every app but Slack — the majority\n * case), `[]` means \"it does, and nothing is in it\" (a quiet Slack window).\n * Losing that distinction here would throw away Stripe's honest answer.\n */\nexport function projectVendorIncidents(\n vendor: ReliabilityVendorStatus | null,\n): VendorIncidentBar[] | undefined {\n if (vendor === null || vendor.timeline === null) return undefined;\n return vendor.timeline.map((entry) => ({\n id: entry.id,\n title: entry.title,\n state: entry.state,\n startedAt: entry.startedAt,\n updatedAt: entry.updatedAt,\n resolvedAt: entry.resolvedAt,\n components: entry.components,\n link: entry.link,\n }));\n}\n\n/**\n * An entry counts as an OPEN incident iff it has a `startedAt` and no\n * `resolvedAt`. An entry with neither is a feed-only update (a status-page\n * note with no span attached) — never an outage — so it is deliberately\n * excluded rather than defaulting to \"open\".\n */\nexport function isOpenIncident(entry: ReliabilityTimelineEntry): boolean {\n return entry.startedAt !== undefined && entry.resolvedAt === undefined;\n}\n\nfunction formatCalendarDay(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n // Pinned to UTC and a fixed locale — this runs inside a unit test as well\n // as the browser, and neither the CI container's timezone nor its ICU\n // locale should change what a fixture asserts.\n return d.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", timeZone: \"UTC\" });\n}\n\nfunction daysBetween(fromIso: string, toMs: number): number {\n const fromMs = new Date(fromIso).getTime();\n if (Number.isNaN(fromMs)) return 0;\n return Math.max(0, Math.floor((toMs - fromMs) / DAY_MS));\n}\n\n/**\n * The age/recovery copy for one OPEN incident — `null` for anything else\n * (not open, or missing `startedAt`), so this stays total rather than\n * throwing on a shape the caller failed to filter.\n *\n * A TOTAL FUNCTION OF `(entry, nowMs)` — `nowMs` is always the caller's\n * argument, never `Date.now()` read in here, which is what makes a\n * ten-day-old incident whose last note is three days old provably render\n * differently from one that started an hour ago: both facts (how long it has\n * been open, how stale the last note is) are day counts computed against the\n * SAME passed-in clock, not two independent reads of the real one.\n */\nexport function incidentAgeCopy(entry: ReliabilityTimelineEntry, nowMs: number): string | null {\n if (!isOpenIncident(entry) || entry.startedAt === undefined) return null;\n\n const ageDays = daysBetween(entry.startedAt, nowMs);\n const startLabel = formatCalendarDay(entry.startedAt);\n const openPart =\n ageDays === 0 ? `open since ${startLabel} (today)` : `open ${ageDays}d (since ${startLabel})`;\n\n const updateIso = entry.updatedAt ?? entry.startedAt;\n const updateDays = daysBetween(updateIso, nowMs);\n const updateLabel = formatCalendarDay(updateIso);\n const updatePart =\n updateDays === 0\n ? `last update ${updateLabel} (today)`\n : `last update ${updateLabel} (${updateDays}d ago)`;\n\n return `${openPart} · ${updatePart}`;\n}\n\n/**\n * `vendor.components` → a stable `[name, report][]` list, `null`-safe. A\n * `null` map (no public check ever reported a breakdown) and an empty one\n * both come back `[]`, so the caller's \"render nothing\" branch is a single\n * length check instead of a `null`-then-`Object.entries` chain repeated at\n * every call site.\n */\nexport function vendorComponentEntries(\n components: Record<string, ReliabilityComponentReport> | null,\n): Array<[string, ReliabilityComponentReport]> {\n return components ? Object.entries(components) : [];\n}\n","import { ApiError } from \"@w6w/sdk\";\nimport type { ApiCallRecord } from \"@w6w/sdk/console\";\nimport { HealthStatusPill, HistoryTimeline } from \"@w6w/ui\";\nimport type { HistoryWindow, UptimeDay } from \"@w6w/ui\";\nimport type { MouseEvent, ReactElement, ReactNode } from \"react\";\nimport { useEmbedProject } from \"../project-context.ts\";\nimport { useApiCallsQuery } from \"../repos/api-calls.ts\";\nimport type { ReliabilityErrorMix, ReliabilityService } from \"../repos/reliability.ts\";\nimport { useReliabilityQuery } from \"../repos/reliability.ts\";\nimport {\n incidentAgeCopy,\n isOpenIncident,\n projectVendorIncidents,\n vendorComponentEntries,\n} from \"./vendor-history.ts\";\n\n/**\n * One service, drilled into: health, error mix, the API's own status, daily history and the recent\n * calls. Moved from Studio's `/reliability/:appId` page (E-3).\n *\n * **One single-service read.** The row comes from `GET /reliability/services?apps=<appId>` —\n * `useReliabilityQuery(project, [appId], days)` — never the whole board. The one other read is the\n * call log (`GET /api-calls?appId=`), the actual drill from \"this service looks like that\" to\n * \"here are the requests behind it\".\n *\n * Holds NO reliability logic (STRATEGY §5.1): every state rendered arrived decided by the server.\n */\n\n/** The uptime strip's cells: the server's own array, in order — no sort, no reverse, no gap fill. */\nfunction uptimeDays(service: ReliabilityService): UptimeDay[] {\n return service.uptime.map((entry) => ({ day: entry.day, state: entry.state }));\n}\n\nconst ERROR_KINDS: Array<[keyof ReliabilityErrorMix, string]> = [\n [\"e4xx\", \"4xx\"],\n [\"e429\", \"429 rate-limited\"],\n [\"eAuth\", \"auth (401/403)\"],\n [\"e5xx\", \"5xx\"],\n];\n\nfunction formatDay(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n return d.toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" });\n}\n\nfunction formatStamp(iso: string | null | undefined): string {\n if (!iso) return \"—\";\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n return d.toLocaleString(undefined, {\n month: \"short\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n}\n\n/** One labelled figure in the summary strip. */\nfunction Stat({ label, value, hint }: { label: string; value: string; hint?: string }) {\n return (\n <div className=\"w6w-rel-card\" style={{ flex: \"1 1 150px\", minWidth: 150 }}>\n <div style={{ fontSize: \"1.6rem\", fontWeight: \"var(--w6w-fw-semibold)\", lineHeight: 1.15 }}>\n {value}\n </div>\n <div className=\"muted small\">{label}</div>\n {hint && <div className=\"muted small\">{hint}</div>}\n </div>\n );\n}\n\n/**\n * The vendor's own verdict, expanded. Unlike the board's compact pill this has\n * room for the attribution — WHICH declared check decided it and when it last\n * actually ran — which is what turns \"degraded\" into something checkable.\n *\n * A SECOND, INDEPENDENT signal from the \"from your calls\" pill above it on\n * the page — never a restatement. Every sentence in here is deliberately\n * phrased as \"what {displayName} says about itself\", so the panel still\n * reads as a different question even once the generic noun \"vendor\" is gone\n * from its own copy (the section wrapper's `<h3>Vendor</h3>` stays generic —\n * that heading is a category label, not this panel's business).\n */\nfunction VendorPanel({\n vendor,\n displayName,\n}: {\n vendor: ReliabilityService[\"vendorStatus\"];\n displayName: string;\n}) {\n if (!vendor) {\n return (\n <div className=\"w6w-rel-card\">\n <h4 style={{ margin: \"0 0 var(--w6w-sp-1)\" }}>{displayName} status</h4>\n <p className=\"muted\">\n {displayName} publishes no public health check, so there is nothing to ask about it. That\n is a statement about {displayName}, not a gap in the data above.\n </p>\n </div>\n );\n }\n // `unknown` here means the probe ran and told us nothing usable — the status\n // page moved, went dark, or answered with something we don't recognise. That\n // is a gap in OUR reading of the API, not a finding about it, and the panel\n // has to say so plainly: the footer below would otherwise claim we \"read\" a\n // page we could not read.\n const unreadable = vendor.state === \"unknown\";\n\n const components = vendorComponentEntries(vendor.components);\n const openIncidents = (vendor.timeline ?? []).filter(isOpenIncident);\n const nowMs = Date.now();\n\n return (\n <div className=\"w6w-rel-card\">\n <h4 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n {displayName} status{\" \"}\n <HealthStatusPill state={vendor.state} label={unreadable ? \"Unavailable\" : undefined} />\n </h4>\n {unreadable && (\n <p style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n We could not get a status from this API, so we cannot say whether it is up. That is\n separate from your own calls above, which are measured here regardless.\n </p>\n )}\n {vendor.message && (\n <p\n className={unreadable ? \"muted small\" : undefined}\n style={{ margin: \"0 0 var(--w6w-sp-2)\" }}\n >\n {vendor.message}\n </p>\n )}\n <p className=\"muted small\" style={{ margin: 0 }}>\n {unreadable ? \"Tried to read\" : \"Read from\"} {displayName}'s own status page — what{\" \"}\n {displayName} says about itself, not what your calls did · last checked{\" \"}\n {formatStamp(vendor.checkedAt)}\n {vendor.attributedTo.length > 0 && (\n <>\n {\" \"}\n · decided by{\" \"}\n {vendor.attributedTo.map((k) => (\n <code key={k}>{k}</code>\n ))}\n </>\n )}\n </p>\n\n {components.length > 0 && (\n <div className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n {components.map(([name, comp]) => (\n <span key={name} className=\"w6w-rel-tag\">\n {name}: {comp.state}\n </span>\n ))}\n </div>\n )}\n\n {openIncidents.length > 0 && (\n <ul className=\"list\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n {openIncidents.map((entry) => (\n <li key={entry.id ?? entry.title}>\n <div className=\"list-main\">\n <strong>{entry.title}</strong> <HealthStatusPill state={entry.state} />\n <div className=\"muted small\">{incidentAgeCopy(entry, nowMs)}</div>\n </div>\n </li>\n ))}\n </ul>\n )}\n\n {vendor.statusPageUrl !== null && (\n <p className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n <a href={vendor.statusPageUrl} target=\"_blank\" rel=\"noopener noreferrer\">\n {displayName}'s status page ↗\n </a>\n </p>\n )}\n </div>\n );\n}\n\n/**\n * Calls per day, oldest first — the one time series this page has that the\n * board doesn't: `service.uptime` carries a real per-day call count, so this\n * is a genuine trend chart, not a single-number stat. Bar HEIGHT is volume;\n * bar COLOUR is that day's own state, the same `--w6w-health-*` tokens the\n * pill and strip read, so a volume spike and a bad day are one picture\n * instead of two separately-read facts.\n */\nfunction DailyVolumeChart({ service }: { service: ReliabilityService }) {\n // Same call as the board row (ReliabilityBoard.tsx): a zero-call window is\n // 30 identical `unknown` days, so a bar chart of them is 30 identical\n // slivers — the plain note matches the board's own wording instead.\n if (service.calls === 0) {\n return (\n <div className=\"w6w-rel-card\">\n <span className=\"w6w-rel-idle-note\">No calls in this window</span>\n </div>\n );\n }\n const days = service.uptime;\n const maxCalls = Math.max(1, ...days.map((d) => d.calls));\n return (\n <div className=\"w6w-rel-card\">\n <div\n className=\"rel-daily-chart\"\n role=\"img\"\n aria-label={`${service.displayName}, calls per day, oldest first`}\n >\n {days.map((d) => (\n <span\n key={d.day}\n className={`rel-daily-bar rel-daily-bar-${d.state}`}\n // A zero-call day still gets a hairline sliver — an invisible bar\n // reads as \"missing data\", not \"zero\", which is exactly the\n // distinction `unknown` vs `ok` exists to preserve.\n style={{ height: `${d.calls > 0 ? Math.max((d.calls / maxCalls) * 100, 4) : 2}%` }}\n title={`${formatDay(`${d.day}T00:00:00.000Z`)} — ${d.calls} calls, ${d.state}`}\n />\n ))}\n </div>\n <p className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n Calls per day, oldest first. Bar colour is that day's own state.\n </p>\n </div>\n );\n}\n\n/**\n * The window's per-day breakdown — our execution history and the vendor's own\n * incident history, on ONE shared axis (`HistoryTimeline`), plus the numbers\n * behind each execution cell below it. Two lanes plotted side by side without\n * a shared axis is the failure mode the human asked to avoid, so both are\n * always the SAME `window` — the board payload's own — never a second window\n * derived from the timeline's own extent.\n */\nfunction UptimeDetail({\n service,\n window: historyWindow,\n}: {\n service: ReliabilityService;\n window: HistoryWindow;\n}) {\n // Newest first here (the board's strip is oldest-first and stays that way):\n // a list is read top-down, and \"what happened lately\" is the question.\n const withTraffic = [...service.uptime].reverse().filter((d) => d.calls > 0);\n const vendor = service.vendorStatus;\n const incidents = projectVendorIncidents(vendor);\n const vendorEmptyLabel =\n incidents === undefined\n ? `${service.displayName} publishes no incident history.`\n : `No incidents from ${service.displayName} in this window.`;\n return (\n <div className=\"w6w-rel-card\">\n <HistoryTimeline\n window={historyWindow}\n days={uptimeDays(service)}\n incidents={incidents}\n vendorEmptyLabel={vendorEmptyLabel}\n ariaLabel={`${service.displayName}, ${service.uptime.length}-day status and ${service.displayName} incidents, oldest day first`}\n />\n <p className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n Oldest day leftmost. Days with no calls are <code>unknown</code> — never a quiet green.\n </p>\n {withTraffic.length > 0 && (\n <div className=\"list\" style={{ marginTop: \"var(--w6w-sp-3)\" }}>\n {withTraffic.slice(0, 14).map((d) => (\n <div key={d.day} className=\"rel-day-row\">\n <span style={{ minWidth: 96 }}>\n <strong>{formatDay(`${d.day}T00:00:00.000Z`)}</strong>\n </span>\n <HealthStatusPill state={d.state} />\n <span className=\"muted small\">{d.calls} calls</span>\n <span className=\"rel-errors\">\n {ERROR_KINDS.filter(([k]) => d.errors[k] > 0).map(([k, label]) => (\n <span className=\"w6w-rel-tag\" key={k}>\n {label} ×{d.errors[k]}\n </span>\n ))}\n </span>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n}\n\n/** The error mix, as bars rather than the board's bare count chips — same four kinds, same order. */\nfunction ErrorMixChart({ errors }: { errors: ReliabilityErrorMix }) {\n const total = ERROR_KINDS.reduce((sum, [k]) => sum + errors[k], 0);\n if (total === 0) {\n return (\n <div className=\"w6w-rel-card\">\n <p className=\"muted\" style={{ margin: 0 }}>\n No errors in this window.\n </p>\n </div>\n );\n }\n const max = Math.max(1, ...ERROR_KINDS.map(([k]) => errors[k]));\n return (\n <div className=\"w6w-rel-card rel-errormix-chart\">\n {ERROR_KINDS.map(([k, label]) => (\n <div key={k} className=\"rel-errormix-row\">\n <span className=\"muted small\">{label}</span>\n <span className=\"rel-errormix-track\">\n <span\n className=\"rel-errormix-bar\"\n style={{ width: `${Math.max((errors[k] / max) * 100, errors[k] > 0 ? 2 : 0)}%` }}\n />\n </span>\n <span className=\"rel-errormix-value small\">{errors[k]}</span>\n </div>\n ))}\n </div>\n );\n}\n\n/** The drill proper: the actual requests behind the numbers above. */\nfunction CallLog({ project, appId }: { project: string | undefined; appId: string }) {\n const query = useApiCallsQuery(project, appId, { limit: 50 });\n\n if (query.isLoading) return <p className=\"muted\">Loading calls…</p>;\n if (query.error) {\n const e = query.error;\n return <div className=\"error\">{e instanceof ApiError ? e.message : (e as Error).message}</div>;\n }\n const calls: ApiCallRecord[] = query.data ?? [];\n if (calls.length === 0) {\n return (\n <p className=\"muted\">\n No calls captured for this service. Calls appear here once a workflow, function or ad-hoc\n invoke reaches it.\n </p>\n );\n }\n return (\n <div className=\"rel-calls\">\n <div className=\"rel-call rel-call-head\">\n <span>When</span>\n <span>Action</span>\n <span>Method</span>\n <span>Status</span>\n <span>Took</span>\n </div>\n {calls.map((call, i) => (\n <div className=\"rel-call\" key={call.id ?? `${call.createdAt}-${i}`}>\n <span className=\"muted small\">{formatStamp(call.createdAt)}</span>\n <span>\n <code>{call.actionKey ?? \"—\"}</code>\n </span>\n <span className=\"muted small\">{call.method}</span>\n <span className={call.status >= 400 || call.status === 0 ? \"error\" : \"ok\"}>\n {/* 0 means the request never got a response at all; `error` says why. */}\n {call.status === 0 ? \"no response\" : call.status}\n </span>\n <span className=\"muted small\">\n {call.durationMs != null ? `${call.durationMs} ms` : \"—\"}\n </span>\n </div>\n ))}\n </div>\n );\n}\n\nexport interface ServiceDetailProps {\n /** The service's app id (e.g. `twilio`). */\n appId: string;\n /** Omitted ⇒ the provider's project; none anywhere ⇒ no request and a \"select a project\" note. */\n project?: string;\n /** Window size in days, sent with the status request (default 30). */\n days?: number;\n /** With `backHref` the not-found card's back link is a real `<a href>`. */\n backHref?: string;\n /** Called on a click of the back link; never cancelled by the component. Alone ⇒ a `<button>`. */\n onBack?: (event: MouseEvent<Element>) => void;\n /** `header`/`actions` sit above the detail; `empty` replaces the not-found copy. */\n slots?: { header?: ReactNode; actions?: ReactNode; empty?: ReactNode };\n}\n\n/** The back link under the not-found copy: an anchor, a button, or nothing. */\nfunction BackLink({\n backHref,\n onBack,\n}: {\n backHref?: string;\n onBack?: (event: MouseEvent<Element>) => void;\n}) {\n if (backHref !== undefined) {\n return (\n <p>\n <a href={backHref} onClick={onBack}>\n ← Back to all services\n </a>\n </p>\n );\n }\n if (onBack) {\n return (\n <p>\n <button type=\"button\" className=\"list-link\" onClick={onBack}>\n ← Back to all services\n </button>\n </p>\n );\n }\n return null;\n}\n\nexport function ServiceDetail({\n appId,\n project,\n days = 30,\n backHref,\n onBack,\n slots,\n}: ServiceDetailProps): ReactElement {\n const provided = useEmbedProject().project;\n const effective = (project === undefined ? provided : project) || undefined;\n const query = useReliabilityQuery(effective, [appId], days);\n\n const error = query.error;\n const errorMessage = error\n ? error instanceof ApiError\n ? error.message\n : (error as Error).message\n : null;\n const service = query.data?.services.find((s) => s.appId === appId);\n\n return (\n <div className=\"w6w-embed-root\">\n {slots?.header}\n {slots?.actions}\n\n {!effective && <p className=\"w6w-muted\">Select a project to see this service.</p>}\n {errorMessage && <div className=\"error\">{errorMessage}</div>}\n {effective && query.isLoading && <p className=\"muted\">Loading…</p>}\n\n {query.data && !service && (\n <div className=\"w6w-rel-card\">\n {slots?.empty ?? (\n <p className=\"muted\">\n <code>{appId}</code> is not used by this project's definitions and has no calls in the\n last {days} days.\n </p>\n )}\n <BackLink backHref={backHref} onBack={onBack} />\n </div>\n )}\n\n {service && (\n <>\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"var(--w6w-sp-3)\",\n marginBottom: \"var(--w6w-sp-3)\",\n }}\n >\n <HealthStatusPill state={service.state} />\n <span className=\"muted small\">from your calls</span>\n <code className=\"muted small\">{service.appId}</code>\n {service.ongoingOutageId && <span className=\"w6w-rel-tag\">outage still open</span>}\n </div>\n <div style={{ display: \"flex\", gap: \"var(--w6w-sp-3)\", flexWrap: \"wrap\" }}>\n <Stat label=\"Calls in window\" value={String(service.calls)} />\n <Stat\n label=\"p95 latency\"\n value={service.p95Ms === null ? \"—\" : `${service.p95Ms} ms`}\n hint={service.p95Ms === null ? \"no timed calls\" : undefined}\n />\n <Stat label=\"Last call\" value={formatStamp(service.lastCallAt)} />\n <Stat\n label=\"Errors\"\n value={String(ERROR_KINDS.reduce((sum, [k]) => sum + service.errors[k], 0))}\n hint={\n ERROR_KINDS.filter(([k]) => service.errors[k] > 0)\n .map(([k, label]) => `${label} ×${service.errors[k]}`)\n .join(\" · \") || \"none\"\n }\n />\n </div>\n </section>\n\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>Error mix</h3>\n <ErrorMixChart errors={service.errors} />\n </section>\n\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>API status</h3>\n <VendorPanel vendor={service.vendorStatus} displayName={service.displayName} />\n </section>\n\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n Last {query.data?.window.days ?? days} days{\" \"}\n <span className=\"muted small\">uptime means {query.data?.uptimeMeans}</span>\n </h3>\n {/* Same `window` for both lanes of `HistoryTimeline` — the payload's own; the\n empty-string fallback is unreachable (`service` only exists once `query.data`\n has resolved) and exists purely so `window` stays required. */}\n <UptimeDetail service={service} window={query.data?.window ?? { from: \"\", to: \"\" }} />\n <DailyVolumeChart service={service} />\n </section>\n\n <section>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n Recent calls{\" \"}\n <span className=\"muted small\">the requests behind the numbers above</span>\n </h3>\n <div className=\"w6w-rel-card\">\n <CallLog project={effective} appId={service.appId} />\n </div>\n </section>\n </>\n )}\n </div>\n );\n}\n","/**\n * The rows of \"what uses this connection\" — shared by the delete confirm and ConnectionDetail.\n * Kind badge, name, the step/site ids; a link-button to the editor when the host supplies\n * `onOpenCallable`, plain text otherwise.\n */\nimport type { ConnectionDependentCallable } from \"@w6w/sdk/console\";\nimport { useState } from \"react\";\nimport { ModelRoutesManager } from \"../forms/ModelRoutesManager.tsx\";\n\nexport type OpenCallable = (kind: string, id: string) => void;\n\n/** `sites` is `unknown[]` on the wire; render each as a short id string. */\nexport function siteLabel(site: unknown): string {\n if (typeof site === \"string\") return site;\n if (site && typeof site === \"object\") {\n const o = site as Record<string, unknown>;\n for (const k of [\"stepId\", \"step\", \"id\", \"nodeId\", \"key\"]) {\n if (typeof o[k] === \"string\") return o[k] as string;\n }\n }\n return String(site);\n}\n\n/**\n * A model route that reaches the model through this connection. `broken` means the route stopped\n * resolving — typically this connection was removed or stopped working — and gets a reconnect.\n */\nexport interface ConnectionDependentRoute {\n id: string;\n name: string;\n status: \"active\" | \"broken\";\n /** The route's own project; Reconnect opens the editor there, whatever project the host is in. */\n project?: string;\n}\n\n/**\n * The `routes` section of a dependents payload. A `broken` route offers \"Reconnect\", which opens\n * the model-route editor for that route so a replacement connection can be picked (the editor\n * PATCHes `connection`). Active routes are listed without the action. `projectId` is passed\n * through to the editor; omitted, the provider's project applies.\n */\nexport function ConnectionDependentRoutes({\n routes,\n projectId,\n}: {\n routes: ConnectionDependentRoute[];\n projectId?: string | null;\n}) {\n const [reconnecting, setReconnecting] = useState<string | null>(null);\n const target = routes.find((r) => r.id === reconnecting);\n if (routes.length === 0) return null;\n return (\n <>\n <ul className=\"list small\" data-testid=\"connection-dependent-routes\">\n {routes.map((r) => (\n <li key={r.id} data-testid={`connection-dependent-route-${r.id}`}>\n <span className=\"badge\">route</span> <span>{r.name}</span>{\" \"}\n {r.status === \"broken\" && (\n <>\n <span className=\"tag warn\">broken</span>{\" \"}\n <button\n type=\"button\"\n className=\"btn link\"\n data-testid={`connection-route-reconnect-${r.id}`}\n onClick={() => setReconnecting(r.id)}\n >\n Reconnect\n </button>\n </>\n )}\n </li>\n ))}\n </ul>\n {target != null && (\n <ReconnectHost\n routeId={target.id}\n projectId={target.project ?? projectId}\n onDone={() => setReconnecting(null)}\n />\n )}\n </>\n );\n}\n\n/** Mounts the routes manager with the broken route's editor open; closing it unmounts both. */\nfunction ReconnectHost(props: {\n routeId: string;\n projectId?: string | null;\n onDone: () => void;\n}) {\n return (\n <div data-testid=\"connection-route-reconnect-host\">\n <ModelRoutesManager projectId={props.projectId} initialEditRouteId={props.routeId} />\n <button type=\"button\" className=\"btn link\" onClick={props.onDone}>\n Done\n </button>\n </div>\n );\n}\n\nexport function ConnectionDependentRows({\n callables,\n onOpenCallable,\n routes,\n projectId,\n}: {\n callables: ConnectionDependentCallable[];\n onOpenCallable?: OpenCallable;\n routes?: ConnectionDependentRoute[];\n projectId?: string | null;\n}) {\n return (\n <>\n <ConnectionDependentRoutes routes={routes ?? []} projectId={projectId} />\n <CallableRows callables={callables} onOpenCallable={onOpenCallable} />\n </>\n );\n}\n\nfunction CallableRows({\n callables,\n onOpenCallable,\n}: {\n callables: ConnectionDependentCallable[];\n onOpenCallable?: OpenCallable;\n}) {\n return (\n <ul className=\"list small\">\n {callables.map((c) => {\n const name = c.displayName || c.key || c.id;\n const sites = c.sites.map(siteLabel);\n return (\n <li key={`${c.kind}:${c.id}`}>\n <span className=\"badge\">{c.kind}</span>{\" \"}\n {onOpenCallable ? (\n <button\n type=\"button\"\n className=\"btn link\"\n onClick={() => onOpenCallable(c.kind, c.id)}\n >\n {name}\n </button>\n ) : (\n <span>{name}</span>\n )}\n {!c.enabled && <span className=\"muted\"> (disabled)</span>}\n {sites.length > 0 && <span className=\"muted\"> · {sites.join(\", \")}</span>}\n </li>\n );\n })}\n </ul>\n );\n}\n","/**\n * `<ConnectionList>` — the connected list of a host's connections: `useConnectionsQuery` into\n * `@w6w/ui`'s presentational `ConnectionList`, plus Add, Edit and Delete wired to the embed repos.\n *\n * Reads only `@w6w/embed/repos` and the host `W6WUIProvider` adapter (`W6WEmbedProvider` supplies\n * both). App meta comes from a bounded `listAppsByIds` for the rows that lack an inline `app`,\n * never a catalog list. Edit is offered only when the adapter can save (`updateConnection`).\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { ConnectionDependentCallable } from \"@w6w/sdk/console\";\nimport {\n AddConnectionModal,\n EditConnectionModal,\n Modal,\n ConnectionList as UiConnectionList,\n type ConnectionListProps as UiConnectionListProps,\n type ConnectionSummary as UiConnectionSummary,\n connectionAppIdsToLookUp,\n useW6WApi,\n} from \"@w6w/ui\";\nimport { type MouseEvent, type ReactNode, useMemo, useState } from \"react\";\nimport { useEditorApps } from \"../editor/editor-apps.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type ConnectionSummary,\n connectionKey,\n connectionsKey,\n useConnectionDependentsQuery,\n useConnectionsQuery,\n useDeleteConnectionMutation,\n} from \"../repos/connections.ts\";\nimport {\n type ConnectionDependentRoute,\n ConnectionDependentRows,\n type OpenCallable,\n} from \"./ConnectionDependents.tsx\";\n\nexport interface ConnectionListProps {\n /** Row click; the host decides whether to `preventDefault` when it also passes `getHref`. */\n onOpen?: (id: string, event: MouseEvent<Element>) => void;\n /** When set, each openable row is a real `<a href>`. */\n getHref?: (id: string) => string;\n /** Label of the default Add button. Default `+ Add connection`. */\n addLabel?: string;\n /**\n * `header` and `empty` pass through. A given `actions` key (even `null`) replaces the default\n * Add button.\n */\n slots?: UiConnectionListProps[\"slots\"];\n /** When set, dependent rows in the delete confirm open the callable's editor. */\n onOpenCallable?: OpenCallable;\n}\n\nconst NO_ROWS: readonly ConnectionSummary[] = [];\n\nexport function ConnectionList({\n onOpen,\n getHref,\n addLabel,\n slots,\n onOpenCallable,\n}: ConnectionListProps) {\n const api = useW6WApi();\n const qc = useQueryClient();\n const query = useConnectionsQuery();\n const data = query.data;\n const rows = data ?? NO_ROWS;\n const lookupIds = useMemo(() => connectionAppIdsToLookUp(rows), [rows]);\n const { byId } = useEditorApps(lookupIds);\n const del = useDeleteConnectionMutation();\n const [adding, setAdding] = useState(false);\n const [editing, setEditing] = useState<UiConnectionSummary | null>(null);\n const [deleting, setDeleting] = useState<UiConnectionSummary | null>(null);\n const projectId = useEditorProject(undefined);\n const deps = useConnectionDependentsQuery(deleting?.id ?? \"\", deleting !== null);\n\n const canEdit = typeof api.updateConnection === \"function\";\n const actions: ReactNode =\n slots && \"actions\" in slots ? (\n slots.actions\n ) : (\n <button type=\"button\" className=\"w6w-btn\" onClick={() => setAdding(true)}>\n {addLabel ?? \"+ Add connection\"}\n </button>\n );\n\n return (\n <div className=\"w6w-embed-root\">\n <UiConnectionList\n connections={rows}\n appsById={byId}\n loading={query.isLoading}\n error={query.error ? (query.error as Error).message : null}\n onOpen={onOpen}\n getHref={getHref}\n onEdit={canEdit ? setEditing : undefined}\n onDelete={setDeleting}\n busy={del.isPending}\n slots={{ ...slots, actions }}\n />\n {adding && (\n <AddConnectionModal\n onClose={() => setAdding(false)}\n onCreated={() => {\n setAdding(false);\n qc.invalidateQueries({ queryKey: connectionsKey });\n }}\n />\n )}\n {editing && (\n <EditConnectionModal\n connection={editing}\n onClose={() => setEditing(null)}\n onSaved={() => {\n const id = editing.id;\n setEditing(null);\n qc.invalidateQueries({ queryKey: connectionsKey });\n qc.invalidateQueries({ queryKey: connectionKey(id) });\n }}\n />\n )}\n {deleting && (\n <DeleteConfirm\n name={deleting.displayName || deleting.id}\n loading={deps.isLoading}\n callables={deps.isError ? [] : (deps.data?.callables ?? [])}\n routes={\n deps.isError\n ? []\n : ((deps.data as { routes?: ConnectionDependentRoute[] } | undefined)?.routes ?? [])\n }\n projectId={projectId}\n onOpenCallable={onOpenCallable}\n onClose={() => setDeleting(null)}\n onConfirm={() => {\n const id = deleting.id;\n setDeleting(null);\n del.mutate({ id, force: true });\n }}\n />\n )}\n </div>\n );\n}\n\nfunction DeleteConfirm({\n name,\n loading,\n callables,\n routes,\n projectId,\n onOpenCallable,\n onClose,\n onConfirm,\n}: {\n name: string;\n loading: boolean;\n callables: ConnectionDependentCallable[];\n routes: ConnectionDependentRoute[];\n projectId: string | null;\n onOpenCallable?: OpenCallable;\n onClose: () => void;\n onConfirm: () => void;\n}) {\n const c = callables.length;\n const r = routes.length;\n const n = c + r;\n const plain = `Delete the connection \"${name}\"? This cannot be undone.`;\n const plural = (k: number, one: string, many: string) => `${k} ${k === 1 ? one : many}`;\n const usedBy = [\n c > 0 ? plural(c, \"callable\", \"callables\") : null,\n r > 0 ? plural(r, \"model route\", \"model routes\") : null,\n ]\n .filter(Boolean)\n .join(\" and \");\n // Callables are disabled; a model route is not disabled but marked `broken` (it stays listed\n // and editable) until it is pointed at another connection.\n const consequences = [\n c > 0\n ? `Deleting disables ${c === 1 ? \"this callable\" : `these ${c} callables`} until you reconnect ${c === 1 ? \"it\" : \"them\"}.`\n : null,\n r > 0\n ? `${r === 1 ? \"The model route becomes\" : `The ${r} model routes become`} broken until ${r === 1 ? \"it is\" : \"they are\"} pointed at another connection.`\n : null,\n ].filter((x): x is string => x != null);\n return (\n <Modal title=\"Delete connection\" onClose={onClose}>\n <div className=\"w6w-modal-body\">\n <p className=\"w6w-muted w6w-small\">\n {n === 0 ? plain : `Delete the connection \"${name}\"? Used by ${usedBy}.`}\n </p>\n {n > 0 && (\n <>\n <ConnectionDependentRows\n callables={callables}\n routes={routes}\n projectId={projectId}\n onOpenCallable={onOpenCallable}\n />\n <p className=\"w6w-small\">{consequences.join(\" \")}</p>\n </>\n )}\n </div>\n <div className=\"w6w-modal-actions\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onClose}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-danger\"\n disabled={loading}\n onClick={onConfirm}\n >\n Delete\n </button>\n </div>\n </Modal>\n );\n}\n","/**\n * `<ConnectionDetail>` — one connection: identity header with Test and Edit, the app card, the\n * app's actions with their saved tests, and recent tester runs. Studio's `ConnectionDetailPage`\n * body, minus the router and the document title; navigation leaves through callbacks.\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { ApiError } from \"@w6w/sdk\";\nimport {\n ConnectionHeader,\n EditButton,\n EditConnectionModal,\n IconButton,\n ListItem,\n connectionAppIdsToLookUp,\n resolveConnectionAppMeta,\n useW6WApi,\n} from \"@w6w/ui\";\nimport { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { useEditorApps } from \"../editor/editor-apps.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport { useAppQuery } from \"../repos/apps.ts\";\nimport {\n connectionKey,\n connectionsKey,\n useConnectionDependentsQuery,\n useConnectionQuery,\n useTestConnectionMutation,\n} from \"../repos/connections.ts\";\nimport { type SavedTest, useSavedTestsQuery, useTestRunsQuery } from \"../repos/saved-tests.ts\";\nimport {\n type ConnectionDependentRoute,\n ConnectionDependentRows,\n type OpenCallable,\n} from \"./ConnectionDependents.tsx\";\n\nexport interface ConnectionDetailProps {\n connectionId: string;\n /** An action row calls `(actionKey)`; one of its saved tests calls `(actionKey, savedTestId)`. */\n onOpenAction: (actionKey: string, savedTestId?: string) => void;\n /** A \"Used by\" row opens the callable's editor; rows are plain text without it. */\n onOpenCallable?: OpenCallable;\n /** The back affordance renders only when given. */\n onBack?: () => void;\n slots?: {\n /** Replaces the header block. */\n header?: ReactNode;\n /** Appended to the header's buttons. */\n actions?: ReactNode;\n /** Replaces the not-found state. */\n empty?: ReactNode;\n };\n}\n\n/** Bare relative-time label (\"just now\", \"5m ago\"), the same wording as the tester overlay. */\nfunction relativeTime(iso: string): string {\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) return \"recently\";\n const secs = Math.max(0, Math.round((Date.now() - then) / 1000));\n if (secs < 45) return \"just now\";\n const mins = Math.round(secs / 60);\n if (mins < 60) return `${mins}m ago`;\n const hours = Math.round(mins / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.round(hours / 24);\n if (days < 30) return `${days}d ago`;\n return new Date(iso).toLocaleDateString();\n}\n\ntype TestNotice = { kind: \"ok\" | \"warn\" | \"error\"; text: string };\nconst NOTICE_DISMISS_MS: Record<TestNotice[\"kind\"], number> = {\n ok: 6000,\n warn: 10000,\n error: 15000,\n};\nconst NOTICE_ICON: Record<TestNotice[\"kind\"], string> = { ok: \"✓\", warn: \"!\", error: \"✕\" };\n\nexport function ConnectionDetail({\n connectionId,\n onOpenAction,\n onBack,\n onOpenCallable,\n slots,\n}: ConnectionDetailProps) {\n const api = useW6WApi();\n const qc = useQueryClient();\n const connQuery = useConnectionQuery(connectionId);\n const appId = connQuery.data?.appId;\n const lookupIds = useMemo(\n () => connectionAppIdsToLookUp(connQuery.data ? [connQuery.data] : []),\n [connQuery.data],\n );\n const { byId: appsById } = useEditorApps(lookupIds);\n const appSummary = connQuery.data\n ? resolveConnectionAppMeta(connQuery.data, appsById)\n : undefined;\n const appDetailQuery = useAppQuery(appId, !!appId);\n\n const savedTestsQuery = useSavedTestsQuery(connectionId);\n const savedTestsByAction = useMemo(() => {\n const map = new Map<string, SavedTest[]>();\n for (const t of savedTestsQuery.data ?? []) {\n const list = map.get(t.actionKey) ?? [];\n list.push(t);\n map.set(t.actionKey, list);\n }\n return map;\n }, [savedTestsQuery.data]);\n\n // Best-effort: a load failure leaves the list empty (`retry: false`), so the section hides.\n // Best-effort too: a failed lookup renders no \"Used by\" card rather than a false \"not used\".\n const dependents = useConnectionDependentsQuery(connectionId).data;\n const projectId = useEditorProject(undefined);\n const usedBy = dependents?.callables ?? [];\n // The sdk's `ConnectionDependents` type predates `routes`; read it structurally.\n const usedByRoutes =\n (dependents as { routes?: ConnectionDependentRoute[] } | undefined)?.routes ?? [];\n const runHistory = useTestRunsQuery(connectionId).data ?? [];\n\n const [editOpen, setEditOpen] = useState(false);\n const [actionFilter, setActionFilter] = useState(\"\");\n const testMut = useTestConnectionMutation(connectionId);\n\n const [testNotice, setTestNotice] = useState<TestNotice | null>(null);\n useEffect(() => {\n if (!testNotice) return;\n const timer = setTimeout(() => setTestNotice(null), NOTICE_DISMISS_MS[testNotice.kind]);\n return () => clearTimeout(timer);\n }, [testNotice]);\n\n const runTest = () => {\n setTestNotice(null);\n testMut.mutate(undefined, {\n onSuccess: (r) => {\n if (!r.ok) {\n setTestNotice({\n kind: \"error\",\n text: `Connection test failed${r.error?.message ? `: ${r.error.message}` : \".\"}`,\n });\n return;\n }\n setTestNotice(\n r.untested\n ? { kind: \"warn\", text: `Connection stored. ${r.message ?? \"\"}`.trim() }\n : {\n kind: \"ok\",\n text: `Connection is valid${r.actionKey ? ` — probed ${r.actionKey}` : \"\"}.`,\n },\n );\n },\n onError: (e) =>\n setTestNotice({ kind: \"error\", text: (e as ApiError)?.message ?? \"Test failed.\" }),\n });\n };\n\n const sortedActions = useMemo(() => {\n const list = [...(appDetailQuery.data?.actions ?? [])];\n list.sort((a, b) => (a.title || a.key).localeCompare(b.title || b.key));\n return list;\n }, [appDetailQuery.data]);\n const filteredActions = useMemo(() => {\n const q = actionFilter.trim().toLowerCase();\n if (!q) return sortedActions;\n return sortedActions.filter(\n (a) =>\n (a.title || \"\").toLowerCase().includes(q) ||\n a.key.toLowerCase().includes(q) ||\n (a.description || \"\").toLowerCase().includes(q),\n );\n }, [sortedActions, actionFilter]);\n\n if (connQuery.isLoading || appDetailQuery.isLoading) {\n return (\n <div className=\"w6w-embed-root w6w-embed-conn-detail\">\n <p className=\"w6w-muted\">Loading…</p>\n </div>\n );\n }\n if (!connQuery.data) {\n return (\n <div className=\"w6w-embed-root w6w-embed-conn-detail\" data-testid=\"connection-not-found\">\n {slots?.empty ?? <h2>Connection not found</h2>}\n {onBack && (\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onBack}>\n Back to integrations\n </button>\n )}\n </div>\n );\n }\n\n const conn = connQuery.data;\n const app = appDetailQuery.data;\n const canEdit = !conn.builtIn && typeof api.updateConnection === \"function\";\n\n // The cards below are a vertical stack, so the gap is @w6w/ui's shared\n // `.w6w-card-stack` (16px, `--w6w-sp-4`) — not a local number in styles.css.\n return (\n <div className=\"w6w-embed-root w6w-embed-conn-detail w6w-card-stack\">\n {slots?.header ?? (\n <ConnectionHeader conn={conn} app={appSummary}>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={testMut.isPending}\n onClick={runTest}\n >\n {testMut.isPending ? \"Testing…\" : \"Test connection\"}\n </button>\n {canEdit && (\n <EditButton\n label=\"Edit\"\n onClick={() => setEditOpen(true)}\n data-testid=\"connection-detail-edit\"\n />\n )}\n {slots?.actions}\n </ConnectionHeader>\n )}\n\n {testNotice && (\n <div\n className={`w6w-result w6w-embed-conn-notice w6w-embed-conn-notice-${testNotice.kind}`}\n role={testNotice.kind === \"error\" ? \"alert\" : \"status\"}\n aria-live={testNotice.kind === \"error\" ? \"assertive\" : \"polite\"}\n data-testid=\"connection-test-notice\"\n >\n <span aria-hidden=\"true\">{NOTICE_ICON[testNotice.kind]}</span>\n <span className=\"w6w-embed-conn-notice-text\">{testNotice.text}</span>\n <IconButton icon=\"close\" label=\"Dismiss\" onClick={() => setTestNotice(null)} />\n </div>\n )}\n\n <div className=\"w6w-embed-conn-card\">\n <h3>App: {appSummary?.displayName ?? conn.appId}</h3>\n {app && (\n <p className=\"w6w-muted w6w-small\">\n Version <code>v{app.version ?? \"?\"}</code> · source <code>{app.sourceRef}</code>\n </p>\n )}\n {onBack && (\n <p className=\"w6w-small\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onBack}>\n ← Integrations\n </button>\n </p>\n )}\n </div>\n\n <div className=\"w6w-embed-conn-card\">\n <h3>Actions</h3>\n {sortedActions.length === 0 && <p className=\"w6w-muted\">No actions exposed.</p>}\n {sortedActions.length > 10 && (\n <input\n type=\"search\"\n value={actionFilter}\n placeholder={`Search ${sortedActions.length} actions…`}\n onChange={(e) => setActionFilter(e.target.value)}\n aria-label=\"Filter actions\"\n className=\"w6w-embed-conn-filter\"\n />\n )}\n {sortedActions.length > 0 && filteredActions.length === 0 && (\n <p className=\"w6w-muted w6w-small\">No actions match “{actionFilter}”.</p>\n )}\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Actions\">\n {filteredActions.map((a) => {\n const tests = savedTestsByAction.get(a.key) ?? [];\n return (\n <li key={a.key}>\n <button\n type=\"button\"\n className=\"w6w-embed-conn-action\"\n data-testid={`connection-action-${a.key}`}\n onClick={() => onOpenAction(a.key)}\n >\n <strong>{a.title}</strong> <code className=\"w6w-muted\">{a.key}</code>{\" \"}\n <span className=\"w6w-embed-conn-badge\">{a.type}</span>\n {a.description && <div className=\"w6w-muted w6w-small\">{a.description}</div>}\n </button>\n {tests.length > 0 && (\n <ul\n className=\"w6w-embed-conn-list w6w-embed-conn-tests\"\n aria-label={`Saved tests for ${a.title || a.key}`}\n >\n {tests.map((t) => (\n <li key={t.id}>\n <ListItem\n title={t.name}\n subtitle={\n t.lastRunAt ? (\n <span>\n <span\n className={\n t.lastRunOk ? \"w6w-embed-conn-ok\" : \"w6w-embed-conn-fail\"\n }\n >\n {t.lastRunOk ? \"✓\" : \"✗\"}\n </span>{\" \"}\n {t.lastRunSummary ? `${t.lastRunSummary} · ` : \"\"}\n {relativeTime(t.lastRunAt)}\n </span>\n ) : (\n `saved ${relativeTime(t.updatedAt)}`\n )\n }\n onClick={() => onOpenAction(a.key, t.id)}\n />\n </li>\n ))}\n </ul>\n )}\n </li>\n );\n })}\n </ul>\n </div>\n\n {dependents && (\n <div className=\"w6w-embed-conn-card\" data-testid=\"connection-used-by\">\n <h3>Used by</h3>\n {usedBy.length === 0 && usedByRoutes.length === 0 ? (\n <p className=\"w6w-muted\">Not used by any callable</p>\n ) : (\n <ConnectionDependentRows\n callables={usedBy}\n routes={usedByRoutes}\n projectId={projectId}\n onOpenCallable={onOpenCallable}\n />\n )}\n </div>\n )}\n\n {runHistory.length > 0 && (\n <div className=\"w6w-embed-conn-card\">\n <h3>Recent runs</h3>\n <p className=\"w6w-muted w6w-small\">Most recent tester runs against this connection.</p>\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Recent runs\">\n {runHistory.map((run) => (\n <li key={run.id}>\n <ListItem\n title={run.actionKey}\n subtitle={\n <span>\n <span className={run.ok ? \"w6w-embed-conn-ok\" : \"w6w-embed-conn-fail\"}>\n {run.ok ? \"✓\" : \"✗\"}\n </span>{\" \"}\n {run.summary ? `${run.summary} · ` : \"\"}\n {relativeTime(run.occurredAt)}\n </span>\n }\n />\n </li>\n ))}\n </ul>\n </div>\n )}\n\n {editOpen && (\n <EditConnectionModal\n connection={conn}\n onClose={() => setEditOpen(false)}\n onSaved={() => {\n setEditOpen(false);\n qc.invalidateQueries({ queryKey: connectionKey(connectionId) });\n qc.invalidateQueries({ queryKey: connectionsKey });\n }}\n />\n )}\n </div>\n );\n}\n","/**\n * `<ModelCatalog>` — every model this tenant may route to: the provider-discovered entries plus\n * the tenant's own manual ones, from `GET /models` (list + empty state, keyset \"load more\").\n *\n * The catalog is TENANT-WIDE: the repo deliberately sends no `project`, so the `projectId` prop is\n * accepted (the Models tab shell passes the same prop to all four tabs) and deliberately unused —\n * this is the one tab that renders before a project resolves. A row shows the model's current rate\n * card (per-million-token minor units, `ModelRate.rates`) and its status; editing rates stays on the\n * server API, it is not a tab affordance.\n */\nimport { useInfiniteQuery } from \"@tanstack/react-query\";\nimport { DataTable, type DataTableColumn, EmptyState } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport {\n type Model,\n type ModelCatalogFilter,\n type ModelCatalogPage,\n type ModelRate,\n listModelCatalog,\n modelCatalogKey,\n} from \"../repos/models.ts\";\n\nexport interface ModelCatalogProps {\n /**\n * The project the Models tab is scoped to. Kept for a uniform tab API: the catalog never sends\n * it (a tenant-wide list), so it changes nothing here.\n */\n projectId?: string | null;\n /** Narrow the list (`provider`, `status`, `limit`). `cursor` is keyset paging, managed here. */\n filter?: Omit<ModelCatalogFilter, \"cursor\">;\n}\n\nconst NO_FILTER: Omit<ModelCatalogFilter, \"cursor\"> = {};\n\n/** Plain thousands separators — no `Intl`, so the text is identical in every host and test. */\nfunction grouped(n: number): string {\n return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\n/** Rates are integer MINOR units per million tokens; print them as major units. */\nfunction major(minor: number): string {\n return (minor / 100).toFixed(2);\n}\n\n/** One rate card on one line: `<CUR> in 3.00 · out 15.00` (only the fields the card sets). */\nfunction rateText(rate: ModelRate | null): string | null {\n if (rate == null) return null;\n const r = rate.rates;\n const parts: string[] = [];\n if (r.input != null) parts.push(`in ${major(r.input)}`);\n if (r.output != null) parts.push(`out ${major(r.output)}`);\n if (r.cachedInput != null) parts.push(`cached ${major(r.cachedInput)}`);\n if (r.cacheWrite != null) parts.push(`cache write ${major(r.cacheWrite)}`);\n if (r.perRequest != null) parts.push(`${major(r.perRequest)}/request`);\n if (parts.length === 0) return null;\n return `${r.currency ?? \"USD\"} ${parts.join(\" · \")}`;\n}\n\nfunction limitsText(m: Model): string {\n const { maxInputTokens, maxOutputTokens } = m.limits ?? {};\n if (maxInputTokens == null && maxOutputTokens == null) return \"—\";\n const parts: string[] = [];\n if (maxInputTokens != null) parts.push(`${grouped(maxInputTokens)} in`);\n if (maxOutputTokens != null) parts.push(`${grouped(maxOutputTokens)} out`);\n return parts.join(\" · \");\n}\n\nconst columns: DataTableColumn<Model>[] = [\n {\n key: \"model\",\n header: \"Model\",\n render: (m) => (\n <div className=\"list-main\" style={{ maxWidth: 0, minWidth: \"100%\" }}>\n <strong className=\"list-name\" title={m.displayName}>\n {m.displayName}\n </strong>\n <div className=\"muted small list-preview\" title={`${m.provider} · ${m.nativeId}`}>\n {m.provider} · {m.nativeId} · {m.source}\n </div>\n </div>\n ),\n },\n {\n key: \"provider\",\n header: \"Provider\",\n render: (m) => <span className=\"muted small\">{m.provider || \"—\"}</span>,\n },\n {\n key: \"status\",\n header: \"Status\",\n render: (m) => <span className={m.status === \"active\" ? \"tag\" : \"tag warn\"}>{m.status}</span>,\n },\n {\n key: \"rate\",\n header: \"Rate (per 1M tokens)\",\n render: (m) => {\n const text = rateText(m.currentRate);\n if (text == null) return <span className=\"muted small\">—</span>;\n return (\n <span\n className=\"muted small\"\n title={m.currentRate ? `effective ${m.currentRate.effectiveFrom}` : undefined}\n >\n {text}\n </span>\n );\n },\n },\n {\n key: \"limits\",\n header: \"Limits\",\n render: (m) => <span className=\"muted small\">{limitsText(m)}</span>,\n },\n];\n\nexport function ModelCatalog(props: ModelCatalogProps): ReactNode {\n const client = useEmbedClient();\n const filter = props.filter ?? NO_FILTER;\n const query = useInfiniteQuery({\n queryKey: modelCatalogKey(filter),\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (last: ModelCatalogPage) => last.nextCursor ?? undefined,\n queryFn: ({ pageParam }): Promise<ModelCatalogPage> =>\n listModelCatalog(client, pageParam ? { ...filter, cursor: pageParam } : filter),\n });\n const models = query.data?.pages.flatMap((p) => p.models) ?? [];\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n <div className=\"section-head\">\n <div>\n <h3>Model catalog</h3>\n <p className=\"muted small\">\n The models discovered on this tenant's connections, plus any added by hand. A route\n may only name a model from this list; the rate card is what usage is priced with.\n </p>\n </div>\n </div>\n\n <div className=\"card\">\n {query.isLoading && <p className=\"muted\">Loading…</p>}\n {query.error != null && <div className=\"error\">{query.error.message}</div>}\n {query.isSuccess && models.length === 0 && (\n <EmptyState testId=\"model-catalog-empty\">\n No models yet. Discover them from a provider connection to start routing to them.\n </EmptyState>\n )}\n {models.length > 0 && (\n <DataTable\n columns={columns}\n rows={models}\n rowKey={(m) => m.id}\n testId=\"model-catalog-table\"\n rowTestId={(m) => `model-catalog-${m.id}`}\n />\n )}\n </div>\n\n {query.hasNextPage && (\n <div className=\"row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n disabled={query.isFetchingNextPage}\n onClick={() => void query.fetchNextPage()}\n data-testid=\"model-catalog-load-more\"\n >\n {query.isFetchingNextPage ? \"Loading…\" : \"Load more\"}\n </button>\n </div>\n )}\n </section>\n </div>\n );\n}\n","/**\n * `<ModelUsage>` — the project's model-call ledger: totals for the window, then one row per call,\n * from `GET /model-usage` with keyset \"load more\" (`nextCursor` until the server stops returning\n * one). Totals are the SERVER's, taken from the first page and never re-summed from the loaded\n * rows, so they stay right as more pages arrive.\n *\n * Two things the wire shape makes easy to get wrong, and this component does not:\n * - `cost` is an ARRAY, one entry per currency; a window that mixed currencies prints every\n * currency rather than adding different monies together.\n * - `costMinor` is `null` when the call had no usable rate (`unpriced`). That is NOT zero spend:\n * the cell prints \"unpriced\", and the totals count those calls instead of pricing them at 0.\n * - `totalsTruncated: true` means the server's totals cover a bounded scan, not every matching\n * call; the note says so instead of presenting a partial number as the whole.\n *\n * The project comes from `useEditorProject(projectId)`: omitted defers to the `<W6WEmbedProvider\n * project>`; `null` or `\"\"` REFUSES — the report query is disabled and no `/model-usage` request\n * is sent.\n */\nimport { useInfiniteQuery } from \"@tanstack/react-query\";\nimport { DataTable, type DataTableColumn, EmptyState } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { formatDuration, formatTimestamp } from \"../lib/recent-activity.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type ModelCost,\n type ModelUsageFilter,\n type ModelUsageItem,\n type ModelUsageReport,\n getModelUsage,\n modelUsageKey,\n} from \"../repos/models.ts\";\n\nexport interface ModelUsageProps {\n /**\n * The project whose usage is shown. Omitted: the `<W6WEmbedProvider project>`. `null` or `\"\"`:\n * no project — nothing is requested.\n */\n projectId?: string | null;\n /** Narrow the report (`route`, `model`, `from`, `to`, `groupBy`, `limit`). `cursor` is paging. */\n filter?: Omit<ModelUsageFilter, \"cursor\">;\n}\n\nconst NO_FILTER: Omit<ModelUsageFilter, \"cursor\"> = {};\n\n/** Plain thousands separators — no `Intl`, so the text is identical in every host and test. */\nfunction grouped(n: number): string {\n return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\n/** Cost is integer MINOR units: `USD 1.50`. */\nfunction costText(cost: ModelCost): string {\n return `${cost.currency} ${(cost.amountMinor / 100).toFixed(2)}`;\n}\n\n/** Every currency in the window, never summed across them. `unpriced` is not a zero. */\nfunction costsText(costs: ModelCost[], unpriced: number): string {\n if (costs.length > 0) return costs.map(costText).join(\" · \");\n return unpriced > 0 ? \"unpriced\" : \"—\";\n}\n\n/** A row's own cost, or `null` when the call had no usable rate. */\nfunction itemCost(item: ModelUsageItem): string | null {\n if (item.costMinor == null) return null;\n return `${item.currency ?? \"USD\"} ${(item.costMinor / 100).toFixed(2)}`;\n}\n\nfunction totalsTruncated(report: ModelUsageReport): boolean {\n return report.totalsTruncated === true;\n}\n\nconst columns: DataTableColumn<ModelUsageItem>[] = [\n {\n key: \"occurredAt\",\n header: \"When\",\n render: (i) => (\n <span className=\"muted small\" title={i.occurredAt}>\n {formatTimestamp(i.occurredAt)}\n </span>\n ),\n },\n {\n key: \"model\",\n header: \"Model\",\n render: (i) => (\n <div className=\"list-main\" style={{ maxWidth: 0, minWidth: \"100%\" }}>\n <strong className=\"list-name\" title={`${i.provider} · ${i.nativeId}`}>\n {i.provider} · {i.nativeId}\n </strong>\n <div className=\"muted small list-preview\" title={i.connectionId}>\n {i.connectionId}\n </div>\n </div>\n ),\n },\n {\n key: \"route\",\n header: \"Route\",\n render: (i) =>\n i.routeId == null ? (\n <span className=\"muted small\">direct</span>\n ) : (\n <code className=\"muted small\" title={i.routeId}>\n {i.routeId}\n </code>\n ),\n },\n {\n key: \"tokens\",\n header: \"Tokens\",\n align: \"right\",\n render: (i) => (\n <span\n className=\"muted small\"\n title={`${grouped(i.inputTokens)} in · ${grouped(i.outputTokens)} out · ${grouped(i.cachedInputTokens)} cached input · ${grouped(i.cacheWriteTokens)} cache write`}\n >\n {grouped(i.totalTokens)}\n </span>\n ),\n },\n {\n key: \"cost\",\n header: \"Cost\",\n align: \"right\",\n render: (i) => {\n const text = itemCost(i);\n if (text == null) {\n return (\n <span className=\"tag warn\" data-testid=\"model-usage-unpriced\" title=\"no usable rate\">\n unpriced\n </span>\n );\n }\n return <span className=\"muted small\">{text}</span>;\n },\n },\n {\n key: \"result\",\n header: \"Result\",\n render: (i) => {\n const duration = formatDuration(i.durationMs);\n return (\n <span className=\"muted small\" title={i.errorCode ?? undefined}>\n <span className={i.ok ? \"tag\" : \"tag warn\"}>\n {i.ok ? \"ok\" : (i.errorCode ?? \"failed\")}\n </span>\n {duration != null && <> · {duration}</>}\n </span>\n );\n },\n },\n];\n\nexport function ModelUsage(props: ModelUsageProps): ReactNode {\n const project = useEditorProject(props.projectId);\n const client = useEmbedClient();\n const filter = props.filter ?? NO_FILTER;\n const query = useInfiniteQuery({\n queryKey: modelUsageKey(project ?? undefined, filter),\n enabled: project != null,\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (last: ModelUsageReport) => last.nextCursor ?? undefined,\n queryFn: ({ pageParam }): Promise<ModelUsageReport> =>\n getModelUsage(\n client,\n project as string,\n pageParam ? { ...filter, cursor: pageParam } : filter,\n ),\n });\n const pages = query.data?.pages ?? [];\n const totals = pages[0]?.totals;\n const items = pages.flatMap((p) => p.items);\n const truncated = pages.length > 0 && totalsTruncated(pages[0]);\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n <div className=\"section-head\">\n <div>\n <h3>Model usage</h3>\n <p className=\"muted small\">\n Every model call this project paid for, priced with the rate card in force when it\n ran. A call with no usable rate counts as unpriced, not as free.\n </p>\n </div>\n </div>\n\n {project == null ? (\n <div className=\"card\">\n <p className=\"muted\" data-testid=\"model-usage-no-project\">\n Select a project to see its model usage.\n </p>\n </div>\n ) : (\n <>\n <div className=\"card\" data-testid=\"model-usage-totals\">\n {truncated && (\n <p className=\"result warn\" data-testid=\"model-usage-totals-partial\">\n Totals are partial: they cover a bounded scan of this window, not every matching\n call. Narrow the range for exact totals.\n </p>\n )}\n {totals == null ? (\n // A failed query is reported once, below — never as a perpetual \"loading\".\n query.error == null && <p className=\"muted\">Loading totals…</p>\n ) : (\n <p className=\"muted small\">\n <span data-testid=\"model-usage-total-requests\">\n {grouped(totals.requests)} requests\n </span>\n {\" · \"}\n <span data-testid=\"model-usage-total-tokens\">\n {grouped(totals.totalTokens)} tokens ({grouped(totals.inputTokens)} in /{\" \"}\n {grouped(totals.outputTokens)} out / {grouped(totals.cachedInputTokens)} cached\n / {grouped(totals.cacheWriteTokens)} cache write)\n </span>\n {\" · \"}\n <span data-testid=\"model-usage-total-cost\">\n {costsText(totals.cost, totals.unpriced)}\n </span>\n {totals.unpriced > 0 && (\n <>\n {\" · \"}\n <span\n className=\"tag warn\"\n data-testid=\"model-usage-unpriced-total\"\n title=\"calls with no usable rate — not included in any cost total\"\n >\n {grouped(totals.unpriced)} unpriced\n </span>\n </>\n )}\n </p>\n )}\n </div>\n\n {query.error != null && (\n <div className=\"error\" role=\"alert\" data-testid=\"model-usage-error\">\n {query.error.message}\n </div>\n )}\n\n <div className=\"card\">\n {query.isLoading && <p className=\"muted\">Loading…</p>}\n {query.isSuccess && items.length === 0 && (\n <EmptyState testId=\"model-usage-empty\">\n No model calls in this window. Usage rows appear here as routes are invoked.\n </EmptyState>\n )}\n {items.length > 0 && (\n <DataTable\n columns={columns}\n rows={items}\n rowKey={(i) => i.id}\n testId=\"model-usage-table\"\n rowTestId={(i) => `model-usage-${i.id}`}\n />\n )}\n </div>\n\n {query.hasNextPage && (\n <div className=\"row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n disabled={query.isFetchingNextPage}\n onClick={() => void query.fetchNextPage()}\n data-testid=\"model-usage-load-more\"\n >\n {query.isFetchingNextPage ? \"Loading…\" : \"Load more\"}\n </button>\n </div>\n )}\n </>\n )}\n </section>\n </div>\n );\n}\n","/**\n * `<CredentialList>` — the host's stored credentials: name, status, one non-secret display value\n * and how many connections use each. Opening a row is the host's `onOpen`; the embed never\n * navigates. Reads only `useCredentialsQuery` (never a secret: the summary carries none).\n */\nimport type { ReactNode } from \"react\";\nimport { type CredentialSummary, useCredentialsQuery } from \"../repos/credentials.ts\";\n\nexport interface CredentialListProps {\n /** Narrow the list to one credential contract. */\n contract?: string;\n /** Row click. */\n onOpen?: (id: string) => void;\n slots?: {\n /** Replaces the heading. */\n header?: ReactNode;\n /** Replaces the empty state. */\n empty?: ReactNode;\n };\n}\n\nconst plural = (n: number) => `${n} connection${n === 1 ? \"\" : \"s\"}`;\n\nexport function CredentialList({ contract, onOpen, slots }: CredentialListProps) {\n const query = useCredentialsQuery(contract ? { contract } : undefined);\n const rows: readonly CredentialSummary[] = query.data ?? [];\n\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-list\">\n {slots?.header ?? <h2>Credentials</h2>}\n {query.isLoading && <p className=\"w6w-muted\">Loading…</p>}\n {query.error && (\n <p className=\"w6w-error\" role=\"alert\">\n {(query.error as Error).message}\n </p>\n )}\n {!query.isLoading && !query.error && rows.length === 0 && (\n <div data-testid=\"credential-list-empty\">\n {slots?.empty ?? <p className=\"w6w-muted\">No credentials yet.</p>}\n </div>\n )}\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Credentials\">\n {rows.map((c) => {\n const shown = Object.values(c.display)[0];\n return (\n <li key={c.id}>\n <button\n type=\"button\"\n className=\"w6w-embed-conn-action\"\n data-testid={`credential-row-${c.id}`}\n onClick={() => onOpen?.(c.id)}\n >\n <strong>{c.name}</strong> <span className=\"w6w-embed-conn-badge\">{c.status}</span>\n {shown !== undefined && <span className=\"w6w-muted w6w-small\"> {shown}</span>}\n <span className=\"w6w-muted w6w-small\"> · {plural(c.connectionCount)}</span>\n </button>\n </li>\n );\n })}\n </ul>\n </div>\n );\n}\n","/**\n * `<CredentialDetail>` — one stored credential: an explicit pick of its non-secret summary, the\n * connections that use it, and Rotate, Disable/Enable, Test and Delete. Never renders a spread or a\n * serialisation of the record. The rotate secret is one masked textarea whose text is parsed\n * locally and sent as `{ source }`; it is never echoed into an error. Navigation leaves through\n * `onOpenConnection`, `onDeleted` and `onBack`.\n */\nimport type { ApiError } from \"@w6w/sdk\";\nimport { type ReactNode, useState } from \"react\";\nimport {\n type CredentialDependents,\n type CredentialTestResult,\n useCredentialDependentsQuery,\n useCredentialQuery,\n useDeleteCredentialMutation,\n useRotateCredentialMutation,\n useSetCredentialStatusMutation,\n useTestCredentialMutation,\n} from \"../repos/credentials.ts\";\n\nexport interface CredentialDetailProps {\n credentialId: string;\n /** A connected-app row calls `(connectionId)`; rows are plain text without it. */\n onOpenConnection?: (id: string) => void;\n /** Called after a delete succeeds. */\n onDeleted?: () => void;\n /** The back affordance renders only when given. */\n onBack?: () => void;\n slots?: {\n /** Replaces the not-found state. */\n empty?: ReactNode;\n };\n}\n\ntype Dependents = CredentialDependents[\"connections\"];\n\n/** The textarea's text as a JSON object, or `null`. Never throws and never carries the text. */\nfunction parseSource(text: string): Record<string, unknown> | null {\n try {\n const v: unknown = JSON.parse(text);\n return v !== null && typeof v === \"object\" && !Array.isArray(v)\n ? (v as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nconst fmt = (iso: string) => (Number.isNaN(Date.parse(iso)) ? iso : new Date(iso).toLocaleString());\n\nexport function CredentialDetail({\n credentialId,\n onOpenConnection,\n onDeleted,\n onBack,\n slots,\n}: CredentialDetailProps) {\n const query = useCredentialQuery(credentialId);\n const deps = useCredentialDependentsQuery(credentialId);\n const rotate = useRotateCredentialMutation(credentialId);\n const setStatus = useSetCredentialStatusMutation(credentialId);\n const testMut = useTestCredentialMutation(credentialId);\n const del = useDeleteCredentialMutation();\n\n const [secret, setSecret] = useState(\"\");\n const [rotateError, setRotateError] = useState<string | null>(null);\n const [rotated, setRotated] = useState(false);\n const [testResult, setTestResult] = useState<CredentialTestResult | null>(null);\n const [testError, setTestError] = useState<string | null>(null);\n const [confirming, setConfirming] = useState(false);\n const [blocking, setBlocking] = useState<Dependents | null>(null);\n const [actionError, setActionError] = useState<string | null>(null);\n\n const back = onBack && (\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onBack}>\n ← Credentials\n </button>\n );\n\n if (query.isLoading) {\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-detail\">\n <p className=\"w6w-muted\">Loading…</p>\n </div>\n );\n }\n const c = query.data;\n if (!c) {\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-detail\" data-testid=\"credential-not-found\">\n {slots?.empty ?? <h2>Credential not found</h2>}\n {back}\n </div>\n );\n }\n\n const connected: Dependents = deps.data?.connections ?? [];\n const n = c.connectionCount;\n const disabled = c.status === \"disabled\";\n\n const doRotate = () => {\n setRotated(false);\n const source = parseSource(secret);\n if (!source) {\n // Fixed text: the typed value is never interpolated.\n setRotateError(\"Enter the new secret as a JSON object.\");\n return;\n }\n setRotateError(null);\n rotate.mutate(\n { source },\n {\n onSuccess: () => {\n setSecret(\"\");\n setRotated(true);\n },\n onError: (e) => setRotateError((e as ApiError)?.message ?? \"Rotate failed.\"),\n },\n );\n };\n\n const doTest = () => {\n setTestResult(null);\n setTestError(null);\n testMut.mutate(undefined, {\n onSuccess: setTestResult,\n onError: (e) => setTestError((e as ApiError)?.message ?? \"Test failed.\"),\n });\n };\n\n const doDelete = () => {\n setActionError(null);\n del.mutate(credentialId, {\n onSuccess: (r) => {\n setConfirming(false);\n if (r.ok) onDeleted?.();\n else setBlocking(r.dependents.connections);\n },\n onError: (e) => setActionError((e as ApiError)?.message ?? \"Delete failed.\"),\n });\n };\n\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-detail w6w-card-stack\">\n <div className=\"w6w-embed-conn-card\">\n <h2>{c.name}</h2>\n <p className=\"w6w-small\">\n <code>{c.contract}</code> <span className=\"w6w-embed-conn-badge\">{c.status}</span>\n </p>\n <dl className=\"w6w-small\" data-testid=\"credential-display\">\n {Object.entries(c.display).map(([k, v]) => (\n <div key={k}>\n <dt className=\"w6w-muted\">{k}</dt>\n <dd>{v}</dd>\n </div>\n ))}\n </dl>\n <p className=\"w6w-muted w6w-small\">\n {n} connection{n === 1 ? \"\" : \"s\"} · created {fmt(c.createdAt)} · updated{\" \"}\n {fmt(c.updatedAt)}\n </p>\n {back}\n </div>\n\n <div className=\"w6w-embed-conn-card\" data-testid=\"credential-connections\">\n <h3>Connected apps</h3>\n {connected.length === 0 ? (\n <p className=\"w6w-muted\">Not used by any connection.</p>\n ) : (\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Connected apps\">\n {connected.map((d) => (\n <li key={d.id}>\n {onOpenConnection ? (\n <button\n type=\"button\"\n className=\"w6w-embed-conn-action\"\n onClick={() => onOpenConnection(d.id)}\n >\n {d.displayName || d.appId}\n </button>\n ) : (\n <span>{d.displayName || d.appId}</span>\n )}\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"w6w-embed-conn-card\">\n <h3>Rotate secret</h3>\n <p className=\"w6w-muted w6w-small\" data-testid=\"credential-rotation-impact\">\n {n} connection{n === 1 ? \"\" : \"s\"} will be marked untested\n </p>\n <textarea\n className=\"w6w-input w6w-secret-input\"\n aria-label=\"New secret (JSON object)\"\n rows={5}\n value={secret}\n onChange={(e) => setSecret(e.target.value)}\n name=\"w6w-cred-rotate\"\n autoComplete=\"off\"\n autoCapitalize=\"off\"\n autoCorrect=\"off\"\n spellCheck={false}\n data-1p-ignore=\"true\"\n data-lpignore=\"true\"\n data-bwignore=\"true\"\n data-form-type=\"other\"\n />\n {rotateError && (\n <p className=\"w6w-error\" role=\"alert\" data-testid=\"credential-rotate-error\">\n {rotateError}\n </p>\n )}\n {rotated && <output>Secret rotated.</output>}\n <button type=\"button\" className=\"w6w-btn\" disabled={rotate.isPending} onClick={doRotate}>\n {rotate.isPending ? \"Rotating…\" : \"Rotate\"}\n </button>\n </div>\n\n <div className=\"w6w-embed-conn-card\">\n <h3>Manage</h3>\n <div className=\"w6w-modal-actions\">\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={setStatus.isPending}\n onClick={() => setStatus.mutate(disabled ? \"active\" : \"disabled\")}\n >\n {disabled ? \"Enable\" : \"Disable\"}\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={testMut.isPending}\n onClick={doTest}\n >\n {testMut.isPending ? \"Testing…\" : \"Test credential\"}\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-danger\"\n onClick={() => {\n setBlocking(null);\n setConfirming(true);\n }}\n >\n Delete\n </button>\n </div>\n {testResult && (\n <output data-testid=\"credential-test-result\">\n {testResult.ok ? \"ok\" : (testResult.code ?? \"failed\")}\n </output>\n )}\n {testError && <p role=\"alert\">{testError}</p>}\n {setStatus.isError && (\n <p role=\"alert\">{(setStatus.error as ApiError)?.message ?? \"Update failed.\"}</p>\n )}\n {confirming && (\n <div data-testid=\"credential-delete-confirm\">\n <p className=\"w6w-small\">Delete the credential \"{c.name}\"? This cannot be undone.</p>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-danger\"\n disabled={del.isPending}\n onClick={doDelete}\n >\n Confirm delete\n </button>{\" \"}\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n onClick={() => setConfirming(false)}\n >\n Cancel\n </button>\n </div>\n )}\n {blocking && (\n <div role=\"alert\" data-testid=\"credential-in-use\">\n <p className=\"w6w-small\">\n This credential is still used by {blocking.length} connection\n {blocking.length === 1 ? \"\" : \"s\"}. Delete those integrations first, or rotate this\n credential instead of deleting it.\n </p>\n <ul className=\"w6w-embed-conn-list\">\n {blocking.map((d) => (\n <li key={d.id}>{d.displayName || d.appId}</li>\n ))}\n </ul>\n </div>\n )}\n {actionError && <p role=\"alert\">{actionError}</p>}\n </div>\n </div>\n );\n}\n","/**\n * `<DataStoreView>` — one data store by id: a `table` store as an editable grid with CSV import and\n * export, a `kv` or `doc` store as an entry list with a value editor. Every read and write goes\n * through the embed's `data-stores` repo (`client.dataStores.*`); parsing, row building and the\n * `ifVersion` conflict rule are `@w6w/ui`'s data-store util, and the markup is ui's. This file owns\n * the queries, drafts and conflict state.\n *\n * A save sends the version the entry was loaded at (`ifVersion`). A stale one is a Reload prompt\n * on that row or editor, and nothing is re-sent without `ifVersion`. Scoped or IP-restricted\n * `tsec_` tokens can read a store but not write it (the server refuses).\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { DataStoreEntry } from \"@w6w/sdk\";\nimport {\n CsvPanel,\n DataEntryEditor,\n DataEntryList,\n type DataStoreErrorLocator,\n DataTableGrid,\n type DataTableGridRow,\n NEW_ROW_ID,\n type RowDraft,\n type TableColumn,\n type DataStore as UiDataStore,\n buildRowValue,\n cellErrorsOf,\n csvFilenameOf,\n csvImportMessage,\n dirtyColumns,\n draftFromEntry,\n isVersionConflict,\n kvValueOf,\n kvValueTypeOf,\n locateDataStoreError,\n newRowDraft,\n parseDocText,\n remainingTtlSeconds,\n rowWriteOf,\n serializeCell,\n tableSchemaOf,\n} from \"@w6w/ui\";\nimport { type ReactNode, useState } from \"react\";\nimport { ConfirmModal } from \"../chrome/ConfirmModal.tsx\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n getEntry,\n useDataStoreQuery,\n useDeleteEntryMutation,\n useEntriesQuery,\n useExportCsvMutation,\n useImportCsvMutation,\n useInsertRowMutation,\n useSetEntryMutation,\n} from \"../repos/data-stores.ts\";\n\nexport interface DataStoreViewProps {\n /** The store's id (`ds_…`). */\n id: string;\n /** Omitted: the provider's project. `null` or `\"\"`: none; nothing is read and writes refuse. */\n project?: string | null;\n slots?: {\n /** Replaces the store's name / kind heading. `null`: none. */\n header?: ReactNode;\n };\n}\n\n/**\n * A thrown SDK failure as the locator the views place: `ApiError{status,code,raw}` with the\n * server's `{error:{code,message,field?,row?,column?}}` read from `raw`. The error's own `code`\n * stands in when the body carried none, so a conflict is never missed for want of an envelope.\n */\nexport function dataStoreErrorOf(e: unknown): DataStoreErrorLocator {\n const loc = locateDataStoreError(e);\n const code = (e as { code?: unknown } | null)?.code;\n return loc.code === undefined && typeof code === \"string\" && code !== \"\" ? { ...loc, code } : loc;\n}\n\n/** How much of a stored value the entry list's Value column shows before eliding. */\nconst PREVIEW_CHARS = 80;\n\n/** Save CSV text through the browser's download path; a no-op where there is no object URL. */\nfunction downloadCsv(filename: string, text: string): void {\n if (typeof URL === \"undefined\" || typeof URL.createObjectURL !== \"function\") return;\n const url = URL.createObjectURL(new Blob([text], { type: \"text/csv\" }));\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n URL.revokeObjectURL(url);\n}\n\ninterface PanelProps {\n store: UiDataStore;\n project: string;\n}\n\nfunction TableView({ store, project }: PanelProps) {\n const schema = tableSchemaOf(store);\n const columns: readonly TableColumn[] = schema?.columns ?? [];\n const keyColumn = schema?.key ?? \"\";\n const [prefix, setPrefix] = useState(\"\");\n const [drafts, setDrafts] = useState<Record<string, RowDraft>>({});\n const [cellErrors, setCellErrors] = useState<Record<string, Record<string, string>>>({});\n const [conflicts, setConflicts] = useState<Record<string, true>>({});\n // Entries re-read by Reload: they win over the list until the next successful write.\n const [fresh, setFresh] = useState<Record<string, DataStoreEntry>>({});\n const [gridError, setGridError] = useState<string | null>(null);\n const [deleteKey, setDeleteKey] = useState<string | null>(null);\n const [csvResult, setCsvResult] = useState<{ ok: boolean; message: string } | null>(null);\n\n const client = useEmbedClient();\n const qc = useQueryClient();\n const entriesQuery = useEntriesQuery(store.id, project, prefix);\n const setMut = useSetEntryMutation();\n const insertMut = useInsertRowMutation();\n const deleteMut = useDeleteEntryMutation();\n const importMut = useImportCsvMutation();\n const exportMut = useExportCsvMutation();\n\n const entries = (entriesQuery.data?.pages.flatMap((p) => p.items) ?? []).map(\n (e) => fresh[e.key] ?? e,\n );\n const entryByKey = new Map(entries.map((e) => [e.key, e]));\n\n const gridRows: DataTableGridRow[] = [];\n const draftOf = (id: string): RowDraft | undefined => drafts[id];\n const newDraft = draftOf(NEW_ROW_ID);\n const rowOf = (id: string, draft: RowDraft, entry: DataStoreEntry | undefined) => {\n const base = entry === undefined ? null : draftFromEntry(entry, columns);\n gridRows.push({\n id,\n isNew: id === NEW_ROW_ID,\n cells: draft.cells,\n version: draft.version,\n dirty: base === null ? true : dirtyColumns(draft, base, columns).length > 0,\n conflict: conflicts[id] === true,\n cellErrors: cellErrors[id],\n });\n };\n if (newDraft !== undefined) rowOf(NEW_ROW_ID, newDraft, undefined);\n for (const entry of entries)\n rowOf(entry.key, draftOf(entry.key) ?? draftFromEntry(entry, columns), entry);\n\n const clearMessages = (id: string) => {\n setCellErrors((p) => omit(p, id));\n setConflicts((p) => omit(p, id));\n };\n const forgetDraft = (id: string) => {\n setDrafts((p) => omit(p, id));\n clearMessages(id);\n };\n\n function editCell(id: string, column: string, text: string) {\n const entry = entryByKey.get(id);\n const draft = draftOf(id) ?? (entry ? draftFromEntry(entry, columns) : newRowDraft(columns));\n setDrafts((p) => ({ ...p, [id]: { ...draft, cells: { ...draft.cells, [column]: text } } }));\n setCellErrors((p) => {\n const row = p[id];\n if (row === undefined || !(column in row)) return p;\n const next = omit(row, column);\n return Object.keys(next).length === 0 ? omit(p, id) : { ...p, [id]: next };\n });\n }\n\n async function save(id: string) {\n const entry = entryByKey.get(id);\n const draft = draftOf(id) ?? (entry ? draftFromEntry(entry, columns) : undefined);\n if (draft === undefined) return;\n setGridError(null);\n clearMessages(id);\n const built = buildRowValue(draft, columns);\n if (!built.ok) {\n setCellErrors((p) => ({ ...p, [id]: built.errors }));\n return;\n }\n const write = rowWriteOf(\n draft,\n built.value,\n remainingTtlSeconds(entry?.expiresAt ?? null, Date.now()),\n );\n try {\n if (write.kind === \"insert\") {\n await insertMut.mutateAsync({\n id: store.id,\n row: write.value,\n ttlSeconds: write.ttlSeconds,\n project,\n });\n } else {\n await setMut.mutateAsync({\n id: store.id,\n key: write.key,\n value: write.value,\n ifVersion: write.ifVersion,\n ttlSeconds: write.ttlSeconds,\n project,\n });\n }\n setFresh((p) => omit(p, id));\n forgetDraft(id);\n } catch (err) {\n const loc = dataStoreErrorOf(err);\n if (isVersionConflict(loc)) {\n setConflicts((p) => ({ ...p, [id]: true }));\n return;\n }\n const placed = cellErrorsOf(loc, columns);\n if (placed !== null) {\n setCellErrors((p) => ({ ...p, [id]: placed }));\n return;\n }\n setGridError(loc.message);\n }\n }\n\n async function reload(id: string) {\n try {\n const entry = await getEntry(client, store.id, id, project);\n setFresh((p) => ({ ...p, [id]: entry }));\n forgetDraft(id);\n await qc.invalidateQueries({ queryKey: [\"data-stores\"] });\n } catch (err) {\n setGridError(dataStoreErrorOf(err).message);\n }\n }\n\n function confirmDelete() {\n const key = deleteKey;\n setDeleteKey(null);\n if (key === null) return;\n if (key !== NEW_ROW_ID) deleteMut.mutate({ id: store.id, key, project });\n forgetDraft(key);\n }\n\n async function importFile(file: File) {\n setCsvResult(null);\n try {\n const res = await importMut.mutateAsync({ id: store.id, csv: await file.text(), project });\n setCsvResult(csvImportMessage({ status: 200, text: JSON.stringify(res) }));\n } catch (err) {\n const e = err as { status?: unknown; raw?: unknown };\n setCsvResult(\n typeof e.status === \"number\"\n ? csvImportMessage({ status: e.status, text: JSON.stringify(e.raw ?? null) })\n : { ok: false, message: dataStoreErrorOf(err).message },\n );\n }\n }\n\n async function exportCsv() {\n try {\n const text = await exportMut.mutateAsync({ id: store.id, project });\n downloadCsv(csvFilenameOf(null, store.name), text);\n setCsvResult(null);\n } catch (err) {\n setCsvResult({ ok: false, message: dataStoreErrorOf(err).message });\n }\n }\n\n return (\n <div>\n <CsvPanel\n result={csvResult}\n busy={exportMut.isPending}\n onImport={importFile}\n onRefuse={(message) => setCsvResult({ ok: false, message })}\n onExport={exportCsv}\n />\n <DataTableGrid\n columns={columns}\n keyColumn={keyColumn}\n rows={gridRows}\n error={gridError}\n loading={entriesQuery.isPending}\n hasMore={entriesQuery.hasNextPage}\n empty={<p className=\"muted small\">No rows match this key prefix.</p>}\n onCellChange={editCell}\n onSave={(id) => void save(id)}\n onDelete={setDeleteKey}\n onReload={(id) => void reload(id)}\n onAddRow={() => {\n if (NEW_ROW_ID in drafts) return;\n setDrafts((p) => ({ ...p, [NEW_ROW_ID]: newRowDraft(columns) }));\n setGridError(null);\n }}\n onLoadMore={() => void entriesQuery.fetchNextPage()}\n onSearch={setPrefix}\n />\n {deleteKey !== null && (\n <ConfirmModal\n title=\"Delete entry\"\n message={\n deleteKey === NEW_ROW_ID\n ? \"Discard this unsaved row?\"\n : `Delete \"${deleteKey}\"? This cannot be undone.`\n }\n confirmLabel=\"Delete\"\n onConfirm={confirmDelete}\n onClose={() => setDeleteKey(null)}\n />\n )}\n </div>\n );\n}\n\nfunction KvDocView({ store, project }: PanelProps) {\n const isDoc = store.kind === \"doc\";\n const kvType = kvValueTypeOf(store);\n const [prefix, setPrefix] = useState(\"\");\n const [selectedKey, setSelectedKey] = useState<string | null>(null);\n const [isNew, setIsNew] = useState(false);\n const [newKey, setNewKey] = useState(\"\");\n const [text, setText] = useState(\"\");\n const [valueError, setValueError] = useState<string | null>(null);\n const [conflict, setConflict] = useState(false);\n const [fresh, setFresh] = useState<Record<string, DataStoreEntry>>({});\n const [deleteKey, setDeleteKey] = useState<string | null>(null);\n\n const client = useEmbedClient();\n const qc = useQueryClient();\n const entriesQuery = useEntriesQuery(store.id, project, prefix);\n const setMut = useSetEntryMutation();\n const deleteMut = useDeleteEntryMutation();\n\n const entries = (entriesQuery.data?.pages.flatMap((p) => p.items) ?? []).map(\n (e) => fresh[e.key] ?? e,\n );\n const selected = selectedKey === null ? undefined : entries.find((e) => e.key === selectedKey);\n const editing = isNew || selectedKey !== null;\n\n const seedOf = (entry: DataStoreEntry): string =>\n isDoc ? JSON.stringify(entry.value ?? null, null, 2) : serializeCell(kvType, entry.value);\n const previewOf = (entry: DataStoreEntry): string => {\n const raw = seedOf(entry).replace(/\\s+/g, \" \");\n return raw.length > PREVIEW_CHARS ? `${raw.slice(0, PREVIEW_CHARS)}…` : raw;\n };\n\n function openEditor(entry: DataStoreEntry) {\n setSelectedKey(entry.key);\n setIsNew(false);\n setText(seedOf(entry));\n setValueError(null);\n setConflict(false);\n }\n function closeEditor() {\n setSelectedKey(null);\n setIsNew(false);\n setNewKey(\"\");\n setText(\"\");\n setValueError(null);\n setConflict(false);\n }\n\n async function save() {\n setValueError(null);\n setConflict(false);\n const parsed = isDoc ? parseDocText(text) : kvValueOf(kvType, text);\n if (!parsed.ok) {\n setValueError(parsed.message);\n return;\n }\n const key = isNew ? newKey.trim() : selectedKey;\n if (key === null || key === \"\") {\n setValueError(\"Enter a key.\");\n return;\n }\n try {\n await setMut.mutateAsync({\n id: store.id,\n key,\n value: parsed.value,\n // A new entry must not exist yet; an existing one is guarded by the version loaded.\n ifVersion: isNew ? 0 : (selected?.version ?? 0),\n ttlSeconds: isNew\n ? undefined\n : remainingTtlSeconds(selected?.expiresAt ?? null, Date.now()),\n project,\n });\n setFresh((p) => omit(p, key));\n closeEditor();\n } catch (err) {\n const loc = dataStoreErrorOf(err);\n if (isVersionConflict(loc)) setConflict(true);\n else setValueError(loc.message);\n }\n }\n\n async function reload() {\n if (selectedKey === null) return;\n try {\n const entry = await getEntry(client, store.id, selectedKey, project);\n setFresh((p) => ({ ...p, [selectedKey]: entry }));\n setText(seedOf(entry));\n setConflict(false);\n setValueError(null);\n await qc.invalidateQueries({ queryKey: [\"data-stores\"] });\n } catch (err) {\n setValueError(dataStoreErrorOf(err).message);\n }\n }\n\n async function confirmDelete() {\n const key = deleteKey;\n setDeleteKey(null);\n if (key === null) return;\n try {\n await deleteMut.mutateAsync({ id: store.id, key, project });\n if (key === selectedKey) closeEditor();\n } catch (err) {\n setValueError(dataStoreErrorOf(err).message);\n }\n }\n\n return (\n <div>\n <DataEntryList\n rows={entries.map((e) => ({ key: e.key, version: e.version, preview: previewOf(e) }))}\n loading={entriesQuery.isPending}\n empty={<p className=\"muted small\">No entries match this key prefix.</p>}\n hasMore={entriesQuery.hasNextPage}\n onOpen={(key) => {\n const entry = entries.find((e) => e.key === key);\n if (entry) openEditor(entry);\n }}\n onSearch={setPrefix}\n onNew={() => {\n setSelectedKey(null);\n setIsNew(true);\n setNewKey(\"\");\n setText(\"\");\n setValueError(null);\n setConflict(false);\n }}\n onLoadMore={() => void entriesQuery.fetchNextPage()}\n />\n {editing && (\n <DataEntryEditor\n kind={isDoc ? \"doc\" : \"kv\"}\n isNew={isNew}\n entryKey={selectedKey ?? undefined}\n newKey={newKey}\n version={selected?.version ?? null}\n expiresAt={selected?.expiresAt ?? null}\n text={text}\n error={valueError}\n conflict={conflict}\n saving={setMut.isPending || deleteMut.isPending}\n onDelete={isNew ? undefined : () => setDeleteKey(selectedKey)}\n onTextChange={(next) => {\n setText(next);\n setValueError(null);\n }}\n onKeyChange={setNewKey}\n onSave={() => void save()}\n onCancel={closeEditor}\n onReload={() => void reload()}\n />\n )}\n {deleteKey !== null && (\n <ConfirmModal\n title=\"Delete entry\"\n message={`Delete \"${deleteKey}\"? This cannot be undone.`}\n confirmLabel=\"Delete\"\n onConfirm={confirmDelete}\n onClose={() => setDeleteKey(null)}\n />\n )}\n </div>\n );\n}\n\n/** A copy of `obj` without `key` (the same object when `key` is absent). */\nfunction omit<T>(obj: Record<string, T>, key: string): Record<string, T> {\n if (!(key in obj)) return obj;\n const next = { ...obj };\n delete next[key];\n return next;\n}\n\nexport function DataStoreView({ id, project, slots }: DataStoreViewProps) {\n const p = useEditorProject(project);\n const storeQuery = useDataStoreQuery(id, p ?? undefined);\n const store = storeQuery.data as unknown as UiDataStore | undefined;\n\n let body: ReactNode;\n if (p == null) {\n body = <p className=\"muted\">No project selected.</p>;\n } else if (storeQuery.isError) {\n body = <p className=\"result error\">{dataStoreErrorOf(storeQuery.error).message}</p>;\n } else if (store === undefined) {\n body = <p className=\"muted\">Loading…</p>;\n } else if (store.kind === \"table\") {\n body = <TableView key={store.id} store={store} project={p} />;\n } else {\n body = <KvDocView key={store.id} store={store} project={p} />;\n }\n\n const header =\n slots?.header === undefined\n ? store && (\n <div>\n <h3>{store.name}</h3>\n <p className=\"muted small\">\n {store.kind} · {store.entryCount} {store.entryCount === 1 ? \"entry\" : \"entries\"}\n </p>\n </div>\n )\n : slots.header;\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n {header}\n {body}\n </section>\n </div>\n );\n}\n","/**\n * `<DataStoreList>` — a project's data stores (key-value, document, table), with in-place create\n * and archive. Rows render through `@w6w/ui`'s `DataStoreList`; this file owns the query, the\n * create dialog and the archive confirmation. Opening a store is the host's `onOpen` / `getHref`\n * (see `<DataStoreView>` for the store itself).\n */\nimport {\n ColumnsEditor,\n DATA_STORE_KINDS,\n DATA_STORE_KIND_LABEL,\n type DataStoreKind,\n SCALAR_TYPES,\n type ScalarType,\n type TableColumn,\n type DataStore as UiDataStore,\n DataStoreList as UiDataStoreList,\n errorPlacement,\n} from \"@w6w/ui\";\nimport type { MouseEvent, ReactNode } from \"react\";\nimport { useState } from \"react\";\nimport { ConfirmModal } from \"../chrome/ConfirmModal.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n useArchiveDataStoreMutation,\n useCreateDataStoreMutation,\n useDataStoresQuery,\n} from \"../repos/data-stores.ts\";\nimport { dataStoreErrorOf } from \"./DataStoreView.tsx\";\n\nexport interface DataStoreListSlots {\n /** Replaces the section heading and its description (the New button stays). `null`: none. */\n header?: ReactNode;\n /** Replaces the empty-state copy. */\n empty?: ReactNode;\n}\n\nexport interface DataStoreListProps {\n /** Omitted: the provider's project. `null` or `\"\"`: none; nothing is read and writes refuse. */\n project?: string | null;\n /** The host decides what opening a row means; with `getHref` it may `preventDefault`. */\n onOpen?: (id: string, event: MouseEvent<Element>) => void;\n /** Given, a row's main area is a real `<a href>`; its click still calls `onOpen`. */\n getHref?: (id: string) => string;\n slots?: DataStoreListSlots;\n}\n\n/** The request-body fields the create dialog has a labelled error slot for. */\nconst FIELD_SLOTS: readonly string[] = [\"name\", \"kind\", \"description\", \"schema\"];\n\nfunction CreateDataStoreModal(props: { project: string; onClose: () => void }) {\n const [name, setName] = useState(\"\");\n const [description, setDescription] = useState(\"\");\n const [kind, setKind] = useState<DataStoreKind>(\"kv\");\n const [valueType, setValueType] = useState<ScalarType>(\"string\");\n const [columns, setColumns] = useState<TableColumn[]>([]);\n const [keyColumn, setKeyColumn] = useState(\"\");\n const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});\n const [columnErrors, setColumnErrors] = useState<Record<string, string>>({});\n const [formError, setFormError] = useState<string | null>(null);\n const createMut = useCreateDataStoreMutation();\n\n function submit() {\n setFieldErrors({});\n setColumnErrors({});\n setFormError(null);\n const input: { kind: DataStoreKind; name: string; description?: string; schema?: object } = {\n kind,\n name,\n };\n if (kind === \"kv\") input.schema = { valueType };\n if (kind === \"table\")\n input.schema = keyColumn === \"\" ? { columns } : { columns, key: keyColumn };\n if (description !== \"\") input.description = description;\n createMut.mutate(\n // The SDK's create body types `schema` as table columns only; the wire takes the S-2 shape\n // per kind, so the kv `{valueType}` schema is passed through as the host defines it.\n { input: input as Parameters<typeof createMut.mutate>[0][\"input\"], project: props.project },\n {\n onSuccess: () => props.onClose(),\n onError: (err) => {\n const loc = dataStoreErrorOf(err);\n const place = errorPlacement(loc);\n if (place.kind === \"cell\" && columns.some((c) => c.name === place.column)) {\n setColumnErrors({ [place.column]: loc.message });\n return;\n }\n if (place.kind === \"field\" && FIELD_SLOTS.includes(place.field)) {\n setFieldErrors({ [place.field]: loc.message });\n return;\n }\n setFormError(loc.message);\n },\n },\n );\n }\n\n return (\n <Modal title=\"New data store\" onClose={props.onClose}>\n <div className=\"modal-body\">\n <label className=\"field\">\n <span>Name</span>\n <input\n type=\"text\"\n data-testid=\"data-store-name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n placeholder=\"e.g. counters\"\n />\n </label>\n {fieldErrors.name !== undefined && (\n <div className=\"result error\" data-testid=\"data-store-field-error-name\">\n {fieldErrors.name}\n </div>\n )}\n <label className=\"field\">\n <span>Description</span>\n <input\n type=\"text\"\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n placeholder=\"What this store holds\"\n />\n </label>\n <label className=\"field\">\n <span>Kind</span>\n <select\n data-testid=\"data-store-kind\"\n value={kind}\n onChange={(e) => {\n setKind(e.target.value as DataStoreKind);\n setKeyColumn(\"\");\n }}\n >\n {DATA_STORE_KINDS.map((k) => (\n <option key={k} value={k}>\n {DATA_STORE_KIND_LABEL[k]}\n </option>\n ))}\n </select>\n <span className=\"hint\">The kind is fixed once the store exists.</span>\n </label>\n {fieldErrors.kind !== undefined && <div className=\"result error\">{fieldErrors.kind}</div>}\n {kind === \"kv\" && (\n <label className=\"field\">\n <span>Value type</span>\n <select value={valueType} onChange={(e) => setValueType(e.target.value as ScalarType)}>\n {SCALAR_TYPES.map((t) => (\n <option key={t} value={t}>\n {t}\n </option>\n ))}\n </select>\n </label>\n )}\n {kind === \"table\" && (\n <ColumnsEditor\n columns={columns}\n onChange={setColumns}\n keyColumn={keyColumn}\n onKeyColumnChange={setKeyColumn}\n columnErrors={columnErrors}\n />\n )}\n {fieldErrors.schema !== undefined && (\n <div className=\"result error\">{fieldErrors.schema}</div>\n )}\n {formError !== null && (\n <div className=\"result error\" data-testid=\"data-store-form-error\">\n {formError}\n </div>\n )}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"data-store-create\"\n disabled={createMut.isPending}\n onClick={submit}\n >\n {createMut.isPending ? \"Creating…\" : \"Create\"}\n </button>\n </div>\n </Modal>\n );\n}\n\nexport function DataStoreList({ project, onOpen, getHref, slots }: DataStoreListProps) {\n const p = useEditorProject(project);\n const storesQuery = useDataStoresQuery(p ?? undefined);\n const archiveMut = useArchiveDataStoreMutation();\n const [creating, setCreating] = useState(false);\n const [pending, setPending] = useState<UiDataStore | null>(null);\n const [archiveError, setArchiveError] = useState<string | null>(null);\n\n const header =\n slots?.header === undefined ? (\n <div>\n <h3>Data stores</h3>\n <p className=\"muted small\">Key-value, document and table storage for this project.</p>\n </div>\n ) : (\n slots.header\n );\n\n return (\n <div className=\"w6w-embed-root\">\n <UiDataStoreList\n stores={(storesQuery.data ?? []) as unknown as UiDataStore[]}\n loading={storesQuery.isLoading}\n error={\n archiveError ??\n (storesQuery.error != null ? dataStoreErrorOf(storesQuery.error).message : null)\n }\n onOpen={onOpen}\n getHref={getHref}\n onArchive={(s) => {\n setArchiveError(null);\n setPending(s);\n }}\n busy={archiveMut.isPending}\n slots={{\n header,\n actions: (\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"data-store-new\"\n disabled={p == null}\n onClick={() => setCreating(true)}\n >\n + New data store\n </button>\n ),\n empty: slots?.empty,\n }}\n />\n\n {creating && p != null && (\n <CreateDataStoreModal project={p} onClose={() => setCreating(false)} />\n )}\n\n {pending && (\n <ConfirmModal\n title=\"Archive data store\"\n message={`Archive \"${pending.name}\" and its ${pending.entryCount} ${\n pending.entryCount === 1 ? \"entry\" : \"entries\"\n }? Workflows and the API can no longer reach it.`}\n confirmLabel=\"Archive\"\n onConfirm={() => {\n const store = pending;\n setPending(null);\n if (p == null) return;\n archiveMut.mutate(\n { id: store.id, project: p },\n { onError: (e) => setArchiveError(dataStoreErrorOf(e).message) },\n );\n }}\n onClose={() => setPending(null)}\n />\n )}\n </div>\n );\n}\n"],"names":["CallableKindList","props","kind","d","descriptorFor","importing","setImporting","useState","rows","row","isRowArchived","jsxs","jsx","CallableList","ImportSpecModal","functionsKey","endpointsKey","workflowsKey","_kind","id","_a","FunctionList","query","useFunctionsQuery","project","useEditorProject","creatingId","setCreatingId","newCallableId","FunctionIdentityModal","EndpointList","useEndpointsQuery","Fragment","isEndpointDraft","EndpointIdentityModal","WorkflowList","useWorkflowsQuery","createMut","useCreateWorkflowMutation","createError","setCreateError","t","blankDefinition","res","e","ReliabilityBoard","variant","limit","days","showChart","getHref","onOpen","showAllHref","onShowAll","slots","provided","useEmbedProject","resolved","effective","useProjectReliabilityQuery","empty","ReliabilityList","_b","preview","content","s","DocumentList","rowSlots","p","docsQuery","useDocumentsQuery","deleteMut","useDeleteDocumentMutation","modal","setModal","pending","setPending","header","EmptyState","columns","lead","footer","CallFromCodeButton","EditButton","DeleteButton","DataTable","DocumentFormModal","ConfirmModal","KIND_LABELS","kindLabel","TILE_VARIANT","isActivityKind","tileVariantFor","buildNameMaps","functions","workflows","functionNames","label","workflowNames","resolveTileTitle","entry","names","fallback","workflowId","left","links","pad2","n","formatTimestamp","iso","formatDuration","ms","startOfTodayIso","formatBucketLabel","bucket","day","OutcomeMark","ok","StatCard","value","HeadlineRow","title","headline","loading","h","ActivityTitle","text","target","click","event","BaseActivityTile","duration","ListItem","NamedActivityTile","TILES","RecentActivityTile","Tile","ActivitySummary","todayQuery","useDashboardStatsQuery","weekQuery","functionsQuery","workflowsQuery","useMemo","error","errorMessage","recent","series","weekBucket","_c","nothingYet","_d","_e","_f","r","isProjectScope","scope","RunHistory","own","setOwn","EMPTY_HISTORY_FILTERS","controlled","filters","onFiltersChange","next","HistoryView","Logs","rest","LogsView","DAY_MS","projectVendorIncidents","vendor","isOpenIncident","formatCalendarDay","daysBetween","fromIso","toMs","fromMs","incidentAgeCopy","nowMs","ageDays","startLabel","openPart","updateIso","updateDays","updateLabel","updatePart","vendorComponentEntries","components","uptimeDays","service","ERROR_KINDS","formatDay","formatStamp","Stat","hint","VendorPanel","displayName","unreadable","openIncidents","HealthStatusPill","k","name","comp","DailyVolumeChart","maxCalls","UptimeDetail","historyWindow","withTraffic","incidents","vendorEmptyLabel","HistoryTimeline","ErrorMixChart","errors","sum","max","CallLog","appId","useApiCallsQuery","ApiError","calls","call","i","BackLink","backHref","onBack","ServiceDetail","useReliabilityQuery","siteLabel","site","o","ConnectionDependentRoutes","routes","projectId","reconnecting","setReconnecting","ReconnectHost","ModelRoutesManager","ConnectionDependentRows","callables","onOpenCallable","CallableRows","c","sites","NO_ROWS","ConnectionList","addLabel","api","useW6WApi","qc","useQueryClient","useConnectionsQuery","lookupIds","connectionAppIdsToLookUp","byId","useEditorApps","del","useDeleteConnectionMutation","adding","setAdding","editing","setEditing","deleting","setDeleting","deps","useConnectionDependentsQuery","canEdit","actions","UiConnectionList","AddConnectionModal","connectionsKey","EditConnectionModal","connectionKey","DeleteConfirm","onClose","onConfirm","plain","plural","one","many","usedBy","consequences","x","Modal","relativeTime","then","secs","mins","hours","NOTICE_DISMISS_MS","NOTICE_ICON","ConnectionDetail","connectionId","onOpenAction","connQuery","useConnectionQuery","appsById","appSummary","resolveConnectionAppMeta","appDetailQuery","useAppQuery","savedTestsQuery","useSavedTestsQuery","savedTestsByAction","map","list","dependents","usedByRoutes","runHistory","useTestRunsQuery","editOpen","setEditOpen","actionFilter","setActionFilter","testMut","useTestConnectionMutation","testNotice","setTestNotice","useEffect","timer","runTest","sortedActions","a","b","filteredActions","q","conn","app","ConnectionHeader","IconButton","tests","run","NO_FILTER","grouped","major","minor","rateText","rate","parts","limitsText","m","maxInputTokens","maxOutputTokens","ModelCatalog","client","useEmbedClient","filter","useInfiniteQuery","modelCatalogKey","last","pageParam","listModelCatalog","models","costText","cost","costsText","costs","unpriced","itemCost","item","totalsTruncated","report","ModelUsage","modelUsageKey","getModelUsage","pages","totals","items","truncated","CredentialList","contract","useCredentialsQuery","shown","parseSource","v","fmt","CredentialDetail","credentialId","onOpenConnection","onDeleted","useCredentialQuery","useCredentialDependentsQuery","rotate","useRotateCredentialMutation","setStatus","useSetCredentialStatusMutation","useTestCredentialMutation","useDeleteCredentialMutation","secret","setSecret","rotateError","setRotateError","rotated","setRotated","testResult","setTestResult","testError","setTestError","confirming","setConfirming","blocking","setBlocking","actionError","setActionError","back","connected","disabled","doRotate","source","doTest","doDelete","dataStoreErrorOf","loc","locateDataStoreError","code","PREVIEW_CHARS","downloadCsv","filename","url","TableView","store","schema","tableSchemaOf","keyColumn","prefix","setPrefix","drafts","setDrafts","cellErrors","setCellErrors","conflicts","setConflicts","fresh","setFresh","gridError","setGridError","deleteKey","setDeleteKey","csvResult","setCsvResult","entriesQuery","useEntriesQuery","setMut","useSetEntryMutation","insertMut","useInsertRowMutation","useDeleteEntryMutation","importMut","useImportCsvMutation","exportMut","useExportCsvMutation","entries","entryByKey","gridRows","draftOf","newDraft","NEW_ROW_ID","rowOf","draft","base","draftFromEntry","dirtyColumns","clearMessages","omit","forgetDraft","editCell","column","newRowDraft","save","built","buildRowValue","write","rowWriteOf","remainingTtlSeconds","err","isVersionConflict","placed","cellErrorsOf","reload","getEntry","confirmDelete","key","importFile","file","csvImportMessage","exportCsv","csvFilenameOf","CsvPanel","message","DataTableGrid","KvDocView","isDoc","kvType","kvValueTypeOf","selectedKey","setSelectedKey","isNew","setIsNew","newKey","setNewKey","setText","valueError","setValueError","conflict","setConflict","selected","seedOf","serializeCell","previewOf","raw","openEditor","closeEditor","parsed","parseDocText","kvValueOf","DataEntryList","DataEntryEditor","obj","DataStoreView","storeQuery","useDataStoreQuery","body","FIELD_SLOTS","CreateDataStoreModal","setName","description","setDescription","setKind","valueType","setValueType","setColumns","setKeyColumn","fieldErrors","setFieldErrors","columnErrors","setColumnErrors","formError","setFormError","useCreateDataStoreMutation","submit","input","place","errorPlacement","DATA_STORE_KINDS","DATA_STORE_KIND_LABEL","SCALAR_TYPES","ColumnsEditor","DataStoreList","storesQuery","useDataStoresQuery","archiveMut","useArchiveDataStoreMutation","creating","setCreating","archiveError","setArchiveError","UiDataStoreList"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmBO,SAASA,GAA6DC,GAiB1E;AACD,QAAM,EAAE,MAAAC,MAASD,GACXE,IAAIC,GAAcF,CAAI,GACtB,CAACG,GAAWC,CAAY,IAAIC,EAAS,EAAK,GAE1CC,KAA2BP,EAAM,QAAQ,CAAA,GAAI,IAAI,CAACQ,OAAS;AAAA,IAC/D,GAAGR,EAAM,MAAMQ,CAAG;AAAA,IAClB,IAAIA,EAAI;AAAA,IACR,UAAUC,GAAcD,CAAG;AAAA,EAAA,EAC3B;AAEF,SACE,gBAAAE,EAAC,OAAA,EAAI,WAAU,kBACb,UAAA;AAAA,IAAA,gBAAAC;AAAA,MAACC;AAAA,MAAA;AAAA,QACC,MAAAL;AAAA,QACA,OAAOL,EAAE;AAAA,QACT,aAAaA,EAAE;AAAA,QACf,WAAWA,EAAE;AAAA,QACb,UAAUA,EAAE;AAAA,QACZ,cAAcA,EAAE;AAAA,QAChB,SAAS;AAAA,UACP,cAAcA,EAAE;AAAA,UAChB,YAAYA,EAAE;AAAA,UACd,eAAeA,EAAE;AAAA,QAAA;AAAA,QAEnB,SAASF,EAAM;AAAA,QACf,OAAOA,EAAM;AAAA,QACb,UAAUA,EAAM;AAAA,QAChB,UAAUA,EAAM;AAAA,QAChB,UAAU,MAAMK,EAAa,EAAI;AAAA,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A;AAAA,IAAA;AAAA,EAChC,GAEJ;AAEJ;"}
1
+ {"version":3,"file":"lists.mjs","sources":["../src/lists/CallableKindList.tsx","../src/lists/FunctionList.tsx","../src/lists/EndpointList.tsx","../src/lists/WorkflowList.tsx","../src/lists/ReliabilityBoard.tsx","../src/lists/DocumentList.tsx","../src/lib/recent-activity.ts","../src/lists/ActivitySummary.tsx","../src/lists/RunHistory.tsx","../src/lists/Logs.tsx","../src/lists/vendor-history.ts","../src/lists/ServiceDetail.tsx","../src/lists/ConnectionDependents.tsx","../src/lists/ConnectionList.tsx","../src/lists/ConnectionDetail.tsx","../src/lists/ModelCatalog.tsx","../src/lists/ModelUsage.tsx","../src/lists/CredentialList.tsx","../src/lists/CredentialDetail.tsx","../src/lists/DataStoreView.tsx","../src/lists/DataStoreList.tsx"],"sourcesContent":["import { CallableList, type CallableListProps, type CallableListRow } from \"@w6w/ui\";\nimport { type ReactNode, useState } from \"react\";\nimport { ImportSpecModal } from \"../chrome/ImportSpecModal.tsx\";\nimport { type CallableKind, descriptorFor } from \"../lib/callable-descriptors.ts\";\nimport { type ArchivableRow, isRowArchived } from \"../lib/rail-settings.ts\";\nimport { endpointsKey } from \"../repos/endpoints.ts\";\nimport { functionsKey } from \"../repos/functions.ts\";\nimport { workflowsKey } from \"../repos/workflows.ts\";\n\n/**\n * The internal frame the three kind lists (`FunctionList`, `EndpointList`, `WorkflowList`) share:\n * ui's presentational `CallableList` filled with one kind's copy and test ids, the archived\n * decision, and the Import flow. Never re-exported from `./lists` — the public surface is the three\n * kind components.\n *\n * It renders the one `.w6w-embed-root` of the list (a kind's create modal rides in as `children`,\n * inside that root) and navigates nowhere: opening is `onOpen`/`getHref`, an imported row opens\n * through `onOpen` too.\n */\nexport function CallableKindList<Row extends { id: string } & ArchivableRow>(props: {\n kind: CallableKind;\n /** `undefined` while the list query has not answered. */\n rows: readonly Row[] | undefined;\n loading: boolean;\n /** Everything about a row except the id and the archived flag, which the frame owns. */\n toRow: (row: Row) => Omit<CallableListRow, \"id\" | \"archived\">;\n /** Only the Import flow reads it (the workflow list key); `null` means no project. */\n project: string | null;\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n getHref?: (id: string) => string;\n onCreate: () => void;\n creating?: boolean;\n error?: string | null;\n slots?: CallableListProps[\"slots\"];\n /** The kind's create modal. */\n children?: ReactNode;\n}) {\n const { kind } = props;\n const d = descriptorFor(kind);\n const [importing, setImporting] = useState(false);\n\n const rows: CallableListRow[] = (props.rows ?? []).map((row) => ({\n ...props.toRow(row),\n id: row.id,\n archived: isRowArchived(row),\n }));\n\n return (\n <div className=\"w6w-embed-root\">\n <CallableList\n rows={rows}\n title={d.listTitle}\n description={d.listDescription}\n emptyCopy={d.emptyCopy}\n newLabel={d.newLabel}\n openRowTitle={d.openRowTitle}\n testIds={{\n showArchived: d.showArchivedTestId,\n importOpen: d.importOpenTestId,\n archivedBadge: d.archivedBadgeTestId,\n }}\n loading={props.loading}\n error={props.error}\n onCreate={props.onCreate}\n creating={props.creating}\n onImport={() => setImporting(true)}\n onOpen={props.onOpen}\n getHref={props.getHref}\n slots={props.slots}\n />\n {importing && (\n <ImportSpecModal\n kind={kind}\n project={props.project ?? undefined}\n listKeys={{ functionsKey, endpointsKey, workflowsKey }}\n onOpenImported={(_kind, id) => props.onOpen?.(id)}\n onClose={() => setImporting(false)}\n />\n )}\n {props.children}\n </div>\n );\n}\n","import type { CallableListProps } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { FunctionIdentityModal } from \"../forms/CreateFunctionModal.tsx\";\nimport { newCallableId } from \"../lib/callable-descriptors.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport { type FunctionSummary, useFunctionsQuery } from \"../repos/functions.ts\";\nimport { CallableKindList } from \"./CallableKindList.tsx\";\n\nexport interface FunctionListProps {\n /** Project for Import only (the Functions list itself is account-wide). Omitted: the provider's. */\n project?: string | null;\n /** A row was clicked, or an import completed. Navigation is the host's. */\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n /** When set, each row is a real `<a href>`; a click still calls `onOpen`. */\n getHref?: (id: string) => string;\n /** A Function was created from the list's New button; receives the SERVER's id. */\n onCreated?: (id: string) => void;\n slots?: CallableListProps[\"slots\"];\n}\n\n/**\n * The account's Functions: rows from `GET /functions`, archived ones behind a Show-archived toggle,\n * a New button that creates a Function (create-first: the row is POSTed before any editor exists),\n * and Import. Never navigates — the host wires `onOpen` / `getHref` / `onCreated`.\n */\nexport function FunctionList(props: FunctionListProps) {\n const query = useFunctionsQuery();\n const project = useEditorProject(props.project);\n const [creatingId, setCreatingId] = useState<string | null>(null);\n\n return (\n <CallableKindList<FunctionSummary>\n kind=\"function\"\n rows={query.data}\n loading={query.isLoading}\n error={query.error ? String(query.error) : null}\n project={project}\n toRow={(row) => ({\n title: row.displayName || row.key,\n description: row.description,\n badges: row.valid ? null : <span className=\"w6w-callable-list-badge\">incomplete</span>,\n })}\n onOpen={props.onOpen}\n getHref={props.getHref}\n onCreate={() => setCreatingId(newCallableId(\"function\"))}\n slots={props.slots}\n >\n {creatingId !== null && (\n <FunctionIdentityModal\n newId={creatingId}\n takenKeys={(query.data ?? []).map((row) => row.key)}\n onClose={() => setCreatingId(null)}\n onCreated={(id) => {\n setCreatingId(null);\n props.onCreated?.(id);\n }}\n />\n )}\n </CallableKindList>\n );\n}\n","import type { CallableListProps } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { EndpointIdentityModal } from \"../forms/CreateEndpointModal.tsx\";\nimport { newCallableId } from \"../lib/callable-descriptors.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport { type EndpointSummary, isEndpointDraft, useEndpointsQuery } from \"../repos/endpoints.ts\";\nimport { CallableKindList } from \"./CallableKindList.tsx\";\n\nexport interface EndpointListProps {\n /** Project for Import only (the Endpoints list itself is account-wide). Omitted: the provider's. */\n project?: string | null;\n /** A row was clicked, or an import completed. Navigation is the host's. */\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n /** When set, each row is a real `<a href>`; a click still calls `onOpen`. */\n getHref?: (id: string) => string;\n /** An Endpoint was created from the list's New button; receives the SERVER's id. */\n onCreated?: (id: string) => void;\n slots?: CallableListProps[\"slots\"];\n}\n\n/**\n * The account's Endpoints: rows from `GET /endpoints`, archived ones behind a Show-archived toggle,\n * an \"Unfinished\" tag on drafts (no target yet), a New button that creates an Endpoint\n * (create-first: the row is POSTed before any editor exists), and Import. Never navigates — the\n * host wires `onOpen` / `getHref` / `onCreated`.\n */\nexport function EndpointList(props: EndpointListProps) {\n const query = useEndpointsQuery();\n const project = useEditorProject(props.project);\n const [creatingId, setCreatingId] = useState<string | null>(null);\n\n return (\n <CallableKindList<EndpointSummary>\n kind=\"endpoint\"\n rows={query.data}\n loading={query.isLoading}\n error={query.error ? String(query.error) : null}\n project={project}\n toRow={(row) => {\n return {\n // The draft tag sits INSIDE the title, after the name: ui `ListItem` puts `badges` in\n // a trailing `margin-left: auto` slot, which would strand it at the row's far edge.\n title: (\n <>\n <strong>{row.displayName || row.key}</strong>\n {isEndpointDraft(row) ? (\n <span\n className=\"tag warn\"\n data-testid=\"endpoint-draft\"\n title=\"No target configured yet — it cannot be invoked until one is set.\"\n >\n Unfinished\n </span>\n ) : null}\n </>\n ),\n description: row.description,\n };\n }}\n onOpen={props.onOpen}\n getHref={props.getHref}\n onCreate={() => setCreatingId(newCallableId(\"endpoint\"))}\n slots={props.slots}\n >\n {creatingId !== null && (\n <EndpointIdentityModal\n newId={creatingId}\n takenKeys={(query.data ?? []).map((row) => row.key)}\n onClose={() => setCreatingId(null)}\n onCreated={(id) => {\n setCreatingId(null);\n props.onCreated?.(id);\n }}\n />\n )}\n </CallableKindList>\n );\n}\n","import type { CallableListProps } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { newCallableId } from \"../lib/callable-descriptors.ts\";\nimport { blankDefinition } from \"../lib/workflow-blank.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type WorkflowSummary,\n useCreateWorkflowMutation,\n useWorkflowsQuery,\n} from \"../repos/workflows.ts\";\nimport { CallableKindList } from \"./CallableKindList.tsx\";\n\nexport interface WorkflowListProps {\n /** The project whose Workflows are listed and created. Omitted: the provider's project. */\n project?: string | null;\n /** A row was clicked, or an import completed. Navigation is the host's. */\n onOpen?: (id: string, event?: React.MouseEvent<Element>) => void;\n /** When set, each row is a real `<a href>`; a click still calls `onOpen`. */\n getHref?: (id: string) => string;\n /** A blank Workflow was created from the list's New button; receives the SERVER's id. */\n onCreated?: (id: string) => void;\n slots?: CallableListProps[\"slots\"];\n}\n\n/**\n * A project's Workflows: rows from `GET /workflows`, archived ones behind a Show-archived toggle,\n * a New button that creates a blank Workflow (the row is POSTed before any editor exists), and\n * Import. With no project there is nothing to list and New refuses. Never navigates — the host\n * wires `onOpen` / `getHref` / `onCreated`.\n */\nexport function WorkflowList(props: WorkflowListProps) {\n const project = useEditorProject(props.project);\n const query = useWorkflowsQuery(project ?? undefined, project != null);\n const createMut = useCreateWorkflowMutation(project ?? undefined);\n const [createError, setCreateError] = useState<string | null>(null);\n\n return (\n <CallableKindList<WorkflowSummary>\n kind=\"workflow\"\n rows={query.data}\n loading={query.isLoading}\n error={createError ?? (query.error ? String(query.error) : null)}\n project={project}\n toRow={(row) => ({\n title: row.displayName || row.name,\n description: row.description,\n badges: (\n <>\n {row.tags.length > 0 && (\n <span className=\"wf-row-tags\">\n {row.tags.map((t) => (\n <span key={t} className=\"tag\">\n {t}\n </span>\n ))}\n </span>\n )}\n {row.status !== \"archived\" && (\n <span className={`badge wf-status ${row.status}`}>{row.status}</span>\n )}\n </>\n ),\n trailing: (\n <span className=\"wf-col wf-col-stats muted small\">\n {row.runCount} {row.runCount === 1 ? \"run\" : \"runs\"}\n </span>\n ),\n })}\n onOpen={props.onOpen}\n getHref={props.getHref}\n onCreate={() => {\n setCreateError(null);\n createMut.mutate(blankDefinition(newCallableId(\"workflow\")), {\n onSuccess: (res) => props.onCreated?.(res.workflow.id),\n onError: (e) => setCreateError(e instanceof Error ? e.message : String(e)),\n });\n }}\n creating={createMut.isPending}\n slots={props.slots}\n />\n );\n}\n","import { ReliabilityList, type ReliabilityListProps } from \"@w6w/ui\";\nimport type { MouseEvent, ReactElement } from \"react\";\nimport { useEmbedProject } from \"../project-context.ts\";\nimport { useProjectReliabilityQuery } from \"../repos/reliability.ts\";\n\nexport interface ReliabilityBoardProps {\n /** Omitted ⇒ the provider's project; `null`/`\"\"` ⇒ no request and a \"select a project\" note. */\n project?: string | null;\n variant?: \"full\" | \"compact\";\n /** DISPLAY cap passed to the list; never sent to the server (it would falsify \"x of y\"). */\n limit?: number;\n /** Window size in days: sent with both requests and labels the table column (default 30). */\n days?: number;\n showChart?: boolean;\n getHref?: (appId: string) => string;\n onOpen?: (appId: string, event: MouseEvent<Element>) => void;\n showAllHref?: string;\n onShowAll?: (event: MouseEvent<Element>) => void;\n slots?: ReliabilityListProps[\"slots\"];\n}\n\n/**\n * One project's service reliability: loads members then status in serial batches of at most ten\n * through `@w6w/embed/repos`, and draws it with `@w6w/ui`'s `ReliabilityList`. Icons come from the\n * rows themselves, so no app-catalog request is made.\n */\nexport function ReliabilityBoard({\n project,\n variant = \"full\",\n limit,\n days = 30,\n showChart,\n getHref,\n onOpen,\n showAllHref,\n onShowAll,\n slots,\n}: ReliabilityBoardProps): ReactElement {\n const provided = useEmbedProject().project;\n const resolved = project === undefined ? provided : project;\n const effective = resolved ? resolved : null;\n const query = useProjectReliabilityQuery(effective ?? undefined, days);\n\n let empty = slots?.empty;\n if (!effective) {\n empty = <p className=\"w6w-muted\">Select a project to see its reliability.</p>;\n } else if (query.isLoading) {\n empty = <p className=\"w6w-muted\">Loading…</p>;\n } else if (query.error) {\n empty = <div className=\"error\">{query.error.message}</div>;\n }\n\n return (\n <div className=\"w6w-embed-root\">\n <ReliabilityList\n services={effective ? (query.data?.services ?? []) : []}\n window={effective ? query.data?.window : undefined}\n days={days}\n compact={variant === \"compact\"}\n showChart={showChart}\n limit={limit}\n getHref={getHref}\n onOpen={onOpen}\n showAllHref={showAllHref}\n onShowAll={onShowAll}\n slots={{ ...slots, empty }}\n />\n </div>\n );\n}\n","import { DataTable, type DataTableColumn, DeleteButton, EditButton, EmptyState } from \"@w6w/ui\";\n/**\n * `<DocumentList>` — a project's documents (key -> free-form content), with in-place create, edit\n * and delete. No repository sync and no \"synced from\" markers: a host that wants them adds them\n * through the three row slots (`lead`, `sharedActions`, `footer`).\n */\nimport type { MouseEvent, ReactNode } from \"react\";\nimport { useState } from \"react\";\nimport { CallFromCodeButton } from \"../chrome/CallFromCodeButton.tsx\";\nimport { ConfirmModal } from \"../chrome/ConfirmModal.tsx\";\nimport { DocumentFormModal } from \"../forms/DocumentFormModal.tsx\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type DocWithProvenance,\n useDeleteDocumentMutation,\n useDocumentsQuery,\n} from \"../repos/documents.ts\";\n\n/** A per-row slot: called once per rendered row with that row's document. */\nexport type DocumentRowSlot = (doc: DocWithProvenance) => ReactNode;\n\nexport interface DocumentListRowSlots {\n /** Before the row's main text, inside the open control (e.g. a source icon). */\n lead?: DocumentRowSlot;\n /** The action group of a SHARED row (a shared row has no Edit or Delete). */\n sharedActions?: DocumentRowSlot;\n /** A full-width line under the row (e.g. a per-row error). */\n footer?: DocumentRowSlot;\n}\n\nexport interface DocumentListSlots {\n /** Replaces the section heading and its description (the Add button stays). `null`: none. */\n header?: ReactNode;\n /** Replaces the empty-state copy. `null`: nothing. */\n empty?: ReactNode;\n}\n\nexport interface DocumentListProps {\n /** Omitted: the provider's project. `null` or `\"\"`: none; nothing is read and writes refuse. */\n project?: string | null;\n /** The host decides what opening a row means; with `getHref` it may `preventDefault`. */\n onOpen?: (id: string, event: MouseEvent<Element>) => void;\n /** Given, a row's main area is a real `<a href>`; its click still calls `onOpen`. */\n getHref?: (id: string) => string;\n slots?: DocumentListSlots;\n rowSlots?: DocumentListRowSlots;\n}\n\n/** One-line preview of a document's content, safe against long bodies. */\nfunction preview(content: string): string {\n const s = content.replace(/\\s+/g, \" \").trim();\n return s.length > 80 ? `${s.slice(0, 80)}…` : s;\n}\n\nexport function DocumentList({ project, onOpen, getHref, slots, rowSlots }: DocumentListProps) {\n const p = useEditorProject(project);\n const docsQuery = useDocumentsQuery(p ?? undefined, p != null);\n const deleteMut = useDeleteDocumentMutation();\n const [modal, setModal] = useState<\n { mode: \"create\" } | { mode: \"edit\"; d: DocWithProvenance } | null\n >(null);\n const [pending, setPending] = useState<DocWithProvenance | null>(null);\n\n const header =\n slots?.header === undefined ? (\n <div>\n <h3>Documents</h3>\n <p className=\"muted small\">Each document is free-form content stored verbatim.</p>\n </div>\n ) : (\n slots.header\n );\n const empty =\n slots?.empty === undefined ? (\n <EmptyState testId=\"document-list-empty\">No documents yet.</EmptyState>\n ) : (\n slots.empty\n );\n\n const columns: DataTableColumn<DocWithProvenance>[] = [\n {\n key: \"key\",\n header: \"Document\",\n render: (d) => {\n const lead = rowSlots?.lead?.(d);\n return (\n <span style={{ display: \"flex\", alignItems: \"center\" }}>\n {lead}\n <span\n className=\"list-main\"\n style={{ marginLeft: lead != null ? \"var(--w6w-sp-2)\" : 0 }}\n >\n <strong className=\"list-name\" title={d.key}>\n {d.key}\n </strong>{\" \"}\n <span className=\"tag\">{d.format}</span>\n <div className=\"muted small list-preview\">\n <code>{preview(d.content)}</code>\n {d.description && <> · {d.description}</>}\n </div>\n </span>\n </span>\n );\n },\n },\n {\n key: \"actions\",\n header: \"\",\n align: \"right\",\n link: false,\n render: (d) => {\n const footer = rowSlots?.footer?.(d);\n return (\n // Clicks here must not reach the row's onOpen.\n // biome-ignore lint/a11y/useKeyWithClickEvents: propagation guard only; the buttons inside are the controls.\n <div onClick={(e) => e.stopPropagation()}>\n <div style={{ display: \"flex\", gap: \"var(--w6w-sp-1-5)\", justifyContent: \"flex-end\" }}>\n <CallFromCodeButton resource={{ kind: \"document\", key: d.key }} />\n {!d.shared ? (\n <>\n <EditButton\n label=\"Edit\"\n onClick={() => setModal({ mode: \"edit\", d })}\n data-testid={`document-edit-${d.id}`}\n />\n <DeleteButton\n label=\"Delete\"\n onClick={() => setPending(d)}\n disabled={deleteMut.isPending}\n data-testid={`document-delete-${d.id}`}\n />\n </>\n ) : (\n rowSlots?.sharedActions?.(d)\n )}\n </div>\n {footer != null && <div className=\"w6w-doc-footer\">{footer}</div>}\n </div>\n );\n },\n },\n ];\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n <div className=\"section-head\">\n {header}\n <button\n type=\"button\"\n className=\"btn\"\n disabled={p == null}\n onClick={() => setModal({ mode: \"create\" })}\n >\n + Add document\n </button>\n </div>\n\n <div>\n {docsQuery.isLoading && <p className=\"muted\">Loading…</p>}\n {docsQuery.data?.length === 0 && empty}\n {docsQuery.data != null && docsQuery.data.length > 0 && (\n <DataTable\n columns={columns}\n rows={docsQuery.data}\n rowKey={(d) => d.id}\n getRowHref={getHref ? (d) => getHref(d.id) : undefined}\n onRowClick={onOpen ? (d, e) => onOpen(d.id, e) : undefined}\n />\n )}\n </div>\n </section>\n\n {modal && (\n <DocumentFormModal\n initial={modal.mode === \"edit\" ? modal.d : undefined}\n project={p}\n onClose={() => setModal(null)}\n onSaved={() => setModal(null)}\n />\n )}\n\n {pending && (\n <ConfirmModal\n title=\"Delete document\"\n message={`Delete the document \"${pending.key}\"? This cannot be undone.`}\n confirmLabel=\"Delete\"\n onConfirm={() => {\n if (p != null) deleteMut.mutate({ id: pending.id, project: p });\n setPending(null);\n }}\n onClose={() => setPending(null)}\n />\n )}\n </div>\n );\n}\n","/**\n * The dashboard's recent-activity rows, decided — which variant a ledger row\n * renders as, what its title says, and where that title links (T1.2.1).\n *\n * **Data only, never JSX.** `components/RecentActivityTile.tsx` is `.tsx` and\n * cannot be loaded by `node --test` (`package.json`'s `test:unit` glob loads\n * only `.ts` under `src/{lib,api,repos}/__tests__/`), exactly the constraint\n * `src/lib/resource-descriptors.ts` documents for itself for the same reason.\n * So the label table, the kind→variant `Record`, the two name maps and the two\n * formatters live here and are driven for real by\n * `__tests__/recent-activity.test.ts`; only the `<ListItem>` and the `<Link>`\n * stay in the component.\n *\n * The one non-local import is `import type`, erased by Node's type stripping —\n * so this module still loads with no `repos/` (and no React) on its runtime\n * import graph, while the entry type stays the WIRE shape rather than a second,\n * drift-prone copy of it.\n */\nimport type { DashboardStats } from \"../repos/dashboard.ts\";\n\n/** One row of the dashboard's \"Recent activity\" list — the pinned wire shape\n * (`DashboardStats[\"recent\"][number]`, widened by T1.1.2). */\nexport type RecentActivityEntry = DashboardStats[\"recent\"][number];\n\n/** Human labels for the ledger `kind` domain (mirrors the server's `run_log.kind`). */\nexport const KIND_LABELS: Record<string, string> = {\n workflow: \"Workflow run\",\n workflow_step: \"Workflow step\",\n connection_test: \"Connection test\",\n node_debug: \"Node debug\",\n // The synchronous arms, which joined the ledger with `0065_invocations`.\n // Without these three the rollup would render raw column values.\n function: \"Function call\",\n endpoint: \"Endpoint call\",\n action: \"App action\",\n};\n\n/**\n * The seven ledger kinds this module KNOWS — the arms the two `Record`s below\n * name explicitly, so a kind added to `run_log.kind` is a compile error here\n * rather than a row silently rendering as another kind (the same reasoning\n * `RESOURCE_DESCRIPTORS` gives for its total `Record`).\n */\nexport type ActivityKind =\n | \"workflow\"\n | \"workflow_step\"\n | \"connection_test\"\n | \"node_debug\"\n | \"function\"\n | \"endpoint\"\n | \"action\";\n\n/**\n * The label for a ledger kind. An unrecognised kind falls back to the raw value:\n * `kind` is a wire field and a client can be older than the server that answered\n * it — a raw `\"schedule\"` reads better than a blank row.\n */\nexport function kindLabel(kind: string): string {\n return KIND_LABELS[kind] ?? kind;\n}\n\n/** Which tile a row renders as: today's row, or one of the three named ones. */\nexport type TileVariant = \"base\" | \"function\" | \"workflow\" | \"workflow_step\";\n\n/**\n * The kind→variant table. Only the kinds that HAVE a name (or, for a step, an\n * id) to link to move off the base tile — `workflow_step` joined them in R-1,\n * titled `{workflow name} - {step id}` (R-2); endpoint/action rows keep\n * today's look (DC-6). Every other arm is spelled out rather than left to a\n * default, so dropping or adding a kind is a visible edit here.\n */\nexport const TILE_VARIANT: Record<ActivityKind, TileVariant> = {\n workflow: \"workflow\",\n workflow_step: \"workflow_step\",\n connection_test: \"base\",\n node_debug: \"base\",\n function: \"function\",\n endpoint: \"base\",\n action: \"base\",\n};\n\nfunction isActivityKind(kind: string): kind is ActivityKind {\n return Object.hasOwn(TILE_VARIANT, kind);\n}\n\n/**\n * The tile a row renders as — the ONE dispatcher `RecentActivityTile` reads.\n * An unknown kind is the base tile, never a missing render: the same\n * older-client-than-server case {@link kindLabel} answers.\n */\nexport function tileVariantFor(kind: string): TileVariant {\n return isActivityKind(kind) ? TILE_VARIANT[kind] : \"base\";\n}\n\n/**\n * The list rows the two name maps are built from, structurally: the SDK's\n * `FunctionSummary`/`WorkflowSummary` satisfy these without a cast, and a\n * fixture in the unit test needs no SDK round trip.\n */\nexport interface FunctionNameRow {\n id: string;\n /** The callable name; `null` on a `WorkflowSummary`, never on a Function. */\n key?: string | null;\n displayName?: string | null;\n}\n\nexport interface WorkflowNameRow {\n id: string;\n /** The stable slug; every Workflow has one. */\n name?: string | null;\n displayName?: string | null;\n}\n\n/** `id → display label` for the two kinds whose rows carry a name. */\nexport interface ActivityNameMaps {\n functions: ReadonlyMap<string, string>;\n workflows: ReadonlyMap<string, string>;\n}\n\n/**\n * Build the two `id → name` maps a tile resolves its title through.\n *\n * Both lists are the ACCOUNT-scoped reads `useFunctionsQuery()`/\n * `useWorkflowsQuery()` already make (DC-1) — the dashboard's own\n * `recentForAccount` is account-wide, so a project-narrowed list here would\n * label most rows with a raw `fn_…`/`wf_…` id. A missing list (its query still\n * loading, or failed) is an empty map: the tile then falls back to today's\n * title rather than blocking the row.\n *\n * The label is `displayName || key` for a Function and `displayName || name`\n * for a Workflow (the server's own fallback order). A row carrying neither is\n * left OUT of the map rather than mapped to `\"\"`: \"in the map\" then means\n * exactly \"there is a name to link to\", which is the rule\n * {@link resolveTileTitle} reads.\n */\nexport function buildNameMaps(\n functions?: readonly FunctionNameRow[],\n workflows?: readonly WorkflowNameRow[],\n): ActivityNameMaps {\n const functionNames = new Map<string, string>();\n for (const row of functions ?? []) {\n const label = row.displayName || row.key;\n if (label) functionNames.set(row.id, label);\n }\n const workflowNames = new Map<string, string>();\n for (const row of workflows ?? []) {\n const label = row.displayName || row.name;\n if (label) workflowNames.set(row.id, label);\n }\n return { functions: functionNames, workflows: workflowNames };\n}\n\n/** The resource a tile title links to — a studio route kind plus its id. */\nexport interface ActivityTileTarget {\n kind: \"function\" | \"workflow\";\n id: string;\n}\n\nexport interface ResolvedTileTitle {\n /** What the title reads: the resolved name, else today's `summary`/kind label. */\n text: string;\n /** Where it links, or `null` for a plain, unlinked title. */\n target: ActivityTileTarget | null;\n}\n\n/**\n * The title of one row — the name-as-link rule.\n *\n * A `function`/`workflow` row links ONLY when its id resolves to a name in the\n * maps above. Every other case — a base-variant kind, a `null` id, or an id the\n * list did not carry — is today's plain title (`summary ?? kindLabel(kind)`)\n * with no target, so a failed or still-loading name lookup degrades to the id\n * the row already shows instead of a dead link.\n *\n * A `workflow_step` row (R-1) is the same rule plus the step's own id: a\n * resolved workflow name makes the link, exactly as it does on a `workflow`\n * row, and the title reads `{workflow name} - {step id}` — a spaced ASCII\n * hyphen-minus, R-2. The step id IS the step's name — `core/rfcs/workflow.md`'s\n * `id` is its machine name and the editor's \"Rename step\" rewrites exactly that\n * — so no definition is fetched and no `notes` is read. When the workflow does\n * NOT resolve the left side is the workflow id itself, then the row's `summary`,\n * then `\"Unknown workflow\"` — never the kind label, since a title reading\n * \"Workflow step\" is exactly what R-1 rejected — and the target is `null`: a\n * link only when the name resolved. An absent `stepId` leaves the title as just\n * that left side.\n */\nexport function resolveTileTitle(\n entry: RecentActivityEntry,\n names: ActivityNameMaps,\n): ResolvedTileTitle {\n const fallback = entry.summary ?? kindLabel(entry.kind);\n const variant = tileVariantFor(entry.kind);\n if (variant === \"function\" && entry.functionId !== null) {\n const label = names.functions.get(entry.functionId);\n if (label !== undefined)\n return { text: label, target: { kind: \"function\", id: entry.functionId } };\n }\n if (variant === \"workflow\" && entry.workflowId !== null) {\n const label = names.workflows.get(entry.workflowId);\n if (label !== undefined)\n return { text: label, target: { kind: \"workflow\", id: entry.workflowId } };\n }\n if (variant === \"workflow_step\") {\n const workflowId = entry.workflowId;\n const label = workflowId !== null ? names.workflows.get(workflowId) : undefined;\n const left = label ?? workflowId ?? entry.summary ?? \"Unknown workflow\";\n const links = label !== undefined && workflowId !== null;\n return {\n text: entry.stepId ? `${left} - ${entry.stepId}` : left,\n target: links ? { kind: \"workflow\", id: workflowId } : null,\n };\n }\n return { text: fallback, target: null };\n}\n\nconst pad2 = (n: number) => String(n).padStart(2, \"0\");\n\n/**\n * A row's timestamp in LOCAL time as `YYYY-MM-DD HH:mm:ss`, 24-hour and\n * zero-padded — the exact, sortable, unambiguous stamp a ledger row wants.\n *\n * `toLocaleString` is deliberately NOT reused (what this replaces): its output\n * is locale-dependent (\"Jan 5, 7:08 AM\", no seconds) and so unreadable as a\n * timestamp. The `get*` accessors, never the `getUTC*` ones, are what make this\n * the viewer's own wall clock. An unparseable value is returned unchanged —\n * better the raw string than `NaN-NaN-NaN`.\n */\nexport function formatTimestamp(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const date = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;\n return `${date} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;\n}\n\n/**\n * A duration in milliseconds, or `null` when there is nothing to show.\n *\n * Three magnitudes, three units, so the number stays readable at every scale:\n * sub-second in ms, sub-minute in seconds to one decimal, and minutes+seconds\n * above that. `null`/`undefined`/negative/non-finite are all \"unknown\" — the\n * ledger writes none of them on purpose, and a tile that renders `NaN s` is\n * worse than one that renders nothing (DC-2: historical rows simply omit it).\n */\nexport function formatDuration(ms: number | null | undefined): string | null {\n if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return null;\n if (ms < 1000) return `${Math.round(ms)} ms`;\n if (ms < 60_000) return `${(Math.floor(ms / 100) / 10).toFixed(1)} s`;\n return `${Math.floor(ms / 60_000)}m ${Math.floor((ms % 60_000) / 1000)}s`;\n}\n","import { ListItem } from \"@w6w/ui\";\nimport type { MouseEvent, ReactElement, ReactNode } from \"react\";\nimport { useMemo } from \"react\";\nimport {\n type ActivityNameMaps,\n type ActivityTileTarget,\n type RecentActivityEntry,\n type TileVariant,\n buildNameMaps,\n formatDuration,\n formatTimestamp,\n kindLabel,\n resolveTileTitle,\n tileVariantFor,\n} from \"../lib/recent-activity.ts\";\nimport { type DashboardStats, useDashboardStatsQuery } from \"../repos/dashboard.ts\";\nimport { useFunctionsQuery } from \"../repos/functions.ts\";\nimport { useWorkflowsQuery } from \"../repos/workflows.ts\";\n\nexport type { ActivityTileTarget };\n\nexport interface ActivitySummaryProps {\n /** Real `href` for a resolved name; given ⇒ the title is an `<a>` (middle-click, new tab). */\n getHref?: (target: ActivityTileTarget) => string;\n /** A click on a resolved name. Never `preventDefault`ed here: the host decides. */\n onOpen?: (target: ActivityTileTarget, event: MouseEvent<Element>) => void;\n slots?: {\n /** Above everything (after the error banner). */\n header?: ReactNode;\n /** A row of host actions under `header`. */\n actions?: ReactNode;\n /** Replaces the \"No runs yet…\" copy. */\n empty?: ReactNode;\n /** Between the two headline rows and \"Activity over time\" (Studio puts its board here). */\n betweenHeadlineAndSeries?: ReactNode;\n };\n}\n\n/** Start of the current local day, as an ISO string — the \"today\" window edge. */\nfunction startOfTodayIso(): string {\n const d = new Date();\n d.setHours(0, 0, 0, 0);\n return d.toISOString();\n}\n\n/**\n * Render a series bucket start as a label. FU-6: a `week` bucket is the Monday that\n * `date_trunc('week', …)` truncates to, so it must read as a week range (\"Week of Jul 21\"),\n * not a bare date, or a weekly chart's axis is misleading.\n */\nfunction formatBucketLabel(iso: string, bucket: \"day\" | \"week\"): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const day = d.toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" });\n return bucket === \"week\" ? `Week of ${day}` : day;\n}\n\n/** ✓ / ✗ / – status glyph for an outcome that may be unknown (`ok === null`). */\nfunction OutcomeMark({ ok }: { ok: boolean | null }) {\n if (ok === null) return <span className=\"muted\">–</span>;\n return <span className={ok ? \"ok\" : \"error\"}>{ok ? \"✓\" : \"✗\"}</span>;\n}\n\n/** A single headline stat card: a big count over a muted label. */\nfunction StatCard({ label, value }: { label: string; value: number }) {\n return (\n <div className=\"w6w-activity-card w6w-activity-stat\">\n <div className=\"w6w-activity-stat-value\">{value}</div>\n <div className=\"muted small\">{label}</div>\n </div>\n );\n}\n\n/** A titled row of headline stat cards for one time window. */\nfunction HeadlineRow({\n title,\n headline,\n loading,\n}: {\n title: string;\n headline: DashboardStats[\"headline\"] | undefined;\n loading: boolean;\n}) {\n const h = headline ?? { workflowRuns: 0, succeeded: 0, failed: 0 };\n return (\n <section className=\"w6w-activity-section\">\n <h3>{title}</h3>\n {loading ? (\n <p className=\"muted\">Loading…</p>\n ) : (\n <div className=\"w6w-activity-stats\">\n <StatCard label=\"Workflow runs\" value={h.workflowRuns} />\n <StatCard label=\"Succeeded\" value={h.succeeded} />\n <StatCard label=\"Failed\" value={h.failed} />\n </div>\n )}\n </section>\n );\n}\n\ntype LinkProps = Pick<ActivitySummaryProps, \"getHref\" | \"onOpen\">;\n\n/**\n * The row's title: the resolved resource NAME as a link — `<a href>` when `getHref` is given,\n * else a `<button>` when only `onOpen` is — or plain text when no name resolved or the host gave\n * neither. It sits INSIDE `ListItem`'s `title` slot, never `ListItem`'s own `href`/`onClick`.\n */\nfunction ActivityTitle({\n entry,\n names,\n getHref,\n onOpen,\n}: LinkProps & { entry: RecentActivityEntry; names: ActivityNameMaps }) {\n const { text, target } = resolveTileTitle(entry, names);\n if (target === null) return <>{text}</>;\n const click = onOpen ? (event: MouseEvent<Element>) => onOpen(target, event) : undefined;\n if (getHref) {\n return (\n <a href={getHref(target)} onClick={click}>\n {text}\n </a>\n );\n }\n if (click) {\n return (\n <button type=\"button\" className=\"w6w-activity-link\" onClick={click}>\n {text}\n </button>\n );\n }\n return <>{text}</>;\n}\n\n/** The base tile: status glyph, title over `\"<kind> · <local timestamp>\"`, duration on the right. */\nfunction BaseActivityTile({ entry, title }: { entry: RecentActivityEntry; title?: ReactNode }) {\n const duration = formatDuration(entry.durationMs);\n return (\n <ListItem\n icon={<OutcomeMark ok={entry.ok} />}\n title={title ?? entry.summary ?? kindLabel(entry.kind)}\n subtitle={`${kindLabel(entry.kind)} · ${formatTimestamp(entry.occurredAt)}`}\n trailing={duration === null ? undefined : <span className=\"muted small\">{duration}</span>}\n />\n );\n}\n\ntype TileProps = LinkProps & { entry: RecentActivityEntry; names: ActivityNameMaps };\n\n/** The `function`, `workflow` and `workflow_step` tiles differ only in which name `resolveTileTitle` reads. */\nfunction NamedActivityTile(props: TileProps) {\n return <BaseActivityTile entry={props.entry} title={<ActivityTitle {...props} />} />;\n}\n\n/** The one dispatcher: the variant table's arm for this row's kind. */\nconst TILES: Record<TileVariant, (props: TileProps) => ReactElement> = {\n base: (p) => <BaseActivityTile entry={p.entry} />,\n function: NamedActivityTile,\n workflow: NamedActivityTile,\n workflow_step: NamedActivityTile,\n};\n\nfunction RecentActivityTile(props: TileProps) {\n const Tile = TILES[tileVariantFor(props.entry.kind)];\n return <Tile {...props} />;\n}\n\n/**\n * The account's run statistics and recent activity: \"Today\" and \"Last 7 days\" headline cards,\n * \"Activity over time\" and \"Recent activity\". Account-scoped (no `project`); it never navigates —\n * opening a resolved name is the host's `onOpen` / `getHref`.\n *\n * Two `/dashboard/stats` requests, deliberately: `today` is `{ from: <local start of day>,\n * bucket: \"day\" }` and `week` is `{ bucket: \"week\" }`. The server's only buckets are `day|week`,\n * cut in the database's timezone, so no single request can cut at the viewer's local midnight.\n */\nexport function ActivitySummary({ getHref, onOpen, slots }: ActivitySummaryProps): ReactElement {\n const todayQuery = useDashboardStatsQuery(\"today\", { from: startOfTodayIso(), bucket: \"day\" });\n const weekQuery = useDashboardStatsQuery(\"week\", { bucket: \"week\" });\n\n // A row's title is the Function's/Workflow's own display name, resolved against these two\n // account-scoped lists. Both are deliberately UNSCOPED: the ledger is account-wide, so a\n // project-narrowed list would answer \"no name\" for every row outside the project. Neither\n // query's error is surfaced: a failed lookup just leaves the plain title.\n const functionsQuery = useFunctionsQuery();\n const workflowsQuery = useWorkflowsQuery();\n const names = useMemo(\n () => buildNameMaps(functionsQuery.data, workflowsQuery.data),\n [functionsQuery.data, workflowsQuery.data],\n );\n\n const error = todayQuery.error ?? weekQuery.error;\n const errorMessage = error ? (error as Error).message : null;\n\n const recent = weekQuery.data?.recent ?? [];\n const series = weekQuery.data?.series ?? [];\n const weekBucket = weekQuery.data?.range.bucket ?? \"week\";\n\n const nothingYet =\n !weekQuery.isLoading &&\n recent.length === 0 &&\n (weekQuery.data?.headline.workflowRuns ?? 0) === 0;\n\n return (\n <div className=\"w6w-embed-root\">\n {errorMessage && <div className=\"error\">{errorMessage}</div>}\n {slots?.header}\n {slots?.actions}\n\n <HeadlineRow\n title=\"Today\"\n headline={todayQuery.data?.headline}\n loading={todayQuery.isLoading}\n />\n <HeadlineRow\n title=\"Last 7 days\"\n headline={weekQuery.data?.headline}\n loading={weekQuery.isLoading}\n />\n\n {slots?.betweenHeadlineAndSeries}\n\n <section className=\"w6w-activity-section\">\n <h3>Activity over time</h3>\n <div className=\"w6w-activity-card\">\n {weekQuery.isLoading ? (\n <p className=\"muted\">Loading…</p>\n ) : series.length === 0 ? (\n <p className=\"muted\">No activity in this window yet.</p>\n ) : (\n <ul className=\"list\">\n {series.map((s) => (\n <li key={`${s.bucket}-${s.kind}-${String(s.ok)}`}>\n <span className=\"list-main\">\n <strong>{formatBucketLabel(s.bucket, weekBucket)}</strong>{\" \"}\n <span className=\"muted small\">{kindLabel(s.kind)}</span>\n </span>{\" \"}\n <OutcomeMark ok={s.ok} /> <span className=\"muted small\">{s.count}</span>\n </li>\n ))}\n </ul>\n )}\n </div>\n </section>\n\n <section>\n <h3 className=\"w6w-activity-h3\">Recent activity</h3>\n <div className=\"w6w-activity-card\">\n {weekQuery.isLoading ? (\n <p className=\"muted\">Loading…</p>\n ) : nothingYet ? (\n (slots?.empty ?? (\n <p className=\"muted\">No runs yet — activity shows up here once your workflows run.</p>\n ))\n ) : recent.length === 0 ? (\n <p className=\"muted\">No recent activity in this window.</p>\n ) : (\n <div className=\"list\">\n {recent.map((r) => (\n <RecentActivityTile\n key={r.id}\n entry={r}\n names={names}\n getHref={getHref}\n onOpen={onOpen}\n />\n ))}\n </div>\n )}\n </div>\n </section>\n </div>\n );\n}\n","import { type ReactElement, useState } from \"react\";\nimport { HistoryView, type HistoryViewProps } from \"../chrome/HistoryView.tsx\";\nimport {\n EMPTY_HISTORY_FILTERS,\n type HistoryFilters,\n type HistoryScope,\n} from \"../lib/history-query.ts\";\nimport { useEmbedProject } from \"../project-context.ts\";\n\nexport interface RunHistoryProps extends Partial<HistoryViewProps> {}\n\n/** A scope names a project when it carries `project` rather than `callable`. */\nfunction isProjectScope(scope: HistoryScope | null): boolean {\n return scope !== null && \"project\" in scope;\n}\n\n/**\n * The execution history: stats, filters, the paged list and the selected run's detail. A thin\n * wrapper over `chrome/HistoryView` (which owns the queries). `scope` omitted ⇒ the provider's\n * project (disabled while it is unresolved); `filters` omitted ⇒ held here, given ⇒ controlled by\n * the host. Never navigates.\n */\nexport function RunHistory(props: RunHistoryProps): ReactElement {\n const provided = useEmbedProject().project;\n const [own, setOwn] = useState<HistoryFilters>(EMPTY_HISTORY_FILTERS);\n\n const scope: HistoryScope | null =\n props.scope !== undefined ? props.scope : provided ? { project: provided } : null;\n const controlled = props.filters !== undefined;\n const filters = props.filters ?? own;\n\n const onFiltersChange = (next: HistoryFilters) => {\n if (!controlled) setOwn(next);\n props.onFiltersChange?.(next);\n };\n\n return (\n <div className=\"w6w-embed-root\">\n <HistoryView\n scope={scope}\n showKind={props.showKind ?? isProjectScope(scope)}\n filters={filters}\n onFiltersChange={onFiltersChange}\n onOpenInEditor={props.onOpenInEditor}\n />\n </div>\n );\n}\n","import type { ReactElement, ReactNode } from \"react\";\nimport { RunHistory, type RunHistoryProps } from \"./RunHistory.tsx\";\n\nexport interface LogsProps extends RunHistoryProps {\n /** The heading above the view. Defaults to `\"Logs\"`; `null` renders none (the host titles its\n * own page). */\n title?: ReactNode | null;\n}\n\n/**\n * The project's Logs: the most recent executions of every workflow, function and endpoint in the\n * provider's project, newest first, and the selected one's detail (input, output, error, a\n * workflow run's steps) opened in place. `RunHistory` under a heading — Studio's History page\n * mounts the same body — so every `RunHistory` prop applies, and with none of them it is\n * project-wide with filters held here. Never navigates; `onOpenInEditor` is the host's way into a\n * workflow run's editor.\n */\nexport function Logs({ title = \"Logs\", ...rest }: LogsProps): ReactElement {\n return (\n <div className=\"w6w-embed-root w6w-embed-logs\">\n {title !== null && <h2>{title}</h2>}\n <RunHistory {...rest} />\n </div>\n );\n}\n\n/** {@link Logs} under the name a host routing table tends to use for a page. */\nexport const LogsView = Logs;\nexport type LogsViewProps = LogsProps;\n","/**\n * Pure projections behind `ServiceDetail.tsx`'s `VendorPanel` and its\n * `<HistoryTimeline>` lane — split out so `node --test` can gate them\n * directly, same reason `src/lib/alias-rail.ts` and `src/repos/\n * reliability-uptime.ts` give: nothing here does I/O and nothing reads the\n * clock itself, so every value a caller sees was decided by an argument, not\n * a hidden `Date.now()`.\n *\n * Holds NO reliability logic (STRATEGY §5.1): a vendor's `state` and a\n * timeline entry's `state` are rendered exactly as they arrived. What lives\n * here is projection and formatting only — reshaping `timeline` into\n * `HistoryTimeline`'s `VendorIncidentBar[]`, and turning an open incident's\n * two timestamps into a readable age — never a re-decided verdict.\n */\nimport type {\n ReliabilityComponentReport,\n ReliabilityTimelineEntry,\n ReliabilityVendorStatus,\n} from \"@w6w/sdk/console\";\nimport type { VendorIncidentBar } from \"@w6w/ui\";\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * `vendor.timeline` → `HistoryTimeline`'s `incidents` prop.\n *\n * `undefined` and `[]` are DIFFERENT FACTS carried through unchanged, never\n * collapsed into each other: `undefined` means \"this vendor publishes no\n * incident history at all\" (Stripe, and every app but Slack — the majority\n * case), `[]` means \"it does, and nothing is in it\" (a quiet Slack window).\n * Losing that distinction here would throw away Stripe's honest answer.\n */\nexport function projectVendorIncidents(\n vendor: ReliabilityVendorStatus | null,\n): VendorIncidentBar[] | undefined {\n if (vendor === null || vendor.timeline === null) return undefined;\n return vendor.timeline.map((entry) => ({\n id: entry.id,\n title: entry.title,\n state: entry.state,\n startedAt: entry.startedAt,\n updatedAt: entry.updatedAt,\n resolvedAt: entry.resolvedAt,\n components: entry.components,\n link: entry.link,\n }));\n}\n\n/**\n * An entry counts as an OPEN incident iff it has a `startedAt` and no\n * `resolvedAt`. An entry with neither is a feed-only update (a status-page\n * note with no span attached) — never an outage — so it is deliberately\n * excluded rather than defaulting to \"open\".\n */\nexport function isOpenIncident(entry: ReliabilityTimelineEntry): boolean {\n return entry.startedAt !== undefined && entry.resolvedAt === undefined;\n}\n\nfunction formatCalendarDay(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n // Pinned to UTC and a fixed locale — this runs inside a unit test as well\n // as the browser, and neither the CI container's timezone nor its ICU\n // locale should change what a fixture asserts.\n return d.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", timeZone: \"UTC\" });\n}\n\nfunction daysBetween(fromIso: string, toMs: number): number {\n const fromMs = new Date(fromIso).getTime();\n if (Number.isNaN(fromMs)) return 0;\n return Math.max(0, Math.floor((toMs - fromMs) / DAY_MS));\n}\n\n/**\n * The age/recovery copy for one OPEN incident — `null` for anything else\n * (not open, or missing `startedAt`), so this stays total rather than\n * throwing on a shape the caller failed to filter.\n *\n * A TOTAL FUNCTION OF `(entry, nowMs)` — `nowMs` is always the caller's\n * argument, never `Date.now()` read in here, which is what makes a\n * ten-day-old incident whose last note is three days old provably render\n * differently from one that started an hour ago: both facts (how long it has\n * been open, how stale the last note is) are day counts computed against the\n * SAME passed-in clock, not two independent reads of the real one.\n */\nexport function incidentAgeCopy(entry: ReliabilityTimelineEntry, nowMs: number): string | null {\n if (!isOpenIncident(entry) || entry.startedAt === undefined) return null;\n\n const ageDays = daysBetween(entry.startedAt, nowMs);\n const startLabel = formatCalendarDay(entry.startedAt);\n const openPart =\n ageDays === 0 ? `open since ${startLabel} (today)` : `open ${ageDays}d (since ${startLabel})`;\n\n const updateIso = entry.updatedAt ?? entry.startedAt;\n const updateDays = daysBetween(updateIso, nowMs);\n const updateLabel = formatCalendarDay(updateIso);\n const updatePart =\n updateDays === 0\n ? `last update ${updateLabel} (today)`\n : `last update ${updateLabel} (${updateDays}d ago)`;\n\n return `${openPart} · ${updatePart}`;\n}\n\n/**\n * `vendor.components` → a stable `[name, report][]` list, `null`-safe. A\n * `null` map (no public check ever reported a breakdown) and an empty one\n * both come back `[]`, so the caller's \"render nothing\" branch is a single\n * length check instead of a `null`-then-`Object.entries` chain repeated at\n * every call site.\n */\nexport function vendorComponentEntries(\n components: Record<string, ReliabilityComponentReport> | null,\n): Array<[string, ReliabilityComponentReport]> {\n return components ? Object.entries(components) : [];\n}\n","import { ApiError } from \"@w6w/sdk\";\nimport type { ApiCallRecord } from \"@w6w/sdk/console\";\nimport { HealthStatusPill, HistoryTimeline } from \"@w6w/ui\";\nimport type { HistoryWindow, UptimeDay } from \"@w6w/ui\";\nimport type { MouseEvent, ReactElement, ReactNode } from \"react\";\nimport { useEmbedProject } from \"../project-context.ts\";\nimport { useApiCallsQuery } from \"../repos/api-calls.ts\";\nimport type { ReliabilityErrorMix, ReliabilityService } from \"../repos/reliability.ts\";\nimport { useReliabilityQuery } from \"../repos/reliability.ts\";\nimport {\n incidentAgeCopy,\n isOpenIncident,\n projectVendorIncidents,\n vendorComponentEntries,\n} from \"./vendor-history.ts\";\n\n/**\n * One service, drilled into: health, error mix, the API's own status, daily history and the recent\n * calls. Moved from Studio's `/reliability/:appId` page (E-3).\n *\n * **One single-service read.** The row comes from `GET /reliability/services?apps=<appId>` —\n * `useReliabilityQuery(project, [appId], days)` — never the whole board. The one other read is the\n * call log (`GET /api-calls?appId=`), the actual drill from \"this service looks like that\" to\n * \"here are the requests behind it\".\n *\n * Holds NO reliability logic (STRATEGY §5.1): every state rendered arrived decided by the server.\n */\n\n/** The uptime strip's cells: the server's own array, in order — no sort, no reverse, no gap fill. */\nfunction uptimeDays(service: ReliabilityService): UptimeDay[] {\n return service.uptime.map((entry) => ({ day: entry.day, state: entry.state }));\n}\n\nconst ERROR_KINDS: Array<[keyof ReliabilityErrorMix, string]> = [\n [\"e4xx\", \"4xx\"],\n [\"e429\", \"429 rate-limited\"],\n [\"eAuth\", \"auth (401/403)\"],\n [\"e5xx\", \"5xx\"],\n];\n\nfunction formatDay(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n return d.toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" });\n}\n\nfunction formatStamp(iso: string | null | undefined): string {\n if (!iso) return \"—\";\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n return d.toLocaleString(undefined, {\n month: \"short\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n });\n}\n\n/** One labelled figure in the summary strip. */\nfunction Stat({ label, value, hint }: { label: string; value: string; hint?: string }) {\n return (\n <div className=\"w6w-rel-card\" style={{ flex: \"1 1 150px\", minWidth: 150 }}>\n <div style={{ fontSize: \"1.6rem\", fontWeight: \"var(--w6w-fw-semibold)\", lineHeight: 1.15 }}>\n {value}\n </div>\n <div className=\"muted small\">{label}</div>\n {hint && <div className=\"muted small\">{hint}</div>}\n </div>\n );\n}\n\n/**\n * The vendor's own verdict, expanded. Unlike the board's compact pill this has\n * room for the attribution — WHICH declared check decided it and when it last\n * actually ran — which is what turns \"degraded\" into something checkable.\n *\n * A SECOND, INDEPENDENT signal from the \"from your calls\" pill above it on\n * the page — never a restatement. Every sentence in here is deliberately\n * phrased as \"what {displayName} says about itself\", so the panel still\n * reads as a different question even once the generic noun \"vendor\" is gone\n * from its own copy (the section wrapper's `<h3>Vendor</h3>` stays generic —\n * that heading is a category label, not this panel's business).\n */\nfunction VendorPanel({\n vendor,\n displayName,\n}: {\n vendor: ReliabilityService[\"vendorStatus\"];\n displayName: string;\n}) {\n if (!vendor) {\n return (\n <div className=\"w6w-rel-card\">\n <h4 style={{ margin: \"0 0 var(--w6w-sp-1)\" }}>{displayName} status</h4>\n <p className=\"muted\">\n {displayName} publishes no public health check, so there is nothing to ask about it. That\n is a statement about {displayName}, not a gap in the data above.\n </p>\n </div>\n );\n }\n // `unknown` here means the probe ran and told us nothing usable — the status\n // page moved, went dark, or answered with something we don't recognise. That\n // is a gap in OUR reading of the API, not a finding about it, and the panel\n // has to say so plainly: the footer below would otherwise claim we \"read\" a\n // page we could not read.\n const unreadable = vendor.state === \"unknown\";\n\n const components = vendorComponentEntries(vendor.components);\n const openIncidents = (vendor.timeline ?? []).filter(isOpenIncident);\n const nowMs = Date.now();\n\n return (\n <div className=\"w6w-rel-card\">\n <h4 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n {displayName} status{\" \"}\n <HealthStatusPill state={vendor.state} label={unreadable ? \"Unavailable\" : undefined} />\n </h4>\n {unreadable && (\n <p style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n We could not get a status from this API, so we cannot say whether it is up. That is\n separate from your own calls above, which are measured here regardless.\n </p>\n )}\n {vendor.message && (\n <p\n className={unreadable ? \"muted small\" : undefined}\n style={{ margin: \"0 0 var(--w6w-sp-2)\" }}\n >\n {vendor.message}\n </p>\n )}\n <p className=\"muted small\" style={{ margin: 0 }}>\n {unreadable ? \"Tried to read\" : \"Read from\"} {displayName}'s own status page — what{\" \"}\n {displayName} says about itself, not what your calls did · last checked{\" \"}\n {formatStamp(vendor.checkedAt)}\n {vendor.attributedTo.length > 0 && (\n <>\n {\" \"}\n · decided by{\" \"}\n {vendor.attributedTo.map((k) => (\n <code key={k}>{k}</code>\n ))}\n </>\n )}\n </p>\n\n {components.length > 0 && (\n <div className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n {components.map(([name, comp]) => (\n <span key={name} className=\"w6w-rel-tag\">\n {name}: {comp.state}\n </span>\n ))}\n </div>\n )}\n\n {openIncidents.length > 0 && (\n <ul className=\"list\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n {openIncidents.map((entry) => (\n <li key={entry.id ?? entry.title}>\n <div className=\"list-main\">\n <strong>{entry.title}</strong> <HealthStatusPill state={entry.state} />\n <div className=\"muted small\">{incidentAgeCopy(entry, nowMs)}</div>\n </div>\n </li>\n ))}\n </ul>\n )}\n\n {vendor.statusPageUrl !== null && (\n <p className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n <a href={vendor.statusPageUrl} target=\"_blank\" rel=\"noopener noreferrer\">\n {displayName}'s status page ↗\n </a>\n </p>\n )}\n </div>\n );\n}\n\n/**\n * Calls per day, oldest first — the one time series this page has that the\n * board doesn't: `service.uptime` carries a real per-day call count, so this\n * is a genuine trend chart, not a single-number stat. Bar HEIGHT is volume;\n * bar COLOUR is that day's own state, the same `--w6w-health-*` tokens the\n * pill and strip read, so a volume spike and a bad day are one picture\n * instead of two separately-read facts.\n */\nfunction DailyVolumeChart({ service }: { service: ReliabilityService }) {\n // Same call as the board row (ReliabilityBoard.tsx): a zero-call window is\n // 30 identical `unknown` days, so a bar chart of them is 30 identical\n // slivers — the plain note matches the board's own wording instead.\n if (service.calls === 0) {\n return (\n <div className=\"w6w-rel-card\">\n <span className=\"w6w-rel-idle-note\">No calls in this window</span>\n </div>\n );\n }\n const days = service.uptime;\n const maxCalls = Math.max(1, ...days.map((d) => d.calls));\n return (\n <div className=\"w6w-rel-card\">\n <div\n className=\"rel-daily-chart\"\n role=\"img\"\n aria-label={`${service.displayName}, calls per day, oldest first`}\n >\n {days.map((d) => (\n <span\n key={d.day}\n className={`rel-daily-bar rel-daily-bar-${d.state}`}\n // A zero-call day still gets a hairline sliver — an invisible bar\n // reads as \"missing data\", not \"zero\", which is exactly the\n // distinction `unknown` vs `ok` exists to preserve.\n style={{ height: `${d.calls > 0 ? Math.max((d.calls / maxCalls) * 100, 4) : 2}%` }}\n title={`${formatDay(`${d.day}T00:00:00.000Z`)} — ${d.calls} calls, ${d.state}`}\n />\n ))}\n </div>\n <p className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n Calls per day, oldest first. Bar colour is that day's own state.\n </p>\n </div>\n );\n}\n\n/**\n * The window's per-day breakdown — our execution history and the vendor's own\n * incident history, on ONE shared axis (`HistoryTimeline`), plus the numbers\n * behind each execution cell below it. Two lanes plotted side by side without\n * a shared axis is the failure mode the human asked to avoid, so both are\n * always the SAME `window` — the board payload's own — never a second window\n * derived from the timeline's own extent.\n */\nfunction UptimeDetail({\n service,\n window: historyWindow,\n}: {\n service: ReliabilityService;\n window: HistoryWindow;\n}) {\n // Newest first here (the board's strip is oldest-first and stays that way):\n // a list is read top-down, and \"what happened lately\" is the question.\n const withTraffic = [...service.uptime].reverse().filter((d) => d.calls > 0);\n const vendor = service.vendorStatus;\n const incidents = projectVendorIncidents(vendor);\n const vendorEmptyLabel =\n incidents === undefined\n ? `${service.displayName} publishes no incident history.`\n : `No incidents from ${service.displayName} in this window.`;\n return (\n <div className=\"w6w-rel-card\">\n <HistoryTimeline\n window={historyWindow}\n days={uptimeDays(service)}\n incidents={incidents}\n vendorEmptyLabel={vendorEmptyLabel}\n ariaLabel={`${service.displayName}, ${service.uptime.length}-day status and ${service.displayName} incidents, oldest day first`}\n />\n <p className=\"muted small\" style={{ margin: \"var(--w6w-sp-2) 0 0\" }}>\n Oldest day leftmost. Days with no calls are <code>unknown</code> — never a quiet green.\n </p>\n {withTraffic.length > 0 && (\n <div className=\"list\" style={{ marginTop: \"var(--w6w-sp-3)\" }}>\n {withTraffic.slice(0, 14).map((d) => (\n <div key={d.day} className=\"rel-day-row\">\n <span style={{ minWidth: 96 }}>\n <strong>{formatDay(`${d.day}T00:00:00.000Z`)}</strong>\n </span>\n <HealthStatusPill state={d.state} />\n <span className=\"muted small\">{d.calls} calls</span>\n <span className=\"rel-errors\">\n {ERROR_KINDS.filter(([k]) => d.errors[k] > 0).map(([k, label]) => (\n <span className=\"w6w-rel-tag\" key={k}>\n {label} ×{d.errors[k]}\n </span>\n ))}\n </span>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n}\n\n/** The error mix, as bars rather than the board's bare count chips — same four kinds, same order. */\nfunction ErrorMixChart({ errors }: { errors: ReliabilityErrorMix }) {\n const total = ERROR_KINDS.reduce((sum, [k]) => sum + errors[k], 0);\n if (total === 0) {\n return (\n <div className=\"w6w-rel-card\">\n <p className=\"muted\" style={{ margin: 0 }}>\n No errors in this window.\n </p>\n </div>\n );\n }\n const max = Math.max(1, ...ERROR_KINDS.map(([k]) => errors[k]));\n return (\n <div className=\"w6w-rel-card rel-errormix-chart\">\n {ERROR_KINDS.map(([k, label]) => (\n <div key={k} className=\"rel-errormix-row\">\n <span className=\"muted small\">{label}</span>\n <span className=\"rel-errormix-track\">\n <span\n className=\"rel-errormix-bar\"\n style={{ width: `${Math.max((errors[k] / max) * 100, errors[k] > 0 ? 2 : 0)}%` }}\n />\n </span>\n <span className=\"rel-errormix-value small\">{errors[k]}</span>\n </div>\n ))}\n </div>\n );\n}\n\n/** The drill proper: the actual requests behind the numbers above. */\nfunction CallLog({ project, appId }: { project: string | undefined; appId: string }) {\n const query = useApiCallsQuery(project, appId, { limit: 50 });\n\n if (query.isLoading) return <p className=\"muted\">Loading calls…</p>;\n if (query.error) {\n const e = query.error;\n return <div className=\"error\">{e instanceof ApiError ? e.message : (e as Error).message}</div>;\n }\n const calls: ApiCallRecord[] = query.data ?? [];\n if (calls.length === 0) {\n return (\n <p className=\"muted\">\n No calls captured for this service. Calls appear here once a workflow, function or ad-hoc\n invoke reaches it.\n </p>\n );\n }\n return (\n <div className=\"rel-calls\">\n <div className=\"rel-call rel-call-head\">\n <span>When</span>\n <span>Action</span>\n <span>Method</span>\n <span>Status</span>\n <span>Took</span>\n </div>\n {calls.map((call, i) => (\n <div className=\"rel-call\" key={call.id ?? `${call.createdAt}-${i}`}>\n <span className=\"muted small\">{formatStamp(call.createdAt)}</span>\n <span>\n <code>{call.actionKey ?? \"—\"}</code>\n </span>\n <span className=\"muted small\">{call.method}</span>\n <span className={call.status >= 400 || call.status === 0 ? \"error\" : \"ok\"}>\n {/* 0 means the request never got a response at all; `error` says why. */}\n {call.status === 0 ? \"no response\" : call.status}\n </span>\n <span className=\"muted small\">\n {call.durationMs != null ? `${call.durationMs} ms` : \"—\"}\n </span>\n </div>\n ))}\n </div>\n );\n}\n\nexport interface ServiceDetailProps {\n /** The service's app id (e.g. `twilio`). */\n appId: string;\n /** Omitted ⇒ the provider's project; none anywhere ⇒ no request and a \"select a project\" note. */\n project?: string;\n /** Window size in days, sent with the status request (default 30). */\n days?: number;\n /** With `backHref` the not-found card's back link is a real `<a href>`. */\n backHref?: string;\n /** Called on a click of the back link; never cancelled by the component. Alone ⇒ a `<button>`. */\n onBack?: (event: MouseEvent<Element>) => void;\n /** `header`/`actions` sit above the detail; `empty` replaces the not-found copy. */\n slots?: { header?: ReactNode; actions?: ReactNode; empty?: ReactNode };\n}\n\n/** The back link under the not-found copy: an anchor, a button, or nothing. */\nfunction BackLink({\n backHref,\n onBack,\n}: {\n backHref?: string;\n onBack?: (event: MouseEvent<Element>) => void;\n}) {\n if (backHref !== undefined) {\n return (\n <p>\n <a href={backHref} onClick={onBack}>\n ← Back to all services\n </a>\n </p>\n );\n }\n if (onBack) {\n return (\n <p>\n <button type=\"button\" className=\"list-link\" onClick={onBack}>\n ← Back to all services\n </button>\n </p>\n );\n }\n return null;\n}\n\nexport function ServiceDetail({\n appId,\n project,\n days = 30,\n backHref,\n onBack,\n slots,\n}: ServiceDetailProps): ReactElement {\n const provided = useEmbedProject().project;\n const effective = (project === undefined ? provided : project) || undefined;\n const query = useReliabilityQuery(effective, [appId], days);\n\n const error = query.error;\n const errorMessage = error\n ? error instanceof ApiError\n ? error.message\n : (error as Error).message\n : null;\n const service = query.data?.services.find((s) => s.appId === appId);\n\n return (\n <div className=\"w6w-embed-root\">\n {slots?.header}\n {slots?.actions}\n\n {!effective && <p className=\"w6w-muted\">Select a project to see this service.</p>}\n {errorMessage && <div className=\"error\">{errorMessage}</div>}\n {effective && query.isLoading && <p className=\"muted\">Loading…</p>}\n\n {query.data && !service && (\n <div className=\"w6w-rel-card\">\n {slots?.empty ?? (\n <p className=\"muted\">\n <code>{appId}</code> is not used by this project's definitions and has no calls in the\n last {days} days.\n </p>\n )}\n <BackLink backHref={backHref} onBack={onBack} />\n </div>\n )}\n\n {service && (\n <>\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"var(--w6w-sp-3)\",\n marginBottom: \"var(--w6w-sp-3)\",\n }}\n >\n <HealthStatusPill state={service.state} />\n <span className=\"muted small\">from your calls</span>\n <code className=\"muted small\">{service.appId}</code>\n {service.ongoingOutageId && <span className=\"w6w-rel-tag\">outage still open</span>}\n </div>\n <div style={{ display: \"flex\", gap: \"var(--w6w-sp-3)\", flexWrap: \"wrap\" }}>\n <Stat label=\"Calls in window\" value={String(service.calls)} />\n <Stat\n label=\"p95 latency\"\n value={service.p95Ms === null ? \"—\" : `${service.p95Ms} ms`}\n hint={service.p95Ms === null ? \"no timed calls\" : undefined}\n />\n <Stat label=\"Last call\" value={formatStamp(service.lastCallAt)} />\n <Stat\n label=\"Errors\"\n value={String(ERROR_KINDS.reduce((sum, [k]) => sum + service.errors[k], 0))}\n hint={\n ERROR_KINDS.filter(([k]) => service.errors[k] > 0)\n .map(([k, label]) => `${label} ×${service.errors[k]}`)\n .join(\" · \") || \"none\"\n }\n />\n </div>\n </section>\n\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>Error mix</h3>\n <ErrorMixChart errors={service.errors} />\n </section>\n\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>API status</h3>\n <VendorPanel vendor={service.vendorStatus} displayName={service.displayName} />\n </section>\n\n <section style={{ marginBottom: \"var(--w6w-sp-5)\" }}>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n Last {query.data?.window.days ?? days} days{\" \"}\n <span className=\"muted small\">uptime means {query.data?.uptimeMeans}</span>\n </h3>\n {/* Same `window` for both lanes of `HistoryTimeline` — the payload's own; the\n empty-string fallback is unreachable (`service` only exists once `query.data`\n has resolved) and exists purely so `window` stays required. */}\n <UptimeDetail service={service} window={query.data?.window ?? { from: \"\", to: \"\" }} />\n <DailyVolumeChart service={service} />\n </section>\n\n <section>\n <h3 style={{ margin: \"0 0 var(--w6w-sp-2)\" }}>\n Recent calls{\" \"}\n <span className=\"muted small\">the requests behind the numbers above</span>\n </h3>\n <div className=\"w6w-rel-card\">\n <CallLog project={effective} appId={service.appId} />\n </div>\n </section>\n </>\n )}\n </div>\n );\n}\n","/**\n * The rows of \"what uses this connection\" — shared by the delete confirm and ConnectionDetail.\n * Kind badge, name, the step/site ids; a link-button to the editor when the host supplies\n * `onOpenCallable`, plain text otherwise.\n */\nimport type { ConnectionDependentCallable } from \"@w6w/sdk/console\";\nimport { useState } from \"react\";\nimport { ModelRoutesManager } from \"../forms/ModelRoutesManager.tsx\";\n\nexport type OpenCallable = (kind: string, id: string) => void;\n\n/** `sites` is `unknown[]` on the wire; render each as a short id string. */\nexport function siteLabel(site: unknown): string {\n if (typeof site === \"string\") return site;\n if (site && typeof site === \"object\") {\n const o = site as Record<string, unknown>;\n for (const k of [\"stepId\", \"step\", \"id\", \"nodeId\", \"key\"]) {\n if (typeof o[k] === \"string\") return o[k] as string;\n }\n }\n return String(site);\n}\n\n/**\n * A model route that reaches the model through this connection. `broken` means the route stopped\n * resolving — typically this connection was removed or stopped working — and gets a reconnect.\n */\nexport interface ConnectionDependentRoute {\n id: string;\n name: string;\n status: \"active\" | \"broken\";\n /** The route's own project; Reconnect opens the editor there, whatever project the host is in. */\n project?: string;\n}\n\n/**\n * The `routes` section of a dependents payload. A `broken` route offers \"Reconnect\", which opens\n * the model-route editor for that route so a replacement connection can be picked (the editor\n * PATCHes `connection`). Active routes are listed without the action. `projectId` is passed\n * through to the editor; omitted, the provider's project applies.\n */\nexport function ConnectionDependentRoutes({\n routes,\n projectId,\n}: {\n routes: ConnectionDependentRoute[];\n projectId?: string | null;\n}) {\n const [reconnecting, setReconnecting] = useState<string | null>(null);\n const target = routes.find((r) => r.id === reconnecting);\n if (routes.length === 0) return null;\n return (\n <>\n <ul className=\"list small\" data-testid=\"connection-dependent-routes\">\n {routes.map((r) => (\n <li key={r.id} data-testid={`connection-dependent-route-${r.id}`}>\n <span className=\"badge\">route</span> <span>{r.name}</span>{\" \"}\n {r.status === \"broken\" && (\n <>\n <span className=\"tag warn\">broken</span>{\" \"}\n <button\n type=\"button\"\n className=\"btn link\"\n data-testid={`connection-route-reconnect-${r.id}`}\n onClick={() => setReconnecting(r.id)}\n >\n Reconnect\n </button>\n </>\n )}\n </li>\n ))}\n </ul>\n {target != null && (\n <ReconnectHost\n routeId={target.id}\n projectId={target.project ?? projectId}\n onDone={() => setReconnecting(null)}\n />\n )}\n </>\n );\n}\n\n/** Mounts the routes manager with the broken route's editor open; closing it unmounts both. */\nfunction ReconnectHost(props: {\n routeId: string;\n projectId?: string | null;\n onDone: () => void;\n}) {\n return (\n <div data-testid=\"connection-route-reconnect-host\">\n <ModelRoutesManager projectId={props.projectId} initialEditRouteId={props.routeId} />\n <button type=\"button\" className=\"btn link\" onClick={props.onDone}>\n Done\n </button>\n </div>\n );\n}\n\nexport function ConnectionDependentRows({\n callables,\n onOpenCallable,\n routes,\n projectId,\n}: {\n callables: ConnectionDependentCallable[];\n onOpenCallable?: OpenCallable;\n routes?: ConnectionDependentRoute[];\n projectId?: string | null;\n}) {\n return (\n <>\n <ConnectionDependentRoutes routes={routes ?? []} projectId={projectId} />\n <CallableRows callables={callables} onOpenCallable={onOpenCallable} />\n </>\n );\n}\n\nfunction CallableRows({\n callables,\n onOpenCallable,\n}: {\n callables: ConnectionDependentCallable[];\n onOpenCallable?: OpenCallable;\n}) {\n return (\n <ul className=\"list small\">\n {callables.map((c) => {\n const name = c.displayName || c.key || c.id;\n const sites = c.sites.map(siteLabel);\n return (\n <li key={`${c.kind}:${c.id}`}>\n <span className=\"badge\">{c.kind}</span>{\" \"}\n {onOpenCallable ? (\n <button\n type=\"button\"\n className=\"btn link\"\n onClick={() => onOpenCallable(c.kind, c.id)}\n >\n {name}\n </button>\n ) : (\n <span>{name}</span>\n )}\n {!c.enabled && <span className=\"muted\"> (disabled)</span>}\n {sites.length > 0 && <span className=\"muted\"> · {sites.join(\", \")}</span>}\n </li>\n );\n })}\n </ul>\n );\n}\n","/**\n * `<ConnectionList>` — the connected list of a host's connections: `useConnectionsQuery` into\n * `@w6w/ui`'s presentational `ConnectionList`, plus Add, Edit and Delete wired to the embed repos.\n *\n * Reads only `@w6w/embed/repos` and the host `W6WUIProvider` adapter (`W6WEmbedProvider` supplies\n * both). App meta comes from a bounded `listAppsByIds` for the rows that lack an inline `app`,\n * never a catalog list. Edit is offered only when the adapter can save (`updateConnection`).\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { ConnectionDependentCallable } from \"@w6w/sdk/console\";\nimport {\n AddConnectionModal,\n EditConnectionModal,\n Modal,\n ConnectionList as UiConnectionList,\n type ConnectionListProps as UiConnectionListProps,\n type ConnectionSummary as UiConnectionSummary,\n connectionAppIdsToLookUp,\n useW6WApi,\n} from \"@w6w/ui\";\nimport { type MouseEvent, type ReactNode, useMemo, useState } from \"react\";\nimport { useEditorApps } from \"../editor/editor-apps.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type ConnectionSummary,\n connectionKey,\n connectionsKey,\n useConnectionDependentsQuery,\n useConnectionsQuery,\n useDeleteConnectionMutation,\n} from \"../repos/connections.ts\";\nimport {\n type ConnectionDependentRoute,\n ConnectionDependentRows,\n type OpenCallable,\n} from \"./ConnectionDependents.tsx\";\n\nexport interface ConnectionListProps {\n /** Row click; the host decides whether to `preventDefault` when it also passes `getHref`. */\n onOpen?: (id: string, event: MouseEvent<Element>) => void;\n /** When set, each openable row is a real `<a href>`. */\n getHref?: (id: string) => string;\n /** Label of the default Add button. Default `+ Add connection`. */\n addLabel?: string;\n /**\n * `header` and `empty` pass through. A given `actions` key (even `null`) replaces the default\n * Add button.\n */\n slots?: UiConnectionListProps[\"slots\"];\n /** When set, dependent rows in the delete confirm open the callable's editor. */\n onOpenCallable?: OpenCallable;\n}\n\nconst NO_ROWS: readonly ConnectionSummary[] = [];\n\nexport function ConnectionList({\n onOpen,\n getHref,\n addLabel,\n slots,\n onOpenCallable,\n}: ConnectionListProps) {\n const api = useW6WApi();\n const qc = useQueryClient();\n const query = useConnectionsQuery();\n const data = query.data;\n const rows = data ?? NO_ROWS;\n const lookupIds = useMemo(() => connectionAppIdsToLookUp(rows), [rows]);\n const { byId } = useEditorApps(lookupIds);\n const del = useDeleteConnectionMutation();\n const [adding, setAdding] = useState(false);\n const [editing, setEditing] = useState<UiConnectionSummary | null>(null);\n const [deleting, setDeleting] = useState<UiConnectionSummary | null>(null);\n const projectId = useEditorProject(undefined);\n const deps = useConnectionDependentsQuery(deleting?.id ?? \"\", deleting !== null);\n\n const canEdit = typeof api.updateConnection === \"function\";\n const actions: ReactNode =\n slots && \"actions\" in slots ? (\n slots.actions\n ) : (\n <button type=\"button\" className=\"w6w-btn\" onClick={() => setAdding(true)}>\n {addLabel ?? \"+ Add connection\"}\n </button>\n );\n\n return (\n <div className=\"w6w-embed-root\">\n <UiConnectionList\n connections={rows}\n appsById={byId}\n loading={query.isLoading}\n error={query.error ? (query.error as Error).message : null}\n onOpen={onOpen}\n getHref={getHref}\n onEdit={canEdit ? setEditing : undefined}\n onDelete={setDeleting}\n busy={del.isPending}\n slots={{ ...slots, actions }}\n />\n {adding && (\n <AddConnectionModal\n onClose={() => setAdding(false)}\n onCreated={() => {\n setAdding(false);\n qc.invalidateQueries({ queryKey: connectionsKey });\n }}\n />\n )}\n {editing && (\n <EditConnectionModal\n connection={editing}\n onClose={() => setEditing(null)}\n onSaved={() => {\n const id = editing.id;\n setEditing(null);\n qc.invalidateQueries({ queryKey: connectionsKey });\n qc.invalidateQueries({ queryKey: connectionKey(id) });\n }}\n />\n )}\n {deleting && (\n <DeleteConfirm\n name={deleting.displayName || deleting.id}\n loading={deps.isLoading}\n callables={deps.isError ? [] : (deps.data?.callables ?? [])}\n routes={\n deps.isError\n ? []\n : ((deps.data as { routes?: ConnectionDependentRoute[] } | undefined)?.routes ?? [])\n }\n projectId={projectId}\n onOpenCallable={onOpenCallable}\n onClose={() => setDeleting(null)}\n onConfirm={() => {\n const id = deleting.id;\n setDeleting(null);\n del.mutate({ id, force: true });\n }}\n />\n )}\n </div>\n );\n}\n\nfunction DeleteConfirm({\n name,\n loading,\n callables,\n routes,\n projectId,\n onOpenCallable,\n onClose,\n onConfirm,\n}: {\n name: string;\n loading: boolean;\n callables: ConnectionDependentCallable[];\n routes: ConnectionDependentRoute[];\n projectId: string | null;\n onOpenCallable?: OpenCallable;\n onClose: () => void;\n onConfirm: () => void;\n}) {\n const c = callables.length;\n const r = routes.length;\n const n = c + r;\n const plain = `Delete the connection \"${name}\"? This cannot be undone.`;\n const plural = (k: number, one: string, many: string) => `${k} ${k === 1 ? one : many}`;\n const usedBy = [\n c > 0 ? plural(c, \"callable\", \"callables\") : null,\n r > 0 ? plural(r, \"model route\", \"model routes\") : null,\n ]\n .filter(Boolean)\n .join(\" and \");\n // Callables are disabled; a model route is not disabled but marked `broken` (it stays listed\n // and editable) until it is pointed at another connection.\n const consequences = [\n c > 0\n ? `Deleting disables ${c === 1 ? \"this callable\" : `these ${c} callables`} until you reconnect ${c === 1 ? \"it\" : \"them\"}.`\n : null,\n r > 0\n ? `${r === 1 ? \"The model route becomes\" : `The ${r} model routes become`} broken until ${r === 1 ? \"it is\" : \"they are\"} pointed at another connection.`\n : null,\n ].filter((x): x is string => x != null);\n return (\n <Modal title=\"Delete connection\" onClose={onClose}>\n <div className=\"w6w-modal-body\">\n <p className=\"w6w-muted w6w-small\">\n {n === 0 ? plain : `Delete the connection \"${name}\"? Used by ${usedBy}.`}\n </p>\n {n > 0 && (\n <>\n <ConnectionDependentRows\n callables={callables}\n routes={routes}\n projectId={projectId}\n onOpenCallable={onOpenCallable}\n />\n <p className=\"w6w-small\">{consequences.join(\" \")}</p>\n </>\n )}\n </div>\n <div className=\"w6w-modal-actions\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onClose}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-danger\"\n disabled={loading}\n onClick={onConfirm}\n >\n Delete\n </button>\n </div>\n </Modal>\n );\n}\n","/**\n * `<ConnectionDetail>` — one connection: identity header with Test and Edit, the app card, the\n * app's actions with their saved tests, and recent tester runs. Studio's `ConnectionDetailPage`\n * body, minus the router and the document title; navigation leaves through callbacks.\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { ApiError } from \"@w6w/sdk\";\nimport {\n ConnectionHeader,\n EditButton,\n EditConnectionModal,\n IconButton,\n ListItem,\n connectionAppIdsToLookUp,\n resolveConnectionAppMeta,\n useW6WApi,\n} from \"@w6w/ui\";\nimport { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { useEditorApps } from \"../editor/editor-apps.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport { useAppQuery } from \"../repos/apps.ts\";\nimport {\n connectionKey,\n connectionsKey,\n useConnectionDependentsQuery,\n useConnectionQuery,\n useTestConnectionMutation,\n} from \"../repos/connections.ts\";\nimport { type SavedTest, useSavedTestsQuery, useTestRunsQuery } from \"../repos/saved-tests.ts\";\nimport {\n type ConnectionDependentRoute,\n ConnectionDependentRows,\n type OpenCallable,\n} from \"./ConnectionDependents.tsx\";\n\nexport interface ConnectionDetailProps {\n connectionId: string;\n /** An action row calls `(actionKey)`; one of its saved tests calls `(actionKey, savedTestId)`. */\n onOpenAction: (actionKey: string, savedTestId?: string) => void;\n /** A \"Used by\" row opens the callable's editor; rows are plain text without it. */\n onOpenCallable?: OpenCallable;\n /** The back affordance renders only when given. */\n onBack?: () => void;\n slots?: {\n /** Replaces the header block. */\n header?: ReactNode;\n /** Appended to the header's buttons. */\n actions?: ReactNode;\n /** Replaces the not-found state. */\n empty?: ReactNode;\n };\n}\n\n/** Bare relative-time label (\"just now\", \"5m ago\"), the same wording as the tester overlay. */\nfunction relativeTime(iso: string): string {\n const then = new Date(iso).getTime();\n if (Number.isNaN(then)) return \"recently\";\n const secs = Math.max(0, Math.round((Date.now() - then) / 1000));\n if (secs < 45) return \"just now\";\n const mins = Math.round(secs / 60);\n if (mins < 60) return `${mins}m ago`;\n const hours = Math.round(mins / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.round(hours / 24);\n if (days < 30) return `${days}d ago`;\n return new Date(iso).toLocaleDateString();\n}\n\ntype TestNotice = { kind: \"ok\" | \"warn\" | \"error\"; text: string };\nconst NOTICE_DISMISS_MS: Record<TestNotice[\"kind\"], number> = {\n ok: 6000,\n warn: 10000,\n error: 15000,\n};\nconst NOTICE_ICON: Record<TestNotice[\"kind\"], string> = { ok: \"✓\", warn: \"!\", error: \"✕\" };\n\nexport function ConnectionDetail({\n connectionId,\n onOpenAction,\n onBack,\n onOpenCallable,\n slots,\n}: ConnectionDetailProps) {\n const api = useW6WApi();\n const qc = useQueryClient();\n const connQuery = useConnectionQuery(connectionId);\n const appId = connQuery.data?.appId;\n const lookupIds = useMemo(\n () => connectionAppIdsToLookUp(connQuery.data ? [connQuery.data] : []),\n [connQuery.data],\n );\n const { byId: appsById } = useEditorApps(lookupIds);\n const appSummary = connQuery.data\n ? resolveConnectionAppMeta(connQuery.data, appsById)\n : undefined;\n const appDetailQuery = useAppQuery(appId, !!appId);\n\n const savedTestsQuery = useSavedTestsQuery(connectionId);\n const savedTestsByAction = useMemo(() => {\n const map = new Map<string, SavedTest[]>();\n for (const t of savedTestsQuery.data ?? []) {\n const list = map.get(t.actionKey) ?? [];\n list.push(t);\n map.set(t.actionKey, list);\n }\n return map;\n }, [savedTestsQuery.data]);\n\n // Best-effort: a load failure leaves the list empty (`retry: false`), so the section hides.\n // Best-effort too: a failed lookup renders no \"Used by\" card rather than a false \"not used\".\n const dependents = useConnectionDependentsQuery(connectionId).data;\n const projectId = useEditorProject(undefined);\n const usedBy = dependents?.callables ?? [];\n // The sdk's `ConnectionDependents` type predates `routes`; read it structurally.\n const usedByRoutes =\n (dependents as { routes?: ConnectionDependentRoute[] } | undefined)?.routes ?? [];\n const runHistory = useTestRunsQuery(connectionId).data ?? [];\n\n const [editOpen, setEditOpen] = useState(false);\n const [actionFilter, setActionFilter] = useState(\"\");\n const testMut = useTestConnectionMutation(connectionId);\n\n const [testNotice, setTestNotice] = useState<TestNotice | null>(null);\n useEffect(() => {\n if (!testNotice) return;\n const timer = setTimeout(() => setTestNotice(null), NOTICE_DISMISS_MS[testNotice.kind]);\n return () => clearTimeout(timer);\n }, [testNotice]);\n\n const runTest = () => {\n setTestNotice(null);\n testMut.mutate(undefined, {\n onSuccess: (r) => {\n if (!r.ok) {\n setTestNotice({\n kind: \"error\",\n text: `Connection test failed${r.error?.message ? `: ${r.error.message}` : \".\"}`,\n });\n return;\n }\n setTestNotice(\n r.untested\n ? { kind: \"warn\", text: `Connection stored. ${r.message ?? \"\"}`.trim() }\n : {\n kind: \"ok\",\n text: `Connection is valid${r.actionKey ? ` — probed ${r.actionKey}` : \"\"}.`,\n },\n );\n },\n onError: (e) =>\n setTestNotice({ kind: \"error\", text: (e as ApiError)?.message ?? \"Test failed.\" }),\n });\n };\n\n const sortedActions = useMemo(() => {\n const list = [...(appDetailQuery.data?.actions ?? [])];\n list.sort((a, b) => (a.title || a.key).localeCompare(b.title || b.key));\n return list;\n }, [appDetailQuery.data]);\n const filteredActions = useMemo(() => {\n const q = actionFilter.trim().toLowerCase();\n if (!q) return sortedActions;\n return sortedActions.filter(\n (a) =>\n (a.title || \"\").toLowerCase().includes(q) ||\n a.key.toLowerCase().includes(q) ||\n (a.description || \"\").toLowerCase().includes(q),\n );\n }, [sortedActions, actionFilter]);\n\n if (connQuery.isLoading || appDetailQuery.isLoading) {\n return (\n <div className=\"w6w-embed-root w6w-embed-conn-detail\">\n <p className=\"w6w-muted\">Loading…</p>\n </div>\n );\n }\n if (!connQuery.data) {\n return (\n <div className=\"w6w-embed-root w6w-embed-conn-detail\" data-testid=\"connection-not-found\">\n {slots?.empty ?? <h2>Connection not found</h2>}\n {onBack && (\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onBack}>\n Back to integrations\n </button>\n )}\n </div>\n );\n }\n\n const conn = connQuery.data;\n const app = appDetailQuery.data;\n const canEdit = !conn.builtIn && typeof api.updateConnection === \"function\";\n\n // The cards below are a vertical stack, so the gap is @w6w/ui's shared\n // `.w6w-card-stack` (16px, `--w6w-sp-4`) — not a local number in styles.css.\n return (\n <div className=\"w6w-embed-root w6w-embed-conn-detail w6w-card-stack\">\n {slots?.header ?? (\n <ConnectionHeader conn={conn} app={appSummary}>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={testMut.isPending}\n onClick={runTest}\n >\n {testMut.isPending ? \"Testing…\" : \"Test connection\"}\n </button>\n {canEdit && (\n <EditButton\n label=\"Edit\"\n onClick={() => setEditOpen(true)}\n data-testid=\"connection-detail-edit\"\n />\n )}\n {slots?.actions}\n </ConnectionHeader>\n )}\n\n {testNotice && (\n <div\n className={`w6w-result w6w-embed-conn-notice w6w-embed-conn-notice-${testNotice.kind}`}\n role={testNotice.kind === \"error\" ? \"alert\" : \"status\"}\n aria-live={testNotice.kind === \"error\" ? \"assertive\" : \"polite\"}\n data-testid=\"connection-test-notice\"\n >\n <span aria-hidden=\"true\">{NOTICE_ICON[testNotice.kind]}</span>\n <span className=\"w6w-embed-conn-notice-text\">{testNotice.text}</span>\n <IconButton icon=\"close\" label=\"Dismiss\" onClick={() => setTestNotice(null)} />\n </div>\n )}\n\n <div className=\"w6w-embed-conn-card\">\n <h3>App: {appSummary?.displayName ?? conn.appId}</h3>\n {app && (\n <p className=\"w6w-muted w6w-small\">\n Version <code>v{app.version ?? \"?\"}</code> · source <code>{app.sourceRef}</code>\n </p>\n )}\n {onBack && (\n <p className=\"w6w-small\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onBack}>\n ← Integrations\n </button>\n </p>\n )}\n </div>\n\n <div className=\"w6w-embed-conn-card\">\n <h3>Actions</h3>\n {sortedActions.length === 0 && <p className=\"w6w-muted\">No actions exposed.</p>}\n {sortedActions.length > 10 && (\n <input\n type=\"search\"\n value={actionFilter}\n placeholder={`Search ${sortedActions.length} actions…`}\n onChange={(e) => setActionFilter(e.target.value)}\n aria-label=\"Filter actions\"\n className=\"w6w-embed-conn-filter\"\n />\n )}\n {sortedActions.length > 0 && filteredActions.length === 0 && (\n <p className=\"w6w-muted w6w-small\">No actions match “{actionFilter}”.</p>\n )}\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Actions\">\n {filteredActions.map((a) => {\n const tests = savedTestsByAction.get(a.key) ?? [];\n return (\n <li key={a.key}>\n <button\n type=\"button\"\n className=\"w6w-embed-conn-action\"\n data-testid={`connection-action-${a.key}`}\n onClick={() => onOpenAction(a.key)}\n >\n <strong>{a.title}</strong> <code className=\"w6w-muted\">{a.key}</code>{\" \"}\n <span className=\"w6w-embed-conn-badge\">{a.type}</span>\n {a.description && <div className=\"w6w-muted w6w-small\">{a.description}</div>}\n </button>\n {tests.length > 0 && (\n <ul\n className=\"w6w-embed-conn-list w6w-embed-conn-tests\"\n aria-label={`Saved tests for ${a.title || a.key}`}\n >\n {tests.map((t) => (\n <li key={t.id}>\n <ListItem\n title={t.name}\n subtitle={\n t.lastRunAt ? (\n <span>\n <span\n className={\n t.lastRunOk ? \"w6w-embed-conn-ok\" : \"w6w-embed-conn-fail\"\n }\n >\n {t.lastRunOk ? \"✓\" : \"✗\"}\n </span>{\" \"}\n {t.lastRunSummary ? `${t.lastRunSummary} · ` : \"\"}\n {relativeTime(t.lastRunAt)}\n </span>\n ) : (\n `saved ${relativeTime(t.updatedAt)}`\n )\n }\n onClick={() => onOpenAction(a.key, t.id)}\n />\n </li>\n ))}\n </ul>\n )}\n </li>\n );\n })}\n </ul>\n </div>\n\n {dependents && (\n <div className=\"w6w-embed-conn-card\" data-testid=\"connection-used-by\">\n <h3>Used by</h3>\n {usedBy.length === 0 && usedByRoutes.length === 0 ? (\n <p className=\"w6w-muted\">Not used by any callable</p>\n ) : (\n <ConnectionDependentRows\n callables={usedBy}\n routes={usedByRoutes}\n projectId={projectId}\n onOpenCallable={onOpenCallable}\n />\n )}\n </div>\n )}\n\n {runHistory.length > 0 && (\n <div className=\"w6w-embed-conn-card\">\n <h3>Recent runs</h3>\n <p className=\"w6w-muted w6w-small\">Most recent tester runs against this connection.</p>\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Recent runs\">\n {runHistory.map((run) => (\n <li key={run.id}>\n <ListItem\n title={run.actionKey}\n subtitle={\n <span>\n <span className={run.ok ? \"w6w-embed-conn-ok\" : \"w6w-embed-conn-fail\"}>\n {run.ok ? \"✓\" : \"✗\"}\n </span>{\" \"}\n {run.summary ? `${run.summary} · ` : \"\"}\n {relativeTime(run.occurredAt)}\n </span>\n }\n />\n </li>\n ))}\n </ul>\n </div>\n )}\n\n {editOpen && (\n <EditConnectionModal\n connection={conn}\n onClose={() => setEditOpen(false)}\n onSaved={() => {\n setEditOpen(false);\n qc.invalidateQueries({ queryKey: connectionKey(connectionId) });\n qc.invalidateQueries({ queryKey: connectionsKey });\n }}\n />\n )}\n </div>\n );\n}\n","/**\n * `<ModelCatalog>` — every model this tenant may route to: the provider-discovered entries plus\n * the tenant's own manual ones, from `GET /models` (list + empty state, keyset \"load more\").\n *\n * The catalog is TENANT-WIDE: the repo deliberately sends no `project`, so the `projectId` prop is\n * accepted (the Models tab shell passes the same prop to all four tabs) and deliberately unused —\n * this is the one tab that renders before a project resolves. A row shows the model's current rate\n * card (per-million-token minor units, `ModelRate.rates`) and its status; editing rates stays on the\n * server API, it is not a tab affordance.\n */\nimport { useInfiniteQuery } from \"@tanstack/react-query\";\nimport { DataTable, type DataTableColumn, EmptyState } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport {\n type Model,\n type ModelCatalogFilter,\n type ModelCatalogPage,\n type ModelRate,\n listModelCatalog,\n modelCatalogKey,\n} from \"../repos/models.ts\";\n\nexport interface ModelCatalogProps {\n /**\n * The project the Models tab is scoped to. Kept for a uniform tab API: the catalog never sends\n * it (a tenant-wide list), so it changes nothing here.\n */\n projectId?: string | null;\n /** Narrow the list (`provider`, `status`, `limit`). `cursor` is keyset paging, managed here. */\n filter?: Omit<ModelCatalogFilter, \"cursor\">;\n}\n\nconst NO_FILTER: Omit<ModelCatalogFilter, \"cursor\"> = {};\n\n/** Plain thousands separators — no `Intl`, so the text is identical in every host and test. */\nfunction grouped(n: number): string {\n return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\n/** Rates are integer MINOR units per million tokens; print them as major units. */\nfunction major(minor: number): string {\n return (minor / 100).toFixed(2);\n}\n\n/** One rate card on one line: `<CUR> in 3.00 · out 15.00` (only the fields the card sets). */\nfunction rateText(rate: ModelRate | null): string | null {\n if (rate == null) return null;\n const r = rate.rates;\n const parts: string[] = [];\n if (r.input != null) parts.push(`in ${major(r.input)}`);\n if (r.output != null) parts.push(`out ${major(r.output)}`);\n if (r.cachedInput != null) parts.push(`cached ${major(r.cachedInput)}`);\n if (r.cacheWrite != null) parts.push(`cache write ${major(r.cacheWrite)}`);\n if (r.perRequest != null) parts.push(`${major(r.perRequest)}/request`);\n if (parts.length === 0) return null;\n return `${r.currency ?? \"USD\"} ${parts.join(\" · \")}`;\n}\n\nfunction limitsText(m: Model): string {\n const { maxInputTokens, maxOutputTokens } = m.limits ?? {};\n if (maxInputTokens == null && maxOutputTokens == null) return \"—\";\n const parts: string[] = [];\n if (maxInputTokens != null) parts.push(`${grouped(maxInputTokens)} in`);\n if (maxOutputTokens != null) parts.push(`${grouped(maxOutputTokens)} out`);\n return parts.join(\" · \");\n}\n\nconst columns: DataTableColumn<Model>[] = [\n {\n key: \"model\",\n header: \"Model\",\n render: (m) => (\n <div className=\"list-main\" style={{ maxWidth: 0, minWidth: \"100%\" }}>\n <strong className=\"list-name\" title={m.displayName}>\n {m.displayName}\n </strong>\n <div className=\"muted small list-preview\" title={`${m.provider} · ${m.nativeId}`}>\n {m.provider} · {m.nativeId} · {m.source}\n </div>\n </div>\n ),\n },\n {\n key: \"provider\",\n header: \"Provider\",\n render: (m) => <span className=\"muted small\">{m.provider || \"—\"}</span>,\n },\n {\n key: \"status\",\n header: \"Status\",\n render: (m) => <span className={m.status === \"active\" ? \"tag\" : \"tag warn\"}>{m.status}</span>,\n },\n {\n key: \"rate\",\n header: \"Rate (per 1M tokens)\",\n render: (m) => {\n const text = rateText(m.currentRate);\n if (text == null) return <span className=\"muted small\">—</span>;\n return (\n <span\n className=\"muted small\"\n title={m.currentRate ? `effective ${m.currentRate.effectiveFrom}` : undefined}\n >\n {text}\n </span>\n );\n },\n },\n {\n key: \"limits\",\n header: \"Limits\",\n render: (m) => <span className=\"muted small\">{limitsText(m)}</span>,\n },\n];\n\nexport function ModelCatalog(props: ModelCatalogProps): ReactNode {\n const client = useEmbedClient();\n const filter = props.filter ?? NO_FILTER;\n const query = useInfiniteQuery({\n queryKey: modelCatalogKey(filter),\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (last: ModelCatalogPage) => last.nextCursor ?? undefined,\n queryFn: ({ pageParam }): Promise<ModelCatalogPage> =>\n listModelCatalog(client, pageParam ? { ...filter, cursor: pageParam } : filter),\n });\n const models = query.data?.pages.flatMap((p) => p.models) ?? [];\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n <div className=\"section-head\">\n <div>\n <h3>Model catalog</h3>\n <p className=\"muted small\">\n The models discovered on this tenant's connections, plus any added by hand. A route\n may only name a model from this list; the rate card is what usage is priced with.\n </p>\n </div>\n </div>\n\n <div>\n {query.isLoading && <p className=\"muted\">Loading…</p>}\n {query.error != null && <div className=\"error\">{query.error.message}</div>}\n {query.isSuccess && models.length === 0 && (\n <EmptyState testId=\"model-catalog-empty\">\n No models yet. Discover them from a provider connection to start routing to them.\n </EmptyState>\n )}\n {models.length > 0 && (\n <DataTable\n columns={columns}\n rows={models}\n rowKey={(m) => m.id}\n testId=\"model-catalog-table\"\n rowTestId={(m) => `model-catalog-${m.id}`}\n />\n )}\n </div>\n\n {query.hasNextPage && (\n <div className=\"row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n disabled={query.isFetchingNextPage}\n onClick={() => void query.fetchNextPage()}\n data-testid=\"model-catalog-load-more\"\n >\n {query.isFetchingNextPage ? \"Loading…\" : \"Load more\"}\n </button>\n </div>\n )}\n </section>\n </div>\n );\n}\n","/**\n * `<ModelUsage>` — the project's model-call ledger: totals for the window, then one row per call,\n * from `GET /model-usage` with keyset \"load more\" (`nextCursor` until the server stops returning\n * one). Totals are the SERVER's, taken from the first page and never re-summed from the loaded\n * rows, so they stay right as more pages arrive.\n *\n * Two things the wire shape makes easy to get wrong, and this component does not:\n * - `cost` is an ARRAY, one entry per currency; a window that mixed currencies prints every\n * currency rather than adding different monies together.\n * - `costMinor` is `null` when the call had no usable rate (`unpriced`). That is NOT zero spend:\n * the cell prints \"unpriced\", and the totals count those calls instead of pricing them at 0.\n * - `totalsTruncated: true` means the server's totals cover a bounded scan, not every matching\n * call; the note says so instead of presenting a partial number as the whole.\n *\n * The project comes from `useEditorProject(projectId)`: omitted defers to the `<W6WEmbedProvider\n * project>`; `null` or `\"\"` REFUSES — the report query is disabled and no `/model-usage` request\n * is sent.\n */\nimport { useInfiniteQuery } from \"@tanstack/react-query\";\nimport { DataTable, type DataTableColumn, EmptyState } from \"@w6w/ui\";\nimport type { ReactNode } from \"react\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { formatDuration, formatTimestamp } from \"../lib/recent-activity.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n type ModelCost,\n type ModelUsageFilter,\n type ModelUsageItem,\n type ModelUsageReport,\n getModelUsage,\n modelUsageKey,\n} from \"../repos/models.ts\";\n\nexport interface ModelUsageProps {\n /**\n * The project whose usage is shown. Omitted: the `<W6WEmbedProvider project>`. `null` or `\"\"`:\n * no project — nothing is requested.\n */\n projectId?: string | null;\n /** Narrow the report (`route`, `model`, `from`, `to`, `groupBy`, `limit`). `cursor` is paging. */\n filter?: Omit<ModelUsageFilter, \"cursor\">;\n}\n\nconst NO_FILTER: Omit<ModelUsageFilter, \"cursor\"> = {};\n\n/** Plain thousands separators — no `Intl`, so the text is identical in every host and test. */\nfunction grouped(n: number): string {\n return String(n).replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\n/** Cost is integer MINOR units: `USD 1.50`. */\nfunction costText(cost: ModelCost): string {\n return `${cost.currency} ${(cost.amountMinor / 100).toFixed(2)}`;\n}\n\n/** Every currency in the window, never summed across them. `unpriced` is not a zero. */\nfunction costsText(costs: ModelCost[], unpriced: number): string {\n if (costs.length > 0) return costs.map(costText).join(\" · \");\n return unpriced > 0 ? \"unpriced\" : \"—\";\n}\n\n/** A row's own cost, or `null` when the call had no usable rate. */\nfunction itemCost(item: ModelUsageItem): string | null {\n if (item.costMinor == null) return null;\n return `${item.currency ?? \"USD\"} ${(item.costMinor / 100).toFixed(2)}`;\n}\n\nfunction totalsTruncated(report: ModelUsageReport): boolean {\n return report.totalsTruncated === true;\n}\n\nconst columns: DataTableColumn<ModelUsageItem>[] = [\n {\n key: \"occurredAt\",\n header: \"When\",\n render: (i) => (\n <span className=\"muted small\" title={i.occurredAt}>\n {formatTimestamp(i.occurredAt)}\n </span>\n ),\n },\n {\n key: \"model\",\n header: \"Model\",\n render: (i) => (\n <div className=\"list-main\" style={{ maxWidth: 0, minWidth: \"100%\" }}>\n <strong className=\"list-name\" title={`${i.provider} · ${i.nativeId}`}>\n {i.provider} · {i.nativeId}\n </strong>\n <div className=\"muted small list-preview\" title={i.connectionId}>\n {i.connectionId}\n </div>\n </div>\n ),\n },\n {\n key: \"route\",\n header: \"Route\",\n render: (i) =>\n i.routeId == null ? (\n <span className=\"muted small\">direct</span>\n ) : (\n <code className=\"muted small\" title={i.routeId}>\n {i.routeId}\n </code>\n ),\n },\n {\n key: \"tokens\",\n header: \"Tokens\",\n align: \"right\",\n render: (i) => (\n <span\n className=\"muted small\"\n title={`${grouped(i.inputTokens)} in · ${grouped(i.outputTokens)} out · ${grouped(i.cachedInputTokens)} cached input · ${grouped(i.cacheWriteTokens)} cache write`}\n >\n {grouped(i.totalTokens)}\n </span>\n ),\n },\n {\n key: \"cost\",\n header: \"Cost\",\n align: \"right\",\n render: (i) => {\n const text = itemCost(i);\n if (text == null) {\n return (\n <span className=\"tag warn\" data-testid=\"model-usage-unpriced\" title=\"no usable rate\">\n unpriced\n </span>\n );\n }\n return <span className=\"muted small\">{text}</span>;\n },\n },\n {\n key: \"result\",\n header: \"Result\",\n render: (i) => {\n const duration = formatDuration(i.durationMs);\n return (\n <span className=\"muted small\" title={i.errorCode ?? undefined}>\n <span className={i.ok ? \"tag\" : \"tag warn\"}>\n {i.ok ? \"ok\" : (i.errorCode ?? \"failed\")}\n </span>\n {duration != null && <> · {duration}</>}\n </span>\n );\n },\n },\n];\n\nexport function ModelUsage(props: ModelUsageProps): ReactNode {\n const project = useEditorProject(props.projectId);\n const client = useEmbedClient();\n const filter = props.filter ?? NO_FILTER;\n const query = useInfiniteQuery({\n queryKey: modelUsageKey(project ?? undefined, filter),\n enabled: project != null,\n initialPageParam: undefined as string | undefined,\n getNextPageParam: (last: ModelUsageReport) => last.nextCursor ?? undefined,\n queryFn: ({ pageParam }): Promise<ModelUsageReport> =>\n getModelUsage(\n client,\n project as string,\n pageParam ? { ...filter, cursor: pageParam } : filter,\n ),\n });\n const pages = query.data?.pages ?? [];\n const totals = pages[0]?.totals;\n const items = pages.flatMap((p) => p.items);\n const truncated = pages.length > 0 && totalsTruncated(pages[0]);\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n <div className=\"section-head\">\n <div>\n <h3>Model usage</h3>\n <p className=\"muted small\">\n Every model call this project paid for, priced with the rate card in force when it\n ran. A call with no usable rate counts as unpriced, not as free.\n </p>\n </div>\n </div>\n\n {project == null ? (\n <div className=\"card\">\n <p className=\"muted\" data-testid=\"model-usage-no-project\">\n Select a project to see its model usage.\n </p>\n </div>\n ) : (\n <>\n <div className=\"card\" data-testid=\"model-usage-totals\">\n {truncated && (\n <p className=\"result warn\" data-testid=\"model-usage-totals-partial\">\n Totals are partial: they cover a bounded scan of this window, not every matching\n call. Narrow the range for exact totals.\n </p>\n )}\n {totals == null ? (\n // A failed query is reported once, below — never as a perpetual \"loading\".\n query.error == null && <p className=\"muted\">Loading totals…</p>\n ) : (\n <p className=\"muted small\">\n <span data-testid=\"model-usage-total-requests\">\n {grouped(totals.requests)} requests\n </span>\n {\" · \"}\n <span data-testid=\"model-usage-total-tokens\">\n {grouped(totals.totalTokens)} tokens ({grouped(totals.inputTokens)} in /{\" \"}\n {grouped(totals.outputTokens)} out / {grouped(totals.cachedInputTokens)} cached\n / {grouped(totals.cacheWriteTokens)} cache write)\n </span>\n {\" · \"}\n <span data-testid=\"model-usage-total-cost\">\n {costsText(totals.cost, totals.unpriced)}\n </span>\n {totals.unpriced > 0 && (\n <>\n {\" · \"}\n <span\n className=\"tag warn\"\n data-testid=\"model-usage-unpriced-total\"\n title=\"calls with no usable rate — not included in any cost total\"\n >\n {grouped(totals.unpriced)} unpriced\n </span>\n </>\n )}\n </p>\n )}\n </div>\n\n {query.error != null && (\n <div className=\"error\" role=\"alert\" data-testid=\"model-usage-error\">\n {query.error.message}\n </div>\n )}\n\n <div>\n {query.isLoading && <p className=\"muted\">Loading…</p>}\n {query.isSuccess && items.length === 0 && (\n <EmptyState testId=\"model-usage-empty\">\n No model calls in this window. Usage rows appear here as routes are invoked.\n </EmptyState>\n )}\n {items.length > 0 && (\n <DataTable\n columns={columns}\n rows={items}\n rowKey={(i) => i.id}\n testId=\"model-usage-table\"\n rowTestId={(i) => `model-usage-${i.id}`}\n />\n )}\n </div>\n\n {query.hasNextPage && (\n <div className=\"row\">\n <button\n type=\"button\"\n className=\"btn ghost\"\n disabled={query.isFetchingNextPage}\n onClick={() => void query.fetchNextPage()}\n data-testid=\"model-usage-load-more\"\n >\n {query.isFetchingNextPage ? \"Loading…\" : \"Load more\"}\n </button>\n </div>\n )}\n </>\n )}\n </section>\n </div>\n );\n}\n","/**\n * `<CredentialList>` — the host's stored credentials: name, status, one non-secret display value\n * and how many connections use each. Opening a row is the host's `onOpen`; the embed never\n * navigates. Reads only `useCredentialsQuery` (never a secret: the summary carries none).\n */\nimport type { ReactNode } from \"react\";\nimport { type CredentialSummary, useCredentialsQuery } from \"../repos/credentials.ts\";\n\nexport interface CredentialListProps {\n /** Narrow the list to one credential contract. */\n contract?: string;\n /** Row click. */\n onOpen?: (id: string) => void;\n slots?: {\n /** Replaces the heading. */\n header?: ReactNode;\n /** Replaces the empty state. */\n empty?: ReactNode;\n };\n}\n\nconst plural = (n: number) => `${n} connection${n === 1 ? \"\" : \"s\"}`;\n\nexport function CredentialList({ contract, onOpen, slots }: CredentialListProps) {\n const query = useCredentialsQuery(contract ? { contract } : undefined);\n const rows: readonly CredentialSummary[] = query.data ?? [];\n\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-list\">\n {slots?.header ?? <h2>Credentials</h2>}\n {query.isLoading && <p className=\"w6w-muted\">Loading…</p>}\n {query.error && (\n <p className=\"w6w-error\" role=\"alert\">\n {(query.error as Error).message}\n </p>\n )}\n {!query.isLoading && !query.error && rows.length === 0 && (\n <div data-testid=\"credential-list-empty\">\n {slots?.empty ?? <p className=\"w6w-muted\">No credentials yet.</p>}\n </div>\n )}\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Credentials\">\n {rows.map((c) => {\n const shown = Object.values(c.display)[0];\n return (\n <li key={c.id}>\n <button\n type=\"button\"\n className=\"w6w-embed-conn-action\"\n data-testid={`credential-row-${c.id}`}\n onClick={() => onOpen?.(c.id)}\n >\n <strong>{c.name}</strong> <span className=\"w6w-embed-conn-badge\">{c.status}</span>\n {shown !== undefined && <span className=\"w6w-muted w6w-small\"> {shown}</span>}\n <span className=\"w6w-muted w6w-small\"> · {plural(c.connectionCount)}</span>\n </button>\n </li>\n );\n })}\n </ul>\n </div>\n );\n}\n","/**\n * `<CredentialDetail>` — one stored credential: an explicit pick of its non-secret summary, the\n * connections that use it, and Rotate, Disable/Enable, Test and Delete. Never renders a spread or a\n * serialisation of the record. The rotate secret is one masked textarea whose text is parsed\n * locally and sent as `{ source }`; it is never echoed into an error. Navigation leaves through\n * `onOpenConnection`, `onDeleted` and `onBack`.\n */\nimport type { ApiError } from \"@w6w/sdk\";\nimport { type ReactNode, useState } from \"react\";\nimport {\n type CredentialDependents,\n type CredentialTestResult,\n useCredentialDependentsQuery,\n useCredentialQuery,\n useDeleteCredentialMutation,\n useRotateCredentialMutation,\n useSetCredentialStatusMutation,\n useTestCredentialMutation,\n} from \"../repos/credentials.ts\";\n\nexport interface CredentialDetailProps {\n credentialId: string;\n /** A connected-app row calls `(connectionId)`; rows are plain text without it. */\n onOpenConnection?: (id: string) => void;\n /** Called after a delete succeeds. */\n onDeleted?: () => void;\n /** The back affordance renders only when given. */\n onBack?: () => void;\n slots?: {\n /** Replaces the not-found state. */\n empty?: ReactNode;\n };\n}\n\ntype Dependents = CredentialDependents[\"connections\"];\n\n/** The textarea's text as a JSON object, or `null`. Never throws and never carries the text. */\nfunction parseSource(text: string): Record<string, unknown> | null {\n try {\n const v: unknown = JSON.parse(text);\n return v !== null && typeof v === \"object\" && !Array.isArray(v)\n ? (v as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nconst fmt = (iso: string) => (Number.isNaN(Date.parse(iso)) ? iso : new Date(iso).toLocaleString());\n\nexport function CredentialDetail({\n credentialId,\n onOpenConnection,\n onDeleted,\n onBack,\n slots,\n}: CredentialDetailProps) {\n const query = useCredentialQuery(credentialId);\n const deps = useCredentialDependentsQuery(credentialId);\n const rotate = useRotateCredentialMutation(credentialId);\n const setStatus = useSetCredentialStatusMutation(credentialId);\n const testMut = useTestCredentialMutation(credentialId);\n const del = useDeleteCredentialMutation();\n\n const [secret, setSecret] = useState(\"\");\n const [rotateError, setRotateError] = useState<string | null>(null);\n const [rotated, setRotated] = useState(false);\n const [testResult, setTestResult] = useState<CredentialTestResult | null>(null);\n const [testError, setTestError] = useState<string | null>(null);\n const [confirming, setConfirming] = useState(false);\n const [blocking, setBlocking] = useState<Dependents | null>(null);\n const [actionError, setActionError] = useState<string | null>(null);\n\n const back = onBack && (\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onBack}>\n ← Credentials\n </button>\n );\n\n if (query.isLoading) {\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-detail\">\n <p className=\"w6w-muted\">Loading…</p>\n </div>\n );\n }\n const c = query.data;\n if (!c) {\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-detail\" data-testid=\"credential-not-found\">\n {slots?.empty ?? <h2>Credential not found</h2>}\n {back}\n </div>\n );\n }\n\n const connected: Dependents = deps.data?.connections ?? [];\n const n = c.connectionCount;\n const disabled = c.status === \"disabled\";\n\n const doRotate = () => {\n setRotated(false);\n const source = parseSource(secret);\n if (!source) {\n // Fixed text: the typed value is never interpolated.\n setRotateError(\"Enter the new secret as a JSON object.\");\n return;\n }\n setRotateError(null);\n rotate.mutate(\n { source },\n {\n onSuccess: () => {\n setSecret(\"\");\n setRotated(true);\n },\n onError: (e) => setRotateError((e as ApiError)?.message ?? \"Rotate failed.\"),\n },\n );\n };\n\n const doTest = () => {\n setTestResult(null);\n setTestError(null);\n testMut.mutate(undefined, {\n onSuccess: setTestResult,\n onError: (e) => setTestError((e as ApiError)?.message ?? \"Test failed.\"),\n });\n };\n\n const doDelete = () => {\n setActionError(null);\n del.mutate(credentialId, {\n onSuccess: (r) => {\n setConfirming(false);\n if (r.ok) onDeleted?.();\n else setBlocking(r.dependents.connections);\n },\n onError: (e) => setActionError((e as ApiError)?.message ?? \"Delete failed.\"),\n });\n };\n\n return (\n <div className=\"w6w-embed-root w6w-embed-cred-detail w6w-card-stack\">\n <div className=\"w6w-embed-conn-card\">\n <h2>{c.name}</h2>\n <p className=\"w6w-small\">\n <code>{c.contract}</code> <span className=\"w6w-embed-conn-badge\">{c.status}</span>\n </p>\n <dl className=\"w6w-small\" data-testid=\"credential-display\">\n {Object.entries(c.display).map(([k, v]) => (\n <div key={k}>\n <dt className=\"w6w-muted\">{k}</dt>\n <dd>{v}</dd>\n </div>\n ))}\n </dl>\n <p className=\"w6w-muted w6w-small\">\n {n} connection{n === 1 ? \"\" : \"s\"} · created {fmt(c.createdAt)} · updated{\" \"}\n {fmt(c.updatedAt)}\n </p>\n {back}\n </div>\n\n <div className=\"w6w-embed-conn-card\" data-testid=\"credential-connections\">\n <h3>Connected apps</h3>\n {connected.length === 0 ? (\n <p className=\"w6w-muted\">Not used by any connection.</p>\n ) : (\n <ul className=\"w6w-embed-conn-list\" aria-label=\"Connected apps\">\n {connected.map((d) => (\n <li key={d.id}>\n {onOpenConnection ? (\n <button\n type=\"button\"\n className=\"w6w-embed-conn-action\"\n onClick={() => onOpenConnection(d.id)}\n >\n {d.displayName || d.appId}\n </button>\n ) : (\n <span>{d.displayName || d.appId}</span>\n )}\n </li>\n ))}\n </ul>\n )}\n </div>\n\n <div className=\"w6w-embed-conn-card\">\n <h3>Rotate secret</h3>\n <p className=\"w6w-muted w6w-small\" data-testid=\"credential-rotation-impact\">\n {n} connection{n === 1 ? \"\" : \"s\"} will be marked untested\n </p>\n <textarea\n className=\"w6w-input w6w-secret-input\"\n aria-label=\"New secret (JSON object)\"\n rows={5}\n value={secret}\n onChange={(e) => setSecret(e.target.value)}\n name=\"w6w-cred-rotate\"\n autoComplete=\"off\"\n autoCapitalize=\"off\"\n autoCorrect=\"off\"\n spellCheck={false}\n data-1p-ignore=\"true\"\n data-lpignore=\"true\"\n data-bwignore=\"true\"\n data-form-type=\"other\"\n />\n {rotateError && (\n <p className=\"w6w-error\" role=\"alert\" data-testid=\"credential-rotate-error\">\n {rotateError}\n </p>\n )}\n {rotated && <output>Secret rotated.</output>}\n <button type=\"button\" className=\"w6w-btn\" disabled={rotate.isPending} onClick={doRotate}>\n {rotate.isPending ? \"Rotating…\" : \"Rotate\"}\n </button>\n </div>\n\n <div className=\"w6w-embed-conn-card\">\n <h3>Manage</h3>\n <div className=\"w6w-modal-actions\">\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={setStatus.isPending}\n onClick={() => setStatus.mutate(disabled ? \"active\" : \"disabled\")}\n >\n {disabled ? \"Enable\" : \"Disable\"}\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={testMut.isPending}\n onClick={doTest}\n >\n {testMut.isPending ? \"Testing…\" : \"Test credential\"}\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-danger\"\n onClick={() => {\n setBlocking(null);\n setConfirming(true);\n }}\n >\n Delete\n </button>\n </div>\n {testResult && (\n <output data-testid=\"credential-test-result\">\n {testResult.ok ? \"ok\" : (testResult.code ?? \"failed\")}\n </output>\n )}\n {testError && <p role=\"alert\">{testError}</p>}\n {setStatus.isError && (\n <p role=\"alert\">{(setStatus.error as ApiError)?.message ?? \"Update failed.\"}</p>\n )}\n {confirming && (\n <div data-testid=\"credential-delete-confirm\">\n <p className=\"w6w-small\">Delete the credential \"{c.name}\"? This cannot be undone.</p>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-danger\"\n disabled={del.isPending}\n onClick={doDelete}\n >\n Confirm delete\n </button>{\" \"}\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n onClick={() => setConfirming(false)}\n >\n Cancel\n </button>\n </div>\n )}\n {blocking && (\n <div role=\"alert\" data-testid=\"credential-in-use\">\n <p className=\"w6w-small\">\n This credential is still used by {blocking.length} connection\n {blocking.length === 1 ? \"\" : \"s\"}. Delete those integrations first, or rotate this\n credential instead of deleting it.\n </p>\n <ul className=\"w6w-embed-conn-list\">\n {blocking.map((d) => (\n <li key={d.id}>{d.displayName || d.appId}</li>\n ))}\n </ul>\n </div>\n )}\n {actionError && <p role=\"alert\">{actionError}</p>}\n </div>\n </div>\n );\n}\n","/**\n * `<DataStoreView>` — one data store by id: a `table` store as an editable grid with CSV import and\n * export, a `kv` or `doc` store as an entry list with a value editor. Every read and write goes\n * through the embed's `data-stores` repo (`client.dataStores.*`); parsing, row building and the\n * `ifVersion` conflict rule are `@w6w/ui`'s data-store util, and the markup is ui's. This file owns\n * the queries, drafts and conflict state.\n *\n * A save sends the version the entry was loaded at (`ifVersion`). A stale one is a Reload prompt\n * on that row or editor, and nothing is re-sent without `ifVersion`. Scoped or IP-restricted\n * `tsec_` tokens can read a store but not write it (the server refuses).\n */\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport type { DataStoreEntry } from \"@w6w/sdk\";\nimport {\n CsvPanel,\n DataEntryEditor,\n DataEntryList,\n type DataStoreErrorLocator,\n DataTableGrid,\n type DataTableGridRow,\n NEW_ROW_ID,\n type RowDraft,\n type TableColumn,\n type DataStore as UiDataStore,\n buildRowValue,\n cellErrorsOf,\n csvFilenameOf,\n csvImportMessage,\n dirtyColumns,\n draftFromEntry,\n isVersionConflict,\n kvValueOf,\n kvValueTypeOf,\n locateDataStoreError,\n newRowDraft,\n parseDocText,\n remainingTtlSeconds,\n rowWriteOf,\n serializeCell,\n tableSchemaOf,\n} from \"@w6w/ui\";\nimport { type ReactNode, useState } from \"react\";\nimport { ConfirmModal } from \"../chrome/ConfirmModal.tsx\";\nimport { useEmbedClient } from \"../draft/client-context.ts\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n getEntry,\n useDataStoreQuery,\n useDeleteEntryMutation,\n useEntriesQuery,\n useExportCsvMutation,\n useImportCsvMutation,\n useInsertRowMutation,\n useSetEntryMutation,\n} from \"../repos/data-stores.ts\";\n\nexport interface DataStoreViewProps {\n /** The store's id (`ds_…`). */\n id: string;\n /** Omitted: the provider's project. `null` or `\"\"`: none; nothing is read and writes refuse. */\n project?: string | null;\n slots?: {\n /** Replaces the store's name / kind heading. `null`: none. */\n header?: ReactNode;\n };\n}\n\n/**\n * A thrown SDK failure as the locator the views place: `ApiError{status,code,raw}` with the\n * server's `{error:{code,message,field?,row?,column?}}` read from `raw`. The error's own `code`\n * stands in when the body carried none, so a conflict is never missed for want of an envelope.\n */\nexport function dataStoreErrorOf(e: unknown): DataStoreErrorLocator {\n const loc = locateDataStoreError(e);\n const code = (e as { code?: unknown } | null)?.code;\n return loc.code === undefined && typeof code === \"string\" && code !== \"\" ? { ...loc, code } : loc;\n}\n\n/** How much of a stored value the entry list's Value column shows before eliding. */\nconst PREVIEW_CHARS = 80;\n\n/** Save CSV text through the browser's download path; a no-op where there is no object URL. */\nfunction downloadCsv(filename: string, text: string): void {\n if (typeof URL === \"undefined\" || typeof URL.createObjectURL !== \"function\") return;\n const url = URL.createObjectURL(new Blob([text], { type: \"text/csv\" }));\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = filename;\n a.click();\n URL.revokeObjectURL(url);\n}\n\ninterface PanelProps {\n store: UiDataStore;\n project: string;\n}\n\nfunction TableView({ store, project }: PanelProps) {\n const schema = tableSchemaOf(store);\n const columns: readonly TableColumn[] = schema?.columns ?? [];\n const keyColumn = schema?.key ?? \"\";\n const [prefix, setPrefix] = useState(\"\");\n const [drafts, setDrafts] = useState<Record<string, RowDraft>>({});\n const [cellErrors, setCellErrors] = useState<Record<string, Record<string, string>>>({});\n const [conflicts, setConflicts] = useState<Record<string, true>>({});\n // Entries re-read by Reload: they win over the list until the next successful write.\n const [fresh, setFresh] = useState<Record<string, DataStoreEntry>>({});\n const [gridError, setGridError] = useState<string | null>(null);\n const [deleteKey, setDeleteKey] = useState<string | null>(null);\n const [csvResult, setCsvResult] = useState<{ ok: boolean; message: string } | null>(null);\n\n const client = useEmbedClient();\n const qc = useQueryClient();\n const entriesQuery = useEntriesQuery(store.id, project, prefix);\n const setMut = useSetEntryMutation();\n const insertMut = useInsertRowMutation();\n const deleteMut = useDeleteEntryMutation();\n const importMut = useImportCsvMutation();\n const exportMut = useExportCsvMutation();\n\n const entries = (entriesQuery.data?.pages.flatMap((p) => p.items) ?? []).map(\n (e) => fresh[e.key] ?? e,\n );\n const entryByKey = new Map(entries.map((e) => [e.key, e]));\n\n const gridRows: DataTableGridRow[] = [];\n const draftOf = (id: string): RowDraft | undefined => drafts[id];\n const newDraft = draftOf(NEW_ROW_ID);\n const rowOf = (id: string, draft: RowDraft, entry: DataStoreEntry | undefined) => {\n const base = entry === undefined ? null : draftFromEntry(entry, columns);\n gridRows.push({\n id,\n isNew: id === NEW_ROW_ID,\n cells: draft.cells,\n version: draft.version,\n dirty: base === null ? true : dirtyColumns(draft, base, columns).length > 0,\n conflict: conflicts[id] === true,\n cellErrors: cellErrors[id],\n });\n };\n if (newDraft !== undefined) rowOf(NEW_ROW_ID, newDraft, undefined);\n for (const entry of entries)\n rowOf(entry.key, draftOf(entry.key) ?? draftFromEntry(entry, columns), entry);\n\n const clearMessages = (id: string) => {\n setCellErrors((p) => omit(p, id));\n setConflicts((p) => omit(p, id));\n };\n const forgetDraft = (id: string) => {\n setDrafts((p) => omit(p, id));\n clearMessages(id);\n };\n\n function editCell(id: string, column: string, text: string) {\n const entry = entryByKey.get(id);\n const draft = draftOf(id) ?? (entry ? draftFromEntry(entry, columns) : newRowDraft(columns));\n setDrafts((p) => ({ ...p, [id]: { ...draft, cells: { ...draft.cells, [column]: text } } }));\n setCellErrors((p) => {\n const row = p[id];\n if (row === undefined || !(column in row)) return p;\n const next = omit(row, column);\n return Object.keys(next).length === 0 ? omit(p, id) : { ...p, [id]: next };\n });\n }\n\n async function save(id: string) {\n const entry = entryByKey.get(id);\n const draft = draftOf(id) ?? (entry ? draftFromEntry(entry, columns) : undefined);\n if (draft === undefined) return;\n setGridError(null);\n clearMessages(id);\n const built = buildRowValue(draft, columns);\n if (!built.ok) {\n setCellErrors((p) => ({ ...p, [id]: built.errors }));\n return;\n }\n const write = rowWriteOf(\n draft,\n built.value,\n remainingTtlSeconds(entry?.expiresAt ?? null, Date.now()),\n );\n try {\n if (write.kind === \"insert\") {\n await insertMut.mutateAsync({\n id: store.id,\n row: write.value,\n ttlSeconds: write.ttlSeconds,\n project,\n });\n } else {\n await setMut.mutateAsync({\n id: store.id,\n key: write.key,\n value: write.value,\n ifVersion: write.ifVersion,\n ttlSeconds: write.ttlSeconds,\n project,\n });\n }\n setFresh((p) => omit(p, id));\n forgetDraft(id);\n } catch (err) {\n const loc = dataStoreErrorOf(err);\n if (isVersionConflict(loc)) {\n setConflicts((p) => ({ ...p, [id]: true }));\n return;\n }\n const placed = cellErrorsOf(loc, columns);\n if (placed !== null) {\n setCellErrors((p) => ({ ...p, [id]: placed }));\n return;\n }\n setGridError(loc.message);\n }\n }\n\n async function reload(id: string) {\n try {\n const entry = await getEntry(client, store.id, id, project);\n setFresh((p) => ({ ...p, [id]: entry }));\n forgetDraft(id);\n await qc.invalidateQueries({ queryKey: [\"data-stores\"] });\n } catch (err) {\n setGridError(dataStoreErrorOf(err).message);\n }\n }\n\n function confirmDelete() {\n const key = deleteKey;\n setDeleteKey(null);\n if (key === null) return;\n if (key !== NEW_ROW_ID) deleteMut.mutate({ id: store.id, key, project });\n forgetDraft(key);\n }\n\n async function importFile(file: File) {\n setCsvResult(null);\n try {\n const res = await importMut.mutateAsync({ id: store.id, csv: await file.text(), project });\n setCsvResult(csvImportMessage({ status: 200, text: JSON.stringify(res) }));\n } catch (err) {\n const e = err as { status?: unknown; raw?: unknown };\n setCsvResult(\n typeof e.status === \"number\"\n ? csvImportMessage({ status: e.status, text: JSON.stringify(e.raw ?? null) })\n : { ok: false, message: dataStoreErrorOf(err).message },\n );\n }\n }\n\n async function exportCsv() {\n try {\n const text = await exportMut.mutateAsync({ id: store.id, project });\n downloadCsv(csvFilenameOf(null, store.name), text);\n setCsvResult(null);\n } catch (err) {\n setCsvResult({ ok: false, message: dataStoreErrorOf(err).message });\n }\n }\n\n return (\n <div>\n <CsvPanel\n result={csvResult}\n busy={exportMut.isPending}\n onImport={importFile}\n onRefuse={(message) => setCsvResult({ ok: false, message })}\n onExport={exportCsv}\n />\n <DataTableGrid\n columns={columns}\n keyColumn={keyColumn}\n rows={gridRows}\n error={gridError}\n loading={entriesQuery.isPending}\n hasMore={entriesQuery.hasNextPage}\n empty={<p className=\"muted small\">No rows match this key prefix.</p>}\n onCellChange={editCell}\n onSave={(id) => void save(id)}\n onDelete={setDeleteKey}\n onReload={(id) => void reload(id)}\n onAddRow={() => {\n if (NEW_ROW_ID in drafts) return;\n setDrafts((p) => ({ ...p, [NEW_ROW_ID]: newRowDraft(columns) }));\n setGridError(null);\n }}\n onLoadMore={() => void entriesQuery.fetchNextPage()}\n onSearch={setPrefix}\n />\n {deleteKey !== null && (\n <ConfirmModal\n title=\"Delete entry\"\n message={\n deleteKey === NEW_ROW_ID\n ? \"Discard this unsaved row?\"\n : `Delete \"${deleteKey}\"? This cannot be undone.`\n }\n confirmLabel=\"Delete\"\n onConfirm={confirmDelete}\n onClose={() => setDeleteKey(null)}\n />\n )}\n </div>\n );\n}\n\nfunction KvDocView({ store, project }: PanelProps) {\n const isDoc = store.kind === \"doc\";\n const kvType = kvValueTypeOf(store);\n const [prefix, setPrefix] = useState(\"\");\n const [selectedKey, setSelectedKey] = useState<string | null>(null);\n const [isNew, setIsNew] = useState(false);\n const [newKey, setNewKey] = useState(\"\");\n const [text, setText] = useState(\"\");\n const [valueError, setValueError] = useState<string | null>(null);\n const [conflict, setConflict] = useState(false);\n const [fresh, setFresh] = useState<Record<string, DataStoreEntry>>({});\n const [deleteKey, setDeleteKey] = useState<string | null>(null);\n\n const client = useEmbedClient();\n const qc = useQueryClient();\n const entriesQuery = useEntriesQuery(store.id, project, prefix);\n const setMut = useSetEntryMutation();\n const deleteMut = useDeleteEntryMutation();\n\n const entries = (entriesQuery.data?.pages.flatMap((p) => p.items) ?? []).map(\n (e) => fresh[e.key] ?? e,\n );\n const selected = selectedKey === null ? undefined : entries.find((e) => e.key === selectedKey);\n const editing = isNew || selectedKey !== null;\n\n const seedOf = (entry: DataStoreEntry): string =>\n isDoc ? JSON.stringify(entry.value ?? null, null, 2) : serializeCell(kvType, entry.value);\n const previewOf = (entry: DataStoreEntry): string => {\n const raw = seedOf(entry).replace(/\\s+/g, \" \");\n return raw.length > PREVIEW_CHARS ? `${raw.slice(0, PREVIEW_CHARS)}…` : raw;\n };\n\n function openEditor(entry: DataStoreEntry) {\n setSelectedKey(entry.key);\n setIsNew(false);\n setText(seedOf(entry));\n setValueError(null);\n setConflict(false);\n }\n function closeEditor() {\n setSelectedKey(null);\n setIsNew(false);\n setNewKey(\"\");\n setText(\"\");\n setValueError(null);\n setConflict(false);\n }\n\n async function save() {\n setValueError(null);\n setConflict(false);\n const parsed = isDoc ? parseDocText(text) : kvValueOf(kvType, text);\n if (!parsed.ok) {\n setValueError(parsed.message);\n return;\n }\n const key = isNew ? newKey.trim() : selectedKey;\n if (key === null || key === \"\") {\n setValueError(\"Enter a key.\");\n return;\n }\n try {\n await setMut.mutateAsync({\n id: store.id,\n key,\n value: parsed.value,\n // A new entry must not exist yet; an existing one is guarded by the version loaded.\n ifVersion: isNew ? 0 : (selected?.version ?? 0),\n ttlSeconds: isNew\n ? undefined\n : remainingTtlSeconds(selected?.expiresAt ?? null, Date.now()),\n project,\n });\n setFresh((p) => omit(p, key));\n closeEditor();\n } catch (err) {\n const loc = dataStoreErrorOf(err);\n if (isVersionConflict(loc)) setConflict(true);\n else setValueError(loc.message);\n }\n }\n\n async function reload() {\n if (selectedKey === null) return;\n try {\n const entry = await getEntry(client, store.id, selectedKey, project);\n setFresh((p) => ({ ...p, [selectedKey]: entry }));\n setText(seedOf(entry));\n setConflict(false);\n setValueError(null);\n await qc.invalidateQueries({ queryKey: [\"data-stores\"] });\n } catch (err) {\n setValueError(dataStoreErrorOf(err).message);\n }\n }\n\n async function confirmDelete() {\n const key = deleteKey;\n setDeleteKey(null);\n if (key === null) return;\n try {\n await deleteMut.mutateAsync({ id: store.id, key, project });\n if (key === selectedKey) closeEditor();\n } catch (err) {\n setValueError(dataStoreErrorOf(err).message);\n }\n }\n\n return (\n <div>\n <DataEntryList\n rows={entries.map((e) => ({ key: e.key, version: e.version, preview: previewOf(e) }))}\n loading={entriesQuery.isPending}\n empty={<p className=\"muted small\">No entries match this key prefix.</p>}\n hasMore={entriesQuery.hasNextPage}\n onOpen={(key) => {\n const entry = entries.find((e) => e.key === key);\n if (entry) openEditor(entry);\n }}\n onSearch={setPrefix}\n onNew={() => {\n setSelectedKey(null);\n setIsNew(true);\n setNewKey(\"\");\n setText(\"\");\n setValueError(null);\n setConflict(false);\n }}\n onLoadMore={() => void entriesQuery.fetchNextPage()}\n />\n {editing && (\n <DataEntryEditor\n kind={isDoc ? \"doc\" : \"kv\"}\n isNew={isNew}\n entryKey={selectedKey ?? undefined}\n newKey={newKey}\n version={selected?.version ?? null}\n expiresAt={selected?.expiresAt ?? null}\n text={text}\n error={valueError}\n conflict={conflict}\n saving={setMut.isPending || deleteMut.isPending}\n onDelete={isNew ? undefined : () => setDeleteKey(selectedKey)}\n onTextChange={(next) => {\n setText(next);\n setValueError(null);\n }}\n onKeyChange={setNewKey}\n onSave={() => void save()}\n onCancel={closeEditor}\n onReload={() => void reload()}\n />\n )}\n {deleteKey !== null && (\n <ConfirmModal\n title=\"Delete entry\"\n message={`Delete \"${deleteKey}\"? This cannot be undone.`}\n confirmLabel=\"Delete\"\n onConfirm={confirmDelete}\n onClose={() => setDeleteKey(null)}\n />\n )}\n </div>\n );\n}\n\n/** A copy of `obj` without `key` (the same object when `key` is absent). */\nfunction omit<T>(obj: Record<string, T>, key: string): Record<string, T> {\n if (!(key in obj)) return obj;\n const next = { ...obj };\n delete next[key];\n return next;\n}\n\nexport function DataStoreView({ id, project, slots }: DataStoreViewProps) {\n const p = useEditorProject(project);\n const storeQuery = useDataStoreQuery(id, p ?? undefined);\n const store = storeQuery.data as unknown as UiDataStore | undefined;\n\n let body: ReactNode;\n if (p == null) {\n body = <p className=\"muted\">No project selected.</p>;\n } else if (storeQuery.isError) {\n body = <p className=\"result error\">{dataStoreErrorOf(storeQuery.error).message}</p>;\n } else if (store === undefined) {\n body = <p className=\"muted\">Loading…</p>;\n } else if (store.kind === \"table\") {\n body = <TableView key={store.id} store={store} project={p} />;\n } else {\n body = <KvDocView key={store.id} store={store} project={p} />;\n }\n\n const header =\n slots?.header === undefined\n ? store && (\n <div>\n <h3>{store.name}</h3>\n <p className=\"muted small\">\n {store.kind} · {store.entryCount} {store.entryCount === 1 ? \"entry\" : \"entries\"}\n </p>\n </div>\n )\n : slots.header;\n\n return (\n <div className=\"w6w-embed-root\">\n <section className=\"section\">\n {header}\n {body}\n </section>\n </div>\n );\n}\n","/**\n * `<DataStoreList>` — a project's data stores (key-value, document, table), with in-place create\n * and archive. Rows render through `@w6w/ui`'s `DataStoreList`; this file owns the query, the\n * create dialog and the archive confirmation. Opening a store is the host's `onOpen` / `getHref`\n * (see `<DataStoreView>` for the store itself).\n */\nimport {\n ColumnsEditor,\n DATA_STORE_KINDS,\n DATA_STORE_KIND_LABEL,\n type DataStoreKind,\n SCALAR_TYPES,\n type ScalarType,\n type TableColumn,\n type DataStore as UiDataStore,\n DataStoreList as UiDataStoreList,\n errorPlacement,\n} from \"@w6w/ui\";\nimport type { MouseEvent, ReactNode } from \"react\";\nimport { useState } from \"react\";\nimport { ConfirmModal } from \"../chrome/ConfirmModal.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport { useEditorProject } from \"../project-context.ts\";\nimport {\n useArchiveDataStoreMutation,\n useCreateDataStoreMutation,\n useDataStoresQuery,\n} from \"../repos/data-stores.ts\";\nimport { dataStoreErrorOf } from \"./DataStoreView.tsx\";\n\nexport interface DataStoreListSlots {\n /** Replaces the section heading and its description (the New button stays). `null`: none. */\n header?: ReactNode;\n /** Replaces the empty-state copy. */\n empty?: ReactNode;\n}\n\nexport interface DataStoreListProps {\n /** Omitted: the provider's project. `null` or `\"\"`: none; nothing is read and writes refuse. */\n project?: string | null;\n /** The host decides what opening a row means; with `getHref` it may `preventDefault`. */\n onOpen?: (id: string, event: MouseEvent<Element>) => void;\n /** Given, a row's main area is a real `<a href>`; its click still calls `onOpen`. */\n getHref?: (id: string) => string;\n slots?: DataStoreListSlots;\n}\n\n/** The request-body fields the create dialog has a labelled error slot for. */\nconst FIELD_SLOTS: readonly string[] = [\"name\", \"kind\", \"description\", \"schema\"];\n\nfunction CreateDataStoreModal(props: { project: string; onClose: () => void }) {\n const [name, setName] = useState(\"\");\n const [description, setDescription] = useState(\"\");\n const [kind, setKind] = useState<DataStoreKind>(\"kv\");\n const [valueType, setValueType] = useState<ScalarType>(\"string\");\n const [columns, setColumns] = useState<TableColumn[]>([]);\n const [keyColumn, setKeyColumn] = useState(\"\");\n const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});\n const [columnErrors, setColumnErrors] = useState<Record<string, string>>({});\n const [formError, setFormError] = useState<string | null>(null);\n const createMut = useCreateDataStoreMutation();\n\n function submit() {\n setFieldErrors({});\n setColumnErrors({});\n setFormError(null);\n const input: { kind: DataStoreKind; name: string; description?: string; schema?: object } = {\n kind,\n name,\n };\n if (kind === \"kv\") input.schema = { valueType };\n if (kind === \"table\")\n input.schema = keyColumn === \"\" ? { columns } : { columns, key: keyColumn };\n if (description !== \"\") input.description = description;\n createMut.mutate(\n // The SDK's create body types `schema` as table columns only; the wire takes the S-2 shape\n // per kind, so the kv `{valueType}` schema is passed through as the host defines it.\n { input: input as Parameters<typeof createMut.mutate>[0][\"input\"], project: props.project },\n {\n onSuccess: () => props.onClose(),\n onError: (err) => {\n const loc = dataStoreErrorOf(err);\n const place = errorPlacement(loc);\n if (place.kind === \"cell\" && columns.some((c) => c.name === place.column)) {\n setColumnErrors({ [place.column]: loc.message });\n return;\n }\n if (place.kind === \"field\" && FIELD_SLOTS.includes(place.field)) {\n setFieldErrors({ [place.field]: loc.message });\n return;\n }\n setFormError(loc.message);\n },\n },\n );\n }\n\n return (\n <Modal title=\"New data store\" onClose={props.onClose}>\n <div className=\"modal-body\">\n <label className=\"field\">\n <span>Name</span>\n <input\n type=\"text\"\n data-testid=\"data-store-name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n placeholder=\"e.g. counters\"\n />\n </label>\n {fieldErrors.name !== undefined && (\n <div className=\"result error\" data-testid=\"data-store-field-error-name\">\n {fieldErrors.name}\n </div>\n )}\n <label className=\"field\">\n <span>Description</span>\n <input\n type=\"text\"\n value={description}\n onChange={(e) => setDescription(e.target.value)}\n placeholder=\"What this store holds\"\n />\n </label>\n <label className=\"field\">\n <span>Kind</span>\n <select\n data-testid=\"data-store-kind\"\n value={kind}\n onChange={(e) => {\n setKind(e.target.value as DataStoreKind);\n setKeyColumn(\"\");\n }}\n >\n {DATA_STORE_KINDS.map((k) => (\n <option key={k} value={k}>\n {DATA_STORE_KIND_LABEL[k]}\n </option>\n ))}\n </select>\n <span className=\"hint\">The kind is fixed once the store exists.</span>\n </label>\n {fieldErrors.kind !== undefined && <div className=\"result error\">{fieldErrors.kind}</div>}\n {kind === \"kv\" && (\n <label className=\"field\">\n <span>Value type</span>\n <select value={valueType} onChange={(e) => setValueType(e.target.value as ScalarType)}>\n {SCALAR_TYPES.map((t) => (\n <option key={t} value={t}>\n {t}\n </option>\n ))}\n </select>\n </label>\n )}\n {kind === \"table\" && (\n <ColumnsEditor\n columns={columns}\n onChange={setColumns}\n keyColumn={keyColumn}\n onKeyColumnChange={setKeyColumn}\n columnErrors={columnErrors}\n />\n )}\n {fieldErrors.schema !== undefined && (\n <div className=\"result error\">{fieldErrors.schema}</div>\n )}\n {formError !== null && (\n <div className=\"result error\" data-testid=\"data-store-form-error\">\n {formError}\n </div>\n )}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={props.onClose}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"data-store-create\"\n disabled={createMut.isPending}\n onClick={submit}\n >\n {createMut.isPending ? \"Creating…\" : \"Create\"}\n </button>\n </div>\n </Modal>\n );\n}\n\nexport function DataStoreList({ project, onOpen, getHref, slots }: DataStoreListProps) {\n const p = useEditorProject(project);\n const storesQuery = useDataStoresQuery(p ?? undefined);\n const archiveMut = useArchiveDataStoreMutation();\n const [creating, setCreating] = useState(false);\n const [pending, setPending] = useState<UiDataStore | null>(null);\n const [archiveError, setArchiveError] = useState<string | null>(null);\n\n const header =\n slots?.header === undefined ? (\n <div>\n <h3>Data stores</h3>\n <p className=\"muted small\">Key-value, document and table storage for this project.</p>\n </div>\n ) : (\n slots.header\n );\n\n return (\n <div className=\"w6w-embed-root\">\n <UiDataStoreList\n stores={(storesQuery.data ?? []) as unknown as UiDataStore[]}\n loading={storesQuery.isLoading}\n error={\n archiveError ??\n (storesQuery.error != null ? dataStoreErrorOf(storesQuery.error).message : null)\n }\n onOpen={onOpen}\n getHref={getHref}\n onArchive={(s) => {\n setArchiveError(null);\n setPending(s);\n }}\n busy={archiveMut.isPending}\n slots={{\n header,\n actions: (\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"data-store-new\"\n disabled={p == null}\n onClick={() => setCreating(true)}\n >\n + New data store\n </button>\n ),\n empty: slots?.empty,\n }}\n />\n\n {creating && p != null && (\n <CreateDataStoreModal project={p} onClose={() => setCreating(false)} />\n )}\n\n {pending && (\n <ConfirmModal\n title=\"Archive data store\"\n message={`Archive \"${pending.name}\" and its ${pending.entryCount} ${\n pending.entryCount === 1 ? \"entry\" : \"entries\"\n }? Workflows and the API can no longer reach it.`}\n confirmLabel=\"Archive\"\n onConfirm={() => {\n const store = pending;\n setPending(null);\n if (p == null) return;\n archiveMut.mutate(\n { id: store.id, project: p },\n { onError: (e) => setArchiveError(dataStoreErrorOf(e).message) },\n );\n }}\n onClose={() => setPending(null)}\n />\n )}\n </div>\n );\n}\n"],"names":["CallableKindList","props","kind","d","descriptorFor","importing","setImporting","useState","rows","row","isRowArchived","jsxs","jsx","CallableList","ImportSpecModal","functionsKey","endpointsKey","workflowsKey","_kind","id","_a","FunctionList","query","useFunctionsQuery","project","useEditorProject","creatingId","setCreatingId","newCallableId","FunctionIdentityModal","EndpointList","useEndpointsQuery","Fragment","isEndpointDraft","EndpointIdentityModal","WorkflowList","useWorkflowsQuery","createMut","useCreateWorkflowMutation","createError","setCreateError","t","blankDefinition","res","e","ReliabilityBoard","variant","limit","days","showChart","getHref","onOpen","showAllHref","onShowAll","slots","provided","useEmbedProject","resolved","effective","useProjectReliabilityQuery","empty","ReliabilityList","_b","preview","content","s","DocumentList","rowSlots","p","docsQuery","useDocumentsQuery","deleteMut","useDeleteDocumentMutation","modal","setModal","pending","setPending","header","EmptyState","columns","lead","footer","CallFromCodeButton","EditButton","DeleteButton","DataTable","DocumentFormModal","ConfirmModal","KIND_LABELS","kindLabel","TILE_VARIANT","isActivityKind","tileVariantFor","buildNameMaps","functions","workflows","functionNames","label","workflowNames","resolveTileTitle","entry","names","fallback","workflowId","left","links","pad2","n","formatTimestamp","iso","formatDuration","ms","startOfTodayIso","formatBucketLabel","bucket","day","OutcomeMark","ok","StatCard","value","HeadlineRow","title","headline","loading","h","ActivityTitle","text","target","click","event","BaseActivityTile","duration","ListItem","NamedActivityTile","TILES","RecentActivityTile","Tile","ActivitySummary","todayQuery","useDashboardStatsQuery","weekQuery","functionsQuery","workflowsQuery","useMemo","error","errorMessage","recent","series","weekBucket","_c","nothingYet","_d","_e","_f","r","isProjectScope","scope","RunHistory","own","setOwn","EMPTY_HISTORY_FILTERS","controlled","filters","onFiltersChange","next","HistoryView","Logs","rest","LogsView","DAY_MS","projectVendorIncidents","vendor","isOpenIncident","formatCalendarDay","daysBetween","fromIso","toMs","fromMs","incidentAgeCopy","nowMs","ageDays","startLabel","openPart","updateIso","updateDays","updateLabel","updatePart","vendorComponentEntries","components","uptimeDays","service","ERROR_KINDS","formatDay","formatStamp","Stat","hint","VendorPanel","displayName","unreadable","openIncidents","HealthStatusPill","k","name","comp","DailyVolumeChart","maxCalls","UptimeDetail","historyWindow","withTraffic","incidents","vendorEmptyLabel","HistoryTimeline","ErrorMixChart","errors","sum","max","CallLog","appId","useApiCallsQuery","ApiError","calls","call","i","BackLink","backHref","onBack","ServiceDetail","useReliabilityQuery","siteLabel","site","o","ConnectionDependentRoutes","routes","projectId","reconnecting","setReconnecting","ReconnectHost","ModelRoutesManager","ConnectionDependentRows","callables","onOpenCallable","CallableRows","c","sites","NO_ROWS","ConnectionList","addLabel","api","useW6WApi","qc","useQueryClient","useConnectionsQuery","lookupIds","connectionAppIdsToLookUp","byId","useEditorApps","del","useDeleteConnectionMutation","adding","setAdding","editing","setEditing","deleting","setDeleting","deps","useConnectionDependentsQuery","canEdit","actions","UiConnectionList","AddConnectionModal","connectionsKey","EditConnectionModal","connectionKey","DeleteConfirm","onClose","onConfirm","plain","plural","one","many","usedBy","consequences","x","Modal","relativeTime","then","secs","mins","hours","NOTICE_DISMISS_MS","NOTICE_ICON","ConnectionDetail","connectionId","onOpenAction","connQuery","useConnectionQuery","appsById","appSummary","resolveConnectionAppMeta","appDetailQuery","useAppQuery","savedTestsQuery","useSavedTestsQuery","savedTestsByAction","map","list","dependents","usedByRoutes","runHistory","useTestRunsQuery","editOpen","setEditOpen","actionFilter","setActionFilter","testMut","useTestConnectionMutation","testNotice","setTestNotice","useEffect","timer","runTest","sortedActions","a","b","filteredActions","q","conn","app","ConnectionHeader","IconButton","tests","run","NO_FILTER","grouped","major","minor","rateText","rate","parts","limitsText","m","maxInputTokens","maxOutputTokens","ModelCatalog","client","useEmbedClient","filter","useInfiniteQuery","modelCatalogKey","last","pageParam","listModelCatalog","models","costText","cost","costsText","costs","unpriced","itemCost","item","totalsTruncated","report","ModelUsage","modelUsageKey","getModelUsage","pages","totals","items","truncated","CredentialList","contract","useCredentialsQuery","shown","parseSource","v","fmt","CredentialDetail","credentialId","onOpenConnection","onDeleted","useCredentialQuery","useCredentialDependentsQuery","rotate","useRotateCredentialMutation","setStatus","useSetCredentialStatusMutation","useTestCredentialMutation","useDeleteCredentialMutation","secret","setSecret","rotateError","setRotateError","rotated","setRotated","testResult","setTestResult","testError","setTestError","confirming","setConfirming","blocking","setBlocking","actionError","setActionError","back","connected","disabled","doRotate","source","doTest","doDelete","dataStoreErrorOf","loc","locateDataStoreError","code","PREVIEW_CHARS","downloadCsv","filename","url","TableView","store","schema","tableSchemaOf","keyColumn","prefix","setPrefix","drafts","setDrafts","cellErrors","setCellErrors","conflicts","setConflicts","fresh","setFresh","gridError","setGridError","deleteKey","setDeleteKey","csvResult","setCsvResult","entriesQuery","useEntriesQuery","setMut","useSetEntryMutation","insertMut","useInsertRowMutation","useDeleteEntryMutation","importMut","useImportCsvMutation","exportMut","useExportCsvMutation","entries","entryByKey","gridRows","draftOf","newDraft","NEW_ROW_ID","rowOf","draft","base","draftFromEntry","dirtyColumns","clearMessages","omit","forgetDraft","editCell","column","newRowDraft","save","built","buildRowValue","write","rowWriteOf","remainingTtlSeconds","err","isVersionConflict","placed","cellErrorsOf","reload","getEntry","confirmDelete","key","importFile","file","csvImportMessage","exportCsv","csvFilenameOf","CsvPanel","message","DataTableGrid","KvDocView","isDoc","kvType","kvValueTypeOf","selectedKey","setSelectedKey","isNew","setIsNew","newKey","setNewKey","setText","valueError","setValueError","conflict","setConflict","selected","seedOf","serializeCell","previewOf","raw","openEditor","closeEditor","parsed","parseDocText","kvValueOf","DataEntryList","DataEntryEditor","obj","DataStoreView","storeQuery","useDataStoreQuery","body","FIELD_SLOTS","CreateDataStoreModal","setName","description","setDescription","setKind","valueType","setValueType","setColumns","setKeyColumn","fieldErrors","setFieldErrors","columnErrors","setColumnErrors","formError","setFormError","useCreateDataStoreMutation","submit","input","place","errorPlacement","DATA_STORE_KINDS","DATA_STORE_KIND_LABEL","SCALAR_TYPES","ColumnsEditor","DataStoreList","storesQuery","useDataStoresQuery","archiveMut","useArchiveDataStoreMutation","creating","setCreating","archiveError","setArchiveError","UiDataStoreList"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmBO,SAASA,GAA6DC,GAiB1E;AACD,QAAM,EAAE,MAAAC,MAASD,GACXE,IAAIC,GAAcF,CAAI,GACtB,CAACG,GAAWC,CAAY,IAAIC,EAAS,EAAK,GAE1CC,KAA2BP,EAAM,QAAQ,CAAA,GAAI,IAAI,CAACQ,OAAS;AAAA,IAC/D,GAAGR,EAAM,MAAMQ,CAAG;AAAA,IAClB,IAAIA,EAAI;AAAA,IACR,UAAUC,GAAcD,CAAG;AAAA,EAAA,EAC3B;AAEF,SACE,gBAAAE,EAAC,OAAA,EAAI,WAAU,kBACb,UAAA;AAAA,IAAA,gBAAAC;AAAA,MAACC;AAAA,MAAA;AAAA,QACC,MAAAL;AAAA,QACA,OAAOL,EAAE;AAAA,QACT,aAAaA,EAAE;AAAA,QACf,WAAWA,EAAE;AAAA,QACb,UAAUA,EAAE;AAAA,QACZ,cAAcA,EAAE;AAAA,QAChB,SAAS;AAAA,UACP,cAAcA,EAAE;AAAA,UAChB,YAAYA,EAAE;AAAA,UACd,eAAeA,EAAE;AAAA,QAAA;AAAA,QAEnB,SAASF,EAAM;AAAA,QACf,OAAOA,EAAM;AAAA,QACb,UAAUA,EAAM;AAAA,QAChB,UAAUA,EAAM;AAAA,QAChB,UAAU,MAAMK,EAAa,EAAI;AAAA,QACjC,QAAQL,EAAM;AAAA,QACd,SAASA,EAAM;AAAA,QACf,OAAOA,EAAM;AAAA,MAAA;AAAA,IAAA;AAAA,IAE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