{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "workflows-02",
  "title": "Node graph editor",
  "description": "A pipeline of typed nodes with their settings inside: a wire between two ports of different types is refused with a shake of its end and the reason, Run lights the nodes in order as their ring closes, one fails with Retry, and the next run serves what did not change from cache.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/agent-run.json",
    "https://ui.ndekocode.dev/r/badge.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.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/input.json",
    "https://ui.ndekocode.dev/r/live-duration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/morph-button.json",
    "https://ui.ndekocode.dev/r/motion-number.json",
    "https://ui.ndekocode.dev/r/motion-presets.json",
    "https://ui.ndekocode.dev/r/replay-button.json",
    "https://ui.ndekocode.dev/r/select.json",
    "https://ui.ndekocode.dev/r/slider.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/use-session.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/index.tsx",
      "content": "'use client';\n\nimport { useEffect, useId, useMemo, useRef, useState } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport { useSession } from '@/registry/ndeko/hooks/use-session';\nimport {\n  pressedSolidOf,\n  spokenUnless,\n} from '@/registry/ndeko/lib/demonstration';\nimport { PlayIcon } from '@/registry/ndeko/lib/icons';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { ClockGate } from '@/registry/ndeko/ui/live-duration';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { MorphButton, type MorphState } from '@/registry/ndeko/ui/morph-button';\nimport { ReplayButton } from '@/registry/ndeko/ui/replay-button';\n\nimport { Canvas } from './canvas';\nimport {\n  nodeOf,\n  NODES,\n  PIPELINE_NAME,\n  PORT_TYPES,\n  TYPE_WORD,\n  type NodeId,\n  type PortType,\n} from './data';\nimport { layoutOf, type Orientation } from './layout';\nimport {\n  INITIAL,\n  isRunning,\n  LOOP_AFTER_MS,\n  phaseOf,\n  reducer,\n  RESTING,\n  SCRIPT,\n  type GraphState,\n  type RunStatus,\n} from './session';\nimport { useIsPhone } from './use-is-phone';\nimport { typeColorOf } from './wires';\n\nconst SESSION = {\n  reducer,\n  initial: INITIAL,\n  resting: RESTING,\n  script: SCRIPT,\n  loopAfter: LOOP_AFTER_MS,\n  holdWhile: isRunning,\n};\n\nconst RUN_LABELS: Record<MorphState, string> = {\n  idle: 'Run pipeline',\n  busy: 'Running',\n  done: 'Run pipeline',\n};\n\n/** How long a refused wire and its reason stay before they leave on their own. */\nconst REFUSAL_MS = 2400;\n\nconst CANVAS_HINT =\n  'Drag from the port on the way out of a node to another node to connect them. The port on the way in of a node opens the list of nodes that can feed it. A wire only joins two ports of the same type.';\n\nfunction orientationOf(isPhone: boolean | null): Orientation {\n  if (isPhone) {\n    return 'down';\n  }\n  return 'across';\n}\n\nfunction morphOf(isBusy: boolean): MorphState {\n  if (isBusy) {\n    return 'busy';\n  }\n  return 'idle';\n}\n\nfunction titleOf(id: NodeId | null) {\n  if (id === null) {\n    return null;\n  }\n  return nodeOf(id).title;\n}\n\nfunction countOf(state: GraphState, status: RunStatus) {\n  const matching = NODES.filter(\n    (node) => state.runs[node.id].status === status\n  );\n  return matching.length;\n}\n\nfunction ranWordOf(count: number) {\n  if (count === 1) {\n    return '1 node ran';\n  }\n  return `${count} nodes ran`;\n}\n\n/** The last run in one line: what ran, what came from cache, what was left out. */\nfunction runLineOf(state: GraphState, runningTitle: string | null) {\n  if (runningTitle !== null) {\n    return `Running ${runningTitle}`;\n  }\n  const failed = NODES.find((node) => state.runs[node.id].status === 'failed');\n  const skipped = countOf(state, 'skipped');\n  if (failed) {\n    return `${failed.title} failed, ${skipped} skipped`;\n  }\n  const done = countOf(state, 'done');\n  const cached = countOf(state, 'cached');\n  const hasRun = done + cached + skipped > 0;\n  if (!hasRun) {\n    return 'Not run yet';\n  }\n  const parts = [ranWordOf(done)];\n  if (cached > 0) {\n    parts.push(`${cached} from cache`);\n  }\n  if (skipped > 0) {\n    parts.push(`${skipped} skipped`);\n  }\n  return parts.join(', ');\n}\n\nfunction LegendEntry({ type }: { type: PortType }) {\n  return (\n    <li className='flex items-center gap-1.5'>\n      <span\n        aria-hidden='true'\n        style={{ backgroundColor: typeColorOf(type) }}\n        className='h-0.5 w-4 rounded-full'\n      />\n      {TYPE_WORD[type]}\n    </li>\n  );\n}\n\nfunction Legend() {\n  return (\n    <ul\n      aria-label='What each wire carries'\n      className='text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-xs'\n    >\n      {PORT_TYPES.map((type) => (\n        <LegendEntry key={type} type={type} />\n      ))}\n    </ul>\n  );\n}\n\nexport default function Workflows02() {\n  const {\n    ref,\n    isInView,\n    isAutoplaying,\n    state,\n    act,\n    pressed,\n    isFinished,\n    restart,\n  } = useSession(SESSION);\n  const cellRef = useRef<HTMLDivElement>(null);\n  const isPhone = useIsPhone(cellRef);\n  const isVisible = useDocumentVisible();\n  const isOnScreen = isInView && isVisible;\n  const hintId = useId();\n  const [round, setRound] = useState(0);\n  const orientation = orientationOf(isPhone);\n  const layout = useMemo(\n    () => layoutOf(state.wires, orientation),\n    [state.wires, orientation]\n  );\n  const phase = phaseOf(state);\n  const phaseId = phase?.id ?? null;\n  const phaseMs = phase?.ms ?? null;\n  const phaseToken = phase?.token ?? null;\n  const refusedId = state.refused?.id ?? null;\n  const isBusy = phase !== null;\n  const runningTitle = titleOf(phaseId);\n  const runLine = runLineOf(state, runningTitle);\n  const canReplay = isFinished && !isAutoplaying;\n  const message = spokenUnless(isAutoplaying, state.notice);\n\n  /**\n   * A run holds its place off screen and in a hidden tab, as the session does: the node it is on\n   * starts over on return.\n   */\n  useEffect(() => {\n    const isIdle = phaseMs === null || phaseToken === null;\n    if (isIdle || !isOnScreen) {\n      return;\n    }\n    const end = () => act({ type: 'phaseEnded', token: phaseToken });\n    const timer = setTimeout(end, phaseMs);\n    return () => clearTimeout(timer);\n  }, [act, isOnScreen, phaseId, phaseMs, phaseToken]);\n\n  useEffect(() => {\n    if (refusedId === null || !isOnScreen) {\n      return;\n    }\n    const clear = () => act({ type: 'refusalCleared', id: refusedId });\n    const timer = setTimeout(clear, REFUSAL_MS);\n    return () => clearTimeout(timer);\n  }, [act, isOnScreen, refusedId]);\n\n  function run() {\n    act({ type: 'ran' });\n  }\n\n  /** A new round starts on a fresh canvas, so the view a person left does not hide the demonstration. */\n  function replay() {\n    restart();\n    setRound((current) => current + 1);\n  }\n\n  return (\n    <ClockGate isActive={isInView}>\n      <div\n        ref={ref}\n        className='bg-background text-foreground @container flex h-dvh min-h-[38rem] w-full flex-col overflow-hidden'\n      >\n        <div className='mx-auto flex min-h-0 w-full max-w-7xl flex-1 flex-col gap-3 p-3 @3xl:gap-4 @3xl:p-4'>\n          <header className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n            <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n              <h1 className='truncate text-lg font-semibold'>\n                {PIPELINE_NAME}\n              </h1>\n              <p className='text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs tabular-nums'>\n                <Swap swapKey={runLine}>{runLine}</Swap>\n                <Badge variant='secondary'>Illustrative</Badge>\n              </p>\n            </div>\n            <div className='flex flex-wrap items-center gap-x-3 gap-y-2'>\n              <ReplayButton\n                isShown={canReplay}\n                onReplay={replay}\n                label='Replay the demo'\n              />\n              <MorphButton\n                type='button'\n                state={morphOf(isBusy)}\n                labels={RUN_LABELS}\n                idleIcon={<PlayIcon />}\n                onClick={run}\n                className={pressedSolidOf(pressed === 'run')}\n              />\n            </div>\n          </header>\n\n          <div\n            ref={cellRef}\n            className='group/canvas bg-foreground/[0.03] relative min-h-0 flex-1 overflow-hidden rounded-xl'\n          >\n            <Canvas\n              key={round}\n              isLaidOut={isPhone !== null}\n              label={`Canvas of ${PIPELINE_NAME}`}\n              subject='the pipeline'\n              hintId={hintId}\n              layout={layout}\n              orientation={orientation}\n              wires={state.wires}\n              params={state.params}\n              runs={state.runs}\n              runningId={phaseId}\n              wiring={state.wiring}\n              refused={state.refused}\n              isDemonstrating={isAutoplaying}\n              pressed={pressed}\n              onAction={act}\n              onRun={run}\n            />\n            <p id={hintId} className='sr-only'>\n              {CANVAS_HINT}\n            </p>\n          </div>\n\n          <Legend />\n        </div>\n        <LiveRegion message={message} />\n      </div>\n    </ClockGate>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/index.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/canvas.tsx",
      "content": "'use client';\n\nimport { useLayoutEffect, useRef, useState } from 'react';\n\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { nodeIdOf, nodeOf, NODES, type NodeId, type Params } from './data';\nimport {\n  nodeAt,\n  wirePathOf,\n  type GraphLayout,\n  type Orientation,\n  type Point,\n} from './layout';\nimport { NodeCard, type Aim } from './node-card';\nimport { refusalOf, signatureOf, sourceOf } from './pipeline';\nimport type { GraphAction, NodeRun, Refused, Wire, Wiring } from './session';\nimport { usePanZoom } from './use-pan-zoom';\nimport {\n  HeldLayer,\n  typeColorOf,\n  WireLayer,\n  type HeldWire,\n  type RefusedWire,\n} from './wires';\nimport { ZoomControl } from './zoom-control';\n\ntype Wired = {\n  kind: 'wire';\n  pointerId: number;\n  from: NodeId;\n  aim: NodeId | null;\n};\n\n/** What the pointers on the canvas are doing: moving the view, or holding a wire out of a port. */\ntype Gesture = { kind: 'pan' } | Wired;\n\n/** A wire lands on a node from this far around it. */\nconst AIM_REACH = 12;\n\nconst FRAME = [\n  'absolute inset-0 cursor-grab overflow-hidden rounded-xl outline-none select-none active:cursor-grabbing',\n  'group-focus-within/canvas:touch-none',\n].join(' ');\n\n/** A held wire only lives while something holds it: a pointer, or the demonstration. */\nfunction heldWiringOf(isHeld: boolean, wiring: Wiring | null) {\n  if (isHeld) {\n    return wiring;\n  }\n  return null;\n}\n\nfunction aimOf(held: Wiring | null, wires: Wire[], id: NodeId): Aim {\n  if (!held) {\n    return 'idle';\n  }\n  if (held.from === id) {\n    return 'source';\n  }\n  const canTake = refusalOf(wires, held.from, id) === null;\n  const isUnder = held.to === id;\n  if (isUnder && canTake) {\n    return 'aimed';\n  }\n  if (isUnder) {\n    return 'refusing';\n  }\n  if (canTake) {\n    return 'open';\n  }\n  return 'closed';\n}\n\n/** The demonstration has no pointer, so its wire is drawn from its port to the node it aims at. */\nfunction demoWireOf(\n  held: Wiring | null,\n  layout: GraphLayout<Wire>,\n  orientation: Orientation\n): HeldWire | null {\n  if (!held || held.to === null) {\n    return null;\n  }\n  const from = layout.places[held.from].output;\n  const to = layout.places[held.to].input;\n  if (!to) {\n    return null;\n  }\n  return {\n    path: wirePathOf(from, to, orientation),\n    type: nodeOf(held.from).output,\n  };\n}\n\nfunction refusedWireOf(\n  refused: Refused | null,\n  layout: GraphLayout<Wire>,\n  orientation: Orientation\n): RefusedWire | null {\n  if (!refused) {\n    return null;\n  }\n  const from = layout.places[refused.from].output;\n  const target = layout.places[refused.to];\n  const end = target.input ?? target.output;\n  return { id: refused.id, path: wirePathOf(from, end, orientation), end };\n}\n\nfunction boxOf(layout: GraphLayout<Wire>, id: NodeId | null) {\n  if (id === null) {\n    return null;\n  }\n  return layout.places[id].box;\n}\n\nfunction inputOf(layout: GraphLayout<Wire>, id: NodeId | null) {\n  if (id === null) {\n    return null;\n  }\n  return layout.places[id].input;\n}\n\n/** A wire is never over the node it leaves. */\nfunction otherThan(from: NodeId, found: NodeId | null) {\n  if (found === from) {\n    return null;\n  }\n  return found;\n}\n\nfunction clientPointOf(event: React.PointerEvent<HTMLDivElement>): Point {\n  return { x: event.clientX, y: event.clientY };\n}\n\n/**\n * The canvas owns the wheel and the touch gestures while it holds the focus. Some browsers do not\n * give the focus to what is pressed, so the frame takes it first.\n */\nfunction engage(frame: HTMLDivElement) {\n  if (!frame.contains(document.activeElement)) {\n    frame.focus({ preventScroll: true });\n  }\n}\n\nexport type CanvasProps = {\n  /** False until the editor knows how wide it is, and so which way the pipeline reads. */\n  isLaidOut: boolean;\n  label: string;\n  /** What Fit brings into view, for its accessible name. */\n  subject: string;\n  hintId: string;\n  layout: GraphLayout<Wire>;\n  orientation: Orientation;\n  wires: Wire[];\n  params: Params;\n  runs: Record<NodeId, NodeRun>;\n  /** The node a run is on, which the view follows. */\n  runningId: NodeId | null;\n  wiring: Wiring | null;\n  refused: Refused | null;\n  isDemonstrating: boolean;\n  pressed: string | null;\n  onAction: (action: GraphAction) => void;\n  onRun: () => void;\n};\n\nexport function Canvas({\n  isLaidOut,\n  label,\n  subject,\n  hintId,\n  layout,\n  orientation,\n  wires,\n  params,\n  runs,\n  runningId,\n  wiring,\n  refused,\n  isDemonstrating,\n  pressed,\n  onAction,\n  onRun,\n}: CanvasProps) {\n  const { frameRef, planeRef, view, isMeasured } = usePanZoom();\n  const isReady = isMeasured && isLaidOut;\n  const [isPointerWiring, setIsPointerWiring] = useState(false);\n  const gesture = useRef<Gesture | null>(null);\n  const liveRef = useRef<SVGPathElement>(null);\n  const isLocked = runningId !== null;\n  const held = heldWiringOf(isDemonstrating || isPointerWiring, wiring);\n  const demoWiring = heldWiringOf(!isPointerWiring, held);\n  const demoWire = demoWireOf(demoWiring, layout, orientation);\n  const refusedWire = refusedWireOf(refused, layout, orientation);\n  const followedId = runningId ?? demoWiring?.to ?? refused?.to ?? null;\n  const pinnedBox = boxOf(layout, followedId);\n\n  useLayoutEffect(() => {\n    view.setScene(layout.bounds, 0);\n  }, [view, layout.bounds]);\n\n  useLayoutEffect(() => {\n    view.pin(pinnedBox);\n  }, [view, pinnedBox]);\n\n  useLayoutEffect(() => {\n    if (isReady) {\n      view.settle();\n    }\n  }, [view, isReady, orientation]);\n\n  /** The wire ends on the pointer, or on the port of the node it is over. */\n  function drawLive(active: Wired, client: Point) {\n    const point = view.toPlane(client);\n    const from = layout.places[active.from].output;\n    const found = nodeAt(layout.places, point, AIM_REACH);\n    const aim = otherThan(active.from, found);\n    const end = inputOf(layout, aim) ?? point;\n    liveRef.current?.setAttribute('d', wirePathOf(from, end, orientation));\n    if (aim !== active.aim) {\n      active.aim = aim;\n      onAction({ type: 'wireAimed', to: aim });\n    }\n  }\n\n  function clearLive() {\n    liveRef.current?.removeAttribute('d');\n  }\n\n  function startWire(event: React.PointerEvent<HTMLDivElement>, from: NodeId) {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const active: Wired = {\n      kind: 'wire',\n      pointerId: event.pointerId,\n      from,\n      aim: null,\n    };\n    gesture.current = active;\n    const live = liveRef.current;\n    if (live) {\n      live.style.stroke = typeColorOf(nodeOf(from).output);\n    }\n    setIsPointerWiring(true);\n    onAction({ type: 'wireStarted', from });\n    drawLive(active, clientPointOf(event));\n  }\n\n  function startPan(event: React.PointerEvent<HTMLDivElement>) {\n    event.currentTarget.setPointerCapture(event.pointerId);\n    gesture.current = { kind: 'pan' };\n    view.grab(event.pointerId, clientPointOf(event));\n  }\n\n  /** A press in the menu of a port reaches this handler through React, yet it is not on the canvas. */\n  function startGesture(event: React.PointerEvent<HTMLDivElement>) {\n    const target = event.target;\n    const frame = event.currentTarget;\n    const isMainButton = event.button === 0;\n    const isOnCanvas = target instanceof Element && frame.contains(target);\n    if (!isMainButton || !isOnCanvas) {\n      return;\n    }\n    if (target.closest('[data-canvas-control]')) {\n      return;\n    }\n    engage(frame);\n    const active = gesture.current;\n    if (active) {\n      if (active.kind === 'pan') {\n        startPan(event);\n      }\n      return;\n    }\n    const port = target.closest<HTMLElement>('[data-port]');\n    const from = nodeIdOf(port?.dataset.port);\n    if (from !== null && !isLocked) {\n      startWire(event, from);\n      return;\n    }\n    startPan(event);\n  }\n\n  function moveGesture(event: React.PointerEvent<HTMLDivElement>) {\n    const active = gesture.current;\n    if (!active) {\n      return;\n    }\n    if (active.kind === 'pan') {\n      view.drag(event.pointerId, clientPointOf(event));\n      return;\n    }\n    if (event.pointerId === active.pointerId) {\n      drawLive(active, clientPointOf(event));\n    }\n  }\n\n  function endWire(action: GraphAction) {\n    clearLive();\n    setIsPointerWiring(false);\n    onAction(action);\n  }\n\n  function finishGesture(\n    event: React.PointerEvent<HTMLDivElement>,\n    wireAction: GraphAction\n  ) {\n    const active = gesture.current;\n    if (!active) {\n      return;\n    }\n    if (active.kind === 'pan') {\n      view.release(event.pointerId);\n      if (!view.isHeld()) {\n        gesture.current = null;\n      }\n      return;\n    }\n    if (event.pointerId !== active.pointerId) {\n      return;\n    }\n    gesture.current = null;\n    endWire(wireAction);\n  }\n\n  function endGesture(event: React.PointerEvent<HTMLDivElement>) {\n    finishGesture(event, { type: 'wireDropped' });\n  }\n\n  function cancelGesture(event: React.PointerEvent<HTMLDivElement>) {\n    finishGesture(event, { type: 'wireCancelled' });\n  }\n\n  function cancelOnEscape(event: React.KeyboardEvent<HTMLDivElement>) {\n    const active = gesture.current;\n    const isWiring = active?.kind === 'wire';\n    if (event.key !== 'Escape' || !isWiring) {\n      return;\n    }\n    const frame = event.currentTarget;\n    if (frame.hasPointerCapture(active.pointerId)) {\n      frame.releasePointerCapture(active.pointerId);\n    }\n    gesture.current = null;\n    endWire({ type: 'wireCancelled' });\n  }\n\n  /** A node that takes the focus from the keyboard is brought into view. A pressed one is already under the pointer. */\n  function revealNode(id: NodeId) {\n    const isPointerDown = gesture.current !== null;\n    if (!isPointerDown) {\n      view.reveal(layout.places[id].box);\n    }\n  }\n\n  return (\n    <>\n      <div\n        ref={frameRef}\n        role='group'\n        aria-label={label}\n        aria-describedby={hintId}\n        tabIndex={-1}\n        onPointerDown={startGesture}\n        onPointerMove={moveGesture}\n        onPointerUp={endGesture}\n        onPointerCancel={cancelGesture}\n        onLostPointerCapture={cancelGesture}\n        onKeyDown={cancelOnEscape}\n        className={FRAME}\n      >\n        <div\n          ref={planeRef}\n          className={cn(\n            'absolute top-0 left-0 origin-top-left',\n            !isReady && 'invisible'\n          )}\n        >\n          <WireLayer layout={layout} />\n          {NODES.map((node) => (\n            <NodeCard\n              key={node.id}\n              node={node}\n              place={layout.places[node.id]}\n              run={runs[node.id]}\n              params={params}\n              wires={wires}\n              sourceId={sourceOf(wires, node.id)}\n              signature={signatureOf(wires, params, node.id)}\n              aim={aimOf(held, wires, node.id)}\n              isOutputHeld={\n                held?.from === node.id || pressed === `out-${node.id}`\n              }\n              isLocked={isLocked}\n              isRetryPressed={pressed === 'retry'}\n              onAction={onAction}\n              onRun={onRun}\n              onReveal={revealNode}\n            />\n          ))}\n          <HeldLayer demo={demoWire} refused={refusedWire} liveRef={liveRef} />\n          {refused && refusedWire && (\n            <RefusalNote\n              key={refused.id}\n              at={refusedWire.end}\n              reason={refused.reason}\n            />\n          )}\n        </div>\n      </div>\n      <ZoomControl view={view} subject={subject} />\n    </>\n  );\n}\n\ntype RefusalNoteProps = {\n  at: Point;\n  reason: string;\n};\n\n/**\n * Why the wire was refused, said where it was let go. It is drawn inside the canvas, hanging from\n * a point without width, so it never leaves the block nor widens the page.\n */\nfunction RefusalNote({ at, reason }: RefusalNoteProps) {\n  const noteStyle = { transform: `translate(${at.x}px, ${at.y - 14}px)` };\n\n  return (\n    <div style={noteStyle} className='absolute top-0 left-0 z-10 w-0'>\n      <p className='surface-raised text-destructive-ink w-max max-w-56 -translate-x-1/2 -translate-y-full rounded-lg px-2 py-1 text-xs leading-snug font-medium text-balance transition-opacity duration-150 starting:opacity-0'>\n        {reason}\n      </p>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/canvas.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/node-card.tsx",
      "content": "'use client';\n\nimport { MotionNumber } from '@/components/core/motion-number';\nimport { pressedQuietOf } from '@/registry/ndeko/lib/demonstration';\nimport {\n  ArrowRightIcon,\n  CircleCheckIcon,\n  CircleXIcon,\n  CpuIcon,\n  FileTextIcon,\n  MessageSquareTextIcon,\n  MinusIcon,\n  PlusIcon,\n  ScissorsIcon,\n  SearchIcon,\n  type Icon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Badge } from '@/registry/ndeko/ui/badge';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuLabel,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuShortcut,\n  DropdownMenuTrigger,\n} from '@/registry/ndeko/ui/dropdown-menu';\nimport { Input } from '@/registry/ndeko/ui/input';\nimport {\n  Select,\n  SelectContent,\n  SelectItem,\n  SelectTrigger,\n  SelectValue,\n} from '@/registry/ndeko/ui/select';\nimport { Slider } from '@/registry/ndeko/ui/slider';\n\nimport {\n  CHUNK_SIZE,\n  EMBED_MODELS,\n  NODES,\n  TOP_K,\n  TYPE_WORD,\n  type NodeId,\n  type NodeSpec,\n  type Params,\n  type PortType,\n} from './data';\nimport type { NodePlace, Point } from './layout';\nimport { refusalOf } from './pipeline';\nimport type { GraphAction, NodeRun, RunStatus, Wire } from './session';\nimport { typeColorOf } from './wires';\n\n/** What a held wire makes of a node: where it leaves, a node that can take it, the one it is over, or one that cannot. */\nexport type Aim = 'idle' | 'source' | 'open' | 'aimed' | 'refusing' | 'closed';\n\nconst NODE_ICON: Record<NodeId, Icon> = {\n  load: FileTextIcon,\n  split: ScissorsIcon,\n  embed: CpuIcon,\n  search: SearchIcon,\n  answer: MessageSquareTextIcon,\n};\n\nconst STATUS_WORD: Record<RunStatus, string> = {\n  idle: 'Not run',\n  running: 'Running',\n  done: 'Done',\n  cached: 'Served from cache',\n  failed: 'Failed',\n  skipped: 'Skipped',\n};\n\nconst CARD =\n  'bg-card hairline-ring ring-border flex size-full flex-col rounded-xl p-2.5 shadow-[0_1px_2px_rgb(0_0_0/0.04)] transition-[box-shadow,opacity] duration-150';\n\nconst STATUS_RING: Partial<Record<RunStatus, string>> = {\n  running: 'ring-primary/60 ring-2',\n  failed: 'ring-destructive/50 ring-2',\n};\n\nconst AIM_RING: Record<Aim, string> = {\n  idle: '',\n  source: '',\n  open: 'ring-primary/45 ring-2',\n  aimed: 'ring-primary ring-2',\n  refusing: 'ring-destructive/70 ring-2',\n  closed: 'opacity-50',\n};\n\nconst PORT =\n  'group/port absolute top-0 left-0 flex size-6 items-center justify-center rounded-full outline-none';\n\nconst DOT =\n  'ring-card size-3 rounded-full ring-2 transition-[scale] duration-150 ease-(--ease-out-strong) group-hover/port:scale-125 group-focus-visible/port:scale-125';\n\nconst NOTHING = 'nothing';\n\n/** A port sits on the edge of its node, in a square large enough for a finger. */\nfunction portStyleOf(port: Point, place: NodePlace) {\n  const x = port.x - place.box.x - 12;\n  const y = port.y - place.box.y - 12;\n  return { transform: `translate(${x}px, ${y}px)` };\n}\n\nfunction heldDotOf(isHeld: boolean) {\n  if (isHeld) {\n    return 'scale-150';\n  }\n  return undefined;\n}\n\nfunction staleToneOf(isStale: boolean) {\n  if (isStale) {\n    return 'opacity-50';\n  }\n  return undefined;\n}\n\nfunction TypeMark({ type }: { type: PortType }) {\n  return (\n    <span className='flex items-center gap-1'>\n      <span\n        aria-hidden='true'\n        style={{ backgroundColor: typeColorOf(type) }}\n        className='size-1.5 rounded-full'\n      />\n      {TYPE_WORD[type]}\n    </span>\n  );\n}\n\n/** The ring closes over the time the node runs. It is drawn once per run and never loops. */\nfunction ProgressRing({ ms }: { ms: number }) {\n  const ringStyle = { transitionDuration: `${ms}ms` };\n\n  return (\n    <svg viewBox='0 0 16 16' aria-hidden='true' className='size-4 -rotate-90'>\n      <circle\n        cx='8'\n        cy='8'\n        r='6'\n        className='stroke-foreground/15 fill-none stroke-2'\n      />\n      <circle\n        cx='8'\n        cy='8'\n        r='6'\n        pathLength='1'\n        strokeDasharray='1'\n        style={ringStyle}\n        className='stroke-primary fill-none stroke-2 transition-[stroke-dashoffset] ease-linear [stroke-dashoffset:0] [stroke-linecap:round] starting:[stroke-dashoffset:1]'\n      />\n    </svg>\n  );\n}\n\nfunction StatusMark({ status, ms }: { status: RunStatus; ms: number }) {\n  return (\n    <span className='flex h-5 shrink-0 items-center'>\n      <Swap swapKey={status}>\n        {status === 'running' && <ProgressRing ms={ms} />}\n        {status === 'done' && (\n          <CircleCheckIcon className='text-success-foreground size-4' />\n        )}\n        {status === 'cached' && <Badge variant='secondary'>Cached</Badge>}\n        {status === 'failed' && (\n          <CircleXIcon className='text-destructive-ink size-4' />\n        )}\n        {status === 'skipped' && <Badge variant='outline'>Skipped</Badge>}\n      </Swap>\n      <span className='sr-only'>{STATUS_WORD[status]}</span>\n    </span>\n  );\n}\n\ntype WidgetProps = {\n  node: NodeSpec;\n  params: Params;\n  isLocked: boolean;\n  onAction: (action: GraphAction) => void;\n};\n\nfunction SizeWidget({ node, params, isLocked, onAction }: WidgetProps) {\n  function change(next: number | readonly number[]) {\n    if (typeof next === 'number') {\n      onAction({ type: 'paramsChanged', params: { chunkSize: next } });\n    }\n  }\n\n  return (\n    <>\n      <span className='text-muted-foreground shrink-0 text-xs'>Size</span>\n      <Slider\n        value={params.chunkSize}\n        min={CHUNK_SIZE.min}\n        max={CHUNK_SIZE.max}\n        step={CHUNK_SIZE.step}\n        disabled={isLocked}\n        thumbLabels={[`Chunk size of ${node.title}, in tokens`]}\n        onValueChange={change}\n      />\n      <span className='w-9 shrink-0 text-end text-xs tabular-nums'>\n        {params.chunkSize}\n      </span>\n    </>\n  );\n}\n\nfunction ModelWidget({ node, params, isLocked, onAction }: WidgetProps) {\n  function change(next: unknown) {\n    const model = EMBED_MODELS.find((candidate) => candidate.value === next);\n    if (model) {\n      onAction({ type: 'paramsChanged', params: { model: model.value } });\n    }\n  }\n\n  return (\n    <Select\n      items={EMBED_MODELS}\n      value={params.model}\n      disabled={isLocked}\n      onValueChange={change}\n    >\n      <SelectTrigger size='sm' aria-label={`Model of ${node.title}`}>\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        {EMBED_MODELS.map((model) => (\n          <SelectItem key={model.value} value={model.value}>\n            {model.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  );\n}\n\nfunction TopWidget({ params, isLocked, onAction }: WidgetProps) {\n  const isLowest = params.topK <= TOP_K.min;\n  const isHighest = params.topK >= TOP_K.max;\n\n  function step(by: number) {\n    onAction({ type: 'paramsChanged', params: { topK: params.topK + by } });\n  }\n\n  return (\n    <>\n      <span className='text-muted-foreground flex-1 text-xs'>Passages</span>\n      <Button\n        type='button'\n        variant='outline'\n        size='icon-sm'\n        aria-label='One passage fewer'\n        disabled={isLocked || isLowest}\n        focusableWhenDisabled\n        onClick={() => step(-1)}\n        className='size-6'\n      >\n        <MinusIcon className='size-3.5' />\n      </Button>\n      <output\n        aria-label='Passages to keep'\n        className='w-5 text-center text-xs font-medium'\n      >\n        <MotionNumber value={params.topK} />\n      </output>\n      <Button\n        type='button'\n        variant='outline'\n        size='icon-sm'\n        aria-label='One passage more'\n        disabled={isLocked || isHighest}\n        focusableWhenDisabled\n        onClick={() => step(1)}\n        className='size-6'\n      >\n        <PlusIcon className='size-3.5' />\n      </Button>\n    </>\n  );\n}\n\nfunction PromptWidget({ node, params, isLocked, onAction }: WidgetProps) {\n  return (\n    <Input\n      size='sm'\n      value={params.prompt}\n      disabled={isLocked}\n      autoComplete='off'\n      aria-label={`Question for ${node.title}`}\n      placeholder='Ask the help center'\n      onChange={(event) =>\n        onAction({\n          type: 'paramsChanged',\n          params: { prompt: event.target.value },\n        })\n      }\n    />\n  );\n}\n\n/** The setting of each node, edited where it applies. Loading has nothing to set. */\nfunction Widget(props: WidgetProps) {\n  const id = props.node.id;\n  if (id === 'split') {\n    return <SizeWidget {...props} />;\n  }\n  if (id === 'embed') {\n    return <ModelWidget {...props} />;\n  }\n  if (id === 'search') {\n    return <TopWidget {...props} />;\n  }\n  if (id === 'answer') {\n    return <PromptWidget {...props} />;\n  }\n  return (\n    <span className='text-muted-foreground truncate text-xs'>\n      Source · Help center\n    </span>\n  );\n}\n\ntype PreviewProps = {\n  node: NodeSpec;\n  run: NodeRun;\n  isStale: boolean;\n  isRetryPressed: boolean;\n  onRun: () => void;\n};\n\n/** What the node last produced. A result older than its settings stays, dimmed, until the next run. */\nfunction Preview({ node, run, isStale, isRetryPressed, onRun }: PreviewProps) {\n  const { status, result } = run;\n\n  if (status === 'running') {\n    return <p className='text-muted-foreground text-xs'>{node.workingLine}</p>;\n  }\n  if (status === 'failed') {\n    return (\n      <div className='flex items-start gap-2'>\n        <p className='text-destructive-ink line-clamp-2 min-w-0 flex-1 text-xs'>\n          {run.message}\n        </p>\n        <Button\n          type='button'\n          size='sm'\n          variant='outline'\n          data-canvas-control\n          onClick={onRun}\n          className={cn('h-6 shrink-0 px-2', pressedQuietOf(isRetryPressed))}\n        >\n          Retry\n        </Button>\n      </div>\n    );\n  }\n  if (status === 'skipped') {\n    return <p className='text-muted-foreground text-xs'>{run.message}</p>;\n  }\n  if (!result) {\n    return <p className='text-muted-foreground text-xs'>Not run yet</p>;\n  }\n\n  return (\n    <div\n      className={cn(\n        'flex flex-col transition-opacity duration-200',\n        staleToneOf(isStale)\n      )}\n    >\n      <p className='text-[13px] leading-5 font-medium tabular-nums'>\n        {result.headline}\n        {isStale && <span className='sr-only'>, out of date</span>}\n      </p>\n      <p className='text-muted-foreground line-clamp-2 text-xs leading-4'>\n        {result.lines.join(', ')}\n      </p>\n    </div>\n  );\n}\n\ntype InputPortProps = {\n  node: NodeSpec;\n  type: PortType;\n  port: Point;\n  place: NodePlace;\n  wires: Wire[];\n  sourceId: NodeId | null;\n  isLocked: boolean;\n  onAction: (action: GraphAction) => void;\n};\n\nfunction sourceWordOf(sourceId: NodeId | null) {\n  const source = NODES.find((candidate) => candidate.id === sourceId);\n  if (!source) {\n    return 'Not connected';\n  }\n  return `Fed by ${source.title}`;\n}\n\n/** Connecting without dragging: the port opens the nodes that can feed it. The others say what they give. */\nfunction InputPort({\n  node,\n  type,\n  port,\n  place,\n  wires,\n  sourceId,\n  isLocked,\n  onAction,\n}: InputPortProps) {\n  const others = NODES.filter((candidate) => candidate.id !== node.id);\n\n  function choose(next: unknown) {\n    const source = others.find((candidate) => candidate.id === next);\n    if (source) {\n      onAction({ type: 'connected', from: source.id, to: node.id });\n      return;\n    }\n    onAction({ type: 'disconnected', to: node.id });\n  }\n\n  return (\n    <DropdownMenu>\n      <DropdownMenuTrigger\n        data-canvas-control\n        disabled={isLocked}\n        aria-label={`Input of ${node.title}: ${TYPE_WORD[type]}. ${sourceWordOf(sourceId)}`}\n        style={portStyleOf(port, place)}\n        className={cn(\n          PORT,\n          'focus-visible:ring-ring cursor-pointer focus-visible:ring-2'\n        )}\n      >\n        <span style={{ backgroundColor: typeColorOf(type) }} className={DOT} />\n      </DropdownMenuTrigger>\n      <DropdownMenuContent className='min-w-60'>\n        <DropdownMenuLabel>Feed {node.title} from</DropdownMenuLabel>\n        <DropdownMenuRadioGroup\n          value={sourceId ?? NOTHING}\n          onValueChange={choose}\n        >\n          {others.map((candidate) => (\n            <DropdownMenuRadioItem\n              key={candidate.id}\n              value={candidate.id}\n              disabled={refusalOf(wires, candidate.id, node.id) !== null}\n            >\n              {candidate.title}\n              <DropdownMenuShortcut>\n                {TYPE_WORD[candidate.output]}\n              </DropdownMenuShortcut>\n            </DropdownMenuRadioItem>\n          ))}\n          <DropdownMenuRadioItem value={NOTHING}>Nothing</DropdownMenuRadioItem>\n        </DropdownMenuRadioGroup>\n      </DropdownMenuContent>\n    </DropdownMenu>\n  );\n}\n\nfunction spokenOf(node: NodeSpec, run: NodeRun, sourceId: NodeId | null) {\n  const status = STATUS_WORD[run.status];\n  if (node.input === null) {\n    return `${node.title}. ${status}`;\n  }\n  return `${node.title}. ${sourceWordOf(sourceId)}. ${status}`;\n}\n\nexport type NodeCardProps = {\n  node: NodeSpec;\n  place: NodePlace;\n  run: NodeRun;\n  params: Params;\n  wires: Wire[];\n  sourceId: NodeId | null;\n  /** What the node would compute now. A result with another signature is out of date. */\n  signature: string;\n  aim: Aim;\n  /** A wire is held out of its output, by a pointer or by the demonstration. */\n  isOutputHeld: boolean;\n  /** A run is going: settings and wires wait until it ends. */\n  isLocked: boolean;\n  isRetryPressed: boolean;\n  onAction: (action: GraphAction) => void;\n  onRun: () => void;\n  onReveal: (id: NodeId) => void;\n};\n\nexport function NodeCard({\n  node,\n  place,\n  run,\n  params,\n  wires,\n  sourceId,\n  signature,\n  aim,\n  isOutputHeld,\n  isLocked,\n  isRetryPressed,\n  onAction,\n  onRun,\n  onReveal,\n}: NodeCardProps) {\n  const Glyph = NODE_ICON[node.id];\n  const { box } = place;\n  const cardStyle = { transform: `translate(${box.x}px, ${box.y}px)` };\n\n  return (\n    <div\n      data-node={node.id}\n      role='group'\n      aria-label={spokenOf(node, run, sourceId)}\n      style={cardStyle}\n      onFocus={() => onReveal(node.id)}\n      className='absolute top-0 left-0 h-[168px] w-[216px]'\n    >\n      <div className={cn(CARD, STATUS_RING[run.status], AIM_RING[aim])}>\n        <p className='text-muted-foreground flex h-5 items-center gap-1.5 text-[11px]'>\n          {node.input && <TypeMark type={node.input} />}\n          {node.input && <ArrowRightIcon className='size-3' />}\n          <TypeMark type={node.output} />\n        </p>\n        <div className='mt-1 flex h-7 items-center gap-2'>\n          <span\n            aria-hidden='true'\n            className='keycap-3d text-muted-foreground inline-flex size-6 shrink-0 items-center justify-center rounded-md'\n          >\n            <Glyph className='size-3.5' />\n          </span>\n          <h3 className='min-w-0 flex-1 truncate text-[13px] font-medium'>\n            {node.title}\n          </h3>\n          <StatusMark status={run.status} ms={node.runMs} />\n        </div>\n        <div data-canvas-control className='mt-1.5 flex h-8 items-center gap-2'>\n          <Widget\n            node={node}\n            params={params}\n            isLocked={isLocked}\n            onAction={onAction}\n          />\n        </div>\n        <div className='mt-2 h-[46px] overflow-hidden'>\n          <Preview\n            node={node}\n            run={run}\n            isStale={run.signature !== signature}\n            isRetryPressed={isRetryPressed}\n            onRun={onRun}\n          />\n        </div>\n      </div>\n      {node.input && place.input && (\n        <InputPort\n          node={node}\n          type={node.input}\n          port={place.input}\n          place={place}\n          wires={wires}\n          sourceId={sourceId}\n          isLocked={isLocked}\n          onAction={onAction}\n        />\n      )}\n      <span\n        data-port={node.id}\n        aria-hidden='true'\n        style={portStyleOf(place.output, place)}\n        className={cn(PORT, 'cursor-crosshair')}\n      >\n        <span\n          style={{ backgroundColor: typeColorOf(node.output) }}\n          className={cn(DOT, heldDotOf(isOutputHeld))}\n        />\n      </span>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/node-card.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/wires.tsx",
      "content": "'use client';\n\nimport { AnimatePresence, motion } from 'motion/react';\n\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { seriesColorOf } from '@/registry/ndeko/lib/agent-run';\nimport { EASE_OUT_STRONG } from '@/registry/ndeko/lib/motion-presets';\nimport { cn } from '@/registry/ndeko/lib/utils';\n\nimport { TYPE_SERIES, type PortType } from './data';\nimport type { GraphLayout, PlacedWire, Point } from './layout';\nimport type { Wire } from './session';\n\nconst LAYER =\n  'pointer-events-none absolute top-0 left-0 size-px overflow-visible';\n\nconst WIRE = 'fill-none stroke-2 [stroke-linecap:round]';\n\n/** A wire that has just been made shows at full strength, then settles among the others. */\nconst SETTLING =\n  'opacity-70 transition-opacity duration-500 starting:opacity-100';\n\nconst DRAW = { duration: 0.5, ease: EASE_OUT_STRONG };\n\nconst REACH = { duration: 0.45, ease: EASE_OUT_STRONG };\n\nconst SHAKE = { duration: 0.34, ease: EASE_OUT_STRONG };\n\n/** An error nudges once: four pixels each way, then back. */\nconst SHAKEN = { x: [0, -4, 4, -3, 3, 0] };\n\nconst STILL = { x: 0 };\n\nconst LEAVE = { opacity: 0, transition: { duration: 0.15 } };\n\nexport function typeColorOf(type: PortType) {\n  return seriesColorOf(TYPE_SERIES[type]);\n}\n\nfunction drawStartOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return { pathLength: 1 };\n  }\n  return { pathLength: 0 };\n}\n\nfunction shakeOf(shouldReduceMotion: boolean) {\n  if (shouldReduceMotion) {\n    return STILL;\n  }\n  return SHAKEN;\n}\n\n/** Only a wire made from a menu draws itself: one let go by a hand is already where it lands. */\nfunction WirePath({ wire }: { wire: PlacedWire<Wire> }) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n  const style = { stroke: typeColorOf(wire.type) };\n\n  if (wire.link.arrival === 'drawn') {\n    return (\n      <motion.path\n        d={wire.path}\n        style={style}\n        initial={drawStartOf(shouldReduceMotion)}\n        animate={{ pathLength: 1 }}\n        transition={DRAW}\n        className={cn(WIRE, SETTLING)}\n      />\n    );\n  }\n\n  const hasLanded = wire.link.arrival === 'dropped';\n\n  return (\n    <path\n      d={wire.path}\n      style={style}\n      className={cn(WIRE, 'opacity-70', hasLanded && SETTLING)}\n    />\n  );\n}\n\nexport function WireLayer({ layout }: { layout: GraphLayout<Wire> }) {\n  return (\n    <svg aria-hidden='true' className={LAYER}>\n      {layout.wires.map((wire) => (\n        <WirePath key={wire.id} wire={wire} />\n      ))}\n    </svg>\n  );\n}\n\nexport type HeldWire = {\n  path: string;\n  type: PortType;\n};\n\nexport type RefusedWire = {\n  id: number;\n  path: string;\n  end: Point;\n};\n\ntype HeldLayerProps = {\n  /** The wire the demonstration holds out, from its port to the node it aims at. */\n  demo: HeldWire | null;\n  /** A wire that was refused: it stays a moment, its end shakes once, then it leaves. */\n  refused: RefusedWire | null;\n  /** The wire a pointer holds. Its path is written to the element on every move, never rendered. */\n  liveRef: React.Ref<SVGPathElement>;\n};\n\nexport function HeldLayer({ demo, refused, liveRef }: HeldLayerProps) {\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  return (\n    <svg aria-hidden='true' className={LAYER}>\n      {demo && (\n        <motion.path\n          key={demo.path}\n          d={demo.path}\n          style={{ stroke: typeColorOf(demo.type) }}\n          initial={drawStartOf(shouldReduceMotion)}\n          animate={{ pathLength: 1 }}\n          transition={REACH}\n          className={WIRE}\n        />\n      )}\n      <AnimatePresence>\n        {refused && (\n          <motion.g key={refused.id} exit={LEAVE}>\n            <path\n              d={refused.path}\n              className={cn(WIRE, 'stroke-destructive [stroke-dasharray:4_5]')}\n            />\n            <motion.circle\n              cx={refused.end.x}\n              cy={refused.end.y}\n              r={5}\n              animate={shakeOf(shouldReduceMotion)}\n              transition={SHAKE}\n              className='fill-destructive'\n            />\n          </motion.g>\n        )}\n      </AnimatePresence>\n      <path ref={liveRef} className={WIRE} />\n    </svg>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/wires.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/zoom-control.tsx",
      "content": "'use client';\n\nimport { MaximizeIcon, MinusIcon, PlusIcon } from '@/registry/ndeko/lib/icons';\nimport { Button } from '@/registry/ndeko/ui/button';\n\nimport {\n  MAX_ZOOM,\n  MIN_ZOOM,\n  useZoomPercent,\n  type CanvasView,\n} from './use-pan-zoom';\n\nconst ZOOM_STEP = 1.25;\n\nconst MIN_PERCENT = Math.round(MIN_ZOOM * 100);\n\nconst MAX_PERCENT = Math.round(MAX_ZOOM * 100);\n\ntype ZoomControlProps = {\n  view: CanvasView;\n  /** What Fit brings into view, for its accessible name. */\n  subject: string;\n};\n\n/** It sits on the canvas and is the only part that renders again while the zoom changes. */\nexport function ZoomControl({ view, subject }: ZoomControlProps) {\n  const percent = useZoomPercent(view);\n  const isSmallest = percent <= MIN_PERCENT;\n  const isLargest = percent >= MAX_PERCENT;\n\n  return (\n    <div\n      role='group'\n      aria-label='Zoom'\n      className='bg-card hairline-ring ring-border absolute bottom-3 left-3 flex items-center gap-0.5 rounded-full p-0.5 shadow-[0_1px_2px_rgb(0_0_0/0.05)]'\n    >\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Zoom out'\n        disabled={isSmallest}\n        focusableWhenDisabled\n        onClick={() => view.zoomStep(1 / ZOOM_STEP)}\n        className='rounded-full'\n      >\n        <MinusIcon />\n      </Button>\n      <Button\n        type='button'\n        variant='ghost'\n        size='sm'\n        aria-label={`Zoom ${percent}%. Reset to 100%`}\n        onClick={() => view.zoomTo(1)}\n        className='w-12 rounded-full px-0 tabular-nums'\n      >\n        {percent}%\n      </Button>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label='Zoom in'\n        disabled={isLargest}\n        focusableWhenDisabled\n        onClick={() => view.zoomStep(ZOOM_STEP)}\n        className='rounded-full'\n      >\n        <PlusIcon />\n      </Button>\n      <Button\n        type='button'\n        variant='ghost'\n        size='icon-sm'\n        aria-label={`Fit ${subject} in view`}\n        onClick={() => view.fit()}\n        className='rounded-full'\n      >\n        <MaximizeIcon />\n      </Button>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/zoom-control.tsx"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/use-pan-zoom.ts",
      "content": "'use client';\n\nimport {\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n} from 'react';\n\ntype Point = {\n  x: number;\n  y: number;\n};\n\ntype Box = Point & {\n  width: number;\n  height: number;\n};\n\ntype Viewport = Point & {\n  zoom: number;\n};\n\ntype Span = {\n  centre: Point;\n  distance: number;\n};\n\nexport const MIN_ZOOM = 0.4;\n\nexport const MAX_ZOOM = 1.6;\n\n/** Fit never enlarges past full size: a small flow stays readable instead of filling the frame. */\nconst FIT_MAX_ZOOM = 1;\n\n/** Nor does it shrink a flow until its text cannot be read: what does not fit is reached by panning. */\nconst FIT_MIN_ZOOM = 0.75;\n\nconst FIT_MARGIN = 20;\n\nconst REVEAL_MARGIN = 16;\n\nconst EASED = 'transform 220ms cubic-bezier(0.23, 1, 0.32, 1)';\n\n/** A wheel that reports lines, as some mice do, moves this many pixels a line. */\nconst LINE_PIXELS = 16;\n\nconst WHEEL_DOM_DELTA_LINE = 1;\n\nconst WHEEL_ZOOM_RATE = 0.01;\n\n/** One wheel event never zooms by more than about a quarter. */\nconst WHEEL_ZOOM_LIMIT = 24;\n\nconst NO_BOX: Box = { x: 0, y: 0, width: 1, height: 1 };\n\nfunction clamp(value: number, min: number, max: number) {\n  const atLeast = Math.max(value, min);\n  return Math.min(atLeast, max);\n}\n\nfunction transitionOf(isEased: boolean) {\n  if (isEased) {\n    return EASED;\n  }\n  return 'none';\n}\n\n/** How far a span has to move to sit between two edges. Its start wins when it is too long to fit. */\nfunction shiftOf(start: number, end: number, min: number, max: number) {\n  if (start < min) {\n    return min - start;\n  }\n  if (end > max) {\n    const back = max - end;\n    const untilStart = min - start;\n    return Math.max(back, untilStart);\n  }\n  return 0;\n}\n\n/**\n * Where the content starts along one axis of the frame: centred when it fits, at the margin when it\n * does not, so the start of the flow is what shows.\n */\nfunction startOf(\n  frameSize: number,\n  contentStart: number,\n  contentSize: number,\n  zoom: number\n) {\n  const scaled = contentSize * zoom;\n  const room = frameSize - FIT_MARGIN * 2;\n  if (scaled <= room) {\n    return (frameSize - scaled) / 2 - contentStart * zoom;\n  }\n  return FIT_MARGIN - contentStart * zoom;\n}\n\nfunction spanOf(pointers: Map<number, Point>): Span | null {\n  const [first, second] = Array.from(pointers.values());\n  if (!first || !second) {\n    return null;\n  }\n  const centre = { x: (first.x + second.x) / 2, y: (first.y + second.y) / 2 };\n  const distance = Math.hypot(second.x - first.x, second.y - first.y);\n  return { centre, distance };\n}\n\nfunction wheelUnitOf(event: WheelEvent) {\n  if (event.deltaMode === WHEEL_DOM_DELTA_LINE) {\n    return LINE_PIXELS;\n  }\n  return 1;\n}\n\n/** Ctrl or Cmd with the wheel, which is also how a trackpad reports a pinch. */\nfunction isZoomWheel(event: WheelEvent) {\n  return event.ctrlKey || event.metaKey;\n}\n\n/**\n * Pan and zoom of a canvas as one transform on one plane element. The transform is written to the\n * element, never through React state: a drag or a pinch changes it on every frame.\n */\nexport function createCanvasView() {\n  let frame: HTMLElement | null = null;\n  let plane: HTMLElement | null = null;\n  let viewport: Viewport = { x: 0, y: 0, zoom: 1 };\n  let content = NO_BOX;\n  let coveredShare = 0;\n  let pinned: Box | null = null;\n  /** True once a person has moved the view: it is no longer refitted when the frame changes size. */\n  let isManual = false;\n  let hasFitted = false;\n  const listeners = new Set<() => void>();\n  const pointers = new Map<number, Point>();\n\n  function sizeOf() {\n    if (!frame) {\n      return null;\n    }\n    return { width: frame.clientWidth, height: frame.clientHeight };\n  }\n\n  function apply(next: Viewport, isEased: boolean) {\n    const x = Math.round(next.x);\n    const y = Math.round(next.y);\n    viewport = { x, y, zoom: next.zoom };\n    if (plane) {\n      plane.style.transition = transitionOf(isEased);\n      plane.style.transform = `translate(${x}px, ${y}px) scale(${next.zoom})`;\n    }\n    listeners.forEach((listener) => listener());\n  }\n\n  function localOf(client: Point): Point {\n    const rect = frame?.getBoundingClientRect();\n    if (!rect) {\n      return client;\n    }\n    return { x: client.x - rect.left, y: client.y - rect.top };\n  }\n\n  function centreOf(): Point {\n    const size = sizeOf();\n    if (!size) {\n      return { x: 0, y: 0 };\n    }\n    return { x: size.width / 2, y: size.height / 2 };\n  }\n\n  /** The point under `anchor` stays under it while the zoom changes. */\n  function zoomedAround(factor: number, anchor: Point): Viewport {\n    const zoom = clamp(viewport.zoom * factor, MIN_ZOOM, MAX_ZOOM);\n    const ratio = zoom / viewport.zoom;\n    const x = anchor.x - (anchor.x - viewport.x) * ratio;\n    const y = anchor.y - (anchor.y - viewport.y) * ratio;\n    return { x, y, zoom };\n  }\n\n  function fitted(): Viewport | null {\n    const size = sizeOf();\n    if (!size) {\n      return null;\n    }\n    const roomX = size.width - FIT_MARGIN * 2;\n    const roomY = size.height - FIT_MARGIN * 2;\n    const scale = Math.min(roomX / content.width, roomY / content.height);\n    const zoom = clamp(scale, FIT_MIN_ZOOM, FIT_MAX_ZOOM);\n    const x = startOf(size.width, content.x, content.width, zoom);\n    const y = startOf(size.height, content.y, content.height, zoom);\n    return { x, y, zoom };\n  }\n\n  function revealed(box: Box): Viewport | null {\n    const size = sizeOf();\n    if (!size) {\n      return null;\n    }\n    const left = box.x * viewport.zoom + viewport.x;\n    const top = box.y * viewport.zoom + viewport.y;\n    const right = left + box.width * viewport.zoom;\n    const bottom = top + box.height * viewport.zoom;\n    const visibleHeight = size.height * (1 - coveredShare);\n    const maxX = size.width - REVEAL_MARGIN;\n    const maxY = visibleHeight - REVEAL_MARGIN;\n    const dx = shiftOf(left, right, REVEAL_MARGIN, maxX);\n    const dy = shiftOf(top, bottom, REVEAL_MARGIN, maxY);\n    if (dx === 0 && dy === 0) {\n      return null;\n    }\n    return { ...viewport, x: viewport.x + dx, y: viewport.y + dy };\n  }\n\n  function refit(isEased: boolean) {\n    const next = fitted();\n    if (next) {\n      hasFitted = true;\n      apply(next, isEased);\n    }\n  }\n\n  /**\n   * Focus on a step outside the frame makes the browser scroll the frame to it. The scroll is taken\n   * back and given to the transform, so the plane stays the only thing that moves.\n   */\n  function absorbScroll() {\n    if (!frame) {\n      return;\n    }\n    const left = frame.scrollLeft;\n    const top = frame.scrollTop;\n    if (left === 0 && top === 0) {\n      return;\n    }\n    frame.scrollLeft = 0;\n    frame.scrollTop = 0;\n    apply({ ...viewport, x: viewport.x - left, y: viewport.y - top }, false);\n  }\n\n  function reveal(box: Box) {\n    absorbScroll();\n    if (!hasFitted) {\n      return;\n    }\n    const next = revealed(box);\n    if (next) {\n      apply(next, true);\n    }\n  }\n\n  function panBy(dx: number, dy: number) {\n    isManual = true;\n    apply({ ...viewport, x: viewport.x + dx, y: viewport.y + dy }, false);\n  }\n\n  function pinch(before: Span, after: Span) {\n    if (before.distance === 0) {\n      return;\n    }\n    const factor = after.distance / before.distance;\n    const zoomed = zoomedAround(factor, localOf(before.centre));\n    const x = zoomed.x + after.centre.x - before.centre.x;\n    const y = zoomed.y + after.centre.y - before.centre.y;\n    isManual = true;\n    apply({ x, y, zoom: zoomed.zoom }, false);\n  }\n\n  return {\n    /** The frame that clips the canvas and the plane that moves inside it. */\n    attach(nextFrame: HTMLElement | null, nextPlane: HTMLElement | null) {\n      frame = nextFrame;\n      plane = nextPlane;\n    },\n    subscribe(listener: () => void) {\n      listeners.add(listener);\n      return () => {\n        listeners.delete(listener);\n      };\n    },\n    percent() {\n      return Math.round(viewport.zoom * 100);\n    },\n    zoom() {\n      return viewport.zoom;\n    },\n    origin(): Point {\n      return { x: viewport.x, y: viewport.y };\n    },\n    /** A point of the screen as a point of the plane. */\n    toPlane(client: Point): Point {\n      const local = localOf(client);\n      const x = (local.x - viewport.x) / viewport.zoom;\n      const y = (local.y - viewport.y) / viewport.zoom;\n      return { x, y };\n    },\n    panBy,\n    zoomStep(factor: number) {\n      isManual = true;\n      apply(zoomedAround(factor, centreOf()), true);\n    },\n    zoomTo(zoom: number) {\n      isManual = true;\n      apply(zoomedAround(zoom / viewport.zoom, centreOf()), true);\n    },\n    /** Shows everything again and hands the view back to the canvas, which refits it on its own. */\n    fit() {\n      isManual = false;\n      refit(true);\n    },\n    /** What Fit shows, and the share of the frame a sheet covers from the bottom, from 0 to 1. */\n    setScene(bounds: Box, covered: number) {\n      content = bounds;\n      coveredShare = covered;\n    },\n    /** Called when the frame, the layout or the sheet changed: refits a view nobody moved. */\n    settle() {\n      const isFirst = !hasFitted;\n      if (isFirst || !isManual) {\n        refit(!isFirst);\n      }\n      if (!pinned) {\n        return;\n      }\n      const next = revealed(pinned);\n      if (next) {\n        apply(next, !isFirst);\n      }\n    },\n    reveal,\n    /** The box to keep in view, now and whenever the frame changes size. */\n    pin(box: Box | null) {\n      pinned = box;\n      if (box) {\n        reveal(box);\n      }\n    },\n    absorbScroll,\n    grab(pointerId: number, at: Point) {\n      pointers.set(pointerId, at);\n    },\n    /** One pointer pans. Two pointers pinch: the zoom follows their distance, the pan their middle. */\n    drag(pointerId: number, now: Point) {\n      const last = pointers.get(pointerId);\n      if (!last) {\n        return;\n      }\n      const before = spanOf(pointers);\n      pointers.set(pointerId, now);\n      const after = spanOf(pointers);\n      if (before && after) {\n        pinch(before, after);\n        return;\n      }\n      panBy(now.x - last.x, now.y - last.y);\n    },\n    release(pointerId: number) {\n      pointers.delete(pointerId);\n    },\n    isHeld() {\n      return pointers.size > 0;\n    },\n    /** A plain wheel pans. A zoom wheel zooms around the pointer. */\n    takeWheel(event: WheelEvent) {\n      const unit = wheelUnitOf(event);\n      if (!isZoomWheel(event)) {\n        panBy(-event.deltaX * unit, -event.deltaY * unit);\n        return;\n      }\n      const raw = event.deltaY * unit;\n      const delta = clamp(raw, -WHEEL_ZOOM_LIMIT, WHEEL_ZOOM_LIMIT);\n      const factor = Math.exp(-delta * WHEEL_ZOOM_RATE);\n      const anchor = localOf({ x: event.clientX, y: event.clientY });\n      isManual = true;\n      apply(zoomedAround(factor, anchor), false);\n    },\n  };\n}\n\nexport type CanvasView = ReturnType<typeof createCanvasView>;\n\n/**\n * The frame and the plane of a canvas, with its view. Call it in the component that renders them,\n * before any effect that uses the view. A plain wheel pans only while the focus is inside the\n * parent of the frame, so a page scrolled past the canvas keeps scrolling. A pinch always zooms the\n * canvas under it, never the page.\n */\nexport function usePanZoom() {\n  const frameRef = useRef<HTMLDivElement>(null);\n  const planeRef = useRef<HTMLDivElement>(null);\n  const [view] = useState(createCanvasView);\n  const [isMeasured, setIsMeasured] = useState(false);\n\n  useLayoutEffect(() => {\n    view.attach(frameRef.current, planeRef.current);\n    return () => view.attach(null, null);\n  }, [view]);\n\n  useEffect(() => {\n    const frame = frameRef.current;\n    if (!frame) {\n      return;\n    }\n    const scope = frame.parentElement ?? frame;\n    let hasMeasured = false;\n\n    /** The first fit is left to the canvas, which knows by then what it shows. */\n    function measure() {\n      setIsMeasured(true);\n      if (hasMeasured) {\n        view.settle();\n      }\n      hasMeasured = true;\n    }\n\n    function takeWheel(event: WheelEvent) {\n      const isEngaged = scope.matches(':focus-within');\n      const isZoom = isZoomWheel(event);\n      if (!isEngaged && !isZoom) {\n        return;\n      }\n      event.preventDefault();\n      view.takeWheel(event);\n    }\n\n    const observer = new ResizeObserver(measure);\n    observer.observe(frame);\n    frame.addEventListener('wheel', takeWheel, { passive: false });\n    frame.addEventListener('scroll', view.absorbScroll);\n    return () => {\n      observer.disconnect();\n      frame.removeEventListener('wheel', takeWheel);\n      frame.removeEventListener('scroll', view.absorbScroll);\n    };\n  }, [view]);\n\n  return { frameRef, planeRef, view, isMeasured };\n}\n\nfunction fullSize() {\n  return 100;\n}\n\n/** The zoom as a whole percentage. Only the text that shows it renders again when it changes. */\nexport function useZoomPercent(view: CanvasView) {\n  return useSyncExternalStore(view.subscribe, view.percent, fullSize);\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/use-pan-zoom.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/use-is-phone.ts",
      "content": "'use client';\n\nimport { useEffect, useState, type RefObject } from 'react';\n\nconst PHONE_BELOW = 640;\n\n/**\n * Whether the editor itself is as narrow as a phone, whatever the window: the pipeline then reads\n * from top to bottom. Null until the element has been measured, so nothing is laid out for the\n * wrong width first.\n */\nexport function useIsPhone(ref: RefObject<HTMLElement | null>) {\n  const [isPhone, setIsPhone] = useState<boolean | null>(null);\n\n  useEffect(() => {\n    const element = ref.current;\n    if (!element) {\n      return;\n    }\n    const observer = new ResizeObserver(([entry]) => {\n      setIsPhone(entry.contentRect.width < PHONE_BELOW);\n    });\n    observer.observe(element);\n    return () => observer.disconnect();\n  }, [ref]);\n\n  return isPhone;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/use-is-phone.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/layout.ts",
      "content": "import { nodeOf, NODES, type Link, type NodeId, type PortType } from './data';\n\n/** A wide canvas reads from left to right. A phone reads from top to bottom. */\nexport type Orientation = 'across' | 'down';\n\nexport type Point = {\n  x: number;\n  y: number;\n};\n\nexport type Box = Point & {\n  width: number;\n  height: number;\n};\n\nexport const NODE_WIDTH = 216;\n\nexport const NODE_HEIGHT = 168;\n\n/** The room between two nodes along the pipeline, where their wire runs. */\nconst GAP = 40;\n\n/** How far every other node steps aside, so a wire curves instead of running straight. */\nconst ASIDE = 48;\n\n/** The ports of a wide canvas sit on the first line of the node, beside its types. */\nconst PORT_INSET = 18;\n\n/** How far a wire runs straight out of a port before it turns. */\nconst MIN_REACH = 28;\n\nexport type NodePlace = {\n  box: Box;\n  /** Where its wire arrives. The first node takes no input. */\n  input: Point | null;\n  output: Point;\n};\n\nexport type PlacedWire<Wire extends Link> = {\n  id: string;\n  link: Wire;\n  type: PortType;\n  path: string;\n};\n\nexport type GraphLayout<Wire extends Link> = {\n  places: Record<NodeId, NodePlace>;\n  wires: PlacedWire<Wire>[];\n  bounds: Box;\n};\n\nfunction asideOf(isAside: boolean) {\n  if (isAside) {\n    return ASIDE;\n  }\n  return 0;\n}\n\nfunction boxOf(\n  column: number,\n  isAside: boolean,\n  orientation: Orientation\n): Box {\n  const aside = asideOf(isAside);\n  if (orientation === 'across') {\n    const x = column * (NODE_WIDTH + GAP);\n    return { x, y: aside, width: NODE_WIDTH, height: NODE_HEIGHT };\n  }\n  const y = column * (NODE_HEIGHT + GAP);\n  return { x: aside, y, width: NODE_WIDTH, height: NODE_HEIGHT };\n}\n\nfunction placeOf(\n  box: Box,\n  hasInput: boolean,\n  orientation: Orientation\n): NodePlace {\n  let input: Point = { x: box.x + box.width / 2, y: box.y };\n  let output: Point = { x: box.x + box.width / 2, y: box.y + box.height };\n  if (orientation === 'across') {\n    input = { x: box.x, y: box.y + PORT_INSET };\n    output = { x: box.x + box.width, y: box.y + PORT_INSET };\n  }\n  if (!hasInput) {\n    return { box, input: null, output };\n  }\n  return { box, input, output };\n}\n\nexport function wirePathOf(from: Point, to: Point, orientation: Orientation) {\n  if (orientation === 'across') {\n    const span = Math.abs(to.x - from.x);\n    const reach = Math.max(MIN_REACH, span / 2);\n    const leaveX = from.x + reach;\n    const arriveX = to.x - reach;\n    return `M ${from.x} ${from.y} C ${leaveX} ${from.y}, ${arriveX} ${to.y}, ${to.x} ${to.y}`;\n  }\n  const span = Math.abs(to.y - from.y);\n  const reach = Math.max(MIN_REACH, span / 2);\n  const leaveY = from.y + reach;\n  const arriveY = to.y - reach;\n  return `M ${from.x} ${from.y} C ${from.x} ${leaveY}, ${to.x} ${arriveY}, ${to.x} ${to.y}`;\n}\n\nfunction nodePlaceOf(id: NodeId, orientation: Orientation) {\n  const node = nodeOf(id);\n  const box = boxOf(node.column, node.isAside, orientation);\n  return placeOf(box, node.input !== null, orientation);\n}\n\nfunction placesOf(orientation: Orientation): Record<NodeId, NodePlace> {\n  return {\n    load: nodePlaceOf('load', orientation),\n    split: nodePlaceOf('split', orientation),\n    embed: nodePlaceOf('embed', orientation),\n    search: nodePlaceOf('search', orientation),\n    answer: nodePlaceOf('answer', orientation),\n  };\n}\n\nfunction boundsOf(places: NodePlace[]): Box {\n  const rights = places.map((place) => place.box.x + place.box.width);\n  const bottoms = places.map((place) => place.box.y + place.box.height);\n  return {\n    x: 0,\n    y: 0,\n    width: Math.max(...rights),\n    height: Math.max(...bottoms),\n  };\n}\n\n/** Everything the canvas draws, worked out from the nodes and their wires alone. */\nexport function layoutOf<Wire extends Link>(\n  links: Wire[],\n  orientation: Orientation\n): GraphLayout<Wire> {\n  const places = placesOf(orientation);\n  const wires: PlacedWire<Wire>[] = [];\n  for (const link of links) {\n    const from = places[link.from].output;\n    const to = places[link.to].input;\n    if (to) {\n      wires.push({\n        id: `${link.from}:${link.to}`,\n        link,\n        type: nodeOf(link.from).output,\n        path: wirePathOf(from, to, orientation),\n      });\n    }\n  }\n  return { places, wires, bounds: boundsOf(Object.values(places)) };\n}\n\nfunction contains(box: Box, point: Point, reach: number) {\n  const isInsideX =\n    point.x >= box.x - reach && point.x <= box.x + box.width + reach;\n  const isInsideY =\n    point.y >= box.y - reach && point.y <= box.y + box.height + reach;\n  return isInsideX && isInsideY;\n}\n\n/** The node under a point of the canvas, with some reach around it so a wire lands easily. */\nexport function nodeAt(\n  places: Record<NodeId, NodePlace>,\n  point: Point,\n  reach: number\n) {\n  const found = NODES.find((node) =>\n    contains(places[node.id].box, point, reach)\n  );\n  return found?.id ?? null;\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/layout.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/pipeline.ts",
      "content": "import {\n  ANSWER_TEXT,\n  ARTICLE_COUNT,\n  EMBED_MODELS,\n  nodeOf,\n  NODES,\n  PASSAGES,\n  TOTAL_TOKENS,\n  TYPE_WORD,\n  type Link,\n  type NodeId,\n  type Params,\n} from './data';\n\n/** An input takes one wire, so a node has at most one source. An output may feed several nodes. */\nexport function sourceOf(links: Link[], id: NodeId) {\n  const link = links.find((candidate) => candidate.to === id);\n  return link?.from ?? null;\n}\n\n/** A node and every node its output reaches, in no particular order. */\nexport function downstreamOf(links: Link[], id: NodeId) {\n  const reached: NodeId[] = [];\n  const pending = [id];\n  let current = pending.pop();\n  while (current !== undefined) {\n    if (!reached.includes(current)) {\n      reached.push(current);\n      const visited = current;\n      const fed = links.filter((link) => link.from === visited);\n      fed.forEach((link) => pending.push(link.to));\n    }\n    current = pending.pop();\n  }\n  return reached;\n}\n\n/**\n * Why the output of one node cannot feed another, said in one sentence, or null when it can. The\n * types of the two ports have to match, and a node never ends up fed by its own output.\n */\nexport function refusalOf(links: Link[], from: NodeId, to: NodeId) {\n  const source = nodeOf(from);\n  const target = nodeOf(to);\n  if (from === to) {\n    return `${source.title} cannot feed itself`;\n  }\n  if (target.input === null) {\n    return `${target.title} takes no input`;\n  }\n  if (source.output !== target.input) {\n    const wanted = TYPE_WORD[target.input];\n    const given = TYPE_WORD[source.output];\n    return `${target.title} takes ${wanted}. ${source.title} gives ${given}`;\n  }\n  if (downstreamOf(links, to).includes(from)) {\n    return `That would feed ${source.title} its own output`;\n  }\n  return null;\n}\n\nexport function missingInputOf(links: Link[], id: NodeId) {\n  const node = nodeOf(id);\n  const isFed = sourceOf(links, id) !== null;\n  if (node.input === null || isFed) {\n    return null;\n  }\n  return `${TYPE_WORD[node.input]} is not connected`;\n}\n\n/** Every node after the one that feeds it: the order a run follows. */\nexport function orderOf(links: Link[]) {\n  const placed: NodeId[] = [];\n  let waiting = NODES.map((node) => node.id);\n  while (waiting.length > 0) {\n    const ready = waiting.filter((id) => {\n      const source = sourceOf(links, id);\n      return source === null || placed.includes(source);\n    });\n    if (ready.length === 0) {\n      return [...placed, ...waiting];\n    }\n    placed.push(...ready);\n    waiting = waiting.filter((id) => !ready.includes(id));\n  }\n  return placed;\n}\n\nfunction settingOf(id: NodeId, params: Params) {\n  if (id === 'split') {\n    return String(params.chunkSize);\n  }\n  if (id === 'embed') {\n    return params.model;\n  }\n  if (id === 'search') {\n    return String(params.topK);\n  }\n  if (id === 'answer') {\n    return params.prompt;\n  }\n  return '';\n}\n\n/**\n * What a node would compute now: its own setting and everything upstream of it. A node whose\n * signature has not changed since it last ran is served from its cache.\n */\nexport function signatureOf(links: Link[], params: Params, id: NodeId): string {\n  const source = sourceOf(links, id);\n  let upstream = '-';\n  if (source !== null) {\n    upstream = signatureOf(links, params, source);\n  }\n  return `${id}:${settingOf(id, params)}(${upstream})`;\n}\n\n/** How many items a node hands on: articles, chunks, vectors, passages, then one answer. */\nfunction countOf(links: Link[], params: Params, id: NodeId): number {\n  if (id === 'load') {\n    return ARTICLE_COUNT;\n  }\n  if (id === 'split') {\n    return Math.round(TOTAL_TOKENS / params.chunkSize);\n  }\n  if (id === 'answer') {\n    return 1;\n  }\n  const source = sourceOf(links, id);\n  let incoming = 0;\n  if (source !== null) {\n    incoming = countOf(links, params, source);\n  }\n  if (id === 'search') {\n    return Math.min(params.topK, incoming);\n  }\n  return incoming;\n}\n\nfunction counted(count: number, word: string) {\n  if (count === 1) {\n    return `1 ${word}`;\n  }\n  return `${count} ${word}s`;\n}\n\nexport type Result = {\n  headline: string;\n  lines: string[];\n};\n\nconst SHOWN_PASSAGES = 2;\n\nfunction dimensionsOf(params: Params) {\n  const model = EMBED_MODELS.find(\n    (candidate) => candidate.value === params.model\n  );\n  return model?.dimensions ?? 0;\n}\n\n/** The preview a node shows once it has run. The figures follow the settings and are illustrative. */\nexport function resultOf(links: Link[], params: Params, id: NodeId): Result {\n  const count = countOf(links, params, id);\n  if (id === 'load') {\n    return {\n      headline: counted(count, 'article'),\n      lines: ['From the help center'],\n    };\n  }\n  if (id === 'split') {\n    return {\n      headline: counted(count, 'chunk'),\n      lines: [`About ${params.chunkSize} tokens each`],\n    };\n  }\n  if (id === 'embed') {\n    return {\n      headline: counted(count, 'vector'),\n      lines: [`${dimensionsOf(params)} dimensions`],\n    };\n  }\n  if (id === 'search') {\n    const shown = PASSAGES.slice(0, Math.min(count, SHOWN_PASSAGES));\n    return {\n      headline: counted(count, 'passage'),\n      lines: shown.map((passage) => `${passage.title} · ${passage.score}`),\n    };\n  }\n  const words = ANSWER_TEXT.split(' ');\n  return { headline: counted(words.length, 'word'), lines: [ANSWER_TEXT] };\n}\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/pipeline.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/session.ts",
      "content": "import type { SessionStep } from '@/registry/ndeko/hooks/use-session';\n\nimport {\n  EMBED_FAILURE,\n  LINKS,\n  nodeOf,\n  NODES,\n  PARAMS,\n  type Link,\n  type NodeId,\n  type Params,\n} from './data';\nimport {\n  downstreamOf,\n  missingInputOf,\n  orderOf,\n  refusalOf,\n  resultOf,\n  signatureOf,\n  sourceOf,\n  type Result,\n} from './pipeline';\n\n/**\n * How a wire came to be: there from the start, let go by a hand where it now sits, or made from a\n * menu. Only the last one draws itself, since the two others are already where they belong.\n */\nexport type Arrival = 'placed' | 'dropped' | 'drawn';\n\nexport type Wire = Link & {\n  arrival: Arrival;\n};\n\nexport type RunStatus =\n  'idle' | 'running' | 'done' | 'cached' | 'failed' | 'skipped';\n\nexport type NodeRun = {\n  status: RunStatus;\n  /** What the node last computed. It stays, dimmed, once a setting upstream has changed. */\n  result: Result | null;\n  /** The signature of that result: the node is served from cache while it still matches. */\n  signature: string | null;\n  /** Why it failed or was skipped. */\n  message: string | null;\n};\n\n/** A wire held out of an output: by a pointer, or by the demonstration. `to` is the node it is over. */\nexport type Wiring = {\n  from: NodeId;\n  to: NodeId | null;\n};\n\nexport type Refused = {\n  id: number;\n  from: NodeId;\n  to: NodeId;\n  reason: string;\n};\n\n/** The node a run has reached. The token tells one run from the next, so a late timer changes nothing. */\nexport type Run = {\n  order: NodeId[];\n  at: number;\n  token: number;\n};\n\nexport type GraphState = {\n  wires: Wire[];\n  params: Params;\n  runs: Record<NodeId, NodeRun>;\n  run: Run | null;\n  runCount: number;\n  /** Embed fails the first time it runs, then works. */\n  hasEmbedFailed: boolean;\n  wiring: Wiring | null;\n  refused: Refused | null;\n  refusalCount: number;\n  /** The last change, said to screen readers. */\n  notice: string;\n};\n\nexport type GraphAction =\n  | { type: 'wireStarted'; from: NodeId }\n  | { type: 'wireAimed'; to: NodeId | null }\n  | { type: 'wireDropped' }\n  | { type: 'wireCancelled' }\n  | { type: 'connected'; from: NodeId; to: NodeId }\n  | { type: 'disconnected'; to: NodeId }\n  | { type: 'refusalCleared'; id: number }\n  | { type: 'paramsChanged'; params: Partial<Params> }\n  | { type: 'ran' }\n  | { type: 'phaseEnded'; token: number }\n  | { type: 'waited' };\n\ntype Beat = SessionStep<GraphState, GraphAction>;\n\n/** A node served from cache shows it for this long before the run moves on. */\nexport const CACHED_MS = 320;\n\nconst NEVER_RUN: NodeRun = {\n  status: 'idle',\n  result: null,\n  signature: null,\n  message: null,\n};\n\nfunction placed(link: Link): Wire {\n  return { ...link, arrival: 'placed' };\n}\n\n/** The documents were loaded before the page opened, so the first run finds them in cache. */\nconst LOADED: NodeRun = {\n  status: 'idle',\n  result: resultOf(LINKS, PARAMS, 'load'),\n  signature: signatureOf(LINKS, PARAMS, 'load'),\n  message: null,\n};\n\nexport const INITIAL: GraphState = {\n  wires: LINKS.map(placed),\n  params: PARAMS,\n  runs: {\n    load: LOADED,\n    split: NEVER_RUN,\n    embed: NEVER_RUN,\n    search: NEVER_RUN,\n    answer: NEVER_RUN,\n  },\n  run: null,\n  runCount: 0,\n  hasEmbedFailed: false,\n  wiring: null,\n  refused: null,\n  refusalCount: 0,\n  notice: '',\n};\n\n/** The node of each setting: changing it makes that node, and what it feeds, out of date. */\nconst NODE_OF_PARAM: Record<keyof Params, NodeId> = {\n  chunkSize: 'split',\n  model: 'embed',\n  topK: 'search',\n  prompt: 'answer',\n};\n\nconst PARAM_KEYS: (keyof Params)[] = ['chunkSize', 'model', 'topK', 'prompt'];\n\nexport function isRunning(state: GraphState) {\n  return state.run !== null;\n}\n\n/** The node the run is on, with how long it stays there. */\nexport function phaseOf(state: GraphState) {\n  const run = state.run;\n  if (!run) {\n    return null;\n  }\n  const id = run.order[run.at];\n  const isCached = state.runs[id].status === 'cached';\n  if (isCached) {\n    return { id, token: run.token, ms: CACHED_MS };\n  }\n  return { id, token: run.token, ms: nodeOf(id).runMs };\n}\n\nfunction withRun(\n  state: GraphState,\n  id: NodeId,\n  patch: Partial<NodeRun>\n): GraphState {\n  const next = { ...state.runs[id], ...patch };\n  return { ...state, runs: { ...state.runs, [id]: next } };\n}\n\n/** A change makes a node and everything it feeds wait for the next run. Their last results stay. */\nfunction staleFrom(state: GraphState, id: NodeId): GraphState {\n  let next = state;\n  for (const reached of downstreamOf(state.wires, id)) {\n    next = withRun(next, reached, { status: 'idle', message: null });\n  }\n  return next;\n}\n\nfunction refusedWith(\n  state: GraphState,\n  from: NodeId,\n  to: NodeId,\n  reason: string\n): GraphState {\n  const id = state.refusalCount + 1;\n  return {\n    ...state,\n    refused: { id, from, to, reason },\n    refusalCount: id,\n    notice: reason,\n  };\n}\n\nfunction linked(\n  state: GraphState,\n  from: NodeId,\n  to: NodeId,\n  arrival: Arrival\n): GraphState {\n  if (isRunning(state)) {\n    return state;\n  }\n  const reason = refusalOf(state.wires, from, to);\n  if (reason !== null) {\n    return refusedWith(state, from, to, reason);\n  }\n  const isSame = sourceOf(state.wires, to) === from;\n  if (isSame) {\n    return state;\n  }\n  const others = state.wires.filter((wire) => wire.to !== to);\n  const rewired = { ...state, wires: [...others, { from, to, arrival }] };\n  const next = staleFrom(rewired, to);\n  const source = nodeOf(from).title;\n  const target = nodeOf(to).title;\n  return { ...next, refused: null, notice: `${source} now feeds ${target}` };\n}\n\nfunction wireStarted(state: GraphState, from: NodeId): GraphState {\n  if (isRunning(state)) {\n    return state;\n  }\n  return { ...state, wiring: { from, to: null }, refused: null };\n}\n\nfunction wireAimed(state: GraphState, to: NodeId | null): GraphState {\n  const wiring = state.wiring;\n  if (!wiring || wiring.to === to) {\n    return state;\n  }\n  return { ...state, wiring: { ...wiring, to } };\n}\n\nfunction wireDropped(state: GraphState): GraphState {\n  const wiring = state.wiring;\n  if (!wiring) {\n    return state;\n  }\n  const released = { ...state, wiring: null };\n  if (wiring.to === null) {\n    return released;\n  }\n  return linked(released, wiring.from, wiring.to, 'dropped');\n}\n\nfunction disconnected(state: GraphState, to: NodeId): GraphState {\n  const wires = state.wires.filter((wire) => wire.to !== to);\n  const hasChanged = wires.length !== state.wires.length;\n  if (isRunning(state) || !hasChanged) {\n    return state;\n  }\n  const next = staleFrom({ ...state, wires }, to);\n  return { ...next, notice: `Nothing feeds ${nodeOf(to).title} now` };\n}\n\nfunction paramsChanged(\n  state: GraphState,\n  changes: Partial<Params>\n): GraphState {\n  if (isRunning(state)) {\n    return state;\n  }\n  const params = { ...state.params, ...changes };\n  let next: GraphState = { ...state, params, notice: '' };\n  for (const key of PARAM_KEYS) {\n    const hasChanged = params[key] !== state.params[key];\n    if (hasChanged) {\n      next = staleFrom(next, NODE_OF_PARAM[key]);\n    }\n  }\n  return next;\n}\n\n/** A node cannot run without its input, nor after a node that failed or was itself skipped. */\nfunction blockedReasonOf(state: GraphState, id: NodeId) {\n  const missing = missingInputOf(state.wires, id);\n  if (missing !== null) {\n    return missing;\n  }\n  const source = sourceOf(state.wires, id);\n  if (source === null) {\n    return null;\n  }\n  const status = state.runs[source].status;\n  const isHeldUp = status === 'failed' || status === 'skipped';\n  if (isHeldUp) {\n    return `Waiting on ${nodeOf(source).title}`;\n  }\n  return null;\n}\n\nfunction startStatusOf(isCached: boolean): RunStatus {\n  if (isCached) {\n    return 'cached';\n  }\n  return 'running';\n}\n\nfunction summaryOf(state: GraphState) {\n  const failed = NODES.find((node) => state.runs[node.id].status === 'failed');\n  if (failed) {\n    const message = state.runs[failed.id].message;\n    return `${failed.title} failed: ${message}. Retry is available`;\n  }\n  return 'The run is finished';\n}\n\n/**\n * Moves the run to the next node that takes time: one that runs, or one served from cache. The\n * nodes that cannot run are marked skipped on the way. Past the last node the run is over.\n */\nfunction advanced(state: GraphState, run: Run, from: number): GraphState {\n  let next = state;\n  for (let at = from; at < run.order.length; at += 1) {\n    const id = run.order[at];\n    const reason = blockedReasonOf(next, id);\n    if (reason === null) {\n      const signature = signatureOf(next.wires, next.params, id);\n      const last = next.runs[id];\n      const isCached = last.result !== null && last.signature === signature;\n      const started = withRun(next, id, { status: startStatusOf(isCached) });\n      return { ...started, run: { ...run, at } };\n    }\n    next = withRun(next, id, { status: 'skipped', message: reason });\n  }\n  return { ...next, run: null, notice: summaryOf(next) };\n}\n\nfunction ran(state: GraphState): GraphState {\n  if (isRunning(state)) {\n    return state;\n  }\n  let next: GraphState = { ...state, wiring: null, refused: null };\n  for (const node of NODES) {\n    next = withRun(next, node.id, { status: 'idle', message: null });\n  }\n  const token = state.runCount + 1;\n  const run = { order: orderOf(next.wires), at: 0, token };\n  return advanced({ ...next, runCount: token, notice: 'Run started' }, run, 0);\n}\n\nfunction finished(state: GraphState, id: NodeId): GraphState {\n  const failsNow = id === 'embed' && !state.hasEmbedFailed;\n  if (failsNow) {\n    const failed = withRun(state, id, {\n      status: 'failed',\n      message: EMBED_FAILURE,\n    });\n    return { ...failed, hasEmbedFailed: true };\n  }\n  return withRun(state, id, {\n    status: 'done',\n    result: resultOf(state.wires, state.params, id),\n    signature: signatureOf(state.wires, state.params, id),\n    message: null,\n  });\n}\n\nfunction phaseEnded(state: GraphState, token: number): GraphState {\n  const run = state.run;\n  if (!run || run.token !== token) {\n    return state;\n  }\n  const id = run.order[run.at];\n  let next = state;\n  if (state.runs[id].status === 'running') {\n    next = finished(state, id);\n  }\n  return advanced(next, run, run.at + 1);\n}\n\nfunction refusalCleared(state: GraphState, id: number): GraphState {\n  if (state.refused?.id !== id) {\n    return state;\n  }\n  return { ...state, refused: null };\n}\n\nexport function reducer(state: GraphState, action: GraphAction): GraphState {\n  switch (action.type) {\n    case 'wireStarted':\n      return wireStarted(state, action.from);\n    case 'wireAimed':\n      return wireAimed(state, action.to);\n    case 'wireDropped':\n      return wireDropped(state);\n    case 'wireCancelled':\n      return { ...state, wiring: null };\n    case 'connected':\n      return linked(state, action.from, action.to, 'drawn');\n    case 'disconnected':\n      return disconnected(state, action.to);\n    case 'refusalCleared':\n      return refusalCleared(state, action.id);\n    case 'paramsChanged':\n      return paramsChanged(state, action.params);\n    case 'ran':\n      return ran(state);\n    case 'phaseEnded':\n      return phaseEnded(state, action.token);\n    case 'waited':\n      return state;\n  }\n}\n\nexport function hasFailure(state: GraphState) {\n  return NODES.some((node) => state.runs[node.id].status === 'failed');\n}\n\nfunction hasNoFailure(state: GraphState) {\n  return !hasFailure(state);\n}\n\n/** Runs to its end at once: what the timers do one node after the other. */\nfunction settled(state: GraphState) {\n  let next = state;\n  while (next.run) {\n    next = phaseEnded(next, next.run.token);\n  }\n  return next;\n}\n\nfunction holdOutSteps(after: number, from: NodeId, to: NodeId): Beat[] {\n  return [\n    {\n      after,\n      by: 'demo',\n      press: `out-${from}`,\n      action: { type: 'wireStarted', from },\n    },\n    { after: 520, by: 'demo', action: { type: 'wireAimed', to } },\n    { after: 850, by: 'demo', action: { type: 'wireDropped' } },\n  ];\n}\n\n/** Chunks into a port that takes Vectors: the wire is refused and says why. */\nconst REFUSED = holdOutSteps(1500, 'split', 'search');\n\nconst CONNECTED = holdOutSteps(2700, 'embed', 'search');\n\nconst RUN: Beat = {\n  after: 1300,\n  by: 'demo',\n  press: 'run',\n  action: { type: 'ran' },\n};\n\n/**\n * A step of the system that only waits. The session holds it while a run is going, so what follows\n * comes once the run is over, however long it took.\n */\nfunction runOver(after: number): Beat {\n  return { after, action: { type: 'waited' } };\n}\n\n/** A failure that waits on a person is retried by the demonstration after this long. */\nconst DECIDE_AFTER_MS = 2500;\n\nconst RETRY: Beat = {\n  after: DECIDE_AFTER_MS,\n  by: 'person',\n  press: 'retry',\n  action: { type: 'ran' },\n  isAnswered: hasNoFailure,\n};\n\nexport const SCRIPT: Beat[] = [\n  ...REFUSED,\n  ...CONNECTED,\n  RUN,\n  runOver(200),\n  RETRY,\n  runOver(600),\n];\n\n/**\n * Under reduced motion the editor rests on the second run: every wire in place, two nodes served\n * from cache, three that ran, each with its preview.\n */\nfunction restingOf() {\n  let state = INITIAL;\n  for (const beat of CONNECTED) {\n    state = reducer(state, beat.action);\n  }\n  const firstRun = settled(ran(state));\n  const secondRun = settled(ran(firstRun));\n  return { ...secondRun, wires: secondRun.wires.map(placed), notice: '' };\n}\n\nexport const RESTING = restingOf();\n\nexport const LOOP_AFTER_MS = 3800;\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/session.ts"
    },
    {
      "path": "registry/ndeko/blocks/workflows/workflows-02/data.ts",
      "content": "import type { SeriesSlot } from '@/registry/ndeko/lib/agent-run';\n\nexport const PIPELINE_NAME = 'Help center answers';\n\n/** What travels along a wire. A wire only joins two ports of the same type. */\nexport type PortType = 'documents' | 'chunks' | 'vectors' | 'text';\n\nexport const PORT_TYPES: PortType[] = [\n  'documents',\n  'chunks',\n  'vectors',\n  'text',\n];\n\nexport const TYPE_WORD: Record<PortType, string> = {\n  documents: 'Documents',\n  chunks: 'Chunks',\n  vectors: 'Vectors',\n  text: 'Text',\n};\n\n/** Each type keeps one series colour, on its ports, its wires and the legend. */\nexport const TYPE_SERIES: Record<PortType, SeriesSlot> = {\n  documents: 1,\n  chunks: 2,\n  vectors: 3,\n  text: 4,\n};\n\nexport type NodeId = 'load' | 'split' | 'embed' | 'search' | 'answer';\n\nexport type NodeSpec = {\n  id: NodeId;\n  title: string;\n  /** What the node takes. The first node of a pipeline takes nothing. */\n  input: PortType | null;\n  output: PortType;\n  /** Its place along the pipeline, and whether it sits a step aside so the wires curve. */\n  column: number;\n  isAside: boolean;\n  /** Said in the node while it runs. */\n  workingLine: string;\n  /** How long it runs in this demo, in milliseconds. */\n  runMs: number;\n};\n\nexport const NODES: NodeSpec[] = [\n  {\n    id: 'load',\n    title: 'Load documents',\n    input: null,\n    output: 'documents',\n    column: 0,\n    isAside: false,\n    workingLine: 'Reading the help center',\n    runMs: 800,\n  },\n  {\n    id: 'split',\n    title: 'Split into chunks',\n    input: 'documents',\n    output: 'chunks',\n    column: 1,\n    isAside: true,\n    workingLine: 'Cutting at headings',\n    runMs: 1100,\n  },\n  {\n    id: 'embed',\n    title: 'Embed',\n    input: 'chunks',\n    output: 'vectors',\n    column: 2,\n    isAside: false,\n    workingLine: 'Embedding the chunks',\n    runMs: 1300,\n  },\n  {\n    id: 'search',\n    title: 'Search',\n    input: 'vectors',\n    output: 'chunks',\n    column: 3,\n    isAside: true,\n    workingLine: 'Ranking the closest chunks',\n    runMs: 1000,\n  },\n  {\n    id: 'answer',\n    title: 'Answer',\n    input: 'chunks',\n    output: 'text',\n    column: 4,\n    isAside: false,\n    workingLine: 'Writing the answer',\n    runMs: 1400,\n  },\n];\n\nexport function nodeOf(id: NodeId) {\n  const node = NODES.find((candidate) => candidate.id === id);\n  return node ?? NODES[0];\n}\n\nexport function nodeIdOf(value: string | undefined | null) {\n  const node = NODES.find((candidate) => candidate.id === value);\n  return node?.id ?? null;\n}\n\nexport type Link = {\n  from: NodeId;\n  to: NodeId;\n};\n\n/** The pipeline as it opens: nothing feeds Search yet. */\nexport const LINKS: Link[] = [\n  { from: 'load', to: 'split' },\n  { from: 'split', to: 'embed' },\n  { from: 'search', to: 'answer' },\n];\n\nexport type EmbedModelId = 'small' | 'large';\n\nexport type EmbedModel = {\n  value: EmbedModelId;\n  label: string;\n  dimensions: number;\n};\n\n/** Invented models of an invented lab. */\nexport const EMBED_MODELS: EmbedModel[] = [\n  { value: 'small', label: 'Lumen Embed Small', dimensions: 384 },\n  { value: 'large', label: 'Lumen Embed Large', dimensions: 1024 },\n];\n\nexport type Params = {\n  chunkSize: number;\n  model: EmbedModelId;\n  topK: number;\n  prompt: string;\n};\n\nexport const CHUNK_SIZE = { min: 200, max: 1200, step: 100 };\n\nexport const TOP_K = { min: 1, max: 10 };\n\nexport const PARAMS: Params = {\n  chunkSize: 400,\n  model: 'small',\n  topK: 5,\n  prompt: 'How do I export my invoices?',\n};\n\nexport const ARTICLE_COUNT = 42;\n\n/** The tokens of the invented help center, which the chunk size divides. */\nexport const TOTAL_TOKENS = 109_200;\n\nexport type Passage = {\n  title: string;\n  score: string;\n};\n\n/** What Search finds for the sample question, best first. Illustrative. */\nexport const PASSAGES: Passage[] = [\n  { title: 'Export invoices as CSV', score: '0.91' },\n  { title: 'Download a receipt', score: '0.84' },\n  { title: 'Change the billing email', score: '0.77' },\n];\n\nexport const ANSWER_TEXT =\n  'Open Billing, choose Invoices, then Export. The file is sent to your email.';\n\n/** The one failure of the demo: Embed gives up the first time it runs. */\nexport const EMBED_FAILURE = 'The embedding service timed out after 30s';\n",
      "type": "registry:component",
      "target": "components/blocks/workflows-02/data.ts"
    }
  ],
  "categories": [
    "blocks",
    "workflows"
  ],
  "type": "registry:block"
}