{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-10",
  "title": "Agent health",
  "description": "One agent's health: a gauge and five signals whose marks change in a wave between periods, a summary written a few words at a time and one action to apply.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/animated-size.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/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/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/status-orb.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.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-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/run/run-10.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { memo, useEffect, useId, useState } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { seriesColorOf, type RunAgent } from '@/registry/ndeko/lib/agent-run';\nimport {\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  pressedSolidOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowUpIcon,\n  CircleXIcon,\n  FeatherIcon,\n  LightbulbIcon,\n  RotateCcwIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { wordsOf } from '@/registry/ndeko/lib/words';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\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 { StatusOrb } from '@/registry/ndeko/ui/status-orb';\n\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport {\n  EASE_OUT_STRONG,\n  INSTANT,\n  rowPresenceOf,\n} from '@/registry/ndeko/lib/motion-presets';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\n\nexport type HealthSignal = {\n  id: string;\n  label: string;\n  value: number;\n  format: Intl.NumberFormatOptions;\n  suffix?: string;\n  /** The range this signal should stay in, in words: \"95% or more\". */\n  target: string;\n  /** Same count of points in every period, so the line morphs from one to the next. */\n  points: number[];\n  isOutOfRange: boolean;\n};\n\nexport type HealthReport = {\n  score: number;\n  change: number;\n  changeLabel: string;\n  signals: HealthSignal[];\n};\n\nexport type SummaryStatus =\n  'idle' | 'thinking' | 'streaming' | 'done' | 'stopped';\n\nexport type ActionStatus = 'idle' | 'pending' | 'failed' | 'done';\n\nexport type HealthAction = {\n  title: string;\n  reason: string;\n  doneLine: string;\n  errorLine: string;\n};\n\nconst GAUGE_WIDTH = 120;\n\nconst GAUGE_HEIGHT = 66;\n\nconst GAUGE_ARC = 'M 12 60 A 48 48 0 0 1 108 60';\n\nconst SPARK_WIDTH = 72;\n\nconst SPARK_HEIGHT = 24;\n\nconst SPARK_PADDING = 2;\n\nconst PATH_MORPH = { duration: 0.45, ease: EASE_OUT_STRONG };\n\nfunction gaugeToneOf(score: number) {\n  if (score >= 80) {\n    return 'stroke-success';\n  }\n  if (score >= 60) {\n    return 'stroke-warning';\n  }\n  return 'stroke-destructive';\n}\n\nfunction changeToneOf(change: number) {\n  if (change < 0) {\n    return 'text-destructive-ink';\n  }\n  return 'text-success-foreground';\n}\n\nfunction changeTurnOf(change: number) {\n  if (change < 0) {\n    return 'rotate-180';\n  }\n  return 'rotate-0';\n}\n\nfunction signedChangeOf(change: number) {\n  const magnitude = Math.abs(change);\n  if (change < 0) {\n    return `down ${magnitude}`;\n  }\n  return `up ${magnitude}`;\n}\n\nconst HealthGauge = memo(function HealthGauge({\n  report,\n}: {\n  report: HealthReport;\n}) {\n  const dashOffset = 100 - report.score;\n  const spokenChange = signedChangeOf(report.change);\n  const spoken = `Health ${report.score} out of 100, ${spokenChange} ${report.changeLabel}`;\n  const magnitude = Math.abs(report.change);\n\n  return (\n    <div\n      role='meter'\n      aria-label='Agent health'\n      aria-valuemin={0}\n      aria-valuemax={100}\n      aria-valuenow={report.score}\n      aria-valuetext={spoken}\n      className='relative mx-auto w-44'\n    >\n      <svg\n        aria-hidden='true'\n        viewBox={`0 0 ${GAUGE_WIDTH} ${GAUGE_HEIGHT}`}\n        className='w-full'\n      >\n        <path\n          d={GAUGE_ARC}\n          pathLength={100}\n          fill='none'\n          strokeWidth={8}\n          strokeLinecap='round'\n          className='stroke-foreground/[0.07]'\n        />\n        <path\n          d={GAUGE_ARC}\n          pathLength={100}\n          fill='none'\n          strokeWidth={8}\n          strokeLinecap='round'\n          strokeDasharray='100 100'\n          strokeDashoffset={dashOffset}\n          className={cn(\n            'transition-[stroke-dashoffset,stroke] duration-500 ease-(--ease-out-strong)',\n            gaugeToneOf(report.score)\n          )}\n        />\n      </svg>\n      <div className='absolute inset-x-0 bottom-0 flex flex-col items-center'>\n        <MotionNumber value={report.score} className='text-3xl font-semibold' />\n        <span\n          className={cn(\n            'flex items-center gap-1 text-xs transition-colors duration-200',\n            changeToneOf(report.change)\n          )}\n        >\n          <ArrowUpIcon\n            className={cn(\n              'size-3 transition-transform duration-300 ease-(--ease-out-strong)',\n              changeTurnOf(report.change)\n            )}\n          />\n          <MotionNumber value={magnitude} />\n          <span className='text-muted-foreground'>{report.changeLabel}</span>\n        </span>\n      </div>\n    </div>\n  );\n});\n\nconst SPARK_INNER_HEIGHT = SPARK_HEIGHT - SPARK_PADDING * 2;\n\nfunction pathCommandOf(index: number) {\n  if (index === 0) {\n    return 'M';\n  }\n  return 'L';\n}\n\n/** Each line is scaled to its own period, so the shape reads even when the values sit close together. */\nfunction sparkPathOf(points: number[]) {\n  let min = Infinity;\n  let max = -Infinity;\n  for (const point of points) {\n    min = Math.min(min, point);\n    max = Math.max(max, point);\n  }\n  const spread = max - min;\n  const range = Math.max(spread, 0.0001);\n  const gaps = Math.max(points.length - 1, 1);\n  const step = SPARK_WIDTH / gaps;\n  const commands: string[] = [];\n  for (let index = 0; index < points.length; index += 1) {\n    const x = index * step;\n    const share = (points[index] - min) / range;\n    const drop = SPARK_INNER_HEIGHT * (1 - share);\n    const y = SPARK_PADDING + drop;\n    const command = pathCommandOf(index);\n    commands.push(`${command} ${x.toFixed(1)} ${y.toFixed(1)}`);\n  }\n  return commands.join(' ');\n}\n\nfunction sparkToneOf(isOutOfRange: boolean) {\n  if (isOutOfRange) {\n    return 'stroke-warning';\n  }\n  return 'stroke-muted-foreground';\n}\n\nfunction Sparkline({ signal }: { signal: HealthSignal }) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const path = sparkPathOf(signal.points);\n  const transition = morphOf(shouldReduceMotion);\n\n  return (\n    <svg\n      aria-hidden='true'\n      width={SPARK_WIDTH}\n      height={SPARK_HEIGHT}\n      viewBox={`0 0 ${SPARK_WIDTH} ${SPARK_HEIGHT}`}\n      className='shrink-0 overflow-visible'\n    >\n      <motion.path\n        initial={false}\n        animate={{ d: path }}\n        transition={transition}\n        fill='none'\n        strokeWidth={1.5}\n        strokeLinecap='round'\n        strokeLinejoin='round'\n        className={cn(\n          'transition-[stroke] duration-200',\n          sparkToneOf(signal.isOutOfRange)\n        )}\n      />\n    </svg>\n  );\n}\n\nfunction morphOf(shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return INSTANT;\n  }\n  return PATH_MORPH;\n}\n\n/** The signals answer a change of period one after the other, this long apart. */\nconst WAVE_MS = 70;\n\nfunction waveDelayOf(index: number, shouldReduceMotion: boolean | null) {\n  if (shouldReduceMotion) {\n    return 0;\n  }\n  return index * WAVE_MS;\n}\n\n/** A value that follows another one after a delay, so the rows of a list answer a change as a wave. */\nfunction useLagged<Value>(value: Value, delayMs: number) {\n  const [shown, setShown] = useState(value);\n\n  useEffect(() => {\n    const timer = setTimeout(() => setShown(value), delayMs);\n    return () => clearTimeout(timer);\n  }, [value, delayMs]);\n\n  return shown;\n}\n\ntype SignalRowProps = {\n  signal: HealthSignal;\n  /** The place of the row in the list: the wave reaches it that many beats late. */\n  index: number;\n};\n\nconst SignalRow = memo(function SignalRow({\n  signal: latest,\n  index,\n}: SignalRowProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const delay = waveDelayOf(index, shouldReduceMotion);\n  const signal = useLagged(latest, delay);\n  const statusKey = String(signal.isOutOfRange);\n\n  return (\n    <li className='flex items-center gap-3 py-1.5'>\n      <div className='min-w-0 flex-1'>\n        <p className='text-muted-foreground truncate text-xs'>{signal.label}</p>\n        <MotionNumber\n          value={signal.value}\n          format={signal.format}\n          suffix={signal.suffix}\n          className='text-[13px] font-medium'\n        />\n      </div>\n      <Sparkline signal={signal} />\n      <span className='flex size-6 shrink-0 items-center justify-center'>\n        <Swap swapKey={statusKey}>\n          {signal.isOutOfRange && <StatusOrb tone='warning' size='sm' />}\n          {!signal.isOutOfRange && (\n            <span className='bg-foreground/15 size-1.5 rounded-full' />\n          )}\n        </Swap>\n      </span>\n      <span className='sr-only'>\n        {signalStatusWordOf(signal)}, target {signal.target}\n      </span>\n    </li>\n  );\n});\n\nfunction signalStatusWordOf(signal: HealthSignal) {\n  if (signal.isOutOfRange) {\n    return 'out of range';\n  }\n  return 'in range';\n}\n\n/**\n * While it is written the summary already holds its whole text, each word hidden until its turn:\n * the panel takes its size once and no line pushes the next one down.\n */\nfunction laidOutWordsOf(status: SummaryStatus, words: string[], shown: number) {\n  if (status === 'streaming') {\n    return words;\n  }\n  return words.slice(0, shown);\n}\n\nfunction wordRevealOf(isShown: boolean) {\n  if (isShown) {\n    return 'opacity-100';\n  }\n  return 'opacity-0';\n}\n\nfunction hiddenUnless(isShown: boolean) {\n  if (isShown) {\n    return undefined;\n  }\n  return true;\n}\n\ntype SummaryProps = {\n  status: SummaryStatus;\n  text: string;\n  shownWords: number;\n  isGeneratePressed: boolean;\n  onGenerate?: () => void;\n  onStop?: () => void;\n};\n\nfunction SummaryPanel({\n  status,\n  text,\n  shownWords,\n  isGeneratePressed,\n  onGenerate,\n  onStop,\n}: SummaryProps) {\n  const words = wordsOf(text);\n  const laidOutWords = laidOutWordsOf(status, words, shownWords);\n  const isIdle = status === 'idle';\n  const isThinking = status === 'thinking';\n  const isStreaming = status === 'streaming';\n  const isStopped = status === 'stopped';\n  const isDone = status === 'done';\n  const hasWords = laidOutWords.length > 0;\n  const canRetry = isStopped || isDone;\n\n  return (\n    <div className='bg-foreground/[0.03] flex flex-col gap-2 rounded-lg p-3'>\n      <div className='flex min-h-7 items-center justify-between gap-2'>\n        <span className='text-xs font-medium'>Summary</span>\n        <Swap swapKey={status}>\n          {isStreaming && (\n            <Button type='button' variant='ghost' size='sm' onClick={onStop}>\n              <span className='bg-foreground size-2 rounded-[2px]' />\n              Stop\n            </Button>\n          )}\n          {canRetry && (\n            <Button\n              type='button'\n              variant='ghost'\n              size='sm'\n              onClick={onGenerate}\n              className='text-muted-foreground'\n            >\n              <RotateCcwIcon />\n              Write again\n            </Button>\n          )}\n        </Swap>\n      </div>\n      <AnimatedSize>\n        {isIdle && (\n          <div className='flex flex-col items-start gap-2'>\n            <p className='text-muted-foreground text-xs leading-5'>\n              A short reading of the five signals for this period.\n            </p>\n            <Button\n              type='button'\n              variant='outline'\n              size='sm'\n              onClick={onGenerate}\n              className={pressedQuietOf(isGeneratePressed)}\n            >\n              <FeatherIcon />\n              Generate summary\n            </Button>\n          </div>\n        )}\n        {isThinking && (\n          <p className='text-muted-foreground animate-pulse text-[13px] motion-reduce:animate-none'>\n            Reading the signals\n          </p>\n        )}\n        {hasWords && (\n          <p className='text-[13px] leading-5'>\n            {laidOutWords.map((word, index) => {\n              const isShown = index < shownWords;\n              return (\n                <span\n                  key={index}\n                  aria-hidden={hiddenUnless(isShown)}\n                  className={cn(\n                    'transition-opacity duration-200',\n                    wordRevealOf(isShown)\n                  )}\n                >\n                  {word}{' '}\n                </span>\n              );\n            })}\n          </p>\n        )}\n        {isStopped && (\n          <p className='text-muted-foreground mt-1 text-xs'>\n            Stopped before the end\n          </p>\n        )}\n      </AnimatedSize>\n    </div>\n  );\n}\n\nfunction applyStateOf(status: ActionStatus): MorphState {\n  if (status === 'pending') {\n    return 'busy';\n  }\n  if (status === 'done') {\n    return 'done';\n  }\n  return 'idle';\n}\n\nfunction applyLabelsOf(status: ActionStatus): Record<MorphState, string> {\n  if (status === 'failed') {\n    return { idle: 'Retry', busy: 'Applying', done: 'Applied' };\n  }\n  return { idle: 'Apply', busy: 'Applying', done: 'Applied' };\n}\n\nfunction ActionCard({\n  action,\n  status,\n  isApplyPressed,\n  onApply,\n}: {\n  action: HealthAction;\n  status: ActionStatus;\n  isApplyPressed: boolean;\n  onApply?: () => void;\n}) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const isFailed = status === 'failed';\n  const isDone = status === 'done';\n\n  return (\n    <div className='bg-foreground/[0.03] flex flex-col rounded-lg p-3'>\n      <div className='flex items-start gap-3'>\n        <span className='keycap-3d text-muted-foreground flex size-7 shrink-0 items-center justify-center rounded-md'>\n          <LightbulbIcon className='size-3.5' />\n        </span>\n        <div className='min-w-0 flex-1'>\n          <p className='text-[13px] font-medium text-balance'>{action.title}</p>\n          <p className='text-muted-foreground mt-0.5 text-xs leading-5'>\n            {action.reason}\n          </p>\n        </div>\n        <MorphButton\n          type='button'\n          size='sm'\n          state={applyStateOf(status)}\n          labels={applyLabelsOf(status)}\n          onClick={onApply}\n          className={pressedSolidOf(isApplyPressed)}\n        />\n      </div>\n      <AnimatePresence initial={false}>\n        {isFailed && (\n          <motion.p\n            key='failed'\n            className='text-destructive-ink overflow-hidden text-xs'\n            {...rowPresence}\n          >\n            <span className='flex items-center gap-1.5 ps-10 pt-2'>\n              <CircleXIcon className='size-3.5 shrink-0' />\n              {action.errorLine}\n            </span>\n          </motion.p>\n        )}\n        {isDone && (\n          <motion.p\n            key='done'\n            className='text-muted-foreground overflow-hidden text-xs'\n            {...rowPresence}\n          >\n            <span className='block ps-10 pt-2'>{action.doneLine}</span>\n          </motion.p>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nexport type AgentHealthProps = {\n  agent: Pick<RunAgent, 'name' | 'series' | 'model'>;\n  report: HealthReport;\n  periodSwitch?: React.ReactNode;\n  summary: { status: SummaryStatus; text: string; shownWords: number };\n  onGenerateSummary?: () => void;\n  onStopSummary?: () => void;\n  action: HealthAction;\n  actionStatus: ActionStatus;\n  onApplyAction?: () => void;\n  /** Show Generate summary or Apply held down, for a demonstration that presses them. */\n  isGeneratePressed?: boolean;\n  isApplyPressed?: boolean;\n  className?: string;\n};\n\nexport function AgentHealth({\n  agent,\n  report,\n  periodSwitch,\n  summary,\n  onGenerateSummary,\n  onStopSummary,\n  action,\n  actionStatus,\n  onApplyAction,\n  isGeneratePressed = false,\n  isApplyPressed = false,\n  className,\n}: AgentHealthProps) {\n  const titleId = useId();\n  const chipColor = seriesColorOf(agent.series);\n\n  return (\n    <section\n      aria-labelledby={titleId}\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 flex-wrap items-center justify-between gap-2'>\n        <div className='flex min-w-0 items-center gap-2'>\n          <h3 id={titleId} className='sr-only'>\n            {agent.name} health\n          </h3>\n          <Chip color={chipColor}>{agent.name}</Chip>\n          {agent.model && (\n            <span className='text-muted-foreground truncate text-xs'>\n              {agent.model}\n            </span>\n          )}\n          <Badge variant='secondary'>Illustrative</Badge>\n        </div>\n        {periodSwitch}\n      </header>\n      <HealthGauge report={report} />\n      <ul aria-label='Signals' className='flex flex-col'>\n        {report.signals.map((signal, index) => (\n          <SignalRow key={signal.id} signal={signal} index={index} />\n        ))}\n      </ul>\n      <SummaryPanel\n        status={summary.status}\n        text={summary.text}\n        shownWords={summary.shownWords}\n        isGeneratePressed={isGeneratePressed}\n        onGenerate={onGenerateSummary}\n        onStop={onStopSummary}\n      />\n      <ActionCard\n        action={action}\n        status={actionStatus}\n        isApplyPressed={isApplyPressed}\n        onApply={onApplyAction}\n      />\n    </section>\n  );\n}\n\ntype PeriodId = 'week' | 'month';\n\nconst PERIODS: Segment<PeriodId>[] = [\n  { value: 'week', label: '7 days' },\n  { value: 'month', label: '30 days' },\n];\n\nconst ONE_DECIMAL: Intl.NumberFormatOptions = {\n  minimumFractionDigits: 1,\n  maximumFractionDigits: 1,\n};\n\nconst CENTS: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 3,\n  maximumFractionDigits: 3,\n};\n\nconst WHOLE: Intl.NumberFormatOptions = { maximumFractionDigits: 0 };\n\nconst REPORTS: Record<PeriodId, HealthReport> = {\n  week: {\n    score: 71,\n    change: -9,\n    changeLabel: 'since last week',\n    signals: [\n      {\n        id: 'success',\n        label: 'Success rate',\n        value: 91.2,\n        format: ONE_DECIMAL,\n        suffix: '%',\n        target: '95% or more',\n        points: [\n          96, 95.8, 96.2, 95.1, 94.6, 93.9, 93.1, 92.4, 91.8, 91.5, 90.9, 91.2,\n        ],\n        isOutOfRange: true,\n      },\n      {\n        id: 'latency',\n        label: 'Median latency',\n        value: 3.4,\n        format: ONE_DECIMAL,\n        suffix: 's',\n        target: '4s or less',\n        points: [3.1, 3.2, 3, 3.3, 3.2, 3.5, 3.4, 3.6, 3.3, 3.5, 3.4, 3.4],\n        isOutOfRange: false,\n      },\n      {\n        id: 'cost',\n        label: 'Cost per run',\n        value: 0.042,\n        format: CENTS,\n        target: '$0.050 or less',\n        points: [\n          0.038, 0.039, 0.04, 0.039, 0.041, 0.042, 0.04, 0.043, 0.042, 0.041,\n          0.043, 0.042,\n        ],\n        isOutOfRange: false,\n      },\n      {\n        id: 'escalations',\n        label: 'Escalations',\n        value: 7,\n        format: WHOLE,\n        target: '5 or fewer',\n        points: [0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 2, 0],\n        isOutOfRange: true,\n      },\n      {\n        id: 'errors',\n        label: 'Tool errors',\n        value: 4.8,\n        format: ONE_DECIMAL,\n        suffix: '%',\n        target: '3% or less',\n        points: [1.9, 2.1, 2, 2.6, 3.1, 3.4, 3.9, 4.2, 4.6, 4.4, 5.1, 4.8],\n        isOutOfRange: true,\n      },\n    ],\n  },\n  month: {\n    score: 86,\n    change: 4,\n    changeLabel: 'since last month',\n    signals: [\n      {\n        id: 'success',\n        label: 'Success rate',\n        value: 95.6,\n        format: ONE_DECIMAL,\n        suffix: '%',\n        target: '95% or more',\n        points: [\n          94.8, 95.2, 95.9, 96.3, 96.1, 96.6, 96.4, 96.8, 96.2, 95.7, 94.1,\n          93.2,\n        ],\n        isOutOfRange: false,\n      },\n      {\n        id: 'latency',\n        label: 'Median latency',\n        value: 3.1,\n        format: ONE_DECIMAL,\n        suffix: 's',\n        target: '4s or less',\n        points: [3.3, 3.2, 3.1, 3, 3.1, 2.9, 3, 3.1, 3, 3.2, 3.3, 3.4],\n        isOutOfRange: false,\n      },\n      {\n        id: 'cost',\n        label: 'Cost per run',\n        value: 0.039,\n        format: CENTS,\n        target: '$0.050 or less',\n        points: [\n          0.041, 0.04, 0.039, 0.038, 0.038, 0.037, 0.038, 0.039, 0.038, 0.039,\n          0.041, 0.042,\n        ],\n        isOutOfRange: false,\n      },\n      {\n        id: 'escalations',\n        label: 'Escalations',\n        value: 3,\n        format: WHOLE,\n        target: '5 or fewer',\n        points: [1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 2, 2],\n        isOutOfRange: false,\n      },\n      {\n        id: 'errors',\n        label: 'Tool errors',\n        value: 2.4,\n        format: ONE_DECIMAL,\n        suffix: '%',\n        target: '3% or less',\n        points: [2.2, 2, 1.9, 1.8, 1.9, 1.7, 1.8, 1.9, 2.1, 2.6, 3.8, 4.8],\n        isOutOfRange: false,\n      },\n    ],\n  },\n};\n\nconst SUMMARIES: Record<PeriodId, string> = {\n  week: 'Success fell to 91% this week, mostly on Brightmoor pricing pages that time out after 8 seconds. Tool errors rose to 4.8% and escalations to 7, both from that same fetch step. Latency and cost stay inside their targets. A longer fetch timeout should recover most of the failed runs.',\n  month:\n    'Over 30 days the Researcher stays healthy: 95.6% of runs succeed, the median run takes 3.1 seconds and costs about 4 cents. The only drift is the last week, where page fetches started to time out. Tool errors are the signal to watch over the next days.',\n};\n\nconst ACTION: HealthAction = {\n  title: 'Raise the timeout of fetch_page to 20s',\n  reason: 'Most failed runs this week stop at the 8s limit on pricing pages.',\n  doneLine: 'Timeout set to 20s. The next runs use it.',\n  errorLine: 'The settings service did not answer. Nothing was changed.',\n};\n\nconst RESEARCHER_AGENT: Pick<RunAgent, 'name' | 'series' | 'model'> = {\n  name: 'Researcher',\n  series: 2,\n  model: 'Claude Sonnet',\n};\n\nconst THINK_MS = 1100;\n\n/** The summary arrives a few words at a time: one render per group, never one per word. */\nconst WORDS_PER_GROUP = 3;\n\nconst GROUP_MS = 150;\n\nconst APPLY_MS = 900;\n\n/** A control that waits on a person is pressed by the demonstration after this long. */\nconst ANSWER_AFTER_MS = 2500;\n\ntype SummaryState = {\n  status: SummaryStatus;\n  shownWords: number;\n};\n\nconst IDLE_SUMMARY: SummaryState = { status: 'idle', shownWords: 0 };\n\nfunction summaryAnnouncementOf(status: SummaryStatus) {\n  if (status === 'thinking') {\n    return 'Writing the summary';\n  }\n  if (status === 'done') {\n    return 'Summary ready';\n  }\n  if (status === 'stopped') {\n    return 'Summary stopped';\n  }\n  return '';\n}\n\nfunction actionAnnouncementOf(status: ActionStatus) {\n  if (status === 'pending') {\n    return 'Applying the change';\n  }\n  if (status === 'failed') {\n    return 'The change failed, nothing was changed';\n  }\n  if (status === 'done') {\n    return 'The change is applied';\n  }\n  return '';\n}\n\nfunction announcementOf(\n  summary: SummaryStatus,\n  action: ActionStatus,\n  fallback: string\n) {\n  const actionLine = actionAnnouncementOf(action);\n  if (actionLine) {\n    return actionLine;\n  }\n  const summaryLine = summaryAnnouncementOf(summary);\n  if (summaryLine) {\n    return summaryLine;\n  }\n  return fallback;\n}\n\n/** How long a summary takes to write itself, from the click to its last word. */\nfunction writingTimeOf(wordCount: number) {\n  const groups = Math.ceil(wordCount / WORDS_PER_GROUP);\n  const streamTime = groups * GROUP_MS;\n  return THINK_MS + streamTime;\n}\n\ntype PressKey = 'generate' | 'apply';\n\nexport default function Run10() {\n  const [periodId, setPeriodId] = useState<PeriodId>('week');\n  const [summaryState, setSummaryState] = useState<SummaryState>(IDLE_SUMMARY);\n  const [actionStatus, setActionStatus] = useState<ActionStatus>('idle');\n  const [attempts, setAttempts] = useState(0);\n  const [periodLine, setPeriodLine] = useState('');\n  const summaryTimers = useTimeouts();\n  const actionTimers = useTimeouts();\n  const { pressed, press } = usePress<PressKey>();\n  const report = REPORTS[periodId];\n  const summaryText = SUMMARIES[periodId];\n  const wordCount = wordsOf(summaryText).length;\n  const announcement = announcementOf(\n    summaryState.status,\n    actionStatus,\n    periodLine\n  );\n\n  function streamFrom(shown: number) {\n    if (shown >= wordCount) {\n      setSummaryState({ status: 'done', shownWords: wordCount });\n      return;\n    }\n    const next = shown + WORDS_PER_GROUP;\n    setSummaryState({ status: 'streaming', shownWords: shown });\n    summaryTimers.schedule(() => streamFrom(next), GROUP_MS);\n  }\n\n  function generateSummary() {\n    summaryTimers.clearAll();\n    setSummaryState({ status: 'thinking', shownWords: 0 });\n    summaryTimers.schedule(() => streamFrom(WORDS_PER_GROUP), THINK_MS);\n  }\n\n  function stopSummary() {\n    summaryTimers.clearAll();\n    setSummaryState((current) => ({ ...current, status: 'stopped' }));\n  }\n\n  function changePeriod(next: PeriodId) {\n    summaryTimers.clearAll();\n    setSummaryState(IDLE_SUMMARY);\n    setPeriodId(next);\n    const nextReport = REPORTS[next];\n    setPeriodLine(`Health ${nextReport.score} ${nextReport.changeLabel}`);\n  }\n\n  function applyAction() {\n    const isBusy = actionStatus === 'pending';\n    const isDone = actionStatus === 'done';\n    if (isBusy || isDone) {\n      return;\n    }\n    const isFirstTry = attempts === 0;\n    setAttempts((current) => current + 1);\n    setActionStatus('pending');\n    actionTimers.schedule(() => {\n      if (isFirstTry) {\n        setActionStatus('failed');\n        return;\n      }\n      setActionStatus('done');\n    }, APPLY_MS);\n  }\n\n  function resetDemo() {\n    summaryTimers.clearAll();\n    actionTimers.clearAll();\n    setPeriodId('week');\n    setSummaryState(IDLE_SUMMARY);\n    setActionStatus('idle');\n    setAttempts(0);\n  }\n\n  const writingTime = writingTimeOf(wordCount);\n  const applyAfter = writingTime + 900;\n  const retryAfter = APPLY_MS + ANSWER_AFTER_MS;\n  const restAfter = APPLY_MS + 1600;\n  const steps: AutoplayStep[] = [\n    { after: 1500, run: () => changePeriod('month') },\n    { after: 2400, run: () => changePeriod('week') },\n    { after: 1500, run: () => press('generate') },\n    { after: PRESS_LEAD_MS, run: generateSummary },\n    { after: applyAfter, run: () => press('apply') },\n    { after: PRESS_LEAD_MS, run: applyAction },\n    { after: retryAfter, run: () => press('apply') },\n    { after: PRESS_LEAD_MS, run: applyAction },\n    { after: restAfter, run: hold },\n  ];\n  const { ref, isInView, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 2600,\n    onReset: resetDemo,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[54rem] w-full max-w-[34rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <AgentHealth\n          agent={RESEARCHER_AGENT}\n          report={report}\n          periodSwitch={\n            <Segments\n              value={periodId}\n              segments={PERIODS}\n              onValueChange={changePeriod}\n              label='Period'\n            />\n          }\n          summary={{\n            status: summaryState.status,\n            text: summaryText,\n            shownWords: summaryState.shownWords,\n          }}\n          onGenerateSummary={generateSummary}\n          onStopSummary={stopSummary}\n          action={ACTION}\n          actionStatus={actionStatus}\n          onApplyAction={applyAction}\n          isGeneratePressed={pressed === 'generate'}\n          isApplyPressed={pressed === 'apply'}\n        />\n      </ClockGate>\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "run"
  ],
  "type": "registry:component"
}