# Tool row (Notchset): prompt.md (v1.2.0)

- id: `tool-row` · version 1.2.0 · component · free
- category: AI
- build: one set of files for every shadcn style
- install: `npx shadcn@latest add https://notchset.dev/r/tool-row.json`
- npm dependencies: lucide-react@^1
- registry dependencies: utils, https://notchset.dev/r/notchset-foundation.json, @notchset/button, @notchset/live-label, @notchset/status-glyph-run, @notchset/stream-adapters
- docs: https://notchset.dev/components/tool-row
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

One tool call, read from the stream's part: present tense while it runs and its clock counts; past tense and outcome when done, the tick drawn; failed says what failed with Retry and Skip; denied stays ink. When it needs a yes, the gate opens in the row. A press opens its input and output: text, list, table or JSON..

## Build it
- Stack: React 18.3 or 19, TypeScript, Tailwind CSS v4 utility classes on the foundation's roles, a components.json (imports use its aliases).
- Packages: `lucide-react@^1` beyond `react` and `react-dom`.
- Files: `components/ui/notchset/tool-row.tsx`, `components/ui/notchset/disclosure-parts.tsx`; shared code: `lib/notchset/controllable.ts`, `lib/notchset/feedback.ts`, `lib/notchset/icons.ts`, `lib/notchset/words.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`, `button`, `live-label`, `status-glyph-run`, `stream-adapters`.
- Builds: one set of files, the same for every shadcn style.
- Exports to keep: `TOOL_ROW_LABELS`, `TOOL_ROW_LINE`, `ToolRow`, `DisclosureScope`, `disclosureScope`, `disclosureTrigger`, `partId`, `useDisclosure`, and every exported type.
- CSS: the install adds the notchset foundation (its roles, keyframes and motion switch, reading your shadcn tokens for colour) to your global stylesheet once. Nothing to import by hand.
- Re-running `add` (or `--overwrite`) re-applies those rules: put overrides in your own CSS, never in the installed rules.
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- This item reads `--ns-bad-ink`, `--ns-ease`, `--ns-ease-panel`, `--ns-font-mono`, `--ns-ink`, `--ns-ink-2`, `--ns-ink-3`, `--ns-lead-body`, `--ns-lead-meta`, `--ns-line-soft`, `--ns-panel`, `--ns-radius`, `--ns-radius-lg`, `--ns-radius-sm`, `--ns-signal`, `--ns-text-body`, `--ns-text-small`, `--ns-time-color`, `--ns-time-menu`, `--ns-time-panel`, `--ns-weight-medium`, `--ns-well`.
- Retune it (on any ancestor) with the foundation's roles and hooks: `--ns-agent-b`, `--ns-agent-c`, `--ns-agent-d`, `--ns-agent-drift`, `--ns-agent-fill`, `--ns-agent-h1`, `--ns-agent-h2`, `--ns-agent-h3`, `--ns-agent-shift`, `--ns-avatar-card`, `--ns-avatar-lg`, `--ns-avatar-md`, `--ns-avatar-sm`, `--ns-avatar-xs`, `--ns-bad`, `--ns-bad-ink`, `--ns-band`, `--ns-band-edge`, `--ns-band-grade`, `--ns-band-optimal`, `--ns-banner-beat`, `--ns-banner-radius`, `--ns-beat`, `--ns-beat-ease`, `--ns-bezel`, `--ns-bloom-close`, `--ns-bloom-open`, `--ns-bloom-rise`, `--ns-btn-bad`, `--ns-btn-bad-hover`, `--ns-btn-bad-line`, `--ns-btn-bezel`, `--ns-btn-chosen`, `--ns-btn-gone`, `--ns-btn-morph`, `--ns-btn-ok`, `--ns-btn-press`, `--ns-btn-release`, `--ns-btn-result`, `--ns-btn-roll`, `--ns-btn-stagger`, `--ns-btn-stagger-step`, `--ns-btn-tick`, `--ns-btn-tonal`, `--ns-btn-tonal-edge`, `--ns-btn-tonal-hover`, `--ns-bulk-clear`, `--ns-button`, `--ns-button-field-inset`, `--ns-button-lg`, `--ns-button-sm`, `--ns-canvas`, `--ns-card-tilt`, `--ns-cat-1`, `--ns-cat-2`, `--ns-cat-3`, `--ns-cat-4`, `--ns-cat-5`, `--ns-cat-6`, `--ns-check`, `--ns-check-round`, `--ns-cheer-1`, `--ns-cheer-2`, `--ns-cheer-3`, `--ns-cheer-edge`, `--ns-cheer-fold`, `--ns-cheer-glow`, `--ns-cheer-lift`, `--ns-chip`, `--ns-chip-pick`, `--ns-control`, `--ns-control-lg`, `--ns-control-pad`, `--ns-control-sm`, `--ns-corner`, `--ns-danger`, `--ns-deep`, `--ns-deep-ink`, `--ns-deep-ink-2`, `--ns-deep-line`, `--ns-depth-card`, `--ns-depth-lift`, `--ns-depth-surface`, `--ns-dialog`, `--ns-dialog-grow`, `--ns-dialog-lg`, `--ns-dialog-max`, `--ns-dialog-shrink`, `--ns-dialog-sm`, `--ns-dialog-top`, `--ns-dock-bottom`, `--ns-drop`, `--ns-ease`, `--ns-ease-arrive`, `--ns-ease-breathe`, `--ns-ease-drum`, `--ns-ease-exit`, `--ns-ease-fling`, `--ns-ease-glide`, `--ns-ease-grow`, `--ns-ease-move`, `--ns-ease-panel`, `--ns-ease-pop`, `--ns-ease-press`, `--ns-ease-spring`, `--ns-ebg-arm`, `--ns-ebg-lit`, `--ns-emoji`, `--ns-emoji-md`, `--ns-emoji-sm`, `--ns-field`, `--ns-field-edge`, `--ns-field-h`, `--ns-fill`, `--ns-fill-time`, `--ns-flood-arc`, `--ns-flood-aurora`, `--ns-flood-behind-1`, `--ns-flood-behind-2`, `--ns-flood-bloom`, `--ns-flood-deep`, `--ns-flood-dial-bloom`, `--ns-flood-glass`, `--ns-flood-grain`, `--ns-flood-image`, `--ns-flood-ink`, `--ns-flood-ink-low`, `--ns-flood-light`, `--ns-flood-mid`, `--ns-flood-pale`, `--ns-flood-pane`, `--ns-flood-pane-edge`, `--ns-flood-pill-ink`, `--ns-flood-ribbon`, `--ns-flood-ribbon-core`, `--ns-flood-shadow`, `--ns-flood-sheen`, `--ns-flood-wash`, `--ns-font-body`, `--ns-font-display`, `--ns-font-mono`, `--ns-font-script`, `--ns-glass`, `--ns-glass-blur`, `--ns-glass-shadow`, `--ns-glow`, `--ns-glyph-pad`, `--ns-grain`, `--ns-gutter`, `--ns-header`, `--ns-help-max`, `--ns-hit`, `--ns-hover`, `--ns-icon`, `--ns-icon-lg`, `--ns-icon-sm`, `--ns-icon-stroke`, `--ns-info`, `--ns-info-ink`, `--ns-ink`, `--ns-ink-2`, `--ns-ink-3`, `--ns-ink-4`, `--ns-layer-bar`, `--ns-layer-modal`, `--ns-layer-panel`, `--ns-layer-popup`, `--ns-layer-sticky`, `--ns-layer-tip`, `--ns-layer-toast`, `--ns-layer-zoom`, `--ns-lead-body`, `--ns-lead-figure`, `--ns-lead-large`, `--ns-lead-meta`, `--ns-lead-small`, `--ns-lead-sub`, `--ns-lead-title`, `--ns-leading`, `--ns-leading-prose`, `--ns-leading-title`, `--ns-lift`, `--ns-light-1`, `--ns-light-2`, `--ns-light-3`, `--ns-light-spread`, `--ns-light-strength`, `--ns-line`, `--ns-line-soft`, `--ns-lit-edge`, `--ns-map-grass`, `--ns-map-water`, `--ns-mark-edge`, `--ns-mark-lifted`, `--ns-mark-rest`, `--ns-mark-swap`, `--ns-marker`, `--ns-marker-ink`, `--ns-mc-place`, `--ns-mc-roll`, `--ns-measure`, `--ns-menu-dy`, `--ns-menu-lit`, `--ns-menu-pad`, `--ns-menu-row`, `--ns-menu-rule`, `--ns-mesh`, `--ns-mesh-frost`, `--ns-nest-inset`, `--ns-nest-outer`, `--ns-nest-r`, `--ns-notch-ease`, `--ns-ok`, `--ns-ok-ink`, `--ns-on-fill`, `--ns-orb-body`, `--ns-orb-cool`, `--ns-orb-core`, `--ns-orb-dawn`, `--ns-orb-deep`, `--ns-orb-edge`, `--ns-orb-grain`, `--ns-orb-ground`, `--ns-orb-halo`, `--ns-orb-inner`, `--ns-orb-key`, `--ns-orb-lift`, `--ns-orb-limb`, `--ns-orb-limb-from`, `--ns-orb-rim`, `--ns-orb-skin-hi`, `--ns-orb-skin-lo`, `--ns-orb-skin-mid`, `--ns-orb-warm`, `--ns-palette-min`, `--ns-panel`, `--ns-panel-room`, `--ns-panel-w`, `--ns-panel-w-lg`, `--ns-pick-slot`, `--ns-pill-prop`, `--ns-play-fill`, `--ns-play-fill-color`, `--ns-play-lift`, `--ns-play-lift-y`, `--ns-play-open`, `--ns-play-open-content`, `--ns-play-press`, `--ns-play-press-box`, `--ns-play-reduced`, `--ns-play-ring`, `--ns-play-roll`, `--ns-play-shake`, `--ns-play-spring`, `--ns-play-swap`, `--ns-play-swap-blur`, `--ns-press-min`, `--ns-press-scale`, `--ns-press-x`, `--ns-press-y`, `--ns-primary-hover`, `--ns-primary-press`, `--ns-prism-edge`, `--ns-prism-glint`, `--ns-prism-sheen`, `--ns-prism-tint`, `--ns-pulse`, `--ns-radius`, `--ns-radius-2xl`, `--ns-radius-button`, `--ns-radius-button-lg`, `--ns-radius-button-sm`, `--ns-radius-card`, `--ns-radius-check`, `--ns-radius-control`, `--ns-radius-control-sm`, `--ns-radius-float`, `--ns-radius-full`, `--ns-radius-lg`, `--ns-radius-mark`, `--ns-radius-menu-row`, `--ns-radius-modal`, `--ns-radius-pill`, `--ns-radius-sm`, `--ns-radius-xl`, `--ns-radius-xs`, `--ns-raised`, `--ns-ramp-1`, `--ns-ramp-2`, `--ns-ramp-3`, `--ns-ramp-4`, `--ns-ramp-5`, `--ns-ramp-shine`, `--ns-range`, `--ns-rest-1`, `--ns-rest-2`, `--ns-rest-3`, `--ns-rise`, `--ns-row`, `--ns-row-compact`, `--ns-row-hue`, `--ns-scrim`, `--ns-search-h`, `--ns-segment`, `--ns-segment-inset`, `--ns-segment-lift`, `--ns-segment-sm`, `--ns-selected`, `--ns-series`, `--ns-series-core`, `--ns-series-glint`, `--ns-series-tint`, `--ns-shadow-dialog`, `--ns-shadow-float`, `--ns-shadow-lift`, `--ns-shadow-panel`, `--ns-sheet`, `--ns-sheet-back`, `--ns-sheet-bottom`, `--ns-sheet-drop`, `--ns-sheet-rise`, `--ns-shift`, `--ns-side`, `--ns-signal`, `--ns-signal-ink`, `--ns-signal-wash`, `--ns-sk-figure`, `--ns-sk-land`, `--ns-sk-p`, `--ns-sk-p0`, `--ns-sk-p1`, `--ns-sk-p2`, `--ns-sk-p3`, `--ns-sk-p4`, `--ns-sk-p5`, `--ns-sk-p6`, `--ns-sk-p7`, `--ns-sk-read`, `--ns-sk-sweep`, `--ns-skeleton`, `--ns-skeleton-bone`, `--ns-skeleton-bone-light`, `--ns-skeleton-light`, `--ns-slab`, `--ns-slab-edge`, `--ns-slab-ink`, `--ns-sleep-awake`, `--ns-sleep-deep`, `--ns-sleep-light`, `--ns-sleep-rem`, `--ns-space-1`, `--ns-space-2`, `--ns-space-3`, `--ns-space-4`, `--ns-space-5`, `--ns-space-6`, `--ns-space-8`, `--ns-space-section`, `--ns-stack-fan`, `--ns-stack-fan-gap`, `--ns-stack-fan-lag`, `--ns-stack-on`, `--ns-stagger-item`, `--ns-stagger-mark`, `--ns-stagger-max`, `--ns-standing-critical`, `--ns-standing-in`, `--ns-standing-out`, `--ns-state-doing`, `--ns-state-done`, `--ns-state-review`, `--ns-state-todo`, `--ns-step`, `--ns-step-from`, `--ns-step-sign`, `--ns-swipe-surface`, `--ns-switch-h`, `--ns-switch-w`, `--ns-text-body`, `--ns-text-control`, `--ns-text-control-lg`, `--ns-text-display`, `--ns-text-editorial`, `--ns-text-empty`, `--ns-text-figure`, `--ns-text-giant`, `--ns-text-heading`, `--ns-text-headline`, `--ns-text-input`, `--ns-text-large`, `--ns-text-lede`, `--ns-text-meta`, `--ns-text-record`, `--ns-text-sentence`, `--ns-text-small`, `--ns-text-sub`, `--ns-text-title`, `--ns-theme-fade`, `--ns-tile-shadow`, `--ns-time-born`, `--ns-time-color`, `--ns-time-confirm`, `--ns-time-dialog`, `--ns-time-fling`, `--ns-time-flip`, `--ns-time-glide`, `--ns-time-grow`, `--ns-time-hold`, `--ns-time-menu`, `--ns-time-page`, `--ns-time-panel`, `--ns-time-quick`, `--ns-time-roll`, `--ns-time-settle`, `--ns-time-snap`, `--ns-time-spin`, `--ns-time-spring`, `--ns-time-sweep`, `--ns-time-toast`, `--ns-tint`, `--ns-tint-c`, `--ns-tint-ease`, `--ns-tint-fill`, `--ns-tint-gap`, `--ns-tint-h1`, `--ns-tint-h2`, `--ns-tint-h3`, `--ns-tint-ink`, `--ns-tint-row`, `--ns-tip-fold`, `--ns-tip-grow`, `--ns-toast-bottom`, `--ns-toast-gap`, `--ns-toast-left`, `--ns-toast-lift`, `--ns-toast-peek`, `--ns-toast-scale`, `--ns-toast-w`, `--ns-touch`, `--ns-tracking-body`, `--ns-tracking-caps`, `--ns-tracking-control`, `--ns-tracking-display`, `--ns-tracking-headline`, `--ns-tracking-sub`, `--ns-tracking-title`, `--ns-warn`, `--ns-warn-ink`, `--ns-wash-clay`, `--ns-wash-dusk`, `--ns-wash-graphite`, `--ns-wash-ink`, `--ns-wash-sage`, `--ns-wash-sand`, `--ns-weight-light`, `--ns-weight-medium`, `--ns-weight-regular`, `--ns-weight-strong`, `--ns-well`, `--ns-width-lg`, `--ns-width-md`, `--ns-width-sm`, `--ns-width-xl`.
- Never add Tailwind colour classes inside the component.

```tsx
import { CompanyMark } from "@/components/ui/notchset/company-mark";
```

## Parts
- A single export that takes props.

## Match the original
- Read `components/ui/notchset/tool-row.tsx`, `components/ui/notchset/disclosure-parts.tsx` as the reference implementation before changing or recreating anything, and match it: sizes, colours per theme, motion timings, copy and behaviour.
- If you deviate (a prop you can't honour, a style you changed, a dependency you swapped), say so in your reply, part by part.
- Keep the accessibility contract, the keyboard map and the motion levels listed below.

## Use it when
- Each call an agent makes on its way to an answer, where the person may want to see what went in and out, or must say yes first.

### Not when
- A turn's calls together are Tool; a step in a plan the person approved is Plan list's.

## Built from
- button (`button`), installed with it: reuse it, don't rebuild it
- live-label (`live-label`), installed with it: reuse it, don't rebuild it
- status-glyph-run (`status-glyph-run`), installed with it: reuse it, don't rebuild it
- stream-adapters (`stream-adapters`), installed with it: reuse it, don't rebuild it
- Controllable (shared helper, ships with it)
- Feedback (shared helper, ships with it)
- Icons (shared helper, ships with it)
- Words (shared helper, ships with it)

## Mistakes
- A spinner beside the sweeping words: the glyph's arc and the sweep are the signs of work
- Denied in red: a person said no, nothing failed
- Opening every row by itself: the person opens what they want to check

## Usage

```tsx
"use client";
import * as React from "react";
import { CompanyMark } from "@/components/ui/notchset/company-mark";
import { FileText, Globe } from "@/lib/notchset/icons";
import { useLessMotion } from "@/lib/notchset/motion";
import { ToolRow } from "@/components/ui/notchset/tool-row";
import type { ToolState } from "@/components/ui/notchset/stream-adapters";
import { PlayOnce, useSelfPlay } from "./self-play";
import { app } from "./tool-marks";

/*
 * One run's three calls, alone. On view the search runs and lands green, the reading runs and lands, then
 * the post asks inline (its gate opens inside the row) and rests there: Approve is the visitor's. A press on a row
 * opens what went in and came out. With "Next post fails" on, the approved post fails in rose, with Retry and Skip.
 */
const SOURCES = ["How Linear writes a changelog", "Figma's launch week, day by day", "Notion's release notes style", "Vercel Ship: the recap post", "Stripe Sessions: what shipped", "Shopify Editions: the format"];
const T0 = 1_762_000_000_000;
const clock = () => Date.now();
const glyph = (Icon: typeof Globe) => <Icon aria-hidden="true" className="size-4 text-[var(--ns-ink-2)]" />;

type Call = { state: ToolState; at: number; end?: number | undefined };
const REST: Call[] = [
  { state: "output-available", at: T0, end: T0 + 2000 },
  { state: "output-available", at: T0 + 2000, end: T0 + 3000 },
  { state: "approval-requested", at: T0 + 3000 },
];
const GATE = { id: "a1", title: "Post the summary to #launch?", effect: ["3 paragraphs, 2 links", "Slack", "posting always asks"], tone: "outside" as const, scopes: ["once" as const] };

export default function ToolRowDemo() {
  const fails = false as boolean;
  const root = React.useRef<HTMLDivElement>(null);
  const less = useLessMotion();
  const settle = Boolean(React.useContext(PlayOnce)?.settle);
  const play = useSelfPlay(root, { beats: [0, 1300, 1100], off: less });
  const [calls, setCalls] = React.useState<Call[]>(REST);
  const timers = React.useRef<number[]>([]);
  React.useEffect(() => () => timers.current.forEach(clearTimeout), []);
  const set = (i: number, c: Partial<Call>) => setCalls((cs) => cs.map((x, k) => (k === i ? { ...x, ...c } : x)));

  /* the arrival: the search runs, lands; the reading runs, lands; the post asks (at once with less motion) */
  const step = play.step;
  React.useEffect(() => {
    if (step < 0 || play.mine) return;
    const t = window.setTimeout(() => {
      const now = clock();
      if (less || settle) return setCalls(REST);
      if (step === 0) setCalls([{ state: "input-available", at: now }]);
      if (step === 1) setCalls((cs) => [{ ...cs[0]!, state: "output-available", end: now }, { state: "input-available", at: now }]);
      if (step === 2) setCalls((cs) => [cs[0]!, { ...cs[1]!, state: "output-available", end: now }, { state: "approval-requested", at: now }]);
    });
    return () => window.clearTimeout(t);
  }, [step, less, settle, play.mine]);

  const run = () => {
    set(2, { state: "input-available", at: clock(), end: undefined });
    const fail = fails;
    timers.current.push(window.setTimeout(() => set(2, fail ? { state: "output-error", end: clock() } : { state: "output-available", end: clock() }), 1200));
  };
  const post = calls[2];

  return (
    <div ref={root} onPointerDownCapture={play.handOver} onKeyDownCapture={play.handOver} className="grid w-[min(100%,560px)] grid-cols-[minmax(0,1fr)]">
      {/* the rest, unseen, holds the stage at its full height while the calls arrive */}
      <div aria-hidden="true" ref={(el) => void (el && (el.inert = true))} className="invisible col-start-1 row-start-1 flex flex-col gap-2">
        <ToolRow part={{ type: "tool-a", toolCallId: "g1", state: "output-available" }} look={{ running: "x", done: () => "x", mark: glyph(Globe) }} />
        <ToolRow part={{ type: "tool-b", toolCallId: "g2", state: "output-available" }} look={{ running: "x", done: () => "x", mark: glyph(Globe) }} />
        <ToolRow part={{ type: "tool-c", toolCallId: "g3", state: "approval-requested" }} look={{ running: "x", done: () => "x", mark: glyph(Globe) }} approval={{ ...GATE, id: "g" }} />
      </div>
      <div className="col-start-1 row-start-1 flex min-w-0 flex-col gap-2">
        {calls[0] && (
          <ToolRow
            part={{ type: "tool-searchWeb", toolCallId: "s1", state: calls[0].state, input: { query: "how teams write a launch post" }, output: SOURCES }}
            look={{ running: "Searching the web", done: (o) => `Searched the web · ${(o as unknown[]).length} sources`, mark: glyph(Globe) }}
            startedAt={calls[0].at}
            endedAt={calls[0].end}
          />
        )}
        {calls[1] && (
          <ToolRow
            part={{ type: "tool-readPages", toolCallId: "r1", state: calls[1].state, input: { pages: 3 }, output: "Each one leads with what changed for the reader, then shows it in one picture." }}
            look={{ running: "Reading 3 pages", done: () => "Read 3 pages · one pattern", mark: glyph(FileText) }}
            startedAt={calls[1].at}
            endedAt={calls[1].end}
          />
        )}
        {post && (
          <ToolRow
            part={{
              type: "tool-postMessage",
              toolCallId: "p1",
              state: post.state,
              input: { channel: "#launch", paragraphs: 3 },
              output: { posted: "#launch", at: "10:52" },
              errorText: "Slack didn't answer in time",
              approval: { id: "a1", ...(post.state === "output-denied" ? { approved: false } : {}) },
            }}
            look={{ running: "Post the summary to #launch", done: () => "Posted the summary · #launch", failed: "Couldn't post to #launch", mark: <CompanyMark {...app("Slack")} size="xs" />, tone: "outside" }}
            approval={GATE}
            onAnswer={(a) => (a.approved ? run() : set(2, { state: "output-denied", end: clock() }))}
            onRetry={run}
            onSkip={() => set(2, { state: "output-denied", end: undefined })}
            labels={post.state === "output-denied" && post.end === undefined ? { denied: "skipped" } : undefined}
            startedAt={post.state === "approval-requested" ? undefined : post.at}
            endedAt={post.end}
          />
        )}
      </div>
    </div>
  );
}
```

This example also uses `company-mark` (https://notchset.dev/components/company-mark). Installing this item doesn't bring them; to paste the example as it is: `npx shadcn@latest add https://notchset.dev/r/tool-row.json https://notchset.dev/r/company-mark.json`.

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `onFeedback` | `(e: FeedbackEvent) => void` |  | called once per move, for your sound or haptics |
| `part` | `ToolPart \| DynamicToolPart` |  | the call, as the stream sends it |
| `look` | `ToolLook` |  | how this tool is named: present words, past words from its output, failed words, its mark |
| `startedAt` | `number` |  | when the call began and ended (ms), for its clock; the clock counts while it runs |
| `endedAt` | `number` |  |  |
| `approval` | `Approval` |  | the gate, while the call asks: what it will do (title, effect) |
| `onAnswer` | `(answer: ApprovalAnswer) => void` |  | the person's answer at the gate |
| `gateAside` | `React.ReactNode` |  | one more control in the gate, at its end ("Edit amount") |
| `gate` | `React.ReactNode` |  | the host's own gate in place of the built-in one (a Confirmation with look="row": scopes, the tool's tone, editable arguments); it opens and folds in the same place, on the same move, while the call asks |
| `onRetry` | `() => void` |  | a failed call, offered again |
| `onSkip` | `() => void` |  | a failed call, passed over so the run goes on |
| `onUndo` | `() => void` |  | a done call taken back (leave it out for one that cannot be, like a payout) |
| `markBand` | `boolean` |  | keep the mark's room when this row has none, so rows in one list (a run's steps) share one title column |
| `output` | `React.ReactNode` |  | what came out, drawn by the host (a list of issues with their keys); otherwise text, a list, a table or JSON |
| `outputNote` | `string` |  | the output's heading words after "Output" ("4 issues") |
| `open` | `boolean` |  | opened or folded; the host keeps it if it wants to (folded by default) |
| `onOpenChange` | `(open: boolean) => void` |  |  |
| `labels` | `Partial<ToolRowLabels>` |  |  |
| `bare` | `boolean` |  | drawn without a box of its own, for a host that is the box (a card holding the one call): the glyph, the gate's well and the detail start on the host's own edge, so there is never a box between the card and the well |

Full docs: https://notchset.dev/components/tool-row

## Customising
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- Dark mode follows the `.dark` class or `data-theme="dark"` on an ancestor (the shadcn and next-themes conventions).
- Update later: Commit or stash local changes first (or copy the files), so the update can be undone. Read https://notchset.dev/r/changelog.json for the new versions: a major version, an entry marked breaking or a merge says what to change. Then re-run the install with `--overwrite`, on a branch. It replaces the component's files, the shared helper files they import, and the item's CSS rules in the global stylesheet, so review the whole diff (components, shared files, CSS), re-apply your own edits, and run the app's typecheck, tests and build.

## Keyboard

| Keys | Action |
|---|---|
| Enter or Space | open or fold what went in and out |
| Tab | to the gate's Approve and Deny, Retry and Skip |

## Performance

- One 1 s clock while a call runs, none at rest; the output is drawn only while open.
- No dependencies.

## Responsive

- phone and desktop
- dark (tokens)
- reduced motion: the row and the gate appear and fold at once

## Motion inventory

| Interaction | What moves |
|---|---|
| Undo fades in after an action | ns-fade on --ns-time-menu, --ns-ease. Reduced motion: already only a fade; it stays. |
| a row born while you watch grows from no height | grid-template-rows on --ns-time-panel, --ns-ease-panel (data-ns-glide). Reduced motion: it is there. |
| the present words sweep, then settle past tense | Live label. Reduced motion: the words swap. |
| the gate opens in the row and Approve folds it | grid-template-rows on --ns-time-panel, --ns-ease-panel (data-ns-glide). Reduced motion: it appears and goes at once. |

## Accessibility contract (preserve when editing)
- The row's words are a disclosure button (aria-expanded, aria-controls) when there is something to open; the gate is a group named by its question, its buttons plain buttons; the run glyph reads the call's state with its words.
- The run that holds the rows announces its phases; a row never announces itself.

## Install

```bash
# npm
npx shadcn@latest add https://notchset.dev/r/tool-row.json
# pnpm
pnpm dlx shadcn@latest add https://notchset.dev/r/tool-row.json
# yarn
yarn dlx shadcn@latest add https://notchset.dev/r/tool-row.json
# bun
bunx --bun shadcn@latest add https://notchset.dev/r/tool-row.json
```

Or add the `@notchset` registry to components.json and run `npx shadcn@latest add @notchset/tool-row`. Every components.json style gets the same files.

### Manual

1. Install the packages: `npm install lucide-react@^1`.
2. Copy `components/ui/notchset/tool-row.tsx`, `lib/notchset/controllable.ts`, `components/ui/notchset/disclosure-parts.tsx`, `lib/notchset/feedback.ts`, `lib/notchset/icons.ts`, `lib/notchset/words.ts` from https://notchset.dev/r/tool-row.json (each file's `content`, at its `target`), keeping the `@/` path alias of your tsconfig.
3. Add what it builds on: shadcn `utils` (cn), `notchset-foundation`, `button`, `live-label`, `status-glyph-run`, `stream-adapters`.

## Continue the workflow

- [Change set](https://notchset.dev/components/change-set)
- [Checkpoint rail](https://notchset.dev/components/checkpoint-rail)
- [Message](https://notchset.dev/components/message)

## Source

### components/ui/notchset/tool-row.tsx

```tsx
// Notchset tool-row 1.2.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { ChevronDown, RotateCcw, Undo2 } from "@/lib/notchset/icons";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/notchset/button";
import { disclosureTrigger } from "@/components/ui/notchset/disclosure-parts";
import { LiveLabel } from "@/components/ui/notchset/live-label";
import { StatusGlyphRun, type StatusGlyphRunState } from "@/components/ui/notchset/status-glyph-run";
import { toolDisplayOf, toolOf, type Approval, type ApprovalAnswer, type DynamicToolPart, type ToolDisplay, type ToolLook, type ToolPart } from "@/components/ui/notchset/stream-adapters";
import { fill } from "@/lib/notchset/words";
import type { FeedbackProps } from "@/lib/notchset/feedback";

/*
 * Tool row: one tool call, read straight from the stream's part (the AI SDK's tool part, or a dynamic tool), through
 * its six words: preparing and running say what it does in the present while the words sweep and the clock counts;
 * done turns past tense with its outcome ("Searched Linear issues · 4 results") as the run glyph draws its tick;
 * failed offers Retry and Skip in place; denied is ink, never red. Done, a call that can be taken back offers Undo.
 * When the tool needs a yes, the gate opens inside the row (what it will do, Approve and Deny, or the host's own
 * `gate`), and Approve folds it. A press on the row opens what went in and came out: text, a list, a table or JSON.
 * The host names each tool once (ToolLook); the words after " · " in the past are the outcome.
 */
type ToolRowLabels = { input: string; output: string; error: string; asking: string; denied: string; deniedReason: string; approve: string; deny: string; retry: string; skip: string; undo: string };
const TOOL_ROW_LABELS: ToolRowLabels = {
  input: "Input",
  output: "Output",
  error: "What went wrong",
  asking: "needs your OK",
  denied: "denied by you",
  deniedReason: "denied: {reason}",
  approve: "Approve",
  deny: "Deny",
  retry: "Retry",
  skip: "Skip",
  undo: "Undo",
};
type ToolRowProps = FeedbackProps & {
  /** the call, as the stream sends it */
  part: ToolPart | DynamicToolPart;
  /** how this tool is named: present words, past words from its output, failed words, its mark */
  look: ToolLook;
  /** when the call began and ended (ms), for its clock; the clock counts while it runs */
  startedAt?: number | undefined;
  endedAt?: number | undefined;
  /** the gate, while the call asks: what it will do (title, effect) */
  approval?: Approval | undefined;
  /** the person's answer at the gate */
  onAnswer?: ((answer: ApprovalAnswer) => void) | undefined;
  /** one more control in the gate, at its end ("Edit amount") */
  gateAside?: React.ReactNode;
  /**
   * the host's own gate in place of the built-in one (a Confirmation with look="row": scopes, the tool's tone,
   * editable arguments); it opens and folds in the same place, on the same move, while the call asks
   */
  gate?: React.ReactNode;
  /** a failed call, offered again */
  onRetry?: (() => void) | undefined;
  /** a failed call, passed over so the run goes on */
  onSkip?: (() => void) | undefined;
  /** a done call taken back (leave it out for one that cannot be, like a payout) */
  onUndo?: (() => void) | undefined;
  /** keep the mark's room when this row has none, so rows in one list (a run's steps) share one title column */
  markBand?: boolean | undefined;
  /** what came out, drawn by the host (a list of issues with their keys); otherwise text, a list, a table or JSON */
  output?: React.ReactNode;
  /** the output's heading words after "Output" ("4 issues") */
  outputNote?: string | undefined;
  /** opened or folded; the host keeps it if it wants to (folded by default) */
  open?: boolean | undefined;
  onOpenChange?: ((open: boolean) => void) | undefined;
  labels?: Partial<ToolRowLabels> | undefined;
  /**
   * drawn without a box of its own, for a host that is the box (a card holding the one call): the glyph, the gate's
   * well and the detail start on the host's own edge, so there is never a box between the card and the well
   */
  bare?: boolean | undefined;
  className?: string | undefined;
};

const GLYPH: Readonly<Record<ToolDisplay, StatusGlyphRunState>> = { preparing: "running", running: "running", asking: "waiting", done: "done", failed: "failed", denied: "stopped" };

/** "0:07", "1:05": a call's time on its clock. */
const clock = (ms: number) => {
  const s = Math.max(0, Math.floor(ms / 1000));
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
};

/* the input as one line of its arguments: query: "checkout bug", team: "WEB" */
function argsLine(input: unknown): string {
  if (input === undefined || input === null) return "";
  if (typeof input !== "object" || Array.isArray(input)) return JSON.stringify(input);
  return Object.entries(input as Record<string, unknown>)
    .map(([k, v]) => `${k}: ${JSON.stringify(v)}`)
    .join(", ");
}

const MONO = "font-[family-name:var(--ns-font-mono)] text-[length:var(--ns-text-small)]";
const WELL = "rounded-[var(--ns-radius)] bg-[var(--ns-well)] px-3 py-2";
/* the row's line: its words' line and 12px above and below, so the words' ink sits at the 12px start inset (14px words
   in 44, 16px touch words in 46); a run's plain steps take the same line, so a list keeps one rhythm */
const TOOL_ROW_LINE = "min-h-[calc(var(--ns-lead-body)+24px)]";

/* what came out: a sentence as text, plain values as a list, records as a table, anything else as JSON */
function Output({ value }: { value: unknown }) {
  if (typeof value === "string") return <p className="m-0 whitespace-pre-wrap [overflow-wrap:anywhere]">{value}</p>;
  const rows = Array.isArray(value) ? value : null;
  if (rows && rows.every((r) => typeof r !== "object" || r === null)) {
    return (
      <ul data-slot="tool-row-list" className="m-0 flex list-disc flex-col gap-1 ps-5">
        {rows.map((r, i) => (
          <li key={i} className="[overflow-wrap:anywhere]">{String(r)}</li>
        ))}
      </ul>
    );
  }
  if (rows && rows.length && rows.every((r) => r && typeof r === "object" && !Array.isArray(r))) {
    const cols = [...new Set(rows.flatMap((r) => Object.keys(r as object)))].slice(0, 5);
    return (
      <div tabIndex={0} role="region" aria-label="Output table" className="max-w-full overflow-x-auto rounded-[var(--ns-radius-sm)] outline-hidden focus-visible:outline-2 focus-visible:outline-[var(--ns-signal)]">
        <table data-slot="tool-row-table" className="w-full border-collapse text-start tabular-nums">
          <thead>
            <tr>
              {cols.map((c) => (
                <th key={c} scope="col" className="border-b border-[var(--ns-line-soft)] py-1 pe-4 text-start font-[number:var(--ns-weight-medium)] text-[var(--ns-ink-3)]">{c}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>
                {cols.map((c) => (
                  <td key={c} className="py-1 pe-4 align-top [overflow-wrap:anywhere]">{String((r as Record<string, unknown>)[c] ?? "")}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
  return (
    <pre tabIndex={0} aria-label="Output" className={cn(MONO, WELL, "m-0 max-h-[16lh] overflow-auto whitespace-pre outline-hidden focus-visible:outline-2 focus-visible:outline-[var(--ns-signal)]")}>
      {JSON.stringify(value, null, 2)}
    </pre>
  );
}

/* a call's clock: counts each second while it runs, holds its last figure after */
function useElapsed(startedAt: number | undefined, endedAt: number | undefined, live: boolean) {
  const [now, setNow] = React.useState<number | null>(null);
  React.useEffect(() => {
    if (!live || startedAt === undefined) return;
    const tick = () => setNow(Date.now());
    const f = requestAnimationFrame(tick);
    const t = setInterval(tick, 1000);
    return () => (cancelAnimationFrame(f), clearInterval(t));
  }, [live, startedAt]);
  if (startedAt === undefined) return null;
  if (endedAt !== undefined) return endedAt - startedAt;
  return now === null ? null : now - startedAt;
}

function ToolRow({ part, look, startedAt, endedAt, approval, onAnswer, gateAside, gate, onRetry, onSkip, onUndo, markBand, output, outputNote, open: openProp, onOpenChange, labels, bare, className, onFeedback }: ToolRowProps) {
  const L = { ...TOOL_ROW_LABELS, ...labels };
  const call = toolOf(part)!;
  const shows = toolDisplayOf(call);
  const live = shows === "preparing" || shows === "running";
  const asking = shows === "asking";
  const id = React.useId();
  const [own, setOwn] = React.useState(false);
  const open = openProp ?? own;
  const setOpen = (o: boolean) => (onFeedback?.(o ? "open" : "close"), onOpenChange ? onOpenChange(o) : setOwn(o));
  /* a row born while you watch (streamed live) grows from no height; one that arrived settled or already asking
     (history, a reload) is simply there, its gate open */
  const [born] = React.useState(() => live);
  const [grown, setGrown] = React.useState(!born);
  React.useEffect(() => {
    if (grown) return;
    const f = requestAnimationFrame(() => setGrown(true));
    return () => cancelAnimationFrame(f);
  }, [grown]);
  const ms = useElapsed(startedAt, endedAt, live || asking);

  /* the words: past and its outcome split at " · "; a failure says what failed; asking and denied say so in ink */
  const doneWords = shows === "done" ? look.done(call.output) : "";
  const cut = doneWords.indexOf(" · ");
  const past = shows === "done" ? (cut < 0 ? doneWords : doneWords.slice(0, cut)) : shows === "failed" ? (look.failed ?? look.running) : look.running;
  const outcome =
    shows === "done" ? (cut < 0 ? undefined : doneWords.slice(cut + 3)) : shows === "failed" ? call.errorText : shows === "denied" ? (call.approval?.reason ? fill(L.deniedReason, { reason: call.approval.reason }) : L.denied) : asking ? L.asking : undefined;
  const has = call.input !== undefined || call.output !== undefined || output !== undefined || !!call.errorText;
  const canOpen = has && !asking;

  return (
    <div
      data-slot="tool-row"
      data-state={shows}
      className={cn("grid min-w-0", !bare && "rounded-[var(--ns-radius-lg)] bg-[var(--ns-panel)] shadow-[inset_0_0_0_1px_var(--ns-line-soft)]", "[transition:grid-template-rows_var(--ns-time-panel)_var(--ns-ease-panel)]", grown ? "grid-rows-[1fr]" : "grid-rows-[0fr]", className)}
      data-ns-glide=""
    >
      <div className="min-h-0 overflow-hidden">
        <div className={cn("flex min-w-0 items-center gap-2.5 text-[length:var(--ns-text-body)]", TOOL_ROW_LINE, bare ? "px-0" : "px-3")}>
          <StatusGlyphRun state={GLYPH[shows]} label={past} />
          {look.mark ? <span className="inline-flex shrink-0 [&>*]:block">{look.mark}</span> : markBand && <span aria-hidden className="w-4 shrink-0" />}
          {canOpen ? (
            <button type="button" {...disclosureTrigger(open, id, () => setOpen(!open))} className={cn("flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-start outline-hidden focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-[var(--ns-signal)] rounded-[var(--ns-radius-sm)]", TOOL_ROW_LINE)}>
              <Words shows={shows} present={look.running} past={past} outcome={outcome} />
              <Meta ms={ms} />
              <ChevronDown aria-hidden className={cn("size-4 shrink-0 text-[var(--ns-ink-3)] [transition:rotate_var(--ns-time-color)]", open ? "rotate-180" : "-rotate-90 rtl:rotate-90")} />
            </button>
          ) : (
            <span className="flex min-w-0 flex-1 items-center gap-2">
              <Words shows={shows} present={look.running} past={past} outcome={outcome} />
              <Meta ms={ms} />
            </span>
          )}
          {shows === "done" && onUndo && (
            <Button size="sm" intent="ghost" onClick={() => (onFeedback?.("press"), onUndo?.())} className="-me-1.5 shrink-0 text-[var(--ns-ink-2)] [animation:ns-fade_var(--ns-time-menu)_var(--ns-ease)_both]">
              <Undo2 aria-hidden />
              {L.undo}
            </Button>
          )}
        </div>

        {/* the gate: what it will do, Approve and Deny; it folds as the call goes on */}
        <div data-ns-glide="" className={cn("grid [transition:grid-template-rows_var(--ns-time-panel)_var(--ns-ease-panel)]", asking && (approval || gate) ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}>
          <div className="min-h-0 overflow-hidden" ref={(el) => void (el && (el.inert = !(asking && (approval || gate))))}>
            {gate ? (
              <div data-slot="tool-row-gate" className={bare ? "" : "mx-3 mb-3"}>
                {gate}
              </div>
            ) : approval && (
              <div data-slot="tool-row-gate" role="group" aria-label={approval.title} className={cn(WELL, !bare && "mx-3 mb-3", "flex flex-col gap-1 py-3 text-[length:var(--ns-text-body)]")}>
                <p className="m-0 font-[number:var(--ns-weight-medium)] text-[var(--ns-ink)] [overflow-wrap:anywhere]">{approval.title}</p>
                {approval.effect.length > 0 && <p className="m-0 text-[length:var(--ns-text-small)] text-[var(--ns-ink-2)] [overflow-wrap:anywhere]">{approval.effect.join(" · ")}</p>}
                <div className="flex flex-wrap items-center gap-2 pt-2">
                  <Button size="sm" intent="primary" onClick={() => (onFeedback?.("press"), onAnswer?.({ approved: true, scope: "once" }))}>{L.approve}</Button>
                  <Button size="sm" onClick={() => (onFeedback?.("press"), onAnswer?.({ approved: false }))}>{L.deny}</Button>
                  {gateAside && <span className="ms-auto">{gateAside}</span>}
                </div>
              </div>
            )}
          </div>
        </div>

        {shows === "failed" && (onRetry || onSkip) && (
          <div data-slot="tool-row-failed" className={cn("flex flex-wrap items-center gap-2 leading-[var(--ns-lead-meta)]", bare ? "ps-6" : "px-3 pb-3")}>
            {onRetry && (
              <Button size="sm" onClick={() => (onFeedback?.("press"), onRetry?.())}>
                <RotateCcw aria-hidden />
                {L.retry}
              </Button>
            )}
            {onSkip && (
              <Button size="sm" intent="ghost" onClick={() => (onFeedback?.("press"), onSkip?.())}>
                {L.skip}
              </Button>
            )}
          </div>
        )}

        {canOpen && open && (
          <div id={id} data-slot="tool-row-detail" className={cn("flex flex-col gap-2 text-[length:var(--ns-text-small)] text-[var(--ns-ink)]", bare ? "ps-6" : "px-3 pb-3")}>
            {call.input !== undefined && (
              <>
                <span className="text-[var(--ns-ink-3)]">{L.input}</span>
                <code className={cn(MONO, WELL, "block [overflow-wrap:anywhere]")}>{argsLine(call.input)}</code>
              </>
            )}
            {shows === "failed" && call.errorText ? (
              <>
                <span className="text-[var(--ns-ink-3)]">{L.error}</span>
                <p className="m-0 text-[var(--ns-bad-ink)] [overflow-wrap:anywhere]">{call.errorText}</p>
              </>
            ) : (output !== undefined || call.output !== undefined) && (
              <>
                <span className="text-[var(--ns-ink-3)]">
                  {L.output}
                  {outputNote ? ` · ${outputNote}` : ""}
                </span>
                {output ?? <Output value={call.output} />}
              </>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

/* the words in their tense: present sweeping while it works, past with its outcome; asking and denied in ink */
function Words({ shows, present, past, outcome }: { shows: ToolDisplay; present: string; past: string; outcome: string | undefined }) {
  if (shows === "asking" || shows === "denied")
    return (
      /* what it asks, or why it stopped, is read whole: on a narrow row it wraps, never cut */
      <span data-slot="tool-row-words" className="min-w-0 flex-1 py-2 leading-snug [overflow-wrap:anywhere]">
        {present}
        {outcome && <span className="text-[var(--ns-ink-3)]"> · {outcome}</span>}
      </span>
    );
  return <LiveLabel state={shows === "done" ? "done" : shows === "failed" ? "failed" : "running"} present={present} past={past} outcome={outcome} className="min-w-0 flex-1" />;
}

function Meta({ ms }: { ms: number | null }) {
  if (ms === null) return null;
  /* the small clock sits in a line box of the label's size, so the two share one baseline */
  return (
    <span className="shrink-0 text-[length:var(--ns-text-body)]">
      <span className="text-[length:var(--ns-text-small)] text-[var(--ns-ink-3)] tabular-nums">{clock(ms)}</span>
    </span>
  );
}

export { TOOL_ROW_LABELS, TOOL_ROW_LINE, ToolRow, type ToolRowLabels, type ToolRowProps };
```

### lib/notchset/controllable.ts

```tsx
// Notchset tool-row 1.2.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";

/**
 * Controlled and uncontrolled, one source of truth: a piece takes `value` with `onValueChange` (controlled) or
 * `defaultValue` (uncontrolled), and reads and sets it through this hook. Controlled, it shows `value` and only asks
 * for a change; uncontrolled, it keeps its own state; it never switches between the two after its first render. On a
 * Base UI root it hands Base UI the controlled value. Controlled, two identical sets in one event can each call
 * onChange (the second is compared with what is shown, not with what was asked): harmless for open and close; a host
 * whose onChange has side effects makes it idempotent.
 * @example
 * const [value, setValue] = useControllable({ value: props.value, defaultValue: props.defaultValue ?? 0, onChange: props.onValueChange });
 * const [open, setOpen] = useControllableOpen(props);
 */
export function useControllable<T>({ value, defaultValue, onChange }: { value?: T | undefined; defaultValue: T; onChange?: ((next: T) => void) | undefined }): [T, (next: T | ((prev: T) => T)) => void] {
  const controlled = value !== undefined;
  const [own, setOwn] = React.useState(defaultValue);
  const current = controlled ? value : own;
  /* `asked` is what this event asked for so far, cleared by each render, so a refused request can be made again; written in an insertion effect so a layout effect reads this render's value. */
  const latest = React.useRef<{ current: T; controlled: boolean; onChange: typeof onChange; asked?: { v: T } | undefined }>({ current, controlled, onChange });
  React.useInsertionEffect(() => {
    latest.current = { current, controlled, onChange };
  });
  const set = React.useCallback((next: T | ((prev: T) => T)) => {
    const l = latest.current;
    const base = l.asked ? l.asked.v : l.current;
    const v = typeof next === "function" ? (next as (prev: T) => T)(base) : next;
    if (Object.is(v, base) && (!l.asked || Object.is(v, l.current))) return;
    l.asked = { v };
    if (!l.controlled) setOwn(v);
    l.onChange?.(v);
  }, []);
  return [current, set];
}

/** The same for a piece that opens: `open` with `onOpenChange`, or `defaultOpen`. */
export function useControllableOpen({ open, defaultOpen = false, onOpenChange }: { open?: boolean | undefined; defaultOpen?: boolean | undefined; onOpenChange?: ((open: boolean) => void) | undefined }) {
  return useControllable({ value: open, defaultValue: defaultOpen, onChange: onOpenChange });
}
```

### components/ui/notchset/disclosure-parts.tsx

```tsx
// Notchset tool-row 1.2.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { useControllableOpen } from "@/lib/notchset/controllable";

/* The disclosure contract without its look (disclosure.tsx draws the rows): for a piece with its own trigger, keeping
   its own open state (the attributes) or this one (useDisclosure). */

/**
 * The trigger attributes for one row of a list whose open rows the list keeps (a hook can't run per row).
 * @example
 * <button type="button" {...disclosureTrigger(open === row.id, `${id}-${row.id}`, () => setOpen(open === row.id ? null : row.id))}>
 */
function disclosureTrigger(open: boolean, controls: string, onToggle: () => void) {
  return { "aria-expanded": open, "aria-controls": controls, onClick: onToggle };
}

/** A valid panel id: a key with a space would split aria-controls, so non-word characters become _. */
function partId(uid: string, key: string) {
  return `${uid}-${key.replace(/[^\w-]/g, "_")}`;
}

/** Spread on the element holding a disclosure: Escape there folds an open one, focus back on its trigger. */
function disclosureScope(open: boolean, controls: string, onFold: () => void) {
  return {
    onKeyDown: (e: React.KeyboardEvent<HTMLElement>) => {
      if (e.key !== "Escape" || !open) return;
      e.stopPropagation();
      onFold();
      e.currentTarget.querySelector<HTMLElement>(`[aria-controls="${CSS.escape(controls)}"]`)?.focus();
    },
  };
}

type DisclosureScopeProps = React.HTMLAttributes<HTMLDivElement> & {
  /** whether the disclosure inside is open */
  open: boolean;
  /** the id of the panel its trigger controls */
  controls: string;
  /** folds it (the host's own state) */
  onFold: () => void;
};

/** disclosureScope as the element itself: `<DisclosureScope open={open} controls={bodyId} onFold={fold}>…` */
const DisclosureScope = React.forwardRef<HTMLDivElement, DisclosureScopeProps>(function DisclosureScope({ open, controls, onFold, ...rest }, ref) {
  return <div data-slot="disclosure-scope" ref={ref} {...rest} {...disclosureScope(open, controls, onFold)} />;
});

type OpenProps = {
  /** Controlled: open or closed. */
  open?: boolean | undefined;
  /** Uncontrolled: how it starts. */
  defaultOpen?: boolean | undefined;
  /** Called with the new state on every press. */
  onOpenChange?: ((open: boolean) => void) | undefined;
};

/**
 * The disclosure contract for a trigger with its own look.
 * @example
 * const d = useDisclosure({ defaultOpen: false });
 * <button {...d.trigger}>Show all</button>
 * {d.open && <ul {...d.panel}>…</ul>}
 */
function useDisclosure({ open: openProp, defaultOpen, onOpenChange }: OpenProps = {}) {
  const [open, setOpen] = useControllableOpen({ open: openProp, defaultOpen, onOpenChange });
  const id = React.useId();
  const toggle = React.useCallback(() => setOpen((o) => !o), [setOpen]);
  return {
    open,
    setOpen,
    toggle,
    /** Spread on the button that opens and closes it. */
    trigger: disclosureTrigger(open, id, toggle),
    /** Spread on the element it shows (it must stay mounted, or be the one the trigger points at once open). */
    panel: { id },
    /** Spread on the element holding the trigger and the panel: Escape there folds it, focus back on the trigger. */
    scope: disclosureScope(open, id, () => setOpen(false)),
  };
}

export { DisclosureScope, disclosureScope, disclosureTrigger, partId, useDisclosure, type DisclosureScopeProps, type OpenProps };
```

### lib/notchset/feedback.ts

```tsx
// Notchset tool-row 1.2.0 · https://notchset.dev/changelog
export type FeedbackEvent = "press" | "toggle-on" | "toggle-off" | "open" | "close" | "select" | "success" | "error" | "add" | "remove" | "send";
export type FeedbackProps = {
  /** called once per move, for your sound or haptics */
  onFeedback?: ((e: FeedbackEvent) => void) | undefined;
};
```

### lib/notchset/icons.ts

```tsx
// Notchset tool-row 1.2.0 · https://notchset.dev/changelog
/** Every piece imports its icons from here: swap the icon set in this one file. */
export * from "lucide-react";
```

### lib/notchset/words.ts

```tsx
// Notchset tool-row 1.2.0 · https://notchset.dev/changelog
import * as React from "react";

/* Built-in words and figures, one way for every piece. */

/** The locale a piece writes in when the app passes none: English at launch, the same on the server and in the browser. */
export const DEFAULT_LOCALE = "en-US";

/** A count's words by the locale's plural rule: `other` always, any of the locale's other forms as it needs them. */
export type Plural = { other: string } & Partial<Record<Intl.LDMLPluralRule, string>>;

/** A whole number (or any figure) in the locale's digits and grouping. */
export function formatCount(n: number, locale: string = DEFAULT_LOCALE, options?: Intl.NumberFormatOptions): string {
  return new Intl.NumberFormat(locale, options).format(n);
}

/** A sentence with its `{name}` blanks filled; a blank with no value is left as written. */
export function fill(sentence: string, vars: Readonly<Record<string, string | number>>): string {
  return sentence.replace(/\{(\w+)\}/g, (blank, name: string) => (name in vars ? String(vars[name]) : blank));
}

/** The same, where a blank is a node (a name in ink): the sentence's own words stay in order around it. */
export function fillNodes(sentence: string, vars: Readonly<Record<string, React.ReactNode>>): React.ReactNode {
  return sentence.split(/(\{\w+\})/).map((part, i) => {
    const name = /^\{(\w+)\}$/.exec(part)?.[1];
    return name !== undefined && name in vars ? React.createElement(React.Fragment, { key: i }, vars[name]) : part;
  });
}

/** A count's sentence by the locale's plural rule, `{count}` written in the locale ("1 message", "4 messages"). */
export function plural(locale: string | undefined, n: number, forms: Plural, vars: Readonly<Record<string, string | number>> = {}): string {
  const loc = locale ?? DEFAULT_LOCALE;
  const rule = new Intl.PluralRules(loc).select(n);
  return fill(forms[rule] ?? forms.other, { count: formatCount(n, loc), ...vars });
}
```

The foundation (the tokens listed above, keyframes and motion levels) installs once with the first component; its CSS is public at https://notchset.dev/r/notchset-foundation.json.
