{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-04",
  "title": "Agent terminal",
  "description": "An agent's shell where output streams in and folds when long: a risky command waits, then runs when it is approved, and any command runs again.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/chip.json",
    "https://ui.ndekocode.dev/r/copy-button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/spinner.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-follow-bottom.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/run/run-04.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useState } from 'react';\n\nimport { useFollowBottom } from '@/registry/ndeko/hooks/use-follow-bottom';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  useSession,\n  type SessionStep,\n} from '@/registry/ndeko/hooks/use-session';\nimport { seriesColorOf, type RunAgent } from '@/registry/ndeko/lib/agent-run';\nimport {\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ChevronDownIcon,\n  RotateCcwIcon,\n  TriangleAlertIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { rowPresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { restingOf } from '@/registry/ndeko/lib/run-session';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { Chip } from '@/registry/ndeko/ui/chip';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { Spinner } from '@/registry/ndeko/ui/spinner';\n\nimport { CopyButton } from '@/registry/ndeko/ui/copy-button';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\n\nexport type TerminalStatus = 'waiting' | 'running' | 'done' | 'skipped';\n\nexport type TerminalCommand = {\n  id: string;\n  command: string;\n  status: TerminalStatus;\n  lines: string[];\n  exitCode?: number;\n  /** Why the command waits for a person before it runs. */\n  reason?: string;\n};\n\n/** Long output folds to its first lines once the command finishes. */\nconst FOLD_AFTER_LINES = 8;\n\nconst FOLDED_LINES = 6;\n\nfunction isFinishedStatus(status: TerminalStatus) {\n  const isDone = status === 'done';\n  const isSkipped = status === 'skipped';\n  return isDone || isSkipped;\n}\n\nfunction isFoldable(command: TerminalCommand) {\n  const isFinished = isFinishedStatus(command.status);\n  const isLong = command.lines.length > FOLD_AFTER_LINES;\n  return isFinished && isLong;\n}\n\nfunction hiddenCountLabelOf(count: number) {\n  if (count === 1) {\n    return 'Show 1 more line';\n  }\n  return `Show ${count} more lines`;\n}\n\nfunction lineToneOf(line: string) {\n  const trimmed = line.trimStart();\n  if (trimmed.startsWith('FAIL')) {\n    return 'text-destructive-ink';\n  }\n  if (trimmed.startsWith('npm ERR!')) {\n    return 'text-destructive-ink';\n  }\n  if (trimmed.startsWith('>')) {\n    return 'text-muted-foreground';\n  }\n  if (trimmed.startsWith('PASS')) {\n    return 'text-success-foreground';\n  }\n  return 'text-foreground/85';\n}\n\nfunction copyTextOf(command: TerminalCommand) {\n  const output = command.lines.join('\\n');\n  return `$ ${command.command}\\n${output}`;\n}\n\nfunction statusKeyOf(command: TerminalCommand) {\n  return `${command.status}-${command.exitCode ?? ''}`;\n}\n\nfunction CommandStatus({ command }: { command: TerminalCommand }) {\n  if (command.status === 'running') {\n    return (\n      <span className='text-muted-foreground inline-flex items-center gap-1.5 font-sans text-xs'>\n        <Spinner\n          label={`${command.command} is running`}\n          className='[&_svg]:size-3.5'\n        />\n        Running\n      </span>\n    );\n  }\n  if (command.status === 'waiting') {\n    return <Badge variant='warning'>Needs approval</Badge>;\n  }\n  if (command.status === 'skipped') {\n    return <Badge variant='secondary'>Skipped</Badge>;\n  }\n  const code = command.exitCode ?? 0;\n  if (code === 0) {\n    return (\n      <Badge variant='secondary' className='font-mono'>\n        exit 0\n      </Badge>\n    );\n  }\n  return (\n    <Badge variant='destructive' className='font-mono'>\n      exit {code}\n    </Badge>\n  );\n}\n\ntype ApprovalBarProps = {\n  command: TerminalCommand;\n  isApprovePressed: boolean;\n  onApprove?: (commandId: string) => void;\n  onSkip?: (commandId: string) => void;\n};\n\nfunction ApprovalBar({\n  command,\n  isApprovePressed,\n  onApprove,\n  onSkip,\n}: ApprovalBarProps) {\n  function approve() {\n    onApprove?.(command.id);\n  }\n\n  function skip() {\n    onSkip?.(command.id);\n  }\n\n  function decideFromKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const isOnGroup = event.target === event.currentTarget;\n    const isEnter = event.key === 'Enter';\n    if (isEnter && isOnGroup) {\n      event.preventDefault();\n      approve();\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      skip();\n    }\n  }\n\n  return (\n    <div className='@container'>\n      <div\n        role='group'\n        tabIndex={0}\n        aria-label={`${command.command} needs your approval. Enter runs it, Escape skips it.`}\n        onKeyDown={decideFromKeys}\n        className='bg-warning/10 focus-visible:ring-ring/25 mt-2 flex flex-col gap-2.5 rounded-lg p-2.5 font-sans outline-none focus-visible:ring-[3px] @lg:flex-row @lg:items-center'\n      >\n        <p className='text-warning-foreground flex min-w-0 flex-1 items-start gap-2 text-xs leading-5'>\n          <TriangleAlertIcon className='mt-0.5 size-3.5 shrink-0' />\n          {command.reason}\n        </p>\n        <div className='flex shrink-0 items-center gap-2'>\n          <Button\n            type='button'\n            size='sm'\n            onClick={approve}\n            className={pressedSolidOf(isApprovePressed)}\n          >\n            Run\n            <Kbd className='ms-0.5'>Enter</Kbd>\n          </Button>\n          <Button type='button' variant='outline' size='sm' onClick={skip}>\n            Skip\n            <Kbd className='ms-0.5'>Esc</Kbd>\n          </Button>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst LINE_CLASS =\n  'block min-h-[1lh] break-words whitespace-pre-wrap transition-opacity duration-150 starting:opacity-0';\n\nfunction OutputLines({ lines }: { lines: string[] }) {\n  return (\n    <>\n      {lines.map((line, index) => (\n        <span key={index} className={cn(LINE_CLASS, lineToneOf(line))}>\n          {line}\n        </span>\n      ))}\n    </>\n  );\n}\n\ntype CommandBlockProps = {\n  command: TerminalCommand;\n  isApprovePressed: boolean;\n  onApprove?: (commandId: string) => void;\n  onSkip?: (commandId: string) => void;\n  onRerun?: (commandId: string) => void;\n};\n\n/**\n * Lines stream straight into the block: nothing resizes it line by line. Only what a person or the\n * end of the command changes at once is animated, the lines that fold away and the approval bar.\n */\nfunction CommandBlock({\n  command,\n  isApprovePressed,\n  onApprove,\n  onSkip,\n  onRerun,\n}: CommandBlockProps) {\n  const [isExpanded, setIsExpanded] = useState(false);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const foldable = isFoldable(command);\n  const isFolded = foldable && !isExpanded;\n  const hiddenCount = command.lines.length - FOLDED_LINES;\n  const isWaiting = command.status === 'waiting';\n  const isFinished = isFinishedStatus(command.status);\n  const canRerun = isFinished && onRerun !== undefined;\n  const isEmptyFinished = isFinished && command.lines.length === 0;\n  const firstLines = command.lines.slice(0, FOLDED_LINES);\n  const laterLines = command.lines.slice(FOLDED_LINES);\n  const hasLaterLines = laterLines.length > 0;\n  const showsLaterLines = hasLaterLines && !isFolded;\n  const toggleLabel = foldToggleLabelOf(isExpanded, hiddenCount);\n\n  function toggleFold() {\n    setIsExpanded((current) => !current);\n  }\n\n  function rerun() {\n    setIsExpanded(false);\n    onRerun?.(command.id);\n  }\n\n  return (\n    <div className='flex flex-col px-3 py-2.5'>\n      <div className='flex min-h-6 items-center gap-2'>\n        <span aria-hidden='true' className='text-muted-foreground select-none'>\n          $\n        </span>\n        <code className='min-w-0 flex-1 truncate'>{command.command}</code>\n        <Swap swapKey={statusKeyOf(command)}>\n          <CommandStatus command={command} />\n        </Swap>\n        <CopyButton\n          text={copyTextOf(command)}\n          label={`Copy ${command.command} and its output`}\n        />\n        {canRerun && (\n          <Button\n            type='button'\n            variant='ghost'\n            size='icon-sm'\n            aria-label={`Run ${command.command} again`}\n            onClick={rerun}\n            className='text-muted-foreground size-6'\n          >\n            <RotateCcwIcon className='size-3.5' />\n          </Button>\n        )}\n      </div>\n      <div className='flex flex-col'>\n        <OutputLines lines={firstLines} />\n        <AnimatePresence initial={false}>\n          {showsLaterLines && (\n            <motion.div\n              key='later'\n              className='flex flex-col overflow-hidden'\n              {...rowPresence}\n            >\n              <OutputLines lines={laterLines} />\n            </motion.div>\n          )}\n        </AnimatePresence>\n        {isEmptyFinished && (\n          <span className='text-muted-foreground font-sans'>No output</span>\n        )}\n        {foldable && (\n          <button\n            type='button'\n            aria-expanded={isExpanded}\n            onClick={toggleFold}\n            className='text-muted-foreground hover:text-foreground focus-visible:ring-ring/25 mt-1 w-fit cursor-pointer rounded-md font-sans text-xs outline-none focus-visible:ring-[3px]'\n          >\n            <Swap swapKey={toggleLabel}>{toggleLabel}</Swap>\n          </button>\n        )}\n        <AnimatePresence initial={false}>\n          {isWaiting && (\n            <motion.div\n              key='approval'\n              className='-m-1 overflow-hidden p-1'\n              {...rowPresence}\n            >\n              <ApprovalBar\n                command={command}\n                isApprovePressed={isApprovePressed}\n                onApprove={onApprove}\n                onSkip={onSkip}\n              />\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n}\n\nfunction foldToggleLabelOf(isExpanded: boolean, hiddenCount: number) {\n  if (isExpanded) {\n    return 'Show fewer lines';\n  }\n  return hiddenCountLabelOf(hiddenCount);\n}\n\nexport type AgentTerminalProps = {\n  commands: TerminalCommand[];\n  agent: Pick<RunAgent, 'name' | 'series'>;\n  cwd: string;\n  onApprove?: (commandId: string) => void;\n  onSkip?: (commandId: string) => void;\n  onRerun?: (commandId: string) => void;\n  /** Shows Run held down on the command that waits, for a demonstration that presses it. */\n  isApprovePressed?: boolean;\n  className?: string;\n};\n\nexport function AgentTerminal({\n  commands,\n  agent,\n  cwd,\n  onApprove,\n  onSkip,\n  onRerun,\n  isApprovePressed = false,\n  className,\n}: AgentTerminalProps) {\n  const { scrollerRef, contentRef, isPinned, updatePinned, jumpToBottom } =\n    useFollowBottom({ tracksPinned: true });\n  const hasCommands = commands.length > 0;\n  const chipColor = seriesColorOf(agent.series);\n\n  return (\n    <section\n      aria-label={`${agent.name} terminal`}\n      className={cn(\n        'bg-card hairline-ring ring-border flex flex-col gap-3 rounded-xl p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <header className='flex items-center gap-2 px-1'>\n        <Chip color={chipColor}>{agent.name}</Chip>\n        <span className='text-muted-foreground min-w-0 truncate font-mono text-xs'>\n          {cwd}\n        </span>\n      </header>\n      <div className='relative'>\n        <div\n          ref={scrollerRef}\n          role='log'\n          aria-label='Commands and their output'\n          tabIndex={0}\n          onScroll={updatePinned}\n          className='bg-foreground/[0.03] dark:bg-foreground/[0.05] focus-visible:ring-ring/25 max-h-80 overflow-y-auto rounded-lg font-mono text-xs leading-5 outline-none focus-visible:ring-[3px]'\n        >\n          <div ref={contentRef} className='flex flex-col py-1'>\n            {commands.map((command) => (\n              <CommandBlock\n                key={command.id}\n                command={command}\n                isApprovePressed={isApprovePressed}\n                onApprove={onApprove}\n                onSkip={onSkip}\n                onRerun={onRerun}\n              />\n            ))}\n            {!hasCommands && (\n              <p className='text-muted-foreground px-3 py-2.5 font-sans'>\n                Commands show here as the agent runs them\n              </p>\n            )}\n          </div>\n        </div>\n        {!isPinned && (\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            onClick={jumpToBottom}\n            className='absolute end-2 bottom-2'\n          >\n            <ChevronDownIcon />\n            Latest output\n          </Button>\n        )}\n      </div>\n    </section>\n  );\n}\n\ntype CommandSpec = {\n  command: string;\n  lines: string[];\n  exitCode: number;\n  reason?: string;\n};\n\nconst NPM_TEST: CommandSpec = {\n  command: 'npm test',\n  exitCode: 1,\n  lines: [\n    '> brightmoor-review@1.4.0 test',\n    '> jest --ci',\n    '',\n    'FAIL src/pricing.test.ts',\n    '  pricing > applies the Q3 list price to bulk lines',\n    '    Expected: 17.9',\n    '    Received: 18.4',\n    '',\n    \"      42 |   const line = bulkLine('BM-2210', 400);\",\n    \"    > 43 |   expect(priceOf(line, 'Q3')).toBe(17.9);\",\n    '      44 | });',\n    '',\n    'PASS src/invoices.test.ts',\n    'PASS src/currency.test.ts',\n    'PASS src/email.test.ts',\n    'PASS src/vendors.test.ts',\n    'PASS src/totals.test.ts',\n    '',\n    'Test Suites: 1 failed, 5 passed, 6 total',\n    'Tests:       1 failed, 47 passed, 48 total',\n    'Snapshots:   0 total',\n    'Time:        3.12 s',\n    'Ran all test suites.',\n    'npm ERR! Test failed. See above for more details.',\n  ],\n};\n\nconst GIT_DIFF: CommandSpec = {\n  command: 'git diff --stat',\n  exitCode: 0,\n  lines: [\n    ' src/pricing.ts         | 14 +++++++-------',\n    ' src/pricing.test.ts    |  6 ++++--',\n    ' data/brightmoor-q3.csv | 42 ++++++++++++++++++++',\n    ' 3 files changed, 53 insertions(+), 9 deletions(-)',\n  ],\n};\n\nconst CLEAR_CACHE: CommandSpec = {\n  command: 'rm -rf ./tmp/cache',\n  exitCode: 0,\n  lines: [],\n  reason:\n    'Deletes 214 cached files. They are not in git, so this cannot be undone.',\n};\n\nconst PRICING_TEST: CommandSpec = {\n  command: 'npm test -- pricing',\n  exitCode: 0,\n  lines: [\n    '> brightmoor-review@1.4.0 test',\n    '> jest --ci pricing',\n    '',\n    'PASS src/pricing.test.ts',\n    '',\n    'Test Suites: 1 passed, 1 total',\n    'Tests:       8 passed, 8 total',\n    'Snapshots:   0 total',\n    'Time:        0.94 s',\n    'Ran all test suites matching /pricing/i.',\n  ],\n};\n\nconst SPECS: Record<string, CommandSpec> = {\n  test: NPM_TEST,\n  diff: GIT_DIFF,\n  cache: CLEAR_CACHE,\n  retest: PRICING_TEST,\n};\n\nconst CODER: Pick<RunAgent, 'name' | 'series'> = { name: 'Coder', series: 5 };\n\n/** Output lands a few lines at a time, the way a process flushes it: one render and one scroll per batch. */\nconst LINES_PER_BATCH = 3;\n\nconst BATCH_MS = 300;\n\nconst SETTLE_MS = 250;\n\n/** A command that waits on a person is run by the demonstration after this long. */\nconst APPROVE_AFTER_MS = 2500;\n\n/** Who prints a command: the script plays its first run, a person's rerun is played by their own click. */\ntype Source = 'script' | 'hand';\n\ntype ShellState = {\n  commands: TerminalCommand[];\n  /** The command the script is playing, if any. */\n  scriptedId: string | null;\n};\n\ntype ShellAction =\n  | { type: 'start'; id: string }\n  | { type: 'print'; id: string; count: number; by: Source }\n  | { type: 'exit'; id: string; by: Source }\n  | { type: 'approve'; id: string }\n  | { type: 'skip'; id: string }\n  | { type: 'rerun'; id: string };\n\ntype ShellStep = SessionStep<ShellState, ShellAction>;\n\nconst INITIAL: ShellState = { commands: [], scriptedId: null };\n\nfunction firstStatusOf(spec: CommandSpec): TerminalStatus {\n  if (spec.reason !== undefined) {\n    return 'waiting';\n  }\n  return 'running';\n}\n\nfunction commandIn(state: ShellState, id: string) {\n  return state.commands.find((command) => command.id === id);\n}\n\nfunction withCommand(state: ShellState, next: TerminalCommand): ShellState {\n  const commands = state.commands.map((command) => {\n    if (command.id === next.id) {\n      return next;\n    }\n    return command;\n  });\n  return { ...state, commands };\n}\n\nfunction isPrintedBy(state: ShellState, id: string, by: Source) {\n  const isScripted = state.scriptedId === id;\n  if (by === 'script') {\n    return isScripted;\n  }\n  return !isScripted;\n}\n\nfunction started(state: ShellState, id: string): ShellState {\n  const spec = SPECS[id];\n  const isKnown = commandIn(state, id) !== undefined;\n  if (!spec || isKnown) {\n    return state;\n  }\n  const command: TerminalCommand = {\n    id,\n    command: spec.command,\n    status: firstStatusOf(spec),\n    lines: [],\n    reason: spec.reason,\n  };\n  return { commands: [...state.commands, command], scriptedId: id };\n}\n\n/** The running command, when the action comes from whoever is printing it. */\nfunction printableIn(state: ShellState, id: string, by: Source) {\n  const command = commandIn(state, id);\n  const isRunning = command?.status === 'running';\n  const isTheirs = isPrintedBy(state, id, by);\n  if (isRunning && isTheirs) {\n    return command;\n  }\n  return undefined;\n}\n\nfunction printed(state: ShellState, id: string, count: number, by: Source) {\n  const command = printableIn(state, id, by);\n  const spec = SPECS[id];\n  if (!command || !spec) {\n    return state;\n  }\n  const lines = spec.lines.slice(0, count);\n  return withCommand(state, { ...command, lines });\n}\n\nfunction scriptedAfterExit(state: ShellState, by: Source) {\n  if (by === 'script') {\n    return null;\n  }\n  return state.scriptedId;\n}\n\nfunction exited(state: ShellState, id: string, by: Source): ShellState {\n  const command = printableIn(state, id, by);\n  const spec = SPECS[id];\n  if (!command || !spec) {\n    return state;\n  }\n  const done: TerminalCommand = {\n    ...command,\n    status: 'done',\n    lines: spec.lines,\n    exitCode: spec.exitCode,\n  };\n  const next = withCommand(state, done);\n  return { ...next, scriptedId: scriptedAfterExit(state, by) };\n}\n\nfunction approved(state: ShellState, id: string) {\n  const command = commandIn(state, id);\n  if (command?.status !== 'waiting') {\n    return state;\n  }\n  return withCommand(state, { ...command, status: 'running' });\n}\n\nfunction scriptedAfterSkip(state: ShellState, id: string) {\n  if (state.scriptedId === id) {\n    return null;\n  }\n  return state.scriptedId;\n}\n\nfunction skipped(state: ShellState, id: string): ShellState {\n  const command = commandIn(state, id);\n  if (command?.status !== 'waiting') {\n    return state;\n  }\n  const next = withCommand(state, { ...command, status: 'skipped' });\n  return { ...next, scriptedId: scriptedAfterSkip(state, id) };\n}\n\n/** A command that needed approval asks again before it runs a second time. */\nfunction rerun(state: ShellState, id: string) {\n  const command = commandIn(state, id);\n  const spec = SPECS[id];\n  if (!command || !spec) {\n    return state;\n  }\n  if (!isFinishedStatus(command.status)) {\n    return state;\n  }\n  const again: TerminalCommand = {\n    ...command,\n    status: firstStatusOf(spec),\n    lines: [],\n    exitCode: undefined,\n  };\n  return withCommand(state, again);\n}\n\nfunction reducer(state: ShellState, action: ShellAction): ShellState {\n  switch (action.type) {\n    case 'start':\n      return started(state, action.id);\n    case 'print':\n      return printed(state, action.id, action.count, action.by);\n    case 'exit':\n      return exited(state, action.id, action.by);\n    case 'approve':\n      return approved(state, action.id);\n    case 'skip':\n      return skipped(state, action.id);\n    case 'rerun':\n      return rerun(state, action.id);\n  }\n}\n\n/** How many lines show after each batch: 3, 6, 9 and so on up to all of them. */\nfunction batchEndsOf(lineCount: number) {\n  const ends: number[] = [];\n  for (let end = LINES_PER_BATCH; end < lineCount; end += LINES_PER_BATCH) {\n    ends.push(end);\n  }\n  if (lineCount > 0) {\n    ends.push(lineCount);\n  }\n  return ends;\n}\n\nfunction printSteps(id: string): ShellStep[] {\n  const spec = SPECS[id];\n  const ends = batchEndsOf(spec.lines.length);\n  return ends.map((count) => ({\n    after: BATCH_MS,\n    action: { type: 'print', id, count, by: 'script' },\n  }));\n}\n\nfunction scriptedRun(id: string, startAfter: number): ShellStep[] {\n  return [\n    { after: startAfter, action: { type: 'start', id } },\n    ...printSteps(id),\n    { after: SETTLE_MS, action: { type: 'exit', id, by: 'script' } },\n  ];\n}\n\nfunction isCacheDecided(state: ShellState) {\n  const command = commandIn(state, 'cache');\n  const isAsked = command !== undefined;\n  const isWaiting = command?.status === 'waiting';\n  return isAsked && !isWaiting;\n}\n\nconst SCRIPT: ShellStep[] = [\n  ...scriptedRun('test', 700),\n  ...scriptedRun('diff', 300),\n  { after: 500, action: { type: 'start', id: 'cache' } },\n  {\n    after: APPROVE_AFTER_MS,\n    by: 'person',\n    press: 'run',\n    action: { type: 'approve', id: 'cache' },\n    isAnswered: isCacheDecided,\n  },\n  { after: 700, action: { type: 'exit', id: 'cache', by: 'script' } },\n  ...scriptedRun('retest', 400),\n];\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: restingOf(INITIAL, SCRIPT, reducer),\n  script: SCRIPT,\n  loopAfter: 3000,\n};\n\nfunction announcementOf(commands: TerminalCommand[]) {\n  const last = commands[commands.length - 1];\n  if (!last) {\n    return '';\n  }\n  if (last.status === 'waiting') {\n    return `${last.command} needs your approval`;\n  }\n  if (last.status === 'skipped') {\n    return `Skipped ${last.command}`;\n  }\n  if (last.status === 'running') {\n    return `Running ${last.command}`;\n  }\n  return `${last.command} exited with code ${last.exitCode ?? 0}`;\n}\n\nexport default function Run04() {\n  const { schedule, clearAll } = useTimeouts();\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const commands = state.commands;\n  const announcement = announcementOf(commands);\n  const isSettled = commands.every((command) =>\n    isFinishedStatus(command.status)\n  );\n  const isOver = isFinished && isSettled;\n  const canReplay = isOver && !isAutoplaying;\n\n  function stream(commandId: string) {\n    const spec = SPECS[commandId];\n    if (!spec) {\n      return;\n    }\n    const ends = batchEndsOf(spec.lines.length);\n    ends.forEach((count, index) => {\n      const batchNumber = index + 1;\n      const printDelay = batchNumber * BATCH_MS;\n      schedule(() => {\n        act({ type: 'print', id: commandId, count, by: 'hand' });\n      }, printDelay);\n    });\n    const printTime = ends.length * BATCH_MS;\n    const exitDelay = printTime + SETTLE_MS;\n    schedule(() => {\n      act({ type: 'exit', id: commandId, by: 'hand' });\n    }, exitDelay);\n  }\n\n  /** The script prints the command it asked about. Any other approved command is printed from here. */\n  function approve(commandId: string) {\n    act({ type: 'approve', id: commandId });\n    const isScripted = state.scriptedId === commandId;\n    if (!isScripted) {\n      stream(commandId);\n    }\n  }\n\n  function skip(commandId: string) {\n    act({ type: 'skip', id: commandId });\n  }\n\n  function rerunCommand(commandId: string) {\n    act({ type: 'rerun', id: commandId });\n    const needsApproval = SPECS[commandId]?.reason !== undefined;\n    if (!needsApproval) {\n      stream(commandId);\n    }\n  }\n\n  function replay() {\n    clearAll();\n    restart();\n  }\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[26.5rem] w-full max-w-[40rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <AgentTerminal\n          commands={commands}\n          agent={CODER}\n          cwd='~/work/brightmoor-review'\n          onApprove={approve}\n          onSkip={skip}\n          onRerun={rerunCommand}\n          isApprovePressed={pressed === 'run'}\n        />\n      </ClockGate>\n      <div className='flex h-7 items-center justify-end'>\n        <ReplayButton isShown={canReplay} onReplay={replay} />\n      </div>\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "run"
  ],
  "type": "registry:component"
}