{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "run-12",
  "title": "Cost tracker",
  "description": "Tokens in and out, the cache share and the cost as plain ticking figures while a step streams, whose totals roll once as each step lands, above a per-step table with the model of each step and a small bar.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.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/icons.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/motion-word-roll.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-session.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/wash.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/run/run-12.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { WordRoll } from '@/components/core/word-roll';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport {\n  useSession,\n  type SessionStep,\n} from '@/registry/ndeko/hooks/use-session';\nimport { formatCost } from '@/registry/ndeko/lib/agent-run';\nimport type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\nimport {\n  pressedQuietOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport { ChevronDownIcon } from '@/registry/ndeko/lib/icons';\nimport { fadePresence } from '@/registry/ndeko/lib/motion-presets';\nimport { restingOf } from '@/registry/ndeko/lib/run-session';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { CallStatusMark } from '@/registry/ndeko/ui/call-status';\nimport { Fold } from '@/registry/ndeko/ui/chat-motion';\nimport { ClockGate, useLiveNow } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\nimport { Wash } from '@/registry/ndeko/ui/wash';\n\nimport { useOpenState } from './_parts/use-open-state';\n\nexport type CostStepStatus = 'queued' | 'running' | 'done';\n\nexport type StepRate = {\n  /** When the figures of the step were reported, in milliseconds. */\n  since: number;\n  tokensPerSecond: number;\n  usdPerSecond: number;\n};\n\nexport type CostStep = {\n  id: string;\n  title: string;\n  /** The model family and tier, without a version: \"Claude Sonnet\". */\n  model: string;\n  brand: BrandSlug;\n  status: CostStepStatus;\n  inputTokens: number;\n  /** The part of the input served from the cache. */\n  cachedTokens: number;\n  outputTokens: number;\n  costUsd: number;\n  /** A running step streams at this rate from the moment its figures were reported. */\n  rate?: StepRate;\n};\n\ntype Totals = {\n  inputTokens: number;\n  cachedTokens: number;\n  outputTokens: number;\n  costUsd: number;\n};\n\nconst TOKEN_FORMAT: Intl.NumberFormatOptions = { maximumFractionDigits: 0 };\n\nconst COST_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 3,\n  maximumFractionDigits: 3,\n};\n\nconst PERCENT_FORMAT: Intl.NumberFormatOptions = { maximumFractionDigits: 0 };\n\nconst COUNT_FORMATTER = new Intl.NumberFormat('en-US', TOKEN_FORMAT);\n\nconst LIVE_TICK_MS = 125;\n\nconst MIN_BAR_SCALE_USD = 0.001;\n\nfunction formatCount(count: number) {\n  return COUNT_FORMATTER.format(Math.round(count));\n}\n\nfunction isDone(step: CostStep) {\n  return step.status === 'done';\n}\n\nfunction isRunning(step: CostStep) {\n  return step.status === 'running';\n}\n\nfunction runningStepOf(steps: CostStep[]) {\n  return steps.find(isRunning);\n}\n\nfunction totalsOf(steps: CostStep[]): Totals {\n  const totals: Totals = {\n    inputTokens: 0,\n    cachedTokens: 0,\n    outputTokens: 0,\n    costUsd: 0,\n  };\n  for (const step of steps.filter(isDone)) {\n    totals.inputTokens += step.inputTokens;\n    totals.cachedTokens += step.cachedTokens;\n    totals.outputTokens += step.outputTokens;\n    totals.costUsd += step.costUsd;\n  }\n  return totals;\n}\n\nfunction cacheShareOf(totals: Totals) {\n  if (totals.inputTokens === 0) {\n    return 0;\n  }\n  const share = totals.cachedTokens / totals.inputTokens;\n  return share * 100;\n}\n\nfunction secondsSince(now: number, since: number) {\n  const elapsed = Math.max(0, now - since);\n  return elapsed / 1000;\n}\n\nfunction liveOutputOf(step: CostStep, now: number) {\n  if (!step.rate) {\n    return step.outputTokens;\n  }\n  const seconds = secondsSince(now, step.rate.since);\n  return step.outputTokens + step.rate.tokensPerSecond * seconds;\n}\n\nfunction liveCostOf(step: CostStep, now: number) {\n  if (!step.rate) {\n    return step.costUsd;\n  }\n  const seconds = secondsSince(now, step.rate.since);\n  return step.costUsd + step.rate.usdPerSecond * seconds;\n}\n\nfunction barScaleOf(steps: CostStep[]) {\n  let largest = MIN_BAR_SCALE_USD;\n  for (const step of steps) {\n    largest = Math.max(largest, step.costUsd);\n  }\n  return largest;\n}\n\nfunction chevronTurnOf(isOpen: boolean) {\n  if (isOpen) {\n    return 'rotate-180';\n  }\n  return 'rotate-0';\n}\n\nfunction stepPositionOf(steps: CostStep[], step: CostStep) {\n  const index = steps.findIndex((candidate) => candidate.id === step.id);\n  return index + 1;\n}\n\nfunction statusLineOf(steps: CostStep[]) {\n  const running = runningStepOf(steps);\n  if (running) {\n    const position = stepPositionOf(steps, running);\n    return `Step ${position} of ${steps.length}: ${running.title}`;\n  }\n  const doneCount = steps.filter(isDone).length;\n  if (doneCount === steps.length) {\n    return `Done, ${countOf(steps.length, 'step')}`;\n  }\n  if (doneCount === 0) {\n    return 'Waiting for the first step';\n  }\n  return `Step ${doneCount} of ${steps.length} done`;\n}\n\nfunction LiveDelta({\n  step,\n  kind,\n}: {\n  step: CostStep;\n  kind: 'input' | 'output' | 'cost';\n}) {\n  const now = useLiveNow(LIVE_TICK_MS, true);\n  let text = formatCount(step.inputTokens);\n  if (kind === 'output') {\n    text = formatCount(liveOutputOf(step, now));\n  }\n  if (kind === 'cost') {\n    text = formatCost(liveCostOf(step, now));\n  }\n\n  return <span className='text-primary-ink text-xs tabular-nums'>+{text}</span>;\n}\n\nfunction LiveAmount({\n  step,\n  kind,\n}: {\n  step: CostStep;\n  kind: 'output' | 'cost';\n}) {\n  const now = useLiveNow(LIVE_TICK_MS, true);\n  if (kind === 'output') {\n    return <>{formatCount(liveOutputOf(step, now))}</>;\n  }\n  return <>{formatCost(liveCostOf(step, now))}</>;\n}\n\nfunction barStyleOf(share: number): React.CSSProperties {\n  const bounded = Math.min(1, Math.max(0, share));\n  return { transform: `scaleX(${bounded})` };\n}\n\nconst BAR_FILL =\n  'bg-primary h-full w-full origin-left rounded-full transition-transform duration-300 ease-(--ease-out-strong) motion-reduce:transition-none';\n\nfunction LiveBar({ step, scaleUsd }: { step: CostStep; scaleUsd: number }) {\n  const now = useLiveNow(LIVE_TICK_MS, true);\n  const share = liveCostOf(step, now) / scaleUsd;\n\n  return <span style={barStyleOf(share)} className={BAR_FILL} />;\n}\n\nfunction StepBar({ step, scaleUsd }: { step: CostStep; scaleUsd: number }) {\n  if (isRunning(step)) {\n    return <LiveBar step={step} scaleUsd={scaleUsd} />;\n  }\n  const share = step.costUsd / scaleUsd;\n\n  return <span style={barStyleOf(share)} className={BAR_FILL} />;\n}\n\nfunction StepOutput({ step }: { step: CostStep }) {\n  if (isRunning(step)) {\n    return (\n      <>\n        <LiveAmount step={step} kind='output' /> out\n      </>\n    );\n  }\n  if (isDone(step)) {\n    return <>{formatCount(step.outputTokens)} out</>;\n  }\n  return <>Waiting</>;\n}\n\nfunction StepCost({ step }: { step: CostStep }) {\n  if (isRunning(step)) {\n    return <LiveAmount step={step} kind='cost' />;\n  }\n  if (isDone(step)) {\n    return <>{formatCost(step.costUsd)}</>;\n  }\n  return <span className='text-muted-foreground'>-</span>;\n}\n\nfunction StepRow({ step, scaleUsd }: { step: CostStep; scaleUsd: number }) {\n  return (\n    <li\n      data-status={step.status}\n      className='grid grid-cols-[1rem_minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1.5 px-1 py-2'\n    >\n      <CallStatusMark status={step.status} />\n      <span className='min-w-0 truncate text-[13px]'>{step.title}</span>\n      <span className='text-end text-[13px] tabular-nums'>\n        <StepCost step={step} />\n      </span>\n      <span className='col-start-2 flex min-w-0 items-center gap-2'>\n        <BrandTile brand={step.brand} size='sm' />\n        <span className='text-muted-foreground min-w-0 truncate text-xs'>\n          {step.model}\n        </span>\n        <span className='text-muted-foreground shrink-0 text-xs tabular-nums'>\n          <StepOutput step={step} />\n        </span>\n      </span>\n      <span\n        aria-hidden='true'\n        className='bg-foreground/10 col-start-3 h-1 w-14 overflow-hidden rounded-full @md:w-24'\n      >\n        <StepBar step={step} scaleUsd={scaleUsd} />\n      </span>\n    </li>\n  );\n}\n\ntype FigureTileProps = {\n  label: string;\n  children: React.ReactNode;\n  live?: React.ReactNode;\n};\n\nfunction FigureTile({ label, children, live }: FigureTileProps) {\n  const fade = fadePresence();\n\n  return (\n    <div className='bg-foreground/[0.04] dark:bg-foreground/[0.06] flex min-w-0 flex-col gap-1 rounded-lg px-3 py-2.5'>\n      <span className='text-muted-foreground text-xs'>{label}</span>\n      <span className='flex flex-wrap items-baseline gap-x-1.5'>\n        <span className='text-xl leading-7 font-semibold tabular-nums'>\n          {children}\n        </span>\n        <AnimatePresence initial={false}>\n          {live && (\n            <motion.span key='live' className='inline-flex' {...fade}>\n              {live}\n            </motion.span>\n          )}\n        </AnimatePresence>\n      </span>\n    </div>\n  );\n}\n\nexport type CostTrackerProps = {\n  steps: CostStep[];\n  isIllustrative?: boolean;\n  isOpen?: boolean;\n  onOpenChange?: (isOpen: boolean) => void;\n  /** Shows the per-step toggle held down, for a demonstration that presses it. */\n  isTogglePressed?: boolean;\n  className?: string;\n};\n\nexport function CostTracker({\n  steps,\n  isIllustrative = false,\n  isOpen,\n  onOpenChange,\n  isTogglePressed = false,\n  className,\n}: CostTrackerProps) {\n  const tableId = useId();\n  const openState = useOpenState({ isOpen, defaultOpen: false, onOpenChange });\n  const totals = totalsOf(steps);\n  const cacheShare = cacheShareOf(totals);\n  const running = runningStepOf(steps);\n  const isStreaming = running !== undefined;\n  const statusLine = statusLineOf(steps);\n  const scaleUsd = barScaleOf(steps);\n  const rate = running?.rate;\n\n  return (\n    <section\n      aria-label='Run cost'\n      className={cn(\n        'bg-card hairline-ring ring-border @container relative isolate flex flex-col gap-4 rounded-xl p-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <Wash shape='top' color='var(--info)' isShown={isStreaming} />\n      <header className='flex flex-wrap items-start justify-between gap-x-3 gap-y-2'>\n        <div className='flex min-w-0 flex-col gap-1'>\n          <div className='flex items-center gap-2'>\n            <h3 className='text-sm font-medium'>Run cost</h3>\n            {isIllustrative && <Badge variant='outline'>Illustrative</Badge>}\n          </div>\n          <p className='text-muted-foreground flex min-w-0 items-center gap-2 text-xs'>\n            <span className='min-w-0 truncate'>\n              <WordRoll text={statusLine} />\n            </span>\n            {rate && (\n              <span className='shrink-0 tabular-nums'>\n                {formatCount(rate.tokensPerSecond)} tokens/s\n              </span>\n            )}\n          </p>\n        </div>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          aria-expanded={openState.isOpen}\n          aria-controls={tableId}\n          onClick={openState.toggle}\n          className={cn(\n            'text-muted-foreground',\n            pressedQuietOf(isTogglePressed)\n          )}\n        >\n          Per step\n          <ChevronDownIcon\n            className={cn(\n              'transition-transform duration-200 ease-(--ease-out-strong)',\n              chevronTurnOf(openState.isOpen)\n            )}\n          />\n        </Button>\n      </header>\n      <div className='grid grid-cols-2 gap-2 @xl:grid-cols-4'>\n        <FigureTile\n          label='Tokens in'\n          live={running && <LiveDelta step={running} kind='input' />}\n        >\n          <MotionNumber value={totals.inputTokens} format={TOKEN_FORMAT} />\n        </FigureTile>\n        <FigureTile\n          label='Tokens out'\n          live={running && <LiveDelta step={running} kind='output' />}\n        >\n          <MotionNumber value={totals.outputTokens} format={TOKEN_FORMAT} />\n        </FigureTile>\n        <FigureTile label='From cache'>\n          <MotionNumber value={cacheShare} format={PERCENT_FORMAT} suffix='%' />\n        </FigureTile>\n        <FigureTile\n          label='Cost'\n          live={running && <LiveDelta step={running} kind='cost' />}\n        >\n          <MotionNumber value={totals.costUsd} format={COST_FORMAT} />\n        </FigureTile>\n      </div>\n      <Fold open={openState.isOpen} id={tableId}>\n        <ol aria-label='Cost per step' className='flex flex-col'>\n          {steps.map((step) => (\n            <StepRow key={step.id} step={step} scaleUsd={scaleUsd} />\n          ))}\n        </ol>\n      </Fold>\n    </section>\n  );\n}\n\ntype StepSpec = {\n  id: string;\n  title: string;\n  model: string;\n  brand: BrandSlug;\n  inputTokens: number;\n  cachedTokens: number;\n  outputTokens: number;\n  costUsd: number;\n  /** What the figures show while the step streams: a little under what the final report says. */\n  tokensPerSecond: number;\n  usdPerSecond: number;\n};\n\nconst SPECS: StepSpec[] = [\n  {\n    id: 'read',\n    title: 'Read the request',\n    model: 'Claude Haiku',\n    brand: 'claude',\n    inputTokens: 3180,\n    cachedTokens: 2400,\n    outputTokens: 224,\n    costUsd: 0.003,\n    tokensPerSecond: 145,\n    usdPerSecond: 0.00194,\n  },\n  {\n    id: 'search',\n    title: 'Search the supplier sites',\n    model: 'Gemini Flash',\n    brand: 'gemini',\n    inputTokens: 5940,\n    cachedTokens: 0,\n    outputTokens: 330,\n    costUsd: 0.004,\n    tokensPerSecond: 145,\n    usdPerSecond: 0.00176,\n  },\n  {\n    id: 'pages',\n    title: 'Read the pricing pages',\n    model: 'Claude Sonnet',\n    brand: 'claude',\n    inputTokens: 18420,\n    cachedTokens: 12100,\n    outputTokens: 212,\n    costUsd: 0.046,\n    tokensPerSecond: 79,\n    usdPerSecond: 0.01716,\n  },\n  {\n    id: 'draft',\n    title: 'Draft the credit request',\n    model: 'Claude Opus',\n    brand: 'claude',\n    inputTokens: 9760,\n    cachedTokens: 7300,\n    outputTokens: 138,\n    costUsd: 0.171,\n    tokensPerSecond: 48,\n    usdPerSecond: 0.0592,\n  },\n  {\n    id: 'review',\n    title: 'Review the draft',\n    model: 'Claude Sonnet',\n    brand: 'claude',\n    inputTokens: 11200,\n    cachedTokens: 9950,\n    outputTokens: 176,\n    costUsd: 0.031,\n    tokensPerSecond: 78,\n    usdPerSecond: 0.01367,\n  },\n];\n\nfunction queuedStep(spec: StepSpec): CostStep {\n  return {\n    id: spec.id,\n    title: spec.title,\n    model: spec.model,\n    brand: spec.brand,\n    status: 'queued',\n    inputTokens: 0,\n    cachedTokens: 0,\n    outputTokens: 0,\n    costUsd: 0,\n  };\n}\n\nfunction runningStep(spec: StepSpec, now: number): CostStep {\n  const rate: StepRate = {\n    since: now,\n    tokensPerSecond: spec.tokensPerSecond,\n    usdPerSecond: spec.usdPerSecond,\n  };\n  return {\n    ...queuedStep(spec),\n    status: 'running',\n    inputTokens: spec.inputTokens,\n    cachedTokens: spec.cachedTokens,\n    rate,\n  };\n}\n\nfunction doneStep(spec: StepSpec): CostStep {\n  return {\n    ...queuedStep(spec),\n    status: 'done',\n    inputTokens: spec.inputTokens,\n    cachedTokens: spec.cachedTokens,\n    outputTokens: spec.outputTokens,\n    costUsd: spec.costUsd,\n  };\n}\n\ntype TrackerState = {\n  steps: CostStep[];\n  isOpen: boolean;\n};\n\ntype TrackerAction =\n  | { type: 'start'; id: string }\n  | { type: 'finish'; id: string }\n  | { type: 'open'; isOpen: boolean }\n  | { type: 'hold' };\n\ntype TrackerStep = SessionStep<TrackerState, TrackerAction>;\n\nconst INITIAL: TrackerState = { steps: SPECS.map(queuedStep), isOpen: false };\n\nfunction specOf(id: string) {\n  return SPECS.find((spec) => spec.id === id);\n}\n\nfunction withStepReplaced(state: TrackerState, next: CostStep): TrackerState {\n  const steps = state.steps.map((step) => {\n    if (step.id === next.id) {\n      return next;\n    }\n    return step;\n  });\n  return { ...state, steps };\n}\n\nfunction started(state: TrackerState, id: string, now: number) {\n  const spec = specOf(id);\n  const current = state.steps.find((step) => step.id === id);\n  if (!spec || current?.status !== 'queued') {\n    return state;\n  }\n  return withStepReplaced(state, runningStep(spec, now));\n}\n\nfunction finished(state: TrackerState, id: string) {\n  const spec = specOf(id);\n  const current = state.steps.find((step) => step.id === id);\n  if (!spec || current?.status !== 'running') {\n    return state;\n  }\n  return withStepReplaced(state, doneStep(spec));\n}\n\nfunction applyAt(\n  state: TrackerState,\n  action: TrackerAction,\n  now: number\n): TrackerState {\n  switch (action.type) {\n    case 'start':\n      return started(state, action.id, now);\n    case 'finish':\n      return finished(state, action.id);\n    case 'open':\n      return { ...state, isOpen: action.isOpen };\n    case 'hold':\n      return state;\n  }\n}\n\n/** The stream stamps a step when it starts, as a backend would report it. */\nfunction reducer(state: TrackerState, action: TrackerAction) {\n  return applyAt(state, action, Date.now());\n}\n\nfunction startStep(after: number, id: string): TrackerStep {\n  return { after, action: { type: 'start', id } };\n}\n\nfunction finishStep(after: number, id: string): TrackerStep {\n  return { after, action: { type: 'finish', id } };\n}\n\nconst SCRIPT: TrackerStep[] = [\n  startStep(900, 'read'),\n  finishStep(1500, 'read'),\n  {\n    after: 400,\n    by: 'demo',\n    press: 'rows',\n    action: { type: 'open', isOpen: true },\n  },\n  startStep(600, 'search'),\n  finishStep(2200, 'search'),\n  startStep(500, 'pages'),\n  finishStep(2600, 'pages'),\n  startStep(500, 'draft'),\n  finishStep(2800, 'draft'),\n  startStep(500, 'review'),\n  finishStep(2200, 'review'),\n  { after: 4500, action: { type: 'hold' } },\n];\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: restingOf(INITIAL, SCRIPT, applyAt),\n  script: SCRIPT,\n  loopAfter: 3000,\n};\n\nfunction announcementOf(steps: CostStep[]) {\n  const running = runningStepOf(steps);\n  if (running) {\n    const position = stepPositionOf(steps, running);\n    return `Step ${position} of ${steps.length} started: ${running.title}`;\n  }\n  const doneSteps = steps.filter(isDone);\n  const last = doneSteps[doneSteps.length - 1];\n  if (!last) {\n    return '';\n  }\n  const total = formatCost(totalsOf(steps).costUsd);\n  if (doneSteps.length === steps.length) {\n    return `The run is done. Total cost ${total}`;\n  }\n  return `${last.title} is done. Total cost so far ${total}`;\n}\n\nexport default function Run12() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const isOver = state.steps.every(isDone);\n  const canReplay = isOver && isFinished && !isAutoplaying;\n  const announcement = announcementOf(state.steps);\n\n  function changeOpen(isOpen: boolean) {\n    act({ type: 'open', isOpen });\n  }\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex min-h-[34rem] w-full max-w-[40rem] flex-col gap-2'\n    >\n      <ClockGate isActive={isInView}>\n        <CostTracker\n          steps={state.steps}\n          isIllustrative\n          isOpen={state.isOpen}\n          onOpenChange={changeOpen}\n          isTogglePressed={pressed === 'rows'}\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-12.tsx"
    },
    {
      "path": "registry/ndeko/components/run/_parts/use-open-state.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\ntype OpenStateOptions = {\n  /** When given, the parent owns the state. */\n  isOpen?: boolean;\n  defaultOpen: boolean;\n  onOpenChange?: (isOpen: boolean) => void;\n};\n\nfunction currentOpenOf(isOpen: boolean | undefined, ownOpen: boolean) {\n  if (isOpen === undefined) {\n    return ownOpen;\n  }\n  return isOpen;\n}\n\nexport function useOpenState({\n  isOpen,\n  defaultOpen,\n  onOpenChange,\n}: OpenStateOptions) {\n  const [ownOpen, setOwnOpen] = useState(defaultOpen);\n  const current = currentOpenOf(isOpen, ownOpen);\n\n  function toggle() {\n    const next = !current;\n    setOwnOpen(next);\n    onOpenChange?.(next);\n  }\n\n  return { isOpen: current, toggle };\n}\n",
      "type": "registry:component",
      "target": "components/run/_parts/use-open-state.ts"
    }
  ],
  "categories": [
    "components",
    "run"
  ],
  "type": "registry:component"
}