{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-chat-01",
  "title": "Agent chat with its run",
  "description": "A conversation that thinks, reads its sources and streams, with the plan checking itself off beside it: when the agent needs a yes, the field you were typing in becomes the request and turns back once you answer.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/avatar.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/brand-logos.json",
    "https://ui.ndekocode.dev/r/brand-tile.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/drawn-check.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/inline-sheet.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/streamed-text.json",
    "https://ui.ndekocode.dev/r/theme.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/blocks/agent-chat/agent-chat-01/index.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useEffect, useRef, useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport {\n  pendingApprovalsOf,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { FeatherIcon, ListChecksIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { rowPresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { InlineSheet } from '@/registry/ndeko/ui/inline-sheet';\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 {\n  shownCountOf,\n  StreamedWords,\n  useRevealedCount,\n} from '@/registry/ndeko/ui/streamed-text';\n\nimport { Composer, type EmailPreview } from './composer';\nimport {\n  ANSWER,\n  CALL_BRAND,\n  CONVERSATION_TITLE,\n  DENIED_LINE,\n  EMAIL,\n  FOLLOW_UP_REPLY,\n  person,\n  PROMPT,\n  SENT_LINE,\n  SOURCES,\n} from './data';\nimport { doneStepsOf, RunPanel } from './run-panel';\nimport {\n  INITIAL,\n  isOver,\n  LOOP_AFTER_MS,\n  reducer,\n  RESTING,\n  SCRIPT,\n  type Decision,\n  type Phase,\n} from './session';\n\nconst ANSWER_WORDS = ANSWER.split(' ');\n\nconst WORD_MS = 48;\n\nconst PHASE_ORDER: Phase[] = [\n  'idle',\n  'thinking',\n  'reading',\n  'streaming',\n  'waiting',\n  'sending',\n  'done',\n  'stopped',\n];\n\nfunction hasReached(phase: Phase, target: Phase) {\n  const position = PHASE_ORDER.indexOf(phase);\n  const targetPosition = PHASE_ORDER.indexOf(target);\n  return position >= targetPosition;\n}\n\nfunction statusWordOf(phase: Phase) {\n  if (phase === 'thinking') {\n    return 'Thinking';\n  }\n  if (phase === 'reading') {\n    return 'Reading your sources';\n  }\n  if (phase === 'sending') {\n    return 'Sending the email';\n  }\n  return null;\n}\n\nfunction closingLineOf(phase: Phase) {\n  if (phase === 'done') {\n    return SENT_LINE;\n  }\n  if (phase === 'stopped') {\n    return DENIED_LINE;\n  }\n  return null;\n}\n\nfunction announcementOf(phase: Phase) {\n  if (phase === 'waiting') {\n    return 'The assistant asks to send an email. Allow or deny it.';\n  }\n  return closingLineOf(phase) ?? '';\n}\n\n/** Only this text re-renders while the answer streams. */\nfunction StreamedAnswer({\n  phase,\n  isActive,\n}: {\n  phase: Phase;\n  isActive: boolean;\n}) {\n  const isStreaming = phase === 'streaming';\n  const isRunning = isStreaming && isActive;\n  const total = ANSWER_WORDS.length;\n  const count = useRevealedCount(total, isRunning, WORD_MS);\n  const shown = shownCountOf(isStreaming, count, total);\n\n  return (\n    <p className='text-sm leading-relaxed'>\n      <StreamedWords words={ANSWER_WORDS} shown={shown} keepsPlace={false} />\n    </p>\n  );\n}\n\nfunction AssistantTile() {\n  return (\n    <span\n      aria-hidden='true'\n      className='gem-plate inline-flex size-7 shrink-0 items-center justify-center rounded-lg [--gem:var(--primary)]'\n    >\n      <FeatherIcon className='size-4' />\n    </span>\n  );\n}\n\nfunction StatusLine({ word }: { word: string }) {\n  return (\n    <p className='text-muted-foreground flex h-7 items-center gap-2 text-[13px]'>\n      <span\n        aria-hidden='true'\n        className='bg-primary size-1.5 animate-pulse rounded-full'\n      />\n      <Swap swapKey={word}>{word}</Swap>\n    </p>\n  );\n}\n\nfunction SourceTiles({ shown }: { shown: number }) {\n  const sources = SOURCES.slice(0, shown);\n\n  return (\n    <ul aria-label='Sources read' className='flex flex-wrap gap-1.5'>\n      {sources.map((source) => (\n        <li\n          key={source.id}\n          className='bg-foreground/[0.04] flex h-9 items-center gap-2 rounded-lg ps-1 pe-2.5 text-xs transition-[opacity,scale] duration-300 ease-(--ease-out-strong) starting:scale-90 starting:opacity-0'\n        >\n          <BrandTile brand={source.brand} size='lg' />\n          <span className='flex flex-col leading-tight'>\n            <span className='font-medium'>{source.title}</span>\n            <span className='text-muted-foreground'>{source.product}</span>\n          </span>\n        </li>\n      ))}\n    </ul>\n  );\n}\n\nfunction PersonMessage({ text }: { text: string }) {\n  return (\n    <div className='flex items-end justify-end gap-2'>\n      <p className='bg-foreground/[0.06] max-w-[85%] rounded-2xl rounded-ee-md px-3.5 py-2 text-sm leading-relaxed'>\n        {text}\n      </p>\n      <Avatar\n        className='hidden size-7 @md:inline-flex'\n        seed={person.name}\n        role='img'\n        aria-label={person.name}\n      />\n    </div>\n  );\n}\n\ntype RunSheetProps = {\n  isOpen: boolean;\n  onClose: () => void;\n  children: React.ReactNode;\n};\n\nfunction RunSheet({ isOpen, onClose, children }: RunSheetProps) {\n  return (\n    <InlineSheet\n      label='Run'\n      closeLabel='Close the run'\n      side='bottom'\n      closer='none'\n      isModal={false}\n      isOpen={isOpen}\n      className='z-10 @3xl:hidden'\n      panelClassName='max-h-[80%] gap-3 overflow-y-auto p-4'\n      onClose={onClose}\n    >\n      <div className='flex items-center justify-between'>\n        <h2 className='text-sm font-medium'>Run</h2>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Close the run'\n          onClick={onClose}\n          className='text-muted-foreground'\n        >\n          <XIcon />\n        </Button>\n      </div>\n      {children}\n    </InlineSheet>\n  );\n}\n\nexport type AgentChatProps = {\n  /** The run drawn beside the conversation: feed it from any backend that emits run events. */\n  run: RunSnapshot;\n  question: string | null;\n  phase: Phase;\n  sourcesShown: number;\n  followUps: string[];\n  draft: string;\n  email: EmailPreview;\n  pressed?: string | null;\n  /** False while the block is off screen: the answer stops streaming until it is back. */\n  isActive?: boolean;\n  header?: React.ReactNode;\n  onDraftChange: (text: string) => void;\n  onSend: (text: string) => void;\n  onDecide: (decision: Decision) => void;\n};\n\nexport function AgentChat({\n  run,\n  question,\n  phase,\n  sourcesShown,\n  followUps,\n  draft,\n  email,\n  pressed = null,\n  isActive = true,\n  header,\n  onDraftChange,\n  onSend,\n  onDecide,\n}: AgentChatProps) {\n  const [isSheetOpen, setIsSheetOpen] = useState(false);\n  const listRef = useRef<HTMLDivElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const [pendingApproval] = pendingApprovalsOf(run);\n  const approval = pendingApproval ?? null;\n  const hasAsked = question !== null;\n  const isRunning = hasAsked && !isOver(phase);\n  const canSend = !isRunning;\n  const statusWord = statusWordOf(phase);\n  const closingLine = closingLineOf(phase);\n  const showsAnswer = hasReached(phase, 'streaming');\n  const doneSteps = doneStepsOf(run);\n  const totalSteps = run.plan.length;\n  const followUpCount = followUps.length;\n\n  useEffect(() => {\n    const list = listRef.current;\n    if (list) {\n      list.scrollTop = list.scrollHeight;\n    }\n  }, [phase, sourcesShown, followUpCount]);\n\n  function send() {\n    onSend(draft);\n  }\n\n  function fillSuggestion() {\n    onDraftChange(PROMPT);\n  }\n\n  return (\n    <div className='mx-auto flex h-full max-w-6xl gap-3 p-3 @3xl:p-4'>\n      <section\n        aria-label='Conversation'\n        className='flex min-w-0 flex-1 flex-col gap-3'\n      >\n        <header className='flex h-9 shrink-0 items-center gap-2.5'>\n          <AssistantTile />\n          <div className='flex min-w-0 flex-1 flex-col leading-tight'>\n            <h2 className='truncate text-sm font-medium'>\n              {CONVERSATION_TITLE}\n            </h2>\n            <span className='text-muted-foreground text-xs'>Assistant</span>\n          </div>\n          {header}\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            aria-expanded={isSheetOpen}\n            onClick={() => setIsSheetOpen(true)}\n            className='@3xl:hidden'\n          >\n            <ListChecksIcon />\n            Run\n            <span className='text-muted-foreground tabular-nums'>\n              {doneSteps}/{totalSteps}\n            </span>\n          </Button>\n        </header>\n\n        <div\n          ref={listRef}\n          className='flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto py-2'\n        >\n          {!hasAsked && (\n            <div className='m-auto flex max-w-sm flex-col items-center gap-3 text-center'>\n              <p className='text-muted-foreground text-[13px]'>\n                Ask about your accounts. The assistant reads your tools and asks\n                before it sends anything.\n              </p>\n              <Button\n                type='button'\n                variant='outline'\n                onClick={fillSuggestion}\n                className='h-auto max-w-full rounded-xl px-3 py-2 text-start whitespace-normal'\n              >\n                {PROMPT}\n              </Button>\n            </div>\n          )}\n\n          {hasAsked && <PersonMessage text={question} />}\n\n          {hasAsked && (\n            <div className='flex items-start gap-2.5'>\n              <AssistantTile />\n              <div className='flex min-w-0 flex-1 flex-col gap-3'>\n                <AnimatePresence initial={false}>\n                  {statusWord && (\n                    <motion.div\n                      key='status'\n                      className='overflow-hidden'\n                      {...rowPresence}\n                    >\n                      <StatusLine word={statusWord} />\n                    </motion.div>\n                  )}\n                </AnimatePresence>\n                <SourceTiles shown={sourcesShown} />\n                {showsAnswer && (\n                  <StreamedAnswer phase={phase} isActive={isActive} />\n                )}\n                <AnimatePresence initial={false}>\n                  {closingLine && (\n                    <motion.p\n                      key='closing'\n                      className='overflow-hidden text-sm leading-relaxed'\n                      {...rowPresence}\n                    >\n                      {closingLine}\n                    </motion.p>\n                  )}\n                </AnimatePresence>\n              </div>\n            </div>\n          )}\n\n          {followUps.map((text, index) => (\n            <div key={index} className='flex flex-col gap-4'>\n              <PersonMessage text={text} />\n              <div className='flex items-start gap-2.5'>\n                <AssistantTile />\n                <p className='pt-1 text-sm leading-relaxed'>\n                  {FOLLOW_UP_REPLY}\n                </p>\n              </div>\n            </div>\n          ))}\n        </div>\n\n        <Composer\n          approval={approval}\n          email={email}\n          draft={draft}\n          placeholder='Ask about your accounts'\n          canSend={canSend}\n          pressed={pressed}\n          onDraftChange={onDraftChange}\n          onSend={send}\n          onDecide={onDecide}\n        />\n      </section>\n\n      <aside\n        aria-label='Run'\n        className='bg-card hairline-ring ring-border hidden w-80 shrink-0 overflow-y-auto rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)] @3xl:flex'\n      >\n        <RunPanel run={run} brands={CALL_BRAND} className='w-full' />\n      </aside>\n\n      <RunSheet isOpen={isSheetOpen} onClose={() => setIsSheetOpen(false)}>\n        <RunPanel run={run} brands={CALL_BRAND} />\n      </RunSheet>\n    </div>\n  );\n}\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n};\n\nexport default function AgentChat01() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const announcement = announcementOf(state.phase);\n  const message = spokenUnless(isAutoplaying, announcement);\n  const canReplay = isFinished && !isAutoplaying;\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container relative h-dvh min-h-[36rem] w-full overflow-hidden'\n      >\n        <AgentChat\n          run={state.run}\n          question={state.question}\n          phase={state.phase}\n          sourcesShown={state.sourcesShown}\n          followUps={state.followUps}\n          draft={state.draft}\n          email={EMAIL}\n          pressed={pressed}\n          isActive={isInView}\n          header={<ReplayButton isShown={canReplay} onReplay={restart} />}\n          onDraftChange={(text) => act({ type: 'typed', text })}\n          onSend={() => act({ type: 'sent' })}\n          onDecide={(decision) => act({ type: 'decided', decision })}\n        />\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-chat-01/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-chat/agent-chat-01/composer.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport type { ApprovalRequest } from '@/registry/ndeko/lib/agent-run';\nimport { pressedSolidOf } from '@/registry/ndeko/lib/demonstration';\nimport { ArrowUpIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport type { Decision } from './session';\n\nconst SHELL =\n  'bg-card hairline-ring ring-foreground/12 rounded-2xl shadow-[0_1px_2px_rgb(0_0_0/0.05)] dark:bg-foreground/[0.04] dark:ring-foreground/15';\n\nconst MORPH = {\n  initial: { opacity: 0, scale: 0.98, filter: 'blur(4px)' },\n  animate: { opacity: 1, scale: 1, filter: 'blur(0px)' },\n  exit: { opacity: 0, transition: { duration: 0.1 } },\n  transition: { duration: 0.22, ease: [0.23, 1, 0.32, 1] as const },\n};\n\nconst MORPH_FADE = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: { opacity: 0, transition: { duration: 0.1 } },\n  transition: { duration: 0.15 },\n};\n\nfunction morphOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return MORPH_FADE;\n  }\n  return MORPH;\n}\n\nfunction isSendKey(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n  const isPlainEnter = event.key === 'Enter' && !event.shiftKey;\n  return isPlainEnter && !event.nativeEvent.isComposing;\n}\n\nexport type EmailPreview = {\n  to: string;\n  subject: string;\n  body: string;\n};\n\ntype ApprovalCardProps = {\n  approval: ApprovalRequest;\n  email: EmailPreview;\n  pressed: string | null;\n  onDecide: (decision: Decision) => void;\n};\n\nfunction ApprovalCard({\n  approval,\n  email,\n  pressed,\n  onDecide,\n}: ApprovalCardProps) {\n  return (\n    <section\n      aria-label='Approval needed'\n      className={cn(SHELL, 'flex flex-col gap-3 p-3')}\n    >\n      <header className='flex items-center gap-2.5'>\n        <BrandTile brand='gmail' size='lg' />\n        <h3 className='min-w-0 flex-1 truncate text-sm font-medium'>\n          {approval.title}\n        </h3>\n        <Badge variant='warning'>Waiting on you</Badge>\n      </header>\n      <dl className='bg-foreground/[0.04] flex flex-col gap-1.5 rounded-lg p-3 text-[13px]'>\n        <div className='flex gap-2'>\n          <dt className='text-muted-foreground w-14 shrink-0'>To</dt>\n          <dd className='min-w-0 truncate'>{email.to}</dd>\n        </div>\n        <div className='flex gap-2'>\n          <dt className='text-muted-foreground w-14 shrink-0'>Subject</dt>\n          <dd className='min-w-0 truncate'>{email.subject}</dd>\n        </div>\n        <div className='flex gap-2'>\n          <dt className='text-muted-foreground w-14 shrink-0'>Message</dt>\n          <dd className='min-w-0'>{email.body}</dd>\n        </div>\n      </dl>\n      <div className='flex items-center justify-end gap-2'>\n        <Button\n          type='button'\n          variant='outline'\n          onClick={() => onDecide('denied')}\n        >\n          Deny\n        </Button>\n        <Button\n          type='button'\n          onClick={() => onDecide('approved')}\n          className={pressedSolidOf(pressed === 'allow')}\n        >\n          Allow and send\n        </Button>\n      </div>\n    </section>\n  );\n}\n\ntype FieldProps = {\n  draft: string;\n  placeholder: string;\n  canSend: boolean;\n  pressed: string | null;\n  onDraftChange: (text: string) => void;\n  onSend: () => void;\n};\n\nfunction Field({\n  draft,\n  placeholder,\n  canSend,\n  pressed,\n  onDraftChange,\n  onSend,\n}: FieldProps) {\n  function handleKeys(event: React.KeyboardEvent<HTMLTextAreaElement>) {\n    if (!isSendKey(event)) {\n      return;\n    }\n    event.preventDefault();\n    if (canSend) {\n      onSend();\n    }\n  }\n\n  return (\n    <div\n      className={cn(\n        SHELL,\n        'has-[textarea:focus-visible]:ring-ring/25 flex items-end gap-2 p-2 transition-[box-shadow] duration-150 has-[textarea:focus-visible]:ring-[3px]'\n      )}\n    >\n      <textarea\n        value={draft}\n        rows={2}\n        aria-label='Message to the assistant'\n        placeholder={placeholder}\n        onChange={(event) => onDraftChange(event.target.value)}\n        onKeyDown={handleKeys}\n        className='placeholder:text-muted-foreground/75 min-h-12 flex-1 resize-none bg-transparent px-1.5 py-1 text-base leading-normal outline-none md:text-[13px]'\n      />\n      <Button\n        type='button'\n        size='icon'\n        aria-label='Send the message'\n        disabled={!canSend}\n        onClick={onSend}\n        className={pressedSolidOf(pressed === 'send')}\n      >\n        <ArrowUpIcon />\n      </Button>\n    </div>\n  );\n}\n\ntype ComposerProps = FieldProps & {\n  /** While it is set, the field gives its place to the request. */\n  approval: ApprovalRequest | null;\n  email: EmailPreview;\n  onDecide: (decision: Decision) => void;\n};\n\n/** The request for a yes takes the place of the field, where the person was typing, and gives it back. */\nexport function Composer({\n  approval,\n  email,\n  onDecide,\n  ...field\n}: ComposerProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const morph = morphOf(shouldReduceMotion);\n\n  return (\n    <AnimatedSize>\n      <AnimatePresence mode='popLayout' initial={false}>\n        {approval && (\n          <motion.div key='approval' {...morph}>\n            <ApprovalCard\n              approval={approval}\n              email={email}\n              pressed={field.pressed}\n              onDecide={onDecide}\n            />\n          </motion.div>\n        )}\n        {!approval && (\n          <motion.div key='field' {...morph}>\n            <Field {...field} />\n          </motion.div>\n        )}\n      </AnimatePresence>\n    </AnimatedSize>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-chat-01/composer.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-chat/agent-chat-01/run-panel.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport type {\n  PlanStep,\n  RunSnapshot,\n  RunStatus,\n  StepStatus,\n  ToolCall,\n} from '@/registry/ndeko/lib/agent-run';\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\nimport { BlocksIcon, LoaderIcon, MinusIcon } from '@/registry/ndeko/lib/icons';\nimport { rowPresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { CallStatusMark } from '@/registry/ndeko/ui/call-status';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { DrawnCheck } from '@/registry/ndeko/ui/drawn-check';\nimport { LiveDuration } from '@/registry/ndeko/ui/live-duration';\n\nconst RUN_WORD: Record<RunStatus, string> = {\n  idle: 'Not started',\n  running: 'Running',\n  waiting: 'Waiting on you',\n  done: 'Done',\n  failed: 'Failed',\n  cancelled: 'Stopped',\n};\n\nconst COST_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 3,\n  maximumFractionDigits: 3,\n};\n\nfunction isLive(status: RunStatus) {\n  return status === 'running' || status === 'waiting';\n}\n\nfunction StepGlyph({ status }: { status: StepStatus }) {\n  if (status === 'done') {\n    return <DrawnCheck entrance='draw' />;\n  }\n  if (status === 'running') {\n    return <LoaderIcon className='text-primary-ink size-4 animate-spin' />;\n  }\n  if (status === 'skipped') {\n    return <MinusIcon className='text-muted-foreground size-4' />;\n  }\n  return (\n    <span className='hairline-ring ring-foreground/25 size-[14px] rounded-full' />\n  );\n}\n\nconst STEP_WORD: Record<StepStatus, string> = {\n  upcoming: 'Upcoming',\n  running: 'Running',\n  done: 'Done',\n  failed: 'Failed',\n  skipped: 'Skipped',\n};\n\nfunction stepTextOf(status: StepStatus) {\n  if (status === 'upcoming') {\n    return 'text-muted-foreground';\n  }\n  if (status === 'skipped') {\n    return 'text-muted-foreground line-through';\n  }\n  return 'text-foreground';\n}\n\nfunction PlanRow({ step }: { step: PlanStep }) {\n  return (\n    <li className='flex h-8 items-center gap-2.5 text-[13px]'>\n      <span className='flex size-[18px] shrink-0 items-center justify-center'>\n        <Swap swapKey={step.status}>\n          <StepGlyph status={step.status} />\n        </Swap>\n        <span className='sr-only'>{STEP_WORD[step.status]}</span>\n      </span>\n      <span\n        className={cn(\n          'min-w-0 flex-1 truncate transition-colors duration-200',\n          stepTextOf(step.status)\n        )}\n      >\n        {step.title}\n      </span>\n    </li>\n  );\n}\n\nfunction CallTile({ brand }: { brand: BrandSlug | undefined }) {\n  if (brand) {\n    return <BrandTile brand={brand} size='lg' />;\n  }\n  return (\n    <span className='keycap-3d text-muted-foreground inline-flex size-7 shrink-0 items-center justify-center rounded-md'>\n      <BlocksIcon className='size-3.5' />\n    </span>\n  );\n}\n\nfunction CallRow({\n  call,\n  brand,\n}: {\n  call: ToolCall;\n  brand: BrandSlug | undefined;\n}) {\n  const isRunning = call.status === 'running';\n\n  return (\n    <div className='flex h-10 items-center gap-2.5 text-[13px]'>\n      <CallTile brand={brand} />\n      <span className='min-w-0 flex-1 truncate'>{call.label}</span>\n      <LiveDuration\n        item={call}\n        isRunning={isRunning}\n        className='text-muted-foreground w-10 shrink-0 text-end text-xs'\n      />\n      <CallStatusMark status={call.status} />\n    </div>\n  );\n}\n\nexport function doneStepsOf(run: RunSnapshot) {\n  const done = run.plan.filter((step) => step.status === 'done');\n  return done.length;\n}\n\ntype RunPanelProps = {\n  run: RunSnapshot;\n  /** The mark of the product behind each tool, by tool name. */\n  brands?: Record<string, BrandSlug>;\n  className?: string;\n};\n\nexport function RunPanel({ run, brands = {}, className }: RunPanelProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const hasStarted = run.status !== 'idle';\n  const hasCalls = run.calls.length > 0;\n\n  return (\n    <div className={cn('flex flex-col gap-5', className)}>\n      <div className='flex items-end justify-between gap-3'>\n        <div className='flex flex-col gap-1'>\n          <span className='text-muted-foreground text-xs'>Cost so far</span>\n          <MotionNumber\n            value={run.usage.costUsd}\n            format={COST_FORMAT}\n            className='text-2xl leading-none font-semibold'\n          />\n        </div>\n        <div className='flex flex-col items-end gap-1 text-xs'>\n          <Swap swapKey={run.status} className='font-medium'>\n            {RUN_WORD[run.status]}\n          </Swap>\n          <LiveDuration\n            item={run}\n            isRunning={isLive(run.status)}\n            className='text-muted-foreground w-12 text-end'\n          />\n        </div>\n      </div>\n\n      {!hasStarted && (\n        <p className='text-muted-foreground bg-foreground/[0.04] rounded-lg p-3 text-[13px]'>\n          The plan, each tool call and the cost show up here once you send.\n        </p>\n      )}\n\n      {hasStarted && (\n        <section aria-label='Plan' className='flex flex-col gap-1'>\n          <h3 className='text-muted-foreground text-xs'>Plan</h3>\n          <ol className='flex flex-col'>\n            {run.plan.map((step) => (\n              <PlanRow key={step.id} step={step} />\n            ))}\n          </ol>\n        </section>\n      )}\n\n      {hasCalls && (\n        <section aria-label='Tool calls' className='flex flex-col gap-1'>\n          <h3 className='text-muted-foreground text-xs'>Tool calls</h3>\n          <ul className='flex flex-col'>\n            <AnimatePresence initial={false}>\n              {run.calls.map((call) => (\n                <motion.li\n                  key={call.id}\n                  className='overflow-hidden'\n                  {...rowPresence}\n                >\n                  <CallRow call={call} brand={brands[call.tool]} />\n                </motion.li>\n              ))}\n            </AnimatePresence>\n          </ul>\n        </section>\n      )}\n\n      <p className='text-muted-foreground mt-auto text-xs'>\n        Illustrative costs and durations\n      </p>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/agent-chat-01/run-panel.tsx"
    },
    {
      "path": "registry/ndeko/blocks/agent-chat/agent-chat-01/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport {\n  emptyRun,\n  reduceRun,\n  type RunEvent,\n  type RunSnapshot,\n} from '@/registry/ndeko/lib/agent-run';\n\nimport { PLAN, PROMPT, SEND_APPROVAL } from './data';\n\nexport type Phase =\n  | 'idle'\n  | 'thinking'\n  | 'reading'\n  | 'streaming'\n  | 'waiting'\n  | 'sending'\n  | 'done'\n  | 'stopped';\n\nexport type Decision = 'approved' | 'denied';\n\nexport type ChatState = {\n  draft: string;\n  question: string | null;\n  phase: Phase;\n  sourcesShown: number;\n  run: RunSnapshot;\n  decision: Decision | null;\n  followUps: string[];\n};\n\nexport type ChatAction =\n  | { type: 'typed'; text: string }\n  | { type: 'sent' }\n  | { type: 'phase'; phase: Phase }\n  | { type: 'source' }\n  | { type: 'run'; event: RunEvent }\n  | { type: 'decided'; decision: Decision }\n  | { type: 'afterDecision' }\n  | { type: 'finished' }\n  | { type: 'batch'; actions: ChatAction[] };\n\ntype Step = SessionStep<ChatState, ChatAction>;\n\nexport const INITIAL: ChatState = {\n  draft: '',\n  question: null,\n  phase: 'idle',\n  sourcesShown: 0,\n  run: emptyRun({ id: 'renewals', title: 'Renewals at risk' }),\n  decision: null,\n  followUps: [],\n};\n\nexport function isOver(phase: Phase) {\n  return phase === 'done' || phase === 'stopped';\n}\n\nfunction questionOf(draft: string) {\n  const trimmed = draft.trim();\n  if (trimmed === '') {\n    return PROMPT;\n  }\n  return trimmed;\n}\n\nfunction sent(state: ChatState): ChatState {\n  const isFirst = state.question === null;\n  if (isFirst) {\n    const question = questionOf(state.draft);\n    return { ...state, draft: '', question, phase: 'thinking' };\n  }\n  const text = state.draft.trim();\n  const canFollowUp = isOver(state.phase) && text !== '';\n  if (!canFollowUp) {\n    return state;\n  }\n  return { ...state, draft: '', followUps: [...state.followUps, text] };\n}\n\nfunction decided(state: ChatState, decision: Decision, now: number): ChatState {\n  if (state.phase !== 'waiting') {\n    return state;\n  }\n  const resolved = reduceRun(\n    state.run,\n    { type: 'approval.resolved', id: SEND_APPROVAL.id, decision },\n    now\n  );\n  if (decision === 'approved') {\n    return { ...state, decision, run: resolved, phase: 'sending' };\n  }\n  const skipped = reduceRun(\n    resolved,\n    { type: 'step.updated', id: 'send', patch: { status: 'skipped' } },\n    now\n  );\n  const cancelled = reduceRun(\n    skipped,\n    { type: 'run.finished', status: 'cancelled' },\n    now\n  );\n  return { ...state, decision, run: cancelled, phase: 'stopped' };\n}\n\nfunction afterDecision(state: ChatState, now: number): ChatState {\n  if (state.phase !== 'sending') {\n    return state;\n  }\n  const running = reduceRun(\n    state.run,\n    { type: 'step.updated', id: 'send', patch: { status: 'running' } },\n    now\n  );\n  const run = reduceRun(\n    running,\n    {\n      type: 'call.started',\n      call: {\n        id: 'c4',\n        tool: 'send_email',\n        label: 'Send to Ines Okafor',\n        status: 'running',\n      },\n    },\n    now\n  );\n  return { ...state, run };\n}\n\nfunction finished(state: ChatState, now: number): ChatState {\n  if (state.phase !== 'sending') {\n    return state;\n  }\n  const events: RunEvent[] = [\n    { type: 'call.updated', id: 'c4', patch: { status: 'done' } },\n    { type: 'step.updated', id: 'send', patch: { status: 'done' } },\n    { type: 'usage.added', costUsd: 0.004 },\n    { type: 'run.finished', status: 'done' },\n  ];\n  let run = state.run;\n  for (const event of events) {\n    run = reduceRun(run, event, now);\n  }\n  return { ...state, run, phase: 'done' };\n}\n\nexport function applyAt(\n  state: ChatState,\n  action: ChatAction,\n  now: number\n): ChatState {\n  switch (action.type) {\n    case 'typed':\n      return { ...state, draft: action.text };\n    case 'sent':\n      return sent(state);\n    case 'phase':\n      return { ...state, phase: action.phase };\n    case 'source':\n      return { ...state, sourcesShown: state.sourcesShown + 1 };\n    case 'run':\n      return { ...state, run: reduceRun(state.run, action.event, now) };\n    case 'decided':\n      return decided(state, action.decision, now);\n    case 'afterDecision':\n      return afterDecision(state, now);\n    case 'finished':\n      return finished(state, now);\n    case 'batch': {\n      let next = state;\n      for (const inner of action.actions) {\n        next = applyAt(next, inner, now);\n      }\n      return next;\n    }\n  }\n}\n\nexport function reducer(state: ChatState, action: ChatAction) {\n  return applyAt(state, action, Date.now());\n}\n\nfunction ran(event: RunEvent): ChatAction {\n  return { type: 'run', event };\n}\n\nfunction frame(after: number, actions: ChatAction[]): Step {\n  return { after, action: { type: 'batch', actions } };\n}\n\nfunction stepStatus(id: string, status: 'running' | 'done'): ChatAction {\n  return ran({ type: 'step.updated', id, patch: { status } });\n}\n\nfunction callStarted(id: string, tool: string, label: string): ChatAction {\n  return ran({\n    type: 'call.started',\n    call: { id, tool, label, status: 'running' },\n  });\n}\n\nfunction callDone(id: string, costUsd: number): ChatAction[] {\n  return [\n    ran({ type: 'call.updated', id, patch: { status: 'done' } }),\n    ran({ type: 'usage.added', costUsd }),\n    { type: 'source' },\n  ];\n}\n\nconst CHUNK = 3;\n\nfunction delayOfChunk(index: number) {\n  if (index === 0) {\n    return 1100;\n  }\n  return 70;\n}\n\nfunction typingSteps(): Step[] {\n  const steps: Step[] = [];\n  const last = PROMPT.length + CHUNK;\n  for (let end = CHUNK; end < last; end += CHUNK) {\n    const text = PROMPT.slice(0, end);\n    const after = delayOfChunk(steps.length);\n    steps.push({ after, by: 'demo', action: { type: 'typed', text } });\n  }\n  return steps;\n}\n\nfunction hasSent(state: ChatState) {\n  return state.question !== null;\n}\n\nfunction hasDecided(state: ChatState) {\n  return state.decision !== null;\n}\n\n/** A request that waits on a person is answered by the demonstration after this long. */\nconst DECIDE_AFTER_MS = 2500;\n\nexport const SCRIPT: Step[] = [\n  ...typingSteps(),\n  {\n    after: 500,\n    by: 'person',\n    press: 'send',\n    action: { type: 'sent' },\n    isAnswered: hasSent,\n  },\n  frame(400, [\n    ran({ type: 'run.started' }),\n    ran({ type: 'plan.set', steps: PLAN }),\n    stepStatus('read', 'running'),\n  ]),\n  frame(500, [\n    { type: 'phase', phase: 'reading' },\n    callStarted('c1', 'read_sheet', 'Read Renewals Q3'),\n  ]),\n  frame(1000, [\n    ...callDone('c1', 0.006),\n    stepStatus('read', 'done'),\n    stepStatus('find', 'running'),\n    callStarted('c2', 'search_pages', 'Search the renewal playbook'),\n  ]),\n  frame(900, [\n    ...callDone('c2', 0.004),\n    callStarted('c3', 'get_account', 'Open Meridian Foods'),\n  ]),\n  frame(1000, [\n    ...callDone('c3', 0.005),\n    stepStatus('find', 'done'),\n    stepStatus('draft', 'running'),\n  ]),\n  frame(300, [{ type: 'phase', phase: 'streaming' }]),\n  frame(2600, [\n    stepStatus('draft', 'done'),\n    ran({ type: 'usage.added', costUsd: 0.018 }),\n    ran({ type: 'approval.requested', approval: SEND_APPROVAL }),\n    { type: 'phase', phase: 'waiting' },\n  ]),\n  {\n    after: DECIDE_AFTER_MS,\n    by: 'person',\n    press: 'allow',\n    action: { type: 'decided', decision: 'approved' },\n    isAnswered: hasDecided,\n  },\n  { after: 250, action: { type: 'afterDecision' } },\n  { after: 1300, action: { type: 'finished' } },\n];\n\nfunction restingOf() {\n  let state = INITIAL;\n  let now = 1000;\n  for (const step of SCRIPT) {\n    now += step.after;\n    state = applyAt(state, step.action, now);\n  }\n  return state;\n}\n\nexport const RESTING = restingOf();\n\nexport const LOOP_AFTER_MS = 3600;\n",
      "type": "registry:component",
      "target": "components/blocks/agent-chat-01/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/agent-chat/agent-chat-01/data.ts",
      "content": "import type { ApprovalRequest, PlanStep } from '@/registry/ndeko/lib/agent-run';\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\n\nexport const PROMPT =\n  'Which accounts are at risk this quarter? Email the owner of the biggest one.';\n\nexport const CONVERSATION_TITLE = 'Renewals at risk';\n\nexport const person = {\n  name: 'Lena Brandt',\n};\n\nexport type Source = {\n  id: string;\n  brand: BrandSlug;\n  product: string;\n  title: string;\n};\n\nexport const SOURCES: Source[] = [\n  {\n    id: 'sheet',\n    brand: 'googledrive',\n    product: 'Google Drive',\n    title: 'Renewals Q3',\n  },\n  {\n    id: 'playbook',\n    brand: 'notion',\n    product: 'Notion',\n    title: 'Renewal playbook',\n  },\n  {\n    id: 'account',\n    brand: 'hubspot',\n    product: 'HubSpot',\n    title: 'Meridian Foods',\n  },\n];\n\nexport const ANSWER =\n  'Three accounts are at risk this quarter. Meridian Foods is the biggest: fewer of its people sign in each week since June and its renewal is due on 28 September. Tallis Freight and Okapi Studio follow, both with support tickets left unanswered. I drafted a check-in for Ines Okafor, who owns the Meridian Foods account.';\n\nexport const SENT_LINE =\n  'Sent to Ines. Her reply will show up in this conversation.';\n\nexport const DENIED_LINE =\n  'Nothing was sent. The draft stays in Gmail if you want it later.';\n\nexport const FOLLOW_UP_REPLY =\n  'This demonstration plays one scripted run. Replay it to watch it again.';\n\nexport const PLAN: PlanStep[] = [\n  { id: 'read', title: 'Read the renewals sheet', status: 'upcoming' },\n  { id: 'find', title: 'Find the accounts at risk', status: 'upcoming' },\n  { id: 'draft', title: 'Draft the check-in email', status: 'upcoming' },\n  { id: 'send', title: 'Send it to the owner', status: 'upcoming' },\n];\n\nexport const CALL_BRAND: Record<string, BrandSlug> = {\n  read_sheet: 'googledrive',\n  search_pages: 'notion',\n  get_account: 'hubspot',\n  send_email: 'gmail',\n};\n\nexport const EMAIL = {\n  to: 'ines.okafor@meridianfoods.example',\n  subject: 'A quick check-in before your renewal',\n  body: 'Hi Ines, fewer people on your team have signed in lately. Could we find 20 minutes this week to see what would help?',\n};\n\nexport const SEND_APPROVAL: ApprovalRequest = {\n  id: 'send-email',\n  title: 'Send this email from your Gmail',\n  risk: 'medium',\n  status: 'pending',\n  detail: EMAIL.subject,\n};\n",
      "type": "registry:component",
      "target": "components/blocks/agent-chat-01/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "agent-chat"
  ],
  "type": "registry:block"
}