{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "application-14",
  "title": "Workflow builder",
  "description": "An Alderbank workflow builder: an email triage flow on a canvas that pans and zooms, a palette that adds a step where you point, an inspector that sets up each kind of step, and undo and redo that walk every edit. A test run travels down the flow step by step: the branch it takes fills with the primary colour while the others dim, a carrier call fails once then passes on its second try, the reply streams in the inspector and a refund waits for Allow or Deny on its step. Plug your backend into onRun, onSave, onPublish, onApprove, onDeny and onChange.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.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/chat-motion.json",
    "https://ui.ndekocode.dev/r/company-mark.json",
    "https://ui.ndekocode.dev/r/copy-button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/dropdown-menu.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/inline-sheet.json",
    "https://ui.ndekocode.dev/r/input.json",
    "https://ui.ndekocode.dev/r/json-view.json",
    "https://ui.ndekocode.dev/r/kbd.json",
    "https://ui.ndekocode.dev/r/label.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/mesh-tile.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/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/popover.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/run-session.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/select.json",
    "https://ui.ndekocode.dev/r/streamed-text.json",
    "https://ui.ndekocode.dev/r/switch.json",
    "https://ui.ndekocode.dev/r/tabs.json",
    "https://ui.ndekocode.dev/r/textarea.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-is-narrow.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/use-timeouts.json",
    "https://ui.ndekocode.dev/r/utils.json",
    "https://ui.ndekocode.dev/r/wash.json",
    "https://ui.ndekocode.dev/r/words.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/index.tsx",
      "content": "'use client';\n\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\n\nimport { useIsNarrow } from '@/registry/ndeko/hooks/use-is-narrow';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport { InlineSheet } from '@/registry/ndeko/ui/inline-sheet';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport { CanvasPanel } from './canvas-panel';\nimport { capitalized } from './capitalized';\nimport { faceKeyOf, placementOf, structureKeyOf } from './flow';\nimport { Inspector } from './inspector';\nimport { layoutOf } from './layout';\nimport type { Workflow } from './model';\nimport { Palette } from './palette';\nimport { isBusy } from './run';\nimport { holdsForRun, LOOP_AFTER_MS, RESTING, SCRIPT } from './script';\nimport { hasUnsavedChanges, INITIAL, reducer } from './session';\nimport { TopBar } from './top-bar';\nimport {\n  paletteTargetOf,\n  useBuilderHandlers,\n  type Backend,\n} from './use-builder-handlers';\nimport { useKept } from './use-kept';\nimport { useRunClock } from './use-run-clock';\nimport { useViewport } from './use-viewport';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n  holdWhile: holdsForRun,\n};\n\n/** The width of the `@3xl` container variant: under it the inspector lives in a sheet. */\nconst INSPECTOR_SHEET_BELOW_REM = 48;\n\n/** The width of the `@5xl` container variant: under it the palette lives in a sheet and the mini map is gone. */\nconst PALETTE_SHEET_BELOW_REM = 64;\n\n/**\n * Nothing calls a network. A real backend plugs in here: a test run with its sample, a save, a\n * publish, the answer of a person to a step that asks first, and every change made to the flow.\n */\nexport type Application14Props = Backend & {\n  onChange?: (workflow: Workflow) => void;\n};\n\nexport default function Application14({\n  onRun,\n  onSave,\n  onPublish,\n  onApprove,\n  onDeny,\n  onChange,\n}: Application14Props) {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n    takeOver,\n  } = useSession(SESSION);\n  const reported = useRef(state.workflow);\n  const hasInspectorSheet = useIsNarrow(ref, INSPECTOR_SHEET_BELOW_REM);\n  const hasPaletteSheet = useIsNarrow(ref, PALETTE_SHEET_BELOW_REM);\n  const { workflow, run, selectedId } = state;\n  const shownFlow = useKept(workflow, faceKeyOf(workflow));\n  const structure = useKept(workflow, structureKeyOf(workflow));\n  const layout = useMemo(() => layoutOf(structure), [structure]);\n  const backend = { onRun, onSave, onPublish, onApprove, onDeny };\n  const {\n    echo,\n    mintId,\n    pickEntry,\n    select,\n    leaveInspector,\n    openInspector,\n    openPalette,\n    closePalette,\n    remove,\n    duplicate,\n    insert,\n    renameStep,\n    renameWorkflow,\n    undo,\n    redo,\n    undoFromNotice,\n    undoFromKeys,\n    redoFromKeys,\n    save,\n    publish,\n    startRun,\n    runAgain,\n    clearRun,\n    decide,\n  } = useBuilderHandlers(ref, {\n    state,\n    act,\n    hasInspectorSheet,\n    hasPaletteSheet,\n    backend,\n  });\n\n  const deselect = useCallback(() => {\n    act({ type: 'selected', id: null });\n  }, [act]);\n\n  const viewport = useViewport(layout, deselect, takeOver);\n\n  const advanceRun = useCallback(\n    (token: number, beat: number) => {\n      act({ type: 'runAdvanced', token, beat });\n    },\n    [act]\n  );\n\n  useRunClock(run, workflow, isInView, advanceRun);\n\n  /** The demonstration edits the sample flow on its own: only what a person changes is reported. */\n  useEffect(() => {\n    const hasChanged = reported.current !== workflow;\n    reported.current = workflow;\n    if (hasChanged && !isAutoplaying) {\n      onChange?.(workflow);\n    }\n  }, [workflow, isAutoplaying, onChange]);\n\n  const isPaletteShown = hasPaletteSheet && state.isPaletteOpen;\n  const isInspectorShown = hasInspectorSheet && state.isInspectorOpen;\n  const isBehindSheet = isPaletteShown || isInspectorShown;\n  const canReplay = isFinished && !isAutoplaying;\n  const message = spokenUnless(isAutoplaying, state.spoken);\n  const paletteTarget = paletteTargetOf(selectedId);\n  const palettePlace = placementOf(workflow, paletteTarget);\n  const placement = capitalized(palettePlace);\n\n  const inspector = {\n    workflow,\n    savedWorkflow: state.savedWorkflow,\n    selectedId,\n    tab: state.tab,\n    run,\n    isActive: isInView,\n    onAct: act,\n    onMintId: mintId,\n    onLeave: leaveInspector,\n  };\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-sidebar text-foreground @container/app min-h-dvh w-full'\n      >\n        <div className='relative flex h-dvh min-h-[40rem] flex-col overflow-hidden'>\n          <div inert={isBehindSheet} className='flex min-h-0 flex-1 flex-col'>\n            <TopBar\n              workflow={shownFlow}\n              save={state.save}\n              hasUnsavedChanges={hasUnsavedChanges(state)}\n              isLive={state.isLive}\n              isRunning={isBusy(run)}\n              pressed={pressed}\n              canReplay={canReplay}\n              onReplay={restart}\n              onRename={renameWorkflow}\n              onSave={save}\n              onPublish={publish}\n              onRun={runAgain}\n            />\n            <div className='flex min-h-0 flex-1 gap-2 @3xl/app:px-2 @3xl/app:pb-2'>\n              <aside\n                aria-label='Steps to add'\n                className='hidden w-56 shrink-0 px-1 pt-1 @5xl/app:flex'\n              >\n                {!hasPaletteSheet && (\n                  <Palette\n                    placement={placement}\n                    pressed={pressed}\n                    onPick={pickEntry}\n                  />\n                )}\n              </aside>\n              <CanvasPanel\n                state={state}\n                shownFlow={shownFlow}\n                layout={layout}\n                viewport={viewport}\n                pressed={pressed}\n                echo={echo}\n                hasMiniMap={!hasPaletteSheet}\n                onSelect={select}\n                onRemove={remove}\n                onDuplicate={duplicate}\n                onInsert={insert}\n                onDecide={decide}\n                onRename={renameStep}\n                onUndo={undo}\n                onRedo={redo}\n                onUndoNotice={undoFromNotice}\n                onUndoKey={undoFromKeys}\n                onRedoKey={redoFromKeys}\n                onRun={startRun}\n                onClearRun={clearRun}\n                onOpenPalette={openPalette}\n                onOpenInspector={openInspector}\n              />\n              <aside\n                aria-label='Setup of the selected step'\n                className='hidden w-72 shrink-0 @3xl/app:flex @6xl/app:w-80'\n              >\n                <div className='bg-card hairline-ring ring-border dark:bg-foreground/[0.03] flex min-h-0 min-w-0 flex-1 rounded-xl p-3 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n                  {!hasInspectorSheet && (\n                    <Inspector {...inspector} className='w-full' />\n                  )}\n                </div>\n              </aside>\n            </div>\n          </div>\n\n          <InlineSheet\n            name='palette'\n            label='Add a step'\n            closeLabel='Close the palette'\n            side='start'\n            isOpen={isPaletteShown}\n            className='@5xl/app:hidden'\n            panelClassName='bg-sidebar gap-1 p-3'\n            onClose={closePalette}\n          >\n            {hasPaletteSheet && (\n              <Palette\n                placement={placement}\n                pressed={pressed}\n                onPick={pickEntry}\n                className='flex-1'\n              />\n            )}\n          </InlineSheet>\n          <InlineSheet\n            name='inspector'\n            label='Step setup'\n            closeLabel='Close the step setup'\n            side='bottom'\n            isOpen={isInspectorShown}\n            className='@3xl/app:hidden'\n            panelClassName='bg-sidebar h-[80%] gap-1 p-3'\n            onClose={leaveInspector}\n          >\n            {hasInspectorSheet && (\n              <Inspector {...inspector} className='flex-1' />\n            )}\n          </InlineSheet>\n          <LiveRegion message={message} />\n        </div>\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/index.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/top-bar.tsx",
      "content": "'use client';\n\nimport { memo } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport { useNow } from '@/registry/ndeko/hooks/use-agent-run';\nimport {\n  pressedQuietOf,\n  pressedSolidOf,\n} from '@/registry/ndeko/lib/demonstration';\nimport { EllipsisIcon, PlayIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { countOf } from '@/registry/ndeko/lib/words';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport {\n  DropdownMenu,\n  DropdownMenuCheckboxItem,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { BRAND } from './data';\nimport { countsOf } from './flow';\nimport type { Workflow } from './model';\nimport { NameField } from './name-field';\nimport type { SaveState } from './session';\n\nconst MINUTE_MS = 60_000;\n\n/** How often the line \"Saved 3 min ago\" looks at the time. */\nconst SAVED_TICK_MS = 15_000;\n\ntype SaveKind = 'saving' | 'unsaved' | 'saved';\n\nconst SAVE_DOT: Record<SaveKind, string> = {\n  saving: 'bg-info animate-pulse',\n  unsaved: 'bg-warning',\n  saved: 'bg-success',\n};\n\nconst RUN_LABELS: Record<MorphState, string> = {\n  idle: 'Test run',\n  busy: 'Running',\n  done: 'Test run',\n};\n\nfunction saveKindOf(save: SaveState, hasUnsavedChanges: boolean): SaveKind {\n  if (save.status === 'saving') {\n    return 'saving';\n  }\n  if (hasUnsavedChanges) {\n    return 'unsaved';\n  }\n  return 'saved';\n}\n\n/** The save the sample data starts from has no time of its own: it reads as two minutes old. */\nfunction savedLineOf(at: number | null, now: number) {\n  if (at === null) {\n    return 'Saved 2 min ago';\n  }\n  const elapsed = now - at;\n  const minutes = Math.floor(elapsed / MINUTE_MS);\n  if (minutes < 1) {\n    return 'Saved just now';\n  }\n  return `Saved ${minutes} min ago`;\n}\n\nfunction saveLineOf(kind: SaveKind, at: number | null, now: number) {\n  if (kind === 'saving') {\n    return 'Saving';\n  }\n  if (kind === 'unsaved') {\n    return 'Unsaved changes';\n  }\n  return savedLineOf(at, now);\n}\n\ntype SaveMarkProps = {\n  save: SaveState;\n  hasUnsavedChanges: boolean;\n};\n\n/** Only this line reads the clock, and only once a save of this session has a time to count from. */\nfunction SaveMark({ save, hasUnsavedChanges }: SaveMarkProps) {\n  const kind = saveKindOf(save, hasUnsavedChanges);\n  const isCounting = kind === 'saved' && save.at !== null;\n  const now = useNow(SAVED_TICK_MS, isCounting);\n  const line = saveLineOf(kind, save.at, now);\n\n  return (\n    <span className='flex shrink-0 items-center gap-1.5'>\n      <span\n        aria-hidden='true'\n        className={cn(\n          'size-1.5 shrink-0 rounded-full transition-colors duration-200',\n          SAVE_DOT[kind]\n        )}\n      />\n      <WordRoll text={line} />\n    </span>\n  );\n}\n\nfunction countsLineOf(workflow: Workflow) {\n  const counts = countsOf(workflow);\n  const steps = countOf(counts.steps, 'step', 'steps');\n  if (counts.branches === 0) {\n    return steps;\n  }\n  const branches = countOf(counts.branches, 'branch', 'branches');\n  return `${steps}, ${branches}`;\n}\n\nfunction publishWordOf(isLive: boolean) {\n  if (isLive) {\n    return 'Live';\n  }\n  return 'Draft';\n}\n\nconst PUBLISH_WORDS = ['Draft', 'Live'];\n\nfunction trackOf(isLive: boolean) {\n  if (isLive) {\n    return 'bg-success';\n  }\n  return 'bg-foreground/20';\n}\n\nfunction thumbOf(isLive: boolean) {\n  if (isLive) {\n    return 'translate-x-2';\n  }\n  return 'translate-x-0';\n}\n\ntype PublishSwitchProps = {\n  isLive: boolean;\n  onPublish: (isLive: boolean) => void;\n  className?: string;\n};\n\n/** A button that is a switch: it reads Draft, a press makes it read Live, and the tool bar confirms it in words. */\nfunction PublishSwitch({ isLive, onPublish, className }: PublishSwitchProps) {\n  const word = publishWordOf(isLive);\n\n  return (\n    <Button\n      type='button'\n      variant='outline'\n      size='sm'\n      role='switch'\n      aria-checked={isLive}\n      aria-label={`${word}, publish the workflow`}\n      onClick={() => onPublish(!isLive)}\n      className={className}\n    >\n      <span\n        aria-hidden='true'\n        className={cn(\n          'flex h-3 w-5 shrink-0 items-center rounded-full p-0.5 transition-colors duration-200',\n          trackOf(isLive)\n        )}\n      >\n        <span\n          className={cn(\n            'bg-primary-foreground size-2 rounded-full transition-[translate] duration-200 ease-(--ease-out-strong)',\n            thumbOf(isLive)\n          )}\n        />\n      </span>\n      <WordRoll text={word} labels={PUBLISH_WORDS} />\n    </Button>\n  );\n}\n\nfunction runStateOf(isRunning: boolean): MorphState {\n  if (isRunning) {\n    return 'busy';\n  }\n  return 'idle';\n}\n\ntype TopBarProps = {\n  workflow: Workflow;\n  save: SaveState;\n  hasUnsavedChanges: boolean;\n  isLive: boolean;\n  isRunning: boolean;\n  pressed: string | null;\n  canReplay: boolean;\n  onReplay: () => void;\n  onRename: (name: string) => void;\n  onSave: () => void;\n  onPublish: (isLive: boolean) => void;\n  onRun: () => void;\n};\n\n/** Under 640px of its own width, Save and Publish go into one menu and the counts move to a line of their own. */\nexport const TopBar = memo(function TopBar({\n  workflow,\n  save,\n  hasUnsavedChanges,\n  isLive,\n  isRunning,\n  pressed,\n  canReplay,\n  onReplay,\n  onRename,\n  onSave,\n  onPublish,\n  onRun,\n}: TopBarProps) {\n  const isSaving = save.status === 'saving';\n  const canSave = hasUnsavedChanges && !isSaving;\n  const isSavePressed = pressed === 'save';\n\n  return (\n    <header className='@container shrink-0 px-3 py-2'>\n      <div className='flex flex-wrap items-center gap-x-3 gap-y-1'>\n        <div className='flex min-w-0 flex-1 items-center gap-2.5 @[40rem]:max-w-[45%] @[40rem]:flex-none'>\n          <CompanyMark seed={BRAND.name} size='lg' title={BRAND.name} />\n          <h1 className='flex min-w-0 text-sm'>\n            <NameField\n              value={workflow.name}\n              label='Workflow name'\n              action='Rename the workflow'\n              onRename={onRename}\n            />\n          </h1>\n        </div>\n        <p className='text-muted-foreground order-last flex w-full min-w-0 items-center gap-3 ps-9.5 text-xs @[40rem]:order-none @[40rem]:w-auto @[40rem]:flex-1 @[40rem]:ps-0'>\n          <span className='min-w-0 truncate tabular-nums'>\n            <WordRoll text={countsLineOf(workflow)} />\n          </span>\n          <SaveMark save={save} hasUnsavedChanges={hasUnsavedChanges} />\n        </p>\n        <div className='flex shrink-0 items-center gap-1.5'>\n          <ReplayButton\n            isShown={canReplay}\n            onReplay={onReplay}\n            label='Replay'\n          />\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            disabled={!canSave}\n            onClick={onSave}\n            className={cn(\n              'hidden @[40rem]:inline-flex',\n              pressedQuietOf(isSavePressed)\n            )}\n          >\n            Save\n          </Button>\n          <PublishSwitch\n            isLive={isLive}\n            onPublish={onPublish}\n            className='hidden @[40rem]:inline-flex'\n          />\n          <DropdownMenu>\n            <DropdownMenuTrigger\n              render={\n                <Button\n                  type='button'\n                  variant='ghost'\n                  size='icon-sm'\n                  aria-label='More actions'\n                  className={cn(\n                    'text-muted-foreground @[40rem]:hidden',\n                    pressedQuietOf(isSavePressed)\n                  )}\n                />\n              }\n            >\n              <EllipsisIcon />\n            </DropdownMenuTrigger>\n            <DropdownMenuContent align='end' className='w-48'>\n              <DropdownMenuItem disabled={!canSave} onClick={onSave}>\n                Save\n              </DropdownMenuItem>\n              <DropdownMenuCheckboxItem\n                checked={isLive}\n                onCheckedChange={onPublish}\n              >\n                Live\n              </DropdownMenuCheckboxItem>\n            </DropdownMenuContent>\n          </DropdownMenu>\n          <MorphButton\n            type='button'\n            size='sm'\n            state={runStateOf(isRunning)}\n            labels={RUN_LABELS}\n            idleIcon={<PlayIcon />}\n            onClick={onRun}\n            className={pressedSolidOf(pressed === 'run')}\n          />\n        </div>\n      </div>\n    </header>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/top-bar.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/name-field.tsx",
      "content": "'use client';\n\nimport { useRef, useState } from 'react';\n\nimport { PencilIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\ntype RenameInputProps = {\n  value: string;\n  label: string;\n  /** `name` is null when nothing changed. `isFromKey` tells a key ended the edit, so the focus has to be put back. */\n  onSettle: (name: string | null, isFromKey: boolean) => void;\n  className?: string;\n};\n\n/** A name edited where it stands: Enter keeps it, Escape gives it up, leaving the field keeps it. */\nexport function RenameInput({\n  value,\n  label,\n  onSettle,\n  className,\n}: RenameInputProps) {\n  const [draft, setDraft] = useState(value);\n  const isSettled = useRef(false);\n\n  /** The field leaves the page when a key settles it, which blurs it: only the first of the two counts. */\n  function settle(next: string, isFromKey: boolean) {\n    if (isSettled.current) {\n      return;\n    }\n    isSettled.current = true;\n    const name = next.trim();\n    const isNewName = name !== '' && name !== value;\n    if (isNewName) {\n      onSettle(name, isFromKey);\n      return;\n    }\n    onSettle(null, isFromKey);\n  }\n\n  function settleFromKeys(event: React.KeyboardEvent<HTMLInputElement>) {\n    if (event.nativeEvent.isComposing) {\n      return;\n    }\n    if (event.key === 'Enter') {\n      event.preventDefault();\n      settle(draft, true);\n      return;\n    }\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      event.stopPropagation();\n      settle(value, true);\n    }\n  }\n\n  return (\n    <input\n      autoFocus\n      value={draft}\n      aria-label={label}\n      onChange={(event) => setDraft(event.target.value)}\n      onFocus={(event) => event.currentTarget.select()}\n      onKeyDown={settleFromKeys}\n      onBlur={() => settle(draft, false)}\n      className={cn(\n        'bg-card text-foreground ring-ring/25 w-full min-w-0 rounded-sm px-1 text-base ring-[3px] outline-none select-text md:text-[13px]',\n        className\n      )}\n    />\n  );\n}\n\ntype NameFieldProps = {\n  value: string;\n  /** The name of the field: \"Workflow name\". */\n  label: string;\n  /** What the button does, before the name: \"Rename the workflow\". */\n  action: string;\n  onRename: (name: string) => void;\n  className?: string;\n};\n\nexport function NameField({\n  value,\n  label,\n  action,\n  onRename,\n  className,\n}: NameFieldProps) {\n  const [isEditing, setIsEditing] = useState(false);\n  const buttonRef = useRef<HTMLButtonElement>(null);\n\n  function settle(name: string | null, isFromKey: boolean) {\n    setIsEditing(false);\n    if (name !== null) {\n      onRename(name);\n    }\n    if (isFromKey) {\n      requestAnimationFrame(() => buttonRef.current?.focus());\n    }\n  }\n\n  if (isEditing) {\n    return (\n      <RenameInput\n        value={value}\n        label={label}\n        onSettle={settle}\n        className={cn('h-6 font-medium', className)}\n      />\n    );\n  }\n\n  return (\n    <button\n      ref={buttonRef}\n      type='button'\n      aria-label={`${action}: ${value}`}\n      onClick={() => setIsEditing(true)}\n      className={cn(\n        'group/name hover:bg-foreground/5 focus-visible:ring-ring/25 -mx-1 flex h-6 min-w-0 cursor-text items-center gap-1.5 rounded-sm px-1 text-start font-medium outline-none focus-visible:ring-[3px]',\n        className\n      )}\n    >\n      <span className='min-w-0 truncate'>{value}</span>\n      <PencilIcon className='text-muted-foreground size-3 shrink-0 opacity-0 transition-opacity duration-150 group-hover/name:opacity-100 group-focus-visible/name:opacity-100' />\n    </button>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/name-field.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/palette.tsx",
      "content": "'use client';\n\nimport { memo, useId, useState } from 'react';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { PlusIcon, SearchIcon, XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Input } from '@/registry/ndeko/ui/input';\n\nimport {\n  GROUP_WORD,\n  GROUPS,\n  PALETTE,\n  pressKeyOf,\n  type PaletteEntry,\n  type PaletteGroup,\n} from './catalog';\nimport { modelOf } from './data';\nimport { LogicTile, MarkTile } from './node-tile';\nimport { toolOf } from './tools';\n\n/** A row is positioned, so the word kept for screen readers inside it stays inside it. */\nconst ROW =\n  'group/entry relative hover:bg-foreground/5 focus-visible:ring-ring/25 flex h-8 w-full min-w-0 cursor-pointer items-center gap-2 rounded-md px-1.5 text-start outline-none transition-[background-color,scale] duration-150 ease-(--ease-out-strong) focus-visible:ring-[3px] focus-visible:ring-inset active:scale-[0.97]';\n\nfunction matchStartOf(text: string, query: string) {\n  const needle = query.trim().toLowerCase();\n  if (needle === '') {\n    return -1;\n  }\n  const haystack = text.toLowerCase();\n  return haystack.indexOf(needle);\n}\n\nfunction matches(entry: PaletteEntry, query: string) {\n  const isSearching = query.trim() !== '';\n  if (!isSearching) {\n    return true;\n  }\n  return matchStartOf(entry.label, query) >= 0;\n}\n\ntype MatchedTextProps = {\n  text: string;\n  query: string;\n};\n\n/** The part of a name that answers the search is marked, so it is clear why the entry stayed. */\nfunction MatchedText({ text, query }: MatchedTextProps) {\n  const start = matchStartOf(text, query);\n  if (start < 0) {\n    return text;\n  }\n  const needle = query.trim();\n  const end = start + needle.length;\n\n  return (\n    <>\n      {text.slice(0, start)}\n      <mark className='bg-primary/15 text-foreground rounded-[3px]'>\n        {text.slice(start, end)}\n      </mark>\n      {text.slice(end)}\n    </>\n  );\n}\n\nfunction EntryTile({ entry }: { entry: PaletteEntry }) {\n  if (entry.group === 'models') {\n    const model = modelOf(entry.modelId);\n    return <BrandTile brand={model.brand} />;\n  }\n  if (entry.group === 'tools') {\n    const tool = toolOf(entry.toolId);\n    return <MarkTile mark={tool.mark} size='md' />;\n  }\n  return <LogicTile logic={entry.logic} size='md' />;\n}\n\nfunction hintOf(entry: PaletteEntry) {\n  if (entry.group === 'logic') {\n    return entry.hint;\n  }\n  return null;\n}\n\ntype EntryRowProps = {\n  entry: PaletteEntry;\n  query: string;\n  isPressed: boolean;\n  onPick: (entry: PaletteEntry) => void;\n};\n\nfunction EntryRow({ entry, query, isPressed, onPick }: EntryRowProps) {\n  const hint = hintOf(entry);\n\n  return (\n    <button\n      type='button'\n      onClick={() => onPick(entry)}\n      className={cn(ROW, pressedQuietOf(isPressed))}\n    >\n      <EntryTile entry={entry} />\n      <span className='shrink-0 text-[13px] font-medium'>\n        <span className='sr-only'>Add </span>\n        <MatchedText text={entry.label} query={query} />\n      </span>\n      <span className='text-muted-foreground min-w-0 flex-1 truncate text-xs'>\n        {hint}\n      </span>\n      <PlusIcon className='text-muted-foreground size-3.5 shrink-0 opacity-0 transition-opacity duration-150 group-hover/entry:opacity-100 group-focus-visible/entry:opacity-100' />\n    </button>\n  );\n}\n\ntype GroupListProps = {\n  group: PaletteGroup;\n  entries: PaletteEntry[];\n  query: string;\n  pressed: string | null;\n  onPick: (entry: PaletteEntry) => void;\n};\n\nfunction GroupList({ group, entries, query, pressed, onPick }: GroupListProps) {\n  const titleId = useId();\n\n  return (\n    <section aria-labelledby={titleId} className='flex flex-col'>\n      <h3\n        id={titleId}\n        className='text-muted-foreground flex h-6 items-center px-1.5 text-xs font-medium'\n      >\n        {GROUP_WORD[group]}\n      </h3>\n      <ul className='flex flex-col'>\n        {entries.map((entry) => (\n          <li key={entry.id}>\n            <EntryRow\n              entry={entry}\n              query={query}\n              isPressed={pressed === pressKeyOf(entry.id)}\n              onPick={onPick}\n            />\n          </li>\n        ))}\n      </ul>\n    </section>\n  );\n}\n\ntype PaletteProps = {\n  /** Where a picked step goes, as a line under the title: \"After Track the parcel\". */\n  placement: string;\n  pressed: string | null;\n  onPick: (entry: PaletteEntry) => void;\n  className?: string;\n};\n\n/** The steps a flow can be made of. It draws again only when the search, the press or the placement changes. */\nexport const Palette = memo(function Palette({\n  placement,\n  pressed,\n  onPick,\n  className,\n}: PaletteProps) {\n  const [query, setQuery] = useState('');\n  const found = PALETTE.filter((entry) => matches(entry, query));\n  const hasQuery = query !== '';\n  const hasNothing = found.length === 0;\n\n  function clear() {\n    setQuery('');\n  }\n\n  /** Enter in the search adds the first step it found. */\n  function pickFirstFromKeys(event: React.KeyboardEvent<HTMLInputElement>) {\n    const first = found[0];\n    const isPick = event.key === 'Enter' && hasQuery;\n    if (isPick && first) {\n      event.preventDefault();\n      onPick(first);\n    }\n  }\n\n  return (\n    <div className={cn('flex min-h-0 w-full flex-col gap-2', className)}>\n      <div className='flex flex-col px-1.5'>\n        <h2 className='text-[13px] font-semibold'>Add a step</h2>\n        <p className='text-muted-foreground truncate text-xs'>{placement}</p>\n      </div>\n      <div className='relative shrink-0'>\n        <SearchIcon className='text-muted-foreground pointer-events-none absolute start-2 top-1/2 size-3.5 -translate-y-1/2' />\n        <Input\n          type='search'\n          value={query}\n          aria-label='Search the steps'\n          placeholder='Search steps'\n          onChange={(event) => setQuery(event.target.value)}\n          onKeyDown={pickFirstFromKeys}\n          className='ps-7 pe-8'\n        />\n        {hasQuery && (\n          <button\n            type='button'\n            aria-label='Clear the search'\n            onClick={clear}\n            className='text-muted-foreground hover:bg-foreground/[0.07] hover:text-foreground focus-visible:ring-ring/25 absolute end-1 top-1/2 flex size-6 -translate-y-1/2 cursor-pointer items-center justify-center rounded-md outline-none focus-visible:ring-[3px]'\n          >\n            <XIcon className='size-3.5' />\n          </button>\n        )}\n      </div>\n      <div className='relative -mx-1 flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto px-1 pb-1'>\n        {GROUPS.map((group) => {\n          const entries = found.filter((entry) => entry.group === group);\n          if (entries.length === 0) {\n            return null;\n          }\n          return (\n            <GroupList\n              key={group}\n              group={group}\n              entries={entries}\n              query={query}\n              pressed={pressed}\n              onPick={onPick}\n            />\n          );\n        })}\n        {hasNothing && (\n          <div className='flex flex-col items-start gap-2 px-1.5 py-2'>\n            <p className='text-muted-foreground text-[13px] break-words'>\n              {`No step matches \"${query.trim()}\"`}\n            </p>\n            <Button type='button' variant='outline' size='sm' onClick={clear}>\n              Clear the search\n            </Button>\n          </div>\n        )}\n      </div>\n    </div>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/palette.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/canvas-panel.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { PlusIcon, SlidersIcon } from '@/registry/ndeko/lib/icons';\nimport { risePresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport { Canvas } from './canvas';\nimport type { StepActions } from './flow-step';\nimport type { FlowLayout } from './layout';\nimport { MiniMap } from './mini-map';\nimport type { Workflow } from './model';\nimport { hasRun, isBusy } from './run';\nimport { SampleCard } from './sample-card';\nimport { otherSampleOf, sampleOf, type SampleId } from './samples';\nimport type { BuilderState } from './session';\nimport { ToolBar, type HistoryEcho } from './tool-bar';\nimport type { Viewport } from './use-viewport';\n\ntype CanvasPanelProps = StepActions & {\n  state: BuilderState;\n  /** The flow as the canvas shows it: the same object while only the settings of a step change. */\n  shownFlow: Workflow;\n  layout: FlowLayout;\n  viewport: Viewport;\n  pressed: string | null;\n  echo: HistoryEcho;\n  /** False on a page too narrow for it: the mini map only shows from 1024px of the template. */\n  hasMiniMap: boolean;\n  onRename: (id: string, name: string) => void;\n  onUndo: () => void;\n  onRedo: () => void;\n  onUndoNotice: () => void;\n  onUndoKey: () => void;\n  onRedoKey: () => void;\n  onRun: (sampleId: SampleId) => void;\n  onClearRun: () => void;\n  onOpenPalette: () => void;\n  onOpenInspector: () => void;\n};\n\n/**\n * The canvas and what floats over it: the two buttons that open the sheets on a narrow page, the\n * sample email of a run at the top, the tool bar and the mini map at the bottom. What floats lets\n * a drag through to the canvas everywhere but on itself.\n */\nexport function CanvasPanel({\n  state,\n  shownFlow,\n  layout,\n  viewport,\n  pressed,\n  echo,\n  hasMiniMap,\n  onSelect,\n  onRemove,\n  onDuplicate,\n  onInsert,\n  onDecide,\n  onRename,\n  onUndo,\n  onRedo,\n  onUndoNotice,\n  onUndoKey,\n  onRedoKey,\n  onRun,\n  onClearRun,\n  onOpenPalette,\n  onOpenInspector,\n}: CanvasPanelProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const cardPresence = risePresenceOf(shouldReduceMotion);\n  const { run, selectedId } = state;\n  const sample = sampleOf(run.sampleId);\n  const isRunning = isBusy(run);\n  const editCount = state.past.length + state.future.length;\n\n  return (\n    <main className='bg-background @3xl/app:hairline-ring @3xl/app:ring-border @container/canvas relative flex min-w-0 flex-1 overflow-hidden @3xl/app:rounded-xl @3xl/app:shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n      <Canvas\n        workflow={shownFlow}\n        layout={layout}\n        viewport={viewport}\n        run={run}\n        selectedId={selectedId}\n        arrivedId={state.arrivedId}\n        hasEdits={editCount > 0}\n        pressed={pressed}\n        onSelect={onSelect}\n        onRemove={onRemove}\n        onDuplicate={onDuplicate}\n        onRename={onRename}\n        onInsert={onInsert}\n        onDecide={onDecide}\n        onUndo={onUndoKey}\n        onRedo={onRedoKey}\n      />\n      <div className='pointer-events-none absolute inset-x-3 top-3 flex flex-col items-start gap-2'>\n        <div\n          data-canvas-overlay='top'\n          className='flex w-full items-center justify-between gap-2 @5xl/app:hidden'\n        >\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            data-sheet-open='palette'\n            aria-haspopup='dialog'\n            onClick={onOpenPalette}\n            className='pointer-events-auto'\n          >\n            <PlusIcon />\n            Add step\n          </Button>\n          <Button\n            type='button'\n            variant='outline'\n            size='sm'\n            aria-haspopup='dialog'\n            onClick={onOpenInspector}\n            className='pointer-events-auto @3xl/app:hidden'\n          >\n            <SlidersIcon />\n            Step setup\n          </Button>\n        </div>\n        <AnimatePresence initial={false}>\n          {hasRun(run) && (\n            <motion.div\n              key='sample'\n              className='w-full max-w-[19rem]'\n              {...cardPresence}\n            >\n              <SampleCard\n                sample={sample}\n                other={otherSampleOf(sample.id)}\n                isRunning={isRunning}\n                pressed={pressed}\n                onRun={onRun}\n                onClear={onClearRun}\n              />\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n      <div className='pointer-events-none absolute inset-x-3 bottom-3 flex items-end justify-between gap-3'>\n        <ToolBar\n          viewport={viewport}\n          canUndo={state.past.length > 0}\n          canRedo={state.future.length > 0}\n          echo={echo}\n          notice={state.notice}\n          lastRun={state.lastRun}\n          hasRunStarted={hasRun(run)}\n          onUndo={onUndo}\n          onRedo={onRedo}\n          onUndoNotice={onUndoNotice}\n        />\n        {hasMiniMap && (\n          <MiniMap\n            layout={layout}\n            viewport={viewport}\n            run={run}\n            selectedId={selectedId}\n            className='hidden shrink-0 @5xl/app:block'\n          />\n        )}\n      </div>\n    </main>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/canvas-panel.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/canvas.tsx",
      "content": "'use client';\n\nimport {\n  memo,\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from 'react';\n\nimport { ARROW_OFFSET, GRID_CELL } from './canvas-frame';\nimport { EdgeLayer } from './edges';\nimport { outputLabelsOf, placementOf, walkOf } from './flow';\nimport { FlowStep, type StepActions } from './flow-step';\nimport { InsertButton } from './insert-button';\nimport { boxOf, type Box, type FlowLayout, type InsertPoint } from './layout';\nimport type { Workflow } from './model';\nimport { liveIdOf, type Run } from './run';\nimport { sampleOf } from './samples';\nimport { useFocusLater } from './use-focus-later';\nimport type { Viewport } from './use-viewport';\nimport { MAX_ZOOM, MIN_ZOOM } from './viewport';\n\n/** The dots are drawn once on a layer large enough for the smallest zoom, then only moved. */\nconst GRID_SPARE_PX = GRID_CELL * MAX_ZOOM * 2;\n\nconst GRID_SIZE = `calc((100% + ${GRID_SPARE_PX}px) / ${MIN_ZOOM})`;\n\nconst GRID_STYLE = {\n  width: GRID_SIZE,\n  height: GRID_SIZE,\n  backgroundSize: `${GRID_CELL}px ${GRID_CELL}px`,\n};\n\n/**\n * The frame clips its plane without being a scroll container. A step that takes the focus outside\n * a frame that hides its overflow would scroll it, and the plane would no longer sit where the view\n * says. The plane stays hidden until the frame has been measured, so it never shows at the wrong place.\n */\nconst FRAME =\n  'focus-visible:ring-ring/25 relative min-h-0 min-w-0 flex-1 cursor-grab touch-none self-stretch overflow-clip outline-none select-none focus-visible:ring-[3px] focus-visible:ring-inset active:cursor-grabbing [&:not([data-ready])_[data-plane]]:invisible';\n\ntype HistoryKey = 'undo' | 'redo';\n\nfunction historyKeyOf(event: React.KeyboardEvent): HistoryKey | null {\n  const hasModifier = event.ctrlKey || event.metaKey;\n  if (!hasModifier) {\n    return null;\n  }\n  const key = event.key.toLowerCase();\n  if (key === 'y') {\n    return 'redo';\n  }\n  if (key !== 'z') {\n    return null;\n  }\n  if (event.shiftKey) {\n    return 'redo';\n  }\n  return 'undo';\n}\n\n/** A step that waits shows its card beside it: the two have to be in view together. */\nfunction boxWithCard(box: Box, viewport: Viewport): Box {\n  const frame = viewport.frameRef.current;\n  const card = frame?.querySelector<HTMLElement>('[data-approval-card]');\n  if (!frame || !card) {\n    return box;\n  }\n  const view = viewport.store.get();\n  const bounds = frame.getBoundingClientRect();\n  const cardBox = card.getBoundingClientRect();\n  const right = (cardBox.right - bounds.left - view.x) / view.zoom;\n  const bottom = (cardBox.bottom - bounds.top - view.y) / view.zoom;\n  const width = Math.max(box.width, right - box.x);\n  const height = Math.max(box.height, bottom - box.y);\n  return { ...box, width, height };\n}\n\ntype CanvasProps = StepActions & {\n  workflow: Workflow;\n  layout: FlowLayout;\n  viewport: Viewport;\n  run: Run;\n  selectedId: string | null;\n  arrivedId: string | null;\n  hasEdits: boolean;\n  pressed: string | null;\n  onRename: (id: string, name: string) => void;\n  onUndo: () => void;\n  onRedo: () => void;\n};\n\nconst NO_INSERTS: InsertPoint[] = [];\n\n/** The points where a step can be added, by the step the keyboard reaches them after. */\nfunction insertsByStepOf(layout: FlowLayout) {\n  const byStep = new Map<string | null, InsertPoint[]>();\n  for (const insert of layout.inserts) {\n    const held = byStep.get(insert.afterId) ?? [];\n    byStep.set(insert.afterId, [...held, insert]);\n  }\n  return byStep;\n}\n\n/**\n * The plane of the flow in its frame. The frame is a group named after the workflow and the steps\n * are a list of buttons in the order of the flow, so the plan reads without the picture. It draws\n * again when what it shows changes, never while the settings of a step are typed.\n */\nexport const Canvas = memo(function Canvas({\n  workflow,\n  layout,\n  viewport,\n  run,\n  selectedId,\n  arrivedId,\n  hasEdits,\n  pressed,\n  onSelect,\n  onRemove,\n  onDuplicate,\n  onRename,\n  onInsert,\n  onDecide,\n  onUndo,\n  onRedo,\n}: CanvasProps) {\n  const hintId = useId();\n  const { frameRef, planeRef, gridRef } = viewport;\n  const { startPan, pan, endPan, cancelPan, panBy, reveal } = viewport;\n  const { focusNode } = useFocusLater(frameRef);\n  const [renamingId, setRenamingId] = useState<string | null>(null);\n  const latest = useRef({ layout, viewport });\n  const lastToken = useRef(run.token);\n  const placedSteps = useMemo(() => walkOf(workflow), [workflow]);\n  const labels = useMemo(() => outputLabelsOf(workflow), [workflow]);\n  const insertsByStep = useMemo(() => insertsByStepOf(layout), [layout]);\n  const total = placedSteps.length;\n  const sample = sampleOf(run.sampleId);\n  const liveId = liveIdOf(run);\n  const looseInserts = insertsByStep.get(null) ?? NO_INSERTS;\n  const planeStyle = { width: layout.width, height: layout.height };\n\n  useEffect(() => {\n    latest.current = { layout, viewport };\n  });\n\n  /** A session that starts again goes back to the opening view. A new run is followed again. */\n  useEffect(() => {\n    const before = lastToken.current;\n    lastToken.current = run.token;\n    if (before === run.token) {\n      return;\n    }\n    const current = latest.current;\n    if (run.token === 0) {\n      current.viewport.goHome();\n      return;\n    }\n    current.viewport.startFollowing();\n  }, [run.token]);\n\n  useEffect(() => {\n    if (liveId === null) {\n      return;\n    }\n    const current = latest.current;\n    const box = boxOf(current.layout, liveId);\n    if (box) {\n      const both = boxWithCard(box, current.viewport);\n      current.viewport.follow(both);\n    }\n  }, [liveId]);\n\n  useEffect(() => {\n    if (arrivedId === null) {\n      return;\n    }\n    const current = latest.current;\n    const box = boxOf(current.layout, arrivedId);\n    if (box) {\n      current.viewport.reveal(box);\n    }\n  }, [arrivedId]);\n\n  const revealStep = useCallback(\n    (id: string) => {\n      const box = boxOf(layout, id);\n      if (box) {\n        reveal(box);\n      }\n    },\n    [layout, reveal]\n  );\n\n  const settleRename = useCallback(\n    (id: string, name: string | null, isFromKey: boolean) => {\n      setRenamingId(null);\n      if (name !== null) {\n        onRename(id, name);\n      }\n      if (isFromKey) {\n        focusNode(id);\n      }\n    },\n    [onRename, focusNode]\n  );\n\n  function playHistoryKey(key: HistoryKey) {\n    if (key === 'undo') {\n      onUndo();\n      return;\n    }\n    onRedo();\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    const isTyping = event.target instanceof HTMLInputElement;\n    const historyKey = historyKeyOf(event);\n    if (historyKey !== null && !isTyping) {\n      event.preventDefault();\n      playHistoryKey(historyKey);\n      return;\n    }\n    const isOnCanvas = event.target === event.currentTarget;\n    if (!isOnCanvas) {\n      return;\n    }\n    const offset = ARROW_OFFSET[event.key];\n    if (offset) {\n      event.preventDefault();\n      panBy(offset.x, offset.y);\n      return;\n    }\n    const isRemoveKey = event.key === 'Delete' || event.key === 'Backspace';\n    if (isRemoveKey && selectedId !== null) {\n      event.preventDefault();\n      onRemove(selectedId);\n    }\n  }\n\n  return (\n    <div\n      ref={frameRef}\n      role='group'\n      tabIndex={0}\n      data-canvas-frame\n      aria-label={`${workflow.name}, workflow canvas`}\n      aria-describedby={hintId}\n      onKeyDown={handleKeys}\n      onPointerDown={startPan}\n      onPointerMove={pan}\n      onPointerUp={endPan}\n      onPointerCancel={cancelPan}\n      className={FRAME}\n    >\n      <div\n        ref={gridRef}\n        aria-hidden='true'\n        style={GRID_STYLE}\n        className='pointer-events-none absolute top-0 left-0 origin-top-left bg-[radial-gradient(circle_at_1px_1px,color-mix(in_oklab,var(--foreground)_16%,transparent)_1px,transparent_1.5px)]'\n      />\n      <div\n        ref={planeRef}\n        data-plane\n        style={planeStyle}\n        className='absolute top-0 left-0 origin-top-left'\n      >\n        <EdgeLayer\n          layout={layout}\n          run={run}\n          labels={labels}\n          arrivedId={arrivedId}\n          hasEdits={hasEdits}\n        />\n        <ol aria-label='Steps, in the order of the flow'>\n          {placedSteps.map((placed) => {\n            const stepId = placed.step.id;\n            const box = boxOf(layout, stepId);\n            if (!box) {\n              return null;\n            }\n            return (\n              <FlowStep\n                key={stepId}\n                placed={placed}\n                total={total}\n                box={box}\n                inserts={insertsByStep.get(stepId) ?? NO_INSERTS}\n                workflow={workflow}\n                stepRun={run.steps[stepId]}\n                sample={sample}\n                isSelected={selectedId === stepId}\n                isArrived={arrivedId === stepId}\n                isRenaming={renamingId === stepId}\n                pressed={pressed}\n                onSelect={onSelect}\n                onRemove={onRemove}\n                onDuplicate={onDuplicate}\n                onInsert={onInsert}\n                onDecide={onDecide}\n                onReveal={revealStep}\n                onStartRename={setRenamingId}\n                onSettleRename={settleRename}\n              />\n            );\n          })}\n        </ol>\n        {looseInserts.map((insert) => (\n          <InsertButton\n            key={insert.id}\n            x={insert.x}\n            y={insert.y}\n            placement={placementOf(workflow, insert.at)}\n            onPick={(entry) => onInsert(insert.at, entry)}\n          />\n        ))}\n      </div>\n      {total === 0 && (\n        <p className='text-muted-foreground pointer-events-none absolute inset-x-6 top-1/2 text-center text-[13px]'>\n          This workflow has no step. Add one from the palette, or with the plus\n          above\n        </p>\n      )}\n      <p id={hintId} className='sr-only'>\n        The arrow keys move the canvas. Tab walks the steps in the order of the\n        flow, Enter opens the setup of a step, Delete removes it\n      </p>\n    </div>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/canvas.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/canvas-frame.ts",
      "content": "import type { Box, FlowLayout, Point } from './layout';\nimport {\n  gridOffsetOf,\n  homeOf,\n  shiftInto,\n  shownOf,\n  type Insets,\n  type Size,\n  type View,\n} from './viewport';\n\nexport const GRID_CELL = 20;\n\n/** What is kept in view around a step the canvas pans to, so the edge that leaves it shows too. */\nconst REVEAL_MARGIN = 20;\n\nconst PAN_STEP = 56;\n\n/** An arrow key moves the view that way, so what is on the canvas slides the other way. */\nexport const ARROW_OFFSET: Partial<Record<string, Point>> = {\n  ArrowLeft: { x: PAN_STEP, y: 0 },\n  ArrowRight: { x: -PAN_STEP, y: 0 },\n  ArrowUp: { x: 0, y: PAN_STEP },\n  ArrowDown: { x: 0, y: -PAN_STEP },\n};\n\nexport const SAFE_MARGIN = 16;\n\n/** A press on one of these is a press on the interface, not on the empty canvas behind it. */\nconst SOLID = 'button, a, input, textarea, select, label, [data-solid]';\n\nexport function flowSizeOf(layout: FlowLayout): Size {\n  return { width: layout.width, height: layout.height };\n}\n\n/**\n * A layer drawn outside the frame (the menu of a step, the palette of a plus) still sends its\n * presses to the frame through React. Taken for the canvas, its item would lose its click to a pan.\n */\nexport function isOnBackground(frame: Element, target: EventTarget) {\n  if (!(target instanceof Element)) {\n    return false;\n  }\n  if (!frame.contains(target)) {\n    return false;\n  }\n  return target.closest(SOLID) === null;\n}\n\nfunction overlayOf(frame: HTMLElement, name: string) {\n  const panel = frame.parentElement;\n  const overlay = panel?.querySelector<HTMLElement>(\n    `[data-canvas-overlay=\"${name}\"]`\n  );\n  return overlay?.getBoundingClientRect();\n}\n\n/** The tool bar and the row of buttons cover the frame: a view that shows the whole flow leaves them their room. */\nexport function insetsOf(frame: HTMLElement): Insets {\n  const bounds = frame.getBoundingClientRect();\n  const topBox = overlayOf(frame, 'top');\n  const bottomBox = overlayOf(frame, 'bottom');\n  const insets = { top: SAFE_MARGIN, bottom: SAFE_MARGIN };\n  if (topBox && topBox.height > 0) {\n    insets.top = topBox.bottom - bounds.top + SAFE_MARGIN;\n  }\n  if (bottomBox && bottomBox.height > 0) {\n    insets.bottom = bounds.bottom - bottomBox.top + SAFE_MARGIN;\n  }\n  return insets;\n}\n\n/** Only what floats above or under a span counts: a card beside it hides nothing of it. */\nexport function clearSpanOf(frame: HTMLElement, left: number, right: number) {\n  const bounds = frame.getBoundingClientRect();\n  const panel = frame.parentElement;\n  const overlays = panel?.querySelectorAll<HTMLElement>(\n    '[data-canvas-overlay]'\n  );\n  const middle = bounds.height / 2;\n  let top = SAFE_MARGIN;\n  let bottom = bounds.height - SAFE_MARGIN;\n  for (const overlay of overlays ?? []) {\n    const box = overlay.getBoundingClientRect();\n    const boxLeft = box.left - bounds.left;\n    const boxRight = box.right - bounds.left;\n    const boxTop = box.top - bounds.top;\n    const boxBottom = box.bottom - bounds.top;\n    const isEmpty = box.width === 0 || box.height === 0;\n    const isBeside = boxRight < left || boxLeft > right;\n    if (isEmpty || isBeside) {\n      continue;\n    }\n    const boxMiddle = (boxTop + boxBottom) / 2;\n    const isAbove = boxMiddle < middle;\n    if (isAbove) {\n      top = Math.max(top, boxBottom + SAFE_MARGIN);\n    } else {\n      bottom = Math.min(bottom, boxTop - SAFE_MARGIN);\n    }\n  }\n  return { top, bottom };\n}\n\n/** How far the view moves so a step shows clear of what floats over the frame. Null when it already does. */\nexport function revealShiftOf(\n  frame: HTMLElement,\n  size: Size,\n  view: View,\n  box: Box\n): Point | null {\n  const shown = shownOf(view, {\n    left: box.x - REVEAL_MARGIN,\n    top: box.y - REVEAL_MARGIN,\n    right: box.x + box.width + REVEAL_MARGIN,\n    bottom: box.y + box.height + REVEAL_MARGIN,\n  });\n  const mostRight = size.width - SAFE_MARGIN;\n  const shiftX = shiftInto(shown.left, shown.right, SAFE_MARGIN, mostRight);\n  const movedLeft = shown.left + shiftX;\n  const movedRight = shown.right + shiftX;\n  const clear = clearSpanOf(frame, movedLeft, movedRight);\n  const shiftY = shiftInto(shown.top, shown.bottom, clear.top, clear.bottom);\n  const isInView = shiftX === 0 && shiftY === 0;\n  if (isInView) {\n    return null;\n  }\n  return { x: shiftX, y: shiftY };\n}\n\nexport function writeView(\n  view: View,\n  plane: HTMLElement | null,\n  grid: HTMLElement | null\n) {\n  const x = Math.round(view.x);\n  const y = Math.round(view.y);\n  if (plane) {\n    const zoom = String(view.zoom);\n    plane.style.transform = `translate(${x}px, ${y}px) scale(${zoom})`;\n    plane.style.setProperty('--zoom', zoom);\n  }\n  if (grid) {\n    const offset = gridOffsetOf({ x, y, zoom: view.zoom }, GRID_CELL);\n    grid.style.transform = `translate(${offset.x}px, ${offset.y}px) scale(${view.zoom})`;\n  }\n}\n\nexport function homeViewOf(frame: HTMLElement, size: Size, layout: FlowLayout) {\n  const flow = flowSizeOf(layout);\n  const insets = insetsOf(frame);\n  return homeOf(size, flow, layout.trunkX, insets);\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/canvas-frame.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/use-viewport.ts",
      "content": "'use client';\n\nimport {\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type RefObject,\n} from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nimport {\n  flowSizeOf,\n  homeViewOf,\n  insetsOf,\n  isOnBackground,\n  revealShiftOf,\n  writeView,\n} from './canvas-frame';\nimport type { Box, FlowLayout } from './layout';\nimport {\n  clampedTo,\n  createViewStore,\n  fitOf,\n  steppedZoom,\n  zoomedAround,\n  type Size,\n  type View,\n  type ViewStore,\n} from './viewport';\n\n/** A press that moved less than this was a click on the empty canvas, not a drag. */\nconst DRAG_SLACK_PX = 4;\n\nconst WHEEL_ZOOM_RATE = 0.0015;\n\ntype Drag = {\n  pointerId: number;\n  startX: number;\n  startY: number;\n  view: View;\n  hasMoved: boolean;\n};\n\nfunction moveTo(store: ViewStore, view: View, shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    store.jump(view);\n    return;\n  }\n  store.glide(view);\n}\n\nexport type Viewport = {\n  frameRef: RefObject<HTMLDivElement | null>;\n  planeRef: RefObject<HTMLDivElement | null>;\n  gridRef: RefObject<HTMLDivElement | null>;\n  store: ViewStore;\n  zoomBy: (direction: 1 | -1) => void;\n  fit: () => void;\n  goHome: () => void;\n  panBy: (offsetX: number, offsetY: number) => void;\n  show: (view: View) => void;\n  reveal: (box: Box) => void;\n  follow: (box: Box) => void;\n  startFollowing: () => void;\n  frameSizeOf: () => Size;\n  startPan: (event: React.PointerEvent<HTMLDivElement>) => void;\n  pan: (event: React.PointerEvent<HTMLDivElement>) => void;\n  endPan: (event: React.PointerEvent<HTMLDivElement>) => void;\n  cancelPan: () => void;\n};\n\n/**\n * Pan and zoom of the canvas: one transform on the plane, written straight to the element. A drag\n * on the empty canvas pans, Ctrl or Cmd with the wheel zooms round the pointer, and the view keeps\n * its opening position through a change of size for as long as nothing has moved it.\n * `onWheelZoom` hears the one gesture a demonstration cannot see by itself: a wheel is neither a\n * press nor a key.\n */\nexport function useViewport(\n  layout: FlowLayout,\n  onBackgroundPress: () => void,\n  onWheelZoom: () => void\n): Viewport {\n  const [store] = useState(createViewStore);\n  const frameRef = useRef<HTMLDivElement>(null);\n  const planeRef = useRef<HTMLDivElement>(null);\n  const gridRef = useRef<HTMLDivElement>(null);\n  const frameSize = useRef<Size>({ width: 0, height: 0 });\n  const latestLayout = useRef(layout);\n  const isAtHome = useRef(true);\n  const followsRun = useRef(true);\n  const drag = useRef<Drag | null>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const { width, height, trunkX } = layout;\n\n  useEffect(() => {\n    latestLayout.current = layout;\n  });\n\n  useEffect(() => {\n    function write() {\n      const view = store.get();\n      writeView(view, planeRef.current, gridRef.current);\n    }\n    write();\n    const unsubscribe = store.subscribe(write);\n    return () => {\n      unsubscribe();\n      store.stop();\n    };\n  }, [store]);\n\n  useLayoutEffect(() => {\n    const frame = frameRef.current;\n    if (!frame) {\n      return;\n    }\n    const observer = new ResizeObserver(([entry]) => {\n      const box = entry.contentRect;\n      const size = { width: box.width, height: box.height };\n      frameSize.current = size;\n      if (isAtHome.current) {\n        const home = homeViewOf(frame, size, latestLayout.current);\n        store.jump(home);\n      } else {\n        const flow = flowSizeOf(latestLayout.current);\n        const kept = clampedTo(store.rest(), size, flow);\n        store.jump(kept);\n      }\n      frame.dataset.ready = 'true';\n    });\n    observer.observe(frame);\n    return () => observer.disconnect();\n  }, [store]);\n\n  useEffect(() => {\n    const frame = frameRef.current;\n    const size = frameSize.current;\n    const isMeasured = size.width > 0;\n    const canGoHome = isMeasured && isAtHome.current;\n    if (!frame || !canGoHome) {\n      return;\n    }\n    const home = homeViewOf(frame, size, latestLayout.current);\n    moveTo(store, home, shouldReduceMotion);\n  }, [store, width, height, trunkX, shouldReduceMotion]);\n\n  useEffect(() => {\n    const frame = frameRef.current;\n    if (!frame) {\n      return;\n    }\n    function zoomFromWheel(event: WheelEvent) {\n      const isZoomGesture = event.ctrlKey || event.metaKey;\n      if (!isZoomGesture || !frame) {\n        return;\n      }\n      event.preventDefault();\n      const bounds = frame.getBoundingClientRect();\n      const anchor = {\n        x: event.clientX - bounds.left,\n        y: event.clientY - bounds.top,\n      };\n      const current = store.rest();\n      const exponent = -event.deltaY * WHEEL_ZOOM_RATE;\n      const zoom = current.zoom * Math.exp(exponent);\n      const zoomed = zoomedAround(current, zoom, anchor);\n      const flow = flowSizeOf(latestLayout.current);\n      const kept = clampedTo(zoomed, frameSize.current, flow);\n      isAtHome.current = false;\n      followsRun.current = false;\n      store.jump(kept);\n      onWheelZoom();\n    }\n    frame.addEventListener('wheel', zoomFromWheel, { passive: false });\n    return () => frame.removeEventListener('wheel', zoomFromWheel);\n  }, [store, onWheelZoom]);\n\n  /** Once a person moves the view it is theirs: it stops following the run and stays where they put it. */\n  const takeOver = useCallback(() => {\n    isAtHome.current = false;\n    followsRun.current = false;\n  }, []);\n\n  const keptInFrame = useCallback(\n    (view: View) => {\n      const flow = flowSizeOf(layout);\n      return clampedTo(view, frameSize.current, flow);\n    },\n    [layout]\n  );\n\n  const zoomBy = useCallback(\n    (direction: 1 | -1) => {\n      const size = frameSize.current;\n      const centre = { x: size.width / 2, y: size.height / 2 };\n      const current = store.rest();\n      const zoom = steppedZoom(current.zoom, direction);\n      const zoomed = zoomedAround(current, zoom, centre);\n      const kept = keptInFrame(zoomed);\n      takeOver();\n      moveTo(store, kept, shouldReduceMotion);\n    },\n    [store, keptInFrame, takeOver, shouldReduceMotion]\n  );\n\n  const fit = useCallback(() => {\n    const frame = frameRef.current;\n    if (!frame) {\n      return;\n    }\n    const insets = insetsOf(frame);\n    const flow = flowSizeOf(layout);\n    const fitted = fitOf(frameSize.current, flow, insets);\n    takeOver();\n    moveTo(store, fitted, shouldReduceMotion);\n  }, [store, layout, takeOver, shouldReduceMotion]);\n\n  const goHome = useCallback(() => {\n    const frame = frameRef.current;\n    isAtHome.current = true;\n    followsRun.current = true;\n    if (!frame || frameSize.current.width === 0) {\n      return;\n    }\n    const home = homeViewOf(frame, frameSize.current, layout);\n    moveTo(store, home, shouldReduceMotion);\n  }, [store, layout, shouldReduceMotion]);\n\n  const show = useCallback(\n    (view: View) => {\n      const kept = keptInFrame(view);\n      takeOver();\n      store.jump(kept);\n    },\n    [store, keptInFrame, takeOver]\n  );\n\n  const panBy = useCallback(\n    (offsetX: number, offsetY: number) => {\n      const current = store.rest();\n      const moved = {\n        x: current.x + offsetX,\n        y: current.y + offsetY,\n        zoom: current.zoom,\n      };\n      show(moved);\n    },\n    [store, show]\n  );\n\n  const reveal = useCallback(\n    (box: Box) => {\n      const frame = frameRef.current;\n      const size = frameSize.current;\n      if (!frame || size.width === 0) {\n        return;\n      }\n      const current = store.rest();\n      const shift = revealShiftOf(frame, size, current, box);\n      if (shift === null) {\n        return;\n      }\n      const moved = {\n        x: current.x + shift.x,\n        y: current.y + shift.y,\n        zoom: current.zoom,\n      };\n      const kept = keptInFrame(moved);\n      isAtHome.current = false;\n      moveTo(store, kept, shouldReduceMotion);\n    },\n    [store, keptInFrame, shouldReduceMotion]\n  );\n\n  const follow = useCallback(\n    (box: Box) => {\n      if (followsRun.current) {\n        reveal(box);\n      }\n    },\n    [reveal]\n  );\n\n  const startFollowing = useCallback(() => {\n    followsRun.current = true;\n  }, []);\n\n  const frameSizeOf = useCallback(() => frameSize.current, []);\n\n  const startPan = useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      const isMainButton = event.button === 0;\n      const isOnCanvas = isOnBackground(event.currentTarget, event.target);\n      if (!isMainButton || !isOnCanvas) {\n        return;\n      }\n      event.currentTarget.setPointerCapture(event.pointerId);\n      drag.current = {\n        pointerId: event.pointerId,\n        startX: event.clientX,\n        startY: event.clientY,\n        view: store.rest(),\n        hasMoved: false,\n      };\n    },\n    [store]\n  );\n\n  const pan = useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      const current = drag.current;\n      if (current?.pointerId !== event.pointerId) {\n        return;\n      }\n      const offsetX = event.clientX - current.startX;\n      const offsetY = event.clientY - current.startY;\n      const distance = Math.hypot(offsetX, offsetY);\n      const isStill = !current.hasMoved && distance < DRAG_SLACK_PX;\n      if (isStill) {\n        return;\n      }\n      current.hasMoved = true;\n      show({\n        x: current.view.x + offsetX,\n        y: current.view.y + offsetY,\n        zoom: current.view.zoom,\n      });\n    },\n    [show]\n  );\n\n  const endPan = useCallback(\n    (event: React.PointerEvent<HTMLDivElement>) => {\n      const current = drag.current;\n      if (current?.pointerId !== event.pointerId) {\n        return;\n      }\n      drag.current = null;\n      if (!current.hasMoved) {\n        onBackgroundPress();\n      }\n    },\n    [onBackgroundPress]\n  );\n\n  const cancelPan = useCallback(() => {\n    drag.current = null;\n  }, []);\n\n  /** One object for as long as the layout stays: the canvas, the tool bar and the mini map hold still while a step is typed into. */\n  return useMemo(\n    () => ({\n      frameRef,\n      planeRef,\n      gridRef,\n      store,\n      zoomBy,\n      fit,\n      goHome,\n      panBy,\n      show,\n      reveal,\n      follow,\n      startFollowing,\n      frameSizeOf,\n      startPan,\n      pan,\n      endPan,\n      cancelPan,\n    }),\n    [\n      store,\n      zoomBy,\n      fit,\n      goHome,\n      panBy,\n      show,\n      reveal,\n      follow,\n      startFollowing,\n      frameSizeOf,\n      startPan,\n      pan,\n      endPan,\n      cancelPan,\n    ]\n  );\n}\n\nfunction serverZoomPercent() {\n  return 100;\n}\n\n/** The zoom as a whole percentage. Only the text that shows it reads this, so a drag draws nothing else again. */\nexport function useZoomPercent(store: ViewStore) {\n  function readPercent() {\n    const view = store.rest();\n    return Math.round(view.zoom * 100);\n  }\n  return useSyncExternalStore(store.subscribe, readPercent, serverZoomPercent);\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/use-viewport.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/viewport.ts",
      "content": "import type { Point } from './layout';\n\n/** Where the plane of the canvas stands in its frame: one translation and one scale. */\nexport type View = {\n  x: number;\n  y: number;\n  zoom: number;\n};\n\nexport type Size = {\n  width: number;\n  height: number;\n};\n\nexport type Rect = {\n  left: number;\n  top: number;\n  right: number;\n  bottom: number;\n};\n\n/** The part of the frame that toolbars and cards cover at its top and at its bottom. */\nexport type Insets = {\n  top: number;\n  bottom: number;\n};\n\nexport const MIN_ZOOM = 0.4;\n\nexport const MAX_ZOOM = 1.6;\n\nconst ZOOM_STEP = 0.1;\n\n/** Under this size the names on the cards stop being readable, so a canvas never opens smaller. */\nconst HOME_MIN_ZOOM = 0.8;\n\n/** What stays of the flow in the frame however far it is panned, so it cannot be lost. */\nconst KEPT_IN_FRAME = 72;\n\nconst GLIDE_MS = 320;\n\n/** A step counts as a tenth already reached when the zoom sits this close to it. */\nconst STEP_SLACK = 0.001;\n\nconst REST_VIEW: View = { x: 0, y: 0, zoom: 1 };\n\nfunction clampedZoom(zoom: number) {\n  const capped = Math.min(MAX_ZOOM, zoom);\n  return Math.max(MIN_ZOOM, capped);\n}\n\n/** The whole flow, centred in the free part of the frame, never larger than life. */\nexport function fitOf(frame: Size, flow: Size, insets: Insets): View {\n  const freeHeight = frame.height - insets.top - insets.bottom;\n  const zoomAcross = frame.width / flow.width;\n  const zoomDown = freeHeight / flow.height;\n  const fitting = Math.min(zoomAcross, zoomDown, 1);\n  const zoom = clampedZoom(fitting);\n  const spareWidth = frame.width - flow.width * zoom;\n  const spareHeight = freeHeight - flow.height * zoom;\n  const offsetDown = Math.max(0, spareHeight / 2);\n  return { x: spareWidth / 2, y: insets.top + offsetDown, zoom };\n}\n\n/** What a canvas opens on: the whole flow when it stays readable, else the top of the trunk at a readable size. */\nexport function homeOf(\n  frame: Size,\n  flow: Size,\n  trunkX: number,\n  insets: Insets\n): View {\n  const fit = fitOf(frame, flow, insets);\n  if (fit.zoom >= HOME_MIN_ZOOM) {\n    return fit;\n  }\n  const middle = frame.width / 2;\n  const x = middle - trunkX * HOME_MIN_ZOOM;\n  return { x, y: insets.top, zoom: HOME_MIN_ZOOM };\n}\n\n/** A new zoom that keeps the point under `anchor` where it is. */\nexport function zoomedAround(view: View, zoom: number, anchor: Point): View {\n  const next = clampedZoom(zoom);\n  const ratio = next / view.zoom;\n  const x = anchor.x - (anchor.x - view.x) * ratio;\n  const y = anchor.y - (anchor.y - view.y) * ratio;\n  return { x, y, zoom: next };\n}\n\n/** The next tenth above or under a zoom: 88% goes to 90% or to 80%. */\nexport function steppedZoom(zoom: number, direction: 1 | -1) {\n  const tenths = zoom / ZOOM_STEP;\n  if (direction === 1) {\n    const reached = Math.floor(tenths + STEP_SLACK);\n    const above = (reached + 1) * ZOOM_STEP;\n    return clampedZoom(above);\n  }\n  const reached = Math.ceil(tenths - STEP_SLACK);\n  const under = (reached - 1) * ZOOM_STEP;\n  return clampedZoom(under);\n}\n\nfunction clampedBetween(value: number, least: number, most: number) {\n  const capped = Math.min(most, value);\n  return Math.max(least, capped);\n}\n\nexport function clampedTo(view: View, frame: Size, flow: Size): View {\n  const leastX = KEPT_IN_FRAME - flow.width * view.zoom;\n  const leastY = KEPT_IN_FRAME - flow.height * view.zoom;\n  const mostX = frame.width - KEPT_IN_FRAME;\n  const mostY = frame.height - KEPT_IN_FRAME;\n  const x = clampedBetween(view.x, leastX, mostX);\n  const y = clampedBetween(view.y, leastY, mostY);\n  return { x, y, zoom: view.zoom };\n}\n\nexport function shownOf(view: View, box: Rect): Rect {\n  return {\n    left: view.x + box.left * view.zoom,\n    top: view.y + box.top * view.zoom,\n    right: view.x + box.right * view.zoom,\n    bottom: view.y + box.bottom * view.zoom,\n  };\n}\n\n/** How far to move along one axis so a span fits between two bounds. Its start wins when it cannot fit. */\nexport function shiftInto(\n  start: number,\n  end: number,\n  least: number,\n  most: number\n) {\n  if (start < least) {\n    return least - start;\n  }\n  if (end > most) {\n    return most - end;\n  }\n  return 0;\n}\n\nfunction positiveModulo(value: number, size: number) {\n  const remainder = value % size;\n  return (remainder + size) % size;\n}\n\n/**\n * The grid starts one tile before the frame and slides by less than a tile, so it never shows an\n * edge and its dots stay on the same points of the plane at every zoom.\n */\nexport function gridOffsetOf(view: View, cell: number) {\n  const scaled = cell * view.zoom;\n  const x = positiveModulo(view.x, scaled);\n  const y = positiveModulo(view.y, scaled);\n  return { x: x - scaled, y: y - scaled };\n}\n\nfunction easedOut(progress: number) {\n  const rest = 1 - progress;\n  return 1 - rest * rest * rest * rest;\n}\n\nfunction between(from: number, to: number, share: number) {\n  return from + (to - from) * share;\n}\n\nexport type ViewStore = {\n  /** Where the plane stands now, in the middle of a glide included. */\n  get: () => View;\n  /** Where it will rest: the end of the glide, or where it stands. */\n  rest: () => View;\n  jump: (view: View) => void;\n  glide: (view: View) => void;\n  subscribe: (listener: () => void) => () => void;\n  stop: () => void;\n};\n\n/**\n * The view lives outside React: it changes on every frame of a drag or a glide, and only the\n * elements it moves are written to. A frame is asked for while a glide lasts, never at rest.\n */\nexport function createViewStore(): ViewStore {\n  const listeners = new Set<() => void>();\n  let view = REST_VIEW;\n  let target = REST_VIEW;\n  let origin = REST_VIEW;\n  let startedAt = 0;\n  let frame = 0;\n\n  function notify() {\n    for (const listener of listeners) {\n      listener();\n    }\n  }\n\n  function stop() {\n    cancelAnimationFrame(frame);\n    frame = 0;\n  }\n\n  function tick(now: number) {\n    const elapsed = now - startedAt;\n    const progress = Math.min(1, elapsed / GLIDE_MS);\n    const share = easedOut(progress);\n    view = {\n      x: between(origin.x, target.x, share),\n      y: between(origin.y, target.y, share),\n      zoom: between(origin.zoom, target.zoom, share),\n    };\n    notify();\n    if (progress >= 1) {\n      frame = 0;\n      return;\n    }\n    frame = requestAnimationFrame(tick);\n  }\n\n  return {\n    get: () => view,\n    rest: () => target,\n    jump(next) {\n      stop();\n      view = next;\n      target = next;\n      notify();\n    },\n    glide(next) {\n      stop();\n      origin = view;\n      target = next;\n      startedAt = performance.now();\n      frame = requestAnimationFrame(tick);\n      notify();\n    },\n    subscribe(listener) {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n    stop,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/viewport.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/layout.ts",
      "content": "import { edgeIdOf } from './flow';\nimport type {\n  BranchOutput,\n  BranchStep,\n  InsertAt,\n  Step,\n  Workflow,\n} from './model';\n\nexport const NODE_WIDTH = 208;\n\nexport const NODE_HEIGHT = 52;\n\nconst COLUMN_GAP = 24;\n\nconst ROW_GAP = 36;\n\nconst PADDING = 32;\n\n/** Under a branch: the line that carries its outputs sideways, then down each column a label, an insert point and the first step. */\nconst FORK_BUS = 14;\n\nconst FORK_LABEL = 18;\n\nconst FORK_INSERT = 42;\n\nconst FORK_STEP = 56;\n\n/** Where outputs join: the line that brings them back under the branch, then the step they join at. */\nconst JOIN_BUS = 30;\n\nconst JOIN_STEP = 30;\n\nconst INSERT_DROP = 15;\n\nconst TAIL_DROP = 28;\n\nconst ELBOW_RADIUS = 8;\n\nexport type Point = {\n  x: number;\n  y: number;\n};\n\nexport type Box = {\n  id: string;\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n};\n\nexport type FlowEdge = {\n  id: string;\n  fromId: string;\n  /** Null for the edge that ends the flow. */\n  toId: string | null;\n  outputId: string | null;\n  /** Where the label of an output sits. Its text is not here: a layout reads only the structure of the flow. */\n  labelAt: Point | null;\n  /** The corners the path turns at, from its first point to its last: what travels along the edge follows them. */\n  points: Point[];\n  path: string;\n};\n\nexport type InsertPoint = {\n  id: string;\n  at: InsertAt;\n  x: number;\n  y: number;\n  /** The step read just before this point in the order of the flow: the keyboard reaches the point right after it. */\n  afterId: string | null;\n};\n\nexport type FlowLayout = {\n  width: number;\n  height: number;\n  trunkX: number;\n  /** In the order of the flow, the outputs of a branch left to right. */\n  boxes: Box[];\n  edges: FlowEdge[];\n  inserts: InsertPoint[];\n};\n\n/** An edge that has left its step and has not reached the next one yet. */\ntype OpenEnd = {\n  fromId: string;\n  outputId: string | null;\n  labelAt: Point | null;\n  points: Point[];\n};\n\ntype Draft = {\n  boxes: Box[];\n  edges: FlowEdge[];\n  inserts: InsertPoint[];\n  lastId: string | null;\n};\n\ntype Placement = {\n  ends: OpenEnd[];\n  bottom: number;\n};\n\n/** A list is as wide as its widest step, and a branch as wide as its outputs side by side. */\nfunction widthOfList(steps: Step[]): number {\n  let width = NODE_WIDTH;\n  for (const step of steps) {\n    const stepWidth = widthOfStep(step);\n    width = Math.max(width, stepWidth);\n  }\n  return width;\n}\n\nfunction widthOfStep(step: Step): number {\n  if (step.kind !== 'branch') {\n    return NODE_WIDTH;\n  }\n  let width = 0;\n  for (const output of step.outputs) {\n    width += widthOfList(output.steps);\n  }\n  const gaps = step.outputs.length - 1;\n  return width + gaps * COLUMN_GAP;\n}\n\nfunction distanceOf(from: Point, to: Point) {\n  const offsetX = to.x - from.x;\n  const offsetY = to.y - from.y;\n  return Math.hypot(offsetX, offsetY);\n}\n\nfunction towards(from: Point, to: Point, distance: number): Point {\n  const length = distanceOf(from, to);\n  if (length === 0) {\n    return from;\n  }\n  const share = distance / length;\n  const offsetX = (to.x - from.x) * share;\n  const offsetY = (to.y - from.y) * share;\n  return { x: from.x + offsetX, y: from.y + offsetY };\n}\n\n/** An elbow: the line stops short of the corner and a curve takes the turn, never over more than half a side. */\nfunction elbowOf(before: Point, corner: Point, after: Point) {\n  const sideIn = distanceOf(before, corner);\n  const sideOut = distanceOf(corner, after);\n  const shortSide = Math.min(sideIn, sideOut);\n  const radius = Math.min(ELBOW_RADIUS, shortSide / 2);\n  const start = towards(corner, before, radius);\n  const end = towards(corner, after, radius);\n  return `L ${start.x} ${start.y} Q ${corner.x} ${corner.y} ${end.x} ${end.y}`;\n}\n\nfunction pathOf(points: Point[]) {\n  const first = points[0];\n  const last = points[points.length - 1];\n  const parts = [`M ${first.x} ${first.y}`];\n  for (let index = 1; index < points.length - 1; index += 1) {\n    const before = points[index - 1];\n    const corner = points[index];\n    const after = points[index + 1];\n    const elbow = elbowOf(before, corner, after);\n    parts.push(elbow);\n  }\n  parts.push(`L ${last.x} ${last.y}`);\n  return parts.join(' ');\n}\n\n/** Straight down when the target sits under the end, else down to a line just above the target and across to it. */\nfunction routeTo(end: OpenEnd, target: Point): Point[] {\n  const last = end.points[end.points.length - 1];\n  if (last.x === target.x) {\n    return [...end.points, target];\n  }\n  const busY = target.y - JOIN_STEP;\n  const down = { x: last.x, y: busY };\n  const across = { x: target.x, y: busY };\n  return [...end.points, down, across, target];\n}\n\nfunction closeEnd(\n  draft: Draft,\n  end: OpenEnd,\n  toId: string | null,\n  target: Point\n) {\n  const points = routeTo(end, target);\n  draft.edges.push({\n    id: edgeIdOf(end.fromId, end.outputId),\n    fromId: end.fromId,\n    toId,\n    outputId: end.outputId,\n    labelAt: end.labelAt,\n    points,\n    path: pathOf(points),\n  });\n}\n\nfunction insertIdOf(at: InsertAt) {\n  if (at.at === 'after') {\n    return `after:${at.stepId}`;\n  }\n  if (at.at === 'first') {\n    return `first:${at.branchId}:${at.outputId}`;\n  }\n  return 'end';\n}\n\nfunction addInsert(draft: Draft, at: InsertAt, point: Point) {\n  draft.inserts.push({\n    id: insertIdOf(at),\n    at,\n    x: point.x,\n    y: point.y,\n    afterId: draft.lastId,\n  });\n}\n\n/** The edge of an output leaves the branch, runs along the line under it and stops above its own column. */\nfunction forkEndOf(\n  branch: BranchStep,\n  output: BranchOutput,\n  from: Point,\n  columnX: number\n): OpenEnd {\n  const busY = from.y + FORK_BUS;\n  const points = [from, { x: from.x, y: busY }];\n  if (columnX !== from.x) {\n    points.push({ x: columnX, y: busY });\n  }\n  return {\n    fromId: branch.id,\n    outputId: output.id,\n    labelAt: { x: columnX, y: busY + FORK_LABEL },\n    points,\n  };\n}\n\nfunction placeBranch(draft: Draft, branch: BranchStep, from: Point): Placement {\n  const busY = from.y + FORK_BUS;\n  const firstTop = busY + FORK_STEP;\n  const ends: OpenEnd[] = [];\n  const total = widthOfStep(branch);\n  let left = from.x - total / 2;\n  let bottom = firstTop;\n  for (const output of branch.outputs) {\n    const width = widthOfList(output.steps);\n    const columnX = left + width / 2;\n    const end = forkEndOf(branch, output, from, columnX);\n    const first: InsertAt = {\n      at: 'first',\n      branchId: branch.id,\n      outputId: output.id,\n    };\n    addInsert(draft, first, { x: columnX, y: busY + FORK_INSERT });\n    const placed = placeList(draft, output.steps, columnX, firstTop, [end]);\n    ends.push(...placed.ends);\n    bottom = Math.max(bottom, placed.bottom);\n    left += width + COLUMN_GAP;\n  }\n  return { ends, bottom };\n}\n\n/**\n * Places a list of steps down one column. `incoming` are the edges that reach its first step. It\n * returns the edges that leave it, for the step that comes next in the list above.\n */\nfunction placeList(\n  draft: Draft,\n  steps: Step[],\n  centerX: number,\n  top: number,\n  incoming: OpenEnd[],\n  isTrunk = false\n): Placement {\n  let ends = incoming;\n  let cursor = top;\n  let bottom = top;\n  let previous: Step | null = null;\n  for (const [index, step] of steps.entries()) {\n    const target = { x: centerX, y: cursor };\n    if (previous?.kind === 'branch') {\n      const join: InsertAt = { at: 'after', stepId: previous.id };\n      addInsert(draft, join, { x: centerX, y: cursor - INSERT_DROP });\n    }\n    for (const end of ends) {\n      closeEnd(draft, end, step.id, target);\n    }\n    draft.boxes.push({\n      id: step.id,\n      x: centerX - NODE_WIDTH / 2,\n      y: cursor,\n      width: NODE_WIDTH,\n      height: NODE_HEIGHT,\n    });\n    draft.lastId = step.id;\n    const stepBottom = cursor + NODE_HEIGHT;\n    const exit = { x: centerX, y: stepBottom };\n    if (step.kind === 'branch') {\n      const fork = placeBranch(draft, step, exit);\n      ends = fork.ends;\n      bottom = fork.bottom;\n      cursor = fork.bottom + JOIN_BUS + JOIN_STEP;\n    } else {\n      const isLast = index === steps.length - 1;\n      addOwnInsert(draft, step, exit, isLast, isTrunk);\n      ends = [openEndOf(step, exit)];\n      bottom = stepBottom;\n      cursor = stepBottom + ROW_GAP;\n    }\n    previous = step;\n  }\n  return { ends, bottom };\n}\n\nfunction openEndOf(step: Step, exit: Point): OpenEnd {\n  return {\n    fromId: step.id,\n    outputId: null,\n    labelAt: null,\n    points: [exit],\n  };\n}\n\n/**\n * Between two steps the point sits halfway. Under the last step of an output it sits close to the\n * step, since the line then turns towards the join. The last step of the trunk has none: the point\n * that ends the flow stands for it.\n */\nfunction addOwnInsert(\n  draft: Draft,\n  step: Step,\n  exit: Point,\n  isLast: boolean,\n  isTrunk: boolean\n) {\n  const after: InsertAt = { at: 'after', stepId: step.id };\n  if (!isLast) {\n    addInsert(draft, after, { x: exit.x, y: exit.y + ROW_GAP / 2 });\n    return;\n  }\n  if (!isTrunk) {\n    addInsert(draft, after, { x: exit.x, y: exit.y + INSERT_DROP });\n  }\n}\n\nfunction tailYOf(bottom: number, last: Step | undefined) {\n  if (!last) {\n    return bottom + INSERT_DROP;\n  }\n  if (last.kind === 'branch') {\n    return bottom + JOIN_BUS + JOIN_STEP;\n  }\n  return bottom + TAIL_DROP;\n}\n\n/** The whole canvas from the data and nothing else: where each step sits, how each edge runs, where a step can be added. */\nexport function layoutOf(workflow: Workflow): FlowLayout {\n  const draft: Draft = { boxes: [], edges: [], inserts: [], lastId: null };\n  const inner = widthOfList(workflow.steps);\n  const width = inner + PADDING * 2;\n  const trunkX = width / 2;\n  const placed = placeList(draft, workflow.steps, trunkX, PADDING, [], true);\n  const last = workflow.steps.at(-1);\n  const tail = { x: trunkX, y: tailYOf(placed.bottom, last) };\n  for (const end of placed.ends) {\n    closeEnd(draft, end, null, tail);\n  }\n  addInsert(draft, { at: 'end' }, tail);\n  return {\n    width,\n    height: tail.y + PADDING,\n    trunkX,\n    boxes: draft.boxes,\n    edges: draft.edges,\n    inserts: draft.inserts,\n  };\n}\n\nexport function boxOf(layout: FlowLayout, id: string) {\n  return layout.boxes.find((box) => box.id === id);\n}\n\nexport function lengthOf(points: Point[]) {\n  let length = 0;\n  for (let index = 1; index < points.length; index += 1) {\n    const from = points[index - 1];\n    const to = points[index];\n    length += distanceOf(from, to);\n  }\n  return length;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/layout.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/flow-step.tsx",
      "content": "'use client';\n\nimport { memo } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { ApprovalCard } from './approval-card';\nimport type { PaletteEntry } from './catalog';\nimport { nodePressKeyOf, placementOf, type Placed } from './flow';\nimport { InsertButton } from './insert-button';\nimport { NODE_HEIGHT, NODE_WIDTH, type Box, type InsertPoint } from './layout';\nimport type { InsertAt, Step, Workflow } from './model';\nimport { NodeCard } from './node-card';\nimport type { Decision, StepRun } from './run';\nimport type { Sample } from './samples';\n\nfunction askingOf(step: Step, isWaiting: boolean) {\n  if (step.kind !== 'approval' || !isWaiting) {\n    return null;\n  }\n  return step;\n}\n\n/** The card of a step and what hangs from it take their size from the layout, so the two never disagree. */\ntype StepStyle = React.CSSProperties & {\n  '--step-width': string;\n  '--step-height': string;\n};\n\n/** The step that waits sits above the ones under it, so its card covers them and not the other way round. */\nfunction layerOf(isWaiting: boolean) {\n  if (isWaiting) {\n    return 'z-10';\n  }\n  return 'z-0';\n}\n\nexport type StepActions = {\n  onSelect: (id: string, isFromKeyboard: boolean) => void;\n  onRemove: (id: string) => void;\n  onDuplicate: (id: string) => void;\n  onInsert: (at: InsertAt, entry: PaletteEntry) => void;\n  onDecide: (decision: Decision) => void;\n};\n\ntype FlowStepProps = StepActions & {\n  placed: Placed;\n  total: number;\n  box: Box;\n  inserts: InsertPoint[];\n  workflow: Workflow;\n  /** The mark of this step in the run: a beat that touches another step leaves this one as it is. */\n  stepRun: StepRun | undefined;\n  sample: Sample;\n  isSelected: boolean;\n  isArrived: boolean;\n  isRenaming: boolean;\n  pressed: string | null;\n  onReveal: (id: string) => void;\n  onStartRename: (id: string) => void;\n  onSettleRename: (id: string, name: string | null, isFromKey: boolean) => void;\n};\n\n/**\n * One step of the list, with what the keyboard reaches right after it: its card when it waits for\n * a person, then the points where a step can be added before the next one.\n */\nexport const FlowStep = memo(function FlowStep({\n  placed,\n  total,\n  box,\n  inserts,\n  workflow,\n  stepRun,\n  sample,\n  isSelected,\n  isArrived,\n  isRenaming,\n  pressed,\n  onSelect,\n  onRemove,\n  onDuplicate,\n  onInsert,\n  onDecide,\n  onReveal,\n  onStartRename,\n  onSettleRename,\n}: FlowStepProps) {\n  const { step } = placed;\n  const isWaiting = stepRun?.status === 'waiting';\n  const asking = askingOf(step, isWaiting);\n  const placeStyle: StepStyle = {\n    translate: `${box.x}px ${box.y}px`,\n    '--step-width': `${NODE_WIDTH}px`,\n    '--step-height': `${NODE_HEIGHT}px`,\n  };\n\n  return (\n    <li\n      style={placeStyle}\n      className={cn(\n        'absolute top-0 left-0 transition-[translate] duration-300 ease-(--ease-out-strong)',\n        layerOf(isWaiting)\n      )}\n    >\n      <NodeCard\n        step={step}\n        position={placed.position}\n        total={total}\n        branchLabel={placed.branchLabel}\n        stepRun={stepRun}\n        isSelected={isSelected}\n        isArrived={isArrived}\n        isPressed={pressed === nodePressKeyOf(step.id)}\n        isRenaming={isRenaming}\n        onSelect={onSelect}\n        onReveal={onReveal}\n        onRemove={onRemove}\n        onDuplicate={onDuplicate}\n        onStartRename={onStartRename}\n        onSettleRename={onSettleRename}\n      />\n      {asking && (\n        <ApprovalCard\n          step={asking}\n          sample={sample}\n          workflowName={workflow.name}\n          pressed={pressed}\n          onDecide={onDecide}\n        />\n      )}\n      {inserts.map((insert) => (\n        <InsertButton\n          key={insert.id}\n          x={insert.x - box.x}\n          y={insert.y - box.y}\n          placement={placementOf(workflow, insert.at)}\n          onPick={(entry) => onInsert(insert.at, entry)}\n        />\n      ))}\n    </li>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/flow-step.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/node-card.tsx",
      "content": "'use client';\n\nimport { memo, useRef } from 'react';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport {\n  CopyPlusIcon,\n  EllipsisIcon,\n  PencilIcon,\n  Trash2Icon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\n\nimport { KIND_WORD, type Step } from './model';\nimport { RenameInput } from './name-field';\nimport { StepTile } from './node-tile';\nimport type { StepRun, StepStatus } from './run';\nimport { StateMark, stateWordsOf } from './state-mark';\n\nconst CARD =\n  'bg-card relative flex h-(--step-height) w-(--step-width) items-center rounded-xl transition-[translate,box-shadow,opacity,scale,background-color] duration-200 ease-(--ease-out-strong)';\n\n/** A step that was just added grows into its place. The others were there already and do not play it. */\nconst ARRIVAL = 'starting:scale-95 starting:opacity-0';\n\nconst RESTING = 'shadow-[0_1px_2px_rgb(0_0_0/0.04)]';\n\n/** A step at work lifts by a pixel, under a hairline of the primary colour. */\nconst LIFTED = '-translate-y-px shadow-[0_4px_10px_-3px_rgb(0_0_0/0.14)]';\n\n/** A note of the run takes the place of the kind with a fade. The kind itself is simply there when the page loads. */\nconst NOTE_FADE = 'transition-opacity duration-300 starting:opacity-0';\n\nfunction isAtWork(status: StepStatus | undefined) {\n  return status === 'running' || status === 'retrying';\n}\n\nfunction ringOf(isSelected: boolean, status: StepStatus | undefined) {\n  if (isSelected) {\n    return 'ring-primary/60 ring-2';\n  }\n  if (isAtWork(status)) {\n    return 'hairline-ring ring-primary';\n  }\n  if (status === 'failed') {\n    return 'hairline-ring ring-destructive/50';\n  }\n  if (status === 'waiting') {\n    return 'hairline-ring ring-warning/70';\n  }\n  return 'hairline-ring ring-border';\n}\n\nfunction liftOf(status: StepStatus | undefined) {\n  if (isAtWork(status)) {\n    return LIFTED;\n  }\n  return RESTING;\n}\n\nfunction noteFadeOf(hasNote: boolean) {\n  if (hasNote) {\n    return NOTE_FADE;\n  }\n  return undefined;\n}\n\nfunction standingOf(status: StepStatus | undefined) {\n  if (status === 'skipped') {\n    return 'opacity-50';\n  }\n  return 'opacity-100';\n}\n\nfunction arrivalOf(isArrived: boolean) {\n  if (isArrived) {\n    return ARRIVAL;\n  }\n  return undefined;\n}\n\nfunction overlineToneOf(status: StepStatus | undefined) {\n  if (status === 'failed') {\n    return 'text-destructive-ink';\n  }\n  if (status === 'waiting') {\n    return 'text-warning-foreground';\n  }\n  return 'text-muted-foreground';\n}\n\n/** \"Tool: Find the order, step 4 of 10, Refund branch, done in 0.7s\". */\nfunction nameOf(\n  step: Step,\n  position: number,\n  total: number,\n  branchLabel: string | null,\n  stepRun: StepRun | undefined\n) {\n  const parts = [\n    `${KIND_WORD[step.kind]}: ${step.name}`,\n    `step ${position} of ${total}`,\n  ];\n  if (branchLabel !== null) {\n    parts.push(`${branchLabel} branch`);\n  }\n  const state = stateWordsOf(stepRun);\n  parts.push(state);\n  return parts.join(', ');\n}\n\ntype NodeMenuProps = {\n  name: string;\n  onRename: () => void;\n  onDuplicate: () => void;\n  onRemove: () => void;\n};\n\nfunction NodeMenu({ name, onRename, onDuplicate, onRemove }: NodeMenuProps) {\n  const hasActed = useRef(false);\n\n  function choose(action: () => void) {\n    hasActed.current = true;\n    action();\n  }\n\n  /** After an action the focus goes where the action leads: the field, the copy, the step before. Closing without one gives it back to the button. */\n  function returnsFocus() {\n    const wasActed = hasActed.current;\n    hasActed.current = false;\n    return !wasActed;\n  }\n\n  return (\n    <DropdownMenu>\n      <DropdownMenuTrigger\n        render={\n          <Button\n            type='button'\n            variant='ghost'\n            size='icon-sm'\n            aria-label={`Actions for ${name}`}\n            className='text-muted-foreground absolute end-1.5 bottom-1.5 size-6'\n          />\n        }\n      >\n        <EllipsisIcon className='size-3.5' />\n      </DropdownMenuTrigger>\n      <DropdownMenuContent\n        align='start'\n        className='w-44'\n        finalFocus={returnsFocus}\n      >\n        <DropdownMenuItem onClick={() => choose(onRename)}>\n          <PencilIcon />\n          Rename\n        </DropdownMenuItem>\n        <DropdownMenuItem onClick={() => choose(onDuplicate)}>\n          <CopyPlusIcon />\n          Duplicate\n        </DropdownMenuItem>\n        <DropdownMenuSeparator />\n        <DropdownMenuItem\n          variant='destructive'\n          onClick={() => choose(onRemove)}\n        >\n          <Trash2Icon />\n          Delete\n        </DropdownMenuItem>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\ntype NodeCardProps = {\n  step: Step;\n  position: number;\n  total: number;\n  branchLabel: string | null;\n  stepRun: StepRun | undefined;\n  isSelected: boolean;\n  isArrived: boolean;\n  isPressed: boolean;\n  isRenaming: boolean;\n  onSelect: (id: string, isFromKeyboard: boolean) => void;\n  onReveal: (id: string) => void;\n  onRemove: (id: string) => void;\n  onDuplicate: (id: string) => void;\n  onStartRename: (id: string) => void;\n  onSettleRename: (id: string, name: string | null, isFromKey: boolean) => void;\n};\n\nexport const NodeCard = memo(function NodeCard({\n  step,\n  position,\n  total,\n  branchLabel,\n  stepRun,\n  isSelected,\n  isArrived,\n  isPressed,\n  isRenaming,\n  onSelect,\n  onReveal,\n  onRemove,\n  onDuplicate,\n  onStartRename,\n  onSettleRename,\n}: NodeCardProps) {\n  const status = stepRun?.status;\n  const note = stepRun?.note ?? null;\n  const overline = note ?? KIND_WORD[step.kind];\n  const name = nameOf(step, position, total, branchLabel, stepRun);\n\n  /** A click from the keyboard carries no press of a pointer: that is how Enter and Space are told apart from a tap. */\n  function select(event: React.MouseEvent<HTMLButtonElement>) {\n    const isFromKeyboard = event.detail === 0;\n    event.currentTarget.focus();\n    onSelect(step.id, isFromKeyboard);\n  }\n\n  /** A step reached with the keyboard may sit outside the frame: the canvas brings it into view. A press of a pointer never moves it. */\n  function revealFromKeys(event: React.FocusEvent<HTMLButtonElement>) {\n    if (event.currentTarget.matches(':focus-visible')) {\n      onReveal(step.id);\n    }\n  }\n\n  function handleKeys(event: React.KeyboardEvent<HTMLButtonElement>) {\n    const isRemoveKey = event.key === 'Delete' || event.key === 'Backspace';\n    if (isRemoveKey) {\n      event.preventDefault();\n      onRemove(step.id);\n      return;\n    }\n    if (event.key === 'F2') {\n      event.preventDefault();\n      onStartRename(step.id);\n    }\n  }\n\n  if (isRenaming) {\n    return (\n      <div\n        data-solid\n        className={cn(CARD, 'ring-primary/60 gap-2.5 px-2.5 ring-2')}\n      >\n        <StepTile step={step} />\n        <span className='flex min-w-0 flex-1 flex-col'>\n          <span className='text-muted-foreground text-[11px] leading-4'>\n            {KIND_WORD[step.kind]}\n          </span>\n          <RenameInput\n            value={step.name}\n            label={`Name of the step ${step.name}`}\n            onSettle={(next, isFromKey) =>\n              onSettleRename(step.id, next, isFromKey)\n            }\n            className='-mx-1 h-5 font-medium'\n          />\n        </span>\n      </div>\n    );\n  }\n\n  return (\n    <div\n      data-solid\n      className={cn(\n        CARD,\n        ringOf(isSelected, status),\n        liftOf(status),\n        standingOf(status),\n        arrivalOf(isArrived),\n        pressedQuietOf(isPressed)\n      )}\n    >\n      <button\n        type='button'\n        data-node={step.id}\n        aria-label={name}\n        aria-pressed={isSelected}\n        aria-keyshortcuts='F2 Delete'\n        onClick={select}\n        onFocus={revealFromKeys}\n        onKeyDown={handleKeys}\n        className='focus-visible:ring-ring focus-visible:ring-offset-background flex h-full min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-xl px-2.5 text-start outline-none focus-visible:ring-2 focus-visible:ring-offset-2'\n      >\n        <StepTile step={step} />\n        <span className='flex min-w-0 flex-1 flex-col'>\n          <span className='flex h-4 items-center gap-1.5'>\n            <span\n              key={overline}\n              className={cn(\n                'min-w-0 flex-1 truncate text-[11px] leading-4',\n                overlineToneOf(status),\n                noteFadeOf(note !== null)\n              )}\n            >\n              {overline}\n            </span>\n            <StateMark stepRun={stepRun} />\n          </span>\n          <span className='truncate pe-6 text-[13px] leading-5 font-medium'>\n            {step.name}\n          </span>\n        </span>\n      </button>\n      <NodeMenu\n        name={step.name}\n        onRename={() => onStartRename(step.id)}\n        onDuplicate={() => onDuplicate(step.id)}\n        onRemove={() => onRemove(step.id)}\n      />\n    </div>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/node-card.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/node-tile.tsx",
      "content": "import { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport {\n  GitBranchIcon,\n  HourglassIcon,\n  RepeatIcon,\n  ShieldCheckIcon,\n  type Icon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { CompanyMark } from '@/registry/ndeko/ui/company-mark';\nimport { MeshTile } from '@/registry/ndeko/ui/mesh-tile';\n\nimport type { LogicKind } from './catalog';\nimport { isProductStep, type Step } from './model';\nimport { toolOf, type ToolMark } from './tools';\n\nexport type TileSize = 'md' | 'lg';\n\nconst KEYCAP_CLASS: Record<TileSize, string> = {\n  md: 'size-5 rounded-[5px]',\n  lg: 'size-7 rounded-md',\n};\n\nconst GLYPH_CLASS: Record<TileSize, string> = {\n  md: 'size-3',\n  lg: 'size-4',\n};\n\nconst LOGIC_ICON: Record<LogicKind, Icon> = {\n  branch: GitBranchIcon,\n  approval: ShieldCheckIcon,\n  wait: HourglassIcon,\n  loop: RepeatIcon,\n};\n\ntype LogicTileProps = {\n  logic: LogicKind;\n  size?: TileSize;\n};\n\n/** A step of logic belongs to no product, so it wears a key cap with the icon of what it does. */\nexport function LogicTile({ logic, size = 'lg' }: LogicTileProps) {\n  const Glyph = LOGIC_ICON[logic];\n\n  return (\n    <span\n      aria-hidden='true'\n      className={cn(\n        'keycap-3d text-muted-foreground inline-flex shrink-0 items-center justify-center',\n        KEYCAP_CLASS[size]\n      )}\n    >\n      <Glyph className={GLYPH_CLASS[size]} />\n    </span>\n  );\n}\n\ntype MarkTileProps = {\n  mark: ToolMark;\n  size?: TileSize;\n};\n\nexport function MarkTile({ mark, size = 'lg' }: MarkTileProps) {\n  if (mark.kind === 'brand') {\n    return <BrandTile brand={mark.brand} size={size} />;\n  }\n  return <CompanyMark seed={mark.seed} size={size} />;\n}\n\ntype StepTileProps = {\n  step: Step;\n  size?: TileSize;\n};\n\n/** An agent wears a picture in its series colour, a step of a product the mark of the product. */\nexport function StepTile({ step, size = 'lg' }: StepTileProps) {\n  if (step.kind === 'agent') {\n    const color = seriesColorOf(step.series);\n    return <MeshTile seed={step.seed} color={color} size={size} />;\n  }\n  if (isProductStep(step)) {\n    const tool = toolOf(step.tool.toolId);\n    return <MarkTile mark={tool.mark} size={size} />;\n  }\n  return <LogicTile logic={step.kind} size={size} />;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/node-tile.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/state-mark.tsx",
      "content": "'use client';\n\nimport { motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { formatDuration } from '@/registry/ndeko/lib/agent-run';\nimport {\n  CircleCheckIcon,\n  CircleDashedIcon,\n  CircleXIcon,\n  HandIcon,\n  LoaderCircleIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { EASE_IN_OUT_STRONG } from '@/registry/ndeko/lib/motion-presets';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\n\nimport type { StepRun, StepStatus } from './run';\n\nconst STATUS_WORD: Record<StepStatus, string> = {\n  running: 'running',\n  retrying: 'trying again',\n  failed: 'failed',\n  waiting: 'waiting for you',\n  done: 'done',\n  denied: 'denied by you',\n  skipped: 'skipped',\n};\n\nconst ONE_TURN = { rotate: 360 };\n\nconst TURN_TIMING = { duration: 0.8, ease: EASE_IN_OUT_STRONG };\n\n/** The mark turns once when a step starts, then holds still: nothing keeps spinning while a step only waits to end. */\nfunction TurningMark() {\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  if (shouldReduceMotion) {\n    return <LoaderCircleIcon className='text-primary-ink size-4' />;\n  }\n  return (\n    <motion.span\n      initial={{ rotate: 0 }}\n      animate={ONE_TURN}\n      transition={TURN_TIMING}\n      className='inline-flex'\n    >\n      <LoaderCircleIcon className='text-primary-ink size-4' />\n    </motion.span>\n  );\n}\n\nfunction StatusGlyph({ status }: { status: StepStatus }) {\n  const isAtWork = status === 'running' || status === 'retrying';\n  if (isAtWork) {\n    return <TurningMark />;\n  }\n  if (status === 'failed') {\n    return <CircleXIcon className='text-destructive-ink size-4' />;\n  }\n  if (status === 'waiting') {\n    return <HandIcon className='text-warning-foreground size-4' />;\n  }\n  if (status === 'done') {\n    return <CircleCheckIcon className='text-success-foreground size-4' />;\n  }\n  if (status === 'denied') {\n    return <CircleXIcon className='text-muted-foreground size-4' />;\n  }\n  return <CircleDashedIcon className='text-muted-foreground size-4' />;\n}\n\n/** A step that is done shows how long it took, one that was left out says so. */\nfunction captionOf(stepRun: StepRun) {\n  if (stepRun.status === 'skipped') {\n    return 'Skipped';\n  }\n  const hasDuration = stepRun.status === 'done' && stepRun.ms > 0;\n  if (hasDuration) {\n    return formatDuration(stepRun.ms);\n  }\n  return null;\n}\n\ntype StateMarkProps = {\n  stepRun: StepRun | undefined;\n};\n\n/** Drawn for the eye only: the button of the step says the same state in words. */\nexport function StateMark({ stepRun }: StateMarkProps) {\n  if (!stepRun) {\n    return null;\n  }\n  const caption = captionOf(stepRun);\n\n  return (\n    <span aria-hidden='true' className='flex shrink-0 items-center gap-1'>\n      {caption && (\n        <span className='text-muted-foreground text-[11px] leading-4 tabular-nums'>\n          {caption}\n        </span>\n      )}\n      <Swap swapKey={stepRun.status} className='size-4'>\n        <StatusGlyph status={stepRun.status} />\n      </Swap>\n    </span>\n  );\n}\n\nfunction timedWordOf(word: string, ms: number) {\n  if (ms <= 0) {\n    return word;\n  }\n  const duration = formatDuration(ms);\n  return `${word} in ${duration}`;\n}\n\nexport function stateWordsOf(stepRun: StepRun | undefined) {\n  if (!stepRun) {\n    return 'not run yet';\n  }\n  const word = STATUS_WORD[stepRun.status];\n  if (stepRun.status === 'failed') {\n    const reason = stepRun.note ?? 'no answer';\n    return `${word}: ${reason}`;\n  }\n  if (stepRun.status !== 'done') {\n    return word;\n  }\n  const timed = timedWordOf(word, stepRun.ms);\n  if (stepRun.note) {\n    return `${timed}. ${stepRun.note}`;\n  }\n  return timed;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/state-mark.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/edges.tsx",
      "content": "'use client';\n\nimport { motion, type Transition } from 'motion/react';\nimport { memo, useState } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { lengthOf, type FlowEdge, type FlowLayout, type Point } from './layout';\nimport { TRAVEL_MS, type Run } from './run';\n\ntype EdgeTone = 'idle' | 'taken' | 'leftOut';\n\nconst TONE_CLASS: Record<EdgeTone, string> = {\n  idle: 'opacity-100',\n  taken: 'opacity-100',\n  leftOut: 'opacity-35',\n};\n\n/** The stroke shows from its first point to its last, once: the path is one dash that slides into place. */\nconst DRAWN =\n  '[stroke-dasharray:1] [stroke-dashoffset:0] transition-[stroke-dashoffset] ease-linear starting:[stroke-dashoffset:1]';\n\n/** The colour of the run fills an edge in the time the dot takes to go along it. */\nconst FILL_STYLE = { transitionDuration: `${TRAVEL_MS}ms` };\n\n/** An edge whose route changed comes back in place with a fade, while the steps travel to their new places. */\nconst REDRAWN = 'transition-opacity delay-150 duration-300 starting:opacity-0';\n\nconst LABEL_TONE: Record<EdgeTone, string> = {\n  idle: 'bg-background text-muted-foreground ring-border',\n  taken:\n    'bg-[color-mix(in_oklab,var(--primary)_10%,var(--background))] text-primary-ink ring-primary/40',\n  leftOut: 'bg-background text-muted-foreground ring-border opacity-50',\n};\n\n/** An edge is left out when the run never came to it: its step was skipped, or its branch took another output. */\nfunction isLeftOut(run: Run, edge: FlowEdge) {\n  const fromStatus = run.steps[edge.fromId]?.status;\n  const wasStopped = fromStatus === 'skipped' || fromStatus === 'denied';\n  if (wasStopped) {\n    return true;\n  }\n  const choice = run.choices[edge.fromId];\n  const isOutput = edge.outputId !== null;\n  const hasChosen = choice !== undefined;\n  const tookAnother = choice !== edge.outputId;\n  return isOutput && hasChosen && tookAnother;\n}\n\nfunction toneOf(run: Run, edge: FlowEdge): EdgeTone {\n  if (run.taken.includes(edge.id)) {\n    return 'taken';\n  }\n  if (isLeftOut(run, edge)) {\n    return 'leftOut';\n  }\n  return 'idle';\n}\n\nfunction entranceOf(isNew: boolean, isRedrawn: boolean) {\n  if (isNew) {\n    return cn(DRAWN, 'duration-500');\n  }\n  if (isRedrawn) {\n    return REDRAWN;\n  }\n  return undefined;\n}\n\n/** Only the run fills an edge. An edge an edit draws again while it is taken shows its colour with the redraw. */\nfunction fillEntranceOf(isFillInherited: boolean) {\n  if (isFillInherited) {\n    return REDRAWN;\n  }\n  return DRAWN;\n}\n\ntype EdgePathProps = {\n  edge: FlowEdge;\n  tone: EdgeTone;\n  isNew: boolean;\n  isRedrawn: boolean;\n};\n\n/** Drawn again only when its own tone or route changes: a beat of the run touches one or two edges. */\nconst EdgePath = memo(function EdgePath({\n  edge,\n  tone,\n  isNew,\n  isRedrawn,\n}: EdgePathProps) {\n  const isTaken = tone === 'taken';\n  const [isFillInherited, setIsFillInherited] = useState(isTaken);\n  const hasLostFill = isFillInherited && !isTaken;\n  if (hasLostFill) {\n    setIsFillInherited(false);\n  }\n\n  return (\n    <g\n      className={cn('transition-opacity duration-300', TONE_CLASS[tone])}\n      fill='none'\n    >\n      <path\n        d={edge.path}\n        pathLength={1}\n        strokeWidth={1.5}\n        className={cn('stroke-foreground/25', entranceOf(isNew, isRedrawn))}\n      />\n      {isTaken && (\n        <path\n          d={edge.path}\n          pathLength={1}\n          strokeWidth={2}\n          style={FILL_STYLE}\n          className={cn('stroke-primary', fillEntranceOf(isFillInherited))}\n        />\n      )}\n    </g>\n  );\n});\n\ntype EdgeLabelProps = {\n  label: string;\n  at: Point;\n  tone: EdgeTone;\n};\n\n/** An output whose name was erased still has to read as an output. */\nfunction shownLabelOf(label: string) {\n  if (label.trim() === '') {\n    return 'Unnamed';\n  }\n  return label;\n}\n\n/** The label hangs from a point without size, so centring it never widens the plane. */\nconst EdgeLabel = memo(function EdgeLabel({ label, at, tone }: EdgeLabelProps) {\n  const anchorStyle = { translate: `${at.x}px ${at.y}px` };\n\n  return (\n    <span\n      className='absolute top-0 left-0 size-0 transition-[translate] duration-300 ease-(--ease-out-strong)'\n      style={anchorStyle}\n    >\n      <span\n        className={cn(\n          'hairline-ring absolute top-0 left-0 flex h-[18px] max-w-44 -translate-x-1/2 -translate-y-1/2 items-center rounded-md px-1.5 text-[11px] font-medium whitespace-nowrap transition-[color,background-color,opacity] duration-300',\n          LABEL_TONE[tone]\n        )}\n      >\n        <span className='truncate'>{shownLabelOf(label)}</span>\n      </span>\n    </span>\n  );\n});\n\n/** The share of the way reached at each corner of an edge, so the dot keeps one speed along all of it. */\nfunction sharesOf(points: Point[]) {\n  const total = lengthOf(points);\n  const shares = [0];\n  let travelled = 0;\n  for (let index = 1; index < points.length; index += 1) {\n    const side = [points[index - 1], points[index]];\n    travelled += lengthOf(side);\n    const share = travelled / total;\n    shares.push(share);\n  }\n  return shares;\n}\n\nconst DOT_FADE = [0, 1, 1, 0];\n\nconst DOT_FADE_TIMES = [0, 0.12, 0.85, 1];\n\nconst TRAVEL_SECONDS = TRAVEL_MS / 1000;\n\ntype DotRoute = {\n  first: Point;\n  xs: number[];\n  ys: number[];\n  times: number[];\n};\n\nfunction routeOf(edge: FlowEdge): DotRoute {\n  return {\n    first: edge.points[0],\n    xs: edge.points.map((point) => point.x),\n    ys: edge.points.map((point) => point.y),\n    times: sharesOf(edge.points),\n  };\n}\n\n/**\n * One dot goes along the edge the run just took, once. It moves with a transform and leaves no loop\n * behind. It keeps the route of that moment: an edit that moves the edge later does not send it again.\n */\nfunction TravelDot({ edge }: { edge: FlowEdge }) {\n  const [route] = useState(() => routeOf(edge));\n  const { first, xs, ys, times } = route;\n  const glide: Transition = {\n    duration: TRAVEL_SECONDS,\n    ease: 'linear',\n    times,\n  };\n  const fade: Transition = {\n    duration: TRAVEL_SECONDS,\n    times: DOT_FADE_TIMES,\n  };\n\n  return (\n    <motion.span\n      aria-hidden='true'\n      initial={{ x: first.x, y: first.y, opacity: 0 }}\n      animate={{ x: xs, y: ys, opacity: DOT_FADE }}\n      transition={{ x: glide, y: glide, opacity: fade }}\n      className='bg-primary pointer-events-none absolute top-0 left-0 -mt-1 -ml-1 size-2 rounded-full'\n    />\n  );\n}\n\nfunction touches(edge: FlowEdge, stepId: string | null) {\n  if (stepId === null) {\n    return false;\n  }\n  return edge.fromId === stepId || edge.toId === stepId;\n}\n\nfunction canTravel(edge: FlowEdge | undefined): edge is FlowEdge {\n  if (!edge) {\n    return false;\n  }\n  return lengthOf(edge.points) > 0;\n}\n\ntype EdgeLayerProps = {\n  layout: FlowLayout;\n  run: Run;\n  /** The text on the edge of each output of a branch, by the id of that edge. */\n  labels: Partial<Record<string, string>>;\n  /** The step that was just added: the edges that touch it draw themselves. */\n  arrivedId: string | null;\n  /** True once the flow was edited. Before that, edges are simply there: nothing plays when the page loads. */\n  hasEdits: boolean;\n};\n\nexport const EdgeLayer = memo(function EdgeLayer({\n  layout,\n  run,\n  labels,\n  arrivedId,\n  hasEdits,\n}: EdgeLayerProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const lastTakenId = run.taken.at(-1);\n  const lastTaken = layout.edges.find((edge) => edge.id === lastTakenId);\n  const showsDot = canTravel(lastTaken) && !shouldReduceMotion;\n\n  return (\n    <>\n      <svg\n        aria-hidden='true'\n        width={layout.width}\n        height={layout.height}\n        className='pointer-events-none absolute top-0 left-0 overflow-visible'\n      >\n        {layout.edges.map((edge) => (\n          <EdgePath\n            key={`${edge.id} ${edge.path}`}\n            edge={edge}\n            tone={toneOf(run, edge)}\n            isNew={touches(edge, arrivedId)}\n            isRedrawn={hasEdits}\n          />\n        ))}\n      </svg>\n      {layout.edges.map((edge) => {\n        const label = labels[edge.id];\n        if (label === undefined || edge.labelAt === null) {\n          return null;\n        }\n        return (\n          <EdgeLabel\n            key={edge.id}\n            label={label}\n            at={edge.labelAt}\n            tone={toneOf(run, edge)}\n          />\n        );\n      })}\n      {showsDot && lastTaken && (\n        <TravelDot key={`${run.token} ${run.taken.length}`} edge={lastTaken} />\n      )}\n    </>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/edges.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/insert-button.tsx",
      "content": "'use client';\n\nimport { useRef, useState } from 'react';\n\nimport { PlusIcon } from '@/registry/ndeko/lib/icons';\nimport {\n  Popover,\n  PopoverContent,\n  PopoverTrigger,\n} from '@/registry/ndeko/ui/popover';\n\nimport { capitalized } from './capitalized';\nimport type { PaletteEntry } from './catalog';\nimport { Palette } from './palette';\n\ntype InsertButtonProps = {\n  /** Where the point sits, from the corner of the step it follows. */\n  x: number;\n  y: number;\n  /** Where a step added here goes, in words that follow \"Add a step\": after Track the parcel. */\n  placement: string;\n  onPick: (entry: PaletteEntry) => void;\n};\n\n/**\n * A small plus on an edge. It opens the palette beside it, and a pick adds the step right there.\n * The point sits on a zero-size anchor, so centring it never widens the plane.\n */\nexport function InsertButton({ x, y, placement, onPick }: InsertButtonProps) {\n  const [isOpen, setIsOpen] = useState(false);\n  const hasPicked = useRef(false);\n  const anchorStyle = { translate: `${x}px ${y}px` };\n\n  function pick(entry: PaletteEntry) {\n    hasPicked.current = true;\n    setIsOpen(false);\n    onPick(entry);\n  }\n\n  /** After a pick the focus belongs to the new step, which takes it itself. Without one it goes back to the plus. */\n  function returnsFocus() {\n    const wasPicked = hasPicked.current;\n    hasPicked.current = false;\n    return !wasPicked;\n  }\n\n  return (\n    <span className='absolute top-0 left-0 size-0' style={anchorStyle}>\n      <Popover open={isOpen} onOpenChange={setIsOpen}>\n        <PopoverTrigger\n          render={\n            <button\n              type='button'\n              aria-label={`Add a step ${placement}`}\n              className='bg-card text-muted-foreground ring-foreground/15 hover:text-foreground hover:ring-foreground/30 focus-visible:ring-ring data-popup-open:bg-primary data-popup-open:text-primary-foreground data-popup-open:ring-primary hairline-ring absolute -top-2 -left-2 flex size-4 cursor-pointer items-center justify-center rounded-full shadow-[0_1px_2px_rgb(0_0_0/0.05)] transition-[color,background-color,box-shadow] duration-150 outline-none after:absolute after:-inset-2 focus-visible:ring-2'\n            />\n          }\n        >\n          <PlusIcon className='size-2.5' strokeWidth={2.5} />\n        </PopoverTrigger>\n        <PopoverContent\n          side='right'\n          align='start'\n          sideOffset={10}\n          finalFocus={returnsFocus}\n          className='flex max-h-80 w-64 flex-col p-2'\n        >\n          <Palette\n            placement={capitalized(placement)}\n            pressed={null}\n            onPick={pick}\n          />\n        </PopoverContent>\n      </Popover>\n    </span>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/insert-button.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/approval-card.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { pressedSolidOf } from '@/registry/ndeko/lib/demonstration';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Kbd } from '@/registry/ndeko/ui/kbd';\nimport { Wash } from '@/registry/ndeko/ui/wash';\n\nimport type { ApprovalStep } from './model';\nimport type { Decision } from './run';\nimport type { Sample } from './samples';\n\ntype ApprovalCardProps = {\n  step: ApprovalStep;\n  sample: Sample;\n  workflowName: string;\n  pressed: string | null;\n  onDecide: (decision: Decision) => void;\n};\n\n/**\n * What a step asks a person before the run goes on. It hangs from its step on the canvas and keeps\n * its size whatever the zoom, so its two answers stay easy to press on a phone.\n */\nexport function ApprovalCard({\n  step,\n  sample,\n  workflowName,\n  pressed,\n  onDecide,\n}: ApprovalCardProps) {\n  const titleId = useId();\n  const keysId = useId();\n  const request = sample.request;\n\n  function allow() {\n    onDecide('approved');\n  }\n\n  function deny() {\n    onDecide('denied');\n  }\n\n  function decideFromKeys(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key === 'Escape') {\n      event.preventDefault();\n      deny();\n      return;\n    }\n    const isOnCard = event.target === event.currentTarget;\n    const isEnter = event.key === 'Enter';\n    if (isEnter && isOnCard) {\n      event.preventDefault();\n      allow();\n    }\n  }\n\n  return (\n    <div\n      role='group'\n      tabIndex={0}\n      data-solid\n      data-approval-card\n      aria-labelledby={titleId}\n      aria-describedby={keysId}\n      onKeyDown={decideFromKeys}\n      className='surface-raised focus-visible:ring-ring/25 absolute top-[calc(var(--step-height)+8px)] left-0 isolate flex w-60 origin-top-left scale-[calc(1/var(--zoom,1))] cursor-default flex-col gap-2.5 rounded-xl p-3 text-start transition-[opacity,translate] duration-200 ease-(--ease-out-strong) outline-none focus-visible:ring-[3px] @2xl/canvas:top-0 @2xl/canvas:left-[calc(var(--step-width)+8px)] starting:translate-y-1 starting:opacity-0'\n    >\n      <Wash color='var(--warning)' />\n      <div className='flex items-center gap-2'>\n        <h3\n          id={titleId}\n          className='min-w-0 flex-1 truncate text-[13px] font-medium'\n        >\n          {step.name}\n        </h3>\n        <Badge variant='warning'>Waiting on you</Badge>\n      </div>\n      {request && (\n        <div className='flex flex-col gap-0.5'>\n          <p className='text-2xl leading-8 font-semibold tabular-nums'>\n            {request.amount}\n          </p>\n          <p className='text-muted-foreground text-xs'>\n            {request.order}, {request.item}\n          </p>\n        </div>\n      )}\n      <p className='text-muted-foreground flex items-center gap-1.5 text-xs'>\n        <Avatar seed={sample.from} className='size-4' />\n        <span className='min-w-0'>\n          Asked by {workflowName}, for {sample.from}\n        </span>\n      </p>\n      <div className='flex flex-wrap items-center gap-2'>\n        <Button\n          type='button'\n          size='sm'\n          onClick={allow}\n          className={pressedSolidOf(pressed === 'allow')}\n        >\n          Allow\n          <Kbd className='ms-0.5'>Enter</Kbd>\n        </Button>\n        <Button type='button' size='sm' variant='outline' onClick={deny}>\n          Deny\n          <Kbd className='ms-0.5'>Esc</Kbd>\n        </Button>\n        <Badge variant='secondary' className='ms-auto'>\n          Illustrative\n        </Badge>\n      </div>\n      <span id={keysId} className='sr-only'>\n        Enter allows, Escape denies\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/approval-card.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/sample-card.tsx",
      "content": "'use client';\n\nimport { memo } from 'react';\n\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport { XIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport { samplePressKeyOf, type Sample, type SampleId } from './samples';\n\ntype SampleCardProps = {\n  sample: Sample;\n  /** The sample the card offers to run next. */\n  other: Sample;\n  isRunning: boolean;\n  pressed: string | null;\n  onRun: (id: SampleId) => void;\n  onClear: () => void;\n};\n\n/** The email a test run sends through the flow, pinned over the top of the canvas while its marks show. */\nexport const SampleCard = memo(function SampleCard({\n  sample,\n  other,\n  isRunning,\n  pressed,\n  onRun,\n  onClear,\n}: SampleCardProps) {\n  const isOtherPressed = pressed === samplePressKeyOf(other.id);\n\n  return (\n    <section\n      data-solid\n      data-canvas-overlay='card'\n      aria-label='Sample email of the test run'\n      className='surface-raised pointer-events-auto flex w-full max-w-[19rem] flex-col gap-2 rounded-xl p-3'\n    >\n      <div className='flex items-center gap-2'>\n        <Avatar seed={sample.from} className='size-6' />\n        <div className='flex min-w-0 flex-1 flex-col leading-tight'>\n          <span className='truncate text-[13px] font-medium'>\n            {sample.from}\n          </span>\n          <span className='text-muted-foreground truncate text-xs'>\n            {sample.subject}\n          </span>\n        </div>\n        <Badge variant='secondary'>Sample</Badge>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Clear the marks of the run'\n          disabled={isRunning}\n          onClick={onClear}\n          className='text-muted-foreground -me-1 size-6'\n        >\n          <XIcon className='size-3.5' />\n        </Button>\n      </div>\n      <p\n        key={sample.id}\n        className='text-[13px] leading-relaxed transition-opacity duration-300 starting:opacity-0'\n      >\n        {sample.body}\n      </p>\n      <Button\n        type='button'\n        variant='outline'\n        size='sm'\n        disabled={isRunning}\n        onClick={() => onRun(other.id)}\n        className={cn('self-start', pressedQuietOf(isOtherPressed))}\n      >\n        {other.runLabel}\n      </Button>\n    </section>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/sample-card.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/tool-bar.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { memo } from 'react';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport {\n  RedoIcon,\n  UndoIcon,\n  ZoomInIcon,\n  ZoomOutIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { risePresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport type { Notice, RunTotals } from './session';\nimport { useZoomPercent, type Viewport } from './use-viewport';\nimport type { ViewStore } from './viewport';\n\n/** Under a dollar a cost keeps three decimals, as in the rest of the kit. */\nconst COST_FORMAT: Intl.NumberFormatOptions = {\n  style: 'currency',\n  currency: 'USD',\n  minimumFractionDigits: 3,\n  maximumFractionDigits: 3,\n};\n\nconst SECONDS_FORMAT: Intl.NumberFormatOptions = {\n  minimumFractionDigits: 1,\n  maximumFractionDigits: 1,\n};\n\nconst DIVIDER = 'bg-border mx-0.5 h-4 w-(--hairline) shrink-0';\n\n/** The only part of the tool bar that draws again while the canvas zooms. */\nfunction ZoomValue({ store }: { store: ViewStore }) {\n  const percent = useZoomPercent(store);\n\n  return (\n    <span className='text-muted-foreground w-10 shrink-0 text-center text-xs tabular-nums'>\n      <span className='sr-only'>Zoom </span>\n      {percent}%\n    </span>\n  );\n}\n\nconst NO_TOTALS: RunTotals = { durationMs: 0, costUsd: 0 };\n\ntype RunFiguresProps = {\n  lastRun: RunTotals | null;\n  hasRunStarted: boolean;\n};\n\n/**\n * The figures of the last run that ended. They stand at zero while the first run plays and roll\n * once, when a run ends: a figure never ticks while a run is on its way.\n */\nfunction RunFigures({ lastRun, hasRunStarted }: RunFiguresProps) {\n  const hasFigures = lastRun !== null || hasRunStarted;\n  if (!hasFigures) {\n    return (\n      <span className='text-muted-foreground px-1.5 text-xs'>No run yet</span>\n    );\n  }\n  const totals = lastRun ?? NO_TOTALS;\n  const seconds = totals.durationMs / 1000;\n\n  return (\n    <span className='flex items-center gap-2 px-1.5 text-xs'>\n      <span className='sr-only'>Last run</span>\n      <MotionNumber value={seconds} format={SECONDS_FORMAT} suffix='s' />\n      <MotionNumber value={totals.costUsd} format={COST_FORMAT} />\n      <Badge variant='secondary'>Illustrative</Badge>\n    </span>\n  );\n}\n\n/** A key that played Undo or Redo shows on its button, the way a press would. */\nexport type HistoryEcho = 'undo' | 'redo' | null;\n\ntype ToolBarProps = {\n  viewport: Viewport;\n  canUndo: boolean;\n  canRedo: boolean;\n  echo: HistoryEcho;\n  notice: Notice | null;\n  lastRun: RunTotals | null;\n  hasRunStarted: boolean;\n  onUndo: () => void;\n  onRedo: () => void;\n  onUndoNotice: () => void;\n};\n\n/**\n * Zoom, fit and history at the bottom of the canvas, then the figures of the last run. What just\n * happened shows in one line above it, with its way back: \"Step removed, Undo\".\n */\nexport const ToolBar = memo(function ToolBar({\n  viewport,\n  canUndo,\n  canRedo,\n  echo,\n  notice,\n  lastRun,\n  hasRunStarted,\n  onUndo,\n  onRedo,\n  onUndoNotice,\n}: ToolBarProps) {\n  const { store, zoomBy, fit } = viewport;\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const noticePresence = risePresenceOf(shouldReduceMotion);\n\n  return (\n    <div\n      data-solid\n      data-canvas-overlay='bottom'\n      className='pointer-events-auto flex max-w-full min-w-0 flex-col items-start gap-1.5'\n    >\n      <AnimatePresence initial={false}>\n        {notice && (\n          <motion.div\n            key={notice.token}\n            className='surface-raised flex max-w-full items-center gap-1 rounded-lg py-1 ps-2.5 pe-1 text-[13px]'\n            {...noticePresence}\n          >\n            <span className='min-w-0 py-0.5 pe-1.5'>{notice.text}</span>\n            {notice.canUndo && (\n              <Button\n                type='button'\n                variant='ghost'\n                size='sm'\n                onClick={onUndoNotice}\n                className='text-primary-ink h-6'\n              >\n                Undo\n              </Button>\n            )}\n          </motion.div>\n        )}\n      </AnimatePresence>\n      <div\n        role='toolbar'\n        aria-label='Canvas tools'\n        className='bg-card hairline-ring ring-border flex max-w-full flex-wrap items-center gap-y-0.5 rounded-xl p-1 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'\n      >\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Zoom out'\n          onClick={() => zoomBy(-1)}\n          className='text-muted-foreground'\n        >\n          <ZoomOutIcon />\n        </Button>\n        <ZoomValue store={store} />\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Zoom in'\n          onClick={() => zoomBy(1)}\n          className='text-muted-foreground'\n        >\n          <ZoomInIcon />\n        </Button>\n        <Button\n          type='button'\n          variant='ghost'\n          size='sm'\n          aria-label='Fit the whole flow in view'\n          onClick={fit}\n          className='text-muted-foreground'\n        >\n          Fit\n        </Button>\n        <span aria-hidden='true' className={DIVIDER} />\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Undo'\n          disabled={!canUndo}\n          onClick={onUndo}\n          className={cn(\n            'text-muted-foreground',\n            pressedQuietOf(echo === 'undo')\n          )}\n        >\n          <UndoIcon />\n        </Button>\n        <Button\n          type='button'\n          variant='ghost'\n          size='icon-sm'\n          aria-label='Redo'\n          disabled={!canRedo}\n          onClick={onRedo}\n          className={cn(\n            'text-muted-foreground',\n            pressedQuietOf(echo === 'redo')\n          )}\n        >\n          <RedoIcon />\n        </Button>\n        <span aria-hidden='true' className={DIVIDER} />\n        <RunFigures lastRun={lastRun} hasRunStarted={hasRunStarted} />\n      </div>\n    </div>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/tool-bar.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/mini-map.tsx",
      "content": "'use client';\n\nimport { memo, useEffect, useRef } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { ARROW_OFFSET } from './canvas-frame';\nimport type { Box, FlowLayout } from './layout';\nimport type { Run, StepStatus } from './run';\nimport type { Viewport } from './use-viewport';\nimport type { View } from './viewport';\n\nconst MAP_WIDTH = 168;\n\nconst MAP_HEIGHT = 128;\n\ntype Drag = {\n  pointerId: number;\n  startX: number;\n  startY: number;\n  view: View;\n};\n\nfunction toneOf(isSelected: boolean, status: StepStatus | undefined) {\n  if (isSelected) {\n    return 'bg-primary';\n  }\n  if (status === 'skipped') {\n    return 'bg-foreground/10';\n  }\n  const isAtWork = status === 'running' || status === 'retrying';\n  if (isAtWork) {\n    return 'bg-primary/60';\n  }\n  return 'bg-foreground/25';\n}\n\ntype MapStepProps = {\n  box: Box;\n  scale: number;\n  tone: string;\n};\n\nfunction MapStep({ box, scale, tone }: MapStepProps) {\n  const left = box.x * scale;\n  const top = box.y * scale;\n  const style = {\n    translate: `${left}px ${top}px`,\n    width: box.width * scale,\n    height: box.height * scale,\n  };\n\n  return (\n    <span\n      style={style}\n      className={cn(\n        'absolute top-0 left-0 rounded-[2px] transition-[translate,background-color] duration-300 ease-(--ease-out-strong)',\n        tone\n      )}\n    />\n  );\n}\n\ntype MiniMapProps = {\n  layout: FlowLayout;\n  viewport: Viewport;\n  run: Run;\n  selectedId: string | null;\n  className?: string;\n};\n\n/**\n * The whole flow as small rectangles, with the part the canvas shows as a frame. The frame is\n * written to straight from the view, and dragging it pans the canvas.\n */\nexport const MiniMap = memo(function MiniMap({\n  layout,\n  viewport,\n  run,\n  selectedId,\n  className,\n}: MiniMapProps) {\n  const { store, show, panBy } = viewport;\n  const frameRef = useRef<HTMLButtonElement>(null);\n  const latestViewport = useRef(viewport);\n  const drag = useRef<Drag | null>(null);\n  const scaleAcross = MAP_WIDTH / layout.width;\n  const scaleDown = MAP_HEIGHT / layout.height;\n  const scale = Math.min(scaleAcross, scaleDown);\n  const mapStyle = {\n    width: layout.width * scale,\n    height: layout.height * scale,\n  };\n\n  useEffect(() => {\n    latestViewport.current = viewport;\n  });\n\n  /** A pan only moves the frame. Its size is written again when the zoom or the canvas changes size, never on each frame of a drag. */\n  useEffect(() => {\n    let writtenSize = '';\n    function place() {\n      const frame = frameRef.current;\n      if (!frame) {\n        return;\n      }\n      const view = store.get();\n      const size = latestViewport.current.frameSizeOf();\n      const ratio = scale / view.zoom;\n      const left = -view.x * ratio;\n      const top = -view.y * ratio;\n      const width = size.width * ratio;\n      const height = size.height * ratio;\n      const nextSize = `${width} ${height}`;\n      frame.style.transform = `translate(${left}px, ${top}px)`;\n      if (nextSize === writtenSize) {\n        return;\n      }\n      writtenSize = nextSize;\n      frame.style.width = `${width}px`;\n      frame.style.height = `${height}px`;\n    }\n    place();\n    return store.subscribe(place);\n  }, [store, scale]);\n\n  function startDrag(event: React.PointerEvent<HTMLButtonElement>) {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    drag.current = {\n      pointerId: event.pointerId,\n      startX: event.clientX,\n      startY: event.clientY,\n      view: store.rest(),\n    };\n  }\n\n  /** A move of the frame on the map is the opposite move of the plane, at the size the plane shows. */\n  function dragFrame(event: React.PointerEvent<HTMLButtonElement>) {\n    const current = drag.current;\n    if (current?.pointerId !== event.pointerId) {\n      return;\n    }\n    const ratio = current.view.zoom / scale;\n    const offsetX = (event.clientX - current.startX) * ratio;\n    const offsetY = (event.clientY - current.startY) * ratio;\n    show({\n      x: current.view.x - offsetX,\n      y: current.view.y - offsetY,\n      zoom: current.view.zoom,\n    });\n  }\n\n  function endDrag() {\n    drag.current = null;\n  }\n\n  function panFromKeys(event: React.KeyboardEvent<HTMLButtonElement>) {\n    const offset = ARROW_OFFSET[event.key];\n    if (offset) {\n      event.preventDefault();\n      panBy(offset.x, offset.y);\n    }\n  }\n\n  return (\n    <div\n      data-solid\n      data-canvas-overlay='map'\n      className={cn(\n        'bg-card hairline-ring ring-border pointer-events-auto rounded-xl p-2 shadow-[0_1px_2px_rgb(0_0_0/0.04)]',\n        className\n      )}\n    >\n      <div className='relative overflow-hidden' style={mapStyle}>\n        {layout.boxes.map((box) => (\n          <MapStep\n            key={box.id}\n            box={box}\n            scale={scale}\n            tone={toneOf(box.id === selectedId, run.steps[box.id]?.status)}\n          />\n        ))}\n        <button\n          ref={frameRef}\n          type='button'\n          aria-label='The part of the flow in view. Drag it, or use the arrow keys, to move the canvas'\n          onPointerDown={startDrag}\n          onPointerMove={dragFrame}\n          onPointerUp={endDrag}\n          onPointerCancel={endDrag}\n          onKeyDown={panFromKeys}\n          className='bg-primary/10 ring-primary/60 focus-visible:ring-primary absolute top-0 left-0 cursor-grab touch-none rounded-[3px] ring-1 outline-none ring-inset focus-visible:ring-2 active:cursor-grabbing'\n        />\n      </div>\n    </div>\n  );\n});\n",
      "type": "registry:component",
      "target": "components/templates/application-14/mini-map.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/inspector.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { MousePointerClickIcon } from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Tabs, TabsList, TabsPanel, TabsTab } from '@/registry/ndeko/ui/tabs';\n\nimport { stepOf } from './flow';\nimport {\n  AgentFields,\n  ApprovalFields,\n  LoopFields,\n  ProductFields,\n  WaitFields,\n} from './inspector-fields';\nimport { BranchFields } from './inspector-outputs';\nimport { LastRunPanel } from './inspector-run';\nimport { VariablesPanel } from './inspector-variables';\nimport { isEscapeInside } from './keys';\nimport { isProductStep, KIND_WORD, type Step, type Workflow } from './model';\nimport { StepTile } from './node-tile';\nimport type { Run } from './run';\nimport type { BuilderAction, InspectorTab } from './session';\nimport { differsFromSaved } from './session-setup';\n\nconst TABS: InspectorTab[] = ['setup', 'variables', 'run'];\n\n/** The panel is positioned: a word kept for screen readers inside it would widen the page otherwise. */\nconst PANEL = 'relative -mx-1 flex min-h-0 flex-col overflow-y-auto px-1 pb-1';\n\ntype SetupPanelProps = {\n  step: Step;\n  onAct: (action: BuilderAction) => void;\n  onMintId: () => string;\n};\n\n/** Each kind of step has its own setup. Every change applies at once, and the flow reads as unsaved until it is saved. */\nfunction SetupPanel({ step, onAct, onMintId }: SetupPanelProps) {\n  const { id } = step;\n\n  if (step.kind === 'agent') {\n    return (\n      <AgentFields\n        step={step}\n        onChange={(patch) => onAct({ type: 'agentChanged', id, patch })}\n      />\n    );\n  }\n  function addOutput() {\n    const outputId = onMintId();\n    onAct({ type: 'outputAdded', id, outputId });\n  }\n\n  if (step.kind === 'branch') {\n    return (\n      <BranchFields\n        step={step}\n        onAdd={addOutput}\n        onRename={(outputId, label) =>\n          onAct({ type: 'outputRenamed', id, outputId, label })\n        }\n        onRemove={(outputId) => onAct({ type: 'outputRemoved', id, outputId })}\n      />\n    );\n  }\n  if (step.kind === 'approval') {\n    return (\n      <ApprovalFields\n        step={step}\n        onChange={(patch) => onAct({ type: 'approvalChanged', id, patch })}\n      />\n    );\n  }\n  if (step.kind === 'wait') {\n    return (\n      <WaitFields\n        step={step}\n        onChange={(duration) => onAct({ type: 'waitChanged', id, duration })}\n      />\n    );\n  }\n  if (step.kind === 'loop') {\n    return (\n      <LoopFields\n        step={step}\n        onChange={(rounds) => onAct({ type: 'loopChanged', id, rounds })}\n      />\n    );\n  }\n  if (isProductStep(step)) {\n    return (\n      <ProductFields\n        step={step}\n        onPickAction={(actionId) =>\n          onAct({ type: 'actionPicked', id, actionId })\n        }\n        onChangeField={(fieldId, value) =>\n          onAct({ type: 'fieldChanged', id, fieldId, value })\n        }\n      />\n    );\n  }\n  return null;\n}\n\n/** The dot beside Last run tells the step has something to show there. */\nfunction hasRunMark(run: Run, step: Step) {\n  const status = run.steps[step.id]?.status;\n  return status !== undefined && status !== 'skipped';\n}\n\ntype InspectorProps = {\n  workflow: Workflow;\n  savedWorkflow: Workflow;\n  selectedId: string | null;\n  tab: InspectorTab;\n  run: Run;\n  /** False off screen: a text that streams holds its place. */\n  isActive: boolean;\n  onAct: (action: BuilderAction) => void;\n  onMintId: () => string;\n  /** Escape gives the focus back to the step on the canvas. */\n  onLeave: () => void;\n  className?: string;\n};\n\nexport function Inspector({\n  workflow,\n  savedWorkflow,\n  selectedId,\n  tab,\n  run,\n  isActive,\n  onAct,\n  onMintId,\n  onLeave,\n  className,\n}: InspectorProps) {\n  const headingId = useId();\n  const step = stepOf(workflow, selectedId);\n\n  function leaveOnEscape(event: React.KeyboardEvent<HTMLElement>) {\n    if (isEscapeInside(event)) {\n      onLeave();\n    }\n  }\n\n  function changeTab(next: unknown) {\n    const found = TABS.find((candidate) => candidate === next);\n    if (found) {\n      onAct({ type: 'tabPicked', tab: found });\n    }\n  }\n\n  if (!step) {\n    return (\n      <section\n        aria-labelledby={headingId}\n        onKeyDown={leaveOnEscape}\n        className={cn('flex min-h-0 flex-col', className)}\n      >\n        <div className='m-auto flex max-w-56 flex-col items-center gap-3 py-6 text-center'>\n          <span\n            aria-hidden='true'\n            className='keycap-3d text-muted-foreground inline-flex size-9 items-center justify-center rounded-lg'\n          >\n            <MousePointerClickIcon className='size-4' />\n          </span>\n          <h2\n            id={headingId}\n            tabIndex={-1}\n            data-inspector-heading\n            className='text-sm font-medium outline-none'\n          >\n            No step selected\n          </h2>\n          <p className='text-muted-foreground text-[13px] leading-relaxed'>\n            Pick a step on the canvas to set it up, see what it can read and\n            what it did in the last run\n          </p>\n        </div>\n      </section>\n    );\n  }\n\n  const savedStep = stepOf(savedWorkflow, step.id);\n  const canReset = differsFromSaved(step, savedStep);\n  const showsRunMark = hasRunMark(run, step);\n\n  return (\n    <section\n      aria-labelledby={headingId}\n      onKeyDown={leaveOnEscape}\n      className={cn('flex min-h-0 flex-col gap-3', className)}\n    >\n      <header className='flex min-h-9 shrink-0 items-center gap-2.5'>\n        <StepTile step={step} />\n        <div className='flex min-w-0 flex-1 flex-col leading-tight'>\n          <span className='text-muted-foreground text-[11px]'>\n            {KIND_WORD[step.kind]}\n          </span>\n          <h2\n            id={headingId}\n            tabIndex={-1}\n            data-inspector-heading\n            className='focus-visible:ring-ring/25 truncate rounded-sm text-sm font-medium outline-none focus-visible:ring-[3px]'\n          >\n            {step.name}\n          </h2>\n        </div>\n        {canReset && (\n          <Button\n            type='button'\n            variant='link'\n            size='sm'\n            aria-label={`Reset ${step.name} to its saved values`}\n            onClick={() => onAct({ type: 'stepReset', id: step.id })}\n            className='shrink-0 px-1 transition-opacity duration-200 starting:opacity-0'\n          >\n            Reset\n          </Button>\n        )}\n      </header>\n      <Tabs\n        value={tab}\n        onValueChange={changeTab}\n        className='min-h-0 flex-1 gap-3'\n      >\n        <TabsList\n          variant='segmented'\n          aria-label='About this step'\n          className='w-full shrink-0'\n        >\n          <TabsTab value='setup' className='flex-1'>\n            Setup\n          </TabsTab>\n          <TabsTab value='variables' className='flex-1'>\n            Variables\n          </TabsTab>\n          <TabsTab value='run' className='flex-1'>\n            Last run\n            {showsRunMark && (\n              <span className='bg-primary size-1.5 rounded-full'>\n                <span className='sr-only'>, has a result</span>\n              </span>\n            )}\n          </TabsTab>\n        </TabsList>\n        <TabsPanel value='setup' className={PANEL}>\n          <SetupPanel\n            key={step.id}\n            step={step}\n            onAct={onAct}\n            onMintId={onMintId}\n          />\n        </TabsPanel>\n        <TabsPanel value='variables' className={PANEL}>\n          <VariablesPanel workflow={workflow} step={step} />\n        </TabsPanel>\n        <TabsPanel value='run' className={PANEL}>\n          <LastRunPanel step={step} run={run} isActive={isActive} />\n        </TabsPanel>\n      </Tabs>\n    </section>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/inspector.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/inspector-fields.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { Label, LABEL_RECIPE } from '@/registry/ndeko/ui/label';\nimport { Segments } from '@/registry/ndeko/ui/segments';\nimport { Textarea } from '@/registry/ndeko/ui/textarea';\n\nimport { CREATIVITIES, ROUNDS, TIMEOUT_RULES, TIMEOUTS, WAITS } from './data';\nimport {\n  ApproverSelect,\n  ChoiceSelect,\n  FIELD,\n  GROUP,\n  HINT,\n  ModelSelect,\n  SwitchRow,\n} from './field-kit';\nimport type {\n  AgentSetup,\n  AgentStep,\n  ApprovalSetup,\n  ApprovalStep,\n  LoopRounds,\n  LoopStep,\n  ProductStep,\n  WaitDuration,\n  WaitStep,\n} from './model';\nimport { MarkTile } from './node-tile';\nimport { actionOf, toolOf, type ToolField } from './tools';\n\n/** A name other steps read between braces: letters, figures and underscores only. */\nfunction variableNameOf(typed: string) {\n  return typed.replace(/[^a-zA-Z0-9_]/g, '_');\n}\n\ntype AgentFieldsProps = {\n  step: AgentStep;\n  onChange: (patch: Partial<AgentSetup>) => void;\n};\n\nexport function AgentFields({ step, onChange }: AgentFieldsProps) {\n  const instructionsId = useId();\n  const outputId = useId();\n  const outputHintId = useId();\n  const { agent } = step;\n\n  function renameOutput(event: React.ChangeEvent<HTMLInputElement>) {\n    const outputName = variableNameOf(event.target.value);\n    onChange({ outputName });\n  }\n\n  return (\n    <div className={GROUP}>\n      <div className={FIELD}>\n        <Label htmlFor={instructionsId}>Instructions</Label>\n        <Textarea\n          id={instructionsId}\n          value={agent.instructions}\n          placeholder='Say what this agent does with what it receives'\n          onChange={(event) => onChange({ instructions: event.target.value })}\n          className='min-h-24'\n        />\n      </div>\n      <ModelSelect\n        value={agent.modelId}\n        onChange={(modelId) => onChange({ modelId })}\n      />\n      <div className={FIELD}>\n        <span className={LABEL_RECIPE}>Creativity</span>\n        <Segments\n          label='Creativity'\n          value={agent.creativity}\n          segments={CREATIVITIES}\n          onValueChange={(creativity) => onChange({ creativity })}\n          className='w-full'\n        />\n      </div>\n      <div className='flex flex-col gap-3'>\n        <SwitchRow\n          label='Stream the answer'\n          hint='Words show as they are written'\n          isOn={agent.streams}\n          onChange={(streams) => onChange({ streams })}\n        />\n        <SwitchRow\n          label='Remember the thread'\n          hint='Earlier emails of the customer are read first'\n          isOn={agent.remembers}\n          onChange={(remembers) => onChange({ remembers })}\n        />\n        <SwitchRow\n          label='Retry once on failure'\n          hint='One more try before the run stops'\n          isOn={agent.retries}\n          onChange={(retries) => onChange({ retries })}\n        />\n      </div>\n      <div className={FIELD}>\n        <Label htmlFor={outputId}>Output name</Label>\n        <Input\n          id={outputId}\n          value={agent.outputName}\n          aria-describedby={outputHintId}\n          onChange={renameOutput}\n          className='font-mono'\n        />\n        <p id={outputHintId} className={HINT}>\n          Later steps read it as{' '}\n          <code className='font-mono'>{`{{${agent.outputName}}}`}</code>\n        </p>\n      </div>\n    </div>\n  );\n}\n\ntype ApprovalFieldsProps = {\n  step: ApprovalStep;\n  onChange: (patch: Partial<ApprovalSetup>) => void;\n};\n\nexport function ApprovalFields({ step, onChange }: ApprovalFieldsProps) {\n  const { approval } = step;\n\n  return (\n    <div className={GROUP}>\n      <ApproverSelect\n        value={approval.approverId}\n        onChange={(approverId) => onChange({ approverId })}\n      />\n      <ChoiceSelect\n        label='If nobody answers'\n        value={approval.timeoutHours}\n        choices={TIMEOUTS}\n        onChange={(timeoutHours) => onChange({ timeoutHours })}\n      />\n      <ChoiceSelect\n        label='Then'\n        value={approval.onTimeout}\n        choices={TIMEOUT_RULES}\n        onChange={(onTimeout) => onChange({ onTimeout })}\n      />\n    </div>\n  );\n}\n\ntype ToolFieldRowProps = {\n  field: ToolField;\n  value: string;\n  onChange: (fieldId: string, value: string) => void;\n};\n\nfunction ToolFieldRow({ field, value, onChange }: ToolFieldRowProps) {\n  const inputId = useId();\n\n  return (\n    <div className={FIELD}>\n      <Label htmlFor={inputId}>{field.label}</Label>\n      <Input\n        id={inputId}\n        value={value}\n        onChange={(event) => onChange(field.id, event.target.value)}\n      />\n    </div>\n  );\n}\n\n/** A trigger listens for an event of its product. A tool or an output runs one of its actions. */\nfunction actionLabelOf(isTrigger: boolean) {\n  if (isTrigger) {\n    return 'Event';\n  }\n  return 'Action';\n}\n\ntype ProductFieldsProps = {\n  step: ProductStep;\n  onPickAction: (actionId: string) => void;\n  onChangeField: (fieldId: string, value: string) => void;\n};\n\nexport function ProductFields({\n  step,\n  onPickAction,\n  onChangeField,\n}: ProductFieldsProps) {\n  const tool = toolOf(step.tool.toolId);\n  const action = actionOf(tool, step.tool.actionId);\n  const isTrigger = step.kind === 'trigger';\n  const offered = tool.actions.filter((entry) => entry.isEvent === isTrigger);\n  const choices = offered.map((entry) => ({\n    value: entry.id,\n    label: entry.label,\n  }));\n\n  return (\n    <div className={GROUP}>\n      <div className='bg-foreground/[0.04] flex items-center gap-2 rounded-lg p-2'>\n        <MarkTile mark={tool.mark} size='md' />\n        <span className='min-w-0 truncate text-[13px] font-medium'>\n          {tool.name}\n        </span>\n      </div>\n      <ChoiceSelect\n        label={actionLabelOf(isTrigger)}\n        value={action.id}\n        choices={choices}\n        onChange={onPickAction}\n      />\n      {action.fields.map((field) => (\n        <ToolFieldRow\n          key={`${action.id} ${field.id}`}\n          field={field}\n          value={step.tool.values[field.id] ?? ''}\n          onChange={onChangeField}\n        />\n      ))}\n    </div>\n  );\n}\n\ntype WaitFieldsProps = {\n  step: WaitStep;\n  onChange: (duration: WaitDuration) => void;\n};\n\nexport function WaitFields({ step, onChange }: WaitFieldsProps) {\n  return (\n    <div className={GROUP}>\n      <ChoiceSelect\n        label='Wait for'\n        value={step.duration}\n        choices={WAITS}\n        onChange={onChange}\n      />\n      <p className={HINT}>A test run does not wait: it goes straight on</p>\n    </div>\n  );\n}\n\ntype LoopFieldsProps = {\n  step: LoopStep;\n  onChange: (rounds: LoopRounds) => void;\n};\n\nexport function LoopFields({ step, onChange }: LoopFieldsProps) {\n  return (\n    <div className={GROUP}>\n      <ChoiceSelect\n        label='Repeat what follows'\n        value={step.rounds}\n        choices={ROUNDS}\n        onChange={onChange}\n      />\n      <p className={HINT}>A test run plays one round</p>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/inspector-fields.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/inspector-outputs.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\nimport { useId, useRef } from 'react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { PlusIcon, Trash2Icon } from '@/registry/ndeko/lib/icons';\nimport { rowPresenceOf } from '@/registry/ndeko/lib/motion-presets';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport { LABEL_RECIPE } from '@/registry/ndeko/ui/label';\n\nimport {\n  BRANCH_MIN_OUTPUTS,\n  type BranchOutput,\n  type BranchStep,\n} from './model';\n\ntype OutputRowProps = {\n  output: BranchOutput;\n  rank: number;\n  canRemove: boolean;\n  onRename: (outputId: string, label: string) => void;\n  onRemove: (outputId: string) => void;\n};\n\nfunction OutputRow({\n  output,\n  rank,\n  canRemove,\n  onRename,\n  onRemove,\n}: OutputRowProps) {\n  return (\n    <div className='flex items-center gap-1.5 py-1'>\n      <Input\n        value={output.label}\n        aria-label={`Name of output ${rank}`}\n        onChange={(event) => onRename(output.id, event.target.value)}\n      />\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label={`Remove the output ${output.label}`}\n        disabled={!canRemove}\n        onClick={() => onRemove(output.id)}\n        className='text-muted-foreground shrink-0'\n      >\n        <Trash2Icon />\n      </Button>\n    </div>\n  );\n}\n\ntype BranchFieldsProps = {\n  step: BranchStep;\n  onAdd: () => void;\n  onRename: (outputId: string, label: string) => void;\n  onRemove: (outputId: string) => void;\n};\n\n/** The outputs of a branch as a list to edit. A branch keeps at least two, so the last two cannot be removed. */\nexport function BranchFields({\n  step,\n  onAdd,\n  onRename,\n  onRemove,\n}: BranchFieldsProps) {\n  const labelId = useId();\n  const ruleId = useId();\n  const addRef = useRef<HTMLButtonElement>(null);\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const rowPresence = rowPresenceOf(shouldReduceMotion);\n  const canRemove = step.outputs.length > BRANCH_MIN_OUTPUTS;\n\n  /** The button that was pressed leaves with its row, so the focus goes to the one that adds a row. */\n  function remove(outputId: string) {\n    onRemove(outputId);\n    requestAnimationFrame(() => addRef.current?.focus());\n  }\n\n  return (\n    <div className='flex flex-col gap-2'>\n      <div className='flex flex-col gap-0.5'>\n        <span id={labelId} className={LABEL_RECIPE}>\n          Outputs\n        </span>\n        <p id={ruleId} className='text-muted-foreground text-xs'>\n          A run takes the output named like its topic, or the last one. A branch\n          keeps at least two\n        </p>\n      </div>\n      <ul\n        aria-labelledby={labelId}\n        aria-describedby={ruleId}\n        className='-my-1 flex flex-col'\n      >\n        <AnimatePresence initial={false}>\n          {step.outputs.map((output, index) => (\n            <motion.li\n              key={output.id}\n              className='-mx-1 overflow-hidden px-1'\n              {...rowPresence}\n            >\n              <OutputRow\n                output={output}\n                rank={index + 1}\n                canRemove={canRemove}\n                onRename={onRename}\n                onRemove={remove}\n              />\n            </motion.li>\n          ))}\n        </AnimatePresence>\n      </ul>\n      <button\n        ref={addRef}\n        type='button'\n        onClick={onAdd}\n        className='hairline-border text-muted-foreground hover:border-foreground/35 hover:text-foreground focus-visible:ring-ring/25 border-foreground/20 flex h-8 w-full cursor-pointer items-center justify-center gap-1.5 rounded-md border-dashed text-[13px] transition-[color,border-color] duration-150 outline-none focus-visible:ring-[3px] active:scale-[0.97]'\n      >\n        <PlusIcon className='size-3.5' />\n        Add an output\n      </button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/inspector-outputs.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/inspector-variables.tsx",
      "content": "'use client';\n\nimport { CopyButton } from '@/registry/ndeko/ui/copy-button';\n\nimport { upstreamOf, type Placed } from './flow';\nimport { isProductStep, type Step, type Workflow } from './model';\nimport { StepTile } from './node-tile';\nimport { actionOf, toolOf } from './tools';\n\nfunction tokenOf(path: string) {\n  return `{{${path}}}`;\n}\n\n/** What a step leaves for the ones after it: the result of its action, the answer of its agent, the decision of a person. */\nfunction tokensOf(step: Step) {\n  if (isProductStep(step)) {\n    const tool = toolOf(step.tool.toolId);\n    const action = actionOf(tool, step.tool.actionId);\n    return action.outputs.map((part) => tokenOf(`${action.namespace}.${part}`));\n  }\n  if (step.kind === 'agent') {\n    const { outputName, outputParts } = step.agent;\n    if (outputParts.length === 0) {\n      return [tokenOf(outputName)];\n    }\n    return outputParts.map((part) => tokenOf(`${outputName}.${part}`));\n  }\n  if (step.kind === 'approval') {\n    return [tokenOf('approval.decision')];\n  }\n  if (step.kind === 'branch') {\n    return [tokenOf('branch.taken')];\n  }\n  if (step.kind === 'loop') {\n    return [tokenOf('loop.round')];\n  }\n  return [];\n}\n\nfunction givesSomething(placed: Placed) {\n  const tokens = tokensOf(placed.step);\n  return tokens.length > 0;\n}\n\n/** A step of a branch only ran when its branch was taken: what it gives may be empty. */\nfunction originOf(placed: Placed) {\n  if (placed.branchLabel === null) {\n    return null;\n  }\n  return `Only when ${placed.branchLabel} ran`;\n}\n\ntype TokenGroupProps = {\n  placed: Placed;\n  tokens: string[];\n};\n\nfunction TokenGroup({ placed, tokens }: TokenGroupProps) {\n  const origin = originOf(placed);\n\n  return (\n    <li className='flex flex-col gap-1.5'>\n      <div className='flex items-center gap-2'>\n        <StepTile step={placed.step} size='md' />\n        <span className='min-w-0 truncate text-[13px] font-medium'>\n          {placed.step.name}\n        </span>\n      </div>\n      {origin && <p className='text-muted-foreground text-xs'>{origin}</p>}\n      <ul\n        aria-label={`What ${placed.step.name} gives`}\n        className='flex flex-col gap-1'\n      >\n        {tokens.map((token) => (\n          <li key={token} className='flex items-center gap-1'>\n            <code className='bg-foreground/[0.05] min-w-0 flex-1 truncate rounded-md px-2 py-1 font-mono text-xs leading-4'>\n              {token}\n            </code>\n            <CopyButton text={token} label={`Copy ${token}`} />\n          </li>\n        ))}\n      </ul>\n    </li>\n  );\n}\n\ntype VariablesPanelProps = {\n  workflow: Workflow;\n  step: Step;\n};\n\nexport function VariablesPanel({ workflow, step }: VariablesPanelProps) {\n  const upstream = upstreamOf(workflow, step.id);\n  const givers = upstream.filter(givesSomething);\n\n  if (givers.length === 0) {\n    return (\n      <p className='text-muted-foreground text-[13px] leading-relaxed'>\n        Nothing runs before this step, so it has nothing to read yet\n      </p>\n    );\n  }\n\n  return (\n    <ul\n      aria-label='Variables this step can read'\n      className='flex flex-col gap-4'\n    >\n      {givers.map((placed) => (\n        <TokenGroup\n          key={placed.step.id}\n          placed={placed}\n          tokens={tokensOf(placed.step)}\n        />\n      ))}\n    </ul>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/inspector-variables.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/inspector-run.tsx",
      "content": "'use client';\n\nimport { formatCost } from '@/registry/ndeko/lib/agent-run';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { JsonView } from '@/registry/ndeko/ui/json-view';\nimport { StreamedText } from '@/registry/ndeko/ui/streamed-text';\n\nimport { capitalized } from './capitalized';\nimport type { Step } from './model';\nimport { exchangeOf, hasRun, WORD_MS, type Run, type StepRun } from './run';\nimport { StateMark, stateWordsOf } from './state-mark';\n\nconst NOTE = 'text-muted-foreground text-[13px] leading-relaxed';\n\nconst SECTION = 'flex flex-col gap-1.5';\n\nconst SECTION_TITLE = 'text-muted-foreground text-xs font-medium';\n\nfunction isSettled(stepRun: StepRun) {\n  return stepRun.status === 'done' || stepRun.status === 'denied';\n}\n\ntype StepOutputProps = {\n  step: Step;\n  run: Run;\n  stepRun: StepRun;\n  isActive: boolean;\n};\n\n/**\n * What the step gave. An agent that writes prose shows its text, word by word while it streams.\n * Any other step shows its result once it has one.\n */\nfunction StepOutput({ step, run, stepRun, isActive }: StepOutputProps) {\n  const { text, output } = exchangeOf(run, step);\n  const isStreaming = run.streamingId === step.id;\n  const hasResult = isSettled(stepRun);\n  const isReadable = isStreaming || hasResult;\n\n  if (stepRun.status === 'failed' || stepRun.status === 'retrying') {\n    return (\n      <p className='text-destructive-ink text-[13px] leading-relaxed'>\n        The first try failed. The step is trying once more\n      </p>\n    );\n  }\n  if (stepRun.status === 'waiting') {\n    return <p className={NOTE}>It waits for your answer on the canvas</p>;\n  }\n  if (text !== null && isReadable) {\n    return (\n      <p className='bg-foreground/[0.03] dark:bg-foreground/[0.05] rounded-lg p-2.5 text-[13px] leading-relaxed'>\n        <StreamedText\n          key={run.token}\n          text={text}\n          isStreaming={isStreaming}\n          isActive={isActive}\n          wordMs={WORD_MS}\n        />\n      </p>\n    );\n  }\n  if (!hasResult) {\n    return <p className={NOTE}>Still at work</p>;\n  }\n  return <JsonView value={output} />;\n}\n\ntype LastRunPanelProps = {\n  step: Step;\n  run: Run;\n  /** False off screen: a text that streams holds its place. */\n  isActive: boolean;\n};\n\nexport function LastRunPanel({ step, run, isActive }: LastRunPanelProps) {\n  const stepRun = run.steps[step.id];\n\n  if (!hasRun(run) || !stepRun) {\n    return (\n      <p className={NOTE}>\n        This step has not run yet. Test run sends a sample email through the\n        flow\n      </p>\n    );\n  }\n  if (stepRun.status === 'skipped') {\n    return (\n      <p className={NOTE}>\n        Skipped in the last run: the run did not come this way\n      </p>\n    );\n  }\n\n  const exchange = exchangeOf(run, step);\n  const hasCost = stepRun.usd > 0;\n  const state = stateWordsOf(stepRun);\n\n  return (\n    <div className='flex flex-col gap-4'>\n      <div className='flex flex-wrap items-center gap-x-2 gap-y-1 text-[13px]'>\n        <StateMark stepRun={stepRun} />\n        <span className='min-w-0 flex-1'>{capitalized(state)}</span>\n        {hasCost && (\n          <span className='text-muted-foreground flex items-center gap-1.5 text-xs tabular-nums'>\n            <span className='sr-only'>Cost</span>\n            {formatCost(stepRun.usd)}\n            <Badge variant='secondary'>Illustrative</Badge>\n          </span>\n        )}\n      </div>\n      <section className={SECTION}>\n        <h3 className={SECTION_TITLE}>Input</h3>\n        <JsonView value={exchange.input} />\n      </section>\n      <section className={SECTION}>\n        <h3 className={SECTION_TITLE}>Output</h3>\n        <StepOutput\n          step={step}\n          run={run}\n          stepRun={stepRun}\n          isActive={isActive}\n        />\n      </section>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/inspector-run.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/field-kit.tsx",
      "content": "'use client';\n\nimport { useId } from 'react';\n\nimport { Avatar } from '@/registry/ndeko/ui/avatar';\nimport { BrandTile } from '@/registry/ndeko/ui/brand-tile';\nimport { LABEL_RECIPE } from '@/registry/ndeko/ui/label';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\nimport { Switch } from '@/registry/ndeko/ui/switch';\n\nimport { modelOf, MODELS, PEOPLE, personOf, type Choice } from './data';\nimport type { ModelId, PersonId } from './model';\n\nexport const GROUP = 'flex flex-col gap-4';\n\nexport const FIELD = 'flex flex-col gap-1.5';\n\nexport const HINT = 'text-muted-foreground text-xs';\n\ntype ChoiceSelectProps<Value extends string> = {\n  label: string;\n  value: Value;\n  choices: Choice<Value>[];\n  onChange: (value: Value) => void;\n};\n\nexport function ChoiceSelect<Value extends string>({\n  label,\n  value,\n  choices,\n  onChange,\n}: ChoiceSelectProps<Value>) {\n  const labelId = useId();\n\n  function change(next: unknown) {\n    const found = choices.find((choice) => choice.value === next);\n    if (found) {\n      onChange(found.value);\n    }\n  }\n\n  return (\n    <div className={FIELD}>\n      <span id={labelId} className={LABEL_RECIPE}>\n        {label}\n      </span>\n      <Select items={choices} value={value} onValueChange={change}>\n        <SelectTrigger aria-labelledby={labelId}>\n          <SelectValue />\n        </SelectTrigger>\n        <SelectContent>\n          {choices.map((choice) => (\n            <SelectItem key={choice.value} value={choice.value}>\n              {choice.label}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n\nconst MODEL_CHOICES: Choice<ModelId>[] = MODELS.map((model) => ({\n  value: model.id,\n  label: model.name,\n}));\n\ntype ModelSelectProps = {\n  value: ModelId;\n  onChange: (modelId: ModelId) => void;\n};\n\n/** A model is named with the mark of its maker, in the field and in its list. */\nexport function ModelSelect({ value, onChange }: ModelSelectProps) {\n  const labelId = useId();\n  const model = modelOf(value);\n\n  function change(next: unknown) {\n    const found = MODELS.find((candidate) => candidate.id === next);\n    if (found) {\n      onChange(found.id);\n    }\n  }\n\n  return (\n    <div className={FIELD}>\n      <span id={labelId} className={LABEL_RECIPE}>\n        Model\n      </span>\n      <Select items={MODEL_CHOICES} value={value} onValueChange={change}>\n        <SelectTrigger aria-labelledby={labelId}>\n          <span className='flex min-w-0 flex-1 items-center gap-2'>\n            <BrandTile brand={model.brand} size='sm' />\n            <SelectValue />\n          </span>\n        </SelectTrigger>\n        <SelectContent>\n          {MODELS.map((option) => (\n            <SelectItem key={option.id} value={option.id}>\n              <BrandTile brand={option.brand} size='sm' />\n              {option.name}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n\ntype SwitchRowProps = {\n  label: string;\n  hint: string;\n  isOn: boolean;\n  onChange: (isOn: boolean) => void;\n};\n\nexport function SwitchRow({ label, hint, isOn, onChange }: SwitchRowProps) {\n  const labelId = useId();\n  const hintId = useId();\n\n  return (\n    <div className='flex items-start gap-3'>\n      <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n        <span id={labelId} className='text-[13px] leading-5 font-medium'>\n          {label}\n        </span>\n        <span id={hintId} className={HINT}>\n          {hint}\n        </span>\n      </div>\n      <Switch\n        checked={isOn}\n        onCheckedChange={onChange}\n        aria-labelledby={labelId}\n        aria-describedby={hintId}\n        className='mt-0.5'\n      />\n    </div>\n  );\n}\n\nconst PERSON_CHOICES: Choice<PersonId>[] = PEOPLE.map((person) => ({\n  value: person.id,\n  label: person.name,\n}));\n\ntype ApproverSelectProps = {\n  value: PersonId;\n  onChange: (approverId: PersonId) => void;\n};\n\nexport function ApproverSelect({ value, onChange }: ApproverSelectProps) {\n  const labelId = useId();\n  const approver = personOf(value);\n\n  function change(next: unknown) {\n    const found = PEOPLE.find((person) => person.id === next);\n    if (found) {\n      onChange(found.id);\n    }\n  }\n\n  return (\n    <div className={FIELD}>\n      <span id={labelId} className={LABEL_RECIPE}>\n        Who is asked\n      </span>\n      <Select items={PERSON_CHOICES} value={value} onValueChange={change}>\n        <SelectTrigger aria-labelledby={labelId}>\n          <span className='flex min-w-0 flex-1 items-center gap-2'>\n            <Avatar seed={approver.name} className='size-4' />\n            <SelectValue />\n          </span>\n        </SelectTrigger>\n        <SelectContent>\n          {PEOPLE.map((person) => (\n            <SelectItem key={person.id} value={person.id}>\n              <Avatar seed={person.name} className='size-4' />\n              <span className='min-w-0 truncate'>{person.name}</span>\n              <span className='text-muted-foreground text-xs'>\n                {person.role}\n              </span>\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/field-kit.tsx"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/use-run-clock.ts",
      "content": "'use client';\n\nimport { useEffect } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\n\nimport type { Workflow } from './model';\nimport { delayOf, type Run } from './run';\n\n/**\n * Plays a run beat by beat, the way a backend would stream it: each beat is asked for once the one\n * before it has had its time. Nothing ticks off screen, in a hidden tab, or while the run waits.\n */\nexport function useRunClock(\n  run: Run,\n  workflow: Workflow,\n  isOnScreen: boolean,\n  onBeat: (token: number, beat: number) => void\n) {\n  const isVisible = useDocumentVisible();\n  const delay = delayOf(run, workflow);\n  const { token, beat } = run;\n  const isPlaying = isOnScreen && isVisible;\n\n  useEffect(() => {\n    if (delay === null || !isPlaying) {\n      return;\n    }\n    const timer = setTimeout(() => onBeat(token, beat), delay);\n    return () => clearTimeout(timer);\n  }, [delay, isPlaying, token, beat, onBeat]);\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/use-run-clock.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/use-focus-later.ts",
      "content": "'use client';\n\nimport { useCallback, type RefObject } from 'react';\n\nexport const CANVAS_FRAME = '[data-canvas-frame]';\n\nexport const INSPECTOR_HEADING = '[data-inspector-heading]';\n\n/**\n * What takes the focus is often drawn by the very change that asks for it: a step that was just\n * added, a sheet that opens. It is looked up once the page has been drawn again, inside the template only.\n */\nexport function useFocusLater(ref: RefObject<HTMLElement | null>) {\n  const focusLater = useCallback(\n    (selector: string) => {\n      requestAnimationFrame(() => {\n        const target = ref.current?.querySelector<HTMLElement>(selector);\n        target?.focus();\n      });\n    },\n    [ref]\n  );\n\n  const focusNode = useCallback(\n    (id: string) => {\n      focusLater(`[data-node=\"${id}\"]`);\n    },\n    [focusLater]\n  );\n\n  return { focusLater, focusNode };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/use-focus-later.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/use-kept.ts",
      "content": "'use client';\n\nimport { useState } from 'react';\n\n/**\n * The value as it was when its key last changed. What reads it draws again only when the key does:\n * the instructions of a step typed key by key leave the canvas as it was.\n */\nexport function useKept<Value>(value: Value, key: string): Value {\n  const [kept, setKept] = useState({ key, value });\n  const isStale = kept.key !== key;\n  if (isStale) {\n    setKept({ key, value });\n    return value;\n  }\n  return kept.value;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/use-kept.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/use-builder-handlers.ts",
      "content": "'use client';\n\nimport { useCallback, useLayoutEffect, useRef, type RefObject } from 'react';\n\nimport { useTimeouts } from '@/registry/ndeko/hooks/use-timeouts';\nimport { usePress } from '@/registry/ndeko/lib/demonstration';\n\nimport type { PaletteEntry } from './catalog';\nimport { previousOf } from './flow';\nimport type { InsertAt, Workflow } from './model';\nimport { waitingIdOf, type Decision } from './run';\nimport { sampleOf, type Sample, type SampleId } from './samples';\nimport { SAVE_MS } from './script';\nimport type { BuilderAction, BuilderState } from './session';\nimport {\n  CANVAS_FRAME,\n  INSPECTOR_HEADING,\n  useFocusLater,\n} from './use-focus-later';\n\n/** How long the line \"Step removed, Undo\" stays in the tool bar. */\nconst NOTICE_MS = 6000;\n\n/** A step picked in the palette goes after the selected one, or at the end of the flow when none is. */\nexport function paletteTargetOf(selectedId: string | null): InsertAt {\n  if (selectedId === null) {\n    return { at: 'end' };\n  }\n  return { at: 'after', stepId: selectedId };\n}\n\nexport type Backend = {\n  onRun?: (workflow: Workflow, sample: Sample) => void;\n  onSave?: (workflow: Workflow) => void;\n  onPublish?: (workflow: Workflow) => void;\n  onApprove?: (stepId: string) => void;\n  onDeny?: (stepId: string) => void;\n};\n\ntype HandlerContext = {\n  state: BuilderState;\n  act: (action: BuilderAction) => void;\n  hasInspectorSheet: boolean;\n  hasPaletteSheet: boolean;\n  backend: Backend;\n};\n\n/**\n * What a person does on the builder. The handlers read the state at the moment they run, so they\n * keep their identity, and the memoised canvas, top bar and tool bar stay still while a step is typed into.\n */\nexport function useBuilderHandlers(\n  rootRef: RefObject<HTMLElement | null>,\n  { state, act, hasInspectorSheet, hasPaletteSheet, backend }: HandlerContext\n) {\n  const { onRun, onSave, onPublish, onApprove, onDeny } = backend;\n  const { schedule } = useTimeouts();\n  const { focusLater, focusNode } = useFocusLater(rootRef);\n  const { pressed: echo, press: echoKey } = usePress<'undo' | 'redo'>();\n  const mintedCount = useRef(0);\n  const latest = useRef(state);\n\n  useLayoutEffect(() => {\n    latest.current = state;\n  });\n\n  const mintId = useCallback(() => {\n    mintedCount.current += 1;\n    return `step-${mintedCount.current}`;\n  }, []);\n\n  /** In the sheet of a narrow page a pick closes the sheet, and the focus goes to the step that arrived. */\n  const pickEntry = useCallback(\n    (entry: PaletteEntry) => {\n      const id = mintId();\n      const at = paletteTargetOf(latest.current.selectedId);\n      act({ type: 'stepAdded', entryId: entry.id, at, id });\n      if (hasPaletteSheet) {\n        act({ type: 'paletteSheet', isOpen: false });\n        focusNode(id);\n      }\n    },\n    [act, mintId, focusNode, hasPaletteSheet]\n  );\n\n  /** Enter or Space on a step moves the focus to the heading of its setup. A tap only selects. */\n  const select = useCallback(\n    (id: string, isFromKeyboard: boolean) => {\n      act({ type: 'selected', id });\n      if (!isFromKeyboard) {\n        return;\n      }\n      if (hasInspectorSheet) {\n        act({ type: 'inspectorSheet', isOpen: true });\n      }\n      focusLater(INSPECTOR_HEADING);\n    },\n    [act, hasInspectorSheet, focusLater]\n  );\n\n  /** Escape in the setup gives the focus back to the step it belongs to. */\n  const leaveInspector = useCallback(() => {\n    const { selectedId } = latest.current;\n    if (hasInspectorSheet) {\n      act({ type: 'inspectorSheet', isOpen: false });\n    }\n    if (selectedId === null) {\n      focusLater(CANVAS_FRAME);\n      return;\n    }\n    focusNode(selectedId);\n  }, [act, hasInspectorSheet, focusLater, focusNode]);\n\n  const openInspector = useCallback(() => {\n    act({ type: 'inspectorSheet', isOpen: true });\n    focusLater(INSPECTOR_HEADING);\n  }, [act, focusLater]);\n\n  const openPalette = useCallback(() => {\n    act({ type: 'paletteSheet', isOpen: true });\n    focusLater('[data-sheet-close=\"palette\"]');\n  }, [act, focusLater]);\n\n  const closePalette = useCallback(() => {\n    act({ type: 'paletteSheet', isOpen: false });\n    focusLater('[data-sheet-open=\"palette\"]');\n  }, [act, focusLater]);\n\n  const forgetNoticeLater = useCallback(() => {\n    const token = latest.current.noticeCount + 1;\n    schedule(() => act({ type: 'noticeCleared', token }), NOTICE_MS);\n  }, [act, schedule]);\n\n  /** The step leaves with its button, so the focus goes to the step read just before it. */\n  const remove = useCallback(\n    (id: string) => {\n      const previous = previousOf(latest.current.workflow, id);\n      act({ type: 'stepRemoved', id });\n      forgetNoticeLater();\n      if (previous) {\n        focusNode(previous.id);\n        return;\n      }\n      focusLater(CANVAS_FRAME);\n    },\n    [act, forgetNoticeLater, focusNode, focusLater]\n  );\n\n  const duplicate = useCallback(\n    (id: string) => {\n      const copyId = mintId();\n      act({ type: 'stepDuplicated', id, copyId });\n      focusNode(copyId);\n    },\n    [act, mintId, focusNode]\n  );\n\n  const insert = useCallback(\n    (at: InsertAt, entry: PaletteEntry) => {\n      const id = mintId();\n      act({ type: 'stepAdded', entryId: entry.id, at, id });\n      focusNode(id);\n    },\n    [act, mintId, focusNode]\n  );\n\n  const renameStep = useCallback(\n    (id: string, name: string) => {\n      act({ type: 'stepRenamed', id, name });\n    },\n    [act]\n  );\n\n  const renameWorkflow = useCallback(\n    (name: string) => {\n      act({ type: 'workflowRenamed', name });\n    },\n    [act]\n  );\n\n  const undo = useCallback(() => {\n    act({ type: 'undone' });\n  }, [act]);\n\n  const redo = useCallback(() => {\n    act({ type: 'redone' });\n  }, [act]);\n\n  /** The line that offered Undo leaves once it is pressed, so the focus goes to the step it brought back. */\n  const undoFromNotice = useCallback(() => {\n    const restoredId = latest.current.notice?.restoresId ?? null;\n    undo();\n    if (restoredId === null) {\n      focusLater(CANVAS_FRAME);\n      return;\n    }\n    focusNode(restoredId);\n  }, [undo, focusLater, focusNode]);\n\n  const undoFromKeys = useCallback(() => {\n    undo();\n    echoKey('undo');\n  }, [undo, echoKey]);\n\n  const redoFromKeys = useCallback(() => {\n    redo();\n    echoKey('redo');\n  }, [redo, echoKey]);\n\n  /** A backend would answer the save itself: here it comes back after a moment. */\n  const save = useCallback(() => {\n    act({ type: 'saveStarted' });\n    schedule(() => act({ type: 'saved' }), SAVE_MS);\n    onSave?.(latest.current.workflow);\n  }, [act, schedule, onSave]);\n\n  const publish = useCallback(\n    (isLive: boolean) => {\n      act({ type: 'published', isLive });\n      forgetNoticeLater();\n      if (isLive) {\n        onPublish?.(latest.current.workflow);\n      }\n    },\n    [act, forgetNoticeLater, onPublish]\n  );\n\n  const startRun = useCallback(\n    (sampleId: SampleId) => {\n      act({ type: 'runStarted', sampleId });\n      onRun?.(latest.current.workflow, sampleOf(sampleId));\n    },\n    [act, onRun]\n  );\n\n  /** Test run in the top bar sends the email of the last run again. */\n  const runAgain = useCallback(() => {\n    startRun(latest.current.run.sampleId);\n  }, [startRun]);\n\n  const clearRun = useCallback(() => {\n    act({ type: 'runCleared' });\n  }, [act]);\n\n  /** The two buttons leave with the card, so the focus goes to the step, which now says what was decided. */\n  const decide = useCallback(\n    (decision: Decision) => {\n      const stepId = waitingIdOf(latest.current.run);\n      act({ type: 'decided', decision });\n      if (stepId === null) {\n        return;\n      }\n      focusNode(stepId);\n      if (decision === 'approved') {\n        onApprove?.(stepId);\n        return;\n      }\n      onDeny?.(stepId);\n    },\n    [act, focusNode, onApprove, onDeny]\n  );\n\n  return {\n    echo,\n    mintId,\n    pickEntry,\n    select,\n    leaveInspector,\n    openInspector,\n    openPalette,\n    closePalette,\n    remove,\n    duplicate,\n    insert,\n    renameStep,\n    renameWorkflow,\n    undo,\n    redo,\n    undoFromNotice,\n    undoFromKeys,\n    redoFromKeys,\n    save,\n    publish,\n    startRun,\n    runAgain,\n    clearRun,\n    decide,\n  };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/use-builder-handlers.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/keys.ts",
      "content": "/**\n * True for Escape pressed inside the element that listens. A list opened from a field is drawn\n * outside its panel, yet its keys still reach the panel: Escape there closes the list and nothing else.\n */\nexport function isEscapeInside(event: React.KeyboardEvent<HTMLElement>) {\n  const target = event.target;\n  const isInside =\n    target instanceof Node && event.currentTarget.contains(target);\n  return event.key === 'Escape' && isInside;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/keys.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/capitalized.ts",
      "content": "/** \"after Track the parcel\" as the start of a line: \"After Track the parcel\". */\nexport function capitalized(text: string) {\n  const first = text.charAt(0);\n  const rest = text.slice(1);\n  return `${first.toUpperCase()}${rest}`;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/capitalized.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/session.ts",
      "content": "import { WORKFLOW } from './data';\nimport type {\n  AgentSetup,\n  ApprovalSetup,\n  InsertAt,\n  LoopRounds,\n  WaitDuration,\n  Workflow,\n} from './model';\nimport {\n  clearedRun,\n  IDLE_RUN,\n  isBusy,\n  isOver,\n  startedRun,\n  type Decision,\n  type Run,\n} from './run';\nimport { advancedRun, decidedRun, type Outcome } from './run-beats';\nimport { sampleOf, type SampleId } from './samples';\nimport {\n  stepAdded,\n  stepDuplicated,\n  stepRemoved,\n  stepRenamed,\n  workflowRenamed,\n} from './session-edits';\nimport { redone, undone } from './session-history';\nimport {\n  actionPicked,\n  agentChanged,\n  approvalChanged,\n  fieldChanged,\n  loopChanged,\n  outputAdded,\n  outputRemoved,\n  outputRenamed,\n  stepReset,\n  waitChanged,\n} from './session-setup';\n\nexport type InspectorTab = 'setup' | 'variables' | 'run';\n\n/** One line in the tool bar about what just happened, with a way back when there is one. */\nexport type Notice = {\n  token: number;\n  text: string;\n  canUndo: boolean;\n  /** The step an Undo brings back, so it is selected again. */\n  restoresId: string | null;\n};\n\n/** `at` is null for the save the sample data starts from: it reads \"Saved 2 min ago\" and never ticks. */\nexport type SaveState = {\n  status: 'saved' | 'saving';\n  at: number | null;\n};\n\nexport type RunTotals = {\n  durationMs: number;\n  costUsd: number;\n};\n\n/** A moment of a run the script waits for: the reply starts to stream, or the run has nothing left to play. */\nexport type Cue = 'reply' | 'settled';\n\nexport type BuilderState = {\n  workflow: Workflow;\n  /** The flow as it was last saved: what Reset gives back, and what \"unsaved\" is measured against. */\n  savedWorkflow: Workflow;\n  /** The flow as it was when Save was pressed. A change made while it saves stays unsaved. */\n  savingWorkflow: Workflow | null;\n  save: SaveState;\n  isLive: boolean;\n  past: Workflow[];\n  future: Workflow[];\n  lastEditKey: string | null;\n  selectedId: string | null;\n  /** The step that was just added: it grows into place and its edges draw themselves. */\n  arrivedId: string | null;\n  tab: InspectorTab;\n  /** The inspector goes to the step that streams, until a person picks a step or a tab themselves. */\n  isFollowingRun: boolean;\n  run: Run;\n  lastRun: RunTotals | null;\n  notice: Notice | null;\n  noticeCount: number;\n  spoken: string;\n  cuesPassed: number;\n  isPaletteOpen: boolean;\n  isInspectorOpen: boolean;\n};\n\nexport type BuilderAction =\n  | { type: 'selected'; id: string | null }\n  | { type: 'tabPicked'; tab: InspectorTab }\n  | { type: 'paletteSheet'; isOpen: boolean }\n  | { type: 'inspectorSheet'; isOpen: boolean }\n  | {\n      type: 'stepAdded';\n      entryId: string;\n      at: InsertAt;\n      id: string;\n      name?: string;\n    }\n  | { type: 'stepRemoved'; id: string }\n  | { type: 'stepDuplicated'; id: string; copyId: string }\n  | { type: 'stepRenamed'; id: string; name: string }\n  | { type: 'workflowRenamed'; name: string }\n  | { type: 'agentChanged'; id: string; patch: Partial<AgentSetup> }\n  | { type: 'approvalChanged'; id: string; patch: Partial<ApprovalSetup> }\n  | { type: 'actionPicked'; id: string; actionId: string }\n  | { type: 'fieldChanged'; id: string; fieldId: string; value: string }\n  | { type: 'waitChanged'; id: string; duration: WaitDuration }\n  | { type: 'loopChanged'; id: string; rounds: LoopRounds }\n  | { type: 'outputAdded'; id: string; outputId: string }\n  | { type: 'outputRenamed'; id: string; outputId: string; label: string }\n  | { type: 'outputRemoved'; id: string; outputId: string }\n  | { type: 'stepReset'; id: string }\n  | { type: 'undone' }\n  | { type: 'redone' }\n  | { type: 'noticeCleared'; token: number }\n  | { type: 'saveStarted' }\n  | { type: 'saved' }\n  | { type: 'published'; isLive: boolean }\n  | { type: 'runStarted'; sampleId: SampleId }\n  | { type: 'runAdvanced'; token: number; beat: number }\n  | { type: 'decided'; decision: Decision }\n  | { type: 'runCleared' }\n  | { type: 'cuePassed'; cue: Cue };\n\nexport const INITIAL: BuilderState = {\n  workflow: WORKFLOW,\n  savedWorkflow: WORKFLOW,\n  savingWorkflow: null,\n  save: { status: 'saved', at: null },\n  isLive: false,\n  past: [],\n  future: [],\n  lastEditKey: null,\n  selectedId: null,\n  arrivedId: null,\n  tab: 'setup',\n  isFollowingRun: false,\n  run: IDLE_RUN,\n  lastRun: null,\n  notice: null,\n  noticeCount: 0,\n  spoken: '',\n  cuesPassed: 0,\n  isPaletteOpen: false,\n  isInspectorOpen: false,\n};\n\n/** Read by content: a Reset, or an edit that puts back what was saved, leaves nothing to save. */\nexport function hasUnsavedChanges(state: BuilderState) {\n  if (state.workflow === state.savedWorkflow) {\n    return false;\n  }\n  const current = JSON.stringify(state.workflow);\n  const saved = JSON.stringify(state.savedWorkflow);\n  return current !== saved;\n}\n\n/** A pick breaks the run of edits that continue one another: typing again later is another step of the history. */\nfunction selected(state: BuilderState, id: string | null): BuilderState {\n  return { ...state, selectedId: id, isFollowingRun: false, lastEditKey: null };\n}\n\nfunction saveStarted(state: BuilderState): BuilderState {\n  if (state.save.status === 'saving') {\n    return state;\n  }\n  return {\n    ...state,\n    savingWorkflow: state.workflow,\n    save: { status: 'saving', at: state.save.at },\n  };\n}\n\nfunction saved(state: BuilderState, now: number): BuilderState {\n  const sent = state.savingWorkflow;\n  const isSaving = state.save.status === 'saving';\n  if (!isSaving || sent === null) {\n    return state;\n  }\n  return {\n    ...state,\n    savedWorkflow: sent,\n    savingWorkflow: null,\n    save: { status: 'saved', at: now },\n    lastEditKey: null,\n    spoken: 'Saved',\n  };\n}\n\nconst LIVE_LINE = 'Live. Every new email now runs through this workflow';\n\nconst DRAFT_LINE = 'Back to draft. New emails wait until you publish again';\n\nfunction publishLineOf(isLive: boolean) {\n  if (isLive) {\n    return LIVE_LINE;\n  }\n  return DRAFT_LINE;\n}\n\n/** Going live or back to draft is confirmed in words, in the tool bar and to a screen reader. */\nfunction published(state: BuilderState, isLive: boolean): BuilderState {\n  if (isLive === state.isLive) {\n    return state;\n  }\n  const noticeCount = state.noticeCount + 1;\n  const text = publishLineOf(isLive);\n  const notice: Notice = {\n    token: noticeCount,\n    text,\n    canUndo: false,\n    restoresId: null,\n  };\n  return { ...state, isLive, notice, noticeCount, spoken: text };\n}\n\nfunction noticeCleared(state: BuilderState, token: number): BuilderState {\n  if (state.notice?.token !== token) {\n    return state;\n  }\n  return { ...state, notice: null };\n}\n\nfunction totalsOf(run: Run): RunTotals {\n  return { durationMs: run.durationMs, costUsd: run.costUsd };\n}\n\nfunction spokenAfter(before: string, spoken: string) {\n  if (spoken === '') {\n    return before;\n  }\n  return spoken;\n}\n\n/** What a beat of the run changes around it: the inspector follows a step that streams, and a finished run leaves its totals. */\nfunction withOutcome(state: BuilderState, outcome: Outcome): BuilderState {\n  const { run } = outcome;\n  const isNewStream = run.streamingId !== state.run.streamingId;\n  const startsStreaming = isNewStream && run.streamingId !== null;\n  const followsStream = startsStreaming && state.isFollowingRun;\n  const hasJustEnded = isOver(run) && !isOver(state.run);\n  let next: BuilderState = {\n    ...state,\n    run,\n    spoken: spokenAfter(state.spoken, outcome.spoken),\n  };\n  if (followsStream) {\n    next = { ...next, selectedId: run.streamingId, tab: 'run' };\n  }\n  if (hasJustEnded) {\n    next = { ...next, lastRun: totalsOf(run) };\n  }\n  return next;\n}\n\nfunction runStarted(state: BuilderState, sampleId: SampleId): BuilderState {\n  if (isBusy(state.run)) {\n    return state;\n  }\n  const sample = sampleOf(sampleId);\n  const run = startedRun(state.run, state.workflow, sampleId);\n  const spoken = `Test run started with the email from ${sample.from}`;\n  return withOutcome({ ...state, isFollowingRun: true }, { run, spoken });\n}\n\nfunction runAdvanced(\n  state: BuilderState,\n  token: number,\n  beat: number\n): BuilderState {\n  const isNextBeat = token === state.run.token && beat === state.run.beat;\n  if (!isNextBeat) {\n    return state;\n  }\n  const outcome = advancedRun(state.run, state.workflow);\n  return withOutcome(state, outcome);\n}\n\nfunction decided(state: BuilderState, decision: Decision): BuilderState {\n  const outcome = decidedRun(state.run, state.workflow, decision);\n  return withOutcome(state, outcome);\n}\n\nfunction runCleared(state: BuilderState): BuilderState {\n  if (isBusy(state.run)) {\n    return state;\n  }\n  return { ...state, run: clearedRun(state.run) };\n}\n\nexport function isCueOpen(state: BuilderState, cue: Cue) {\n  if (!isBusy(state.run)) {\n    return true;\n  }\n  if (cue === 'reply') {\n    return state.run.streamingId !== null;\n  }\n  return false;\n}\n\n/** More beats than any run of the sample flow has: the walk to a cue always ends. */\nconst CUE_BEAT_LIMIT = 200;\n\n/**\n * Live, the script waits for a cue and this only counts it. When the resting state is worked out\n * no clock plays the run, so the run is walked here up to the cue.\n */\nfunction cuePassed(state: BuilderState, cue: Cue): BuilderState {\n  let next = state;\n  for (let beats = 0; beats < CUE_BEAT_LIMIT; beats += 1) {\n    if (isCueOpen(next, cue)) {\n      break;\n    }\n    next = runAdvanced(next, next.run.token, next.run.beat);\n  }\n  return { ...next, cuesPassed: state.cuesPassed + 1 };\n}\n\nexport function applyAt(\n  state: BuilderState,\n  action: BuilderAction,\n  now: number\n): BuilderState {\n  switch (action.type) {\n    case 'selected':\n      return selected(state, action.id);\n    case 'tabPicked':\n      return { ...state, tab: action.tab, isFollowingRun: false };\n    case 'paletteSheet':\n      return { ...state, isPaletteOpen: action.isOpen };\n    case 'inspectorSheet':\n      return { ...state, isInspectorOpen: action.isOpen };\n    case 'stepAdded':\n      return stepAdded(\n        state,\n        action.entryId,\n        action.at,\n        action.id,\n        action.name\n      );\n    case 'stepRemoved':\n      return stepRemoved(state, action.id);\n    case 'stepDuplicated':\n      return stepDuplicated(state, action.id, action.copyId);\n    case 'stepRenamed':\n      return stepRenamed(state, action.id, action.name);\n    case 'workflowRenamed':\n      return workflowRenamed(state, action.name);\n    case 'agentChanged':\n      return agentChanged(state, action.id, action.patch);\n    case 'approvalChanged':\n      return approvalChanged(state, action.id, action.patch);\n    case 'actionPicked':\n      return actionPicked(state, action.id, action.actionId);\n    case 'fieldChanged':\n      return fieldChanged(state, action.id, action.fieldId, action.value);\n    case 'waitChanged':\n      return waitChanged(state, action.id, action.duration);\n    case 'loopChanged':\n      return loopChanged(state, action.id, action.rounds);\n    case 'outputAdded':\n      return outputAdded(state, action.id, action.outputId);\n    case 'outputRenamed':\n      return outputRenamed(state, action.id, action.outputId, action.label);\n    case 'outputRemoved':\n      return outputRemoved(state, action.id, action.outputId);\n    case 'stepReset':\n      return stepReset(state, action.id);\n    case 'undone':\n      return undone(state);\n    case 'redone':\n      return redone(state);\n    case 'noticeCleared':\n      return noticeCleared(state, action.token);\n    case 'saveStarted':\n      return saveStarted(state);\n    case 'saved':\n      return saved(state, now);\n    case 'published':\n      return published(state, action.isLive);\n    case 'runStarted':\n      return runStarted(state, action.sampleId);\n    case 'runAdvanced':\n      return runAdvanced(state, action.token, action.beat);\n    case 'decided':\n      return decided(state, action.decision);\n    case 'runCleared':\n      return runCleared(state);\n    case 'cuePassed':\n      return cuePassed(state, action.cue);\n  }\n}\n\nexport function reducer(state: BuilderState, action: BuilderAction) {\n  return applyAt(state, action, Date.now());\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/session.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/session-edits.ts",
      "content": "import { countOf } from '@/registry/ndeko/lib/words';\n\nimport { entryOf, seriesAfter, stepOfEntry } from './catalog';\nimport { changed, copyOf, inserted, removed } from './edits';\nimport { agentCountOf, placementOf, stepOf, withInside } from './flow';\nimport type { InsertAt, Step, Workflow } from './model';\nimport type { BuilderState, Notice } from './session';\nimport { edited } from './session-history';\n\nfunction namedAs(step: Step, name: string | undefined): Step {\n  if (name === undefined) {\n    return step;\n  }\n  return { ...step, name };\n}\n\n/** A new step takes the selection, and the inspector opens on its setup. */\nfunction arrived(\n  state: BuilderState,\n  step: Step,\n  spoken: string\n): BuilderState {\n  return {\n    ...state,\n    selectedId: step.id,\n    arrivedId: step.id,\n    tab: 'setup',\n    isFollowingRun: false,\n    spoken,\n  };\n}\n\nexport function stepAdded(\n  state: BuilderState,\n  entryId: string,\n  at: InsertAt,\n  id: string,\n  name: string | undefined\n): BuilderState {\n  const entry = entryOf(entryId);\n  if (!entry) {\n    return state;\n  }\n  const agentCount = agentCountOf(state.workflow);\n  const series = seriesAfter(agentCount);\n  const fresh = stepOfEntry(entry, id, series);\n  const step = namedAs(fresh, name);\n  let workflow = inserted(state.workflow, at, step);\n  let placement = placementOf(state.workflow, at);\n  const isPlaceGone = workflow === state.workflow;\n  if (isPlaceGone) {\n    workflow = inserted(state.workflow, { at: 'end' }, step);\n    placement = placementOf(state.workflow, { at: 'end' });\n  }\n  const next = edited(state, workflow, null);\n  return arrived(next, step, `${step.name} added ${placement}`);\n}\n\nfunction removedTextOf(count: number) {\n  if (count === 1) {\n    return 'Step removed';\n  }\n  const steps = countOf(count, 'step', 'steps');\n  return `${steps} removed`;\n}\n\nexport function stepRemoved(state: BuilderState, id: string): BuilderState {\n  const step = stepOf(state.workflow, id);\n  if (!step) {\n    return state;\n  }\n  const gone = withInside(step);\n  const workflow = removed(state.workflow, id);\n  const next = edited(state, workflow, null);\n  const noticeCount = state.noticeCount + 1;\n  const notice: Notice = {\n    token: noticeCount,\n    text: removedTextOf(gone.length),\n    canUndo: true,\n    restoresId: id,\n  };\n  return {\n    ...next,\n    notice,\n    noticeCount,\n    spoken: `${step.name} removed. Undo is in the tool bar`,\n  };\n}\n\n/** A copied agent is another agent: it takes the next series colour, never the one of its model. */\nfunction recolored(copy: Step, workflow: Workflow): Step {\n  if (copy.kind !== 'agent') {\n    return copy;\n  }\n  const agentCount = agentCountOf(workflow);\n  return { ...copy, series: seriesAfter(agentCount) };\n}\n\nexport function stepDuplicated(\n  state: BuilderState,\n  id: string,\n  copyId: string\n): BuilderState {\n  const step = stepOf(state.workflow, id);\n  if (!step) {\n    return state;\n  }\n  const plainCopy = copyOf(step, copyId);\n  const copy = recolored(plainCopy, state.workflow);\n  const after: InsertAt = { at: 'after', stepId: id };\n  const workflow = inserted(state.workflow, after, copy);\n  const next = edited(state, workflow, null);\n  return arrived(next, copy, `${copy.name} added after ${step.name}`);\n}\n\nexport function stepRenamed(\n  state: BuilderState,\n  id: string,\n  name: string\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => ({ ...step, name }));\n  const next = edited(state, workflow, null);\n  return { ...next, spoken: `Renamed to ${name}` };\n}\n\nexport function workflowRenamed(\n  state: BuilderState,\n  name: string\n): BuilderState {\n  if (name === state.workflow.name) {\n    return state;\n  }\n  const next = edited(state, { ...state.workflow, name }, null);\n  return { ...next, spoken: `Workflow renamed to ${name}` };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/session-edits.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/session-history.ts",
      "content": "import { stepOf } from './flow';\nimport type { Workflow } from './model';\nimport { reconciledRun } from './run';\nimport type { BuilderState } from './session';\n\nconst HISTORY_DEPTH = 50;\n\nfunction pastAfter(state: BuilderState, continuesEdit: boolean) {\n  if (continuesEdit) {\n    return state.past;\n  }\n  const grown = [...state.past, state.workflow];\n  return grown.slice(-HISTORY_DEPTH);\n}\n\nfunction selectedIn(workflow: Workflow, id: string | null) {\n  const step = stepOf(workflow, id);\n  if (!step) {\n    return null;\n  }\n  return step.id;\n}\n\n/**\n * Every change to the flow goes through here, so Undo can walk each of them back. Edits that carry\n * the same key continue one another: a text typed key by key is one step of the history.\n */\nexport function edited(\n  state: BuilderState,\n  workflow: Workflow,\n  editKey: string | null\n): BuilderState {\n  if (workflow === state.workflow) {\n    return state;\n  }\n  const continuesEdit = editKey !== null && editKey === state.lastEditKey;\n  return {\n    ...state,\n    workflow,\n    past: pastAfter(state, continuesEdit),\n    future: [],\n    lastEditKey: editKey,\n    arrivedId: null,\n    notice: null,\n    selectedId: selectedIn(workflow, state.selectedId),\n    run: reconciledRun(state.run, workflow),\n  };\n}\n\n/** A walk through the history shows the flow as it was: what was selected stays so only if it is still there. */\nfunction walkedTo(\n  state: BuilderState,\n  workflow: Workflow,\n  past: Workflow[],\n  future: Workflow[]\n): BuilderState {\n  const restoredId = state.notice?.restoresId ?? state.selectedId;\n  return {\n    ...state,\n    workflow,\n    past,\n    future,\n    lastEditKey: null,\n    arrivedId: null,\n    notice: null,\n    selectedId: selectedIn(workflow, restoredId),\n    run: reconciledRun(state.run, workflow),\n  };\n}\n\nexport function undone(state: BuilderState): BuilderState {\n  const previous = state.past.at(-1);\n  if (!previous) {\n    return state;\n  }\n  const past = state.past.slice(0, -1);\n  const future = [state.workflow, ...state.future];\n  const walked = walkedTo(state, previous, past, future);\n  return { ...walked, spoken: 'Undone' };\n}\n\nexport function redone(state: BuilderState): BuilderState {\n  const next = state.future[0];\n  if (!next) {\n    return state;\n  }\n  const past = [...state.past, state.workflow];\n  const future = state.future.slice(1);\n  const walked = walkedTo(state, next, past, future);\n  return { ...walked, spoken: 'Redone' };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/session-history.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/session-setup.ts",
      "content": "import { changed, changedBranch } from './edits';\nimport { stepOf } from './flow';\nimport {\n  BRANCH_MIN_OUTPUTS,\n  isProductStep,\n  type AgentSetup,\n  type ApprovalSetup,\n  type BranchOutput,\n  type BranchStep,\n  type LoopRounds,\n  type Step,\n  type WaitDuration,\n} from './model';\nimport type { BuilderState } from './session';\nimport { edited } from './session-history';\nimport { actionOf, toolOf, valuesOf } from './tools';\n\nexport function agentChanged(\n  state: BuilderState,\n  id: string,\n  patch: Partial<AgentSetup>\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => {\n    if (step.kind !== 'agent') {\n      return step;\n    }\n    return { ...step, agent: { ...step.agent, ...patch } };\n  });\n  const fields = Object.keys(patch).join(' ');\n  return edited(state, workflow, `agent ${id} ${fields}`);\n}\n\nexport function approvalChanged(\n  state: BuilderState,\n  id: string,\n  patch: Partial<ApprovalSetup>\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => {\n    if (step.kind !== 'approval') {\n      return step;\n    }\n    return { ...step, approval: { ...step.approval, ...patch } };\n  });\n  return edited(state, workflow, null);\n}\n\n/** Another action has other fields: they start from what the action holds by default. */\nexport function actionPicked(\n  state: BuilderState,\n  id: string,\n  actionId: string\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => {\n    if (!isProductStep(step)) {\n      return step;\n    }\n    const tool = toolOf(step.tool.toolId);\n    const action = actionOf(tool, actionId);\n    const values = valuesOf(action);\n    return { ...step, tool: { toolId: tool.id, actionId: action.id, values } };\n  });\n  return edited(state, workflow, null);\n}\n\nexport function fieldChanged(\n  state: BuilderState,\n  id: string,\n  fieldId: string,\n  value: string\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => {\n    if (!isProductStep(step)) {\n      return step;\n    }\n    const values = { ...step.tool.values, [fieldId]: value };\n    return { ...step, tool: { ...step.tool, values } };\n  });\n  return edited(state, workflow, `field ${id} ${fieldId}`);\n}\n\nexport function waitChanged(\n  state: BuilderState,\n  id: string,\n  duration: WaitDuration\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => {\n    if (step.kind !== 'wait') {\n      return step;\n    }\n    return { ...step, duration };\n  });\n  return edited(state, workflow, null);\n}\n\nexport function loopChanged(\n  state: BuilderState,\n  id: string,\n  rounds: LoopRounds\n): BuilderState {\n  const workflow = changed(state.workflow, id, (step) => {\n    if (step.kind !== 'loop') {\n      return step;\n    }\n    return { ...step, rounds };\n  });\n  return edited(state, workflow, null);\n}\n\nexport function outputAdded(\n  state: BuilderState,\n  id: string,\n  outputId: string\n): BuilderState {\n  const workflow = changedBranch(state.workflow, id, (branch) => {\n    const rank = branch.outputs.length + 1;\n    const output: BranchOutput = {\n      id: outputId,\n      label: `Output ${rank}`,\n      steps: [],\n    };\n    return { ...branch, outputs: [...branch.outputs, output] };\n  });\n  const next = edited(state, workflow, null);\n  return { ...next, spoken: 'Output added' };\n}\n\nfunction relabelled(output: BranchOutput, outputId: string, label: string) {\n  if (output.id !== outputId) {\n    return output;\n  }\n  return { ...output, label };\n}\n\nexport function outputRenamed(\n  state: BuilderState,\n  id: string,\n  outputId: string,\n  label: string\n): BuilderState {\n  const workflow = changedBranch(state.workflow, id, (branch) => {\n    const outputs = branch.outputs.map((output) =>\n      relabelled(output, outputId, label)\n    );\n    return { ...branch, outputs };\n  });\n  return edited(state, workflow, `output ${id} ${outputId}`);\n}\n\n/** A branch keeps at least two outputs. The steps of the one that goes leave with it. */\nexport function outputRemoved(\n  state: BuilderState,\n  id: string,\n  outputId: string\n): BuilderState {\n  const workflow = changedBranch(state.workflow, id, (branch) => {\n    if (branch.outputs.length <= BRANCH_MIN_OUTPUTS) {\n      return branch;\n    }\n    const outputs = branch.outputs.filter((output) => output.id !== outputId);\n    return { ...branch, outputs };\n  });\n  const next = edited(state, workflow, null);\n  return { ...next, spoken: 'Output removed' };\n}\n\nfunction savedLabelOf(output: BranchOutput, saved: BranchStep) {\n  const match = saved.outputs.find((entry) => entry.id === output.id);\n  if (!match) {\n    return output;\n  }\n  return { ...output, label: match.label };\n}\n\n/**\n * The values of a step as they were saved. For a branch that means the labels of its outputs: the\n * steps it holds are other steps, with their own reset.\n */\nfunction resetOf(step: Step, saved: Step): Step {\n  if (step.kind !== saved.kind) {\n    return step;\n  }\n  if (step.kind !== 'branch') {\n    return saved;\n  }\n  if (saved.kind !== 'branch') {\n    return step;\n  }\n  const outputs = step.outputs.map((output) => savedLabelOf(output, saved));\n  return { ...step, name: saved.name, outputs };\n}\n\nfunction branchDiffers(step: BranchStep, saved: BranchStep) {\n  if (step.name !== saved.name) {\n    return true;\n  }\n  return step.outputs.some((output) => {\n    const relabelledOutput = savedLabelOf(output, saved);\n    return relabelledOutput.label !== output.label;\n  });\n}\n\n/** Whether Reset has something to give back: the step was saved once and reads differently now. */\nexport function differsFromSaved(step: Step, saved: Step | undefined) {\n  if (!saved || step === saved) {\n    return false;\n  }\n  const areBranches = step.kind === 'branch' && saved.kind === 'branch';\n  if (areBranches) {\n    return branchDiffers(step, saved);\n  }\n  const now = JSON.stringify(step);\n  const then = JSON.stringify(saved);\n  return now !== then;\n}\n\nexport function stepReset(state: BuilderState, id: string): BuilderState {\n  const saved = stepOf(state.savedWorkflow, id);\n  if (!saved) {\n    return state;\n  }\n  const workflow = changed(state.workflow, id, (step) => resetOf(step, saved));\n  const next = edited(state, workflow, null);\n  return { ...next, spoken: `${saved.name} is back to its saved values` };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/session-setup.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/script.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\nimport { keyDelayOf, prefixesOf } from '@/registry/ndeko/lib/demonstration';\nimport { restingOf } from '@/registry/ndeko/lib/run-session';\n\nimport { pressKeyOf } from './catalog';\nimport { DEMO_STEP } from './data';\nimport { nodePressKeyOf } from './flow';\nimport { samplePressKeyOf } from './samples';\nimport {\n  applyAt,\n  INITIAL,\n  isCueOpen,\n  type BuilderAction,\n  type BuilderState,\n  type Cue,\n} from './session';\n\ntype Step = SessionStep<BuilderState, BuilderAction>;\n\n/** The pace a person types at, the default of the library: the script has no need of a faster one. */\nconst KEY_MS = 42;\n\nexport const SAVE_MS = 900;\n\n/** A request that waits on a person is answered by the demonstration after this long. */\nconst DEMO_DECIDES_AFTER_MS = 2500;\n\nfunction hasRunOnce(state: BuilderState) {\n  return state.run.token >= 1;\n}\n\nfunction hasRunTwice(state: BuilderState) {\n  return state.run.token >= 2;\n}\n\nfunction hasNoRequest(state: BuilderState) {\n  return state.run.phase !== 'waiting';\n}\n\nfunction typingSteps(text: string, startAfter: number): Step[] {\n  const prefixes = prefixesOf(text);\n  return prefixes.map((typed, index) => ({\n    after: keyDelayOf(index, startAfter, KEY_MS),\n    by: 'demo',\n    action: {\n      type: 'agentChanged',\n      id: DEMO_STEP.id,\n      patch: { instructions: typed },\n    },\n  }));\n}\n\n/** The run is played by its own clock. The script waits here until the run reaches the cue. */\nfunction waitFor(cue: Cue): Step {\n  return { after: 0, action: { type: 'cuePassed', cue } };\n}\n\nfunction sheet(\n  after: number,\n  type: 'paletteSheet' | 'inspectorSheet',\n  isOpen: boolean\n): Step {\n  return { after, by: 'demo', action: { type, isOpen } };\n}\n\n/**\n * A step is added to the Delivery branch and set up. On a narrow page the palette and the inspector\n * live in sheets, which the demonstration opens and closes as a person would.\n */\nconst BUILDING: Step[] = [\n  {\n    after: 1200,\n    by: 'demo',\n    press: nodePressKeyOf(DEMO_STEP.afterId),\n    action: { type: 'selected', id: DEMO_STEP.afterId },\n  },\n  sheet(450, 'paletteSheet', true),\n  {\n    after: 800,\n    by: 'demo',\n    press: pressKeyOf(DEMO_STEP.entryId),\n    action: {\n      type: 'stepAdded',\n      entryId: DEMO_STEP.entryId,\n      at: { at: 'after', stepId: DEMO_STEP.afterId },\n      id: DEMO_STEP.id,\n      name: DEMO_STEP.name,\n    },\n  },\n  sheet(350, 'paletteSheet', false),\n  sheet(300, 'inspectorSheet', true),\n  ...typingSteps(DEMO_STEP.instructions, 600),\n  sheet(500, 'inspectorSheet', false),\n  { after: 400, by: 'demo', press: 'save', action: { type: 'saveStarted' } },\n  { after: SAVE_MS, action: { type: 'saved' } },\n];\n\n/**\n * Two runs: a delivery question that goes through the new step, then a refund that stops on the\n * approval. Starting a run and answering the approval are the steps of a person.\n */\nconst RUNNING: Step[] = [\n  {\n    after: 1000,\n    by: 'person',\n    press: 'run',\n    action: { type: 'runStarted', sampleId: 'delivery' },\n    isAnswered: hasRunOnce,\n  },\n  waitFor('reply'),\n  sheet(250, 'inspectorSheet', true),\n  waitFor('settled'),\n  sheet(1000, 'inspectorSheet', false),\n  {\n    after: 1100,\n    by: 'person',\n    press: samplePressKeyOf('refund'),\n    action: { type: 'runStarted', sampleId: 'refund' },\n    isAnswered: hasRunTwice,\n  },\n  waitFor('settled'),\n  {\n    after: DEMO_DECIDES_AFTER_MS,\n    by: 'person',\n    press: 'allow',\n    action: { type: 'decided', decision: 'approved' },\n    isAnswered: hasNoRequest,\n  },\n  waitFor('reply'),\n  sheet(250, 'inspectorSheet', true),\n  waitFor('settled'),\n  sheet(1000, 'inspectorSheet', false),\n];\n\nexport const SCRIPT: Step[] = [...BUILDING, ...RUNNING];\n\nfunction cuesOf(steps: Step[]) {\n  const cues: Cue[] = [];\n  for (const step of steps) {\n    if (step.action.type === 'cuePassed') {\n      cues.push(step.action.cue);\n    }\n  }\n  return cues;\n}\n\nconst CUES = cuesOf(SCRIPT);\n\n/** The steps of the system hold while the run has not reached the cue the script waits for. */\nexport function holdsForRun(state: BuilderState) {\n  const cue = CUES[state.cuesPassed] ?? 'settled';\n  return !isCueOpen(state, cue);\n}\n\nconst PLAYED = restingOf(INITIAL, SCRIPT, applyAt);\n\n/** Under reduced motion the flow shows its last run finished: the Refund branch taken, the others skipped, the reply written. */\nexport const RESTING: BuilderState = {\n  ...PLAYED,\n  save: { status: 'saved', at: null },\n  arrivedId: null,\n  notice: null,\n  spoken: '',\n  isPaletteOpen: false,\n  isInspectorOpen: false,\n};\n\nexport const LOOP_AFTER_MS = 3600;\n",
      "type": "registry:component",
      "target": "components/templates/application-14/script.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/run.ts",
      "content": "import { wordsOf } from '@/registry/ndeko/lib/words';\n\nimport { stepOf } from './flow';\nimport type { Step, Workflow } from './model';\nimport {\n  FAILED_TRY_MS,\n  resultOf,\n  sampleOf,\n  type Sample,\n  type SampleId,\n} from './samples';\n\nexport type RunPhase = 'idle' | 'running' | 'waiting' | 'done' | 'stopped';\n\nexport type StepStatus =\n  'running' | 'failed' | 'retrying' | 'waiting' | 'done' | 'denied' | 'skipped';\n\nexport type Decision = 'approved' | 'denied';\n\nexport type StepRun = {\n  status: StepStatus;\n  ms: number;\n  usd: number;\n  /** One line the card shows in place of the kind: what a branch took, why a try failed. */\n  note: string | null;\n};\n\nexport type Beat = {\n  kind: 'start' | 'finish' | 'retry';\n  stepId: string;\n};\n\nexport type Run = {\n  /** Counts the runs, so what belongs to an earlier one can be told apart. */\n  token: number;\n  sampleId: SampleId;\n  phase: RunPhase;\n  /** Counts the beats played in this run: a timer that fires late cannot play one twice. */\n  beat: number;\n  next: Beat | null;\n  steps: Partial<Record<string, StepRun>>;\n  taken: string[];\n  choices: Partial<Record<string, string>>;\n  streamingId: string | null;\n  decision: Decision | null;\n  durationMs: number;\n  costUsd: number;\n};\n\nexport const WORD_MS = 45;\n\n/** A stream is given a little longer than its words need, so its last word lands before the step ends. */\nconst STREAM_MARGIN_MS = 400;\n\nconst START_MS = 500;\n\n/** The run waits this long between two steps: the time the dot takes along the edge. */\nexport const TRAVEL_MS = 380;\n\n/** How long a failure stays on the card before the step tries again. */\nconst RETRY_AFTER_MS = 800;\n\n/** The agent whose answer carries this name writes the email that goes back to the customer. */\nconst REPLY_NAME = 'reply';\n\nexport const IDLE_RUN: Run = {\n  token: 0,\n  sampleId: 'delivery',\n  phase: 'idle',\n  beat: 0,\n  next: null,\n  steps: {},\n  taken: [],\n  choices: {},\n  streamingId: null,\n  decision: null,\n  durationMs: 0,\n  costUsd: 0,\n};\n\nexport function isBusy(run: Run) {\n  return run.phase === 'running';\n}\n\nexport function isOver(run: Run) {\n  return run.phase === 'done' || run.phase === 'stopped';\n}\n\nexport function hasRun(run: Run) {\n  return run.phase !== 'idle';\n}\n\nexport function startedRun(\n  run: Run,\n  workflow: Workflow,\n  sampleId: SampleId\n): Run {\n  const token = run.token + 1;\n  const fresh: Run = { ...IDLE_RUN, token, sampleId };\n  const first = workflow.steps[0];\n  if (!first) {\n    return { ...fresh, phase: 'done' };\n  }\n  const next: Beat = { kind: 'start', stepId: first.id };\n  return { ...fresh, phase: 'running', next };\n}\n\n/** The marks of the last run leave the canvas. The count of runs stays, so a late timer still misses. */\nexport function clearedRun(run: Run): Run {\n  return { ...IDLE_RUN, token: run.token, sampleId: run.sampleId };\n}\n\nexport function waitingIdOf(run: Run) {\n  const entries = Object.entries(run.steps);\n  const waiting = entries.find(([, stepRun]) => stepRun?.status === 'waiting');\n  if (!waiting) {\n    return null;\n  }\n  return waiting[0];\n}\n\nfunction isLive(stepRun: StepRun | undefined) {\n  const status = stepRun?.status;\n  const isAtWork = status === 'running' || status === 'retrying';\n  return isAtWork || status === 'waiting';\n}\n\nexport function liveIdOf(run: Run) {\n  const entries = Object.entries(run.steps);\n  const live = entries.find(([, stepRun]) => isLive(stepRun));\n  if (!live) {\n    return null;\n  }\n  return live[0];\n}\n\n/** A failed try is followed by another one: a run that stops in between leaves the step unfinished too. */\nfunction isUnfinished(stepRun: StepRun | undefined) {\n  const hasFailedTry = stepRun?.status === 'failed';\n  return isLive(stepRun) || hasFailedTry;\n}\n\n/**\n * A run that stops keeps what its steps did and drops what they were still doing: nothing would ever\n * end it, and an Undo that brings the step back would show it at work or waiting for good.\n */\nexport function stoppedRun(run: Run): Run {\n  const steps: Partial<Record<string, StepRun>> = {};\n  for (const [id, stepRun] of Object.entries(run.steps)) {\n    if (!isUnfinished(stepRun)) {\n      steps[id] = stepRun;\n    }\n  }\n  return { ...run, steps, phase: 'stopped', next: null, streamingId: null };\n}\n\n/** A run that waits on a step that is gone has nothing left to wait for. */\nexport function reconciledRun(run: Run, workflow: Workflow): Run {\n  if (run.phase !== 'waiting') {\n    return run;\n  }\n  const waitingId = waitingIdOf(run);\n  const step = stepOf(workflow, waitingId);\n  if (step) {\n    return run;\n  }\n  return stoppedRun(run);\n}\n\n/** Only an agent writes prose. The others give a result with named parts. */\nfunction textOf(step: Step, sample: Sample, decision: Decision | null) {\n  if (step.kind !== 'agent') {\n    return null;\n  }\n  if (step.agent.outputName !== REPLY_NAME) {\n    const result = resultOf(sample, step);\n    return result.text ?? null;\n  }\n  if (decision === 'denied') {\n    return sample.replyIfDenied;\n  }\n  return sample.reply;\n}\n\nfunction streamMsOf(text: string) {\n  const words = wordsOf(text);\n  return words.length * WORD_MS + STREAM_MARGIN_MS;\n}\n\n/** A step that streams runs for as long as its text takes to arrive. */\nexport function tryMsOf(step: Step, sample: Sample, decision: Decision | null) {\n  const result = resultOf(sample, step);\n  const text = textOf(step, sample, decision);\n  const isStreamed = step.kind === 'agent' && step.agent.streams;\n  const followsText = isStreamed || result.ms === 0;\n  if (text !== null && followsText) {\n    return streamMsOf(text);\n  }\n  return result.ms;\n}\n\nexport function failsNow(run: Run, step: Step, sample: Sample) {\n  const isTheOne = sample.failure?.stepId === step.id;\n  const isFirstTry = run.steps[step.id]?.status === 'running';\n  return isTheOne && isFirstTry;\n}\n\nfunction startDelayOf(run: Run) {\n  if (run.beat === 0) {\n    return START_MS;\n  }\n  return TRAVEL_MS;\n}\n\n/** How long to wait before the next beat. Null while the run has nothing to play. */\nexport function delayOf(run: Run, workflow: Workflow) {\n  const beat = run.next;\n  if (run.phase !== 'running' || beat === null) {\n    return null;\n  }\n  if (beat.kind === 'retry') {\n    return RETRY_AFTER_MS;\n  }\n  if (beat.kind === 'start') {\n    return startDelayOf(run);\n  }\n  const step = stepOf(workflow, beat.stepId);\n  if (!step) {\n    return 0;\n  }\n  const sample = sampleOf(run.sampleId);\n  if (failsNow(run, step, sample)) {\n    return FAILED_TRY_MS;\n  }\n  return tryMsOf(step, sample, run.decision);\n}\n\nexport type StepExchange = {\n  input: Record<string, unknown>;\n  output: Record<string, unknown>;\n  text: string | null;\n};\n\n/** An approval gives what the person decided, so its output is not in the recorded results. */\nexport function exchangeOf(run: Run, step: Step): StepExchange {\n  const sample = sampleOf(run.sampleId);\n  const result = resultOf(sample, step);\n  const text = textOf(step, sample, run.decision);\n  if (step.kind !== 'approval') {\n    return { input: result.input, output: result.output, text };\n  }\n  const status = run.steps[step.id]?.status;\n  if (status === 'done') {\n    return { input: result.input, output: { decision: 'approved' }, text };\n  }\n  if (status === 'denied') {\n    return { input: result.input, output: { decision: 'denied' }, text };\n  }\n  return { input: result.input, output: {}, text };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/run.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/run-beats.ts",
      "content": "import { formatDuration } from '@/registry/ndeko/lib/agent-run';\n\nimport {\n  edgeIdOf,\n  firstOf,\n  joinAfter,\n  outputNamed,\n  restAfter,\n  stepOf,\n  successorOf,\n  withInside,\n} from './flow';\nimport type { BranchOutput, BranchStep, Step, Workflow } from './model';\nimport {\n  failsNow,\n  stoppedRun,\n  tryMsOf,\n  waitingIdOf,\n  type Beat,\n  type Decision,\n  type Run,\n  type StepRun,\n} from './run';\nimport { FAILED_TRY_MS, resultOf, sampleOf, type Sample } from './samples';\n\nexport type Outcome = {\n  run: Run;\n  /** The one line a screen reader hears about the beat. Empty when there is nothing to say. */\n  spoken: string;\n};\n\nfunction withStep(run: Run, id: string, stepRun: StepRun): Run {\n  return { ...run, steps: { ...run.steps, [id]: stepRun } };\n}\n\nfunction withSkipped(run: Run, skipped: Step[]): Run {\n  const steps = { ...run.steps };\n  for (const step of skipped) {\n    steps[step.id] = { status: 'skipped', ms: 0, usd: 0, note: null };\n  }\n  return { ...run, steps };\n}\n\nfunction stopped(run: Run): Outcome {\n  const ended = stoppedRun(run);\n  return { run: ended, spoken: 'The run stopped: its next step was removed' };\n}\n\n/** The run takes the edge out of a step, then goes on with what it leads to or ends there. */\nfunction handedOver(\n  run: Run,\n  target: Step | null,\n  edgeId: string,\n  spoken: string\n): Outcome {\n  const taken = [...run.taken, edgeId];\n  if (!target) {\n    const total = formatDuration(run.durationMs);\n    const ended: Run = { ...run, taken, phase: 'done', next: null };\n    return { run: ended, spoken: `${spoken}. Run finished in ${total}` };\n  }\n  const next: Beat = { kind: 'start', stepId: target.id };\n  return { run: { ...run, taken, next }, spoken };\n}\n\nfunction streamingIdOf(step: Step) {\n  const isStreamed = step.kind === 'agent' && step.agent.streams;\n  if (isStreamed) {\n    return step.id;\n  }\n  return null;\n}\n\nfunction startedStep(run: Run, step: Step): Outcome {\n  if (step.kind === 'approval') {\n    const sample = sampleOf(run.sampleId);\n    const asked = sample.request?.spoken ?? step.name;\n    const waiting = withStep(run, step.id, {\n      status: 'waiting',\n      ms: 0,\n      usd: 0,\n      note: 'Waiting for you',\n    });\n    return {\n      run: { ...waiting, phase: 'waiting', next: null },\n      spoken: `Waiting for you: ${asked}`,\n    };\n  }\n  const running = withStep(run, step.id, {\n    status: 'running',\n    ms: 0,\n    usd: 0,\n    note: null,\n  });\n  const next: Beat = { kind: 'finish', stepId: step.id };\n  const streamingId = streamingIdOf(step);\n  return { run: { ...running, next, streamingId }, spoken: '' };\n}\n\nfunction retriedStep(run: Run, step: Step): Outcome {\n  const spentMs = run.steps[step.id]?.ms ?? 0;\n  const retrying = withStep(run, step.id, {\n    status: 'retrying',\n    ms: spentMs,\n    usd: 0,\n    note: 'Trying again',\n  });\n  const next: Beat = { kind: 'finish', stepId: step.id };\n  return { run: { ...retrying, next }, spoken: '' };\n}\n\nfunction failedStep(run: Run, step: Step, sample: Sample): Outcome {\n  const error = sample.failure?.error ?? 'It did not answer';\n  const failed = withStep(run, step.id, {\n    status: 'failed',\n    ms: FAILED_TRY_MS,\n    usd: 0,\n    note: error,\n  });\n  const next: Beat = { kind: 'retry', stepId: step.id };\n  return {\n    run: { ...failed, next },\n    spoken: `${step.name} failed: ${error}. Trying again`,\n  };\n}\n\nfunction doneNoteOf(step: Step, wasRetried: boolean) {\n  if (wasRetried) {\n    return 'Done on the second try';\n  }\n  if (step.kind === 'wait') {\n    return 'A test run does not wait';\n  }\n  if (step.kind === 'loop') {\n    return 'A test run plays it once';\n  }\n  return null;\n}\n\nfunction insideOfOutput(output: BranchOutput) {\n  return output.steps.flatMap(withInside);\n}\n\n/** A branch takes the output that carries the topic of the sample, or its last one when none does. */\nfunction routed(\n  run: Run,\n  workflow: Workflow,\n  branch: BranchStep,\n  sample: Sample\n): Outcome {\n  const named = outputNamed(branch, sample.topic);\n  const output = named ?? branch.outputs.at(-1);\n  if (!output) {\n    return stopped(run);\n  }\n  const others = branch.outputs.filter((other) => other.id !== output.id);\n  const leftOut = others.flatMap(insideOfOutput);\n  const skipped = withSkipped(run, leftOut);\n  const spentMs = skipped.steps[branch.id]?.ms ?? 0;\n  const noted = withStep(skipped, branch.id, {\n    status: 'done',\n    ms: spentMs,\n    usd: 0,\n    note: `Took ${output.label}`,\n  });\n  const choices = { ...noted.choices, [branch.id]: output.id };\n  const target = firstOf(workflow, branch, output);\n  const edgeId = edgeIdOf(branch.id, output.id);\n  const spoken = `${branch.name} took ${output.label}`;\n  return handedOver({ ...noted, choices }, target, edgeId, spoken);\n}\n\nfunction finishedStep(run: Run, workflow: Workflow, step: Step): Outcome {\n  const sample = sampleOf(run.sampleId);\n  if (failsNow(run, step, sample)) {\n    return failedStep(run, step, sample);\n  }\n  const before = run.steps[step.id];\n  const wasRetried = before?.status === 'retrying';\n  const spentMs = before?.ms ?? 0;\n  const result = resultOf(sample, step);\n  const tryMs = tryMsOf(step, sample, run.decision);\n  const ms = spentMs + tryMs;\n  const done = withStep(run, step.id, {\n    status: 'done',\n    ms,\n    usd: result.usd,\n    note: doneNoteOf(step, wasRetried),\n  });\n  const counted: Run = {\n    ...done,\n    streamingId: null,\n    durationMs: run.durationMs + ms,\n    costUsd: run.costUsd + result.usd,\n  };\n  if (step.kind === 'branch') {\n    return routed(counted, workflow, step, sample);\n  }\n  const target = successorOf(workflow, step.id);\n  const edgeId = edgeIdOf(step.id, null);\n  const spoken = `${step.name} done in ${formatDuration(ms)}`;\n  return handedOver(counted, target, edgeId, spoken);\n}\n\nexport function advancedRun(run: Run, workflow: Workflow): Outcome {\n  const beat = run.next;\n  if (run.phase !== 'running' || beat === null) {\n    return { run, spoken: '' };\n  }\n  const played: Run = { ...run, beat: run.beat + 1 };\n  const step = stepOf(workflow, beat.stepId);\n  if (!step) {\n    return stopped(played);\n  }\n  if (beat.kind === 'start') {\n    return startedStep(played, step);\n  }\n  if (beat.kind === 'retry') {\n    return retriedStep(played, step);\n  }\n  return finishedStep(played, workflow, step);\n}\n\n/**\n * Allow lets the run go on. Deny stops its branch there: what was left of the branch is skipped and\n * the run goes on from the step where the branches join, or ends when the approval sat on the trunk.\n */\nexport function decidedRun(\n  run: Run,\n  workflow: Workflow,\n  decision: Decision\n): Outcome {\n  if (run.phase !== 'waiting') {\n    return { run, spoken: '' };\n  }\n  const waitingId = waitingIdOf(run);\n  const step = stepOf(workflow, waitingId);\n  if (!step) {\n    return stopped(run);\n  }\n  const answered: Run = { ...run, phase: 'running', decision };\n  if (decision === 'approved') {\n    const allowed = withStep(answered, step.id, {\n      status: 'done',\n      ms: 0,\n      usd: 0,\n      note: 'Allowed by you',\n    });\n    const target = successorOf(workflow, step.id);\n    const edgeId = edgeIdOf(step.id, null);\n    return handedOver(allowed, target, edgeId, 'Allowed by you');\n  }\n  const denied = withStep(answered, step.id, {\n    status: 'denied',\n    ms: 0,\n    usd: 0,\n    note: 'Denied by you',\n  });\n  const leftOut = restAfter(workflow, step.id);\n  const skipped = withSkipped(denied, leftOut);\n  const target = joinAfter(workflow, step.id);\n  if (!target) {\n    const ended: Run = { ...skipped, phase: 'stopped', next: null };\n    return { run: ended, spoken: 'Denied. The run stops here' };\n  }\n  const next: Beat = { kind: 'start', stepId: target.id };\n  return {\n    run: { ...skipped, next },\n    spoken:\n      'Denied. The branch stops here and the reply says a person will follow up',\n  };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/run-beats.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/flow.ts",
      "content": "import {\n  isProductStep,\n  type BranchOutput,\n  type BranchStep,\n  type InsertAt,\n  type Step,\n  type Workflow,\n} from './model';\n\n/** A step with its place in the flow: its rank when the flow is read from top to bottom, the outputs of a branch left to right. */\nexport type Placed = {\n  step: Step;\n  position: number;\n  /** The label of the nearest output of a branch that holds the step. */\n  branchLabel: string | null;\n};\n\ntype Hold = {\n  list: Step[];\n  index: number;\n};\n\nfunction visit(steps: Step[], branchLabel: string | null, into: Placed[]) {\n  for (const step of steps) {\n    const position = into.length + 1;\n    into.push({ step, position, branchLabel });\n    if (step.kind !== 'branch') {\n      continue;\n    }\n    for (const output of step.outputs) {\n      visit(output.steps, output.label, into);\n    }\n  }\n}\n\nexport function walkOf(workflow: Workflow) {\n  const placed: Placed[] = [];\n  visit(workflow.steps, null, placed);\n  return placed;\n}\n\nexport function withInside(step: Step) {\n  const placed: Placed[] = [];\n  visit([step], null, placed);\n  return placed.map((entry) => entry.step);\n}\n\nfunction trailIn(list: Step[], id: string): Hold[] | null {\n  for (const [index, step] of list.entries()) {\n    if (step.id === id) {\n      return [{ list, index }];\n    }\n    if (step.kind !== 'branch') {\n      continue;\n    }\n    for (const output of step.outputs) {\n      const inner = trailIn(output.steps, id);\n      if (inner) {\n        return [{ list, index }, ...inner];\n      }\n    }\n  }\n  return null;\n}\n\n/** The lists that hold a step, from the flow itself down to the list the step sits in. */\nfunction trailOf(workflow: Workflow, id: string) {\n  return trailIn(workflow.steps, id);\n}\n\nexport function stepOf(workflow: Workflow, id: string | null) {\n  if (id === null) {\n    return undefined;\n  }\n  const placed = walkOf(workflow);\n  const found = placed.find((entry) => entry.step.id === id);\n  return found?.step;\n}\n\nfunction branchOf(workflow: Workflow, id: string) {\n  const step = stepOf(workflow, id);\n  if (step?.kind !== 'branch') {\n    return undefined;\n  }\n  return step;\n}\n\n/** The output of a branch whose label reads like `label`, whatever its case. */\nexport function outputNamed(branch: BranchStep, label: string) {\n  const wanted = label.trim().toLowerCase();\n  return branch.outputs.find((output) => {\n    const own = output.label.trim().toLowerCase();\n    return own === wanted;\n  });\n}\n\n/** What runs once a step is over: the next one of its list, or the one after the branch that holds it. */\nfunction afterOf(trail: Hold[]) {\n  for (let depth = trail.length - 1; depth >= 0; depth -= 1) {\n    const hold = trail[depth];\n    const next = hold.list[hold.index + 1];\n    if (next) {\n      return next;\n    }\n  }\n  return null;\n}\n\nexport function successorOf(workflow: Workflow, id: string) {\n  const trail = trailOf(workflow, id);\n  if (!trail) {\n    return null;\n  }\n  return afterOf(trail);\n}\n\n/** What runs once the whole list that holds a step is over: the step where its branch joins, if it sits in one. */\nexport function joinAfter(workflow: Workflow, id: string) {\n  const trail = trailOf(workflow, id);\n  if (!trail) {\n    return null;\n  }\n  const outer = trail.slice(0, -1);\n  return afterOf(outer);\n}\n\n/** An empty output hands over at once to the step where the outputs join. */\nexport function firstOf(\n  workflow: Workflow,\n  branch: BranchStep,\n  output: BranchOutput\n) {\n  const first = output.steps[0];\n  if (first) {\n    return first;\n  }\n  return successorOf(workflow, branch.id);\n}\n\n/** The steps after `id` in its own list, with all they hold. They are what a denied approval leaves out. */\nexport function restAfter(workflow: Workflow, id: string) {\n  const trail = trailOf(workflow, id);\n  const hold = trail?.at(-1);\n  if (!hold) {\n    return [];\n  }\n  const rest = hold.list.slice(hold.index + 1);\n  return rest.flatMap(withInside);\n}\n\n/**\n * Every step that has run when `id` starts: what comes before it in each list that holds it. The\n * other outputs of its own branch are left out, since they never run in the same pass.\n */\nexport function upstreamOf(workflow: Workflow, id: string) {\n  const trail = trailOf(workflow, id);\n  if (!trail) {\n    return [];\n  }\n  const ids = new Set<string>();\n  for (const hold of trail) {\n    const earlier = hold.list.slice(0, hold.index);\n    const steps = earlier.flatMap(withInside);\n    for (const step of steps) {\n      ids.add(step.id);\n    }\n  }\n  const placed = walkOf(workflow);\n  return placed.filter((entry) => ids.has(entry.step.id));\n}\n\nexport function previousOf(workflow: Workflow, id: string) {\n  const placed = walkOf(workflow);\n  const index = placed.findIndex((entry) => entry.step.id === id);\n  if (index <= 0) {\n    return null;\n  }\n  return placed[index - 1].step;\n}\n\nexport function countsOf(workflow: Workflow) {\n  const placed = walkOf(workflow);\n  let branches = 0;\n  for (const entry of placed) {\n    if (entry.step.kind === 'branch') {\n      branches += entry.step.outputs.length;\n    }\n  }\n  return { steps: placed.length, branches };\n}\n\nexport function agentCountOf(workflow: Workflow) {\n  const placed = walkOf(workflow);\n  const agents = placed.filter((entry) => entry.step.kind === 'agent');\n  return agents.length;\n}\n\nexport function nodePressKeyOf(stepId: string) {\n  return `node-${stepId}`;\n}\n\n/** A step has one way out, a branch one for each output: that is enough to name an edge. */\nexport function edgeIdOf(fromId: string, outputId: string | null) {\n  if (outputId === null) {\n    return fromId;\n  }\n  return `${fromId}:${outputId}`;\n}\n\n/** The label each output of a branch carries on its edge, by the id of that edge. */\nexport function outputLabelsOf(workflow: Workflow) {\n  const labels: Record<string, string> = {};\n  for (const { step } of walkOf(workflow)) {\n    if (step.kind !== 'branch') {\n      continue;\n    }\n    for (const output of step.outputs) {\n      const edgeId = edgeIdOf(step.id, output.id);\n      labels[edgeId] = output.label;\n    }\n  }\n  return labels;\n}\n\ntype KeyPart = string | number | KeyPart[];\n\nfunction shapeOfStep(step: Step): KeyPart[] {\n  if (step.kind !== 'branch') {\n    return [step.id, step.kind];\n  }\n  const outputs = step.outputs.map(shapeOfOutput);\n  return [step.id, step.kind, outputs];\n}\n\nfunction shapeOfOutput(output: BranchOutput): KeyPart[] {\n  const steps = output.steps.map(shapeOfStep);\n  return [output.id, steps];\n}\n\n/** What the layout reads: the ids, the kinds, the outputs of each branch and their order. Never a name or a setting. */\nexport function structureKeyOf(workflow: Workflow) {\n  const steps = workflow.steps.map(shapeOfStep);\n  return JSON.stringify(steps);\n}\n\nfunction pictureOf(step: Step): KeyPart[] {\n  if (step.kind === 'agent') {\n    return [step.seed, step.series];\n  }\n  if (isProductStep(step)) {\n    return [step.tool.toolId];\n  }\n  return [];\n}\n\nfunction faceOfStep(step: Step): KeyPart[] {\n  const picture = pictureOf(step);\n  const face: KeyPart[] = [step.id, step.kind, step.name, picture];\n  if (step.kind === 'branch') {\n    const outputs = step.outputs.map(faceOfOutput);\n    face.push(outputs);\n  }\n  return face;\n}\n\nfunction faceOfOutput(output: BranchOutput): KeyPart[] {\n  const steps = output.steps.map(faceOfStep);\n  return [output.id, output.label, steps];\n}\n\n/**\n * What the canvas shows: the structure, the names, the pictures and the labels of the outputs.\n * Instructions and the other settings are not in it, so typing them leaves the canvas as it is.\n */\nexport function faceKeyOf(workflow: Workflow) {\n  const steps = workflow.steps.map(faceOfStep);\n  return JSON.stringify([workflow.name, steps]);\n}\n\nconst AT_THE_END = 'at the end of the flow';\n\n/** Where a new step would go, in words that follow \"Add a step\": after Track the parcel, first in Refund. */\nexport function placementOf(workflow: Workflow, at: InsertAt) {\n  if (at.at === 'end') {\n    return AT_THE_END;\n  }\n  if (at.at === 'first') {\n    const branch = branchOf(workflow, at.branchId);\n    const output = branch?.outputs.find((entry) => entry.id === at.outputId);\n    const label = output?.label ?? 'this output';\n    return `first in ${label}`;\n  }\n  const step = stepOf(workflow, at.stepId);\n  if (!step) {\n    return AT_THE_END;\n  }\n  if (step.kind === 'branch') {\n    return `where the outputs of ${step.name} join`;\n  }\n  return `after ${step.name}`;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/flow.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/edits.ts",
      "content": "import type {\n  BranchOutput,\n  BranchStep,\n  InsertAt,\n  Step,\n  Workflow,\n} from './model';\n\ntype ListEdit = (list: Step[], index: number) => Step[];\n\n/** Every list and step an edit does not touch keeps its identity, so only what changed is drawn again. */\nfunction editedWhereHeld(steps: Step[], id: string, edit: ListEdit): Step[] {\n  const index = steps.findIndex((step) => step.id === id);\n  if (index >= 0) {\n    return edit(steps, index);\n  }\n  let hasChanged = false;\n  const next = steps.map((step) => {\n    const edited = editedInside(step, id, edit);\n    if (edited !== step) {\n      hasChanged = true;\n    }\n    return edited;\n  });\n  if (!hasChanged) {\n    return steps;\n  }\n  return next;\n}\n\nfunction editedInside(step: Step, id: string, edit: ListEdit): Step {\n  if (step.kind !== 'branch') {\n    return step;\n  }\n  let hasChanged = false;\n  const outputs = step.outputs.map((output) => {\n    const steps = editedWhereHeld(output.steps, id, edit);\n    if (steps === output.steps) {\n      return output;\n    }\n    hasChanged = true;\n    return { ...output, steps };\n  });\n  if (!hasChanged) {\n    return step;\n  }\n  return { ...step, outputs };\n}\n\nfunction withSteps(workflow: Workflow, steps: Step[]): Workflow {\n  if (steps === workflow.steps) {\n    return workflow;\n  }\n  return { ...workflow, steps };\n}\n\nexport function changed(\n  workflow: Workflow,\n  id: string,\n  change: (step: Step) => Step\n) {\n  const steps = editedWhereHeld(workflow.steps, id, (list, index) => {\n    const next = change(list[index]);\n    if (next === list[index]) {\n      return list;\n    }\n    const copy = [...list];\n    copy[index] = next;\n    return copy;\n  });\n  return withSteps(workflow, steps);\n}\n\nexport function removed(workflow: Workflow, id: string) {\n  const steps = editedWhereHeld(workflow.steps, id, (list, index) => {\n    const before = list.slice(0, index);\n    const after = list.slice(index + 1);\n    return [...before, ...after];\n  });\n  return withSteps(workflow, steps);\n}\n\nfunction insertedAfter(workflow: Workflow, stepId: string, step: Step) {\n  const steps = editedWhereHeld(workflow.steps, stepId, (list, index) => {\n    const before = list.slice(0, index + 1);\n    const after = list.slice(index + 1);\n    return [...before, step, ...after];\n  });\n  return withSteps(workflow, steps);\n}\n\nfunction withFirst(output: BranchOutput, outputId: string, step: Step) {\n  if (output.id !== outputId) {\n    return output;\n  }\n  return { ...output, steps: [step, ...output.steps] };\n}\n\nfunction insertedFirst(\n  workflow: Workflow,\n  branchId: string,\n  outputId: string,\n  step: Step\n) {\n  return changed(workflow, branchId, (branch) => {\n    if (branch.kind !== 'branch') {\n      return branch;\n    }\n    const hasOutput = branch.outputs.some((output) => output.id === outputId);\n    if (!hasOutput) {\n      return branch;\n    }\n    const outputs = branch.outputs.map((output) =>\n      withFirst(output, outputId, step)\n    );\n    return { ...branch, outputs };\n  });\n}\n\nexport function inserted(workflow: Workflow, at: InsertAt, step: Step) {\n  if (at.at === 'after') {\n    return insertedAfter(workflow, at.stepId, step);\n  }\n  if (at.at === 'first') {\n    return insertedFirst(workflow, at.branchId, at.outputId, step);\n  }\n  return withSteps(workflow, [...workflow.steps, step]);\n}\n\n/** Copies never share an id with what they come from: the copy takes the base, what it holds the base and a rank. */\ntype IdMint = { base: string; count: number };\n\nfunction mintedId(mint: IdMint) {\n  const rank = mint.count;\n  mint.count += 1;\n  if (rank === 0) {\n    return mint.base;\n  }\n  return `${mint.base}-${rank}`;\n}\n\nfunction copiedOutput(output: BranchOutput, mint: IdMint): BranchOutput {\n  const id = mintedId(mint);\n  const steps = output.steps.map((step) => copiedStep(step, mint));\n  return { ...output, id, steps };\n}\n\nfunction copiedStep(step: Step, mint: IdMint): Step {\n  const id = mintedId(mint);\n  if (step.kind === 'branch') {\n    const outputs = step.outputs.map((output) => copiedOutput(output, mint));\n    return { ...step, id, outputs };\n  }\n  if (step.kind === 'agent') {\n    return { ...step, id, seed: id };\n  }\n  return { ...step, id };\n}\n\nexport function copyOf(step: Step, idBase: string): Step {\n  const mint: IdMint = { base: idBase, count: 0 };\n  const copy = copiedStep(step, mint);\n  return { ...copy, name: `${step.name} copy` };\n}\n\nexport function changedBranch(\n  workflow: Workflow,\n  id: string,\n  change: (branch: BranchStep) => BranchStep\n) {\n  return changed(workflow, id, (step) => {\n    if (step.kind !== 'branch') {\n      return step;\n    }\n    return change(step);\n  });\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/edits.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/model.ts",
      "content": "import type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\n\nexport type ToolId =\n  | 'gmail'\n  | 'stripe'\n  | 'linear'\n  | 'notion'\n  | 'github'\n  | 'googledrive'\n  | 'shopify'\n  | 'airtable'\n  | 'zendesk'\n  | 'calder';\n\nexport type ModelId =\n  'claude-haiku' | 'claude-sonnet' | 'gpt-mini' | 'gemini-flash';\n\nexport type PersonId = 'maren' | 'idris' | 'lotte';\n\nexport type StepKind =\n  | 'trigger'\n  | 'agent'\n  | 'branch'\n  | 'approval'\n  | 'tool'\n  | 'output'\n  | 'wait'\n  | 'loop';\n\nexport const KIND_WORD: Record<StepKind, string> = {\n  trigger: 'Trigger',\n  agent: 'Agent',\n  branch: 'Branch',\n  approval: 'Approval',\n  tool: 'Tool',\n  output: 'Output',\n  wait: 'Wait',\n  loop: 'Loop',\n};\n\n/** A value may name what an earlier step gave, between braces: {{order.id}}. */\nexport type ToolSetup = {\n  toolId: ToolId;\n  actionId: string;\n  values: Record<string, string>;\n};\n\nexport type Creativity = 'precise' | 'balanced' | 'creative';\n\nexport type AgentSetup = {\n  instructions: string;\n  modelId: ModelId;\n  creativity: Creativity;\n  streams: boolean;\n  remembers: boolean;\n  retries: boolean;\n  outputName: string;\n  /** The parts of a structured answer, read as {{topic.order}}. Empty when the agent writes plain text. */\n  outputParts: string[];\n};\n\nexport type TimeoutHours = '1' | '4' | '24';\n\nexport type TimeoutRule = 'deny' | 'wait' | 'escalate';\n\nexport type ApprovalSetup = {\n  approverId: PersonId;\n  timeoutHours: TimeoutHours;\n  onTimeout: TimeoutRule;\n};\n\nexport type WaitDuration = '5m' | '1h' | '1d';\n\nexport type LoopRounds = '2' | '3' | '5';\n\ntype StepBase = {\n  id: string;\n  name: string;\n};\n\nexport type TriggerStep = StepBase & {\n  kind: 'trigger';\n  tool: ToolSetup;\n};\n\nexport type AgentStep = StepBase & {\n  kind: 'agent';\n  /** What its picture is drawn from. It stays the same when the step is renamed. */\n  seed: string;\n  series: SeriesSlot;\n  agent: AgentSetup;\n};\n\nexport type BranchOutput = {\n  id: string;\n  label: string;\n  steps: Step[];\n};\n\nexport type BranchStep = StepBase & {\n  kind: 'branch';\n  outputs: BranchOutput[];\n};\n\nexport type ApprovalStep = StepBase & {\n  kind: 'approval';\n  approval: ApprovalSetup;\n};\n\nexport type ToolStep = StepBase & {\n  kind: 'tool';\n  tool: ToolSetup;\n};\n\nexport type OutputStep = StepBase & {\n  kind: 'output';\n  tool: ToolSetup;\n};\n\nexport type WaitStep = StepBase & {\n  kind: 'wait';\n  duration: WaitDuration;\n};\n\nexport type LoopStep = StepBase & {\n  kind: 'loop';\n  rounds: LoopRounds;\n};\n\nexport type Step =\n  | TriggerStep\n  | AgentStep\n  | BranchStep\n  | ApprovalStep\n  | ToolStep\n  | OutputStep\n  | WaitStep\n  | LoopStep;\n\nexport type ProductStep = TriggerStep | ToolStep | OutputStep;\n\n/** A flow runs downwards. The outputs of a branch run side by side, then join at the step after it. */\nexport type Workflow = {\n  id: string;\n  name: string;\n  steps: Step[];\n};\n\n/** Where a new step goes: after a step of the same list, first in an output of a branch, or at the end of the flow. */\nexport type InsertAt =\n  | { at: 'after'; stepId: string }\n  | { at: 'first'; branchId: string; outputId: string }\n  | { at: 'end' };\n\nexport const BRANCH_MIN_OUTPUTS = 2;\n\nexport function isProductStep(step: Step): step is ProductStep {\n  const isTrigger = step.kind === 'trigger';\n  const isTool = step.kind === 'tool';\n  const isOutput = step.kind === 'output';\n  return isTrigger || isTool || isOutput;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/model.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/catalog.ts",
      "content": "import type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\n\nimport { MODELS, type Model } from './data';\nimport type { ModelId, Step, ToolId } from './model';\nimport { toolOf, TOOLS, valuesOf, type Tool } from './tools';\n\nexport type PaletteGroup = 'models' | 'logic' | 'tools';\n\nexport type LogicKind = 'branch' | 'approval' | 'wait' | 'loop';\n\nexport type PaletteEntry =\n  | { id: string; group: 'models'; label: string; modelId: ModelId }\n  | {\n      id: string;\n      group: 'logic';\n      label: string;\n      hint: string;\n      logic: LogicKind;\n    }\n  | { id: string; group: 'tools'; label: string; toolId: ToolId };\n\nexport const GROUP_WORD: Record<PaletteGroup, string> = {\n  models: 'Models',\n  logic: 'Logic',\n  tools: 'Tools',\n};\n\nexport const GROUPS: PaletteGroup[] = ['models', 'logic', 'tools'];\n\nfunction entryOfModel(model: Model): PaletteEntry {\n  return {\n    id: `model-${model.id}`,\n    group: 'models',\n    label: model.name,\n    modelId: model.id,\n  };\n}\n\nfunction entryOfTool(tool: Tool): PaletteEntry {\n  return {\n    id: `tool-${tool.id}`,\n    group: 'tools',\n    label: tool.name,\n    toolId: tool.id,\n  };\n}\n\nconst LOGIC_ENTRIES: PaletteEntry[] = [\n  {\n    id: 'logic-branch',\n    group: 'logic',\n    label: 'Branch',\n    hint: 'Route by a condition',\n    logic: 'branch',\n  },\n  {\n    id: 'logic-approval',\n    group: 'logic',\n    label: 'Approval',\n    hint: 'Ask a person first',\n    logic: 'approval',\n  },\n  {\n    id: 'logic-wait',\n    group: 'logic',\n    label: 'Wait',\n    hint: 'Pause before the next step',\n    logic: 'wait',\n  },\n  {\n    id: 'logic-loop',\n    group: 'logic',\n    label: 'Loop',\n    hint: 'Repeat the steps after it',\n    logic: 'loop',\n  },\n];\n\nexport const PALETTE: PaletteEntry[] = [\n  ...MODELS.map(entryOfModel),\n  ...LOGIC_ENTRIES,\n  ...TOOLS.map(entryOfTool),\n];\n\nexport function pressKeyOf(entryId: string) {\n  return `palette-${entryId}`;\n}\n\nexport function entryOf(id: string) {\n  return PALETTE.find((entry) => entry.id === id);\n}\n\n/** Agents take the series colours in their fixed order, so the third agent of a flow is always the third colour. */\nconst SERIES_ORDER: SeriesSlot[] = [1, 2, 3, 4, 5];\n\nexport function seriesAfter(agentCount: number) {\n  const index = agentCount % SERIES_ORDER.length;\n  return SERIES_ORDER[index];\n}\n\nfunction logicStepOf(logic: LogicKind, id: string): Step {\n  if (logic === 'branch') {\n    return {\n      id,\n      kind: 'branch',\n      name: 'New branch',\n      outputs: [\n        { id: `${id}-yes`, label: 'If yes', steps: [] },\n        { id: `${id}-else`, label: 'Otherwise', steps: [] },\n      ],\n    };\n  }\n  if (logic === 'approval') {\n    return {\n      id,\n      kind: 'approval',\n      name: 'Ask a person',\n      approval: { approverId: 'maren', timeoutHours: '4', onTimeout: 'deny' },\n    };\n  }\n  if (logic === 'wait') {\n    return { id, kind: 'wait', name: 'Wait', duration: '1h' };\n  }\n  return { id, kind: 'loop', name: 'Repeat', rounds: '3' };\n}\n\nfunction toolStepOf(toolId: ToolId, id: string): Step {\n  const tool = toolOf(toolId);\n  const firstAction = tool.actions.find((action) => !action.isEvent);\n  const action = firstAction ?? tool.actions[0];\n  return {\n    id,\n    kind: 'tool',\n    name: action.label,\n    tool: { toolId: tool.id, actionId: action.id, values: valuesOf(action) },\n  };\n}\n\n/** A step as it lands on the canvas: ready to run, with the first action of its product and plain settings. */\nexport function stepOfEntry(\n  entry: PaletteEntry,\n  id: string,\n  series: SeriesSlot\n): Step {\n  if (entry.group === 'logic') {\n    return logicStepOf(entry.logic, id);\n  }\n  if (entry.group === 'tools') {\n    return toolStepOf(entry.toolId, id);\n  }\n  return {\n    id,\n    kind: 'agent',\n    name: 'New agent',\n    seed: id,\n    series,\n    agent: {\n      instructions: '',\n      modelId: entry.modelId,\n      creativity: 'balanced',\n      streams: false,\n      remembers: false,\n      retries: true,\n      outputName: 'answer',\n      outputParts: [],\n    },\n  };\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/catalog.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/tools.ts",
      "content": "import type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\n\nimport type { ToolId } from './model';\n\nexport type ToolField = {\n  id: string;\n  label: string;\n  value: string;\n};\n\nexport type ToolAction = {\n  id: string;\n  label: string;\n  /** An event starts a flow. An action runs inside it. */\n  isEvent: boolean;\n  /** What the step calls its result, and what the result holds: {{order.total}}. */\n  namespace: string;\n  outputs: string[];\n  fields: ToolField[];\n};\n\n/** A known product wears its real mark. Kestrel Post is invented, so it wears a drawn one. */\nexport type ToolMark =\n  { kind: 'brand'; brand: BrandSlug } | { kind: 'company'; seed: string };\n\nexport type Tool = {\n  id: ToolId;\n  name: string;\n  mark: ToolMark;\n  actions: ToolAction[];\n};\n\nexport const SUPPORT_MAILBOX = 'support@alderbank.example';\n\nexport const TOOLS: Tool[] = [\n  {\n    id: 'gmail',\n    name: 'Gmail',\n    mark: { kind: 'brand', brand: 'gmail' },\n    actions: [\n      {\n        id: 'new-email',\n        label: 'New email',\n        isEvent: true,\n        namespace: 'email',\n        outputs: ['from', 'subject', 'body'],\n        fields: [{ id: 'mailbox', label: 'Mailbox', value: SUPPORT_MAILBOX }],\n      },\n      {\n        id: 'send-reply',\n        label: 'Send a reply',\n        isEvent: false,\n        namespace: 'sent',\n        outputs: ['time'],\n        fields: [\n          { id: 'from', label: 'From', value: SUPPORT_MAILBOX },\n          { id: 'body', label: 'Body', value: '{{reply}}' },\n        ],\n      },\n      {\n        id: 'add-label',\n        label: 'Add a label',\n        isEvent: false,\n        namespace: 'label',\n        outputs: ['name'],\n        fields: [{ id: 'label', label: 'Label', value: 'Answered' }],\n      },\n    ],\n  },\n  {\n    id: 'stripe',\n    name: 'Stripe',\n    mark: { kind: 'brand', brand: 'stripe' },\n    actions: [\n      {\n        id: 'find-payment',\n        label: 'Find a payment',\n        isEvent: false,\n        namespace: 'order',\n        outputs: ['id', 'total', 'item'],\n        fields: [\n          { id: 'order', label: 'Order number', value: '{{topic.order}}' },\n        ],\n      },\n      {\n        id: 'refund',\n        label: 'Issue a refund',\n        isEvent: false,\n        namespace: 'refund',\n        outputs: ['amount', 'status'],\n        fields: [\n          { id: 'payment', label: 'Payment', value: '{{order.id}}' },\n          { id: 'amount', label: 'Amount', value: '{{order.total}}' },\n        ],\n      },\n    ],\n  },\n  {\n    id: 'linear',\n    name: 'Linear',\n    mark: { kind: 'brand', brand: 'linear' },\n    actions: [\n      {\n        id: 'open-issue',\n        label: 'Open an issue',\n        isEvent: false,\n        namespace: 'issue',\n        outputs: ['url'],\n        fields: [\n          { id: 'team', label: 'Team', value: 'Support' },\n          { id: 'title', label: 'Title', value: '{{email.subject}}' },\n        ],\n      },\n    ],\n  },\n  {\n    id: 'notion',\n    name: 'Notion',\n    mark: { kind: 'brand', brand: 'notion' },\n    actions: [\n      {\n        id: 'add-page',\n        label: 'Add a page',\n        isEvent: false,\n        namespace: 'page',\n        outputs: ['url'],\n        fields: [\n          { id: 'database', label: 'Database', value: 'Customer notes' },\n          { id: 'title', label: 'Title', value: '{{email.subject}}' },\n        ],\n      },\n    ],\n  },\n  {\n    id: 'github',\n    name: 'GitHub',\n    mark: { kind: 'brand', brand: 'github' },\n    actions: [\n      {\n        id: 'open-issue',\n        label: 'Open an issue',\n        isEvent: false,\n        namespace: 'ticket',\n        outputs: ['url'],\n        fields: [\n          { id: 'repository', label: 'Repository', value: 'alderbank/shop' },\n          { id: 'title', label: 'Title', value: '{{email.subject}}' },\n        ],\n      },\n    ],\n  },\n  {\n    id: 'googledrive',\n    name: 'Google Drive',\n    mark: { kind: 'brand', brand: 'googledrive' },\n    actions: [\n      {\n        id: 'save-file',\n        label: 'Save a file',\n        isEvent: false,\n        namespace: 'file',\n        outputs: ['url'],\n        fields: [\n          { id: 'folder', label: 'Folder', value: 'Support, replies' },\n          { id: 'name', label: 'File name', value: '{{topic.order}}' },\n        ],\n      },\n    ],\n  },\n  {\n    id: 'shopify',\n    name: 'Shopify',\n    mark: { kind: 'brand', brand: 'shopify' },\n    actions: [\n      {\n        id: 'find-order',\n        label: 'Find an order',\n        isEvent: false,\n        namespace: 'purchase',\n        outputs: ['items', 'address'],\n        fields: [\n          { id: 'order', label: 'Order number', value: '{{topic.order}}' },\n        ],\n      },\n    ],\n  },\n  {\n    id: 'airtable',\n    name: 'Airtable',\n    mark: { kind: 'brand', brand: 'airtable' },\n    actions: [\n      {\n        id: 'add-record',\n        label: 'Add a record',\n        isEvent: false,\n        namespace: 'record',\n        outputs: ['id'],\n        fields: [{ id: 'table', label: 'Table', value: 'Order questions' }],\n      },\n    ],\n  },\n  {\n    id: 'zendesk',\n    name: 'Zendesk',\n    mark: { kind: 'brand', brand: 'zendesk' },\n    actions: [\n      {\n        id: 'add-note',\n        label: 'Add a note',\n        isEvent: false,\n        namespace: 'note',\n        outputs: ['id'],\n        fields: [{ id: 'note', label: 'Note', value: '{{topic.label}}' }],\n      },\n    ],\n  },\n  {\n    id: 'calder',\n    name: 'Kestrel Post',\n    mark: { kind: 'company', seed: 'Kestrel Post' },\n    actions: [\n      {\n        id: 'track-parcel',\n        label: 'Track a parcel',\n        isEvent: false,\n        namespace: 'parcel',\n        outputs: ['status', 'due'],\n        fields: [\n          { id: 'order', label: 'Order number', value: '{{topic.order}}' },\n        ],\n      },\n    ],\n  },\n];\n\nexport function toolOf(id: ToolId) {\n  const tool = TOOLS.find((candidate) => candidate.id === id);\n  return tool ?? TOOLS[0];\n}\n\nexport function actionOf(tool: Tool, actionId: string) {\n  const action = tool.actions.find((candidate) => candidate.id === actionId);\n  return action ?? tool.actions[0];\n}\n\nexport function valuesOf(action: ToolAction) {\n  const values: Record<string, string> = {};\n  for (const field of action.fields) {\n    values[field.id] = field.value;\n  }\n  return values;\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/tools.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/samples.ts",
      "content": "import type { Step, StepKind } from './model';\n\nexport type SampleId = 'delivery' | 'refund';\n\n/** What an approval asks a person for when this sample reaches it. */\nexport type SampleRequest = {\n  amount: string;\n  order: string;\n  item: string;\n  /** How the live region names it: \"refund of 34.90 EUR\". */\n  spoken: string;\n};\n\nexport type SampleFailure = {\n  stepId: string;\n  error: string;\n};\n\nexport type Sample = {\n  id: SampleId;\n  from: string;\n  address: string;\n  subject: string;\n  body: string;\n  /** What the email is about. A branch takes the output that carries this label. */\n  topic: string;\n  runLabel: string;\n  reply: string;\n  replyIfDenied: string;\n  request: SampleRequest | null;\n  /** A step that fails on its first try with this sample. Kestrel Post is invented, so the failure names no real product. */\n  failure: SampleFailure | null;\n};\n\nconst REFUND = {\n  amount: '34.90 EUR',\n  order: 'AB-20874',\n  item: 'Hedge shears, 60 cm',\n};\n\nconst DELIVERY_BODY = 'Where is my order AB-20931? It was due on Tuesday.';\n\nconst REFUND_BODY =\n  'The hedge shears came with a bent blade. I would like a refund for order AB-20874.';\n\n/** Two invented customers of an invented shop. */\nconst SAMPLES: Sample[] = [\n  {\n    id: 'delivery',\n    from: 'Tamsin Okoro',\n    address: 'tamsin.okoro@fernhill.example',\n    subject: 'Where is my order?',\n    body: DELIVERY_BODY,\n    topic: 'Delivery',\n    runLabel: 'Run with a delivery question',\n    reply:\n      'Hello Tamsin, your order AB-20931 left our depot on Monday and is on its way with Kestrel Post. It should reach you on Thursday, two days later than planned. We are sorry for the wait. The Alderbank team',\n    replyIfDenied:\n      'Hello Tamsin, thank you for your message about order AB-20931. A member of our team will follow up with you today. The Alderbank team',\n    request: null,\n    failure: { stepId: 'track', error: 'Carrier did not answer' },\n  },\n  {\n    id: 'refund',\n    from: 'Jonas Lindqvist',\n    address: 'jonas.lindqvist@marlowe.example',\n    subject: 'Damaged hedge shears',\n    body: REFUND_BODY,\n    topic: 'Refund',\n    runLabel: 'Run with a refund request',\n    reply:\n      'Hello Jonas, we are sorry the hedge shears arrived with a bent blade. We refunded 34.90 EUR to your card, and you can keep the pair. The money shows within a few days. The Alderbank team',\n    replyIfDenied:\n      'Hello Jonas, thank you for telling us about the hedge shears. A member of our team will follow up on your refund today. The Alderbank team',\n    request: {\n      amount: REFUND.amount,\n      order: `Order ${REFUND.order}`,\n      item: REFUND.item,\n      spoken: `refund of ${REFUND.amount}`,\n    },\n    failure: null,\n  },\n];\n\nexport function samplePressKeyOf(id: SampleId) {\n  return `sample-${id}`;\n}\n\nexport function sampleOf(id: SampleId) {\n  const sample = SAMPLES.find((candidate) => candidate.id === id);\n  return sample ?? SAMPLES[0];\n}\n\nexport function otherSampleOf(id: SampleId) {\n  const other = SAMPLES.find((candidate) => candidate.id !== id);\n  return other ?? SAMPLES[0];\n}\n\n/** What a step took and gave in a run. `text` is what an agent wrote, for the ones that write prose. */\nexport type StepResult = {\n  ms: number;\n  usd: number;\n  input: Record<string, unknown>;\n  output: Record<string, unknown>;\n  text?: string;\n};\n\nexport const FAILED_TRY_MS = 700;\n\nconst DELIVERY_RESULTS: Record<string, StepResult> = {\n  trigger: {\n    ms: 300,\n    usd: 0,\n    input: { mailbox: 'support@alderbank.example' },\n    output: {\n      from: 'tamsin.okoro@fernhill.example',\n      subject: 'Where is my order?',\n      body: DELIVERY_BODY,\n    },\n  },\n  classify: {\n    ms: 1000,\n    usd: 0.002,\n    input: { subject: 'Where is my order?', body: DELIVERY_BODY },\n    output: { label: 'Delivery', order: 'AB-20931' },\n  },\n  route: {\n    ms: 200,\n    usd: 0,\n    input: { topic: 'Delivery' },\n    output: { taken: 'Delivery' },\n  },\n  track: {\n    ms: 800,\n    usd: 0,\n    input: { order: 'AB-20931' },\n    output: { status: 'In transit', due: 'Thursday' },\n  },\n  draft: {\n    ms: 1100,\n    usd: 0.003,\n    input: { status: 'In transit', due: 'Thursday' },\n    output: {},\n    text: 'Your parcel left our depot on Monday and is on its way with Kestrel Post. It should reach you on Thursday.',\n  },\n  write: {\n    ms: 0,\n    usd: 0.005,\n    input: { topic: 'Delivery', order: 'AB-20931', status: 'In transit' },\n    output: {},\n  },\n  send: {\n    ms: 400,\n    usd: 0,\n    input: { to: 'tamsin.okoro@fernhill.example' },\n    output: { sent: true },\n  },\n};\n\nconst REFUND_RESULTS: Record<string, StepResult> = {\n  trigger: {\n    ms: 300,\n    usd: 0,\n    input: { mailbox: 'support@alderbank.example' },\n    output: {\n      from: 'jonas.lindqvist@marlowe.example',\n      subject: 'Damaged hedge shears',\n      body: REFUND_BODY,\n    },\n  },\n  classify: {\n    ms: 1000,\n    usd: 0.002,\n    input: { subject: 'Damaged hedge shears', body: REFUND_BODY },\n    output: { label: 'Refund', order: REFUND.order },\n  },\n  route: {\n    ms: 200,\n    usd: 0,\n    input: { topic: 'Refund' },\n    output: { taken: 'Refund' },\n  },\n  find: {\n    ms: 700,\n    usd: 0,\n    input: { order: REFUND.order },\n    output: { id: REFUND.order, total: REFUND.amount, item: REFUND.item },\n  },\n  ask: {\n    ms: 0,\n    usd: 0,\n    input: { amount: REFUND.amount, order: REFUND.order },\n    output: {},\n  },\n  issue: {\n    ms: 900,\n    usd: 0,\n    input: { payment: REFUND.order, amount: REFUND.amount },\n    output: { amount: REFUND.amount, status: 'Refunded' },\n  },\n  write: {\n    ms: 0,\n    usd: 0.005,\n    input: { topic: 'Refund', order: REFUND.order },\n    output: {},\n  },\n  send: {\n    ms: 400,\n    usd: 0,\n    input: { to: 'jonas.lindqvist@marlowe.example' },\n    output: { sent: true },\n  },\n};\n\nconst RESULTS: Record<SampleId, Partial<Record<string, StepResult>>> = {\n  delivery: DELIVERY_RESULTS,\n  refund: REFUND_RESULTS,\n};\n\nconst PASSED_ON = { from: 'The step before' };\n\n/** What a step added on the canvas takes and gives: a test run has no recorded result for it. */\nconst KIND_RESULT: Record<StepKind, StepResult> = {\n  trigger: { ms: 300, usd: 0, input: {}, output: { received: true } },\n  agent: {\n    ms: 1200,\n    usd: 0.002,\n    input: PASSED_ON,\n    output: {},\n    text: 'A sample answer. A real run writes its own here.',\n  },\n  branch: { ms: 200, usd: 0, input: PASSED_ON, output: {} },\n  approval: { ms: 0, usd: 0, input: PASSED_ON, output: {} },\n  tool: { ms: 700, usd: 0, input: PASSED_ON, output: { ok: true } },\n  output: { ms: 400, usd: 0, input: PASSED_ON, output: { sent: true } },\n  wait: { ms: 300, usd: 0, input: {}, output: { waited: false } },\n  loop: { ms: 300, usd: 0, input: PASSED_ON, output: { rounds: 1 } },\n};\n\nexport function resultOf(sample: Sample, step: Step) {\n  const recorded = RESULTS[sample.id][step.id];\n  return recorded ?? KIND_RESULT[step.kind];\n}\n",
      "type": "registry:component",
      "target": "components/templates/application-14/samples.ts"
    },
    {
      "path": "registry/ndeko/templates/workflow-builder/application-14/data.ts",
      "content": "import type { BrandSlug } from '@/registry/ndeko/lib/brand-logos';\n\nimport type {\n  Creativity,\n  LoopRounds,\n  ModelId,\n  PersonId,\n  TimeoutHours,\n  TimeoutRule,\n  WaitDuration,\n  Workflow,\n} from './model';\nimport { SUPPORT_MAILBOX } from './tools';\n\nexport const BRAND = { name: 'Alderbank' };\n\nexport type Person = {\n  id: PersonId;\n  name: string;\n  role: string;\n};\n\n/** Invented people of an invented shop: the ones a step can ask before it goes on. */\nexport const PEOPLE: Person[] = [\n  { id: 'maren', name: 'Maren Solberg', role: 'Support lead' },\n  { id: 'idris', name: 'Idris Achebe', role: 'Finance' },\n  { id: 'lotte', name: 'Lotte Verhoeven', role: 'Store manager' },\n];\n\nexport function personOf(id: PersonId) {\n  const person = PEOPLE.find((candidate) => candidate.id === id);\n  return person ?? PEOPLE[0];\n}\n\nexport type Model = {\n  id: ModelId;\n  name: string;\n  brand: BrandSlug;\n};\n\nexport const MODELS: Model[] = [\n  { id: 'claude-haiku', name: 'Claude Haiku', brand: 'claude' },\n  { id: 'claude-sonnet', name: 'Claude Sonnet', brand: 'claude' },\n  { id: 'gpt-mini', name: 'GPT mini', brand: 'openai' },\n  { id: 'gemini-flash', name: 'Gemini Flash', brand: 'gemini' },\n];\n\nexport function modelOf(id: ModelId) {\n  const model = MODELS.find((candidate) => candidate.id === id);\n  return model ?? MODELS[0];\n}\n\nexport type Choice<Value extends string> = {\n  value: Value;\n  label: string;\n};\n\nexport const CREATIVITIES: Choice<Creativity>[] = [\n  { value: 'precise', label: 'Precise' },\n  { value: 'balanced', label: 'Balanced' },\n  { value: 'creative', label: 'Creative' },\n];\n\nexport const TIMEOUTS: Choice<TimeoutHours>[] = [\n  { value: '1', label: 'After 1 hour' },\n  { value: '4', label: 'After 4 hours' },\n  { value: '24', label: 'After 1 day' },\n];\n\nexport const TIMEOUT_RULES: Choice<TimeoutRule>[] = [\n  { value: 'deny', label: 'Deny and tell the customer' },\n  { value: 'wait', label: 'Keep waiting' },\n  { value: 'escalate', label: 'Ask the next person' },\n];\n\nexport const WAITS: Choice<WaitDuration>[] = [\n  { value: '5m', label: '5 minutes' },\n  { value: '1h', label: '1 hour' },\n  { value: '1d', label: '1 day' },\n];\n\nexport const ROUNDS: Choice<LoopRounds>[] = [\n  { value: '2', label: '2 times' },\n  { value: '3', label: '3 times' },\n  { value: '5', label: '5 times' },\n];\n\nexport const WORKFLOW: Workflow = {\n  id: 'order-triage',\n  name: 'Order question triage',\n  steps: [\n    {\n      id: 'trigger',\n      kind: 'trigger',\n      name: 'New email',\n      tool: {\n        toolId: 'gmail',\n        actionId: 'new-email',\n        values: { mailbox: SUPPORT_MAILBOX },\n      },\n    },\n    {\n      id: 'classify',\n      kind: 'agent',\n      name: 'Read and classify',\n      seed: 'Read and classify',\n      series: 1,\n      agent: {\n        instructions:\n          'Read the email. Say whether it is about a refund, a delivery or something else, and pull out the order number.',\n        modelId: 'claude-haiku',\n        creativity: 'precise',\n        streams: false,\n        remembers: false,\n        retries: true,\n        outputName: 'topic',\n        outputParts: ['label', 'order'],\n      },\n    },\n    {\n      id: 'route',\n      kind: 'branch',\n      name: 'Route by topic',\n      outputs: [\n        {\n          id: 'refund',\n          label: 'Refund',\n          steps: [\n            {\n              id: 'find',\n              kind: 'tool',\n              name: 'Find the order',\n              tool: {\n                toolId: 'stripe',\n                actionId: 'find-payment',\n                values: { order: '{{topic.order}}' },\n              },\n            },\n            {\n              id: 'ask',\n              kind: 'approval',\n              name: 'Ask before refunding',\n              approval: {\n                approverId: 'maren',\n                timeoutHours: '4',\n                onTimeout: 'deny',\n              },\n            },\n            {\n              id: 'issue',\n              kind: 'tool',\n              name: 'Issue the refund',\n              tool: {\n                toolId: 'stripe',\n                actionId: 'refund',\n                values: { payment: '{{order.id}}', amount: '{{order.total}}' },\n              },\n            },\n          ],\n        },\n        {\n          id: 'delivery',\n          label: 'Delivery',\n          steps: [\n            {\n              id: 'track',\n              kind: 'tool',\n              name: 'Track the parcel',\n              tool: {\n                toolId: 'calder',\n                actionId: 'track-parcel',\n                values: { order: '{{topic.order}}' },\n              },\n            },\n          ],\n        },\n        {\n          id: 'other',\n          label: 'Other',\n          steps: [\n            {\n              id: 'open',\n              kind: 'tool',\n              name: 'Open an issue',\n              tool: {\n                toolId: 'linear',\n                actionId: 'open-issue',\n                values: { team: 'Support', title: '{{email.subject}}' },\n              },\n            },\n          ],\n        },\n      ],\n    },\n    {\n      id: 'write',\n      kind: 'agent',\n      name: 'Write the reply',\n      seed: 'Write the reply',\n      series: 2,\n      agent: {\n        instructions:\n          'Write a short, warm reply that answers the question with what the branch found. Sign as the Alderbank team.',\n        modelId: 'claude-sonnet',\n        creativity: 'balanced',\n        streams: true,\n        remembers: true,\n        retries: true,\n        outputName: 'reply',\n        outputParts: [],\n      },\n    },\n    {\n      id: 'send',\n      kind: 'output',\n      name: 'Send the reply',\n      tool: {\n        toolId: 'gmail',\n        actionId: 'send-reply',\n        values: { from: SUPPORT_MAILBOX, body: '{{reply}}' },\n      },\n    },\n  ],\n};\n\n/** What the demonstration adds to the Delivery branch, under the step it selects first. */\nexport const DEMO_STEP = {\n  id: 'draft',\n  name: 'Draft the update',\n  afterId: 'track',\n  entryId: 'model-claude-haiku',\n  instructions:\n    'Say where the parcel is and when it should arrive. Two sentences, no jargon.',\n};\n",
      "type": "registry:component",
      "target": "components/templates/application-14/data.ts"
    }
  ],
  "categories": [
    "templates",
    "workflow-builder"
  ],
  "type": "registry:block"
}