{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-03",
  "title": "Run in sentences",
  "description": "One bar of where the time went and a sentence per step on its own track: the sentence rewrites itself word by word when a step ends, and a step waiting on you lifts out with Approve.",
  "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/call-status.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.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/theme.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/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/run/run-03.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport {\n  elapsedOf,\n  emptyRun,\n  formatDuration,\n  pendingApprovalsOf,\n  type ApprovalRequest,\n  type CallStatus,\n  type PlanStep,\n  type RunEvent,\n  type RunSnapshot,\n  type RunStatus,\n  type StepStatus,\n} from '@/registry/ndeko/lib/agent-run';\nimport {\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport { CheckIcon } from '@/registry/ndeko/lib/icons';\nimport {\n  applyBatchAt,\n  batch,\n  batchOf,\n  reduceBatch,\n  restingOf,\n  type RunStep,\n} 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';\n\nimport { CallStatusMark } from '@/registry/ndeko/ui/call-status';\nimport {\n  ClockGate,\n  LiveDuration,\n  useLiveNow,\n} from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport {\n  INSTANT,\n  rowPresenceOf,\n  SPRING,\n  springOf,\n} from '@/registry/ndeko/lib/motion-presets';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { PAGE_ERROR, RUN_TITLE } from './_parts/scenario';\n\nexport type StepKind = 'thinking' | 'tools' | 'waiting' | 'writing';\n\nexport type RunSentence = {\n  step: PlanStep;\n  kind: StepKind;\n  /** The request a step waits on; while it is pending the step lifts out of the list. */\n  approval?: ApprovalRequest;\n};\n\ntype RunTiming = Pick<RunSnapshot, 'status' | 'startedAt' | 'endedAt'>;\n\nconst KINDS: StepKind[] = ['thinking', 'tools', 'waiting', 'writing'];\n\nconst KIND_LABEL: Record<StepKind, string> = {\n  thinking: 'Thinking',\n  tools: 'Tools',\n  waiting: 'Waiting on you',\n  writing: 'Writing',\n};\n\nconst KIND_COLOR: Record<StepKind, string> = {\n  thinking: 'var(--chart-3)',\n  tools: 'var(--chart-1)',\n  waiting: 'var(--warning)',\n  writing: 'var(--chart-2)',\n};\n\nconst RUN_STATUS_LOOK: Record<\n  RunStatus,\n  { label: string; variant: 'secondary' | 'success' | 'warning' }\n> = {\n  idle: { label: 'Not started', variant: 'secondary' },\n  running: { label: 'Running', variant: 'secondary' },\n  waiting: { label: 'Waiting on you', variant: 'warning' },\n  done: { label: 'Done', variant: 'success' },\n  failed: { label: 'Failed', variant: 'secondary' },\n  cancelled: { label: 'Stopped', variant: 'secondary' },\n};\n\nconst LIFT_Y = -3;\n\nfunction isLiveRun(run: RunTiming) {\n  const isRunning = run.status === 'running';\n  const isWaiting = run.status === 'waiting';\n  return isRunning || isWaiting;\n}\n\nfunction isPending(approval: ApprovalRequest | undefined) {\n  if (!approval) {\n    return false;\n  }\n  return approval.status === 'pending';\n}\n\nfunction pendingOf(approval: ApprovalRequest | undefined) {\n  if (isPending(approval)) {\n    return approval ?? null;\n  }\n  return null;\n}\n\nfunction markOf(status: StepStatus, isWaiting: boolean): CallStatus {\n  if (isWaiting) {\n    return 'waiting';\n  }\n  if (status === 'upcoming') {\n    return 'queued';\n  }\n  if (status === 'skipped') {\n    return 'done';\n  }\n  return status;\n}\n\nfunction liftOf(isLifted: boolean, shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return 0;\n  }\n  if (isLifted) {\n    return LIFT_Y;\n  }\n  return 0;\n}\n\nfunction rowSurfaceOf(isLifted: boolean, isDimmed: boolean) {\n  if (isLifted) {\n    return 'surface-raised';\n  }\n  if (isDimmed) {\n    return 'opacity-55';\n  }\n  return 'opacity-100';\n}\n\ntype KindTotals = Record<StepKind, number>;\n\ntype KindShare = {\n  kind: StepKind;\n  /** Where the kind starts on the bar and how much of it is its own, both from 0 to 1. */\n  start: number;\n  share: number;\n};\n\n/**\n * The bar and the tracks are drawn one step ahead and travel there at a constant speed, so one\n * transition plays per step. `GROW` below lasts exactly as long.\n */\nconst GROW_STEP_MS = 1000;\n\nconst MIN_TRACK_SHARE = 0.012;\n\nconst GROW =\n  'transition-transform duration-1000 ease-linear motion-reduce:transition-none';\n\nconst GLIDE =\n  'transition-transform duration-300 ease-(--ease-in-out-strong) motion-reduce:transition-none';\n\n/** Without motion nothing travels, so nothing is drawn ahead of the present. */\nfunction leadOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return 0;\n  }\n  return GROW_STEP_MS;\n}\n\nfunction travelOf(isLive: boolean) {\n  if (isLive) {\n    return GROW;\n  }\n  return GLIDE;\n}\n\nfunction totalsOf(sentences: RunSentence[], now: number): KindTotals {\n  const totals: KindTotals = { thinking: 0, tools: 0, waiting: 0, writing: 0 };\n  for (const sentence of sentences) {\n    const elapsed = elapsedOf(sentence.step, now);\n    totals[sentence.kind] += elapsed;\n  }\n  return totals;\n}\n\nfunction sharesOf(totals: KindTotals): KindShare[] {\n  let sum = 0;\n  for (const kind of KINDS) {\n    sum += totals[kind];\n  }\n  const whole = Math.max(1, sum);\n  const shares: KindShare[] = [];\n  let start = 0;\n  for (const kind of KINDS) {\n    const share = totals[kind] / whole;\n    shares.push({ kind, start, share });\n    start += share;\n  }\n  return shares;\n}\n\n/** A segment is the whole bar, moved to its start and scaled to its share: no width to lay out. */\nfunction segmentStyleOf(segment: KindShare): React.CSSProperties {\n  const offset = segment.start * 100;\n  return {\n    backgroundColor: KIND_COLOR[segment.kind],\n    transform: `translateX(${offset}%) scaleX(${segment.share})`,\n  };\n}\n\n/** A gap between two segments: a mark of the surface behind the bar, moved to where they meet. */\nfunction boundaryStyleOf(segment: KindShare): React.CSSProperties {\n  const offset = segment.start * 100;\n  return { transform: `translateX(${offset}%)` };\n}\n\nfunction isInsideBar(segment: KindShare) {\n  const isPastStart = segment.start > 0;\n  const isBeforeEnd = segment.start < 1;\n  return isPastStart && isBeforeEnd;\n}\n\nfunction isRunningKind(sentences: RunSentence[], kind: StepKind) {\n  return sentences.some((sentence) => {\n    const isKind = sentence.kind === kind;\n    const isRunning = sentence.step.status === 'running';\n    return isKind && isRunning;\n  });\n}\n\nfunction kindTotalOf(sentences: RunSentence[], kind: StepKind, now: number) {\n  let total = 0;\n  for (const sentence of sentences) {\n    if (sentence.kind === kind) {\n      total += elapsedOf(sentence.step, now);\n    }\n  }\n  return total;\n}\n\ntype KindTimeProps = {\n  sentences: RunSentence[];\n  kind: StepKind;\n  isLive: boolean;\n};\n\n/** Only the figure of the kind being spent ticks: the three others hold still. */\nfunction KindTime({ sentences, kind, isLive }: KindTimeProps) {\n  const isSpending = isRunningKind(sentences, kind);\n  const isTicking = isLive && isSpending;\n  const now = useLiveNow(100, isTicking);\n  const total = kindTotalOf(sentences, kind, now);\n\n  return (\n    <span className='inline-block min-w-7 tabular-nums'>\n      {formatDuration(total)}\n    </span>\n  );\n}\n\nfunction TimeSplit({\n  sentences,\n  run,\n}: {\n  sentences: RunSentence[];\n  run: RunTiming;\n}) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const isLive = isLiveRun(run);\n  const now = useLiveNow(GROW_STEP_MS, isLive);\n  const lead = leadOf(shouldReduceMotion);\n  const reach = now + lead;\n  const totals = totalsOf(sentences, reach);\n  const shares = sharesOf(totals);\n  const laterShares = shares.slice(1);\n  const boundaries = laterShares.filter(isInsideBar);\n  const travel = travelOf(isLive);\n\n  return (\n    <div className='flex flex-col gap-2.5'>\n      <div\n        aria-hidden='true'\n        className='bg-foreground/[0.05] relative h-2.5 overflow-hidden rounded-full'\n      >\n        {shares.map((segment) => (\n          <span\n            key={segment.kind}\n            className={cn('absolute inset-0 origin-left', travel)}\n            style={segmentStyleOf(segment)}\n          />\n        ))}\n        {boundaries.map((segment) => (\n          <span\n            key={segment.kind}\n            className={cn('absolute inset-0', travel)}\n            style={boundaryStyleOf(segment)}\n          >\n            <span className='bg-card absolute inset-y-0 -start-px w-0.5' />\n          </span>\n        ))}\n      </div>\n      <ul\n        aria-label='Time by kind'\n        className='flex flex-wrap gap-x-4 gap-y-1 text-xs'\n      >\n        {KINDS.map((kind) => (\n          <li key={kind} className='flex items-center gap-1.5'>\n            <span\n              className='size-2 rounded-full'\n              style={{ backgroundColor: KIND_COLOR[kind] }}\n            />\n            <span className='text-muted-foreground'>{KIND_LABEL[kind]}</span>\n            <KindTime sentences={sentences} kind={kind} isLive={isLive} />\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n\nfunction trackWholeOf(run: RunTiming, reach: number, windowMs: number) {\n  const runStart = run.startedAt ?? reach;\n  const runEnd = run.endedAt ?? reach;\n  const spent = runEnd - runStart;\n  return Math.max(1, spent, windowMs);\n}\n\n/** A track is the whole lane, moved to where its step starts and scaled to how long it took. */\nfunction trackStyleOf(\n  sentence: RunSentence,\n  run: RunTiming,\n  reach: number,\n  windowMs: number\n) {\n  const whole = trackWholeOf(run, reach, windowMs);\n  const runStart = run.startedAt ?? reach;\n  const stepStart = sentence.step.startedAt ?? reach;\n  const stepElapsed = elapsedOf(sentence.step, reach);\n  const waited = stepStart - runStart;\n  const startShare = waited / whole;\n  const share = stepElapsed / whole;\n  const shownShare = Math.max(share, MIN_TRACK_SHARE);\n  const offset = startShare * 100;\n  return {\n    backgroundColor: KIND_COLOR[sentence.kind],\n    transform: `translateX(${offset}%) scaleX(${shownShare})`,\n    '--track-from': `${offset}%`,\n  } as React.CSSProperties;\n}\n\n/** A step that is running starts from nothing, so its track is seen growing from the first frame. */\nfunction trackBirthOf(isRunning: boolean) {\n  if (isRunning) {\n    return 'starting:[transform:translateX(var(--track-from))_scaleX(0)]';\n  }\n  return undefined;\n}\n\nfunction StepTrack({\n  sentence,\n  run,\n  windowMs,\n}: {\n  sentence: RunSentence;\n  run: RunTiming;\n  windowMs: number;\n}) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const isLive = isLiveRun(run);\n  const isRunning = sentence.step.status === 'running';\n  const now = useLiveNow(GROW_STEP_MS, isLive);\n  const stepStart = sentence.step.startedAt ?? now;\n  const present = Math.max(now, stepStart);\n  const lead = leadOf(shouldReduceMotion);\n  const reach = present + lead;\n  const style = trackStyleOf(sentence, run, reach, windowMs);\n\n  return (\n    <span\n      aria-hidden='true'\n      className='bg-foreground/[0.06] relative block h-1 overflow-hidden rounded-full'\n    >\n      <span\n        className={cn(\n          'absolute inset-0 origin-left',\n          travelOf(isLive),\n          trackBirthOf(isRunning)\n        )}\n        style={style}\n      />\n    </span>\n  );\n}\n\nfunction ApprovalAsk({\n  approval,\n  isApprovePressed,\n  onApprove,\n  onDeny,\n}: {\n  approval: ApprovalRequest;\n  isApprovePressed: boolean;\n  onApprove?: (approvalId: string) => void;\n  onDeny?: (approvalId: string) => void;\n}) {\n  return (\n    <div className='flex flex-col gap-3 pt-3'>\n      <div className='bg-foreground/[0.03] rounded-lg p-3'>\n        <p className='text-[13px] font-medium'>{approval.title}</p>\n        {approval.detail && (\n          <p className='text-muted-foreground mt-1 text-xs leading-5'>\n            {approval.detail}\n          </p>\n        )}\n      </div>\n      <div className='flex items-center gap-3'>\n        <Button\n          type='button'\n          size='sm'\n          onClick={() => onApprove?.(approval.id)}\n          className={pressedSolidOf(isApprovePressed)}\n        >\n          <CheckIcon />\n          Approve\n        </Button>\n        <Button\n          type='button'\n          variant='link'\n          size='sm'\n          onClick={() => onDeny?.(approval.id)}\n          className='px-0'\n        >\n          Deny\n        </Button>\n      </div>\n    </div>\n  );\n}\n\nconst WORD_SWAP = {\n  initial: { opacity: 0, y: 4, filter: 'blur(2px)' },\n  animate: { opacity: 1, y: 0, filter: 'blur(0px)' },\n  exit: { opacity: 0, y: -4, filter: 'blur(2px)' },\n  transition: { duration: 0.2, ease: [0.23, 1, 0.32, 1], layout: SPRING },\n} as const;\n\nconst WORD_FADE = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0 },\n  transition: { duration: 0.15, layout: INSTANT },\n} as const;\n\nfunction wordMotionOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return WORD_FADE;\n  }\n  return WORD_SWAP;\n}\n\n/**\n * A step sentence wraps, so it rewrites itself word by word: a word that changed leaves and its\n * replacement rises in, a word that stayed slides to its new place, once per rewrite.\n */\nfunction SentenceText({ text }: { text: string }) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const wordMotion = wordMotionOf(shouldReduceMotion);\n  const words = text.split(' ');\n\n  return (\n    <span className='relative min-w-0 flex-1 text-[13px] leading-5'>\n      <span className='sr-only'>{text}</span>\n      <span aria-hidden='true'>\n        <AnimatePresence initial={false} mode='popLayout'>\n          {words.map((word, index) => (\n            <motion.span\n              key={`${index}:${word}`}\n              layout='position'\n              layoutDependency={text}\n              className='inline-block whitespace-pre'\n              {...wordMotion}\n            >\n              {`${word} `}\n            </motion.span>\n          ))}\n        </AnimatePresence>\n      </span>\n    </span>\n  );\n}\n\ntype SentenceRowProps = {\n  sentence: RunSentence;\n  run: RunTiming;\n  windowMs: number;\n  isDimmed: boolean;\n  isApprovePressed: boolean;\n  onApprove?: (approvalId: string) => void;\n  onDeny?: (approvalId: string) => void;\n};\n\nfunction SentenceRow({\n  sentence,\n  run,\n  windowMs,\n  isDimmed,\n  isApprovePressed,\n  onApprove,\n  onDeny,\n}: SentenceRowProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const { step, approval } = sentence;\n  const askingApproval = pendingOf(approval);\n  const isLifted = askingApproval !== null;\n  const isRunning = step.status === 'running';\n  const isFailed = step.status === 'failed';\n  const hasFailureDetail = isFailed && step.detail !== undefined;\n  const hasStarted = step.startedAt !== undefined;\n  const mark = markOf(step.status, isLifted);\n  const liftY = liftOf(isLifted, shouldReduceMotion);\n  const spring = springOf(shouldReduceMotion);\n\n  return (\n    <motion.div\n      animate={{ y: liftY }}\n      transition={spring}\n      className={cn(\n        'relative rounded-xl px-2.5 py-2 transition-[background-color,box-shadow,opacity] duration-200 ease-(--ease-out-strong)',\n        rowSurfaceOf(isLifted, isDimmed)\n      )}\n    >\n      <div className='flex items-start gap-3'>\n        <CallStatusMark status={mark} className='mt-0.5' />\n        <div className='flex min-w-0 flex-1 flex-col gap-1.5'>\n          <div className='flex items-baseline justify-between gap-3'>\n            <SentenceText text={step.title} />\n            {hasStarted && (\n              <LiveDuration\n                item={step}\n                isRunning={isRunning}\n                className='text-muted-foreground min-w-8 shrink-0 text-end text-xs'\n              />\n            )}\n          </div>\n          {hasFailureDetail && (\n            <p className='text-destructive-ink text-xs'>{step.detail}</p>\n          )}\n          <StepTrack sentence={sentence} run={run} windowMs={windowMs} />\n        </div>\n      </div>\n      <AnimatePresence initial={false}>\n        {askingApproval && (\n          <motion.div\n            key='ask'\n            className='overflow-hidden ps-7'\n            {...rowPresence}\n          >\n            <ApprovalAsk\n              approval={askingApproval}\n              isApprovePressed={isApprovePressed}\n              onApprove={onApprove}\n              onDeny={onDeny}\n            />\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </motion.div>\n  );\n}\n\nfunction hasStartedStep(sentence: RunSentence) {\n  return sentence.step.status !== 'upcoming';\n}\n\nexport type RunInSentencesProps = {\n  title: string;\n  run: RunTiming;\n  sentences: RunSentence[];\n  onApprove?: (approvalId: string) => void;\n  onDeny?: (approvalId: string) => void;\n  /**\n   * How long each track spans from the start of the run. While the run fits in it a finished track\n   * never moves and the running one only grows. Without it the tracks follow the length of the run.\n   */\n  windowMs?: number;\n  /** Shows Approve held down, for a demonstration that presses it. */\n  isApprovePressed?: boolean;\n  className?: string;\n};\n\nexport function RunInSentences({\n  title,\n  run,\n  sentences,\n  onApprove,\n  onDeny,\n  windowMs = 0,\n  isApprovePressed = false,\n  className,\n}: RunInSentencesProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const startedSentences = sentences.filter(hasStartedStep);\n  const hasLifted = startedSentences.some((sentence) =>\n    isPending(sentence.approval)\n  );\n  const hasSteps = startedSentences.length > 0;\n  const statusLook = RUN_STATUS_LOOK[run.status];\n  const hasStarted = run.startedAt !== undefined;\n\n  function isDimmed(sentence: RunSentence) {\n    const isLifted = isPending(sentence.approval);\n    return hasLifted && !isLifted;\n  }\n\n  return (\n    <section\n      aria-label={title}\n      className={cn(\n        'bg-card hairline-ring ring-border flex flex-col gap-4 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <header className='flex items-start justify-between gap-3'>\n        <div className='min-w-0'>\n          <h3 className='text-sm font-medium text-balance'>{title}</h3>\n          {hasStarted && (\n            <LiveDuration\n              item={run}\n              isRunning={isLiveRun(run)}\n              className='text-muted-foreground text-xs'\n            />\n          )}\n        </div>\n        <Badge variant={statusLook.variant}>\n          <Swap swapKey={run.status}>{statusLook.label}</Swap>\n        </Badge>\n      </header>\n      <TimeSplit sentences={startedSentences} run={run} />\n      <ol aria-label='Steps' className='-mx-2.5 flex flex-col'>\n        <AnimatePresence initial={false}>\n          {startedSentences.map((sentence) => (\n            <motion.li key={sentence.step.id} {...rowPresence}>\n              <SentenceRow\n                sentence={sentence}\n                run={run}\n                windowMs={windowMs}\n                isDimmed={isDimmed(sentence)}\n                isApprovePressed={isApprovePressed}\n                onApprove={onApprove}\n                onDeny={onDeny}\n              />\n            </motion.li>\n          ))}\n        </AnimatePresence>\n      </ol>\n      {!hasSteps && (\n        <p className='text-muted-foreground text-[13px]'>\n          The steps show here as the agent takes them\n        </p>\n      )}\n    </section>\n  );\n}\n\nconst STEP_KINDS: Record<string, StepKind> = {\n  scope: 'thinking',\n  search: 'tools',\n  page: 'tools',\n  'page-again': 'tools',\n  sheet: 'tools',\n  compare: 'thinking',\n  draft: 'writing',\n  approve: 'waiting',\n  send: 'tools',\n  summary: 'writing',\n};\n\nfunction upcoming(id: string, title: string): PlanStep {\n  return { id, title, status: 'upcoming' };\n}\n\n/** Each step is told in the present while it runs and rewritten in the past when it ends. */\nconst PLAN: PlanStep[] = [\n  upcoming('scope', 'Working out what the review needs'),\n  upcoming('search', 'Searching the web for Brightmoor prices'),\n  upcoming('page', 'Reading the Brightmoor pricing page'),\n  upcoming('page-again', 'Reading the pricing page again'),\n  upcoming('sheet', 'Reading the Q3 invoices spreadsheet'),\n  upcoming('compare', 'Comparing invoice lines with the list price'),\n  upcoming('draft', 'Writing the email to Brightmoor accounts'),\n  upcoming('approve', 'Waiting for you to approve the email'),\n  upcoming('send', 'Sending the email to Brightmoor accounts'),\n  upcoming('summary', 'Writing the summary for the finance team'),\n];\n\nconst SEND_APPROVAL: ApprovalRequest = {\n  id: 'send-email',\n  title: 'Send the Q3 pricing review to accounts@brightmoor-supply.example',\n  risk: 'medium',\n  status: 'pending',\n  detail: '186 words with the comparison attached. It asks for $1,840.20 back.',\n};\n\nconst INITIAL_RUN = emptyRun({ id: 'brightmoor-sentences', title: RUN_TITLE });\n\nfunction started(id: string): RunEvent {\n  return { type: 'step.updated', id, patch: { status: 'running' } };\n}\n\nfunction ended(id: string, title: string): RunEvent {\n  return { type: 'step.updated', id, patch: { status: 'done', title } };\n}\n\nconst PAGE_FAILED: RunEvent = {\n  type: 'step.updated',\n  id: 'page',\n  patch: {\n    status: 'failed',\n    title: 'Could not read the Brightmoor pricing page',\n    detail: PAGE_ERROR,\n  },\n};\n\nconst APPROVED = batchOf(\n  { type: 'approval.resolved', id: SEND_APPROVAL.id, decision: 'approved' },\n  ended('approve', 'You approved the email')\n);\n\nconst DENIED = batchOf(\n  { type: 'approval.resolved', id: SEND_APPROVAL.id, decision: 'denied' },\n  {\n    type: 'step.updated',\n    id: 'approve',\n    patch: {\n      status: 'failed',\n      title: 'You stopped the email',\n      detail: 'The draft stays in the outbox',\n    },\n  },\n  { type: 'run.finished', status: 'cancelled' }\n);\n\n/** A request that waits on a person is answered by the demonstration after this long. */\nconst DECIDE_AFTER_MS = 2500;\n\nfunction hasDecided(run: RunSnapshot) {\n  const pending = pendingApprovalsOf(run);\n  return pending.length === 0;\n}\n\nfunction isStopped(run: RunSnapshot) {\n  return run.status === 'cancelled';\n}\n\nconst SCRIPT: RunStep[] = [\n  batch(\n    400,\n    { type: 'run.started' },\n    { type: 'plan.set', steps: PLAN },\n    started('scope')\n  ),\n  batch(\n    900,\n    ended('scope', 'Worked out what the review needs'),\n    started('search')\n  ),\n  batch(\n    1000,\n    ended('search', 'Searched the web for Brightmoor prices'),\n    started('page')\n  ),\n  batch(600, PAGE_FAILED),\n  batch(200, started('page-again')),\n  batch(\n    800,\n    ended('page-again', 'Read the pricing page again'),\n    started('sheet')\n  ),\n  batch(\n    700,\n    ended('sheet', 'Read the Q3 invoices spreadsheet'),\n    started('compare')\n  ),\n  batch(\n    800,\n    ended('compare', 'Found six invoice lines above the list price'),\n    started('draft')\n  ),\n  batch(\n    1400,\n    ended('draft', 'Wrote the email to Brightmoor accounts'),\n    started('approve'),\n    { type: 'approval.requested', approval: SEND_APPROVAL }\n  ),\n  {\n    after: DECIDE_AFTER_MS,\n    by: 'person',\n    press: 'approve',\n    action: APPROVED,\n    isAnswered: hasDecided,\n  },\n  batch(300, started('send')),\n  batch(\n    600,\n    ended('send', 'Sent the email to Brightmoor accounts'),\n    started('summary')\n  ),\n  batch(1000, ended('summary', 'Wrote the summary for the finance team'), {\n    type: 'run.finished',\n    status: 'done',\n  }),\n];\n\n/** The run takes about eleven seconds with its approval, so every track fits in a window that never moves. */\nconst WINDOW_MS = 12_000;\n\nconst SESSION = {\n  reducer: reduceBatch,\n  initial: INITIAL_RUN,\n  resting: restingOf(INITIAL_RUN, SCRIPT, applyBatchAt),\n  script: SCRIPT,\n  loopAfter: 3000,\n  holdWhile: isStopped,\n};\n\nfunction sentencesOf(run: RunSnapshot): RunSentence[] {\n  const approval = run.approvals.find(\n    (request) => request.id === SEND_APPROVAL.id\n  );\n  return run.plan.map((step) => {\n    const kind = STEP_KINDS[step.id] ?? 'thinking';\n    if (step.id === 'approve') {\n      return { step, kind, approval };\n    }\n    return { step, kind };\n  });\n}\n\nfunction announcementOf(run: RunSnapshot) {\n  const pending = pendingApprovalsOf(run);\n  const [first] = pending;\n  if (first) {\n    return `Waiting on you: ${first.title}`;\n  }\n  if (run.status === 'done') {\n    return 'The run finished';\n  }\n  if (run.status === 'cancelled') {\n    return 'The run stopped before sending the email';\n  }\n  const running = run.plan.find((step) => step.status === 'running');\n  if (running) {\n    return running.title;\n  }\n  return '';\n}\n\nexport default function Run03() {\n  const { ref, isInView, isAutoplaying, state, act, pressed, restart } =\n    useSession(SESSION);\n  const isEnded = state.endedAt !== undefined;\n  const canReplay = isEnded && !isAutoplaying;\n  const sentences = sentencesOf(state);\n  const announcement = announcementOf(state);\n\n  function approve() {\n    act(APPROVED);\n  }\n\n  function deny() {\n    act(DENIED);\n  }\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[53.5rem] w-full max-w-[36rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <RunInSentences\n          title={state.title}\n          run={state}\n          sentences={sentences}\n          onApprove={approve}\n          onDeny={deny}\n          windowMs={WINDOW_MS}\n          isApprovePressed={pressed === 'approve'}\n        />\n      </ClockGate>\n      <div className='flex h-7 items-center justify-end'>\n        <ReplayButton isShown={canReplay} onReplay={restart} />\n      </div>\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/run/run-03.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/scenario.ts",
      "content": "import type { RunAgent } from '@/registry/ndeko/lib/agent-run';\n\nexport const RUN_TITLE = 'Quarterly vendor review for Brightmoor Supply';\n\nexport const PLANNER: RunAgent = {\n  id: 'planner',\n  name: 'Planner',\n  series: 1,\n  status: 'idle',\n  model: 'Claude Opus',\n  role: 'Lead',\n};\n\nexport const RESEARCHER: RunAgent = {\n  id: 'researcher',\n  name: 'Researcher',\n  series: 2,\n  status: 'idle',\n  model: 'Claude Sonnet',\n  parentId: 'planner',\n};\n\nexport const WRITER: RunAgent = {\n  id: 'writer',\n  name: 'Writer',\n  series: 3,\n  status: 'idle',\n  model: 'Claude Haiku',\n  parentId: 'planner',\n};\n\nexport const PRICING_URL = 'https://brightmoor-supply.example/pricing';\n\nexport const SEARCH_INPUT = {\n  query: 'Brightmoor Supply wholesale price list',\n  limit: 5,\n};\n\nexport const SEARCH_OUTPUT = {\n  results: 5,\n  top: PRICING_URL,\n};\n\nexport const PAGE_INPUT = {\n  url: PRICING_URL,\n  timeoutMs: 8000,\n};\n\nexport const PAGE_ERROR = '403 Forbidden: the site refused the reader';\n\nexport const PAGE_OUTPUT = {\n  title: 'Wholesale pricing',\n  tables: 3,\n  updated: '2026-10-02',\n};\n\nexport const SHEET_INPUT = {\n  file: 'q3-invoices.xlsx',\n  sheet: 'Brightmoor',\n  range: 'A1:F118',\n};\n\nexport const SHEET_OUTPUT = {\n  rows: 117,\n  total: 48210.5,\n  currency: 'USD',\n  flagged: false,\n};\n\nexport const SCRIPT_INPUT = {\n  script: 'compare_prices.py',\n  args: ['--quarter', 'Q3'],\n};\n\nexport const SCRIPT_OUTPUT = {\n  items: 42,\n  aboveList: 6,\n  overpaid: 1840.2,\n};\n\nexport const EMAIL_INPUT = {\n  to: 'accounts@brightmoor-supply.example',\n  subject: 'Q3 pricing review',\n};\n\nexport const EMAIL_OUTPUT = {\n  words: 186,\n  attachments: 1,\n};\n",
      "type": "registry:component",
      "target": "components/run/_parts/scenario.ts"
    }
  ],
  "categories": [
    "components",
    "run"
  ],
  "type": "registry:component"
}