{
  "schemaVersion": 1,
  "target": "react",
  "name": "agent-workspace",
  "version": "0.3.1",
  "category": "block",
  "title": "Agent Workspace",
  "description": "A complete agent workspace laid out as one document of the run: a slim status header with a progress line, one-line steps that open in place, files, inline approvals, the streamed reply, and a pinned prompt composer.",
  "tags": [
    "agent",
    "workspace",
    "block",
    "chat",
    "approval",
    "activity"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [
    {
      "name": "agent-run",
      "version": "0.1.2"
    },
    {
      "name": "agent-state",
      "version": "0.1.0"
    },
    {
      "name": "approval-card",
      "version": "0.3.0"
    },
    {
      "name": "artifact-preview",
      "version": "0.3.1"
    },
    {
      "name": "prompt-composer",
      "version": "0.3.0"
    },
    {
      "name": "streaming-message",
      "version": "0.3.0"
    }
  ],
  "docsPath": "/components/agent-workspace",
  "props": [
    {
      "name": "run",
      "type": "AgentRun",
      "description": "The run to render, normalized with agent-run's applyEvents and fromSnapshot."
    },
    {
      "name": "onSubmit / onStop",
      "type": "(prompt, context) => void | Promise<void> / () => void",
      "description": "Prompt composer actions; context carries the chosen mode, model, permission, and files."
    },
    {
      "name": "onApprove / onReject",
      "type": "(approvalId: string) => void | Promise<void>",
      "description": "Approval decisions; send them to your backend for verification."
    },
    {
      "name": "composerStatus",
      "type": "\"idle\" | \"submitting\" | \"running\"",
      "description": "Defaults from the run status."
    },
    {
      "name": "composer",
      "type": "Pick<PromptComposerProps, \"placeholder\" | \"mode\" | \"model\" | \"permissions\" | \"attachments\" | \"mentions\" | \"beam\">",
      "description": "Composer options. Mode, model, and permission selectors are on by default."
    },
    {
      "name": "outline / defaultOutlineOpen",
      "type": "boolean / boolean",
      "default": "true / true",
      "description": "A collapsible rail beside the run on wide screens listing every step and file; choosing one scrolls the run to it."
    },
    {
      "name": "height",
      "type": "CSS height",
      "default": "\"42rem\"",
      "description": "The run scrolls between the header and the pinned composer. Pass \"100%\" to fill a pane."
    },
    {
      "name": "banner",
      "type": "ReactNode",
      "description": "Optional notice above the run, e.g. reconnecting."
    }
  ],
  "accessibility": [
    "The run is a polite log: new steps, files, approvals, and reply text are announced as they arrive, and each step announces its new status (for example \"search_docs, Done\").",
    "The header status pill is a live region whose text is exactly the run status; every status is shown as text and a shape, with color as reinforcement.",
    "Steps and decided approvals open in place with native details and summary. After Approve or Reject, focus moves to the approval so keyboard and screen reader users keep their place.",
    "The outline toggle reports aria-expanded; outline entries are buttons that scroll to and focus the matching step or file.",
    "With reduced motion, entries appear instantly, the activity marks hold a still frame, and the composer's border light stays still."
  ],
  "states": [
    "queued",
    "running",
    "waiting-for-approval",
    "succeeded",
    "failed",
    "cancelled"
  ],
  "files": [
    {
      "path": "blocks/agent-workspace.tsx",
      "content": "\"use client\";\n\nimport { type CSSProperties, type ReactNode, useEffect, useId, useRef, useState } from \"react\";\nimport type { AgentRun, RunApproval, RunArtifact, RunStatus, RunStep, StepStatus } from \"../agent/agent-run\";\nimport { type AgentActivity, type AgentPhase, AgentMark, AgentState } from \"../agent/agent-state\";\nimport { ApprovalCard } from \"../agent/approval-card\";\nimport { ArtifactPreview } from \"../agent/artifact-preview\";\nimport { type ComposerStatus, type ComposerSubmitContext, PromptComposer, type PromptComposerProps } from \"../agent/prompt-composer\";\nimport { MessageScroller, StreamingMessage } from \"../agent/streaming-message\";\n\nexport interface AgentWorkspaceProps {\n  /** The run to show, normalized (see agent-run's applyEvents and fromSnapshot). */\n  run: AgentRun;\n  composerStatus?: ComposerStatus;\n  onSubmit: (prompt: string, context: ComposerSubmitContext) => void | Promise<void>;\n  onStop?: () => void;\n  onApprove?: (approvalId: string) => void | Promise<void>;\n  onReject?: (approvalId: string) => void | Promise<void>;\n  /** Optional notice above the run, e.g. a connection message. */\n  banner?: ReactNode;\n  /** Shows a collapsible outline of steps and files beside the run on wide screens. */\n  outline?: boolean;\n  /** Whether the outline starts open. */\n  defaultOutlineOpen?: boolean;\n  /** Height of the workspace. The run scrolls between the header and the composer. Pass \"100%\" to fill a pane. */\n  height?: CSSProperties[\"height\"];\n  /** Composer options. Mode, model, and permission selectors are on by default. */\n  composer?: Pick<PromptComposerProps, \"placeholder\" | \"mode\" | \"model\" | \"permissions\" | \"attachments\" | \"mentions\" | \"beam\">;\n  className?: string;\n}\n\nconst runStatus: Record<RunStatus, { label: string; phase: AgentPhase }> = {\n  queued: { label: \"Queued\", phase: \"idle\" },\n  running: { label: \"Running\", phase: \"active\" },\n  \"waiting-for-approval\": { label: \"Needs approval\", phase: \"waiting\" },\n  succeeded: { label: \"Succeeded\", phase: \"done\" },\n  failed: { label: \"Failed\", phase: \"failed\" },\n  cancelled: { label: \"Cancelled\", phase: \"cancelled\" },\n};\n\nconst stepLabel: Record<StepStatus, string> = {\n  queued: \"Queued\",\n  running: \"Running\",\n  succeeded: \"Done\",\n  failed: \"Failed\",\n  skipped: \"Skipped\",\n};\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n/** New entries settle in with a short rise; instant with reduced motion. */\nconst rise = `transition-[opacity,translate] duration-200 ${ease} starting:translate-y-1 starting:opacity-0 motion-reduce:transition-none`;\nconst hairline = \"border-zinc-950/[0.07] dark:border-white/[0.08]\";\n\n/**\n * A complete agent workspace laid out as one document of the run: a slim header with the run's\n * state and a progress hairline, then the request, each step as a one-line row that opens in\n * place, files, approvals, and the streamed reply, with the composer pinned underneath.\n * It renders whatever run you pass and reports user actions through callbacks.\n */\nexport function AgentWorkspace({\n  run,\n  composerStatus,\n  onSubmit,\n  onStop,\n  onApprove,\n  onReject,\n  banner,\n  outline = true,\n  defaultOutlineOpen = true,\n  height = \"42rem\",\n  composer,\n  className,\n}: AgentWorkspaceProps) {\n  const id = useId();\n  const [outlineOpen, setOutlineOpen] = useState(defaultOutlineOpen);\n  const items = useArrivalOrder(activityItems(run));\n\n  const firstReply = run.messages.findIndex((message) => message.role === \"assistant\");\n  const lead = firstReply === -1 ? run.messages : run.messages.slice(0, firstReply);\n  const rest = firstReply === -1 ? [] : run.messages.slice(firstReply);\n  const empty = run.messages.length === 0 && items.length === 0;\n\n  const running = run.steps.find((step) => step.status === \"running\");\n  const writing = run.messages.some((message) => message.role === \"assistant\" && message.status === \"streaming\");\n  const activity = writing ? { activity: \"thinking\" as const, label: \"Writing\" } : activityOf(running);\n  const meta = runStatus[run.status];\n  const statusLabel = run.status === \"running\" ? activity.label : meta.label;\n\n  const settled = run.steps.filter((step) => step.status !== \"queued\" && step.status !== \"running\").length;\n  const progress = run.status === \"succeeded\" ? 1 : run.steps.length ? settled / run.steps.length : 0;\n  const elapsed = elapsedOf(run);\n  const status: ComposerStatus =\n    composerStatus ?? (run.status === \"running\" || run.status === \"waiting-for-approval\" ? \"running\" : \"idle\");\n  const contentKey = `${run.messages.reduce((total, message) => total + message.content.length, 0)}:${items.map((item) => item.status).join()}`;\n  const failedStepShown = run.steps.some((step) => step.status === \"failed\" && step.error);\n  const showOutline = outline && outlineOpen;\n\n  /** Brings a step or file in the run into view and moves focus to it. */\n  function reveal(key: string) {\n    const target = document.getElementById(`${id}-${key}`);\n    if (!target) return;\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    target.scrollIntoView({ block: \"nearest\", behavior: reduce ? \"auto\" : \"smooth\" });\n    (target.querySelector<HTMLElement>(\"summary\") ?? target).focus({ preventScroll: true });\n  }\n\n  return (\n    <div\n      data-status={run.status}\n      style={{ height }}\n      className={[\"flex min-h-0 w-full flex-col text-zinc-950 dark:text-white\", className].filter(Boolean).join(\" \")}\n    >\n      <header className=\"relative flex min-w-0 items-center gap-3 pb-3\">\n        <h3 className=\"min-w-0 flex-1 truncate text-sm leading-6 font-semibold\">{run.title}</h3>\n        {run.steps.length || elapsed ? (\n          <p className=\"shrink-0 font-mono text-xs text-zinc-500 tabular-nums\">\n            {run.steps.length ? (\n              <span className=\"hidden sm:inline\">\n                {settled} of {run.steps.length} {run.steps.length === 1 ? \"step\" : \"steps\"}\n                {elapsed ? <span aria-hidden=\"true\"> · </span> : null}\n              </span>\n            ) : null}\n            {elapsed ? (\n              <>\n                <span className=\"sr-only\">Elapsed </span>\n                {elapsed}\n              </>\n            ) : null}\n          </p>\n        ) : null}\n        {/* A live region whose text is exactly the status label; the mark is decorative. */}\n        <AgentState\n          status\n          data-slot=\"run-status\"\n          size=\"sm\"\n          activity={activity.activity}\n          phase={meta.phase}\n          label={statusLabel}\n          className=\"shrink-0\"\n        />\n        {outline ? (\n          <button\n            type=\"button\"\n            aria-label=\"Run outline\"\n            aria-expanded={outlineOpen}\n            aria-controls={`${id}-outline`}\n            onClick={() => setOutlineOpen((open) => !open)}\n            className={[\n              \"-mr-1 hidden size-7 shrink-0 items-center justify-center rounded-lg text-zinc-500 lg:inline-flex\",\n              \"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none\",\n              \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 aria-expanded:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white dark:aria-expanded:text-white\",\n              \"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n            ].join(\" \")}\n          >\n            <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinejoin=\"round\" className=\"size-4\">\n              <rect x=\"2.25\" y=\"3\" width=\"11.5\" height=\"10\" rx=\"2\" />\n              <path d=\"M10 3v10\" />\n            </svg>\n          </button>\n        ) : null}\n        {/* The header's bottom edge is the progress line: it fills as steps settle. */}\n        <span aria-hidden=\"true\" className=\"absolute inset-x-0 bottom-0 h-px overflow-hidden bg-zinc-950/[0.07] dark:bg-white/[0.08]\">\n          <span\n            className={[\n              \"absolute inset-0 origin-left transition-[scale,background-color] duration-500 motion-reduce:transition-none\",\n              ease,\n              run.status === \"failed\" ? \"bg-red-500/70\" : run.status === \"waiting-for-approval\" ? \"bg-amber-500/70\" : \"bg-zinc-950/35 dark:bg-white/45\",\n            ].join(\" \")}\n            style={{ scale: `${progress} 1` }}\n          />\n        </span>\n      </header>\n\n      <div className={`grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)] ${showOutline ? \"lg:grid-cols-[minmax(0,1fr)_15rem]\" : \"\"}`}>\n        <section aria-label=\"Run\" className=\"flex min-h-0 min-w-0 flex-col\">\n          {banner ? (\n            <div className=\"px-2 pt-4\">\n              <div className=\"mx-auto max-w-2xl\">{banner}</div>\n            </div>\n          ) : null}\n          <div className=\"min-h-0 flex-1 [&>div]:h-full\">\n            <MessageScroller\n              contentKey={contentKey}\n              className=\"px-2 [mask-image:linear-gradient(to_bottom,transparent,#000_1.25rem,#000_calc(100%-1.25rem),transparent)]\"\n            >\n              <div className=\"mx-auto flex min-h-full w-full max-w-2xl flex-col py-6\">\n                {empty ? (\n                  <div className=\"m-auto max-w-xs py-10 text-center\">\n                    <p className=\"text-sm font-medium\">Describe a task</p>\n                    <p className=\"mt-1 text-sm text-pretty text-zinc-500\">\n                      The agent's steps, files, and reply build up here as one record of the run.\n                    </p>\n                  </div>\n                ) : null}\n\n                {lead.map((message, index) => (\n                  <Prompt key={message.id} content={message.content} className={index ? \"mt-3\" : \"\"} />\n                ))}\n\n                {items.length ? (\n                  <ol aria-label=\"Activity\" className={`flex flex-col ${lead.length ? \"mt-5\" : \"\"}`}>\n                    {items.map((item) =>\n                      item.kind === \"step\" ? (\n                        <StepRow key={item.key} domId={`${id}-${item.key}`} step={item.step} />\n                      ) : item.kind === \"artifact\" ? (\n                        <li key={item.key} id={`${id}-${item.key}`} tabIndex={-1} className={`my-1.5 min-w-0 outline-none ${rise}`}>\n                          <ArtifactPreview\n                            name={item.artifact.name}\n                            type={item.artifact.type}\n                            status={item.artifact.status}\n                            path={item.artifact.path}\n                            content={item.artifact.content}\n                            sizeBytes={item.artifact.sizeBytes}\n                            error={item.artifact.error}\n                          />\n                        </li>\n                      ) : (\n                        <ApprovalItem key={item.key} approval={item.approval} onApprove={onApprove} onReject={onReject} />\n                      ),\n                    )}\n                  </ol>\n                ) : null}\n\n                {rest.map((message) =>\n                  message.role === \"user\" ? (\n                    <Prompt key={message.id} content={message.content} className=\"mt-8\" />\n                  ) : (\n                    <StreamingMessage\n                      key={message.id}\n                      role=\"assistant\"\n                      content={message.content}\n                      status={message.status}\n                      error={message.error}\n                      className=\"mt-5\"\n                    />\n                  ),\n                )}\n\n                {run.status === \"failed\" && run.error && !failedStepShown ? (\n                  <p className={`mt-5 text-sm text-red-700 dark:text-red-400 ${rise}`}>{run.error}</p>\n                ) : null}\n              </div>\n            </MessageScroller>\n          </div>\n          <div className=\"px-2 pt-1\">\n            <div className=\"mx-auto max-w-2xl\">\n              <PromptComposer mode model permissions {...composer} onSubmit={onSubmit} onStop={onStop} status={status} />\n            </div>\n          </div>\n        </section>\n\n        {showOutline ? (\n          <aside\n            id={`${id}-outline`}\n            aria-label=\"Run outline\"\n            className={`hidden min-h-0 overflow-y-auto border-l py-6 pl-4 lg:block ${hairline}`}\n          >\n            <Outline run={run} onReveal={reveal} />\n          </aside>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\n// ---------------------------------------------------------------------------\n// The run, as a list of activity\n\ntype ActivityItem =\n  | { kind: \"step\"; key: string; status: string; step: RunStep }\n  | { kind: \"artifact\"; key: string; status: string; artifact: RunArtifact }\n  | { kind: \"approval\"; key: string; status: string; approval: RunApproval };\n\n/**\n * Steps, files, and approvals in a sensible order for a run loaded all at once: steps in the\n * order they started, a decided approval before the steps that started after the decision, then\n * files, then anything still waiting for a decision.\n */\nfunction activityItems(run: AgentRun): ActivityItem[] {\n  const ordered: ActivityItem[] = run.steps.map((step) => ({ kind: \"step\", key: `step-${step.id}`, status: step.status, step }));\n  for (const approval of run.approvals) {\n    if (approval.status === \"pending\") continue;\n    const decided = time(approval.decidedAt);\n    const index = ordered.findIndex((item) => item.kind === \"step\" && time(item.step.startedAt) > decided);\n    const entry: ActivityItem = { kind: \"approval\", key: `approval-${approval.id}`, status: approval.status, approval };\n    if (index === -1) ordered.push(entry);\n    else ordered.splice(index, 0, entry);\n  }\n  for (const artifact of run.artifacts) ordered.push({ kind: \"artifact\", key: `artifact-${artifact.id}`, status: artifact.status, artifact });\n  for (const approval of run.approvals) {\n    if (approval.status === \"pending\") ordered.push({ kind: \"approval\", key: `approval-${approval.id}`, status: approval.status, approval });\n  }\n  return ordered;\n}\n\n/**\n * Keeps entries in the order they first appeared, so a streamed run reads in the order it\n * happened and nothing jumps when an approval is decided. Entries that arrive together (a run\n * loaded from a snapshot) take the order from `activityItems`.\n */\nfunction useArrivalOrder(items: ActivityItem[]): ActivityItem[] {\n  const order = useRef(new Map<string, number>());\n  const next = useRef(0);\n  const present = new Set(items.map((item) => item.key));\n  for (const key of order.current.keys()) if (!present.has(key)) order.current.delete(key);\n  if (order.current.size === 0) next.current = 0;\n  for (const item of items) if (!order.current.has(item.key)) order.current.set(item.key, next.current++);\n  return [...items].sort((a, b) => order.current.get(a.key)! - order.current.get(b.key)!);\n}\n\n/** The request that starts a turn: the document's opening line, not a chat bubble. */\nfunction Prompt({ content, className = \"\" }: { content: string; className?: string }) {\n  return (\n    <article data-role=\"user\" className={`${rise} ${className}`}>\n      <p className=\"sr-only\">You:</p>\n      <p className=\"text-[15px] leading-relaxed font-medium tracking-[-0.005em] break-words whitespace-pre-wrap text-pretty\">{content}</p>\n    </article>\n  );\n}\n\nconst rowClass = \"-mx-2 flex min-h-9 items-center gap-3 rounded-lg px-2 py-1.5\";\nconst summaryClass = [\n  \"cursor-pointer list-none select-none [&::-webkit-details-marker]:hidden\",\n  \"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]\",\n  \"focus-visible:outline-2 focus-visible:outline-sky-500\",\n].join(\" \");\nconst disclosure = [\n  \"group [interpolate-size:allow-keywords]\",\n  // Height animates where ::details-content and interpolate-size are supported; elsewhere it simply opens.\n  \"[&::details-content]:h-0 [&::details-content]:overflow-clip [&::details-content]:transition-[height,content-visibility] [&::details-content]:duration-[220ms] [&::details-content]:ease-[cubic-bezier(0.23,1,0.32,1)] [&::details-content]:[transition-behavior:allow-discrete]\",\n  \"open:[&::details-content]:h-auto motion-reduce:[&::details-content]:transition-none\",\n].join(\" \");\n\n/** The disclosure arrow on rows that open; it turns to point down while open. */\nfunction Chevron() {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 16 16\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"1.5\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={`size-3.5 shrink-0 text-zinc-400 transition-transform duration-200 ${ease} group-open:rotate-90 motion-reduce:transition-none dark:text-zinc-500`}\n    >\n      <path d=\"m6.25 4.5 3.5 3.5-3.5 3.5\" />\n    </svg>\n  );\n}\n\n/** One step on one line: status, tool name, what it does, and how long it took. Opens in place. */\nfunction StepRow({ step, domId }: { step: RunStep; domId: string }) {\n  const hasInput = step.input !== undefined;\n  const hasOutput = step.status === \"succeeded\" && step.output != null;\n  const expandable = hasInput || hasOutput;\n  const duration = step.startedAt && step.finishedAt ? formatDuration(step.startedAt, step.finishedAt) : \"\";\n  const dim = step.status === \"queued\" || step.status === \"skipped\";\n\n  const row = (\n    <>\n      <StepGlyph key={step.status} status={step.status} activity={activityOf(step).activity} />\n      <span className=\"flex min-w-0 flex-1 items-baseline gap-2.5\">\n        <span\n          aria-hidden=\"true\"\n          className={[\n            \"max-w-[65%] shrink-0 truncate font-mono text-[13px] transition-colors duration-200 motion-reduce:transition-none\",\n            dim ? \"text-zinc-500\" : \"text-zinc-950 dark:text-white\",\n            step.status === \"skipped\" ? \"line-through decoration-zinc-500/60\" : \"\",\n          ].join(\" \")}\n        >\n          {step.name}\n        </span>\n        {/* Remounts with the status, so the log announces \"search_docs, Done\". */}\n        <span key={step.status} className=\"sr-only\">\n          {step.name}, {stepLabel[step.status]}.\n        </span>\n        {step.summary ? <span className=\"min-w-0 truncate text-sm text-zinc-500\">{step.summary}</span> : null}\n      </span>\n      <span\n        aria-hidden=\"true\"\n        className={`shrink-0 font-mono text-xs tabular-nums ${step.status === \"failed\" ? \"text-red-600 dark:text-red-400\" : \"text-zinc-500\"}`}\n      >\n        {step.status === \"succeeded\" ? duration : step.status === \"failed\" && duration ? `Failed · ${duration}` : stepLabel[step.status]}\n      </span>\n      {expandable ? (\n        <Chevron />\n      ) : (\n        <span aria-hidden=\"true\" className=\"size-3.5 shrink-0\" />\n      )}\n    </>\n  );\n\n  return (\n    <li id={domId} tabIndex={-1} data-slot=\"step\" data-status={step.status} className={`min-w-0 outline-none ${rise}`}>\n      {expandable ? (\n        <details className={disclosure}>\n          <summary className={`${rowClass} ${summaryClass}`}>{row}</summary>\n          <div className={`grid grid-cols-[minmax(0,1fr)] gap-3 pt-1 pb-3 pl-7 opacity-0 transition-opacity duration-200 ${ease} group-open:opacity-100 motion-reduce:transition-none`}>\n            {hasInput ? <Well label={hasOutput ? \"Input\" : undefined}>{JSON.stringify(step.input, null, 2)}</Well> : null}\n            {hasOutput ? (\n              <Well label={hasInput ? \"Output\" : undefined} wrap>\n                {step.output!}\n              </Well>\n            ) : null}\n          </div>\n        </details>\n      ) : (\n        <div className={rowClass}>{row}</div>\n      )}\n      {step.status === \"failed\" && step.error ? (\n        <p className={`-mt-1 pb-2 pl-7 text-xs leading-relaxed text-red-700 dark:text-red-400 ${rise}`}>{step.error}</p>\n      ) : null}\n    </li>\n  );\n}\n\n/** A preformatted value inside an opened step. `wrap` soft-wraps tool output; JSON keeps its layout. */\nfunction Well({ label, wrap = false, children }: { label?: string; wrap?: boolean; children: string }) {\n  return (\n    <div>\n      {label ? <p className=\"mb-1.5 text-xs font-medium text-zinc-500\">{label}</p> : null}\n      <pre\n        className={[\n          wrap ? \"break-words whitespace-pre-wrap\" : \"overflow-x-auto\",\n          \"rounded-lg border border-zinc-950/[0.07] bg-zinc-950/[0.02] px-3 py-2.5 font-mono text-xs leading-relaxed text-zinc-800 dark:border-white/[0.08] dark:bg-transparent dark:text-zinc-300\",\n        ].join(\" \")}\n      >\n        {children}\n      </pre>\n    </div>\n  );\n}\n\n/**\n * An approval inline in the run. When the decision lands and its buttons go away, focus moves\n * to the approval itself so keyboard and screen reader users stay where they were.\n */\nfunction ApprovalItem({\n  approval,\n  onApprove,\n  onReject,\n}: {\n  approval: RunApproval;\n  onApprove?: (approvalId: string) => void | Promise<void>;\n  onReject?: (approvalId: string) => void | Promise<void>;\n}) {\n  const ref = useRef<HTMLLIElement>(null);\n  const previous = useRef(approval.status);\n\n  useEffect(() => {\n    const was = previous.current;\n    previous.current = approval.status;\n    const element = ref.current;\n    if (was !== \"pending\" || approval.status === \"pending\" || !element) return;\n    const active = document.activeElement;\n    if (!active || active === document.body || element.contains(active)) element.focus({ preventScroll: true });\n  }, [approval.status]);\n\n  if (approval.status === \"pending\") {\n    return (\n      <li ref={ref} tabIndex={-1} className={`my-2 min-w-0 outline-none ${rise}`}>\n        <ApprovalCard\n          title={approval.title}\n          description={approval.description}\n          detail={approval.detail}\n          status={approval.status}\n          onApprove={onApprove ? () => onApprove(approval.id) : undefined}\n          onReject={onReject ? () => onReject(approval.id) : undefined}\n        />\n      </li>\n    );\n  }\n\n  // Once decided, the approval settles into a row like the steps; what it covered opens in place.\n  const decision = decisions[approval.status];\n  const row = (\n    <>\n      <span aria-hidden=\"true\" className={`flex h-5 w-4 shrink-0 items-center justify-center ${decision.tone}`}>\n        <DecisionGlyph status={approval.status} />\n      </span>\n      <span className=\"flex min-w-0 flex-1 items-baseline gap-2.5\">\n        <span className={`shrink-0 text-sm font-medium ${decision.tone}`}>{decision.label}</span>\n        <span className=\"min-w-0 truncate text-sm text-zinc-600 dark:text-zinc-400\">{approval.title}</span>\n      </span>\n      <span aria-hidden=\"true\" className=\"hidden shrink-0 text-xs text-zinc-500 sm:inline\">\n        {decision.outcome}\n      </span>\n      <span className=\"sr-only\">{decision.outcome}</span>\n    </>\n  );\n\n  return (\n    <li ref={ref} tabIndex={-1} data-slot=\"approval\" data-status={approval.status} className={`min-w-0 outline-none ${rise}`}>\n      {approval.detail || approval.description ? (\n        <details className={disclosure}>\n          <summary className={`${rowClass} ${summaryClass}`}>\n            {row}\n            <Chevron />\n          </summary>\n          <div className={`grid grid-cols-[minmax(0,1fr)] gap-2 pt-1 pb-3 pl-7 opacity-0 transition-opacity duration-200 ${ease} group-open:opacity-100 motion-reduce:transition-none`}>\n            {approval.description ? <p className=\"text-sm text-pretty text-zinc-600 dark:text-zinc-400\">{approval.description}</p> : null}\n            {approval.detail ? <Well wrap>{approval.detail}</Well> : null}\n          </div>\n        </details>\n      ) : (\n        <div className={rowClass}>\n          {row}\n          <span aria-hidden=\"true\" className=\"size-3.5 shrink-0\" />\n        </div>\n      )}\n    </li>\n  );\n}\n\nconst decisions: Record<Exclude<RunApproval[\"status\"], \"pending\">, { label: string; outcome: string; tone: string }> = {\n  approved: { label: \"Approved\", outcome: \"The agent continued.\", tone: \"text-emerald-700 dark:text-emerald-400\" },\n  rejected: { label: \"Rejected\", outcome: \"Nothing ran.\", tone: \"text-red-700 dark:text-red-400\" },\n  expired: { label: \"Expired\", outcome: \"Nothing ran.\", tone: \"text-zinc-500\" },\n};\n\n/** The approval glyphs from Approval Card: check, x, or slash in a circle. */\nfunction DecisionGlyph({ status }: { status: RunApproval[\"status\"] }) {\n  return (\n    <svg\n      viewBox=\"0 0 16 16\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={`size-4 transition-[opacity,scale] duration-200 ${ease} starting:scale-90 starting:opacity-0 motion-reduce:transition-none`}\n    >\n      <circle cx=\"8\" cy=\"8\" r=\"6.25\" />\n      {status === \"approved\" ? (\n        <path d=\"m5.35 8.25 1.75 1.75 3.55-3.75\" />\n      ) : status === \"rejected\" ? (\n        <path d=\"m6.1 6.1 3.8 3.8m0-3.8-3.8 3.8\" />\n      ) : (\n        <path d=\"m5.6 10.4 4.8-4.8\" />\n      )}\n    </svg>\n  );\n}\n\n/** The outline rail: every step and file at a glance; choosing one scrolls the run to it. */\nfunction Outline({ run, onReveal }: { run: AgentRun; onReveal: (key: string) => void }) {\n  const button = [\n    \"flex w-full min-w-0 items-center gap-2.5 rounded-md px-2 py-1.5 text-left\",\n    \"transition-colors duration-150 ease-out hover:bg-zinc-950/[0.04] motion-reduce:transition-none dark:hover:bg-white/[0.06]\",\n    \"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-500\",\n  ].join(\" \");\n\n  return (\n    <div className=\"grid gap-6\">\n      <div>\n        <p className=\"px-2 text-xs font-medium text-zinc-500\">Steps</p>\n        {run.steps.length ? (\n          <ol className=\"mt-1.5 grid\">\n            {run.steps.map((step) => (\n              <li key={step.id} data-slot=\"outline-step\" data-status={step.status}>\n                <button type=\"button\" onClick={() => onReveal(`step-${step.id}`)} className={button}>\n                  <OutlineGlyph status={step.status} />\n                  <span\n                    className={[\n                      \"min-w-0 flex-1 truncate font-mono text-xs\",\n                      step.status === \"queued\" || step.status === \"skipped\" ? \"text-zinc-500\" : \"text-zinc-800 dark:text-zinc-200\",\n                      step.status === \"skipped\" ? \"line-through decoration-zinc-500/60\" : \"\",\n                    ].join(\" \")}\n                  >\n                    {step.name}\n                  </span>\n                  <span className=\"sr-only\">, {stepLabel[step.status]}</span>\n                  {step.startedAt && step.finishedAt ? (\n                    <span aria-hidden=\"true\" className=\"shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums\">\n                      {formatDuration(step.startedAt, step.finishedAt)}\n                    </span>\n                  ) : null}\n                </button>\n              </li>\n            ))}\n          </ol>\n        ) : (\n          <p className=\"mt-1.5 px-2 text-xs text-zinc-500\">None yet</p>\n        )}\n      </div>\n      {run.artifacts.length ? (\n        <div>\n          <p className=\"px-2 text-xs font-medium text-zinc-500\">Files</p>\n          <ul className=\"mt-1.5 grid\">\n            {run.artifacts.map((artifact) => (\n              <li key={artifact.id}>\n                <button type=\"button\" onClick={() => onReveal(`artifact-${artifact.id}`)} className={button}>\n                  <span className=\"min-w-0 flex-1 truncate text-xs text-zinc-800 dark:text-zinc-200\">{artifact.name}</span>\n                  <span\n                    className={`shrink-0 text-[11px] ${artifact.status === \"failed\" ? \"text-red-600 dark:text-red-400\" : \"text-zinc-500\"}`}\n                  >\n                    {artifact.status === \"generating\" ? \"Writing\" : artifact.status === \"failed\" ? \"Failed\" : \"Ready\"}\n                  </span>\n                </button>\n              </li>\n            ))}\n          </ul>\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\n// ---------------------------------------------------------------------------\n// Glyphs and helpers\n\n/**\n * The row's status: the animated mark while running, a bare check, an x, a dash, or a small\n * open dot. Remounted per status so the new shape eases in and the check draws.\n */\nfunction StepGlyph({ status, activity }: { status: StepStatus; activity: AgentActivity }) {\n  const enter = `flex h-5 w-4 shrink-0 items-center justify-center transition-[opacity,scale,filter] duration-300 ${ease} starting:scale-75 starting:opacity-0 starting:blur-[2px] motion-reduce:transition-none`;\n  if (status === \"running\") {\n    return (\n      <span aria-hidden=\"true\" className={enter}>\n        <AgentMark activity={activity} size={16} className=\"text-zinc-950 dark:text-white\" />\n      </span>\n    );\n  }\n  const tone =\n    status === \"succeeded\"\n      ? \"text-emerald-600 dark:text-emerald-400\"\n      : status === \"failed\"\n        ? \"text-red-600 dark:text-red-400\"\n        : \"text-zinc-400 dark:text-zinc-600\";\n  return (\n    <span aria-hidden=\"true\" className={enter}>\n      <svg viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.5} strokeLinecap=\"round\" strokeLinejoin=\"round\" className={`size-4 ${tone}`}>\n        {status === \"succeeded\" ? (\n          <path\n            d=\"m4.25 8.4 2.5 2.45 5-5.6\"\n            pathLength={1}\n            strokeDasharray=\"1\"\n            className={`[stroke-dashoffset:0] transition-[stroke-dashoffset] delay-75 duration-300 ${ease} starting:[stroke-dashoffset:1] motion-reduce:transition-none`}\n          />\n        ) : status === \"failed\" ? (\n          <path d=\"m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5\" />\n        ) : status === \"skipped\" ? (\n          <path d=\"M5.5 8h5\" />\n        ) : (\n          <circle cx=\"8\" cy=\"8\" r=\"3\" />\n        )}\n      </svg>\n    </span>\n  );\n}\n\n/** Still versions of the step glyphs for the outline; only the run itself animates. */\nfunction OutlineGlyph({ status }: { status: StepStatus }) {\n  const tone =\n    status === \"succeeded\"\n      ? \"text-emerald-600 dark:text-emerald-400\"\n      : status === \"failed\"\n        ? \"text-red-600 dark:text-red-400\"\n        : status === \"running\"\n          ? \"text-zinc-950 dark:text-white\"\n          : \"text-zinc-400 dark:text-zinc-600\";\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.6} strokeLinecap=\"round\" strokeLinejoin=\"round\" className={`size-3.5 shrink-0 ${tone}`}>\n      {status === \"succeeded\" ? (\n        <path d=\"m4.25 8.4 2.5 2.45 5-5.6\" />\n      ) : status === \"failed\" ? (\n        <path d=\"m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5\" />\n      ) : status === \"skipped\" ? (\n        <path d=\"M5.5 8h5\" />\n      ) : status === \"running\" ? (\n        <circle cx=\"8\" cy=\"8\" r=\"3\" fill=\"currentColor\" stroke=\"none\" />\n      ) : (\n        <circle cx=\"8\" cy=\"8\" r=\"3\" />\n      )}\n    </svg>\n  );\n}\n\n/** Picks the mark and verb for what a step is doing, from its tool name. */\nfunction activityOf(step?: RunStep): { activity: AgentActivity; label: string } {\n  if (!step) return { activity: \"thinking\", label: \"Thinking\" };\n  const name = step.name.toLowerCase();\n  if (/search|find|query|lookup|grep|browse/.test(name)) return { activity: \"searching\", label: \"Searching\" };\n  if (/read|fetch|load|download|list/.test(name)) return { activity: \"searching\", label: \"Reading\" };\n  if (/plan|think|reason/.test(name)) return { activity: \"planning\", label: \"Planning\" };\n  if (/edit|write|patch|create|update|generate|draft/.test(name)) return { activity: \"shaping\", label: \"Editing\" };\n  return { activity: \"working\", label: \"Working\" };\n}\n\nfunction time(iso?: string): number {\n  const value = iso ? Date.parse(iso) : Number.NaN;\n  return Number.isNaN(value) ? Number.POSITIVE_INFINITY : value;\n}\n\n/** Time from the run's start to its end, or to the latest event while it is still going. */\nfunction elapsedOf(run: AgentRun): string {\n  const start = run.createdAt ? Date.parse(run.createdAt) : Number.NaN;\n  if (Number.isNaN(start)) return \"\";\n  const stamps = [run.finishedAt, ...run.steps.flatMap((step) => [step.startedAt, step.finishedAt]), ...run.approvals.map((approval) => approval.decidedAt)]\n    .map((value) => (value ? Date.parse(value) : Number.NaN))\n    .filter((value) => !Number.isNaN(value));\n  const end = run.finishedAt ? Date.parse(run.finishedAt) : Math.max(...stamps);\n  const ms = end - start;\n  if (!Number.isFinite(ms) || ms <= 0) return \"\";\n  if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;\n  return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n}\n\nfunction formatDuration(start: string, end: string): string {\n  const ms = new Date(end).getTime() - new Date(start).getTime();\n  if (!Number.isFinite(ms) || ms < 0) return \"\";\n  return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport type { AgentRun } from \"@/components/shaken/agent/agent-run\";\nimport { AgentWorkspace } from \"@/components/shaken/blocks/agent-workspace\";\n\nconst initialRun: AgentRun = {\n  id: \"run_1\",\n  title: \"Update the rate-limit docs\",\n  status: \"waiting-for-approval\",\n  createdAt: \"2026-11-14T10:00:00.000Z\",\n  messages: [{ id: \"m1\", role: \"user\", status: \"complete\", content: \"Update the rate limits and open a pull request.\" }],\n  steps: [\n    { id: \"s1\", name: \"search_docs\", kind: \"tool\", status: \"succeeded\", summary: \"Find pages that mention rate limits\", input: { query: \"rate limits\" }, output: \"Found 3 pages.\", startedAt: \"2026-11-14T10:00:00.600Z\", finishedAt: \"2026-11-14T10:00:01.400Z\" },\n    { id: \"s2\", name: \"edit_files\", kind: \"tool\", status: \"succeeded\", summary: \"Update the limits table\", output: \"Changed 1 file.\", startedAt: \"2026-11-14T10:00:01.600Z\", finishedAt: \"2026-11-14T10:00:02.600Z\" },\n  ],\n  approvals: [{ id: \"a1\", title: \"Open a pull request?\", status: \"pending\", detail: \"gh pr create --title \\\"Update rate limits\\\"\" }],\n  artifacts: [{ id: \"f1\", name: \"rate-limits.md\", type: \"text/markdown\", status: \"ready\", content: \"Free: 60/min\\nPro: 600/min\" }],\n};\n\nexport default function AgentWorkspaceExample() {\n  // In your app, build the run from your backend's events with applyEvents (see agent-run).\n  const [run, setRun] = useState(initialRun);\n  const decide = (status: \"approved\" | \"rejected\") => async (id: string) =>\n    setRun((current) => ({\n      ...current,\n      status: status === \"approved\" ? \"running\" : \"cancelled\",\n      approvals: current.approvals.map((a) => (a.id === id ? { ...a, status, decidedAt: new Date().toISOString() } : a)),\n    }));\n\n  return <AgentWorkspace run={run} height=\"36rem\" onSubmit={() => {}} onApprove={decide(\"approved\")} onReject={decide(\"rejected\")} />;\n}\n"
  }
}
