Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(chat): add the run cards and the runs tray (#1787)
Cihan9c5da13ab0cd
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 51a8abc75..e5d56575b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3267,6 +3267,128 @@"itemsNeedYou": "{count, plural, one {# item} other {# items}} · {needsYou}"},"tick": "Done",+ "stepList": {+ "skipped": "Skipped",+ "waiting": "Waiting for you"+ },+ "runSteps": {+ "working": "Working on it",+ "workedFor": "Worked for {duration}",+ "stoppedAfter": "Stopped after {duration}",+ "failed": "Stopped: something went wrong",+ "steps": "{count, plural, one {# step} other {# steps}}",+ "stepsSources": "{steps, plural, one {# step} other {# steps}} · {sources, plural, one {# source} other {# sources}}",+ "stepsClock": "{steps, plural, one {# step} other {# steps}} · {clock}",+ "rows": "{count, plural, one {# row} other {# rows}}",+ "seconds": "{s}s",+ "minutes": "{m}m {s}s",+ "now": "Step {n}: {label}"+ },+ "planCard": {+ "head": "Here’s my plan",+ "uses": "Uses",+ "about": "About",+ "aiUsage": "AI usage",+ "aiUsageValue": "{value} of monthly limit",+ "outputs": "Outputs",+ "mode": "Mode:",+ "modes": {+ "ask_first": "Ask me first",+ "auto": "Auto, ask before changes",+ "full_auto": "Full auto"+ },+ "edit": "Edit plan",+ "doneEditing": "Done editing",+ "start": "Start",+ "askAdmin": "Ask your Admin",+ "moveUp": "Move up",+ "moveDown": "Move down",+ "remove": "Remove step",+ "notConnected": "{name} isn’t connected.",+ "connected": "Connected",+ "connect": "Connect {name}",+ "startNeedsPlan": "Starting a run needs a plan",+ "askNeedsPlan": "Sending a request needs a plan"+ },+ "approvalCard": {+ "stepOf": "Step {n} of {total}",+ "before": "Before",+ "after": "After",+ "approve": "Approve",+ "skip": "Skip",+ "edit": "Edit",+ "cancel": "Cancel",+ "saveAndApprove": "Save & approve",+ "newText": "New text",+ "dontAskAgain": "Don’t ask again for this kind of change",+ "dontAskAgainTip": "Only for you, and only where your Admin’s tool policy allows it",+ "approved": "Step {n} approved",+ "skipped": "Step {n} skipped",+ "done": "Done",+ "working": "Working…",+ "retry": "Retry",+ "preview": "Preview",+ "sources": "Sources",+ "approveNeedsPlan": "Approving changes needs a plan",+ "clickNeedsPlan": "Going live needs a plan"+ },+ "resultCard": {+ "generated": "Generated {date} · {time}",+ "generatedTip": "Generated {full}",+ "dataAsOf": "Data as of {date}, {time}",+ "dataAsOfTip": "Data as of {full}",+ "open": "Open",+ "files": "What I made",+ "summary": "Result"+ },+ "denialCard": {+ "asked": "You asked",+ "why": "Why not",+ "who": "Who can",+ "next": "Next",+ "requestGoes": "Your request goes to the workspace Admins, in the app",+ "actions": {+ "ask_admin": "Ask your Admin",+ "see_access": "See your access ↗",+ "upgrade": "Upgrade",+ "choose_plan": "Choose a plan",+ "compare_plans": "Compare plans",+ "open_policy": "See tool policy ↗"+ },+ "sent": "Sent",+ "sentToast": "Sent to your Admins",+ "sendFailed": "Couldn’t send it. Try again.",+ "askNeedsPlan": "Sending a request needs a plan"+ },+ "errorCard": {+ "failed": "Failed",+ "stoppedAt": "Stopped at step {n} of {total}",+ "stopped": "Stopped: something went wrong",+ "retry": "Retry",+ "retryStep": "Retry step {n}",+ "retryFrom": "Retry starts again from step {n}",+ "retryNeedsPlan": "Retrying a run needs a plan"+ },+ "runsTray": {+ "label": "Your runs",+ "title": "Your runs",+ "button": "{count, plural, =0 {Runs} other {# running}}",+ "needsYouTip": "{count, plural, one {# needs you} other {# need you}}",+ "summary": "{running} running · {needsYou, plural, one {# needs you} other {# need you}}",+ "summaryRunning": "{running} running",+ "empty": "No runs yet. Runs keep going when you leave a page.",+ "failedToLoad": "Couldn’t load your runs.",+ "newChat": "New chat",+ "stepOf": "Step {n} of {total}",+ "stepOfLabel": "Step {n} of {total} · {label}",+ "needsYou": "Needs your OK · step {n} of {total}",+ "paused": "Paused · step {n} of {total}",+ "done": "Done {time}",+ "failed": "Stopped · step {n} of {total}",+ "starting": "Starting…",+ "review": "Review",+ "open": "Open"+ },"preview": {"title": "Chat pieces","description": "The agent's shared pieces in every state, for design sign-off. Nothing here runs.",@@ -3297,7 +3419,52 @@"onIcon": "On a menu icon","countNeedsYou": "Count, 1 needs you","countNone": "Count, nothing needs you",- "tickPop": "Pops in once"+ "tickPop": "Pops in once",+ "cards": {+ "title": "Run cards",+ "description": "Plan, approval, result, out-of-permission and failed-run cards, and the runs tray, in every state. Sample data; nothing here runs.",+ "sections": {+ "plan": "Plan card",+ "runSteps": "Run steps",+ "approval": "Approval card",+ "execute": "Click card (EXECUTE)",+ "result": "Result card",+ "denial": "Out-of-permission answer",+ "failed": "Failed run",+ "tray": "Runs tray"+ },+ "states": {+ "planAuto": "Auto, ask before changes",+ "planFullAuto": "Full auto, a tool not connected",+ "planReadOnly": "Analyst: read-only",+ "stepsRunning": "Running",+ "stepsWaiting": "Waiting for you",+ "stepsDone": "Done",+ "stepsSingle": "Done, one step",+ "stepsStopped": "Stopped",+ "stepsError": "Failed",+ "pendingDontAsk": "Waiting, Don’t ask again allowed",+ "pendingNoDontAsk": "Waiting, Don’t ask again not allowed",+ "saving": "Saving",+ "error": "Failed, with Retry",+ "approved": "Approved",+ "skipped": "Skipped",+ "executePending": "Waiting for the click",+ "executeDisabled": "Before the draft is approved",+ "executeSaving": "Publishing",+ "executeDone": "Published",+ "resultDone": "Done",+ "resultNeedsClick": "Done but for a click",+ "denialRole": "Role",+ "denialPlan": "Plan",+ "denialPolicy": "Policy",+ "failedStep": "A step failed",+ "failedRun": "The run failed",+ "trayRuns": "With runs (click to open)",+ "trayEmpty": "No runs",+ "trayLive": "Live: your runs and this brand’s"+ }+ }}},"chatDenial": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/_card-samples.ts b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/_card-samples.tsnew file mode 100644index 000000000..5ec1f3585--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/_card-samples.ts@@ -0,0 +1,359 @@+import type { ChatStep } from '@/lib/chat/events';+import type { TrayResponse } from '@/lib/chat/runs-tray';+import type { PlanStep } from '@/components/agentic/plan-card';+import type { StepRow } from '@/components/agentic/step-list';++/**+ * The run cards' sample data for the design preview (Chat P0, D2), taken+ * from the approved Chat v2 mockups (CHAT-mockup-v2.html `#s-plan`,+ * `#s-need`, `#s-done`, `#s-denied`, `#s-failed`). In the product the server+ * sends these words (the label registry, the precedence's denial), so they+ * are data here, not the app's own copy.+ */++export const TASKS_PLAN = {+ title: 'Action Center tasks · 4 due',+ due: 'Due Fri, Oct 30',+ uses: 'Action Center · 52 sources · 2 live pages',+ connections: [+ { name: 'Google Search Console', connected: true },+ { name: 'Webflow', connected: true },+ ],+ time: '6 min',+ aiUsage: '~2%',+ outputs: 'FAQ draft, schema code, report',+ steps: [+ {+ label: 'Read the 4 tasks and rank them by impact',+ detail: 'Action Center · citations last 30 days',+ cls: 'read',+ },+ {+ label: 'Check /pricing and /features as AI engines see them',+ detail: 'Live page read · schema check',+ cls: 'read',+ },+ {+ label: 'Write an FAQ block for /pricing from 18 fan-outs',+ detail: 'Draft in this chat · your brand facts',+ cls: 'read',+ },+ {+ label: 'Change one cited passage on /pricing',+ detail: 'Cited 12× · I show you the change first',+ cls: 'write',+ },+ {+ label: 'Push the FAQ, FAQPage schema and 2 link fixes to Webflow as a draft',+ detail: 'Webflow draft · nothing goes live',+ cls: 'write',+ },+ {+ label: 'Publish the Webflow draft',+ detail: 'Goes live on ansvisor.com/pricing',+ cls: 'execute',+ },+ ] satisfies PlanStep[],+};++export const SHOPPING_PLAN = {+ title: 'AI shopping readiness · 48 products',+ uses: 'Product Visibility · 48 products',+ connections: [{ name: 'Shopify', connected: false }],+ time: '6 min',+ aiUsage: '~2%',+ outputs: 'Fix list, feed changes',+ steps: [+ { label: 'Read product pages and feed', detail: 'Shopify · 48 products', cls: 'read' },+ {+ label: 'Check against ChatGPT Shopping and Google Shopping',+ detail: 'Product Visibility',+ cls: 'read',+ },+ { label: 'Save the fixes as drafts', detail: 'Shopify drafts', cls: 'write' },+ { label: 'Push the feed', detail: 'Leaves your workspace', cls: 'execute' },+ ] satisfies PlanStep[],+};++export const QUALITY_PLAN = {+ title: 'Quality pass · 3 drafts',+ uses: 'Content · 3 drafts',+ time: '4 min',+ aiUsage: '~1%',+ outputs: '3 improved drafts, your to-do list',+ steps: [+ { label: 'Score the 3 drafts under 60', detail: 'E-E-A-T · Trust · Readability', cls: 'read' },+ { label: 'Save the fixes to the drafts', detail: 'Content Editor drafts', cls: 'write' },+ { label: 'List what only you can add', detail: 'Quotes, first-hand data, author', cls: 'read' },+ ] satisfies PlanStep[],+};++const step = (+ n: number,+ status: ChatStep['status'],+ label: string,+ detail?: string,+ kind: ChatStep['kind'] = 'read',+): ChatStep => ({ n, kind, status, label, ...(detail ? { detail } : {}) });++/** A run's steps at one moment of the Action Center tasks run. */+export const RUN_STEPS = {+ running: [+ step(1, 'done', 'Read Action Center', '4 tasks due this week'),+ step(+ 2,+ 'done',+ 'Opened ansvisor.com/pricing',+ 'No FAQ block and no FAQPage schema found',+ 'open_page',+ ),+ step(3, 'running', 'Drafted FAQ block · /pricing', 'From 18 fan-outs', 'write'),+ ],+ waiting: [+ step(1, 'done', 'Read Action Center', '4 tasks due this week'),+ step(2, 'done', 'Opened ansvisor.com/pricing', undefined, 'open_page'),+ step(3, 'done', 'Drafted FAQ block · /pricing', undefined, 'write'),+ step(4, 'waiting', 'Change one cited passage on /pricing', 'Waiting for your OK', 'write'),+ ],+ done: [+ step(1, 'done', 'Thinking · 3s', '3 tasks are due this week.', 'thinking'),+ step(2, 'done', 'Read Action Center', '4 tasks due this week'),+ step(+ 3,+ 'done',+ 'Read Citations',+ 'Pricing prompts · Last 30 days · ChatGPT, Perplexity · 42 rows',+ ),+ step(4, 'done', 'Opened ansvisor.com/pricing', undefined, 'open_page'),+ step(5, 'done', 'Read Prompts', '12 prompts'),+ step(6, 'done', 'Checked facts', 'Plan names and prices match your Billing page', 'check'),+ step(7, 'done', 'Saved draft in Content', 'FAQ block · /pricing', 'write'),+ ],+ single: [+ {+ ...step(1, 'done', 'Read Citations', 'Perplexity · Last 30 days'),+ rowCount: 18,+ },+ ],+ stopped: [+ step(1, 'done', 'Read Action Center', '4 tasks due this week'),+ step(2, 'skipped', 'Opened ansvisor.com/pricing', undefined, 'open_page'),+ ],+ error: [+ step(1, 'done', 'Read Action Center', '4 tasks due this week'),+ step(2, 'error', 'Read Citations', 'Timed out'),+ ],+} satisfies Record<string, ChatStep[]>;++export const APPROVAL_HEAD = {+ title: 'I need your OK on one change',+ subtitle: 'Step 4 of 6 · Action Center tasks',+ note: 'The run waits up to 7 days for you, then stops. Nothing changes until you answer.',+};++export const APPROVAL = {+ title: 'Change a cited passage on /pricing',+ badge: 'Cited 12× last month',+ why: 'ChatGPT cites this passage, but it says “7 platforms” on Starter. Your pricing page says Starter covers ChatGPT and Copilot.',+ change: {+ before: 'Every plan tracks all 7 AI platforms, including Claude.',+ after:+ 'Starter tracks ChatGPT and Copilot. Growth adds Gemini, Perplexity, AI Overviews and AI Mode. Claude is on Enterprise.',+ },+ sources: [+ 'Brand fact · Plans (approved)',+ 'Cited page · /pricing',+ 'Fan-out · ansvisor plans platforms',+ ],+ dontAskAgainLabel: 'Don’t ask again for brand-fact fixes',+ doneLabel: 'cited passage changed',+};++export const PUSH_APPROVAL = {+ title: 'Push to Webflow as a draft',+ items: [+ { icon: '≡', title: 'FAQ block · 6 questions', detail: 'New section on /pricing' },+ { icon: '{ }', title: 'FAQPage schema', detail: 'JSON-LD in the page head' },+ { icon: '↗', title: '2 broken links fixed', detail: '/pricing → /plans, /features#api → /api' },+ ],+ note: 'Draft only · nothing goes live',+};++export const PUBLISH = {+ title: 'Publish the Webflow draft for /pricing',+ summary:+ 'FAQ block (6 questions), FAQPage schema, 1 changed passage and 2 link fixes · Webflow draft “Pricing”',+ note: 'Goes live on ansvisor.com/pricing · same in every mode',+ actionLabel: 'Publish',+ busyLabel: 'Publishing…',+ previewLabel: 'Preview in Webflow',+ disabledReason: 'After the draft is approved',+ doneLabel: 'Published to ansvisor.com/pricing · 14:32 · by you',+};++export const RESULT = {+ done: {+ title: 'Done. 4 tasks are ready for you to close.',+ summary: '6 of 6 steps · Auto (Haiku 5.5 + Sonnet 5.5) · 2% of monthly AI limit',+ },+ needsClick: {+ title: 'Ready to go live. Publishing needs your click.',+ summary: '5 of 6 steps · Auto (Haiku 5.5 + Sonnet 5.5) · 2% of monthly AI limit',+ },+ generatedAt: '2026-10-26T11:32:00Z',+ dataAsOf: '2026-10-26T05:00:00Z',+ timeZone: 'Europe/Istanbul',+ kpis: [+ { label: 'Tasks ready', value: '4', note: 'of 4' },+ { label: 'Changes', value: '2', note: 'you approved 2' },+ { label: 'First impact check', value: 'Nov 2', note: 'day 7 · 14 · 30 · 90' },+ ],+ files: [+ {+ icon: '≡',+ title: 'FAQ block for /pricing',+ meta: '6 questions · HTML + Markdown · in Files',+ href: '/dashboard/content/library',+ },+ { icon: '{ }', title: 'FAQPage schema', meta: 'JSON-LD · in the Webflow draft' },+ // Not a path in the app: no Open.+ {+ icon: '▤',+ title: 'What I did and why',+ meta: 'Report · 1 page',+ href: 'https://example.com/report',+ },+ ],+ note: 'You close tasks in Action Center. I never mark them done.',+ primary: {+ label: 'Close tasks in Action Center',+ href: '/dashboard/action-center',+ action: 'done.closeTasksInActionCenter',+ },+} as const;++export const DENIALS = {+ role: {+ title: 'I can’t add these prompts for you',+ subtitle: 'Answered in 1 s · you are signed in as Analyst',+ asked: 'Add 5 prompts to Tracked Prompts for Ansvisor.',+ askedItems: [+ 'best aeo tools',+ 'aeo vs seo',+ 'ai visibility tracker',+ 'track brand in perplexity',+ 'llms.txt generator',+ ],+ why: 'Your role is Analyst. Adding prompts needs Manager or Admin.',+ whySource: 'Role rule · Settings › Team › Roles & access',+ whoCan: 'Admins and Managers can do this.',+ nextActions: ['ask_admin', 'see_access'],+ },+ plan: {+ title: 'Full auto needs Growth',+ subtitle: 'Answered in 1 s · you are signed in as Admin · preview as Starter',+ asked: 'Run /winback in Full auto, so drafts are saved without asking you first.',+ why: 'Full auto needs Growth. Your plan: Starter.',+ whySource: 'Plan rule · Billing › Plans',+ whoCan: 'Admins can change the plan.',+ nextActions: ['upgrade', 'compare_plans'],+ extra: {+ label: 'Growth adds',+ items: [+ { title: 'Full auto', detail: 'agents apply changes for you, logged and undoable' },+ { title: '4 more AI platforms', detail: 'Gemini, Perplexity, AI Overviews, AI Mode' },+ {+ title: 'Open pull request and MCP write',+ detail: 'ship fixes as PRs, act from Claude, ChatGPT, Cursor',+ },+ ],+ note: '$249 a month · $200 more than Starter',+ },+ },+ policy: {+ title: 'Your Admin set this tool to Never',+ subtitle: 'Answered in 1 s · you are signed in as Manager',+ asked: 'Send 4 outreach emails from /wrongclaim to third-party sites.',+ why: 'Your Admin set this tool to Never: Send outreach email. Chat can’t run it for anyone in this workspace.',+ whySource: 'Tool policy · Settings › Chat',+ whoCan: 'Admins can change the tool policy.',+ nextActions: ['ask_admin', 'open_policy', 'see_access'],+ },+} as const;++export const DENIAL_FOOTNOTE = 'Nothing was changed · nothing outside your access was shown';++export const FAILED = {+ title: 'Merchant feed fix · EU',+ reason: 'Google Merchant Center isn’t connected · nothing was changed',+ connect: 'Connect Google Merchant Center',+ steps: [+ { n: 1, label: 'Read 48 products', detail: 'Product Visibility · EU', state: 'done' },+ {+ n: 2,+ label: 'Update 12 titles in Google Merchant Center',+ detail: 'Google Merchant Center isn’t connected',+ state: 'failed',+ pill: 'asks',+ },+ {+ n: 3,+ label: 'Push the feed',+ detail: 'Leaves your workspace',+ state: 'pending',+ pill: 'click',+ },+ ] satisfies StepRow[],+ runReason: 'The answer stopped before it was done · Retry sends your message again',+};++export const TRAY: TrayResponse = {+ running: 1,+ needsYou: 1,+ runs: [+ {+ source: 'chat',+ state: 'needsYou',+ title: 'Action Center tasks',+ step: 4,+ steps: 6,+ stepLabel: 'Change one cited passage on /pricing',+ startedAt: '2026-10-26T13:02:00Z',+ finishedAt: null,+ href: '/dashboard/action-center',+ },+ {+ source: 'chat',+ state: 'running',+ title: 'Win back citations · /features',+ step: 2,+ steps: 5,+ stepLabel: 'Comparing cited pages',+ startedAt: '2026-10-26T12:40:00Z',+ finishedAt: null,+ href: '/dashboard/citations',+ },+ {+ source: 'content',+ state: 'done',+ title: 'Weekly citations report',+ step: 3,+ steps: 3,+ stepLabel: 'Checking sources',+ startedAt: '2026-10-26T04:58:00Z',+ finishedAt: '2026-10-26T05:02:00Z',+ href: '/dashboard/content/library',+ },+ {+ source: 'chat',+ state: 'failed',+ title: 'Merchant feed fix · EU',+ step: 2,+ steps: 3,+ stepLabel: 'Update 12 titles in Google Merchant Center',+ startedAt: '2026-10-26T04:30:00Z',+ finishedAt: '2026-10-26T04:31:00Z',+ href: '/dashboard/shopping',+ },+ ],+};diff --git a/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/_cards-preview.tsx b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/_cards-preview.tsxnew file mode 100644index 000000000..59962b336--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/_cards-preview.tsx@@ -0,0 +1,271 @@+'use client';++import type { ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import { useBrandStore } from '@/stores/use-brand-store';+import { PlanCard } from '@/components/agentic/plan-card';+import { RunSteps } from '@/components/agentic/run-steps';+import { ApprovalCard } from '@/components/agentic/approval-card';+import { AgentHead } from '@/components/agentic/agent-card';+import { ResultCard } from '@/components/agentic/result-card';+import { DenialCard } from '@/components/agentic/denial-card';+import { ErrorCard } from '@/components/agentic/error-card';+import { RunsTray, RunsTrayView } from '@/components/agentic/runs-tray';+import {+ APPROVAL,+ APPROVAL_HEAD,+ DENIAL_FOOTNOTE,+ DENIALS,+ FAILED,+ PUBLISH,+ PUSH_APPROVAL,+ QUALITY_PLAN,+ RESULT,+ RUN_STEPS,+ SHOPPING_PLAN,+ TASKS_PLAN,+ TRAY,+} from './_card-samples';++const noop = () => {};+/** Ask your Admin in the preview: answers after a moment, as B2's request will. */+const sendLater = () => new Promise<void>((resolve) => setTimeout(resolve, 600));++function Group({ title, children }: { title: string; children: ReactNode }) {+ return (+ <section className="rounded-[14px] border bg-card p-4 shadow-[0_1px_2px_rgba(10,10,10,.04)]">+ <h2 className="mb-4 text-sm font-semibold">{title}</h2>+ <div className="grid gap-6">{children}</div>+ </section>+ );+}++/** One card in one state, its state's name above it, at the conversation's width. */+function State({ caption, children }: { caption: string; children: ReactNode }) {+ return (+ <figure className="m-0 max-w-[760px]">+ <figcaption className="mb-2 text-xs text-muted-foreground">{caption}</figcaption>+ {children}+ </figure>+ );+}++/**+ * The run cards for design sign-off (Chat P0, D2): each card in each state,+ * with the approved mockups' sample data, and the runs tray, also live.+ */+export function CardsPreview() {+ const t = useTranslations('agentic.preview.cards');+ const s = (key: string) => t(`states.${key}` as never);+ const brandId = useBrandStore((state) => state.activeBrandId);+ const stepOf = (n: number) => ({ n, total: 6 });++ return (+ <div data-slot="cards-preview" className="space-y-6">+ <div>+ <h2 className="text-xl font-bold tracking-tight">{t('title')}</h2>+ <p className="text-sm text-muted-foreground">{t('description')}</p>+ </div>++ <Group title={t('sections.plan')}>+ <State caption={s('planAuto')}>+ <PlanCard {...TASKS_PLAN} mode="auto" onStart={noop} />+ </State>+ <State caption={s('planFullAuto')}>+ <PlanCard {...SHOPPING_PLAN} mode="full_auto" onStart={noop} onConnect={noop} />+ </State>+ <State caption={s('planReadOnly')}>+ <PlanCard {...QUALITY_PLAN} mode="auto" canStart={false} onAskAdmin={noop} />+ </State>+ </Group>++ <Group title={t('sections.runSteps')}>+ <State caption={s('stepsRunning')}>+ <RunSteps status="running" steps={RUN_STEPS.running} workingMs={41_000} />+ </State>+ <State caption={s('stepsWaiting')}>+ <RunSteps status="waiting" steps={RUN_STEPS.waiting} workingMs={63_000} />+ </State>+ <State caption={s('stepsDone')}>+ <RunSteps status="done" steps={RUN_STEPS.done} workingMs={72_000} sources={4} />+ </State>+ <State caption={s('stepsSingle')}>+ <RunSteps status="done" steps={RUN_STEPS.single} workingMs={4_000} sources={1} />+ </State>+ <State caption={s('stepsStopped')}>+ <RunSteps status="stopped" steps={RUN_STEPS.stopped} workingMs={41_000} />+ </State>+ <State caption={s('stepsError')}>+ <RunSteps status="error" steps={RUN_STEPS.error} workingMs={30_000} />+ </State>+ </Group>++ <Group title={t('sections.approval')}>+ <State caption={s('pendingDontAsk')}>+ <AgentHead state="waiting" {...APPROVAL_HEAD} />+ <ApprovalCard+ {...APPROVAL}+ step={stepOf(4)}+ canDontAskAgain+ onApprove={noop}+ onSkip={noop}+ />+ </State>+ <State caption={s('pendingNoDontAsk')}>+ <ApprovalCard {...PUSH_APPROVAL} step={stepOf(5)} onApprove={noop} onSkip={noop} />+ </State>+ <State caption={s('saving')}>+ <ApprovalCard {...APPROVAL} step={stepOf(4)} canDontAskAgain status="saving" />+ </State>+ <State caption={s('error')}>+ <ApprovalCard+ {...PUSH_APPROVAL}+ step={stepOf(5)}+ status="error"+ error="Webflow didn’t answer. Nothing was changed."+ onApprove={noop}+ onSkip={noop}+ />+ </State>+ <State caption={s('approved')}>+ <ApprovalCard {...APPROVAL} step={stepOf(4)} status="approved" />+ </State>+ <State caption={s('skipped')}>+ <ApprovalCard {...APPROVAL} step={stepOf(4)} status="skipped" />+ </State>+ </Group>++ <Group title={t('sections.execute')}>+ <State caption={s('executePending')}>+ <ApprovalCard+ kind="execute"+ {...PUBLISH}+ disabledReason={undefined}+ step={stepOf(6)}+ onPreview={noop}+ onApprove={noop}+ />+ </State>+ <State caption={s('executeDisabled')}>+ <ApprovalCard kind="execute" {...PUBLISH} step={stepOf(6)} onPreview={noop} />+ </State>+ <State caption={s('executeSaving')}>+ <ApprovalCard+ kind="execute"+ {...PUBLISH}+ disabledReason={undefined}+ step={stepOf(6)}+ status="saving"+ onPreview={noop}+ />+ </State>+ <State caption={s('executeDone')}>+ <ApprovalCard kind="execute" {...PUBLISH} step={stepOf(6)} status="approved" />+ </State>+ </Group>++ <Group title={t('sections.result')}>+ <State caption={s('resultDone')}>+ <ResultCard+ state="done"+ {...RESULT.done}+ generatedAt={RESULT.generatedAt}+ dataAsOf={RESULT.dataAsOf}+ timeZone={RESULT.timeZone}+ run={{ steps: RUN_STEPS.done, workingMs: 340_000, sources: 4 }}+ kpis={[...RESULT.kpis]}+ files={[...RESULT.files]}+ note={RESULT.note}+ primary={RESULT.primary}+ />+ </State>+ <State caption={s('resultNeedsClick')}>+ <ResultCard+ state="needsClick"+ {...RESULT.needsClick}+ generatedAt={RESULT.generatedAt}+ dataAsOf={RESULT.dataAsOf}+ timeZone={RESULT.timeZone}+ kpis={[...RESULT.kpis]}+ files={[...RESULT.files]}+ note={RESULT.note}+ primary={RESULT.primary}+ before={+ <ApprovalCard+ kind="execute"+ {...PUBLISH}+ disabledReason={undefined}+ step={stepOf(6)}+ onPreview={noop}+ onApprove={noop}+ />+ }+ />+ </State>+ </Group>++ <Group title={t('sections.denial')}>+ <State caption={s('denialRole')}>+ <DenialCard+ {...DENIALS.role}+ askedItems={[...DENIALS.role.askedItems]}+ nextActions={[...DENIALS.role.nextActions]}+ footnote={DENIAL_FOOTNOTE}+ onAskAdmin={sendLater}+ />+ </State>+ <State caption={s('denialPlan')}>+ <DenialCard+ {...DENIALS.plan}+ nextActions={[...DENIALS.plan.nextActions]}+ extra={{ ...DENIALS.plan.extra, items: [...DENIALS.plan.extra.items] }}+ footnote={DENIAL_FOOTNOTE}+ />+ </State>+ <State caption={s('denialPolicy')}>+ <DenialCard+ {...DENIALS.policy}+ nextActions={[...DENIALS.policy.nextActions]}+ footnote={DENIAL_FOOTNOTE}+ onAskAdmin={sendLater}+ />+ </State>+ </Group>++ <Group title={t('sections.failed')}>+ <State caption={s('failedStep')}>+ <ErrorCard+ title={FAILED.title}+ reason={FAILED.reason}+ steps={FAILED.steps}+ failedStep={2}+ onRetry={noop}+ extraAction={+ <Button data-action="integrations.connect" variant="outline" onClick={noop}>+ {FAILED.connect}+ </Button>+ }+ />+ </State>+ <State caption={s('failedRun')}>+ <ErrorCard title={TASKS_PLAN.title} reason={FAILED.runReason} steps={[]} onRetry={noop} />+ </State>+ </Group>++ <Group title={t('sections.tray')}>+ <div className="flex flex-wrap items-start gap-x-8 gap-y-5">+ <State caption={s('trayRuns')}>+ <RunsTrayView data={TRAY} />+ </State>+ <State caption={s('trayEmpty')}>+ <RunsTrayView data={{ runs: [], running: 0, needsYou: 0 }} />+ </State>+ <State caption={s('trayLive')}>+ <RunsTray brandId={brandId} />+ </State>+ </div>+ </Group>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.test.tsxindex bafc4f074..5af627f8a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.test.tsx@@ -1,12 +1,12 @@-import { act } from 'react';+import { act, type ReactNode } from 'react';import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../messages/en.json';/**- * The Chat pieces preview (Chat P0, D1): there only with the new Chat on for- * the workspace, and every piece in every state on it.+ * The Chat pieces preview (Chat P0, D1 and D2): there only with the new Chat+ * on for the workspace, and every piece and run card in every state on it.*/const session = vi.hoisted(() => ({@@ -29,6 +29,13 @@ const notFound = vi.hoisted(() =>}),);vi.mock('next/navigation', () => ({ notFound }));+vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));import ChatPiecesPreviewPage from './page';@@ -47,12 +54,20 @@ beforeEach(() => {notFound.mockClear();vi.stubEnv('CHAT_AGENTIC', 'true');vi.stubEnv('CHAT_AGENTIC_ORGS', '');+ // The live runs tray reads its runs.+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () => new Response(JSON.stringify({ ok: true, runs: [], running: 0, needsYou: 0 })),+ ),+ );});afterEach(() => {act(() => root.unmount());container.remove();vi.unstubAllEnvs();+ vi.unstubAllGlobals();});async function render() {@@ -66,6 +81,9 @@ async function render() {);}const slots = (slot: string) => container.querySelectorAll(`[data-slot="${slot}"]`);+/** D1's pieces on their own, without the ones inside D2's run cards. */+const pieces = (slot: string) =>+ [...slots(slot)].filter((el) => !el.closest('[data-slot="cards-preview"]'));describe('the Chat pieces preview', () => {it.each([undefined, '', 'false'])('is not found with CHAT_AGENTIC=%s', async (value) => {@@ -91,7 +109,7 @@ describe('the Chat pieces preview', () => {await render();expect(notFound).not.toHaveBeenCalled();// 5 states in 3 sizes, and the 5 still ones of the Agents list.- const avatars = [...slots('agent-avatar')] as HTMLElement[];+ const avatars = pieces('agent-avatar') as HTMLElement[];const states = new Set(['idle', 'working', 'waiting', 'done', 'failed']);const live = avatars.filter((el) => el.dataset.tone === 'live');const muted = avatars.filter((el) => el.dataset.tone === 'muted');@@ -99,20 +117,52 @@ describe('the Chat pieces preview', () => {expect(new Set(live.map((el) => el.dataset.state))).toEqual(states);expect(muted).toHaveLength(5);expect(new Set(muted.map((el) => el.dataset.state))).toEqual(states);- expect(slots('status-pill')).toHaveLength(9);- expect(slots('approval-pill')).toHaveLength(5);- expect(slots('step-marker')).toHaveLength(5);- expect(slots('list-dot')).toHaveLength(6);- expect(slots('list-progress')).toHaveLength(1);- expect(slots('new-pill')).toHaveLength(1);- expect(slots('attention-dot')).toHaveLength(1);- expect(slots('attention-count')).toHaveLength(2);- expect(slots('done-tick')).toHaveLength(3);+ expect(pieces('status-pill')).toHaveLength(9);+ expect(pieces('approval-pill')).toHaveLength(5);+ expect(pieces('step-marker')).toHaveLength(5);+ expect(pieces('list-dot')).toHaveLength(6);+ expect(pieces('list-progress')).toHaveLength(1);+ expect(pieces('new-pill')).toHaveLength(1);+ expect(pieces('attention-dot')).toHaveLength(1);+ expect(pieces('attention-count')).toHaveLength(2);+ expect(pieces('done-tick')).toHaveLength(3);+ });++ it('shows every run card in every state, and the runs tray', async () => {+ await render();+ expect(slots('plan-card')).toHaveLength(3);+ // Running, waiting, done, one step, stopped, failed; and one in the result card.+ expect(slots('run-steps')).toHaveLength(7);+ const approvals = ([...slots('agent-card')] as HTMLElement[]).filter((el) =>+ el.hasAttribute('data-kind'),+ );+ expect(approvals.map((el) => `${el.dataset.kind}:${el.dataset.status}`)).toEqual([+ 'write:pending',+ 'write:pending',+ 'write:saving',+ 'write:error',+ 'execute:pending',+ 'execute:pending',+ 'execute:saving',+ 'execute:pending',+ ]);+ expect(slots('done-line')).toHaveLength(2);+ expect(slots('approval-skipped')).toHaveLength(1);+ expect([...slots('result-card')].map((el) => (el as HTMLElement).dataset.state)).toEqual([+ 'done',+ 'needsClick',+ ]);+ expect(slots('denial-card')).toHaveLength(3);+ expect(slots('error-card')).toHaveLength(2);+ expect(container.querySelectorAll('[data-action="runs.toggleTray"]')).toHaveLength(3);});it('gives every control on it a data-action id', async () => {await render();- const controls = [...container.querySelectorAll<HTMLElement>('button, a, [role="button"]')];- expect(controls.map((el) => el.dataset.action)).toEqual(['chatMenu.dotLegend']);+ const controls = [+ ...container.querySelectorAll<HTMLElement>('button, a, input, textarea, [role="button"]'),+ ];+ expect(controls.length).toBeGreaterThan(40);+ for (const el of controls) expect(el.dataset.action, el.outerHTML.slice(0, 80)).toBeTruthy();});});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.tsxindex ecc7a0843..4478bf01f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/chat/preview/page.tsx@@ -16,6 +16,7 @@ import { DotLegend } from '@/components/agentic/dot-legend';import { NewPill } from '@/components/agentic/new-pill';import { AttentionCount, AttentionDot } from '@/components/agentic/attention-badge';import { DoneTick } from '@/components/agentic/done-tick';+import { CardsPreview } from './_cards-preview';const AVATAR_SIZES: readonly AgentAvatarSize[] = ['md', 'sm', 'xs'];@@ -155,14 +156,16 @@ function ChatPiecesPreview() {<DoneTick pop /></Sample></Section>++ <CardsPreview /></div>);}/**- * Chat's shared agent pieces for design sign-off (Chat P0, D1). Only with the- * new Chat on for this workspace (CHAT_AGENTIC); otherwise the page isn't- * there. Not linked from the menu.+ * Chat's shared agent pieces and run cards for design sign-off (Chat P0, D1+ * and D2). Only with the new Chat on for this workspace (CHAT_AGENTIC);+ * otherwise the page isn't there. Not linked from the menu.*/export default async function ChatPiecesPreviewPage() {const supabase = await createClient();diff --git a/web/src/app/api/chat/runs/tray/route.test.ts b/web/src/app/api/chat/runs/tray/route.test.tsnew file mode 100644index 000000000..d81318992--- /dev/null+++ b/web/src/app/api/chat/runs/tray/route.test.ts@@ -0,0 +1,314 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { CHAT_RUN_STEP_SELECT } from '@/lib/chat/steps';++/**+ * GET /api/chat/runs/tray (Chat P0, D2): not there while the new Chat is off+ * for the workspace; the person's own Chat runs and the brand's Content Agent+ * runs, newest first — never another person's chat or another brand's draft —+ * with steps read by their member columns.+ */++const ORG = 'org-1';+const ME = 'user-1';+const BRAND = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const OTHER_BRAND = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';++type Row = Record<string, unknown>;++const db = vi.hoisted(() => ({+ user: { id: 'user-1' } as { id: string } | null,+ tables: {} as Record<string, Record<string, unknown>[]>,+ selects: [] as { table: string; columns: string }[],+}));++/** A path into a row: "content_drafts.brand_id" reads the embedded draft. */+const get = (row: Row, path: string): unknown =>+ path.split('.').reduce<unknown>((v, k) => (v as Row | null)?.[k], row);++/** Just enough of PostgREST: select, eq, in, order, limit, single. Row policies aren't modelled. */+function query(table: string) {+ const filters: ((row: Row) => boolean)[] = [];+ let order: { key: string; ascending: boolean } | null = null;+ let limit = Infinity;+ const result = () => {+ let rows = (db.tables[table] ?? []).filter((row) => filters.every((f) => f(row)));+ if (order) {+ const { key, ascending } = order;+ rows = [...rows].sort(+ (a, b) => String(get(a, key)).localeCompare(String(get(b, key))) * (ascending ? 1 : -1),+ );+ }+ return rows.slice(0, limit);+ };+ const q = {+ select: (columns: string) => {+ db.selects.push({ table, columns });+ return q;+ },+ eq: (key: string, value: unknown) => {+ filters.push((row) => get(row, key) === value);+ return q;+ },+ in: (key: string, values: unknown[]) => {+ filters.push((row) => values.includes(get(row, key)));+ return q;+ },+ order: (key: string, opts: { ascending: boolean }) => {+ order = { key, ascending: opts.ascending };+ return q;+ },+ limit: (n: number) => {+ limit = n;+ return q;+ },+ single: async () => ({ data: result()[0] ?? null, error: null }),+ then: (resolve: (value: { data: Row[]; error: null }) => unknown) =>+ Promise.resolve({ data: result(), error: null }).then(resolve),+ };+ return q;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user: db.user } }) },+ from: (table: string) => query(table),+ }),+}));++const { GET } = await import('./route');++const get_ = (search = `?brand=${BRAND}`) =>+ GET(new Request(`http://localhost/api/chat/runs/tray${search}`));++const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString();++beforeEach(() => {+ vi.stubEnv('CHAT_AGENTIC', 'true');+ vi.stubEnv('CHAT_AGENTIC_ORGS', '');+ db.user = { id: ME };+ db.selects = [];+ db.tables = {+ profiles: [+ { id: ME, organization_id: ORG },+ { id: 'user-2', organization_id: ORG },+ ],+ chat_conversations: [+ {+ id: 'chat-mine',+ user_id: ME,+ organization_id: ORG,+ title: 'Action Center tasks',+ last_message_at: minutesAgo(1),+ },+ {+ id: 'chat-mine-2',+ user_id: ME,+ organization_id: ORG,+ title: 'Weekly report',+ last_message_at: minutesAgo(30),+ },+ {+ id: 'chat-theirs',+ user_id: 'user-2',+ organization_id: ORG,+ title: 'Their secret chat',+ last_message_at: minutesAgo(2),+ },+ {+ id: 'chat-elsewhere',+ user_id: ME,+ organization_id: 'org-2',+ title: 'Another workspace',+ last_message_at: minutesAgo(3),+ },+ ],+ chat_runs: [+ {+ id: 'run-1',+ conversation_id: 'chat-mine',+ status: 'waiting',+ created_at: minutesAgo(5),+ finished_at: null,+ },+ {+ id: 'run-2',+ conversation_id: 'chat-mine-2',+ status: 'done',+ created_at: minutesAgo(40),+ finished_at: minutesAgo(35),+ },+ {+ id: 'run-3',+ conversation_id: 'chat-theirs',+ status: 'running',+ created_at: minutesAgo(1),+ finished_at: null,+ },+ {+ id: 'run-4',+ conversation_id: 'chat-elsewhere',+ status: 'running',+ created_at: minutesAgo(1),+ finished_at: null,+ },+ ],+ chat_run_steps: [+ {+ id: 's1',+ run_id: 'run-1',+ position: 1,+ kind: 'read',+ status: 'done',+ label: 'Read Action Center',+ tool: 'list_actions',+ debug_json: {},+ },+ {+ id: 's2',+ run_id: 'run-1',+ position: 2,+ kind: 'write',+ status: 'waiting',+ label: 'Change one cited passage',+ tool: 'update_draft',+ debug_json: {},+ },+ {+ id: 's3',+ run_id: 'run-3',+ position: 1,+ kind: 'read',+ status: 'running',+ label: 'Read their data',+ tool: 'x',+ debug_json: {},+ },+ ],+ content_agent_runs: [+ {+ id: 'crun-1',+ kind: 'fix',+ steps: [+ { key: 'read_rules', count: 3 },+ { key: 'write_changes', count: null },+ ],+ step: 1,+ started_at: minutesAgo(2),+ finished_at: null,+ stopped_at: null,+ outcome: null,+ draft_id: 'draft-1',+ content_drafts: { title: 'Pricing FAQ', brand_id: BRAND },+ },+ {+ id: 'crun-2',+ kind: 'fix',+ steps: [{ key: 'read_rules', count: 3 }],+ step: 0,+ started_at: minutesAgo(1),+ finished_at: null,+ stopped_at: null,+ outcome: null,+ draft_id: 'draft-2',+ content_drafts: { title: 'Another brand’s draft', brand_id: OTHER_BRAND },+ },+ ],+ };+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('GET /api/chat/runs/tray', () => {+ it.each([undefined, '', 'false'])('is not found with CHAT_AGENTIC=%s', async (value) => {+ vi.stubEnv('CHAT_AGENTIC', value);+ const res = await get_();+ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ ok: false, failure: 'not_found', error: 'Not found' });+ // Nothing of Chat is read while it is off.+ expect(db.selects.map((s) => s.table)).toEqual(['profiles']);+ });++ it("is not found for a workspace Chat isn't on for", async () => {+ vi.stubEnv('CHAT_AGENTIC_ORGS', 'org-9');+ expect((await get_()).status).toBe(404);+ });++ it('asks the signed-out to sign in', async () => {+ db.user = null;+ const res = await get_();+ expect(res.status).toBe(401);+ expect(await res.json()).toEqual({ ok: false, failure: 'session', error: 'Unauthorized' });+ });++ it('refuses a brand that is no id', async () => {+ const res = await get_('?brand=not-a-uuid');+ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ ok: false, failure: 'failed', error: 'Invalid brand' });+ });++ it("shows the person's own runs and the brand's, newest first, and no one else's", async () => {+ const res = await get_();+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.ok).toBe(true);+ expect(body.runs.map((r: Row) => [r.title, r.state, r.href])).toEqual([+ ['Pricing FAQ', 'running', '/dashboard/content/editor/draft-1'],+ ['Action Center tasks', 'needsYou', '/dashboard/chat/chat-mine'],+ ['Weekly report', 'done', '/dashboard/chat/chat-mine-2'],+ ]);+ expect([body.running, body.needsYou]).toEqual([1, 1]);+ const wire = JSON.stringify(body);+ expect(wire).not.toContain('Their secret chat');+ expect(wire).not.toContain('Read their data');+ expect(wire).not.toContain('Another workspace');+ expect(wire).not.toContain('Another brand');+ expect(body.runs[1]).toMatchObject({+ step: 2,+ steps: 2,+ stepLabel: 'Change one cited passage',+ });+ });++ it('reads steps by their member columns, never * or the tool', async () => {+ await get_();+ const steps = db.selects.find((s) => s.table === 'chat_run_steps')!;+ expect(steps.columns).toBe(CHAT_RUN_STEP_SELECT);+ for (const { columns } of db.selects) {+ expect(columns).not.toContain('*');+ expect(columns).not.toMatch(/\btool\b|debug_json/);+ }+ const wire = JSON.stringify(await (await get_()).json());+ expect(wire).not.toMatch(/list_actions|update_draft|debug/);+ });++ it('says a read that failed, or threw, as plain JSON', async () => {+ const tables = db.tables;+ db.tables = new Proxy(tables, {+ get: (target, table: string) => {+ if (table === 'chat_runs') throw new Error('connection reset');+ return target[table];+ },+ });+ const res = await get_();+ expect(res.status).toBe(500);+ expect(res.headers.get('content-type')).toContain('application/json');+ expect(await res.json()).toEqual({+ ok: false,+ failure: 'failed',+ error: 'Failed to read runs',+ });+ db.tables = tables;+ });++ it('shows only Chat runs without a brand', async () => {+ const body = await (await get_('')).json();+ expect(body.runs.map((r: Row) => r.href)).toEqual([+ '/dashboard/chat/chat-mine',+ '/dashboard/chat/chat-mine-2',+ ]);+ expect(db.selects.some((s) => s.table === 'content_agent_runs')).toBe(false);+ });+});diff --git a/web/src/app/api/chat/runs/tray/route.ts b/web/src/app/api/chat/runs/tray/route.tsnew file mode 100644index 000000000..c9b2fef09--- /dev/null+++ b/web/src/app/api/chat/runs/tray/route.ts@@ -0,0 +1,177 @@+import { NextResponse } from 'next/server';+import { createClient } from '@/lib/supabase/server';+import { chatAgenticEnabled } from '@/lib/chat/flag';+import { CHAT_RUN_STEP_SELECT, type ChatRunStepMemberRow } from '@/lib/chat/steps';+import type { ApiFailure } from '@/lib/api-failure';+import {+ chatTrayRun,+ contentTrayRun,+ trayResponse,+ type ChatRunRow,+ type TrayFailure,+ type TrayResult,+ type TrayRun,+} from '@/lib/chat/runs-tray';++/** The person's chats the tray looks through, the most recent first. */+const CHATS_LIMIT = 50;+/** Runs read per source, before the tray keeps its newest. */+const RUNS_LIMIT = 30;++const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** A failure as a value the browser reads (TrayFailure), never an HTML error page. */+const fail = (status: number, failure: ApiFailure, error: string) =>+ NextResponse.json<TrayFailure>({ ok: false, failure, error }, { status });++/**+ * GET /api/chat/runs/tray?brand={brandId}+ *+ * The runs tray (Chat agentic plan §2, CHAT-23 G4): the person's own Chat+ * runs, and the Content Agent's runs on the brand's drafts, newest first —+ * the ones under way and those that ended in the last day. Read as the+ * person (their row policies): a chat is its author's only (CHAT-20 §16c),+ * and is asked for by author besides; a draft's runs are its workspace's.+ * Steps by their member columns (CHAT_RUN_STEP_SELECT), never the tool or its+ * debug record. Not there (404) while the new Chat is off for the workspace+ * (CHAT_AGENTIC).+ *+ * Answers `{ ok: true, runs, running, needsYou }`, or `{ ok: false, failure,+ * error }` with its status — also for an error nothing expected — so the+ * tray can say what went wrong in plain words (TrayResult).+ */+export async function GET(req: Request) {+ try {+ return await tray(req);+ } catch (error) {+ console.error('Failed to build the runs tray:', error);+ return fail(500, 'failed', 'Failed to read runs');+ }+}++async function tray(req: Request) {+ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return fail(401, 'session', 'Unauthorized');++ const { data: profile } = await supabase+ .from('profiles')+ .select('organization_id')+ .eq('id', user.id)+ .single();+ const organizationId = profile?.organization_id ?? null;+ if (!organizationId || !chatAgenticEnabled(organizationId)) {+ return fail(404, 'not_found', 'Not found');+ }++ const brandId = new URL(req.url).searchParams.get('brand');+ if (brandId !== null && !UUID.test(brandId)) {+ return fail(400, 'failed', 'Invalid brand');+ }++ const now = Date.now();+ const [chat, content] = await Promise.all([+ chatRuns(supabase, user.id, organizationId, now),+ brandId ? contentRuns(supabase, brandId, now) : Promise.resolve([]),+ ]);+ if (chat === null || content === null) return fail(500, 'failed', 'Failed to read runs');+ return NextResponse.json<TrayResult>({ ok: true, ...trayResponse([...chat, ...content]) });+}++type Supabase = Awaited<ReturnType<typeof createClient>>;++/** The person's own Chat runs in this workspace, with their steps; null when they can't be read. */+async function chatRuns(+ supabase: Supabase,+ userId: string,+ organizationId: string,+ now: number,+): Promise<TrayRun[] | null> {+ const { data: chats, error: chatsError } = await supabase+ .from('chat_conversations')+ .select('id, title')+ .eq('user_id', userId)+ .eq('organization_id', organizationId)+ .order('last_message_at', { ascending: false })+ .limit(CHATS_LIMIT);+ if (chatsError) {+ console.error('Failed to read chats for the runs tray:', chatsError);+ return null;+ }+ if (!chats?.length) return [];+ const titles = new Map(chats.map((c) => [c.id, c.title]));++ const { data: runs, error: runsError } = await supabase+ .from('chat_runs')+ .select('id, conversation_id, status, created_at, finished_at')+ .in('conversation_id', [...titles.keys()])+ .order('created_at', { ascending: false })+ .limit(RUNS_LIMIT);+ if (runsError) {+ console.error('Failed to read chat runs for the runs tray:', runsError);+ return null;+ }+ if (!runs?.length) return [];++ const { data: steps, error: stepsError } = await supabase+ .from('chat_run_steps')+ .select(CHAT_RUN_STEP_SELECT)+ .in(+ 'run_id',+ runs.map((r) => r.id),+ )+ .order('position', { ascending: true });+ if (stepsError) {+ console.error('Failed to read chat run steps for the runs tray:', stepsError);+ return null;+ }+ const byRun = new Map<string, ChatRunStepMemberRow[]>();+ for (const step of (steps ?? []) as unknown as ChatRunStepMemberRow[]) {+ byRun.set(step.run_id, [...(byRun.get(step.run_id) ?? []), step]);+ }++ return runs.flatMap((run) => {+ // Only runs of the chats read above: the person's own.+ if (!titles.has(run.conversation_id)) return [];+ const row = chatTrayRun(+ run as ChatRunRow,+ titles.get(run.conversation_id) ?? null,+ byRun.get(run.id) ?? [],+ now,+ );+ return row ? [row] : [];+ });+}++/** The Content Agent's runs on the brand's drafts; null when they can't be read. */+async function contentRuns(+ supabase: Supabase,+ brandId: string,+ now: number,+): Promise<TrayRun[] | null> {+ const { data, error } = await supabase+ .from('content_agent_runs')+ .select(+ 'id, kind, steps, step, started_at, finished_at, stopped_at, outcome, draft_id, content_drafts!content_agent_runs_draft_id_fkey!inner(title, brand_id)',+ )+ .eq('content_drafts.brand_id', brandId)+ .order('started_at', { ascending: false })+ .limit(RUNS_LIMIT);+ if (error) {+ console.error('Failed to read Content Agent runs for the runs tray:', error);+ return null;+ }+ return (data ?? []).flatMap((row) => {+ const draft = row.content_drafts as { title: string | null; brand_id: string } | null;+ // Only the brand's drafts: the filter above, held here too.+ if (!draft || draft.brand_id !== brandId) return [];+ const run = contentTrayRun(+ row as unknown as Record<string, unknown>,+ { id: row.draft_id, title: draft.title },+ now,+ );+ return run ? [run] : [];+ });+}diff --git a/web/src/components/agentic/agent-card.tsx b/web/src/components/agentic/agent-card.tsxnew file mode 100644index 000000000..b6066b011--- /dev/null+++ b/web/src/components/agentic/agent-card.tsx@@ -0,0 +1,174 @@+import type { ReactNode } from 'react';+import { cn } from '@/lib/utils';+import { AgentAvatar, type AgentAvatarState } from './agent-avatar';+import { DoneTick } from './done-tick';++/**+ * The parts every run card shares (Chat v2 mockups: plan, approval, result,+ * out-of-permission and failed run): a 14 px card with a hairline border and+ * a soft shadow that rises in once (still with reduced motion), a header row,+ * a body and a footer with the note on the left and the buttons on the right.+ */++/** How a card stands out: plain; amber while it needs the person's OK; dark for a click; red once failed. */+export type AgentCardTone = 'plain' | 'needsYou' | 'click' | 'failed';++const TONE: Record<AgentCardTone, string> = {+ plain: '',+ needsYou: 'border-amber-200 ring-3 ring-amber-50 dark:border-amber-900 dark:ring-amber-950/60',+ click: 'border-foreground ring-3 ring-foreground/5',+ failed: 'border-red-200 dark:border-red-900',+};++export function AgentCard({+ tone = 'plain',+ className,+ children,+ ...rest+}: {+ tone?: AgentCardTone;+ className?: string;+ children: ReactNode;+} & Omit<React.HTMLAttributes<HTMLElement>, 'className' | 'children'>) {+ return (+ <section+ data-slot="agent-card"+ data-tone={tone}+ className={cn(+ 'mb-4 animate-in overflow-hidden rounded-[14px] border bg-card shadow-[0_1px_2px_rgba(10,10,10,.04)] duration-300 fade-in-0 slide-in-from-bottom-1.5 motion-reduce:animate-none',+ TONE[tone],+ className,+ )}+ {...rest}+ >+ {children}+ </section>+ );+}++/** The card's title row: a tag or pill on the left, the title, and pills on the right. */+export function AgentCardHeader({+ lead,+ title,+ end,+ titleId,+}: {+ lead?: ReactNode;+ title: ReactNode;+ end?: ReactNode;+ /** For the card's aria-labelledby. */+ titleId?: string;+}) {+ return (+ <div className="flex flex-wrap items-center gap-2.5 border-b px-3.5 py-3">+ {lead}+ <h3 id={titleId} className="m-0 min-w-0 text-sm font-semibold">+ {title}+ </h3>+ {end && <div className="ml-auto flex items-center gap-1.5">{end}</div>}+ </div>+ );+}++export function AgentCardBody({+ className,+ children,+}: {+ className?: string;+ children: ReactNode;+}) {+ return <div className={cn('px-3.5 pt-1.5 pb-3', className)}>{children}</div>;+}++/** The footer: a short muted note on the left, the card's buttons on the right. */+export function AgentCardFooter({ note, children }: { note?: ReactNode; children?: ReactNode }) {+ return (+ <div className="flex flex-wrap items-center gap-2 border-t px-3.5 py-2.5">+ {note && <div className="text-xs text-muted-foreground">{note}</div>}+ {children && <div className="ml-auto flex flex-wrap gap-1.5">{children}</div>}+ </div>+ );+}++/** A small grey pill on the right of a header, or amber when it is a warning. */+export function CardPill({+ tone = 'grey',+ children,+}: {+ tone?: 'grey' | 'amber';+ children: ReactNode;+}) {+ return (+ <span+ className={cn(+ 'inline-flex shrink-0 items-center rounded-full border px-[9px] py-px text-[11.5px] leading-[14px] whitespace-nowrap',+ tone === 'grey'+ ? 'border-border text-muted-foreground'+ : 'border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300',+ )}+ >+ {children}+ </span>+ );+}++/** Source chips: where a change or an answer comes from ("Brand fact · Plans (approved)"). */+export function SourceChips({ label, sources }: { label: string; sources: string[] }) {+ if (sources.length === 0) return null;+ return (+ <ul aria-label={label} className="m-0 mt-2 flex list-none flex-wrap gap-1.5 p-0">+ {sources.map((source) => (+ <li+ key={source}+ className="rounded-full border bg-card px-[9px] py-px text-[11.5px] text-foreground/80"+ >+ {source}+ </li>+ ))}+ </ul>+ );+}++/**+ * The agent's line above its card (the mockups' answer head): the avatar in+ * the run's state, a bold title, and muted lines under it.+ */+export function AgentHead({+ state,+ title,+ subtitle,+ note,+}: {+ state: AgentAvatarState;+ title: ReactNode;+ subtitle?: ReactNode;+ note?: ReactNode;+}) {+ return (+ <div data-slot="agent-head" className="mb-2 flex items-center gap-2.5">+ <AgentAvatar state={state} />+ <div className="min-w-0 leading-normal">+ <p className="m-0 text-[13.5px] font-semibold">{title}</p>+ {subtitle && <p className="m-0 text-xs text-muted-foreground">{subtitle}</p>}+ {note && <p className="m-0 text-[11.5px] text-muted-foreground">{note}</p>}+ </div>+ </div>+ );+}++/** The success line a card collapses into (the mockups' okline), its tick popping in once. */+export function DoneLine({ children, detail }: { children: ReactNode; detail?: ReactNode }) {+ return (+ <div+ role="status"+ data-slot="done-line"+ className="my-2 flex flex-wrap items-center gap-2.5 rounded-xl border border-green-200 bg-green-50/60 px-3 py-[9px] text-[13px] dark:border-green-900 dark:bg-green-950/40"+ >+ <DoneTick pop decorative />+ <div className="min-w-0 flex-1">+ {children}+ {detail && <span className="block text-xs text-muted-foreground">{detail}</span>}+ </div>+ </div>+ );+}diff --git a/web/src/components/agentic/approval-card.tsx b/web/src/components/agentic/approval-card.tsxnew file mode 100644index 000000000..f09df22a2--- /dev/null+++ b/web/src/components/agentic/approval-card.tsx@@ -0,0 +1,343 @@+'use client';++import { useId, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2 } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { ApprovalPill } from './approval-pill';+import {+ AgentCard,+ AgentCardBody,+ AgentCardFooter,+ AgentCardHeader,+ CardPill,+ DoneLine,+ SourceChips,+} from './agent-card';++/**+ * Where an approval stands: waiting for the person; saving their answer;+ * approved (it collapses to a green line); skipped; or the change failed,+ * with the reason and Retry.+ */+export type ApprovalCardStatus = 'pending' | 'saving' | 'approved' | 'skipped' | 'error';++export const APPROVAL_CARD_STATUSES: readonly ApprovalCardStatus[] = [+ 'pending',+ 'saving',+ 'approved',+ 'skipped',+ 'error',+];++/** A line of what a change carries ("FAQ block · 6 questions" / "New section on /pricing"). */+export interface ApprovalItem {+ /** A short glyph for its tile: "≡", "{ }", "↗". */+ icon?: string;+ title: string;+ detail?: string;+}++/** What the person answered: the text as they left it, and their "Don't ask again" tick. */+export interface ApprovalAnswer {+ /** The edited new text, when they edited it (an edit is new arguments: CHAT-20 §6). */+ text?: string;+ dontAskAgain: boolean;+}++const spinner = <Loader2 aria-hidden className="animate-spin motion-reduce:animate-none" />;++/**+ * The approval card (CHAT-mockup-v2 `#s-need`, `#s-done`; CHAT-20 §6; CHAT-23+ * G7, G8). A WRITE (`kind="write"`) shows the step, the change as before and+ * after, why, its sources, and Skip · Edit · Approve; "Don't ask again for+ * this kind of change" only when the precedence allows it (`canDontAskAgain`,+ * CHAT-20 §5 step 6). An EXECUTE (`kind="execute"`) is the click that goes+ * live: the dark "Needs your click" pill, the only dark one, and a button that+ * names the outside effect ("Publish"); never a "Don't ask again". Approve,+ * Save & approve and the click go through the read-only gate.+ */+export function ApprovalCard({+ kind = 'write',+ step,+ title,+ badge,+ why,+ change,+ items,+ summary,+ sources = [],+ note,+ canDontAskAgain = false,+ dontAskAgainLabel,+ actionLabel,+ busyLabel,+ disabledReason,+ previewLabel,+ onPreview,+ status = 'pending',+ error,+ doneLabel,+ onApprove,+ onSkip,+}: {+ kind?: 'write' | 'execute';+ /** The step it stops at, and the run's step count. */+ step: { n: number; total: number };+ title: string;+ /** A WRITE's amber pill on the right: "Cited 12× last month". */+ badge?: string;+ /** Why the change: "ChatGPT cites this passage, but it says…". */+ why?: string;+ change?: { before: string; after: string };+ items?: ApprovalItem[];+ /** An EXECUTE's one line of what goes live. */+ summary?: string;+ sources?: string[];+ /** The footer's note: "Draft only · nothing goes live", "Goes live on ansvisor.com/pricing · same in every mode". */+ note?: string;+ /** The precedence's offerDontAskAgain (A3): Growth+, policy allows auto, not always_card, never an EXECUTE. */+ canDontAskAgain?: boolean;+ /** "Don't ask again for brand-fact fixes"; else the generic words. */+ dontAskAgainLabel?: string;+ /** An EXECUTE's button, naming the outside effect: "Publish", "Send to [email protected]". */+ actionLabel?: string;+ /** An EXECUTE's button while it works: "Publishing…". */+ busyLabel?: string;+ /** Why the click can't be made yet ("After the draft is approved"): the button is off, with it as its tooltip. */+ disabledReason?: string;+ previewLabel?: string;+ onPreview?: () => void;+ status?: ApprovalCardStatus;+ /** The plain reason a change failed (CHAT-23 P9). */+ error?: string;+ /** The green line once approved: "Cited passage changed", "Published to ansvisor.com/pricing · 14:32". */+ doneLabel?: string;+ onApprove?: (answer: ApprovalAnswer) => void;+ onSkip?: () => void;+}) {+ const t = useTranslations('agentic.approvalCard');+ const { guard } = useUpgradeGate();+ const titleId = useId();+ const [dontAskAgain, setDontAskAgain] = useState(false);+ const [editing, setEditing] = useState(false);+ const [text, setText] = useState(change?.after ?? '');+ const [editedText, setEditedText] = useState<string | undefined>(undefined);+ const execute = kind === 'execute';+ const busy = status === 'saving';+ const offerDontAsk = canDontAskAgain && !execute;+ const stepOf = t('stepOf', step);++ if (status === 'approved') {+ return (+ <DoneLine>+ {execute+ ? (doneLabel ?? t('done'))+ : [t('approved', { n: step.n }), doneLabel].filter(Boolean).join(' · ')}+ </DoneLine>+ );+ }+ if (status === 'skipped') {+ return (+ <p+ role="status"+ data-slot="approval-skipped"+ className="my-2 rounded-xl border border-dashed px-3 py-[9px] text-[13px] text-muted-foreground"+ >+ {t('skipped', { n: step.n })} · {title}+ </p>+ );+ }++ const approve = guard(+ (answer: ApprovalAnswer) => {+ setEditing(false);+ onApprove?.(answer);+ },+ { action: execute ? t('clickNeedsPlan') : t('approveNeedsPlan') },+ );+ const answer = (): ApprovalAnswer => ({+ ...(editedText !== undefined ? { text: editedText } : {}),+ dontAskAgain: offerDontAsk && dontAskAgain,+ });++ return (+ <AgentCard+ tone={execute ? 'click' : 'needsYou'}+ aria-labelledby={titleId}+ data-kind={kind}+ data-status={status}+ >+ <AgentCardHeader+ titleId={titleId}+ lead={+ execute ? (+ <ApprovalPill kind="click" />+ ) : (+ <span className="inline-flex shrink-0 items-center rounded-full bg-amber-100 px-2 py-px text-[11px] leading-[14px] whitespace-nowrap text-amber-700 dark:bg-amber-950 dark:text-amber-300">+ {stepOf}+ </span>+ )+ }+ title={title}+ end={+ execute ? (+ <CardPill>{stepOf}</CardPill>+ ) : badge ? (+ <CardPill tone="amber">{badge}</CardPill>+ ) : undefined+ }+ />+ <AgentCardBody className={execute ? 'pt-2.5 text-[13px]' : undefined}>+ {why && <p className="mt-2 mb-1 text-[13px] text-muted-foreground">{why}</p>}+ {summary && <p className="m-0">{summary}</p>}+ {change && (+ <div className="my-2 overflow-hidden rounded-xl border text-[13px]">+ <p className="m-0 bg-red-50 px-2.5 py-1.5 text-red-900 line-through decoration-red-900/40 dark:bg-red-950/40 dark:text-red-200 dark:decoration-red-200/40">+ <span className="sr-only">{t('before')}: </span>+ {change.before}+ </p>+ {editing ? (+ <div className="bg-green-50 px-2.5 py-1.5 dark:bg-green-950/40">+ <textarea+ data-action="approval.editText"+ aria-label={t('newText')}+ value={text}+ onChange={(e) => setText(e.target.value)}+ className="min-h-16 w-full resize-y rounded-lg border border-green-200 bg-card px-2 py-1.5 text-foreground outline-none focus-visible:ring-3 focus-visible:ring-ring/50 dark:border-green-900"+ />+ </div>+ ) : (+ <p className="m-0 bg-green-50 px-2.5 py-1.5 text-green-900 dark:bg-green-950/40 dark:text-green-200">+ <span className="sr-only">{t('after')}: </span>+ {editedText ?? change.after}+ </p>+ )}+ </div>+ )}+ {items && items.length > 0 && (+ <ul className="m-0 my-2 grid list-none gap-1.5 p-0">+ {items.map((item) => (+ <li+ key={item.title}+ className="grid min-h-[50px] grid-cols-[30px_minmax(0,1fr)] items-center gap-2.5 rounded-xl border px-2.5 py-2 text-[13px]"+ >+ <span+ aria-hidden+ className="flex size-[30px] items-center justify-center rounded-lg border bg-muted text-[13px]"+ >+ {item.icon ?? '≡'}+ </span>+ <span className="min-w-0 truncate">+ {item.title}+ {item.detail && (+ <span className="block truncate text-xs text-muted-foreground">+ {item.detail}+ </span>+ )}+ </span>+ </li>+ ))}+ </ul>+ )}+ <SourceChips label={t('sources')} sources={sources} />+ {status === 'error' && error && (+ <p role="alert" className="mt-2 mb-0 text-[12.5px] text-red-700 dark:text-red-300">+ {error}+ </p>+ )}+ </AgentCardBody>+ <AgentCardFooter+ note={+ offerDontAsk ? (+ <label+ className="flex cursor-pointer items-center gap-1.5"+ title={t('dontAskAgainTip')}+ >+ <input+ data-action="approval.dontAskAgain"+ type="checkbox"+ checked={dontAskAgain}+ disabled={busy}+ onChange={(e) => setDontAskAgain(e.target.checked)}+ className="size-3.5 accent-foreground"+ />+ {dontAskAgainLabel ?? t('dontAskAgain')}+ </label>+ ) : (+ (disabledReason ?? note)+ )+ }+ >+ {execute ? (+ <>+ {onPreview && (+ <Button data-action="exec.preview" variant="outline" onClick={onPreview}>+ {previewLabel ?? t('preview')}+ </Button>+ )}+ <Button+ data-action="exec.publish"+ disabled={busy || !!disabledReason}+ aria-busy={busy || undefined}+ title={disabledReason}+ onClick={() => approve({ dontAskAgain: false })}+ >+ {busy && spinner}+ {busy ? (busyLabel ?? t('working')) : status === 'error' ? t('retry') : actionLabel}+ </Button>+ </>+ ) : editing ? (+ <>+ <Button+ data-action="approval.cancelEdit"+ variant="outline"+ onClick={() => {+ setEditing(false);+ setText(editedText ?? change?.after ?? '');+ }}+ >+ {t('cancel')}+ </Button>+ <Button+ data-action="approval.saveAndApprove"+ disabled={busy || !text.trim()}+ onClick={() => {+ setEditedText(text);+ approve({ text, dontAskAgain: offerDontAsk && dontAskAgain });+ }}+ >+ {t('saveAndApprove')}+ </Button>+ </>+ ) : (+ <>+ <Button data-action="approval.skip" variant="outline" disabled={busy} onClick={onSkip}>+ {t('skip')}+ </Button>+ {change && (+ <Button+ data-action="approval.edit"+ variant="outline"+ disabled={busy}+ onClick={() => setEditing(true)}+ >+ {t('edit')}+ </Button>+ )}+ <Button+ data-action="approval.approve"+ disabled={busy}+ aria-busy={busy || undefined}+ onClick={() => approve(answer())}+ >+ {busy && spinner}+ {status === 'error' ? t('retry') : t('approve')}+ </Button>+ </>+ )}+ </AgentCardFooter>+ </AgentCard>+ );+}diff --git a/web/src/components/agentic/cards.test.tsx b/web/src/components/agentic/cards.test.tsxnew file mode 100644index 000000000..950c9d9f0--- /dev/null+++ b/web/src/components/agentic/cards.test.tsx@@ -0,0 +1,810 @@+import { act, type ReactElement, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';+import type { ChatStep } from '@/lib/chat/events';+import { PlanCard, planStepPill, type PlanStep } from './plan-card';+import { ApprovalCard, APPROVAL_CARD_STATUSES } from './approval-card';+import { ResultCard } from './result-card';+import { DenialCard } from './denial-card';+import { ErrorCard } from './error-card';+import { RunSteps, runClock } from './run-steps';+import type { StepRow } from './step-list';++/**+ * The run cards (Chat P0, D2; CHAT-mockup-v2 `#s-plan`, `#s-need`, `#s-done`,+ * `#s-denied`, `#s-failed`; CHAT-03; CHAT-20 §4c, §6; CHAT-23 G7, G8, P10):+ * each state, "Don't ask again" only where allowed, EXECUTE's one dark pill,+ * the denial's four parts, the read-only gate on every approve and send,+ * screen readers hearing the steps, and no motion with reduced motion.+ */++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));+const toast = vi.hoisted(() => ({ success: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;+const openUpgrade = vi.fn();++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ openUpgrade.mockReset();+ toast.success.mockReset();+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function tree(ui: ReactElement, isLocked: boolean) {+ return (+ <NextIntlClientProvider locale="en" messages={messages}>+ <UpgradeDialogContext.Provider+ value={{ isLocked, reason: 'ended', adminName: null, openUpgrade }}+ >+ {ui}+ </UpgradeDialogContext.Provider>+ </NextIntlClientProvider>+ );+}++async function render(ui: ReactElement, { isLocked = false } = {}) {+ await act(async () => root.render(tree(ui, isLocked)));+}++const $ = <T extends Element = HTMLElement>(selector: string) =>+ container.querySelector<T & HTMLElement>(selector);+const $$ = (selector: string) => [...container.querySelectorAll<HTMLElement>(selector)];+const action = (id: string) => $<HTMLButtonElement>(`[data-action="${id}"]`);+const click = async (el: Element | null) => {+ expect(el).not.toBeNull();+ await act(async () => (el as HTMLElement).click());+};+const classOf = (el: Element) => el.getAttribute('class') ?? '';++const PLAN: PlanStep[] = [+ { label: 'Read the 4 tasks', detail: 'Action Center', cls: 'read' },+ { label: 'Change one cited passage', cls: 'write' },+ { label: 'Publish the Webflow draft', cls: 'execute' },+];++const CHANGE = { before: 'Every plan tracks all 7 platforms.', after: 'Starter tracks 2.' };++const step = (n: number, status: ChatStep['status'], label: string, extra = {}): ChatStep => ({+ n,+ kind: 'read',+ status,+ label,+ ...extra,+});++describe('PlanCard', () => {+ it('shows how each step runs in each mode (CHAT-23 P10)', async () => {+ expect(PLAN.map((s) => planStepPill(s.cls, 'auto'))).toEqual(['auto', 'asks', 'click']);+ expect(PLAN.map((s) => planStepPill(s.cls, 'ask_first'))).toEqual(['asks', 'asks', 'click']);+ expect(PLAN.map((s) => planStepPill(s.cls, 'full_auto'))).toEqual(['auto', 'logged', 'click']);++ await render(<PlanCard title="Action Center tasks" steps={PLAN} mode="full_auto" />);+ const pills = $$('[data-slot="approval-pill"]').map((p) => p.dataset.state);+ expect(pills).toEqual(['auto', 'logged', 'click']);+ expect(container.textContent).toContain('Here’s my plan');+ expect(container.textContent).toContain('Mode: Full auto');+ // Steps are numbered, none started.+ expect($$('[data-slot="step-marker"]').map((m) => m.dataset.state)).toEqual([+ 'pending',+ 'pending',+ 'pending',+ ]);+ });++ it('lists what the run uses, connects, takes and makes', async () => {+ await render(+ <PlanCard+ title="Plan"+ steps={PLAN}+ mode="auto"+ uses="Action Center · 52 sources"+ connections={[+ { name: 'Webflow', connected: true },+ { name: 'Shopify', connected: false },+ ]}+ time="6 min"+ aiUsage="~2%"+ outputs="FAQ draft"+ onConnect={() => {}}+ />,+ );+ const text = container.textContent!;+ expect(text).toContain('Uses Action Center · 52 sources');+ expect(text).toContain('About 6 min');+ expect(text).toContain('AI usage ~2% of monthly limit');+ expect(text).toContain('Outputs FAQ draft');+ expect(text).toContain('Shopify isn’t connected.');+ expect(action('integrations.connect')!.textContent).toBe('Connect Shopify');+ });++ it('starts with the plan as edited: moved and removed steps', async () => {+ const onStart = vi.fn();+ await render(<PlanCard title="Plan" steps={PLAN} mode="auto" onStart={onStart} />);+ expect(action('plan.moveStepUp')).toBeNull();+ await click(action('plan.edit'));+ expect(action('plan.edit')!.textContent).toBe('Done editing');+ // Move the second step up, then remove the (now) last step.+ await click($$('[data-action="plan.moveStepUp"]')[1]);+ await click($$('[data-action="plan.removeStep"]')[2]);+ await click(action('plan.start'));+ expect(onStart).toHaveBeenCalledWith([PLAN[1], PLAN[0]]);+ });++ it('gives a role that can’t start runs Ask your Admin, and no Edit plan', async () => {+ const onAskAdmin = vi.fn();+ await render(+ <PlanCard title="Plan" steps={PLAN} mode="auto" canStart={false} onAskAdmin={onAskAdmin} />,+ );+ expect(action('plan.start')).toBeNull();+ expect(action('plan.edit')).toBeNull();+ await click(action('access.askAdmin'));+ expect(onAskAdmin).toHaveBeenCalledOnce();+ });++ it('starts nothing while the workspace is read-only: the upgrade dialog opens', async () => {+ const onStart = vi.fn();+ await render(<PlanCard title="Plan" steps={PLAN} mode="auto" onStart={onStart} />, {+ isLocked: true,+ });+ await click(action('plan.start'));+ expect(onStart).not.toHaveBeenCalled();+ expect(openUpgrade).toHaveBeenCalledWith('Starting a run needs a plan');+ });+});++describe('ApprovalCard', () => {+ const write = (props: Partial<Parameters<typeof ApprovalCard>[0]> = {}) => (+ <ApprovalCard+ step={{ n: 4, total: 6 }}+ title="Change a cited passage on /pricing"+ badge="Cited 12× last month"+ why="ChatGPT cites this passage."+ change={CHANGE}+ sources={['Brand fact · Plans', 'Cited page · /pricing']}+ {...props}+ />+ );++ it('shows a WRITE: its step, the change before and after, why and its sources', async () => {+ await render(write());+ const card = $('[data-slot="agent-card"]')!;+ expect(card.dataset.tone).toBe('needsYou');+ expect(card.getAttribute('aria-labelledby')).toBe(card.querySelector('h3')!.id);+ expect(card.textContent).toContain('Step 4 of 6');+ expect(card.textContent).toContain('Cited 12× last month');+ expect(card.textContent).toContain('Before: Every plan tracks all 7 platforms.');+ expect(card.textContent).toContain('After: Starter tracks 2.');+ expect($$('li').map((li) => li.textContent)).toEqual([+ 'Brand fact · Plans',+ 'Cited page · /pricing',+ ]);+ expect($$('button').map((b) => b.dataset.action)).toEqual([+ 'approval.skip',+ 'approval.edit',+ 'approval.approve',+ ]);+ // A WRITE has no dark pill.+ expect($('[data-slot="approval-pill"][data-state="click"]')).toBeNull();+ });++ it('offers "Don’t ask again" only when the precedence allows it', async () => {+ await render(write());+ expect(action('approval.dontAskAgain')).toBeNull();+ await render(write({ canDontAskAgain: true }));+ expect(action('approval.dontAskAgain')).not.toBeNull();+ expect(container.textContent).toContain('Don’t ask again for this kind of change');+ await render(+ write({ canDontAskAgain: true, dontAskAgainLabel: 'Don’t ask again for CMS drafts' }),+ );+ expect(container.textContent).toContain('Don’t ask again for CMS drafts');+ // Never on an EXECUTE, even if asked.+ await render(write({ kind: 'execute', canDontAskAgain: true, actionLabel: 'Publish' }));+ expect(action('approval.dontAskAgain')).toBeNull();+ });++ it('approves with the tick only when it was offered and ticked', async () => {+ const onApprove = vi.fn();+ await render(write({ canDontAskAgain: true, onApprove }));+ await click(action('approval.approve'));+ expect(onApprove).toHaveBeenLastCalledWith({ dontAskAgain: false });+ await click(action('approval.dontAskAgain'));+ await click(action('approval.approve'));+ expect(onApprove).toHaveBeenLastCalledWith({ dontAskAgain: true });+ });++ it('approves the edited text with Save & approve, and Cancel keeps the proposal', async () => {+ const onApprove = vi.fn();+ await render(write({ onApprove }));+ await click(action('approval.edit'));+ const box = $<HTMLTextAreaElement>('textarea')!;+ expect(box.getAttribute('aria-label')).toBe('New text');+ expect(box.value).toBe('Starter tracks 2.');+ await click(action('approval.cancelEdit'));+ expect($('textarea')).toBeNull();+ await click(action('approval.edit'));+ await act(async () => {+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;+ setter.call($('textarea'), 'Starter tracks ChatGPT and Copilot.');+ $('textarea')!.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await click(action('approval.saveAndApprove'));+ expect(onApprove).toHaveBeenCalledWith({+ text: 'Starter tracks ChatGPT and Copilot.',+ dontAskAgain: false,+ });+ });++ it('skips without the gate, and says what it is in each state', async () => {+ const onSkip = vi.fn();+ await render(write({ onSkip }), { isLocked: true });+ await click(action('approval.skip'));+ expect(onSkip).toHaveBeenCalledOnce();++ expect(APPROVAL_CARD_STATUSES).toEqual(['pending', 'saving', 'approved', 'skipped', 'error']);+ await render(write({ status: 'saving' }));+ expect(action('approval.approve')!.disabled).toBe(true);+ expect(action('approval.approve')!.getAttribute('aria-busy')).toBe('true');+ expect(action('approval.skip')!.disabled).toBe(true);++ await render(write({ status: 'error', error: 'Webflow didn’t answer.' }));+ expect($('[role="alert"]')!.textContent).toBe('Webflow didn’t answer.');+ expect(action('approval.approve')!.textContent).toBe('Retry');++ await render(write({ status: 'approved', doneLabel: 'cited passage changed' }));+ expect($('[data-slot="done-line"]')!.getAttribute('role')).toBe('status');+ expect($('[data-slot="done-line"]')!.textContent).toBe(+ 'Step 4 approved · cited passage changed',+ );+ expect($('button')).toBeNull();++ await render(write({ status: 'skipped' }));+ expect($('[role="status"]')!.textContent).toBe(+ 'Step 4 skipped · Change a cited passage on /pricing',+ );+ });++ it('shows an EXECUTE as the one dark "Needs your click" pill and a button naming the effect', async () => {+ const onApprove = vi.fn();+ const onPreview = vi.fn();+ await render(+ <ApprovalCard+ kind="execute"+ step={{ n: 6, total: 6 }}+ title="Publish the Webflow draft for /pricing"+ summary="FAQ block · Webflow draft “Pricing”"+ note="Goes live on ansvisor.com/pricing · same in every mode"+ actionLabel="Publish"+ busyLabel="Publishing…"+ previewLabel="Preview in Webflow"+ onPreview={onPreview}+ onApprove={onApprove}+ />,+ );+ expect($('[data-slot="agent-card"]')!.dataset.tone).toBe('click');+ const pills = $$('[data-slot="approval-pill"]');+ expect(pills).toHaveLength(1);+ expect(pills[0].dataset.state).toBe('click');+ expect(pills[0].textContent).toBe('Needs your click');+ expect(classOf(pills[0])).toContain('bg-foreground');+ expect(container.textContent).toContain('Step 6 of 6');+ expect(action('exec.publish')!.textContent).toBe('Publish');+ await click(action('exec.preview'));+ expect(onPreview).toHaveBeenCalledOnce();+ await click(action('exec.publish'));+ expect(onApprove).toHaveBeenCalledWith({ dontAskAgain: false });+ });++ it('keeps the click off until it can be made, with the reason, and says Publishing… while it works', async () => {+ const props = {+ kind: 'execute' as const,+ step: { n: 6, total: 6 },+ title: 'Publish',+ actionLabel: 'Publish',+ busyLabel: 'Publishing…',+ };+ await render(<ApprovalCard {...props} disabledReason="After the draft is approved" />);+ expect(action('exec.publish')!.disabled).toBe(true);+ expect(action('exec.publish')!.title).toBe('After the draft is approved');+ expect(container.textContent).toContain('After the draft is approved');+ await render(<ApprovalCard {...props} status="saving" />);+ expect(action('exec.publish')!.textContent).toBe('Publishing…');+ expect(action('exec.publish')!.disabled).toBe(true);+ await render(<ApprovalCard {...props} status="approved" doneLabel="Published · 14:32" />);+ expect($('[data-slot="done-line"]')!.textContent).toBe('Published · 14:32');+ });++ it('approves nothing while the workspace is read-only: the upgrade dialog opens', async () => {+ const onApprove = vi.fn();+ await render(write({ onApprove }), { isLocked: true });+ await click(action('approval.approve'));+ expect(openUpgrade).toHaveBeenLastCalledWith('Approving changes needs a plan');+ await click(action('approval.edit'));+ await click(action('approval.saveAndApprove'));+ expect(openUpgrade).toHaveBeenCalledTimes(2);+ await render(+ <ApprovalCard+ kind="execute"+ step={{ n: 6, total: 6 }}+ title="Publish"+ actionLabel="Publish"+ onApprove={onApprove}+ />,+ { isLocked: true },+ );+ await click(action('exec.publish'));+ expect(openUpgrade).toHaveBeenLastCalledWith('Going live needs a plan');+ expect(onApprove).not.toHaveBeenCalled();+ });+});++describe('RunSteps', () => {+ const running = [+ step(1, 'done', 'Read Action Center'),+ step(2, 'running', 'Read Citations', { detail: 'Last 30 days' }),+ ];++ it('is open while it runs, with the step count and the clock, and says each new step', async () => {+ expect(runClock(41_000)).toBe('0:41');+ expect(runClock(72_000)).toBe('1:12');+ await render(<RunSteps status="running" steps={running} workingMs={41_000} />);+ const header = $('button')!;+ expect(header.getAttribute('aria-expanded')).toBe('true');+ expect(header.textContent).toContain('Working on it');+ expect(header.textContent).toContain('2 steps · 0:41');+ const live = $('[aria-live]')!;+ expect(live.getAttribute('aria-live')).toBe('polite');+ expect(live.textContent).toBe('Step 2: Read Citations');+ expect(document.getElementById(header.getAttribute('aria-controls')!)!.hidden).toBe(false);++ // A new step starts: the same region says it.+ await render(+ <RunSteps+ status="running"+ steps={[+ ...running.slice(0, 1),+ step(2, 'done', 'Read Citations'),+ step(3, 'running', 'Opened /pricing'),+ ]}+ workingMs={52_000}+ />,+ );+ expect($$('[aria-live]')).toHaveLength(1);+ expect($('[aria-live]')!.textContent).toBe('Step 3: Opened /pricing');+ // Waiting on the person is the step it says.+ await render(+ <RunSteps+ status="waiting"+ steps={[step(1, 'done', 'Read'), step(2, 'waiting', 'Change a passage')]}+ workingMs={60_000}+ />,+ );+ expect($('[aria-live]')!.textContent).toBe('Step 2: Change a passage');+ });++ it('folds to "Worked for" once done, and opens on a click', async () => {+ const done = [+ step(1, 'done', 'Thinking · 3s', { kind: 'thinking' }),+ step(2, 'done', 'Read Action Center'),+ step(3, 'done', 'Read Citations'),+ ];+ await render(<RunSteps status="done" steps={done} workingMs={72_000} sources={4} />);+ const header = $('button')!;+ expect(header.getAttribute('aria-expanded')).toBe('false');+ expect(header.textContent).toContain('Worked for 1m 12s');+ expect(header.textContent).toContain('3 steps · 4 sources');+ expect($('[aria-live]')!.textContent).toBe('Worked for 1m 12s');+ expect($('[data-slot="step-list"]')!.parentElement!.hidden).toBe(true);+ await click(header);+ expect(header.getAttribute('aria-expanded')).toBe('true');+ expect($('[data-slot="step-list"]')!.parentElement!.hidden).toBe(false);++ await render(<RunSteps status="done" steps={done} workingMs={41_000} />);+ expect($('button')!.textContent).toContain('Worked for 41s');+ expect($('button')!.textContent).toContain('3 steps');+ expect($('button')!.textContent).not.toContain('sources');+ });++ it('shows a one-step run as that step’s line, and its rows', async () => {+ await render(+ <RunSteps+ status="done"+ steps={[+ step(1, 'done', 'Read Citations', { detail: 'Perplexity · Last 30 days', rowCount: 18 }),+ ]}+ workingMs={4_000}+ sources={1}+ />,+ );+ expect($('button')!.textContent).toContain('Read Citations · Perplexity · Last 30 days');+ expect($('button')!.textContent).toContain('18 rows');+ });++ it('says a stop and an error, and shows nothing without steps', async () => {+ await render(<RunSteps status="stopped" steps={running} workingMs={41_000} />);+ expect($('button')!.textContent).toContain('Stopped after 41s');+ await render(+ <RunSteps+ status="error"+ steps={[step(1, 'error', 'Read Citations', { detail: 'Timed out' })]}+ workingMs={9_000}+ />,+ );+ expect($('button')!.textContent).toContain('Stopped: something went wrong');+ expect($('[data-slot="step-marker"]')!.dataset.state).toBe('failed');+ expect(container.textContent).toContain('Timed out');+ await render(<RunSteps status="done" steps={[]} workingMs={0} />);+ expect(container.innerHTML).toBe('');+ });+});++describe('ResultCard', () => {+ const base = {+ title: 'Done. 4 tasks are ready for you to close.',+ summary: '6 of 6 steps · 2% of monthly AI limit',+ generatedAt: '2026-10-26T11:32:00Z',+ dataAsOf: '2026-10-26T05:00:00Z',+ timeZone: 'Europe/Istanbul',+ };++ it('says when it was made and what data it used, in absolute time with the offset', async () => {+ await render(<ResultCard state="done" {...base} />);+ const head = $('[data-slot="agent-head"]')!;+ expect(head.querySelector('[data-slot="agent-avatar"]')!.getAttribute('data-state')).toBe(+ 'done',+ );+ expect(head.textContent).toContain('Generated Oct 26, 2026 · 14:32');+ expect(head.textContent).toContain('Data as of Oct 26, 08:00');+ expect(head.querySelector('[title^="Generated"]')!.getAttribute('title')).toBe(+ 'Generated Oct 26, 2026 14:32 GMT+3',+ );+ await render(<ResultCard state="done" {...base} dataAsOf={null} />);+ expect(container.textContent).not.toContain('Data as of');+ });++ it('opens files only at a path in the app', async () => {+ await render(+ <ResultCard+ state="done"+ {...base}+ files={[+ { title: 'FAQ block', href: '/dashboard/content/library' },+ { title: 'Schema' },+ { title: 'Outside', href: 'https://example.com/x' },+ { title: 'Sneaky', href: '/dashboard/../admin' },+ ]}+ primary={{+ label: 'Close tasks',+ href: '/dashboard/action-center',+ action: 'done.closeTasksInActionCenter',+ }}+ />,+ );+ const opens = $$('[data-action="deliverable.open"]');+ expect(opens.map((a) => a.getAttribute('href'))).toEqual(['/dashboard/content/library']);+ expect(opens[0].textContent).toBe('Open');+ expect(action('done.closeTasksInActionCenter')!.getAttribute('href')).toBe(+ '/dashboard/action-center',+ );+ });++ it('shows counts, the steps under "Worked for", and the click that waits above it', async () => {+ await render(+ <ResultCard+ state="needsClick"+ {...base}+ title="Ready to go live. Publishing needs your click."+ run={{+ steps: [step(1, 'done', 'Read'), step(2, 'done', 'Wrote')],+ workingMs: 340_000,+ sources: 4,+ }}+ kpis={[{ label: 'Tasks ready', value: '4', note: 'of 4' }]}+ before={+ <ApprovalCard+ kind="execute"+ step={{ n: 6, total: 6 }}+ title="Publish"+ actionLabel="Publish"+ />+ }+ />,+ );+ expect($('[data-slot="agent-avatar"]')!.dataset.state).toBe('waiting');+ expect(container.textContent).toContain('Tasks ready4of 4');+ expect($('[data-slot="run-steps"] button')!.textContent).toContain('Worked for 5m 40s');+ expect($('[data-slot="run-steps"] button')!.textContent).toContain('2 steps · 4 sources');+ // The click card comes before the result.+ const cards = $$('[data-slot="agent-card"]');+ expect(cards[0].dataset.tone).toBe('click');+ });+});++describe('DenialCard', () => {+ const role = {+ title: 'I can’t add these prompts for you',+ asked: 'Add 5 prompts to Tracked Prompts for Ansvisor.',+ askedItems: ['best aeo tools', 'aeo vs seo'],+ why: 'Your role is Analyst. Adding prompts needs Manager or Admin.',+ whySource: 'Role rule · Settings › Team › Roles & access',+ whoCan: 'Admins and Managers can do this.',+ nextActions: ['ask_admin', 'see_access'] as const,+ };++ it('answers in four parts: what was asked, why not, who can, what next', async () => {+ await render(+ <DenialCard {...role} nextActions={[...role.nextActions]} onAskAdmin={() => {}} />,+ );+ expect($$('dt').map((dt) => dt.textContent)).toEqual([+ 'You asked',+ 'Why not',+ 'Who can',+ 'Next',+ ]);+ expect($('[data-part="asked"]')!.textContent).toBe(+ 'Add 5 prompts to Tracked Prompts for Ansvisor.best aeo toolsaeo vs seo',+ );+ expect($('[data-part="why"]')!.textContent).toBe(+ 'Your role is Analyst. Adding prompts needs Manager or Admin.Role rule · Settings › Team › Roles & access',+ );+ expect($('[data-part="who"]')!.textContent).toBe(+ 'Admins and Managers can do this.Your request goes to the workspace Admins, in the app',+ );+ const next = [...$('[data-part="next"]')!.children] as HTMLElement[];+ expect(next.map((el) => [el.dataset.action, el.textContent])).toEqual([+ ['access.askAdmin', 'Ask your Admin'],+ ['access.see', 'See your access ↗'],+ ]);+ expect(next[1].getAttribute('href')).toBe('/dashboard/settings/team');+ });++ it('adds what the next plan unlocks for a plan gate, and links plans to Billing', async () => {+ await render(+ <DenialCard+ title="Full auto needs Growth"+ asked="Run /winback in Full auto."+ why="Full auto needs Growth. Your plan: Starter."+ whoCan="Admins can change the plan."+ nextActions={['upgrade', 'compare_plans']}+ extra={{+ label: 'Growth adds',+ items: [{ title: 'Full auto', detail: 'logged and undoable' }],+ note: '$249 a month',+ }}+ />,+ );+ expect($$('dt').map((dt) => dt.textContent)).toEqual([+ 'You asked',+ 'Why not',+ 'Who can',+ 'Growth adds',+ 'Next',+ ]);+ expect($('[data-part="who"]')!.textContent).toBe('Admins can change the plan.');+ expect(action('plan.upgrade')!.getAttribute('href')).toBe('/dashboard/settings/billing');+ expect(action('plan.compare')!.getAttribute('href')).toBe('/dashboard/settings/billing');+ });++ it('shows See tool policy only once its page has an address', async () => {+ const policy = {+ title: 'Your Admin set this tool to Never',+ asked: 'Send 4 outreach emails.',+ why: 'Your Admin set this tool to Never.',+ whoCan: 'Admins can change the tool policy.',+ nextActions: ['ask_admin', 'open_policy'] as ('ask_admin' | 'open_policy')[],+ };+ await render(<DenialCard {...policy} />);+ expect(action('policy.open')).toBeNull();+ await render(<DenialCard {...policy} hrefs={{ open_policy: '/dashboard/settings/chat' }} />);+ expect(action('policy.open')!.getAttribute('href')).toBe('/dashboard/settings/chat');+ });++ it('sends Ask your Admin once, then says Sent', async () => {+ let resolve!: () => void;+ const onAskAdmin = vi.fn(() => new Promise<void>((r) => (resolve = r)));+ await render(+ <DenialCard {...role} nextActions={[...role.nextActions]} onAskAdmin={onAskAdmin} />,+ );+ await click(action('access.askAdmin'));+ expect(action('access.askAdmin')!.disabled).toBe(true);+ expect(action('access.askAdmin')!.getAttribute('aria-busy')).toBe('true');+ await act(async () => resolve());+ expect(action('access.askAdmin')!.textContent).toBe('Sent');+ expect(action('access.askAdmin')!.disabled).toBe(true);+ expect(toast.success).toHaveBeenCalledWith('Sent to your Admins');+ expect(onAskAdmin).toHaveBeenCalledOnce();+ });++ it('says a request that failed, and sends nothing while read-only', async () => {+ await render(+ <DenialCard+ {...role}+ nextActions={[...role.nextActions]}+ onAskAdmin={() => Promise.reject(new Error('down'))}+ />,+ );+ await click(action('access.askAdmin'));+ expect($('[role="alert"]')!.textContent).toBe('Couldn’t send it. Try again.');+ expect(action('access.askAdmin')!.disabled).toBe(false);++ const onAskAdmin = vi.fn();+ await render(+ <DenialCard {...role} nextActions={[...role.nextActions]} onAskAdmin={onAskAdmin} />,+ {+ isLocked: true,+ },+ );+ await click(action('access.askAdmin'));+ expect(onAskAdmin).not.toHaveBeenCalled();+ expect(openUpgrade).toHaveBeenCalledWith('Sending a request needs a plan');+ });+});++describe('ErrorCard', () => {+ const rows: StepRow[] = [+ { n: 1, label: 'Read 48 products', state: 'done' },+ {+ n: 2,+ label: 'Update 12 titles',+ detail: 'Google Merchant Center isn’t connected',+ state: 'failed',+ pill: 'asks',+ },+ { n: 3, label: 'Push the feed', state: 'pending', pill: 'click' },+ ];++ it('shows the agent in red, where it stopped and why, and Retry from that step', async () => {+ const onRetry = vi.fn();+ await render(+ <ErrorCard+ title="Merchant feed fix · EU"+ reason="Google Merchant Center isn’t connected · nothing was changed"+ steps={rows}+ failedStep={2}+ onRetry={onRetry}+ />,+ );+ const head = $('[data-slot="agent-head"]')!;+ expect(head.querySelector('[data-slot="agent-avatar"]')!.getAttribute('data-state')).toBe(+ 'failed',+ );+ expect(head.textContent).toContain('Stopped at step 2 of 3');+ expect(head.textContent).toContain('nothing was changed');+ expect($('[data-slot="agent-card"]')!.dataset.tone).toBe('failed');+ expect($('[data-slot="status-pill"]')!.textContent).toBe('Failed');+ expect($$('[data-slot="step-marker"]').map((m) => m.dataset.state)).toEqual([+ 'done',+ 'failed',+ 'pending',+ ]);+ expect(container.textContent).toContain('Retry starts again from step 2');+ expect(action('run.retryStep')!.textContent).toBe('Retry step 2');+ await click(action('run.retryStep'));+ expect(onRetry).toHaveBeenCalledOnce();+ });++ it('retries the whole run after an error outside a step, and nothing while read-only', async () => {+ const onRetry = vi.fn();+ await render(+ <ErrorCard title="Run" reason="Something went wrong" steps={[]} onRetry={onRetry} />,+ {+ isLocked: true,+ },+ );+ expect($('[data-slot="agent-head"]')!.textContent).toContain('Stopped: something went wrong');+ expect(action('run.retry')!.textContent).toBe('Retry');+ await click(action('run.retry'));+ expect(onRetry).not.toHaveBeenCalled();+ expect(openUpgrade).toHaveBeenCalledWith('Retrying a run needs a plan');+ });+});++describe('every card', () => {+ async function renderAll() {+ await render(+ <>+ <PlanCard+ title="Plan"+ steps={PLAN}+ mode="auto"+ connections={[{ name: 'Shopify', connected: false }]}+ />+ <RunSteps status="running" steps={[step(1, 'running', 'Read')]} workingMs={1000} />+ <RunSteps+ status="done"+ steps={[step(1, 'done', 'Read'), step(2, 'done', 'Wrote')]}+ workingMs={1000}+ />+ <ApprovalCard+ step={{ n: 4, total: 6 }}+ title="Change"+ change={CHANGE}+ canDontAskAgain+ status="saving"+ />+ <ApprovalCard step={{ n: 4, total: 6 }} title="Change" status="approved" />+ <ApprovalCard step={{ n: 4, total: 6 }} title="Change" status="error" error="Failed" />+ <ApprovalCard+ kind="execute"+ step={{ n: 6, total: 6 }}+ title="Publish"+ actionLabel="Publish"+ />+ <ResultCard+ state="done"+ title="Done"+ generatedAt="2026-10-26T11:32:00Z"+ kpis={[{ label: 'Tasks', value: '4', note: 'of 4' }]}+ />+ <DenialCard+ title="No"+ asked="Add"+ why="Role"+ whoCan="Admins"+ nextActions={['ask_admin']}+ onAskAdmin={() => {}}+ />+ <ErrorCard+ title="Run"+ reason="Failed"+ steps={[{ n: 1, label: 'Read', state: 'failed' }]}+ failedStep={1}+ retrying+ />+ </>,+ );+ }++ it('stops every motion with reduced motion', async () => {+ await renderAll();+ const moving = $$('[class*="animate-"]');+ expect(moving.length).toBeGreaterThan(10);+ for (const el of moving) expect(classOf(el)).toContain('motion-reduce:animate-none');+ for (const el of $$('[class*="rotate-"], [class*="transition-transform"]')) {+ expect(classOf(el)).toContain('motion-reduce:transition-none');+ }+ });++ it('gives each coloured state its dark-theme colour', async () => {+ await renderAll();+ for (const el of $$('*')) {+ const cls = classOf(el).split(/\s+/);+ for (const hue of ['green', 'amber', 'red']) {+ for (const c of cls.filter((c) => new RegExp(`^(bg|text|border|ring)-${hue}-`).test(c))) {+ const kind = c.slice(0, c.indexOf(`-${hue}-`));+ expect(+ cls.some((d) => d.startsWith(`dark:${kind}-${hue}-`)),+ c,+ ).toBe(true);+ }+ }+ }+ });++ it('gives every control a data-action id', async () => {+ await renderAll();+ const controls = $$('button, a, input, textarea');+ expect(controls.length).toBeGreaterThan(10);+ for (const el of controls) expect(el.dataset.action, el.outerHTML.slice(0, 80)).toBeTruthy();+ });+});diff --git a/web/src/components/agentic/denial-card.tsx b/web/src/components/agentic/denial-card.tsxnew file mode 100644index 000000000..4a063b526--- /dev/null+++ b/web/src/components/agentic/denial-card.tsx@@ -0,0 +1,241 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2 } from 'lucide-react';+import { toast } from 'sonner';+import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button-variants';+import { CHOOSE_PLAN_HREF, useUpgradeGate } from '@/components/providers/upgrade-gate';+import type { ChatHref } from '@/lib/chat/events';+import { cn } from '@/lib/utils';+import { AgentCard, AgentHead } from './agent-card';+import { TICK_CIRCLE, TickIcon } from './done-tick';++/** What a denial offers next (CHAT-20 §4c part 4); the server's list, in its order. */+export type DenialNextAction =+ | 'ask_admin'+ | 'see_access'+ | 'upgrade'+ | 'choose_plan'+ | 'compare_plans'+ | 'open_policy';++export const DENIAL_NEXT_ACTIONS: readonly DenialNextAction[] = [+ 'ask_admin',+ 'see_access',+ 'upgrade',+ 'choose_plan',+ 'compare_plans',+ 'open_policy',+];++type DenialLink = Exclude<DenialNextAction, 'ask_admin'>;++/** Each next step's CHAT-23 id. */+const ACTION_ID: Record<DenialNextAction, string> = {+ ask_admin: 'access.askAdmin',+ see_access: 'access.see',+ upgrade: 'plan.upgrade',+ choose_plan: 'plan.upgrade',+ compare_plans: 'plan.compare',+ open_policy: 'policy.open',+};++/**+ * Where the links go today: Roles & access is in Settings › Team (CHAT-20+ * §4a); plans are in Settings › Billing. Settings › Chat's tool policy comes+ * with its own page (B3): until then See tool policy needs its href given.+ */+const DEFAULT_HREFS: Partial<Record<DenialLink, ChatHref>> = {+ see_access: '/dashboard/settings/team',+ upgrade: CHOOSE_PLAN_HREF,+ choose_plan: CHOOSE_PLAN_HREF,+ compare_plans: CHOOSE_PLAN_HREF,+};++type AskState = 'idle' | 'sending' | 'sent' | 'error';++/**+ * The out-of-permission answer (CHAT-mockup-v2 `#s-denied`, CHAT-20 §4c): no+ * silent failure, never a bare error, in four parts — what was asked, why not+ * (the exact rule and where it is set), who can (by role, never a person), and+ * what to do next as buttons. The parts come from the server's denial (A3's+ * buildDenial), never from the model. For a plan gate, what the next plan+ * adds (`extra`). Ask your Admin sends the request through `onAskAdmin`+ * (B2's access.request), through the read-only gate, then says Sent.+ */+export function DenialCard({+ title,+ subtitle,+ asked,+ askedItems,+ why,+ whySource,+ whoCan,+ nextActions,+ extra,+ hrefs,+ footnote,+ onAskAdmin,+}: {+ /** The agent's line: "I can't add these prompts for you". */+ title: string;+ subtitle?: string;+ /** 1. What was asked, in the person's words. */+ asked: string;+ /** What the ask lists ("best aeo tools", "aeo vs seo"…), as small tiles. */+ askedItems?: string[];+ /** 2. Why not: the rule. */+ why: string;+ /** Where the rule is set: "Settings › Team › Roles & access"; null for nowhere. */+ whySource?: string | null;+ /** 3. Who can: "Admins and Managers can do this." */+ whoCan: string;+ /** 4. What next. */+ nextActions: DenialNextAction[];+ /** A plan gate's "Growth adds" list and its price line. */+ extra?: { label: string; items: { title: string; detail?: string }[]; note?: string };+ /** Overrides or adds where a link goes. */+ hrefs?: Partial<Record<DenialLink, ChatHref>>;+ /** The quiet line under it: "Nothing was changed · nothing outside your access was shown". */+ footnote?: string;+ /** Sends the request to the workspace's Admins; a rejection shows Retry. */+ onAskAdmin?: () => void | Promise<unknown>;+}) {+ const t = useTranslations('agentic.denialCard');+ const { guard } = useUpgradeGate();+ const [ask, setAsk] = useState<AskState>('idle');+ const links = { ...DEFAULT_HREFS, ...hrefs };+ const shown = nextActions.filter((a) => a === 'ask_admin' || links[a]);++ const askAdmin = guard(+ async () => {+ setAsk('sending');+ try {+ await onAskAdmin?.();+ setAsk('sent');+ toast.success(t('sentToast'));+ } catch {+ setAsk('error');+ }+ },+ { action: t('askNeedsPlan') },+ );++ return (+ <div data-slot="denial-card">+ <AgentHead state="idle" title={title} subtitle={subtitle} />+ <AgentCard aria-label={title}>+ <dl className="m-0 grid grid-cols-1 gap-x-3.5 gap-y-2.5 px-3.5 py-3 text-[13.5px] sm:grid-cols-[88px_minmax(0,1fr)]">+ <dt className={DT}>{t('asked')}</dt>+ <dd data-part="asked" className={DD}>+ {asked}+ {askedItems && askedItems.length > 0 && (+ <span className="mt-1.5 flex flex-wrap gap-1">+ {askedItems.map((item) => (+ <span+ key={item}+ className="max-w-full truncate rounded-lg border bg-muted px-[9px] py-[3px] text-[12.5px]"+ >+ {item}+ </span>+ ))}+ </span>+ )}+ </dd>+ <dt className={DT}>{t('why')}</dt>+ <dd data-part="why" className={DD}>+ {why}+ {whySource && <span className={EM}>{whySource}</span>}+ </dd>+ <dt className={DT}>{t('who')}</dt>+ <dd data-part="who" className={DD}>+ {whoCan}+ {nextActions.includes('ask_admin') && <span className={EM}>{t('requestGoes')}</span>}+ </dd>+ {extra && (+ <>+ <dt className={DT}>{extra.label}</dt>+ <dd className={DD}>+ <ul className="m-0 mt-1.5 mb-0.5 grid list-none gap-1.5 p-0 text-[13px]">+ {extra.items.map((item) => (+ <li+ key={item.title}+ className="grid grid-cols-[20px_minmax(0,1fr)] items-start gap-2"+ >+ <span+ aria-hidden+ className={cn(+ 'flex size-5 items-center justify-center rounded-full',+ TICK_CIRCLE,+ )}+ >+ <TickIcon className="size-[13px]" />+ </span>+ <span>+ <b className="font-semibold">{item.title}</b>+ {item.detail && (+ <span className="text-muted-foreground"> · {item.detail}</span>+ )}+ </span>+ </li>+ ))}+ </ul>+ {extra.note && <span className={EM}>{extra.note}</span>}+ </dd>+ </>+ )}+ {shown.length > 0 && (+ <>+ <dt className={DT}>{t('next')}</dt>+ <dd data-part="next" className={cn(DD, 'flex flex-wrap gap-1.5')}>+ {shown.map((action, i) =>+ action === 'ask_admin' ? (+ <Button+ key={action}+ data-action={ACTION_ID[action]}+ size="sm"+ variant={i === 0 ? 'default' : 'outline'}+ disabled={ask === 'sending' || ask === 'sent' || !onAskAdmin}+ aria-busy={ask === 'sending' || undefined}+ onClick={askAdmin}+ >+ {ask === 'sending' && (+ <Loader2 aria-hidden className="animate-spin motion-reduce:animate-none" />+ )}+ {ask === 'sent' ? t('sent') : t('actions.ask_admin')}+ </Button>+ ) : (+ <Link+ key={action}+ href={links[action]!}+ data-action={ACTION_ID[action]}+ className={buttonVariants({+ variant: i === 0 ? 'default' : 'outline',+ size: 'sm',+ })}+ >+ {t(`actions.${action}`)}+ </Link>+ ),+ )}+ {ask === 'error' && (+ <span role="alert" className="w-full text-xs text-red-700 dark:text-red-300">+ {t('sendFailed')}+ </span>+ )}+ </dd>+ </>+ )}+ </dl>+ </AgentCard>+ {footnote && <p className="-mt-2 mb-4 text-[11.5px] text-muted-foreground">{footnote}</p>}+ </div>+ );+}++const DT = 'pt-[3px] text-[11px] tracking-[.4px] text-muted-foreground uppercase';+const DD = 'm-0 min-w-0';+const EM = 'block text-xs text-muted-foreground';diff --git a/web/src/components/agentic/error-card.tsx b/web/src/components/agentic/error-card.tsxnew file mode 100644index 000000000..3b5bb9cc6--- /dev/null+++ b/web/src/components/agentic/error-card.tsx@@ -0,0 +1,83 @@+'use client';++import type { ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { Loader2 } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import {+ AgentCard,+ AgentCardBody,+ AgentCardFooter,+ AgentCardHeader,+ AgentHead,+} from './agent-card';+import { StatusPill } from './status-pill';+import { StepList, type StepRow } from './step-list';++/**+ * A run that stopped on an error (CHAT-mockup-v2 `#s-failed`, CHAT-03 items+ * 16–18): the agent in red, where it stopped and the plain reason, nothing+ * changed; its steps, the failed one with "!" and its reason; and Retry, from+ * the failed step ("Retry step 2", CHAT-23 `run.retryStep`) or the whole run+ * (`run.retry`), through the read-only gate. Never a tool's name or a raw+ * error (CHAT-23 P9).+ */+export function ErrorCard({+ title,+ reason,+ steps,+ failedStep,+ retrying = false,+ onRetry,+ extraAction,+}: {+ /** The run's name: "Merchant feed fix · EU". */+ title: string;+ /** The plain reason: "Google Merchant Center isn't connected · nothing was changed". */+ reason: string;+ steps: StepRow[];+ /** The step it stopped at, from 1; none for an error outside a step. */+ failedStep?: number;+ retrying?: boolean;+ onRetry?: () => void;+ /** A way out beside Retry, such as Connect Google Merchant Center. */+ extraAction?: ReactNode;+}) {+ const t = useTranslations('agentic.errorCard');+ const { guard } = useUpgradeGate();+ const total = steps.length;+ const retry = guard(() => onRetry?.(), { action: t('retryNeedsPlan') });++ return (+ <div data-slot="error-card">+ <AgentHead+ state="failed"+ title={failedStep && total > 0 ? t('stoppedAt', { n: failedStep, total }) : t('stopped')}+ subtitle={reason}+ />+ <AgentCard tone="failed" aria-label={title}>+ <AgentCardHeader title={title} end={<StatusPill state="failed" />} />+ {steps.length > 0 && (+ <AgentCardBody>+ <StepList rows={steps} />+ </AgentCardBody>+ )}+ <AgentCardFooter note={failedStep ? t('retryFrom', { n: failedStep }) : undefined}>+ {extraAction}+ <Button+ data-action={failedStep ? 'run.retryStep' : 'run.retry'}+ disabled={retrying || !onRetry}+ aria-busy={retrying || undefined}+ onClick={retry}+ >+ {retrying && (+ <Loader2 aria-hidden className="animate-spin motion-reduce:animate-none" />+ )}+ {failedStep ? t('retryStep', { n: failedStep }) : t('retry')}+ </Button>+ </AgentCardFooter>+ </AgentCard>+ </div>+ );+}diff --git a/web/src/components/agentic/plan-card.tsx b/web/src/components/agentic/plan-card.tsxnew file mode 100644index 000000000..8b85dadd6--- /dev/null+++ b/web/src/components/agentic/plan-card.tsx@@ -0,0 +1,261 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { ArrowDown, ArrowUp, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import { cn } from '@/lib/utils';+import type { ApprovalPillKind } from './approval-pill';+import {+ AgentCard,+ AgentCardBody,+ AgentCardFooter,+ AgentCardHeader,+ AgentHead,+ CardPill,+} from './agent-card';+import { StepList, type StepRow } from './step-list';++/** A step's action class (CHAT-20 §3): READ runs, WRITE changes, EXECUTE goes live or leaves. */+export type PlanStepClass = 'read' | 'write' | 'execute';++/** How much the agent does alone (Chat agentic plan §2, CHAT-20 §5). */+export type ChatRunMode = 'ask_first' | 'auto' | 'full_auto';++export interface PlanStep {+ label: string;+ /** The grey line: what it uses, or what it changes. */+ detail?: string;+ cls: PlanStepClass;+ /** The precedence's own answer for this step, when the server has it; else from the class and mode. */+ pill?: ApprovalPillKind;+}++export interface PlanConnection {+ name: string;+ connected: boolean;+}++/**+ * The pill a plan step wears (the mockup's tagFor, CHAT-23 P10): an EXECUTE+ * always needs a click; a WRITE asks, or runs and is logged in Full auto; a+ * READ runs by itself, but asks in Ask me first.+ */+export function planStepPill(cls: PlanStepClass, mode: ChatRunMode): ApprovalPillKind {+ if (cls === 'execute') return 'click';+ if (cls === 'write') return mode === 'full_auto' ? 'logged' : 'asks';+ return mode === 'ask_first' ? 'asks' : 'auto';+}++/**+ * The plan card (CHAT-mockup-v2 `#s-plan`): before anything runs, the steps+ * with how each one runs, what the run uses and connects to, about how long+ * and how much of the monthly AI limit, and what it makes; then Edit plan and+ * Start. Nothing changes before Start (CHAT-23 `plan.start`, through the+ * read-only gate). Edit plan lets the person move or remove steps; Start runs+ * the edited plan. A role that can't start runs gets Ask your Admin instead.+ */+export function PlanCard({+ title,+ due,+ steps,+ mode,+ uses,+ connections = [],+ time,+ aiUsage,+ outputs,+ canStart = true,+ onStart,+ onAskAdmin,+ onConnect,+}: {+ title: string;+ /** "Due Fri, Oct 30" */+ due?: string;+ steps: PlanStep[];+ mode: ChatRunMode;+ /** "Action Center · 52 sources · 2 live pages" */+ uses?: string;+ connections?: PlanConnection[];+ /** "6 min" */+ time?: string;+ /** "~2%" */+ aiUsage?: string;+ /** "FAQ draft, schema code, report" */+ outputs?: string;+ /** False for a role that can't start runs: Ask your Admin instead of Start. */+ canStart?: boolean;+ /** Starts the run with the steps as the person left them. */+ onStart?: (steps: PlanStep[]) => void;+ onAskAdmin?: () => void;+ /** Connect a tool the plan needs (an Admin's: CHAT-23 `integrations.connect`). */+ onConnect?: (name: string) => void;+}) {+ const t = useTranslations('agentic.planCard');+ const { guard } = useUpgradeGate();+ const [editing, setEditing] = useState(false);+ const [plan, setPlan] = useState(steps);++ const move = (from: number, to: number) =>+ setPlan((current) => {+ const next = [...current];+ const [step] = next.splice(from, 1);+ next.splice(to, 0, step);+ return next;+ });+ const remove = (index: number) => setPlan((current) => current.filter((_, i) => i !== index));++ const rows: StepRow[] = plan.map((step, i) => ({+ n: i + 1,+ label: step.label,+ detail: step.detail,+ state: 'pending',+ pill: step.pill ?? planStepPill(step.cls, mode),+ }));+ const missing = connections.filter((c) => !c.connected);++ return (+ <div data-slot="plan-card">+ <AgentHead state="idle" title={t('head')} />+ <AgentCard aria-label={title}>+ <AgentCardHeader title={title} end={due ? <CardPill>{due}</CardPill> : undefined} />+ <AgentCardBody>+ <StepList+ rows={rows}+ controls={+ editing+ ? (_, i) => (+ <span className="flex gap-0.5 self-center">+ <Button+ data-action="plan.moveStepUp"+ variant="ghost"+ size="icon-sm"+ aria-label={t('moveUp')}+ disabled={i === 0}+ onClick={() => move(i, i - 1)}+ >+ <ArrowUp />+ </Button>+ <Button+ data-action="plan.moveStepDown"+ variant="ghost"+ size="icon-sm"+ aria-label={t('moveDown')}+ disabled={i === plan.length - 1}+ onClick={() => move(i, i + 1)}+ >+ <ArrowDown />+ </Button>+ <Button+ data-action="plan.removeStep"+ variant="ghost"+ size="icon-sm"+ aria-label={t('remove')}+ disabled={plan.length === 1}+ onClick={() => remove(i)}+ >+ <X />+ </Button>+ </span>+ )+ : undefined+ }+ />+ {missing.map((c) => (+ <div+ key={c.name}+ className="mt-1.5 flex flex-wrap items-center gap-2 rounded-[10px] border border-amber-200 bg-amber-50 px-2.5 py-1.5 text-[12.5px] text-amber-900 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-200"+ >+ {t('notConnected', { name: c.name })}+ {onConnect && (+ <Button+ data-action="integrations.connect"+ variant="outline"+ size="sm"+ className="ml-auto"+ onClick={() => onConnect(c.name)}+ >+ {t('connect', { name: c.name })}+ </Button>+ )}+ </div>+ ))}+ </AgentCardBody>+ <div className="flex flex-wrap gap-3.5 border-t bg-muted/50 px-3.5 py-2.5 text-xs text-muted-foreground">+ {uses && (+ <span>+ {t('uses')} <b className="font-medium text-foreground">{uses}</b>+ </span>+ )}+ {connections.map((c) => (+ <span+ key={c.name}+ className="inline-flex items-center gap-1"+ title={c.connected ? t('connected') : t('notConnected', { name: c.name })}+ >+ <span+ aria-hidden+ className={cn(+ 'size-1.5 rounded-full',+ c.connected ? 'bg-green-600 dark:bg-green-400' : 'bg-foreground/20',+ )}+ />+ <b className={cn('font-medium', c.connected && 'text-foreground')}>{c.name}</b>+ </span>+ ))}+ {time && (+ <span>+ {t('about')} <b className="font-medium text-foreground">{time}</b>+ </span>+ )}+ {aiUsage && (+ <span>+ {t('aiUsage')}{' '}+ <b className="font-medium text-foreground">{t('aiUsageValue', { value: aiUsage })}</b>+ </span>+ )}+ {outputs && (+ <span>+ {t('outputs')} <b className="font-medium text-foreground">{outputs}</b>+ </span>+ )}+ </div>+ <AgentCardFooter+ note={+ <>+ {t('mode')} <b className="font-medium text-foreground">{t(`modes.${mode}`)}</b>+ </>+ }+ >+ {canStart && (+ <Button+ data-action="plan.edit"+ variant="outline"+ aria-pressed={editing}+ onClick={() => setEditing((on) => !on)}+ >+ {editing ? t('doneEditing') : t('edit')}+ </Button>+ )}+ {canStart ? (+ <Button+ data-action="plan.start"+ onClick={guard(() => onStart?.(plan), { action: t('startNeedsPlan') })}+ >+ {t('start')}+ </Button>+ ) : (+ <Button+ data-action="access.askAdmin"+ onClick={guard(() => onAskAdmin?.(), { action: t('askNeedsPlan') })}+ >+ {t('askAdmin')}+ </Button>+ )}+ </AgentCardFooter>+ </AgentCard>+ </div>+ );+}diff --git a/web/src/components/agentic/result-card.tsx b/web/src/components/agentic/result-card.tsxnew file mode 100644index 000000000..e35edb744--- /dev/null+++ b/web/src/components/agentic/result-card.tsx@@ -0,0 +1,218 @@+'use client';++import type { ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import { Link } from '@/i18n/navigation';+import { buttonVariants } from '@/components/ui/button-variants';+import { isChatHref, type ChatHref, type ChatStep } from '@/lib/chat/events';+import { AgentCard, AgentCardBody, AgentCardFooter, AgentHead } from './agent-card';+import { RunSteps } from './run-steps';++/** Done: everything ran. needsClick: done but for a step that goes live on the person's click. */+export type ResultCardState = 'done' | 'needsClick';++export interface ResultKpi {+ /** "Tasks ready" */+ label: string;+ /** "4" */+ value: string;+ /** "of 4" */+ note?: string;+}++export interface ResultFile {+ /** A short glyph for its tile: "≡", "{ }", "▤". */+ icon?: string;+ title: string;+ /** "6 questions · HTML + Markdown · in Files" */+ meta?: string;+ /** Its Open: a path in the app only (A1's ChatHref); anything else shows no Open. */+ href?: string;+}++/** "Oct 26, 2026", "14:32", "Oct 26" and the GMT offset of an instant, in a time zone. */+export function stampParts(iso: string, timeZone?: string) {+ const at = new Date(iso);+ const date = at.toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ timeZone,+ });+ const day = at.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone });+ const time = at.toLocaleTimeString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ hourCycle: 'h23',+ timeZone,+ });+ const offset =+ new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'shortOffset' })+ .formatToParts(at)+ .find((part) => part.type === 'timeZoneName')?.value ?? '';+ return { date, day, time, offset };+}++/**+ * The result card (CHAT-mockup-v2 `#s-done`, CHAT-03 v2, CHAT-23 G7): the+ * agent's line in the run's end state, with what it did, and when — an+ * absolute "Generated Oct 26, 2026 · 14:32" and "Data as of …" when it read+ * workspace data, the GMT offset in their tooltips, never a relative time+ * alone; the run's steps folded under "Worked for …"; the counts; the files+ * it made, each with Open into the app; and a footer with one next action.+ * A step that goes live waits as its own click card (`before`, above it).+ */+export function ResultCard({+ state,+ title,+ summary,+ generatedAt,+ dataAsOf,+ timeZone,+ run,+ kpis = [],+ files = [],+ note,+ primary,+ before,+ children,+}: {+ state: ResultCardState;+ /** "Done. 4 tasks are ready for you to close." */+ title: string;+ /** "6 of 6 steps · Auto (Haiku 5.5 + Sonnet 5.5) · 2% of monthly AI limit" */+ summary?: string;+ /** ISO. */+ generatedAt: string;+ /** ISO; null when the run read no workspace data. */+ dataAsOf?: string | null;+ /** The IANA time zone the answer was shown in (chat_messages.timezone). */+ timeZone?: string;+ run?: { steps: ChatStep[]; workingMs: number; sources?: number };+ kpis?: ResultKpi[];+ files?: ResultFile[];+ note?: string;+ /** The footer's one next action, with its CHAT-23 id ("done.closeTasksInActionCenter"). */+ primary?: { label: string; href: ChatHref; action: string };+ /** The EXECUTE click card that waits, shown above the result. */+ before?: ReactNode;+ /** Follow-up checks and the like, inside the card under the files. */+ children?: ReactNode;+}) {+ const t = useTranslations('agentic.resultCard');+ const generated = stampParts(generatedAt, timeZone);+ const data = dataAsOf ? stampParts(dataAsOf, timeZone) : null;+ const stamps = (+ <span suppressHydrationWarning>+ <span+ title={t('generatedTip', {+ full: `${generated.date} ${generated.time} ${generated.offset}`.trim(),+ })}+ >+ {t('generated', { date: generated.date, time: generated.time })}+ </span>+ {data && (+ <>+ {' · '}+ <span+ title={t('dataAsOfTip', { full: `${data.date} ${data.time} ${data.offset}`.trim() })}+ >+ {t('dataAsOf', { date: data.day, time: data.time })}+ </span>+ </>+ )}+ </span>+ );+ const showPrimary = primary && isChatHref(primary.href);++ return (+ <div data-slot="result-card" data-state={state}>+ <AgentHead+ state={state === 'done' ? 'done' : 'waiting'}+ title={title}+ subtitle={summary}+ note={stamps}+ />+ {before}+ <AgentCard aria-label={t('summary')}>+ <AgentCardBody className="pt-3">+ {run && run.steps.length > 0 && (+ <RunSteps+ status="done"+ steps={run.steps}+ workingMs={run.workingMs}+ sources={run.sources}+ className="mb-2"+ />+ )}+ {kpis.length > 0 && (+ <div className="my-2 grid grid-cols-1 gap-2 sm:grid-cols-3">+ {kpis.map((kpi) => (+ <div+ key={kpi.label}+ className="rounded-[14px] border bg-card px-3 py-2.5 shadow-[0_1px_2px_rgba(10,10,10,.04)]"+ >+ <span className="block text-[11.5px] text-muted-foreground">{kpi.label}</span>+ <b className="text-[28px] leading-[1.15] font-semibold tracking-[-0.6px] tabular-nums">+ {kpi.value}+ </b>+ {kpi.note && (+ <span className="ml-1 text-[11.5px] text-green-700 dark:text-green-400">+ {kpi.note}+ </span>+ )}+ </div>+ ))}+ </div>+ )}+ {files.length > 0 && (+ <ul aria-label={t('files')} className="m-0 my-2 grid list-none gap-1.5 p-0">+ {files.map((file) => (+ <li+ key={file.title}+ className="grid min-h-[50px] grid-cols-[30px_minmax(0,1fr)_auto] items-center gap-2.5 rounded-xl border px-2.5 py-2 text-[13px]"+ >+ <span+ aria-hidden+ className="flex size-[30px] items-center justify-center rounded-lg border bg-muted text-[13px]"+ >+ {file.icon ?? '≡'}+ </span>+ <span className="min-w-0 truncate">+ {file.title}+ {file.meta && (+ <span className="block truncate text-xs text-muted-foreground">+ {file.meta}+ </span>+ )}+ </span>+ {isChatHref(file.href) ? (+ <Link+ href={file.href}+ data-action="deliverable.open"+ className={buttonVariants({ variant: 'outline', size: 'sm' })}+ >+ {t('open')}+ </Link>+ ) : (+ <span />+ )}+ </li>+ ))}+ </ul>+ )}+ {children}+ </AgentCardBody>+ {(note || showPrimary) && (+ <AgentCardFooter note={note}>+ {showPrimary && (+ <Link href={primary.href} data-action={primary.action} className={buttonVariants()}>+ {primary.label}+ </Link>+ )}+ </AgentCardFooter>+ )}+ </AgentCard>+ </div>+ );+}diff --git a/web/src/components/agentic/run-steps.tsx b/web/src/components/agentic/run-steps.tsxnew file mode 100644index 000000000..e4da61dbf--- /dev/null+++ b/web/src/components/agentic/run-steps.tsx@@ -0,0 +1,136 @@+'use client';++import { useId, useState } from 'react';+import { useTranslations } from 'next-intl';+import { ChevronDown } from 'lucide-react';+import type { ChatStep } from '@/lib/chat/events';+import { cn } from '@/lib/utils';+import { DoneTick } from './done-tick';+import { ListDot } from './list-dot';+import { StepList, stepRowFrom } from './step-list';++/** Where a run is, for its step header (CHAT-03 items 9–12, 18–19). */+export type RunStepsStatus = 'running' | 'waiting' | 'done' | 'stopped' | 'error';++/** Working time in the header's words: "41s" under a minute, else "1m 12s". */+export function workedParts(ms: number): { m: number; s: number } {+ const total = Math.max(0, Math.round(ms / 1000));+ return { m: Math.floor(total / 60), s: total % 60 };+}++/** The running header's clock: "0:41", "1:12". */+export function runClock(ms: number): string {+ const { m, s } = workedParts(ms);+ return `${m}:${String(s).padStart(2, '0')}`;+}++/**+ * A run's steps under its header (CHAT-03 "Step list" and "Header"). While+ * it runs: "Working on it", "{N} steps · m:ss", open. Once done, it folds to+ * "Worked for 1m 12s" and "{N} steps · {M} sources"; a run of one step (not+ * counting thinking) shows that step's own line and its rows instead. Stopped:+ * "Stopped after 41s"; failed: "Stopped: something went wrong". A click opens+ * and closes it (aria-expanded). Screen readers hear each new step as it+ * starts, and the end (aria-live, polite). No steps, nothing.+ *+ * `workingMs` is the run's working time, which pauses while a step waits for+ * the person; the caller ticks it.+ */+export function RunSteps({+ status,+ steps,+ workingMs,+ sources = 0,+ className,+}: {+ status: RunStepsStatus;+ steps: ChatStep[];+ workingMs: number;+ /** How many "Data used" chips the run has. */+ sources?: number;+ className?: string;+}) {+ const t = useTranslations('agentic.runSteps');+ const listId = useId();+ const active = status === 'running' || status === 'waiting';+ // Open while it runs, folded once it ends, until the person toggles it.+ const [toggled, setToggled] = useState<{ active: boolean; open: boolean } | null>(null);+ const open = toggled && toggled.active === active ? toggled.open : active;++ if (steps.length === 0) return null;++ const ordered = [...steps].sort((a, b) => a.n - b.n);+ const count = ordered.length;+ const duration = (() => {+ const { m, s } = workedParts(workingMs);+ return m > 0 ? t('minutes', { m, s }) : t('seconds', { s });+ })();+ const current =+ ordered.find((s) => s.status === 'waiting') ??+ [...ordered].reverse().find((s) => s.status === 'running');+ const work = ordered.filter((s) => s.kind !== 'thinking');+ const single = status === 'done' && work.length === 1 ? work[0] : null;++ let title: string;+ let end: string;+ if (active) {+ title = t('working');+ end = t('stepsClock', { steps: count, clock: runClock(workingMs) });+ } else if (single) {+ title = single.detail ? `${single.label} · ${single.detail}` : single.label;+ end = single.rowCount !== undefined ? t('rows', { count: single.rowCount }) : '';+ } else if (status === 'done') {+ title = t('workedFor', { duration });+ end = sources > 0 ? t('stepsSources', { steps: count, sources }) : t('steps', { count });+ } else if (status === 'stopped') {+ title = t('stoppedAfter', { duration });+ end = t('steps', { count });+ } else {+ title = t('failed');+ end = t('steps', { count });+ }++ const announce = active+ ? current+ ? t('now', { n: current.n, label: current.label })+ : t('working')+ : title;++ return (+ <div data-slot="run-steps" data-status={status} className={className}>+ {/* CHAT-23 has no id for it yet: answer.toggleSteps, after answer.toggleThinking. */}+ <button+ type="button"+ data-action="answer.toggleSteps"+ aria-expanded={open}+ aria-controls={listId}+ onClick={() => setToggled({ active, open: !open })}+ className="flex w-full items-center gap-2 rounded-lg py-1 text-left text-[13px] hover:bg-muted/60 focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-none"+ >+ {status === 'done' ? (+ <DoneTick size="sm" decorative />+ ) : (+ <ListDot+ state={active ? 'running' : status === 'stopped' ? 'paused' : 'failed'}+ decorative+ />+ )}+ <span className="min-w-0 flex-1 truncate font-medium">{title}</span>+ {end && <span className="shrink-0 text-xs text-muted-foreground tabular-nums">{end}</span>}+ <ChevronDown+ aria-hidden+ className={cn(+ 'size-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none',+ open && 'rotate-180',+ )}+ />+ </button>+ <p aria-live="polite" className="sr-only">+ {announce}+ </p>+ <div id={listId} hidden={!open}>+ <StepList rows={ordered.map((step) => stepRowFrom(step))} className="pl-1" />+ </div>+ </div>+ );+}diff --git a/web/src/components/agentic/runs-tray.test.tsx b/web/src/components/agentic/runs-tray.test.tsxnew file mode 100644index 000000000..e3abca545--- /dev/null+++ b/web/src/components/agentic/runs-tray.test.tsx@@ -0,0 +1,261 @@+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../messages/en.json';+import type { TrayResponse } from '@/lib/chat/runs-tray';+import { RunsTray, RunsTrayView, TRAY_POLL_CLOSED_MS, TRAY_POLL_OPEN_MS } from './runs-tray';++/**+ * The runs pill and its tray (CHAT-23 G4 `runs.toggleTray`, `runs.open`):+ * what runs and what needs the person at a glance; open, every run with+ * Review, its progress, or Open; read again every few seconds.+ */++vi.mock('@/i18n/navigation', () => ({+ Link: ({ href, children, ...rest }: { href: string; children: ReactNode }) => (+ <a href={href} {...rest}>+ {children}+ </a>+ ),+}));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const TRAY: TrayResponse = {+ running: 1,+ needsYou: 1,+ runs: [+ {+ source: 'chat',+ state: 'needsYou',+ title: 'Action Center tasks',+ step: 4,+ steps: 6,+ stepLabel: 'Change one cited passage',+ startedAt: '2026-10-26T13:02:00Z',+ finishedAt: null,+ href: '/dashboard/chat/a',+ },+ {+ source: 'chat',+ state: 'running',+ title: null,+ step: 2,+ steps: 5,+ stepLabel: 'Comparing cited pages',+ startedAt: '2026-10-26T12:40:00Z',+ finishedAt: null,+ href: '/dashboard/chat/b',+ },+ {+ source: 'content',+ state: 'done',+ title: 'Pricing FAQ',+ step: 3,+ steps: 3,+ stepLabel: 'Checking sources',+ startedAt: '2026-10-26T04:58:00Z',+ finishedAt: '2026-10-26T05:02:00Z',+ href: '/dashboard/content/editor/c',+ },+ {+ source: 'chat',+ state: 'failed',+ title: 'Merchant feed fix',+ step: 2,+ steps: 3,+ stepLabel: 'Update titles',+ startedAt: '2026-10-26T04:30:00Z',+ finishedAt: '2026-10-26T04:31:00Z',+ href: '/dashboard/chat/d',+ },+ ],+};++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++async function render(ui: ReactNode) {+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ {ui}+ </NextIntlClientProvider>,+ ),+ );+}++const pill = () => container.querySelector<HTMLButtonElement>('[data-action="runs.toggleTray"]')!;+const popup = () => document.querySelector<HTMLElement>('[data-slot="popover-content"]');+const openTray = async () => {+ await act(async () => pill().click());+ await act(async () => {});+};++describe('RunsTrayView', () => {+ it('says what runs and what needs the person on its pill', async () => {+ await render(<RunsTrayView data={TRAY} />);+ expect(pill().textContent).toBe('1 running1');+ expect(pill().getAttribute('aria-label')).toBe('Your runs: 1 running · 1 needs you');+ expect(pill().getAttribute('aria-expanded')).toBe('false');+ const count = pill().querySelector('[title]')!;+ expect(count.getAttribute('title')).toBe('1 needs you');+ expect(count.getAttribute('class')).toContain('dark:bg-amber-500');+ // The bouncing dots stop with reduced motion.+ const dots = [...pill().querySelectorAll('i')];+ expect(dots).toHaveLength(3);+ for (const dot of dots)+ expect(dot.getAttribute('class')).toContain('motion-reduce:animate-none');+ });++ it('lists every run with Review, its progress, or Open, each opening its run', async () => {+ await render(<RunsTrayView data={TRAY} />);+ await openTray();+ expect(pill().getAttribute('aria-expanded')).toBe('true');+ const tray = popup()!;+ expect(tray.className).toContain('motion-reduce:animate-none!');+ expect(tray.textContent).toContain('Your runs');+ const rows = [...tray.querySelectorAll<HTMLAnchorElement>('[data-action="runs.open"]')];+ expect(rows.map((a) => [a.getAttribute('href'), a.dataset.state])).toEqual([+ ['/dashboard/chat/a', 'needsYou'],+ ['/dashboard/chat/b', 'running'],+ ['/dashboard/content/editor/c', 'done'],+ ['/dashboard/chat/d', 'failed'],+ ]);+ expect(rows[0].textContent).toBe('Action Center tasksNeeds your OK · step 4 of 6Review');+ expect(rows[1].textContent).toBe('New chatStep 2 of 5 · Comparing cited pages');+ expect(rows[1].querySelector('[role="progressbar"]')!.getAttribute('aria-valuenow')).toBe('20');+ expect(rows[2].textContent).toMatch(/^Pricing FAQDone \d\d:\d\dOpen$/);+ expect(rows[3].textContent).toBe('Merchant feed fixStopped · step 2 of 3Open');+ // The avatar in each run's state; the words already say it.+ expect(+ rows.map((a) => a.querySelector<HTMLElement>('[data-slot="agent-avatar"]')!.dataset.state),+ ).toEqual(['waiting', 'working', 'done', 'failed']);++ await act(async () =>+ document.activeElement!.dispatchEvent(+ new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }),+ ),+ );+ await act(async () => {});+ expect(popup()).toBeNull();+ });++ it('says when nothing runs, and when the runs could not be read', async () => {+ await render(<RunsTrayView data={{ runs: [], running: 0, needsYou: 0 }} />);+ expect(pill().textContent).toBe('Runs');+ expect(pill().querySelectorAll('i')).toHaveLength(0);+ await openTray();+ expect(popup()!.textContent).toContain('No runs yet. Runs keep going when you leave a page.');+ await act(async () => root.unmount());+ root = createRoot(container);+ await render(<RunsTrayView data={null} load="error" />);+ await openTray();+ expect(popup()!.querySelector('[role="alert"]')!.textContent).toBe('Couldn’t load your runs.');+ });+});++describe('RunsTray', () => {+ it('reads the runs for the brand, and again every few seconds, more often while open', async () => {+ vi.useFakeTimers();+ const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise<Response>>(+ async () => new Response(JSON.stringify({ ok: true, ...TRAY }), { status: 200 }),+ );+ vi.stubGlobal('fetch', fetchMock);+ await render(<RunsTray brandId="brand-1" />);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0]).toEqual([+ '/api/chat/runs/tray?brand=brand-1',+ { cache: 'no-store' },+ ]);+ expect(pill().textContent).toBe('1 running1');++ await act(async () => vi.advanceTimersByTimeAsync(TRAY_POLL_CLOSED_MS));+ expect(fetchMock).toHaveBeenCalledTimes(2);++ // Opening reads at once, then every few seconds.+ await act(async () => pill().click());+ await act(async () => {});+ expect(fetchMock).toHaveBeenCalledTimes(3);+ await act(async () => vi.advanceTimersByTimeAsync(TRAY_POLL_OPEN_MS));+ expect(fetchMock).toHaveBeenCalledTimes(4);+ });++ it('reads nothing while the tab is hidden, and says when it couldn’t read', async () => {+ vi.useFakeTimers();+ const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise<Response>>(+ async () =>+ new Response(JSON.stringify({ ok: false, failure: 'failed', error: 'x' }), {+ status: 500,+ }),+ );+ vi.stubGlobal('fetch', fetchMock);+ await render(<RunsTray />);+ expect(fetchMock.mock.calls[0][0]).toBe('/api/chat/runs/tray');+ const hidden = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');+ await act(async () => vi.advanceTimersByTimeAsync(TRAY_POLL_CLOSED_MS * 2));+ expect(fetchMock).toHaveBeenCalledTimes(1);+ hidden.mockRestore();+ await act(async () => pill().click());+ await act(async () => {});+ expect(popup()!.querySelector('[role="alert"]')!.textContent).toBe('Couldn’t load your runs.');+ });++ it.each([+ [+ 'the route’s failure',+ () =>+ Response.json({ ok: false, failure: 'session', error: 'Unauthorized' }, { status: 401 }),+ 'Your session expired. Sign in again.',+ ],+ [+ 'one read from the status and body',+ () => Response.json({ code: 'not_in_workspace' }, { status: 403 }),+ "This brand isn't in your workspace. Switch to one of your brands.",+ ],+ ])('says why in the app’s words: %s', async (_, answer, why) => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => answer()),+ );+ await render(<RunsTray />);+ await act(async () => pill().click());+ await act(async () => {});+ expect(popup()!.querySelector('[role="alert"]')!.textContent).toBe(+ `Couldn’t load your runs.${why}`,+ );+ });++ it('keeps the runs it has when a later read fails, and says nothing went wrong once one works', async () => {+ vi.useFakeTimers();+ const answers = [+ new Response(JSON.stringify({ ok: true, ...TRAY })),+ new Response('<html>Bad gateway</html>', { status: 502 }),+ ];+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => answers.shift()!),+ );+ await render(<RunsTray />);+ await act(async () => vi.advanceTimersByTimeAsync(TRAY_POLL_CLOSED_MS));+ await act(async () => pill().click());+ await act(async () => {});+ expect(popup()!.querySelector('[role="alert"]')).toBeNull();+ expect(popup()!.querySelectorAll('[data-action="runs.open"]')).toHaveLength(4);+ });+});diff --git a/web/src/components/agentic/runs-tray.tsx b/web/src/components/agentic/runs-tray.tsxnew file mode 100644index 000000000..a97b8833f--- /dev/null+++ b/web/src/components/agentic/runs-tray.tsx@@ -0,0 +1,267 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { Link } from '@/i18n/navigation';+import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@/components/ui/popover';+import { API_FAILURES, apiFailure, type ApiFailure } from '@/lib/api-failure';+import type { TrayResponse, TrayResult, TrayRun, TrayRunState } from '@/lib/chat/runs-tray';+import { cn } from '@/lib/utils';+import { AgentAvatar, type AgentAvatarState } from './agent-avatar';+import { ListProgress } from './list-dot';++const isApiFailure = (value: unknown): value is ApiFailure =>+ (API_FAILURES as readonly unknown[]).includes(value);++/** How often the tray reads its runs: often while open, less while closed. */+export const TRAY_POLL_OPEN_MS = 4_000;+export const TRAY_POLL_CLOSED_MS = 15_000;++const AVATAR: Record<TrayRunState, AgentAvatarState> = {+ running: 'working',+ needsYou: 'waiting',+ paused: 'idle',+ done: 'done',+ failed: 'failed',+};++const SMALL_BUTTON =+ 'inline-flex h-7 w-full items-center justify-center rounded-lg border bg-background px-2.5 text-xs font-medium';++/** "08:02": a run's end, in the viewer's time. */+function clock(iso: string): string {+ return new Date(iso).toLocaleTimeString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ hourCycle: 'h23',+ });+}++/** One run: avatar, title, where it stands; Review, its progress, or Open. Opens the run (CHAT-23 `runs.open`). */+function TrayRow({ run }: { run: TrayRun }) {+ const t = useTranslations('agentic.runsTray');+ const at = { n: run.step, total: run.steps };+ const line = (() => {+ switch (run.state) {+ case 'needsYou':+ return t('needsYou', at);+ case 'paused':+ return t('paused', at);+ case 'done':+ return t('done', { time: clock(run.finishedAt ?? run.startedAt) });+ case 'failed':+ return t('failed', at);+ default:+ if (run.steps === 0) return t('starting');+ return run.stepLabel ? t('stepOfLabel', { ...at, label: run.stepLabel }) : t('stepOf', at);+ }+ })();+ const progress = run.steps > 0 ? ((run.step - 1) / run.steps) * 100 : 0;+ return (+ <li className="border-t first:border-t-0">+ <Link+ href={run.href}+ data-action="runs.open"+ data-state={run.state}+ className="grid w-full grid-cols-[26px_minmax(0,1fr)_72px] items-center gap-2.5 px-3 py-2.5 text-[13px] outline-none hover:bg-muted/50 focus-visible:bg-muted/50"+ >+ <AgentAvatar state={AVATAR[run.state]} size="sm" decorative />+ <span className="min-w-0 truncate">+ {run.title ?? t('newChat')}+ <span+ className={cn(+ 'block truncate text-[11.5px] text-muted-foreground',+ run.state === 'needsYou' && 'text-amber-700 dark:text-amber-300',+ run.state === 'failed' && 'text-red-700 dark:text-red-300',+ )}+ >+ {line}+ </span>+ </span>+ {run.state === 'needsYou' ? (+ <span className={SMALL_BUTTON}>{t('review')}</span>+ ) : run.state === 'running' || run.state === 'paused' ? (+ <ListProgress value={progress} className="h-1.5 w-full rounded-md" />+ ) : (+ <span className={SMALL_BUTTON}>{t('open')}</span>+ )}+ </Link>+ </li>+ );+}++export type TrayLoad = 'loading' | 'ready' | 'error';++/**+ * The runs pill and its tray (CHAT-mockup-v2 header, CHAT-23 G4+ * `runs.toggleTray`): "1 running" with bouncing dots and an amber count of+ * what needs the person; open, "Your runs" with every run newest first.+ * Esc, a click outside or the pill closes it, focus back on the pill.+ */+export function RunsTrayView({+ data,+ load = 'ready',+ failure,+ open,+ onOpenChange,+ className,+}: {+ data: TrayResponse | null;+ load?: TrayLoad;+ /** Why the last read failed, said in the app's plain words under "Couldn't load your runs." */+ failure?: ApiFailure | null;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ className?: string;+}) {+ const t = useTranslations('agentic.runsTray');+ const tFailure = useTranslations('apiFailure');+ const running = data?.running ?? 0;+ const needsYou = data?.needsYou ?? 0;+ const summary = needsYou ? t('summary', { running, needsYou }) : t('summaryRunning', { running });+ const runs = data?.runs ?? [];+ return (+ <Popover open={open} onOpenChange={(next) => onOpenChange?.(next)}>+ <PopoverTrigger+ data-action="runs.toggleTray"+ aria-label={`${t('label')}: ${summary}`}+ className={cn(+ 'inline-flex h-8 shrink-0 items-center gap-1.5 rounded-[10px] border bg-card px-2.5 text-[13px] outline-none hover:bg-muted/50 focus-visible:ring-3 focus-visible:ring-ring/50',+ className,+ )}+ >+ {running > 0 && (+ <span aria-hidden className="inline-flex gap-[3px]">+ {[0, 1, 2].map((i) => (+ <i+ key={i}+ className="size-1 animate-agent-dot rounded-full bg-current opacity-25 motion-reduce:animate-none motion-reduce:opacity-60"+ style={{ animationDelay: `${i * 0.2}s` }}+ />+ ))}+ </span>+ )}+ <span>{t('button', { count: running })}</span>+ {needsYou > 0 && (+ <span+ title={t('needsYouTip', { count: needsYou })}+ className="rounded-md bg-amber-600 px-[5px] text-[11px] text-white tabular-nums dark:bg-amber-500 dark:text-amber-950"+ >+ {needsYou}+ </span>+ )}+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="w-[340px] max-w-[calc(100vw-32px)] rounded-[14px] p-0 shadow-[0_14px_36px_rgba(0,0,0,.14)] motion-reduce:animate-none!"+ >+ <div className="flex border-b px-3 py-2.5 text-xs text-muted-foreground">+ <PopoverTitle className="text-xs font-normal text-muted-foreground">+ {t('title')}+ </PopoverTitle>+ {runs.length > 0 && <span className="ml-auto">{summary}</span>}+ </div>+ {load === 'error' && runs.length === 0 ? (+ <p role="alert" className="m-0 px-3 py-4 text-[13px] text-muted-foreground">+ {t('failedToLoad')}+ {failure && failure !== 'failed' && (+ <span className="mt-1 block text-xs">{tFailure(failure)}</span>+ )}+ </p>+ ) : load === 'loading' && runs.length === 0 ? (+ <div aria-hidden className="grid gap-2 px-3 py-3">+ <span className="h-[26px] rounded-md bg-muted" />+ <span className="h-[26px] rounded-md bg-muted" />+ </div>+ ) : runs.length === 0 ? (+ <p className="m-0 px-3 py-4 text-[13px] text-muted-foreground">{t('empty')}</p>+ ) : (+ <ul className="m-0 max-h-[60vh] list-none overflow-y-auto p-0">+ {runs.map((run) => (+ <TrayRow key={run.href} run={run} />+ ))}+ </ul>+ )}+ </PopoverContent>+ </Popover>+ );+}++/**+ * The runs tray with its runs (`/api/chat/runs/tray`): the person's Chat+ * runs and the brand's Content Agent runs, read again every few seconds+ * while it is open (less often while closed, not while the tab is hidden),+ * so a run's step and state keep up.+ */+export function RunsTray({ brandId, className }: { brandId?: string | null; className?: string }) {+ const [data, setData] = useState<TrayResponse | null>(null);+ const [load, setLoad] = useState<TrayLoad>('loading');+ const [failure, setFailure] = useState<ApiFailure | null>(null);+ const [open, setOpen] = useState(false);+ const latest = useRef(0);++ const read = useCallback(async () => {+ const call = ++latest.current;+ // A failure is a value (TrayResult), never thrown: the route says why,+ // and a body that isn't one says it by its status.+ let result: TrayResult;+ try {+ const query = brandId ? `?brand=${encodeURIComponent(brandId)}` : '';+ const res = await fetch(`/api/chat/runs/tray${query}`, { cache: 'no-store' });+ const body = (await res.json().catch(() => ({}))) as Partial<TrayResult>;+ result =+ res.ok && body.ok === true+ ? (body as TrayResult)+ : {+ ok: false,+ failure:+ body.ok === false && isApiFailure(body.failure)+ ? body.failure+ : apiFailure(res.status, body),+ error: `runs tray ${res.status}`,+ };+ } catch {+ // No answer: the next read tries again.+ result = { ok: false, failure: 'failed', error: 'no answer' };+ }+ if (call !== latest.current) return;+ if (result.ok) {+ setData(result);+ setFailure(null);+ setLoad('ready');+ } else {+ setFailure(result.failure);+ setLoad('error');+ }+ }, [brandId]);++ useEffect(() => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ let stopped = false;+ const tick = async () => {+ if (document.visibilityState !== 'hidden') await read();+ if (!stopped) timer = setTimeout(tick, open ? TRAY_POLL_OPEN_MS : TRAY_POLL_CLOSED_MS);+ };+ void tick();+ const onVisible = () => {+ if (document.visibilityState === 'visible') void read();+ };+ document.addEventListener('visibilitychange', onVisible);+ return () => {+ stopped = true;+ clearTimeout(timer);+ document.removeEventListener('visibilitychange', onVisible);+ };+ }, [read, open]);++ return (+ <RunsTrayView+ data={data}+ load={load}+ failure={failure}+ open={open}+ onOpenChange={setOpen}+ className={className}+ />+ );+}diff --git a/web/src/components/agentic/step-list.tsx b/web/src/components/agentic/step-list.tsxnew file mode 100644index 000000000..5d290ed89--- /dev/null+++ b/web/src/components/agentic/step-list.tsx@@ -0,0 +1,91 @@+import type { ReactNode } from 'react';+import { useTranslations } from 'next-intl';+import type { ChatStep, ChatStepStatus } from '@/lib/chat/events';+import { cn } from '@/lib/utils';+import { ApprovalPill, type ApprovalPillKind } from './approval-pill';+import { StepMarker, type StepMarkerState } from './step-marker';++/** One row of a plan or a run (the mockups' `.step`). */+export interface StepRow {+ /** Its place in the run, from 1. */+ n: number;+ /** "Read the 4 tasks and rank them by impact" */+ label: string;+ /** The grey line under it: what it reads, or why it failed. */+ detail?: string | null;+ state: StepMarkerState;+ /** How it runs (Auto, Asks you, Needs your click…); none once it ran. */+ pill?: ApprovalPillKind | null;+ /** Skipped by the person or by a Stop: greyed, with "Skipped". */+ skipped?: boolean;+}++/** A stored step's status as its marker shows it (CHAT-03 icons, Chat v2 step states). */+export function stepMarkerState(status: ChatStepStatus): StepMarkerState {+ switch (status) {+ case 'running':+ return 'current';+ case 'waiting':+ return 'waiting';+ case 'done':+ return 'done';+ case 'error':+ return 'failed';+ default:+ return 'pending';+ }+}++/** A run's step (A1's ChatStep) as a row: its label, its detail, and where it stands. */+export function stepRowFrom(step: ChatStep, pill?: ApprovalPillKind | null): StepRow {+ return {+ n: step.n,+ label: step.label,+ detail: step.detail ?? null,+ state: stepMarkerState(step.status),+ skipped: step.status === 'skipped',+ pill: step.status === 'done' ? null : (pill ?? null),+ };+}++/**+ * Numbered steps (Chat v2 mockups `#s-plan`, `#s-work`, `#s-failed`): the+ * marker, the step in words with a grey line under it, and its approval pill+ * at a fixed width on the right, so the pills line up. A step waiting on the+ * person says so. `controls` adds what a row offers while a plan is edited.+ */+export function StepList({+ rows,+ controls,+ className,+}: {+ rows: StepRow[];+ controls?: (row: StepRow, index: number) => ReactNode;+ className?: string;+}) {+ const t = useTranslations('agentic.stepList');+ return (+ <ol data-slot="step-list" className={cn('m-0 list-none p-0', className)}>+ {rows.map((row, index) => {+ const detail = row.skipped+ ? t('skipped')+ : (row.detail ?? (row.state === 'waiting' ? t('waiting') : null));+ return (+ <li+ key={row.n}+ data-state={row.skipped ? 'skipped' : row.state}+ className="flex items-start gap-2.5 border-b border-dashed py-[9px] text-[13.5px] last:border-b-0"+ >+ <StepMarker number={row.n} state={row.state} />+ <div className={cn('min-w-0 flex-1', row.skipped && 'text-muted-foreground')}>+ {row.label}+ {detail && <span className="block text-xs text-muted-foreground">{detail}</span>}+ </div>+ {controls?.(row, index)}+ {row.pill && <ApprovalPill kind={row.pill} className="w-[104px] self-center" />}+ </li>+ );+ })}+ </ol>+ );+}diff --git a/web/src/lib/chat/runs-tray.test.ts b/web/src/lib/chat/runs-tray.test.tsnew file mode 100644index 000000000..3ffb0f0b2--- /dev/null+++ b/web/src/lib/chat/runs-tray.test.ts@@ -0,0 +1,291 @@+import { describe, expect, it } from 'vitest';+import type { ChatRunStepMemberRow } from './steps';+import {+ chatTrayRun,+ chatTrayState,+ contentTrayRun,+ TRAY_LIMIT,+ trayResponse,+ type TrayRun,+} from './runs-tray';++/**+ * The runs tray's rows (Chat agentic plan §2, CHAT-23 G4): where each run+ * stands, the step it is on in words, its Open, newest first — and nothing a+ * browser may not see.+ */++const NOW = Date.parse('2026-10-29T12:00:00Z');+const CHAT = '11111111-1111-4111-8111-111111111111';+const DRAFT = '22222222-2222-4222-8222-222222222222';++const stepRow = (+ position: number,+ status: string,+ label: string,+ extra: Partial<ChatRunStepMemberRow> = {},+): ChatRunStepMemberRow => ({+ id: `step-${position}`,+ run_id: 'run-1',+ position,+ kind: 'read',+ status,+ label,+ detail: null,+ scope_json: null,+ row_count: null,+ data_as_of: null,+ started_at: null,+ finished_at: null,+ ...extra,+});++const chatRun = (+ status: string,+ extra: Partial<{ created_at: string; finished_at: string | null }> = {},+) => ({+ conversation_id: CHAT,+ status,+ created_at: '2026-10-29T11:00:00Z',+ finished_at: null,+ ...extra,+});++describe('chatTrayState', () => {+ it('shows each chat_runs status as the tray does', () => {+ expect(+ [+ 'queued',+ 'running',+ 'waiting',+ 'paused',+ 'paused_cap',+ 'done',+ 'error',+ 'stopped',+ 'new',+ ].map(chatTrayState),+ ).toEqual([+ 'running',+ 'running',+ 'needsYou',+ 'paused',+ 'paused',+ 'done',+ 'failed',+ 'failed',+ null,+ ]);+ });+});++describe('chatTrayRun', () => {+ it('names the step waiting on the person, by its label, and opens the chat', () => {+ const run = chatTrayRun(+ chatRun('waiting'),+ 'Action Center tasks',+ [+ stepRow(3, 'pending', 'Publish'),+ stepRow(1, 'done', 'Read Action Center'),+ stepRow(2, 'waiting', 'Change one cited passage'),+ ],+ NOW,+ );+ expect(run).toEqual({+ source: 'chat',+ state: 'needsYou',+ title: 'Action Center tasks',+ step: 2,+ steps: 3,+ stepLabel: 'Change one cited passage',+ startedAt: '2026-10-29T11:00:00Z',+ finishedAt: null,+ href: `/dashboard/chat/${CHAT}`,+ });+ });++ it('else the step running, else the last; none yet is step 0', () => {+ const running = chatTrayRun(+ chatRun('running'),+ null,+ [+ stepRow(1, 'done', 'Read'),+ stepRow(2, 'running', 'Opened /pricing'),+ stepRow(3, 'pending', 'Write'),+ ],+ NOW,+ )!;+ expect([running.step, running.stepLabel, running.title]).toEqual([2, 'Opened /pricing', null]);+ const done = chatTrayRun(+ chatRun('done', { finished_at: '2026-10-29T11:05:00Z' }),+ 'Report',+ [stepRow(1, 'done', 'Read'), stepRow(2, 'done', 'Saved report')],+ NOW,+ )!;+ expect([done.state, done.step, done.stepLabel, done.finishedAt]).toEqual([+ 'done',+ 2,+ 'Saved report',+ '2026-10-29T11:05:00Z',+ ]);+ const queued = chatTrayRun(chatRun('queued'), 'New', [], NOW)!;+ expect([queued.state, queued.step, queued.steps, queued.stepLabel]).toEqual([+ 'running',+ 0,+ 0,+ null,+ ]);+ });++ it('keeps runs under way of any age, and drops ended runs after a day', () => {+ const old = '2026-10-20T11:00:00Z';+ expect(chatTrayRun(chatRun('waiting', { created_at: old }), 'Old', [], NOW)).not.toBeNull();+ expect(+ chatTrayRun(+ chatRun('done', { created_at: old, finished_at: '2026-10-28T11:59:00Z' }),+ 'Done',+ [],+ NOW,+ ),+ ).toBeNull();+ expect(+ chatTrayRun(chatRun('error', { finished_at: '2026-10-28T12:30:00Z' }), 'Err', [], NOW)!.state,+ ).toBe('failed');+ expect(chatTrayRun(chatRun('archived'), 'Unknown', [], NOW)).toBeNull();+ });++ it('gives the browser no tool, no debug record and no id but in its link', () => {+ const uuid = '33333333-3333-4333-8333-333333333333';+ const run = chatTrayRun(+ chatRun('running'),+ `Chat about ${uuid}`,+ [+ {+ ...stepRow(1, 'running', `Read draft ${uuid}`),+ tool: 'get_draft',+ debug_json: { tokens: 12 },+ } as ChatRunStepMemberRow,+ ],+ NOW,+ )!;+ expect(run.title).toBe('Chat about …');+ expect(run.stepLabel).toBe('Read draft …');+ const wire = JSON.stringify(run);+ expect(wire).not.toMatch(/get_draft|debug|tokens|"tool"/);+ expect(wire.replace(run.href, '')).not.toContain(CHAT);+ expect(Object.keys(run).filter((k) => /id$/i.test(k))).toEqual([]);+ });+});++describe('contentTrayRun', () => {+ const contentRow = (extra: Record<string, unknown> = {}) => ({+ id: 'run-c',+ kind: 'fix',+ steps: [+ { key: 'read_rules', count: 4 },+ { key: 'gather_sources', count: 52 },+ { key: 'write_changes', count: null },+ { key: 'check_sources', count: null },+ ],+ step: 1,+ started_at: '2026-10-29T11:58:00Z',+ finished_at: null,+ stopped_at: null,+ outcome: null,+ ...extra,+ });++ it('names the step under way in the editor’s words, and opens the draft', () => {+ expect(contentTrayRun(contentRow(), { id: DRAFT, title: 'Pricing FAQ' }, NOW)).toEqual({+ source: 'content',+ state: 'running',+ title: 'Pricing FAQ',+ step: 2,+ steps: 4,+ stepLabel: 'Gathering 52 sources',+ startedAt: '2026-10-29T11:58:00Z',+ finishedAt: null,+ href: `/dashboard/content/editor/${DRAFT}`,+ });+ });++ it('says done, stopped and a run a stopped server left as they ended', () => {+ const done = contentTrayRun(+ contentRow({ step: 4, finished_at: '2026-10-29T11:59:00Z', outcome: 'done' }),+ { id: DRAFT, title: 'Pricing FAQ' },+ NOW,+ )!;+ expect([done.state, done.step, done.stepLabel]).toEqual(['done', 4, 'Checking sources']);+ const stopped = contentTrayRun(+ contentRow({+ finished_at: '2026-10-29T11:59:00Z',+ stopped_at: '2026-10-29T11:59:00Z',+ outcome: 'stopped',+ }),+ { id: DRAFT, title: 'Pricing FAQ' },+ NOW,+ )!;+ expect(stopped.state).toBe('failed');+ // Unfinished and older than a run can take: a stopped server's.+ const left = contentTrayRun(+ contentRow({ started_at: '2026-10-29T11:00:00Z' }),+ { id: DRAFT, title: 'Pricing FAQ' },+ NOW,+ )!;+ expect([left.state, left.finishedAt]).toEqual(['failed', '2026-10-29T11:00:00Z']);+ // Ended more than a day ago: not in the tray.+ expect(+ contentTrayRun(+ contentRow({+ started_at: '2026-10-27T11:00:00Z',+ finished_at: '2026-10-27T11:02:00Z',+ outcome: 'done',+ }),+ { id: DRAFT, title: 'Pricing FAQ' },+ NOW,+ ),+ ).toBeNull();+ // A row the editor couldn't show.+ expect(contentTrayRun(contentRow({ steps: [] }), { id: DRAFT, title: 'x' }, NOW)).toBeNull();+ });+});++describe('trayResponse', () => {+ const row = (href: string, startedAt: string, state: TrayRun['state'] = 'running'): TrayRun => ({+ source: 'chat',+ state,+ title: href,+ step: 1,+ steps: 2,+ stepLabel: null,+ startedAt,+ finishedAt: null,+ href: href as TrayRun['href'],+ });++ it('puts the newest first, one row per chat or draft, with the counts', () => {+ const res = trayResponse([+ row('/dashboard/chat/a', '2026-10-29T09:00:00Z', 'done'),+ row('/dashboard/chat/b', '2026-10-29T11:00:00Z', 'needsYou'),+ row('/dashboard/chat/a', '2026-10-29T10:00:00Z', 'running'),+ row('/dashboard/content/editor/c', '2026-10-29T10:30:00Z', 'paused'),+ ]);+ expect(res.runs.map((r) => [r.href, r.state])).toEqual([+ ['/dashboard/chat/b', 'needsYou'],+ ['/dashboard/content/editor/c', 'paused'],+ ['/dashboard/chat/a', 'running'],+ ]);+ expect([res.running, res.needsYou]).toEqual([2, 1]);+ });++ it(`keeps at most ${TRAY_LIMIT}`, () => {+ const many = Array.from({ length: 14 }, (_, i) =>+ row(`/dashboard/chat/${i}`, `2026-10-29T${String(i).padStart(2, '0')}:00:00Z`),+ );+ const res = trayResponse(many);+ expect(res.runs).toHaveLength(TRAY_LIMIT);+ expect(res.runs[0].href).toBe('/dashboard/chat/13');+ // The count is of every run, not only the ones shown.+ expect(res.running).toBe(14);+ });+});diff --git a/web/src/lib/chat/runs-tray.ts b/web/src/lib/chat/runs-tray.tsnew file mode 100644index 000000000..5126caf29--- /dev/null+++ b/web/src/lib/chat/runs-tray.ts@@ -0,0 +1,206 @@+import { createTranslator } from 'next-intl';+import messages from '../../../messages/en.json';+import type { ApiFailure } from '@/lib/api-failure';+import { agentRunFrom, runUnderWay, shownSteps, stepMessage } from '@/lib/content/agent-runs';+import { isChatHref, maskIds, type ChatHref } from './events';+import { toClientStep, type ChatRunStepMemberRow } from './steps';++/**+ * The runs tray (Chat agentic plan §2, CHAT-23 G4 `runs.toggleTray`): the+ * person's Chat runs and the brand's Content Agent runs, newest first, each+ * with where it stands and where its Open goes. Built on the server from the+ * rows the person may read; what reaches the browser has no id but the one in+ * its link, and no tool name (CHAT-03 item 22).+ */++/** Where a run stands, as its row's avatar and right-hand control show it. */+export type TrayRunState = 'running' | 'needsYou' | 'paused' | 'done' | 'failed';++export interface TrayRun {+ source: 'chat' | 'content';+ state: TrayRunState;+ /** The chat's title or the draft's; null for a chat Chat hasn't named yet ("New chat"). */+ title: string | null;+ /** The step it is on, from 1; 0 when it has none yet. */+ step: number;+ /** How many steps it has; 0 when it has none yet. */+ steps: number;+ /** The step it is on, in words ("Read Citations", "Gathering 52 sources"). */+ stepLabel: string | null;+ /** When it started, ISO: the tray's order. */+ startedAt: string;+ /** When it ended, ISO; null while it is under way. */+ finishedAt: string | null;+ /** Its Open: the chat, or the draft in the Content Editor. Also the row's key. */+ href: ChatHref;+}++export interface TrayResponse {+ runs: TrayRun[];+ /** Runs under way (running or paused) and runs that need the person, in the whole list. */+ running: number;+ needsYou: number;+}++/**+ * Why the tray's runs couldn't be read, as a value (the reads' pattern since+ * #1777): `failure` for the app's plain words (apiFailure), `error` for a log.+ */+export interface TrayFailure {+ ok: false;+ failure: ApiFailure;+ error: string;+}++/** /api/chat/runs/tray's answer. */+export type TrayResult = ({ ok: true } & TrayResponse) | TrayFailure;++/** The tray's length: the newest runs first. */+export const TRAY_LIMIT = 10;++/** How long a run that ended stays in the tray. */+export const TRAY_DONE_MS = 24 * 60 * 60_000;++/** chat_runs.status (00400) as the tray shows it; null for one this build doesn't know. */+export function chatTrayState(status: string): TrayRunState | null {+ switch (status) {+ case 'queued':+ case 'running':+ return 'running';+ case 'waiting':+ return 'needsYou';+ case 'paused':+ case 'paused_cap':+ return 'paused';+ case 'done':+ return 'done';+ case 'error':+ case 'stopped':+ return 'failed';+ default:+ return null;+ }+}++const ended = (state: TrayRunState) => state === 'done' || state === 'failed';++/** Whether a run that ended, ended long enough ago to leave the tray. */+function tooOld(finishedAt: string | null, now: number): boolean {+ if (!finishedAt) return false;+ const at = Date.parse(finishedAt);+ return Number.isFinite(at) && now - at > TRAY_DONE_MS;+}++export interface ChatRunRow {+ conversation_id: string;+ status: string;+ created_at: string;+ finished_at: string | null;+}++/**+ * A Chat run as the tray shows it: its chat's title, and the step it is on (a+ * step waiting on the person, else the one running, else the last), in the+ * label registry's words. Null for a status this build doesn't know, or one+ * that ended more than a day ago.+ */+export function chatTrayRun(+ run: ChatRunRow,+ chatTitle: string | null,+ stepRows: ChatRunStepMemberRow[],+ now = Date.now(),+): TrayRun | null {+ const state = chatTrayState(run.status);+ const href = `/dashboard/chat/${run.conversation_id}`;+ if (!state || !isChatHref(href)) return null;+ const finishedAt = ended(state) ? (run.finished_at ?? run.created_at) : null;+ if (tooOld(finishedAt, now)) return null;+ const steps = stepRows+ .map(toClientStep)+ .filter((s): s is NonNullable<typeof s> => s !== null)+ .sort((a, b) => a.n - b.n);+ const current =+ steps.find((s) => s.status === 'waiting') ??+ [...steps].reverse().find((s) => s.status === 'running') ??+ steps.at(-1);+ return {+ source: 'chat',+ state,+ title: chatTitle ? maskIds(chatTitle) : null,+ step: current ? steps.indexOf(current) + 1 : 0,+ steps: steps.length,+ stepLabel: current?.label ?? null,+ startedAt: run.created_at,+ finishedAt,+ href,+ };+}++/** The editor's step words; keys from stepMessage(), so typed loosely. */+const stepT = createTranslator({+ locale: 'en',+ messages,+ namespace: 'contentEditor.editor.agentCard.steps',+}) as unknown as (key: string, values: { count: number }) => string;++/**+ * A Content Agent run (content_agent_runs, 00249) as the tray shows it: its+ * draft's title, and the step it is on, in the editor's own words. A run a+ * stopped server left unfinished shows as failed, as the editor treats it.+ * Null for a row the editor couldn't show, or one that ended more than a day+ * ago.+ */+export function contentTrayRun(+ row: Record<string, unknown>,+ draft: { id: string; title: string | null },+ now = Date.now(),+): TrayRun | null {+ const run = agentRunFrom(row);+ const href = `/dashboard/content/editor/${draft.id}`;+ if (!run || !isChatHref(href)) return null;+ const underWay = runUnderWay(run, now);+ const state: TrayRunState = underWay+ ? 'running'+ : run.outcome === 'done' || (run.finishedAt && !run.outcome)+ ? 'done'+ : 'failed';+ const finishedAt = underWay ? null : (run.finishedAt ?? run.stoppedAt ?? run.startedAt);+ if (tooOld(finishedAt, now)) return null;+ const shown = shownSteps(run);+ // The step under way among the ones the editor shows; the last once done.+ const at = shown.findIndex(({ index }) => index >= run.step);+ const current = at === -1 ? shown.length - 1 : at;+ const message = shown[current] ? stepMessage(shown[current].step) : null;+ return {+ source: 'content',+ state,+ title: draft.title ? maskIds(draft.title) : null,+ step: shown.length ? current + 1 : 0,+ steps: shown.length,+ stepLabel: message ? stepT(message.key, { count: message.count ?? 0 }) : null,+ startedAt: run.startedAt,+ finishedAt,+ href,+ };+}++/**+ * The tray: newest first, one row per chat and per draft (its latest run),+ * at most TRAY_LIMIT, with the counts for its button.+ */+export function trayResponse(rows: TrayRun[], limit = TRAY_LIMIT): TrayResponse {+ const time = (iso: string) => {+ const at = Date.parse(iso);+ return Number.isFinite(at) ? at : 0;+ };+ const latest = new Map<string, TrayRun>();+ for (const row of [...rows].sort((a, b) => time(b.startedAt) - time(a.startedAt))) {+ if (!latest.has(row.href)) latest.set(row.href, row);+ }+ const runs = [...latest.values()];+ return {+ runs: runs.slice(0, limit),+ running: runs.filter((r) => r.state === 'running' || r.state === 'paused').length,+ needsYou: runs.filter((r) => r.state === 'needsYou').length,+ };+}