# Thinking fold (Notchset): prompt.md (v1.2.0)

- id: `thinking-fold` · 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/thinking-fold.json`
- npm dependencies: lucide-react@^1
- registry dependencies: utils, https://notchset.dev/r/notchset-foundation.json, @notchset/live-label
- docs: https://notchset.dev/components/thinking-fold
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

A reply's thinking, folded always. Live it is one line of a fixed height, "Thinking 7 s" and the current thought in ink-3, so nothing under it moves. Finished, it settles in place to "Thought for 7 s"; stopped mid-thought, it keeps what it had and says where. Only the reader opens it..

## 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/thinking-fold.tsx`, `components/ui/notchset/disclosure-parts.tsx`, `components/ui/notchset/stream-text-parts.tsx`; shared code: `lib/notchset/controllable.ts`, `lib/notchset/feedback.ts`, `lib/notchset/icons.ts`, `lib/notchset/motion.ts`, `lib/notchset/ui-message.ts`, `lib/notchset/words.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`, `live-label`.
- Builds: one set of files, the same for every shadcn style.
- Exports to keep: `THINKING_FOLD_LABELS`, `ThinkingFold`, `DisclosureScope`, `disclosureScope`, `disclosureTrigger`, `partId`, `useDisclosure`, `StreamText`, 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-control-sm`, `--ns-ease`, `--ns-ease-spring`, `--ns-ink-2`, `--ns-ink-3`, `--ns-leading-prose`, `--ns-line`, `--ns-radius-sm`, `--ns-signal`, `--ns-signal-ink`, `--ns-signal-wash`, `--ns-text-small`, `--ns-time-color`, `--ns-time-menu`, `--ns-time-spring`, `--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 { ThinkingFold } from "@/components/ui/notchset/thinking-fold";
```

## Parts
- A single export that takes props.

## Match the original
- Read `components/ui/notchset/thinking-fold.tsx`, `components/ui/notchset/disclosure-parts.tsx`, `components/ui/notchset/stream-text-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
- A model's reasoning before its answer, offered to the reader who wants to check it, never in the way of the answer.

### Not when
- What the agent did (searches, edits) is Tool's; what it read is Sources'.

## Built from
- live-label (`live-label`), 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)
- Motion (shared helper, ships with it)
- Ui message (shared helper, ships with it)
- Words (shared helper, ships with it)

## Mistakes
- Opening it by itself while the model thinks: it pushes the answer down; only the reader opens it
- A spinner beside the words: the sweep is the sign
- The thinking in ink: it is quiet, ink-2 and ink-3, behind a hairline

## Usage

```tsx
"use client";
import * as React from "react";
import { useLessMotion } from "@/lib/notchset/motion";
import { ThinkingFold } from "@/components/ui/notchset/thinking-fold";
import { PlayOnce, useSelfPlay } from "./self-play";

/*
 * The fold alone, over the answer it folds above. On view it thinks once: "Thinking 4 s" counts while the thoughts
 * arrive one line at a time, then it settles in place to "Thought for 7 s" and the answer rises in under it. The hand
 * opens it; R thinks again. With "Next one stops" on, that next one stops mid-thought: it keeps what it had and says
 * where it stopped.
 */
const LINES = [
  "Lisbon is on UTC+0 in November, New York on UTC−5 and Tokyo on UTC+9.",
  "A 9:00 start in New York is 14:00 in Lisbon and 23:00 in Tokyo: too late there.",
  "8:00 in New York is 13:00 in Lisbon and 22:00 in Tokyo, the latest a call there should run.",
];
const ANSWER = "Start at 8:00 in New York: it is 13:00 in Lisbon and 22:00 in Tokyo, inside everyone's day.";
const clock = () => Date.now();

type Run = { phase: "live" | "done" | "stopped"; n: number; began: number; ms: number };
const END: Run = { phase: "done", n: LINES.length, began: 0, ms: 7000 };

export default function ThinkingFoldDemo() {
  const stops = 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], off: less });
  const [run, setRun] = React.useState<Run>(END);
  const timers = React.useRef<number[]>([]);
  React.useEffect(() => () => timers.current.forEach(clearTimeout), []);

  const think = React.useCallback(
    (stop: boolean, instant: boolean) => {
      timers.current.forEach(clearTimeout);
      timers.current = [];
      const began = clock() - 4000;
      const at = (ms: number, f: () => void) => timers.current.push(window.setTimeout(f, ms));
      if (instant) {
        at(0, () => setRun(stop ? { phase: "stopped", n: 2, began, ms: 5700 } : { ...END, began }));
        return;
      }
      at(0, () => setRun({ phase: "live", n: 1, began, ms: 0 }));
      at(1000, () => setRun((r) => ({ ...r, n: 2 })));
      if (stop) {
        at(1700, () => setRun((r) => ({ ...r, phase: "stopped", ms: 5700 })));
        return;
      }
      at(2000, () => setRun((r) => ({ ...r, n: 3 })));
      at(3100, () => setRun((r) => ({ ...r, phase: "done", ms: 7000 })));
    },
    [],
  );
  /* the arrival: one think, or its end at once */
  const step = play.step;
  React.useEffect(() => {
    if (step === 0) think(false, less || settle);
  }, [step, think, less, settle]);

  const live = run.phase === "live";
  const text = LINES.slice(0, run.n).join("\n");
  return (
    <div
      ref={root}
      onPointerDownCapture={play.handOver}
      onKeyDownCapture={play.handOver}
      onKeyDown={(e) => {
        if (e.key !== "r" && e.key !== "R") return;
        if (e.metaKey || e.ctrlKey || e.altKey) return;
        e.preventDefault();
        think(stops, less);
      }}
      className="flex w-[min(100%,520px)] flex-col gap-2"
    >
      <ThinkingFold
        key={run.began}
        part={{ type: "reasoning", text, state: live ? "streaming" : "done", ...(run.phase === "done" ? { durationMs: run.ms } : {}) }}
        startedAt={run.phase === "live" ? run.began : undefined}
        interrupted={run.phase === "stopped"}
        stoppedNote="Stopped by you, before it found a time"
        labels={run.phase === "stopped" ? { stoppedNoTime: `Stopped thinking at ${Math.round(run.ms / 1000)} s` } : undefined}
      />
      <p className="m-0 min-h-[3lh] text-[length:var(--ns-text-body)] leading-[var(--ns-leading-prose)] text-[var(--ns-ink)]">
        {run.phase === "done" ? (
          <span key={run.began} className="block [animation:ns-rise_var(--ns-time-page)_var(--ns-ease)_both]">
            {ANSWER}
          </span>
        ) : run.phase === "stopped" ? (
          <span className="text-[var(--ns-ink-3)]">You stopped this reply.</span>
        ) : null}
      </p>
    </div>
  );
}
```

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `onFeedback` | `(e: FeedbackEvent) => void` |  | called once per move, for your sound or haptics |
| `part` | `ReasoningPart` |  | the reasoning part: streaming is live, done is finished |
| `startedAt` | `number` |  | when the thinking began (ms), for the live seconds |
| `steps` | `readonly ThinkingStep[]` |  | the steps it took |
| `interrupted` | `boolean` | `false` | the reply ended mid-thought |
| `stoppedNote` | `string` |  | where it stopped, under the thoughts |
| `open` | `boolean` |  | opened or folded (folded by default) |
| `onOpenChange` | `(open: boolean) => void` |  |  |
| `labels` | `Partial<ThinkingFoldLabels>` |  |  |

Full docs: https://notchset.dev/components/thinking-fold

## 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 the thinking |
| Arrow keys | scroll the opened thoughts |

## Performance

- A 1 s clock only while it thinks; the thoughts reveal through Stream text.
- No dependencies.

## Responsive

- phone and desktop
- dark (tokens)
- reduced motion: words swap, thoughts land whole, it opens at once

## Motion inventory

| Interaction | What moves |
|---|---|
| a new step's glyph drops into the row | ns-menu-in on --ns-time-spring, --ns-ease-spring. Reduced motion: it is there at once (motion-reduce). |
| each new thought fades in over the last in the one line | ns-fade on --ns-time-menu, --ns-ease (data-ns-still). Reduced motion: the line swaps. |
| "Thinking 7 s" settles into "Thought for 7 s" in place | Live label's crossfade. Reduced motion: the words swap. |
| it opens and folds on one spring | grid-template-rows on --ns-time-spring, --ns-ease-spring (data-ns-glide). Reduced motion: at once. |

## Accessibility contract (preserve when editing)
- One disclosure button (aria-expanded, aria-controls) whose name is its state's words; the opened thoughts are a named, focusable region that scrolls by keys.
- The current thought on the folded line is hidden from assistive tech (it is in the region); the reply announces itself, the fold never does.

## Install

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

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

### Manual

1. Install the packages: `npm install lucide-react@^1`.
2. Copy `components/ui/notchset/thinking-fold.tsx`, `lib/notchset/controllable.ts`, `components/ui/notchset/disclosure-parts.tsx`, `lib/notchset/feedback.ts`, `lib/notchset/icons.ts`, `lib/notchset/motion.ts`, `components/ui/notchset/stream-text-parts.tsx`, `lib/notchset/ui-message.ts`, `lib/notchset/words.ts` from https://notchset.dev/r/thinking-fold.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`, `live-label`.

## 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/thinking-fold.tsx

```tsx
// Notchset thinking-fold 1.2.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { ArrowLeftRight, ChevronDown, CircleCheck, FileText, Search, type LucideIcon } from "@/lib/notchset/icons";
import { cn } from "@/lib/utils";
import { disclosureTrigger } from "@/components/ui/notchset/disclosure-parts";
import { LiveLabel } from "@/components/ui/notchset/live-label";
import { StreamText } from "@/components/ui/notchset/stream-text-parts";
import { seconds, type ReasoningPart } from "@/lib/notchset/ui-message";
import { fill } from "@/lib/notchset/words";
import type { FeedbackProps } from "@/lib/notchset/feedback";

/*
 * Thinking fold: a reply's thinking, folded always. Live, one fixed line: "Thinking 7 s", a glyph a step taken (the
 * newest lit) and the current thought in ink-3, so nothing under it moves. Finished, "Thought for 7 s"; stopped, it
 * says where. Only the reader opens it.
 */
type ThinkingStepKind = "search" | "read" | "compare" | "check";
type ThinkingStep = { kind: ThinkingStepKind; text: string; /** from the start (ms) */ atMs?: number | undefined };
type ThinkingFoldLabels = { thinking: string; thought: string; thoughtNoTime: string; stopped: string; stoppedNoTime: string; answered: string } & Record<ThinkingStepKind, string>;
const THINKING_FOLD_LABELS: ThinkingFoldLabels = {
  thinking: "Thinking",
  thought: "Thought for {time}",
  thoughtNoTime: "Thought it through",
  stopped: "Stopped thinking at {time}",
  stoppedNoTime: "Stopped thinking",
  answered: "Answered",
  search: "searched",
  read: "read",
  compare: "compared",
  check: "checked",
};
const STEP_ICON: Readonly<Record<ThinkingStepKind, LucideIcon>> = { search: Search, read: FileText, compare: ArrowLeftRight, check: CircleCheck };
const COLS = "grid grid-cols-[2.75rem_1.25rem_1fr] gap-x-2";
const secs = (ms: number) => `${(ms / 1000).toFixed(1)} s`;
function Glyph({ kind, lit, className }: { kind: ThinkingStepKind; lit?: boolean; className?: string }) {
  const G = STEP_ICON[kind];
  return (
    <span aria-hidden className={cn("grid size-5 place-items-center rounded-full", lit ? "bg-[var(--ns-signal-wash)] text-[var(--ns-signal-ink)]" : "bg-[var(--ns-well)] text-[var(--ns-ink-2)]", className)}>
      <G className="size-3" strokeWidth={2} />
    </span>
  );
}
type ThinkingFoldProps = FeedbackProps & {
  /** the reasoning part: streaming is live, done is finished */
  part: ReasoningPart;
  /** when the thinking began (ms), for the live seconds */
  startedAt?: number | undefined;
  /** the steps it took */
  steps?: readonly ThinkingStep[] | undefined;
  /** the reply ended mid-thought */
  interrupted?: boolean | undefined;
  /** where it stopped, under the thoughts */
  stoppedNote?: string | undefined;
  /** opened or folded (folded by default) */
  open?: boolean | undefined;
  onOpenChange?: ((open: boolean) => void) | undefined;
  labels?: Partial<ThinkingFoldLabels> | undefined;
  className?: string | undefined;
};

/* the thinking, line by line */
const linesOf = (text: string) =>
  text
    .split(/\n+/)
    .map((l) => l.trim())
    .filter(Boolean);

function ThinkingFold({ part, steps, startedAt, interrupted = false, stoppedNote, open: openProp, onOpenChange, labels, className, onFeedback }: ThinkingFoldProps) {
  const L = { ...THINKING_FOLD_LABELS, ...labels };
  const live = part.state === "streaming" && !interrupted;
  const [own, setOwn] = React.useState(false);
  const open = openProp ?? own;
  const setOpen = (o: boolean) => (onFeedback?.(o ? "open" : "close"), onOpenChange ? onOpenChange(o) : setOwn(o));
  const id = React.useId();

  /* a 1 s clock while it thinks */
  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]);
  const ms = part.durationMs ?? (startedAt !== undefined && now !== null ? now - startedAt : undefined);
  const time = ms !== undefined ? seconds(ms) : undefined;
  const past = interrupted ? (time ? fill(L.stopped, { time }) : L.stoppedNoTime) : time ? fill(L.thought, { time }) : L.thoughtNoTime;

  const lines = steps ? steps.map((x) => x.text) : linesOf(part.text);
  const current = lines.at(-1) ?? "";
  const said = (["search", "read", "compare", "check"] as const)
    .map((k) => [k, steps?.filter((x) => x.kind === k).length] as const)
    .filter(([, n]) => n)
    .map(([k, n]) => `${L[k]} ${n}`)
    .join(", ");

  /* opened while live, it follows the newest unless scrolled up */
  const box = React.useRef<HTMLDivElement>(null);
  const follow = React.useRef(true);
  React.useEffect(() => {
    if (open) follow.current = true;
  }, [open]);
  React.useEffect(() => {
    const el = box.current;
    if (open && live && el && follow.current) el.scrollTop = el.scrollHeight;
  }, [open, live, part.text, lines.length]);

  return (
    <div data-slot="thinking-fold" data-state={live ? "live" : interrupted ? "interrupted" : "finished"} className={cn("flex min-w-0 flex-col", className)}>
      <button
        type="button"
        {...disclosureTrigger(open, id, () => setOpen(!open))}
        data-ns-press=""
        className="-ms-1 flex h-[var(--ns-control-sm)] min-w-0 cursor-pointer items-center gap-1.5 self-stretch rounded-[var(--ns-radius-sm)] px-1 text-start text-[length:var(--ns-text-small)] text-[var(--ns-ink-3)] outline-hidden [transition:color_var(--ns-time-color)] hover:text-[var(--ns-ink-2)] focus-visible:outline-2 focus-visible:outline-[var(--ns-signal)]"
      >
        <LiveLabel state={live ? "running" : "done"} present={live && time ? `${L.thinking} ${time}` : L.thinking} past={past} className="shrink-0 tabular-nums [&_[data-slot=live-label-past]]:[color:inherit]" />
        {steps && steps.length > 0 && (
          <span data-slot="thinking-fold-run" role="img" aria-label={said} className="flex shrink-0 items-center gap-0.5 ps-0.5">
            {steps.slice(0, 6).map((x, i) => (
              <Glyph key={i} kind={x.kind} lit={live && i === steps.length - 1} className="[--ns-menu-dy:0px] [animation:ns-menu-in_var(--ns-time-spring)_var(--ns-ease-spring)_backwards] motion-reduce:animate-none" />
            ))}
            {steps.length > 6 && (
              <span aria-hidden className={cn("ps-0.5 tabular-nums", live && "text-[var(--ns-signal-ink)]")}>
                +{steps.length - 6}
              </span>
            )}
          </span>
        )}
        <ChevronDown aria-hidden className={cn("size-3.5 shrink-0 [transition:rotate_var(--ns-time-color)]", open ? "rotate-180" : "-rotate-90 rtl:rotate-90")} />
        {/* the current thought, while live and folded */}
        {live && !open && current && (
          <span key={lines.length} data-slot="thinking-fold-now" data-ns-still="" aria-hidden className="min-w-0 truncate ps-1 [animation:ns-fade_var(--ns-time-menu)_var(--ns-ease)_both]">
            {current}
          </span>
        )}
      </button>
      <div data-ns-glide="" data-panel="" className={cn("grid [transition:grid-template-rows_var(--ns-time-spring)_var(--ns-ease-spring)]", open ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}>
        <div className="min-h-0 overflow-hidden" ref={(el) => void (el && (el.inert = !open))}>
          <div
            ref={box}
            id={id}
            role="region"
            aria-label={L.thinking}
            tabIndex={open ? 0 : -1}
            data-slot="thinking-fold-thoughts"
            onScroll={(e) => {
              const el = e.currentTarget;
              follow.current = el.scrollHeight - el.scrollTop - el.clientHeight < 8;
            }}
            className={cn(
              "overflow-y-auto overscroll-contain text-[length:var(--ns-text-small)] leading-[var(--ns-leading-prose)] text-[var(--ns-ink-2)] outline-hidden focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--ns-signal)]",
              steps ? "mt-1.5" : "mt-1 ms-1 border-s border-[var(--ns-line)] ps-3",
              live ? (steps ? "h-[9lh]" : "h-[7.5lh]") : "max-h-[16lh]",
            )}
          >
            {steps ? (
              <ol data-slot="thinking-fold-steps" className="m-0 list-none p-0">
                {steps.map((x, i) => (
                  <li key={i} className={COLS}>
                    <span className="pt-px text-end tabular-nums text-[var(--ns-ink-3)]">{x.atMs !== undefined && secs(x.atMs)}</span>
                    <span className="relative flex justify-center">
                      {i < steps.length - 1 && <span className="absolute top-5 bottom-0 w-px bg-[var(--ns-line)]" />}
                      <Glyph kind={x.kind} className="relative mt-0.5" />
                    </span>
                    <p className={cn("m-0 pb-2.5 [overflow-wrap:anywhere]", live && i === steps.length - 1 && "text-[var(--ns-ink-3)]")}>
                      <span className="sr-only">{L[x.kind]}: </span>
                      {x.text}
                    </p>
                  </li>
                ))}
                {!live && !interrupted && ms !== undefined && (
                  <li className={cn(COLS, "text-[var(--ns-ink-3)]")}>
                    <span className="text-end tabular-nums">{secs(ms)}</span>
                    <span />
                    {L.answered}
                  </li>
                )}
              </ol>
            ) : (
            <StreamText text={part.text} streaming={live}>
              {(shown) => (
                <div className="flex flex-col gap-1.5">
                  {linesOf(shown).map((l, i, all) => (
                    <p key={i} className={cn("m-0 [overflow-wrap:anywhere]", live && i === all.length - 1 && "text-[var(--ns-ink-3)]")}>
                      {l}
                    </p>
                  ))}
                </div>
              )}
            </StreamText>
            )}
          </div>
          {interrupted && stoppedNote && (
            <p data-slot="thinking-fold-stopped" className="m-0 mt-1.5 ms-1 ps-3 text-[length:var(--ns-text-small)] text-[var(--ns-ink-2)]">
              {stoppedNote}
            </p>
          )}
        </div>
      </div>
    </div>
  );
}

export { THINKING_FOLD_LABELS, ThinkingFold, type ThinkingFoldLabels, type ThinkingFoldProps, type ThinkingStep, type ThinkingStepKind };
```

### lib/notchset/controllable.ts

```tsx
// Notchset thinking-fold 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 thinking-fold 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 thinking-fold 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 thinking-fold 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/motion.ts

```tsx
// Notchset thinking-fold 1.2.0 · https://notchset.dev/changelog
"use client";
/*
 * Less motion, the one switch every piece reads, and a motion role's timing for a Web Animation. Split from
 * physics.ts so a piece that needs only these does not carry the springs.
 */
import * as React from "react";

/**
 * Less motion where `el` sits: the device's setting, then a data-motion="reduced" on `el` or any ancestor, falling
 * back to <html>'s when there is no element. The one copy: every piece reads this.
 */
const REDUCED = '[data-motion="reduced"],[data-motion="off"]';
export function lessMotion(el?: Element | null): boolean {
  if (typeof document === "undefined") return true;
  if (typeof matchMedia !== "undefined" && matchMedia("(prefers-reduced-motion: reduce)").matches) return true;
  return !!(el?.closest?.(REDUCED) ?? document.documentElement.matches(REDUCED));
}

/** Less motion, kept current as the setting changes; true on a server, so a piece starts in its still. */
export function useLessMotion(): boolean {
  return React.useSyncExternalStore(
    (f) => {
      if (typeof matchMedia === "undefined") return () => {};
      const q = matchMedia("(prefers-reduced-motion: reduce)");
      q.addEventListener("change", f);
      const mo = typeof MutationObserver === "undefined" ? null : new MutationObserver(f);
      mo?.observe(document.documentElement, { attributes: true, attributeFilter: ["data-motion"] });
      return () => {
        q.removeEventListener("change", f);
        mo?.disconnect();
      };
    },
    () => lessMotion(),
    () => true,
  );
}

/** A motion role's duration and curve (0 under less motion: the result at once), read from the foundation where `el` sits, for a Web Animation that glides
    something CSS can't transition (a width to `auto`, a node on its way out): `roleTiming(el, "--ns-time-menu")`. */
export function roleTiming(el: Element, time: string, ease = "--ns-ease"): KeyframeAnimationOptions {
  if (lessMotion(el)) return { duration: 0, easing: "linear" };
  const cs = getComputedStyle(el);
  const t = cs.getPropertyValue(time).trim();
  const ms = t.endsWith("ms") ? parseFloat(t) : parseFloat(t) * 1000;
  return { duration: Number.isFinite(ms) ? ms : 0, easing: cs.getPropertyValue(ease).trim() || "linear" };
}

/** The foundation's curves as literal strings, for a Web Animation (`element.animate`, `KeyframeEffect`,
    `updateTiming`): those take a literal easing and throw on a CSS var. Copied from foundation.css's `--ns-ease-*`;
    CSS transitions and keyframes keep the vars. */
export const EASE = {
  enter: "cubic-bezier(0.22, 1, 0.36, 1)",
  move: "cubic-bezier(.5, 0, .2, 1)",
  exit: "cubic-bezier(.6, 0, .9, .5)",
  panel: "cubic-bezier(0.32, 0.72, 0, 1)",
  press: "cubic-bezier(0.2, 0, 0, 1)",
  spring: "cubic-bezier(0.16, 1, 0.3, 1)",
  arrive: "cubic-bezier(.3, 1.22, .5, 1)",
  breathe: "cubic-bezier(.45, 0, .55, 1)",
} as const;
```

### components/ui/notchset/stream-text-parts.tsx

```tsx
// Notchset thinking-fold 1.2.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import { useLessMotion } from "@/lib/notchset/motion";

/*
 * Stream text: arrived words let out at their arrival rate, 3 to 8 at a time, each chunk only fading in. Settled
 * words never render again; streaming false lands every word. Less motion: a sentence at a time.
 */
type StreamTextProps = {
  /** all that arrived so far */
  text: string;
  /** more is coming; false lands the rest */
  streaming: boolean;
  /** the host's own drawing of the shown text; its words fade in */
  children?: ((shown: string) => React.ReactNode) | undefined;
  /** the sentence still arriving reads ink-3 until its full stop lands (default true; plain drawing only) */
  settle?: boolean | undefined;
  className?: string | undefined;
};

function ends(text: string, from: number, re: RegExp, n: number) {
  re.lastIndex = from;
  let end = from, count = 0;
  for (let m: RegExpExecArray | null; count < n && (m = re.exec(text)); count++) end = m.index + m[0].length;
  return { end, count };
}

function useReveal(text: string, streaming: boolean, less: boolean) {
  const [shown, setShown] = React.useState(text.length);
  const s = React.useRef({ text, shown: text.length, samples: [] as number[][], budget: 0, at: 0, landed: 0 });
  React.useEffect(() => {
    const st = s.current, t = performance.now();
    if (text.slice(0, st.shown) !== st.text.slice(0, st.shown)) st.shown = streaming ? 0 : text.length;
    if (text.length > st.text.length) st.samples.push([t, text.length]);
    st.samples = st.samples.filter(([at], i, all) => at! >= t - 2000 || i >= all.length - 2);
    st.text = text;
    if (!streaming) st.shown = text.length;
    setShown(st.shown);
    if (st.shown >= text.length) return void (st.budget = 0);
    let frame = 0;
    const step = () => {
      const t2 = performance.now(), [a, b] = [st.samples[0]!, st.samples.at(-1)!];
      /* the last 2 s of arrivals; a retry starts over; trail at most 1.2 s */
      const rate = Math.max(b[0]! > a[0]! ? (b[1]! - a[1]!) / (b[0]! - a[0]!) : 0, (st.text.length - st.shown) / 1200);
      st.budget += rate * Math.min(64, t2 - st.at);
      st.at = t2;
      /* ~0.2 s of words (3 to 8, fewer after 0.4 s); less motion: sentences */
      const n = less ? 1e9 : Math.max(3, Math.min(8, Math.round((rate * 200) / 6)));
      const next = ends(st.text, st.shown, less ? /[.!?…:]["')\]]*\s+|\n+/g : /\S+\s+/g, n);
      if (next.count && (less || ((next.count === n || t2 - st.landed > 400) && st.budget >= next.end - st.shown))) {
        st.budget = less ? 0 : Math.max(0, st.budget - (next.end - st.shown));
        st.shown = next.end;
        st.landed = t2;
        setShown(next.end);
      }
      if (st.shown < st.text.length) frame = requestAnimationFrame(step);
    };
    st.at = t;
    st.landed ||= t;
    frame = requestAnimationFrame(step);
    return () => cancelAnimationFrame(frame);
  }, [text, streaming, less]);
  return text.slice(0, shown);
}

const Word = React.memo(function Word({ w }: { w: string }) {
  return <span className="[animation:ns-fade_var(--ns-time-color)_var(--ns-ease)_backwards]">{w}</span>;
});

function words(node: React.ReactNode): React.ReactNode {
  return React.Children.map(node, (c) => {
    if (typeof c === "string") return c.match(/\s+|\S+\s*/g)?.map((w, i) => <Word key={i} w={w} />);
    if (React.isValidElement<{ children?: React.ReactNode }>(c) && typeof c.type === "string" && c.props.children != null) return React.cloneElement(c, undefined, words(c.props.children));
    return c;
  });
}

const plain = (shown: string) => shown;

/* a sentence ends at its stop (and any closing quote or bracket) followed by space or the end of what came */
const SENTENCE = /[\s\S]*?[.!?…]+["'’”)\]]*(?:\s+|$)|[\s\S]+$/g;

/** the shown text as sentences: each final once its stop has landed, the one still arriving ink-3 */
function sentences(shown: string, live: boolean): React.ReactNode {
  const parts = shown.match(SENTENCE) ?? [];
  return parts.map((t, i) => {
    const final = !live || i < parts.length - 1 || /[.!?…]["'’”)\]]*\s*$/.test(t);
    return (
      <span key={i} data-slot="stream-sentence" data-final={final || undefined} className={cn("[transition:color_600ms_var(--ns-ease)] motion-reduce:transition-none", !final && "text-[var(--ns-ink-3)]")}>
        {t}
      </span>
    );
  });
}

function StreamText({ text, streaming, children = plain, settle = true, className }: StreamTextProps) {
  const less = useLessMotion();
  const shown = useReveal(text, streaming, less);
  const [live, setLive] = React.useState(streaming);
  if (streaming && !live) setLive(true);
  /* a reply from history is drawn plainly; one that streamed here keeps its sentence spans, all final once it lands */
  const drawn = children === plain && settle && (live || streaming) ? sentences(shown, streaming || shown.length < text.length) : children(shown);
  const body = (live || streaming) && !less ? words(drawn) : drawn;
  const Tag = children === plain ? "span" : "div";
  return (
    <Tag data-slot="stream-text" className={cn(children === plain ? "whitespace-pre-wrap" : "contents", className)}>
      {body}
    </Tag>
  );
}

export { StreamText, type StreamTextProps };
```

### lib/notchset/ui-message.ts

```tsx
// Notchset thinking-fold 1.2.0 · https://notchset.dev/changelog
/*
 * The assistant's shared words and shapes (installs to lib/notchset/ui-message.ts with any piece that reads it).
 *
 * Messages are shaped like the AI SDK's UIMessage (an id, a role and parts: text, reasoning, tool-*, dynamic-tool,
 * source-url, source-document, file, step-start, data-*), defined here so a piece needs no runtime dependency: a buyer on the AI SDK passes its messages
 * straight in. The figures every piece shows (what answered, how much of a window is used, when it resets) are
 * worked out here, once, so the usage meter, the composer's line and the plan card can never read two ways
 * ("One name, one calculation").
 */
import { DEFAULT_LOCALE } from "@/lib/notchset/words";

/* ---------- messages ---------- */

export type TextPart = { type: "text"; text: string; state?: "streaming" | "done" | undefined };
export type ReasoningPart = { type: "reasoning"; text: string; state?: "streaming" | "done" | undefined; durationMs?: number | undefined };
/** A tool call, as the AI SDK names its states, approvals included. */
export type ToolState = "input-streaming" | "input-available" | "approval-requested" | "approval-responded" | "output-available" | "output-error" | "output-denied";
export type ToolPart = {
  type: `tool-${string}`;
  toolCallId: string;
  state: ToolState;
  input?: unknown;
  output?: unknown;
  errorText?: string | undefined;
  /** an output a later one replaces (progress) */
  preliminary?: boolean | undefined;
  approval?: { id: string; approved?: boolean | undefined; reason?: string | undefined } | undefined;
};
export type SourceUrlPart = { type: "source-url"; sourceId: string; url: string; title?: string | undefined };
export type FilePart = { type: "file"; mediaType: string; url: string; filename?: string | undefined };
/** A tool the host registered at run time (the AI SDK's dynamic tool): named by `toolName`, not by its type. */
export type DynamicToolPart = {
  type: "dynamic-tool";
  toolName: string;
  toolCallId: string;
  state: ToolState;
  input?: unknown;
  output?: unknown;
  errorText?: string | undefined;
  title?: string | undefined;
  preliminary?: boolean | undefined;
  approval?: { id: string; approved?: boolean | undefined; reason?: string | undefined } | undefined;
};
export type SourceDocumentPart = { type: "source-document"; sourceId: string; mediaType: string; title: string; filename?: string | undefined };
/** Where one model step began in a multi-step reply: a boundary the SDK writes, nothing to draw. */
export type StepStartPart = { type: "step-start" };
/** Provider-specific content and files the model reasoned with: carried through, not drawn. */
export type CustomPart = { type: "custom"; kind: `${string}.${string}` };
export type ReasoningFilePart = { type: "reasoning-file"; mediaType: string; url: string };
export type DataPart = { type: `data-${string}`; id?: string | undefined; data: unknown };
export type UIMessagePart = TextPart | ReasoningPart | ToolPart | DynamicToolPart | SourceUrlPart | SourceDocumentPart | FilePart | ReasoningFilePart | CustomPart | StepStartPart | DataPart;

export type UIMessage<M = unknown> = { id: string; role: "system" | "user" | "assistant"; parts: UIMessagePart[]; metadata?: M | undefined };

export const isToolPart = (p: UIMessagePart): p is ToolPart => p.type.startsWith("tool-");
/** A tool call as one shape: a dynamic tool becomes `tool-<its name>`; anything else that is not a tool is null. */
export const toolOf = (p: UIMessagePart): ToolPart | null => (isToolPart(p) ? p : p.type === "dynamic-tool" ? { ...p, type: `tool-${p.toolName}` } : null);
export const textOf = (m: Pick<UIMessage, "parts">) =>
  m.parts
    .filter((p): p is TextPart => p.type === "text")
    .map((p) => p.text)
    .join("");

/* ---------- what answered ---------- */

/** The purpose-named choices a picker offers (never "Auto"); each maps to a model and an effort in the adapter. */
export type ModelPurpose = "fast" | "balanced" | "deep" | "long";
export type ModelLine = {
  /** the purpose the person reads: "Balanced" */
  purpose: string;
  /** the model's own name, a second line: "Claude Sonnet 5.5" */
  name: string;
  effort?: "low" | "medium" | "high" | undefined;
  /** how long it thought before answering, when it did */
  thoughtForMs?: number | undefined;
  /** the purpose that was asked for, when another one answered ("Deep thinking was busy") */
  asked?: string | undefined;
  /** why another answered */
  fallbackReason?: string | undefined;
};

/** "14 s", "1 min 5 s": a duration a person reads. */
export function seconds(ms: number) {
  const s = Math.max(1, Math.round(ms / 1000));
  return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min${s % 60 ? ` ${s % 60} s` : ""}`;
}

/** The model line under every reply: "Balanced · thought for 9 s", or what answered in another's place. */
export function modelLineWords(m: ModelLine) {
  const lead = m.asked && m.asked !== m.purpose ? `Answered by ${m.purpose}; ${m.asked} ${m.fallbackReason ?? "wasn't available"}` : m.purpose;
  return m.thoughtForMs ? `${lead} · thought for ${seconds(m.thoughtForMs)}` : lead;
}

/* ---------- usage ---------- */

/** What is used of each window, as a share from 0 to 1, and when each resets. Null when nothing measures it. */
export type Usage = {
  window: number;
  week: number;
  windowResetsAt: string;
  weekResetsAt: string;
  /** what this window's use was spent on, each a share of the window (0 to 1): "Chat" 0.44, "Code" 0.12 */
  windowParts?: readonly { label: string; share: number }[] | undefined;
};

/** "4:10 pm" in the reader's own clock. */
export function clockTime(iso: string, locale?: string) {
  return new Date(iso).toLocaleTimeString(locale ?? DEFAULT_LOCALE, { hour: "numeric", minute: "2-digit" }).replace(/\s?([AP])M$/i, (_, a: string) => ` ${a.toLowerCase()}m`);
}

/** "today at 4:10 pm", "Monday", or a date further out. */
export function resetWords(iso: string, now: Date, locale?: string) {
  const at = new Date(iso);
  const days = Math.round((new Date(at.getFullYear(), at.getMonth(), at.getDate()).getTime() - new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime()) / 864e5);
  if (days <= 0) return clockTime(iso, locale);
  if (days === 1) return `tomorrow ${clockTime(iso, locale)}`;
  if (days < 7) return at.toLocaleDateString(locale ?? DEFAULT_LOCALE, { weekday: "long" });
  return at.toLocaleDateString(locale ?? DEFAULT_LOCALE, { month: "short", day: "numeric" });
}

/** The reset in a sentence: "at 4:10 pm", "tomorrow at 4:10 pm", "on Monday". */
export function resetPhrase(iso: string, now: Date, locale?: string) {
  const w = resetWords(iso, now, locale);
  return /^\d/.test(w) ? `at ${w}` : w.startsWith("tomorrow ") ? `tomorrow at ${w.slice(9)}` : `on ${w}`;
}

/** Where a figure stands against its limit: the same edges the Meter uses (75% warns, 100% is full). */
export type UsageLevel = "ok" | "near" | "full";

/**
 * Every usage figure the pieces show, from one calculation: each window's share used (a whole percent, rounded
 * down so "100%" only ever means full), its words, its reset, whether to warn (under 20% of the window left) and
 * whether the window is spent. Whichever window runs out first is the one that limits.
 */
export function usageFigures(u: Usage, now: Date, locale?: string) {
  const pct = (x: number) => Math.max(0, Math.min(100, Math.floor(x * 100)));
  const window = pct(u.window), week = pct(u.week);
  const level = (p: number): UsageLevel => (p >= 100 ? "full" : p >= 75 ? "near" : "ok");
  const windowReset = resetWords(u.windowResetsAt, now, locale), weekReset = resetWords(u.weekResetsAt, now, locale);
  const limiting = week >= 100 || (week > window && week >= 80) ? "week" : "window";
  const left = 100 - (limiting === "week" ? week : window);
  const reset = limiting === "week" ? weekReset : windowReset;
  return {
    window,
    week,
    windowLevel: level(window),
    weekLevel: level(week),
    windowLine: `${window}% used · resets ${windowReset}`,
    weekLine: `${week}% of this week · resets ${weekReset}`,
    limiting,
    left,
    reset,
    /** the reset in a sentence ("at 4:10 pm", "on Monday") */
    resetPhrase: resetPhrase(limiting === "week" ? u.weekResetsAt : u.windowResetsAt, now, locale),
    resetsAt: limiting === "week" ? u.weekResetsAt : u.windowResetsAt,
    /** under 20% left: the composer shows its quiet line */
    low: left < 20 && left > 0,
    atLimit: left <= 0,
    /** the composer's line, only when low or spent */
    composerLine: left <= 0 ? `${limiting === "week" ? "You've reached this week's limit" : "You've reached your limit for now"} · resets ${reset}` : `${left}% left${limiting === "week" ? " this week" : ""} · resets ${reset}`,
  };
}

/** How full a chat is against what the model can read at once, in words with no token talk (DEPTH 93). */
export function contextWords(share: number) {
  const p = Math.max(0, Math.min(100, Math.floor(share * 100)));
  if (p >= 90) return { pct: p, line: "This chat is very long: early messages may be left out. Start a new chat to keep answers sharp." };
  if (p >= 60) return { pct: p, line: "This chat is getting long: answers may miss early details." };
  return { pct: p, line: "Room to keep going in this chat." };
}
```

### lib/notchset/words.ts

```tsx
// Notchset thinking-fold 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.
