# Insight thread

> An analytics assistant’s thread: the queries it ran, sources with previews, an annotated chart of what dropped and when, and a composer with @table mentions.

One question about the data and its answer, laid out so the work shows. “Thought for 12 s · ran 3 queries” opens to the queries; the sources are chips that preview their columns; the chart draws each platform, the one that fell in red from the day a release shipped, its expected level dashed and the gap hatched with its size. The composer turns “@” into a menu of tables and the one picked into a token, picks the answer’s format, range and comparison, and streams the answer back with a small chart or table. Light and dark.

A React component by Bruno Delorence: https://brunodelorence.com/components/insight-thread. MIT License, Copyright (c) 2026 Bruno Delorence.

Category: AI.

## Anatomy

1. **Header**: The sparkle, the thread’s title, the model picker and Share, which copies a link to the thread.
2. **Model picker**: A menu button: each model says what it is for and how long it thinks; the next answer uses the one chosen.
3. **Question**: The question, right-aligned in a bubble; mentioned tables show as blue tokens.
4. **Thought**: How long the assistant thought and how many queries it ran. It opens to the queries, each with its rows and time.
5. **Sources**: A chip per table or doc the answer read; hovering or focusing one shows its columns or its lines.
6. **Annotated chart**: A line per series with a legend that turns them off, the expected level dashed, the gap hatched with its size, a release marker and values at the ends.
7. **Actions**: A suggested follow-up that asks itself when pressed, Copy, and a thumbs up.
8. **Composer**: One line that takes text and @table tokens; Enter sends, Backspace takes back the last token.
9. **Tools**: Mention a table, the answer’s format, its range and the comparison with last week, then dictation and Send.
10. **Send**: Off until there is a question; while an answer streams it turns into Stop.

## Properties

### Answer format (`defaultFormat`)

1. **Text**: The answer in words alone, with its sources. For a yes or no, or a single figure.
2. **Chart (default)**: A bar per category, red where it fell, ticked where it was last week.
3. **Table**: The figures in rows, with a coloured change column against last week.

Pick the form most questions here want: a chart to compare a few categories, a table when people copy the figures. It only sets where the format switch starts; people can change it before each question.

### Opening thread (`thread`)

1. **A thread (default)**: Opens on a question already answered, with its queries, sources and chart.
2. **Composer alone**: `null`: no header and no thread, only the composer, until the first question.

Pass a thread when people arrive from a finding, like a link to it or an alert. Pass `null` for a blank page where they start by asking.

## When to use

- An assistant that answers questions about a team’s data, where each answer has to show its work: the queries it ran and the tables and docs it read.
- A finding worth explaining in one place: the answer in a sentence, a chart annotated with what changed and when, and what to do next.
- Follow-up questions about the same data, where naming a table with @ keeps the assistant on the right source.
- Answers whose form the asker chooses: a sentence, a small chart or a table, over a range and against last week.

## When not to use

- A general chat assistant with no data behind it. The sources, queries and charts would stay empty; use a plain message list.
- A dashboard someone checks every day. Pin the chart to a dashboard; a thread is for one question and its follow-ups.
- Running or editing SQL by hand. Use a query editor with results; the thread shows queries, it does not let you change them.
- Long reports with many charts. Write a doc; past two or three charts, a thread is hard to scan.

### Placement and size

- **A panel or page of its own**, one thread at a time. The window grows to 760 px wide and centres itself in what is left.
- **Its layout answers to its container**, not the screen: at 560 px and under, the range shows its icon only and the gap label drops “vs expected”; at 400 px and under, the title gets a row of its own, with the picker and Share under it.
- **`maxHeight`** (560 px by default) is how tall the thread gets before it scrolls inside its own box, keeping its end in view. Set it to the room the panel has.

### Shaping an answer

- `answer` comes first: what changed, by how much and where, in a sentence or two.
- Then `chart` or `table`, never both: the table takes the chart’s place. Past one chart, a thread is hard to scan.
- Mark the change on the chart: `anomaly` turns a series red from the day it left its `expected` level and hatches the gap; `marker` names what happened that day.
- `followUp` goes under the chart with the why and what to do; `suggestion` is the next question, asked when pressed.
- List in `sources` every table or doc the answer read, and in `thought` the queries it ran, so the answer can be checked.

### New questions

- `onAsk` hears every question sent, with the tables it mentions and the format, range, comparison and model it was sent with. Run the question from there.
- The answers the thread writes back to new questions come from its own sample tables. Wire it to your data before it shows real figures.
- `tables` lists what “@” offers, with row counts; `models` fills the picker, the first one chosen.

### Chart vs. table

**Chart**
- For a change over time: a drop, a spike, the day it began.
- The anomaly, the expected level and the marker show at a glance what changed.
- Up to four or five series; past that the lines tangle.

**Table**
- For figures people compare or copy: plans, regions, versions.
- A change column coloured by direction, with its sign in the text.
- Fine for many rows; no shape over time.

## Do’s and don’ts

- **Do**: Title the thread with the finding in a few words: `Activation drop, last 14 days`.
- **Don’t**: Write the title as a sentence. Above 400 px it stays on one line and is cut off with an ellipsis before the model picker.
- **Do**: Open the answer with the figure that changed and where, then let the chart show it.
- **Don’t**: Put the reasoning above the chart. The finding sinks under it; the why belongs in the follow-up, under the chart.
- **Do**: Name the table with “@” when the data could come from more than one. It becomes a token, and the answer lists it first in its sources.
- **Don’t**: Ask about “it” with no metric, no range and no table. The assistant has to guess which data you mean.

## Content

Every piece of a thread is written to be read in order: the finding, the proof, then what to do.

- **The title**: the finding as a noun phrase, sentence case, no full stop: `Refund spike on Tuesday`.
- **The question**: as someone would ask it, with the metric and the time: `Why did activation drop last week?`
- **The answer**: the figures first, with the before and after: `Activation fell from 41% to 33%.`
- **The chart**: a title naming what is measured and how it is split (`Email verified, by platform`), a caption with the range, and a headline with the figure.
- **The marker**: what happened, in two or three words (`2.14 shipped`), with its date under it.
- **`describe`**: the chart in sentences for screen readers, with the figures a sighted reader would take from it.
- **The suggestion**: the next question, short enough for a chip: `Compare 2.13 vs 2.14`.
- **Sources**: the table or doc names as they are in your warehouse, so people can find them.

## Installation

Install it with the shadcn CLI, into components/insight-thread of any React project:

```sh
npx shadcn@latest add https://brunodelorence.com/r/insight-thread.json
```

Or add the registry to components.json once, as a namespace that coding agents and the shadcn MCP server search by name:

```json
{
  "registries": {
    "@brunodelorence": "https://brunodelorence.com/r/{name}.json"
  }
}
```

```sh
npx shadcn@latest add @brunodelorence/insight-thread
```

Or copy all the source files below into one folder of your project. Either way it needs React 19 and a bundler with CSS Modules (Next.js, Vite).

It has a dark colour scheme. Its colours are CSS light-dark() pairs, kept inside @supports so that builds which rewrite light-dark() for older browsers leave them alone: it follows your page’s color-scheme (light unless the page sets one) or its colorScheme prop, with nothing to configure. Browsers without light-dark() show it light.

## Usage

```tsx
import { InsightThread } from './insight-thread';

export function AskPage() {
  return (
    <InsightThread
      assistant="Wren"
      defaultFormat="chart"
      defaultRange="30d"
      onAsk={(question, options) => runQuestion(question, options)}
      autoplay={false}
    />
  );
}
```

## States

- **Answered**: The default: the question, the answer with its sources and chart, and the composer empty.
- **Queries open**: Thought for 12 s, opened: the three queries the answer rests on, with their rows and times.
- **Reading a day**: The crosshair on October 16: every series’ value that day, in a tooltip that flips sides past the middle.
- **Source preview**: The signups chip hovered or focused: its rows, how fresh it is and its columns.
- **Series turned off**: Android off in the legend: its line, the expected level, the gap and its label go with it.
- **Mentioning a table**: An “@” typed in the composer: the Tables menu with each table’s rows; the arrows move, Enter picks, Escape closes.
- **Question with a token**: signups picked: a blue token in the line, the rest of the question typed after it.
- **Model menu**: Three models, each with what it is for and how long it thinks.
- **Streaming**: A new answer halfway written, a caret at its end; Send has turned into Stop.
- **Answer with a chart**: The new answer done: its sources, bars for each channel with ticks where they were last week, Copy and a thumbs up.
- **Answer with a table**: The same question with Table chosen in the tools: the figures in rows, the change against last week coloured.
- **Phone**: At 390 px: the range shows its icon only, the gap label drops “vs expected”, and the tools wrap.

## Examples

### Table answer

A thread about churn answered with a table instead of a chart, and the composer set to answer new questions with tables too.

```tsx
import { CHURN, InsightThread } from './insight-thread';

/** A thread answered with a table, and new questions answered with tables too. */
export function TableAnswer() {
  return <InsightThread thread={CHURN} defaultFormat="table" autoplay={false} />;
}
```

### Still streaming

A breakdown by @signups channel asked a moment ago: the queries running, the answer halfway written, and Send turned into Stop.

```tsx
import { InsightThread } from './insight-thread';

/** A breakdown asked a moment ago, its answer halfway through streaming. */
export function StillStreaming() {
  return (
    <InsightThread
      autoplay={false}
      defaultState={{
        asked: { question: ['Break it down by', { table: 'signups' }, 'channel'], progress: 0.55 },
      }}
    />
  );
}
```

### Refund spike

A different anomaly: card refunds jump eighteen points over their expected level after a gateway timeout, so the gap and its label sit above the line.

```tsx
import { InsightThread, REFUNDS } from './insight-thread';

/** A different anomaly: card refunds jump over their expected level after a gateway timeout. */
export function RefundSpike() {
  return <InsightThread thread={REFUNDS} defaultRange="7d" autoplay={false} />;
}
```

### Composer only

No thread yet: the composer alone, answering in text. The first question grows a thread above it.

```tsx
import { InsightThread } from './insight-thread';

/** No thread yet: the composer alone, which grows a thread above it with the first question. */
export function ComposerOnly() {
  return <InsightThread thread={null} defaultFormat="text" maxHeight={420} autoplay={false} />;
}
```

## How it works

- The chart is SVG drawn in real px: a ResizeObserver reads its box, so the text never stretches and the labels are HTML over it. Each line is a run of cubic curves whose handles follow the neighbouring days. A series with an anomaly turns red from its first day off, a dashed line holds its expected level, and the gap between them is filled with a hatch pattern and labelled with its size in points.
- The values at the right end are sorted by height and pushed apart so none overlap. The release marker’s label goes under the lines, or over them when the lines run low, as in the refund spike.
- The crosshair follows the pointer (or the arrow keys, Home and End) to the nearest day: a dot on each series and a tooltip with the values, highest first, that flips to the left past the middle. The legend’s buttons turn series off, and the gap goes with its series.
- The composer is a line of parts: text, @table tokens, and the field being typed. A space or the start followed by “@” and letters opens the Tables menu, filtered by those letters; Enter or a press turns the match into a token. Backspace in the empty field takes back the last part whole.
- A question is answered from its words and the tables it mentions: a breakdown by channel, a comparison of versions, or activation by platform. The format picks bars, a table or text alone; the range dilutes the drop over a longer window; the comparison adds last week as ticks on the bars or a change column.
- The answer thinks for a moment, then streams two words at a time; Send turns into Stop meanwhile. Under reduced motion it comes all at once. The thread scrolls inside its own box and keeps its end in view.
- The model picker sets how long the next answer thinks and how many queries it runs. Share and Copy write to the clipboard; the thumbs up is a toggle.
- While on screen and untouched, a demo pointer opens the queries, reads the chart a day at a time, types “Break it down by @”, picks signups, types “channel” and sends. Any real input hands it over; it comes back after 9 s of quiet.

## API reference

- **thread** (`Thread | null`, default `ACTIVATION`): The conversation it opens on: title, question, the queries behind it, the answer, sources, a line chart or a table, the follow-up and a suggestion. null opens on the composer alone. ACTIVATION, REFUNDS and CHURN are exported.
- **assistant** (`string`, default `'Wren'`): The assistant’s name, in the composer’s placeholder and what it announces.
- **models** (`Model[]`, default `three`): The header’s model picker: name, a note and how long it thinks. The first is chosen.
- **tables** (`{ name: string; rows: string }[]`, default `four`): The tables “@” lists, with their row counts.
- **defaultFormat** (`'text' | 'chart' | 'table'`, default `'chart'`): How new answers come back at first.
- **defaultRange** (`'7d' | '30d' | '90d'`, default `'30d'`): The range new answers cover at first.
- **onAsk** (`(question: string, options) => void`): Called with each question sent, its mentioned tables, and the format, range, comparison and model it was sent with.
- **maxHeight** (`number`, default `560`): The thread’s height before it scrolls on its own, in px.
- **autoplay** (`boolean`, default `true`): While on screen and untouched, a demo pointer shows the main interactions. Any real input stops it.
- **defaultState** (`InsightThreadState`): Opens held in a moment (queries open, a day read, a menu open, a question half answered), with the demo off.
- **colorScheme** (`'light' | 'dark' | 'system'`): Light or dark colours, or the reader’s; without it, the page’s color-scheme.
- **className** (`string`): Classes for the stage.

## Accessibility

### Screen readers

- The thread is a section named by its title; each question and answer is an article named by its question, marked busy while its answer streams.
- A polite live region announces the answer once it is complete, not word by word, and says when a table is added to the question.

### The chart

- The chart says in words what it shows: its `describe` text is tied to the plot by `aria-describedby`.
- The plot takes the focus: the Left and Right arrows, Home and End read a day at a time into a live region, and Escape clears it. The legend’s buttons are `aria-pressed`.
- Colour is never the only sign of the change: the expected level is dashed, the gap is hatched and labelled with its size in points (WCAG 1.4.1, A).
- Every word, figure and end label is at least 4.5:1 against its surface in both schemes (WCAG 1.4.3, AA), and the lines, marks and switch track at least 3:1 (WCAG 1.4.11, AA).

### Keyboard

The composer’s field is a combobox: “@” opens a listbox of tables, the arrows move through it, Enter or Tab picks and Escape closes. Enter sends; Backspace in an empty field takes back the last part whole. The model and range menus move with the arrows, Home and End, and Escape closes them with the focus back on their button. The format is a radiogroup moved with the arrows; the comparison is a switch.

### Motion

Under reduced motion nothing slides, blinks or streams: an answer comes all at once, and the demo never plays. Otherwise the pointer over it holds the demo, and the first press, key or wheel stops it for good (WCAG 2.2.2, A).

### In this build

- The thread is a section named by its title; each question and answer is an article named by its question, busy while its answer streams. The answer is announced in a polite live region once it is complete, not word by word.
- The chart says in words what it shows. Its plot takes the focus: the arrow keys, Home and End read a day at a time into a live region, and Escape clears it. The legend’s buttons are aria-pressed.
- The source chips are buttons whose preview is a tooltip linked by aria-describedby, shown on hover and on focus and closed by Escape.
- The composer’s field is a combobox: “@” opens a listbox of tables, the arrows move aria-activedescendant, Enter or Tab picks and Escape closes. The model and range are menu buttons whose menus move with the arrows and close on Escape with the focus back on their button.
- The format is a radiogroup moved with the arrow keys; the comparison is a switch; dictation is a toggle button. Send is aria-disabled until there is a question, and becomes Stop while an answer streams.
- Under reduced motion nothing slides, blinks or streams and the demo never plays. The demo pointer is decorative.

## Source

### insight-thread/insight-thread.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useEffectEvent,
  useId,
  useLayoutEffect,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import { AnswerBars, AnswerTable, LineChart, chartX } from './charts';
import {
  ACTIVATION,
  MODELS,
  RANGES,
  TABLES,
  answerFor,
  type Answer,
  type Format,
  type Model,
  type Query,
  type RangeId,
  type Source,
  type Thread,
} from './data';
import { DemoPointer, runDemo, type Point } from './demo-pointer';
import { Icon, Sparkle, StopSquare, type IconName } from './glyphs';
import { Menu, MenuItem } from './menu';
import { useAutoplay } from './use-autoplay';
import styles from './insight-thread.module.css';

/*
 * Insight thread: an analytics assistant's conversation about one finding.
 *
 * - The header names the thread, picks the model (which sets how long new answers think) and
 *   copies a link to it.
 * - The thread opens on a question and its answer: a disclosure with the queries the assistant
 *   ran, the answer, its sources (chips with a preview on hover or focus), an annotated chart
 *   (charts.tsx) and a suggested follow-up.
 * - The composer writes the next question. "@" opens a menu of tables, and the one chosen becomes
 *   a token. The tools pick the answer's format (text, chart or table), its range and whether it
 *   compares with last week; a sent question gets an answer streamed word by word (all at once
 *   under reduced motion), with a small chart or table to match.
 * - While on screen and untouched, a demo pointer opens the queries, reads the chart, asks for a
 *   breakdown by @signups channel and sends it, in a loop. The pointer over it holds the demo;
 *   the first press, key or wheel stops it for good.
 */

export type {
  Answer,
  BarSpec,
  Format,
  LineChartSpec,
  Model,
  RangeId,
  Source,
  TableSpec,
  Thread,
} from './data';
export { ACTIVATION, CHURN, REFUNDS } from './data';

/** A piece of the composer's question: text, or a mentioned table. */
export type DraftPart = string | { table: string };

/** A moment to open in, held still: no demo. */
export type InsightThreadState = {
  /** The queries under "Thought for" shown. */
  thought?: boolean;
  /** The chart's crosshair on this day (its index). */
  hover?: number;
  /** A source's preview open, by its id. */
  source?: string;
  /** Series turned off in the legend. */
  hidden?: string[];
  /** A menu open. */
  menu?: 'model' | 'range';
  /** The composer: the question so far, and the text being typed (ending in "@" opens tables). */
  draft?: DraftPart[];
  input?: string;
  format?: Format;
  range?: RangeId;
  compare?: boolean;
  /** A question already sent: answered, or held part-way through its answer (progress under 1). */
  asked?: { question: DraftPart[]; progress?: number };
};

type Phase = 'thinking' | 'writing' | 'done' | 'stopped';
type Turn = {
  id: number;
  parts: DraftPart[];
  answer: Answer;
  seconds: number;
  phase: Phase;
  /** How many words of the answer show. */
  shown: number;
  /** Held part-way by defaultState: the stream does not run. */
  held?: boolean;
};
type MenuState = { id: 'model' | 'range'; anchor: HTMLElement; byReader: boolean };

const FORMATS: { id: Format; label: string; icon: IconName }[] = [
  { id: 'text', label: 'Answer in text', icon: 'lines' },
  { id: 'chart', label: 'Answer with a chart', icon: 'bars' },
  { id: 'table', label: 'Answer with a table', icon: 'table' },
];

const words = (text: string) => text.split(/(?<=\s)/);
const textOf = (parts: DraftPart[]) =>
  parts
    .map((part) => (typeof part === 'string' ? part : `@${part.table}`))
    .join(' ')
    .replace(/\s+/g, ' ')
    .trim();
const tablesOf = (parts: DraftPart[]) =>
  parts.flatMap((part) => (typeof part === 'string' ? [] : [part.table]));
/** "@" at the end of what is typed, after a space or at the start, and the letters after it. */
const MENTION = /(^|\s)@(\w*)$/;

const DEMO_QUESTION = 'Break it down by @';
const DEMO_AFTER = 'channel';

export function InsightThread({
  thread = ACTIVATION,
  assistant = 'Wren',
  models = MODELS,
  tables = TABLES,
  defaultFormat = 'chart',
  defaultRange = '30d',
  onAsk,
  maxHeight = 560,
  autoplay = true,
  defaultState,
  colorScheme,
  className = '',
}: {
  /** The conversation it opens on; null opens on the composer alone. */
  thread?: Thread | null;
  /** The assistant's name, in the composer's placeholder and the messages. */
  assistant?: string;
  /** The models the header's picker offers; the first is chosen. */
  models?: Model[];
  /** The tables "@" lists, with their row counts. */
  tables?: { name: string; rows: string }[];
  defaultFormat?: Format;
  defaultRange?: RangeId;
  /** Called with each question sent, and the options it was sent with. */
  onAsk?: (
    question: string,
    options: { tables: string[]; format: Format; range: RangeId; compare: boolean; model: string },
  ) => void;
  /** The thread's height before it scrolls on its own, in px. */
  maxHeight?: number;
  autoplay?: boolean;
  /** Opens in a given moment, held still (no demo). */
  defaultState?: InsightThreadState;
  colorScheme?: 'light' | 'dark' | 'system';
  className?: string;
}) {
  const uid = useId();
  const { ref: root, playing, reduced, take, pause } = useAutoplay<HTMLDivElement>(9000);
  const pointer = useRef<HTMLSpanElement>(null);
  const scroller = useRef<HTMLDivElement>(null);
  const field = useRef<HTMLInputElement>(null);
  const composer = useRef<HTMLDivElement>(null);
  const held = defaultState !== undefined;
  const start = defaultState ?? {};

  const [model, setModel] = useState<Model>(models[0]);
  const [menu, setMenu] = useState<MenuState | null>(null);
  const [thoughtOpen, setThoughtOpen] = useState(Boolean(start.thought));
  const [openTurns, setOpenTurns] = useState<Set<number>>(new Set());
  const [hover, setHover] = useState<number | null>(start.hover ?? null);
  const [hidden, setHidden] = useState<string[]>(start.hidden ?? []);
  const [source, setSource] = useState<string | null>(start.source ? `base:${start.source}` : null);
  const [draft, setDraft] = useState<DraftPart[]>(start.draft ?? []);
  const [input, setInput] = useState(start.input ?? '');
  const [dismissed, setDismissed] = useState(false);
  const [active, setActive] = useState(0);
  const [mentionLeft, setMentionLeft] = useState(0);
  const [format, setFormat] = useState<Format>(start.format ?? defaultFormat);
  const [range, setRange] = useState<RangeId>(start.range ?? defaultRange);
  const [compare, setCompare] = useState(start.compare ?? true);
  const [listening, setListening] = useState(false);
  const [liked, setLiked] = useState<Set<string>>(new Set());
  const [copied, setCopied] = useState<string | null>(null);
  const [message, setMessage] = useState('');
  const [turns, setTurns] = useState<Turn[]>(() => {
    if (!start.asked) return [];
    const question = start.asked.question;
    const answer = answerFor({
      question: textOf(question),
      mentions: tablesOf(question),
      format: start.format ?? defaultFormat,
      range: start.range ?? defaultRange,
      compare: start.compare ?? true,
      model: models[0],
    });
    const total = words(answer.text).length;
    const progress = start.asked.progress ?? 1;
    return [
      {
        id: 1,
        parts: question,
        answer,
        seconds: models[0].seconds,
        phase: progress >= 1 ? 'done' : progress <= 0 ? 'thinking' : 'writing',
        shown: Math.round(total * Math.min(1, progress)),
        held: progress < 1,
      },
    ];
  });

  // A menu held open by defaultState: its anchor is found once the tools are drawn.
  useLayoutEffect(() => {
    if (!start.menu) return;
    const anchor = root.current?.querySelector<HTMLElement>(`[data-demo="${start.menu}"]`);
    if (anchor) setMenu({ id: start.menu, anchor, byReader: false });
    // Only on the first draw.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const say = (text: string) => setMessage(text);

  // ---- The @ menu --------------------------------------------------------------------------------

  const match = input.match(MENTION);
  const query = match ? match[2].toLowerCase() : '';
  const options = match ? tables.filter((table) => table.name.includes(query)) : [];
  const mentionOpen = Boolean(match) && !dismissed;
  const current = Math.min(active, Math.max(0, options.length - 1));

  useLayoutEffect(() => {
    const box = composer.current;
    const at = field.current;
    if (!mentionOpen || !box || !at) return;
    const scale = box.getBoundingClientRect().width / box.offsetWidth || 1;
    const left = (at.getBoundingClientRect().left - box.getBoundingClientRect().left) / scale;
    setMentionLeft(Math.max(8, Math.min(left - 8, box.offsetWidth - 268)));
  }, [mentionOpen, draft.length]);

  const choose = (name: string, focus: boolean) => {
    const found = input.match(MENTION);
    const before = found ? input.slice(0, (found.index ?? 0) + found[1].length) : input;
    setDraft((now) => [...now, ...(before.trim() ? [before] : []), { table: name }]);
    setInput('');
    setActive(0);
    say(`Table ${name} added to the question`);
    if (focus) field.current?.focus();
  };

  // ---- Asking ------------------------------------------------------------------------------------

  const live = turns.find((turn) => turn.phase === 'thinking' || turn.phase === 'writing');
  const canSend = Boolean(textOf([...draft, input])) && !live;

  const ask = (parts: DraftPart[]) => {
    const question = textOf(parts);
    if (!question || live) return;
    const mentions = tablesOf(parts);
    const answer = answerFor({ question, mentions, format, range, compare, model });
    const total = words(answer.text).length;
    const turn: Turn = {
      id: Date.now(),
      parts,
      answer,
      seconds: model.seconds,
      phase: reduced ? 'done' : 'thinking',
      shown: reduced ? total : 0,
    };
    setTurns((now) => [...now, turn]);
    say(reduced ? `${assistant} answered: ${answer.text}` : `${assistant} is thinking`);
    onAsk?.(question, { tables: mentions, format, range, compare, model: model.id });
  };

  const send = () => {
    if (!canSend) return;
    ask([...draft, ...(input.trim() ? [input] : [])]);
    setDraft([]);
    setInput('');
    setDismissed(false);
  };

  const stop = () => {
    if (!live) return;
    setTurns((now) =>
      now.map((turn) => (turn.id === live.id ? { ...turn, phase: 'stopped' } : turn)),
    );
    say('Answer stopped');
  };

  // The stream: a pause to think, then two words at a time.
  useEffect(() => {
    if (!live || live.held) return;
    const total = words(live.answer.text).length;
    const timer = window.setTimeout(
      () => {
        setTurns((now) =>
          now.map((turn) => {
            if (turn.id !== live.id) return turn;
            if (turn.phase === 'thinking') return { ...turn, phase: 'writing' };
            const shown = Math.min(total, turn.shown + 2);
            return { ...turn, shown, phase: shown >= total ? 'done' : 'writing' };
          }),
        );
        if (live.phase === 'writing' && live.shown + 2 >= total)
          say(`${assistant} answered: ${live.answer.text}`);
      },
      live.phase === 'thinking' ? 1100 : 42,
    );
    return () => window.clearTimeout(timer);
  }, [live, assistant]);

  // New words keep the end of the thread in view.
  useEffect(() => {
    const box = scroller.current;
    if (box && turns.length) box.scrollTop = box.scrollHeight;
  }, [turns.length, live?.shown, live?.phase]);

  // Dictation: listens a moment, then writes what it heard.
  useEffect(() => {
    if (!listening) return;
    const timer = window.setTimeout(() => {
      setInput(
        (now) => `${now.trim() ? `${now.trim()} ` : ''}How many Android sign-ups did 2.14 cost us?`,
      );
      setListening(false);
      say('Dictation added to the question');
    }, 1800);
    return () => window.clearTimeout(timer);
  }, [listening]);

  useEffect(() => {
    if (!copied) return;
    const timer = window.setTimeout(() => setCopied(null), 1600);
    return () => window.clearTimeout(timer);
  }, [copied]);

  const copy = (key: string, text: string, done: string) => {
    navigator.clipboard?.writeText(text).catch(() => {});
    setCopied(key);
    say(done);
  };

  const openMenu = (id: MenuState['id'], anchor: HTMLElement, byReader = true) =>
    setMenu((now) => (now?.id === id ? null : { id, anchor, byReader }));
  const closeMenu = (back: boolean) => {
    if (back) menu?.anchor.focus();
    setMenu(null);
  };

  const toggleSeries = (id: string) => {
    const name = thread?.chart?.series.find((s) => s.id === id)?.name ?? id;
    setHidden((now) => {
      const off = now.includes(id);
      say(`${name} ${off ? 'shown' : 'hidden'}`);
      return off ? now.filter((x) => x !== id) : [...now, id];
    });
  };

  // ---- The composer's keys -----------------------------------------------------------------------

  const onFieldKey = (event: ReactKeyboardEvent<HTMLInputElement>) => {
    if (mentionOpen) {
      if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
        event.preventDefault();
        if (options.length)
          setActive(
            (current + (event.key === 'ArrowDown' ? 1 : -1) + options.length) % options.length,
          );
        return;
      }
      if ((event.key === 'Enter' || event.key === 'Tab') && options.length) {
        event.preventDefault();
        choose(options[current].name, true);
        return;
      }
      if (event.key === 'Escape') {
        event.preventDefault();
        event.stopPropagation();
        setDismissed(true);
        return;
      }
    }
    if (event.key === 'Enter') {
      event.preventDefault();
      send();
    } else if (event.key === 'Backspace' && input === '' && draft.length) {
      // Back over a token removes it; back over text brings it into the field.
      event.preventDefault();
      const last = draft[draft.length - 1];
      setDraft((now) => now.slice(0, -1));
      if (typeof last === 'string') setInput(last);
      else say(`Table ${last.table} removed`);
    }
  };

  const onFormatKey = (event: ReactKeyboardEvent) => {
    const step =
      event.key === 'ArrowRight' || event.key === 'ArrowDown'
        ? 1
        : event.key === 'ArrowLeft' || event.key === 'ArrowUp'
          ? -1
          : 0;
    if (!step) return;
    event.preventDefault();
    const index = FORMATS.findIndex((f) => f.id === format);
    const next = FORMATS[(index + step + FORMATS.length) % FORMATS.length];
    setFormat(next.id);
    const group = event.currentTarget.parentElement;
    group?.querySelector<HTMLElement>(`[data-format="${next.id}"]`)?.focus();
  };

  // ---- The demo ----------------------------------------------------------------------------------

  const demo = autoplay && playing && !held;
  const dirty = useEffectEvent(
    () =>
      thoughtOpen ||
      turns.length > 0 ||
      draft.length > 0 ||
      input !== '' ||
      hover !== null ||
      hidden.length > 0,
  );
  const reset = useEffectEvent(() => {
    setThoughtOpen(false);
    setTurns([]);
    setDraft([]);
    setInput('');
    setDismissed(false);
    setHover(null);
    setHidden([]);
    setMenu(null);
    setSource(null);
    scroller.current?.scrollTo({ top: 0 });
  });
  const demoType = useEffectEvent((text: string) => {
    setInput(text);
    setDismissed(false);
  });
  const demoHover = useEffectEvent((index: number | null) => setHover(index));
  const demoClear = useEffectEvent(() => {
    setMenu(null);
    setHover(null);
  });
  const days = thread?.chart?.days.length ?? 0;

  useEffect(() => {
    const stage = root.current;
    const arrow = pointer.current;
    if (!demo || !stage || !arrow) return;
    const find = (name: string) => stage.querySelector<HTMLElement>(`[data-demo="${name}"]`);
    const on = (element: Element | null, fx = 0.5, fy = 0.5): Point => {
      const frame = stage.getBoundingClientRect();
      const scale = frame.width / stage.offsetWidth || 1;
      const rect = element?.getBoundingClientRect() ?? frame;
      return {
        x: (rect.left + rect.width * fx - frame.left) / scale,
        y: (rect.top + rect.height * fy - frame.top) / scale,
      };
    };
    let over: HTMLElement | null = null;
    const stop = runDemo(stage, arrow, async ({ wait, glide, glyph }) => {
      /** Scrolls the thread so the element shows, `at` of the way down its box. */
      const reveal = async (element: HTMLElement, at = 0.3) => {
        const box = scroller.current;
        if (!box || !box.contains(element)) return;
        const b = box.getBoundingClientRect();
        const r = element.getBoundingClientRect();
        if (r.top >= b.top && r.bottom <= b.bottom) return;
        box.scrollTo({ top: box.scrollTop + r.top - b.top - b.height * at, behavior: 'smooth' });
        await wait(520);
      };
      const press = async (name: string, ms: number, after: number, fx = 0.5, fy = 0.5) => {
        const element = find(name);
        if (!element) return;
        await reveal(element);
        glyph('arrow');
        await glide(on(element, fx, fy), ms);
        glyph('hand');
        over = element;
        element.dataset.over = '';
        await wait(240);
        const target = find(name) ?? element;
        delete element.dataset.over;
        over = null;
        target.click();
        await wait(after);
      };
      const type = async (text: string, from = '') => {
        for (let i = 1; i <= text.length; i += 1) {
          demoType(from + text.slice(0, i));
          await wait(text[i - 1] === ' ' ? 90 : 55);
        }
      };
      for (;;) {
        if (dirty()) {
          reset();
          await wait(500);
        }
        await wait(900);
        // What it ran to get there.
        await press('thought', 750, 1500, 0.2);
        // Read the chart, a day at a time.
        const plot = find('plot');
        if (plot && days) {
          await reveal(plot, 0.1);
          glyph('arrow');
          for (const day of [2, 6, 8, 10, days - 1]) {
            await glide(
              on(plot, chartX(plot.clientWidth, day, days) / plot.clientWidth, 0.45),
              520,
            );
            demoHover(day);
            await wait(day === days - 1 ? 1300 : 650);
          }
          demoHover(null);
        }
        // Ask for a breakdown by a table's column.
        await press('input', 800, 200, 0.2);
        await type(DEMO_QUESTION);
        await wait(700);
        await press('mention-signups', 600, 400, 0.3);
        await type(DEMO_AFTER);
        await wait(500);
        await press('send', 650, 4200);
        glyph('arrow');
        await glide(on(stage, 0.82, 0.94), 800);
        await wait(2200);
      }
    });
    return () => {
      stop();
      if (over) delete over.dataset.over;
      demoClear();
    };
  }, [demo, root, days]);

  // ---- Drawing -----------------------------------------------------------------------------------

  const bare = thread === null && turns.length === 0;
  const title = thread?.title ?? (turns[0] ? textOf(turns[0].parts) : 'New question');
  const rangeInfo = RANGES.find((r) => r.id === range)!;

  const sources = (key: string, list: Source[]) => (
    <ul className={styles.sources} aria-label="Sources" data-part="sources">
      {list.map((s) => {
        const id = `${key}:${s.id}`;
        const open = source === id;
        return (
          <li key={s.id} className={styles.sourceItem}>
            <button
              type="button"
              className={styles.source}
              data-demo={`source-${s.id}`}
              aria-describedby={open ? `${uid}-${id}` : undefined}
              onPointerEnter={(event) => {
                if (event.pointerType !== 'touch') setSource(id);
              }}
              onPointerLeave={(event) => {
                if (event.pointerType !== 'touch') setSource(null);
              }}
              onFocus={() => setSource(id)}
              onBlur={() => setSource(null)}
              onClick={() => setSource(id)}
              onKeyDown={(event) => {
                if (event.key === 'Escape' && open) {
                  event.stopPropagation();
                  setSource(null);
                }
              }}
            >
              <Icon name={s.kind === 'doc' ? 'doc' : 'table'} className={styles.sourceIcon} />
              {s.name}
            </button>
            {open && (
              <span
                role="tooltip"
                id={`${uid}-${id}`}
                className={styles.preview}
                data-part="source-preview"
              >
                <span className={styles.previewHead}>
                  <Icon name={s.kind === 'doc' ? 'doc' : 'table'} className={styles.sourceIcon} />
                  <b>{s.name}</b>
                </span>
                <span className={styles.previewMeta}>{s.meta}</span>
                {s.kind === 'table' ? (
                  <span className={styles.previewColumns}>
                    {s.lines.map((column) => (
                      <code key={column}>{column}</code>
                    ))}
                  </span>
                ) : (
                  s.lines.map((line) => (
                    <span key={line} className={styles.previewLine}>
                      {line}
                    </span>
                  ))
                )}
              </span>
            )}
          </li>
        );
      })}
    </ul>
  );

  const thought = (
    key: string,
    seconds: number,
    queries: Query[],
    open: boolean,
    onToggle: () => void,
    running = false,
    demo?: string,
  ) => (
    <div className={styles.thought} data-part="thought">
      <button
        type="button"
        className={styles.thoughtToggle}
        aria-expanded={open}
        aria-controls={`${uid}-${key}-queries`}
        data-demo={demo}
        onClick={onToggle}
      >
        <Icon name="chevronRight" className={styles.thoughtChevron} width={2} />
        {running ? (
          <span className={styles.thinking}>
            Thinking · running {queries.length} {queries.length === 1 ? 'query' : 'queries'}
          </span>
        ) : (
          <span>
            Thought for {seconds} s · ran {queries.length}{' '}
            {queries.length === 1 ? 'query' : 'queries'}
          </span>
        )}
      </button>
      <ol id={`${uid}-${key}-queries`} className={styles.queries} hidden={!open}>
        {queries.map((q, i) => (
          <li key={i} className={styles.query} data-running={running || undefined}>
            <Icon name="query" className={styles.queryIcon} />
            <code className={styles.sql}>{q.sql}</code>
            <span className={styles.queryRows}>
              {running ? 'running' : `${q.rows} · ${q.ms} ms`}
            </span>
          </li>
        ))}
      </ol>
    </div>
  );

  const actions = (key: string, text: string, suggestion?: string) => (
    <div className={styles.actions} data-part="actions">
      {suggestion && (
        <button
          type="button"
          className={styles.suggestion}
          data-demo="suggestion"
          disabled={Boolean(live)}
          onClick={() => ask([suggestion])}
        >
          <Sparkle className={styles.suggestionSpark} />
          {suggestion}
        </button>
      )}
      <span className={styles.actionsEnd}>
        <button
          type="button"
          className={styles.iconButton}
          aria-label={copied === key ? 'Copied' : 'Copy answer'}
          title="Copy answer"
          onClick={() => copy(key, text, 'Answer copied')}
        >
          <Icon name={copied === key ? 'check' : 'copy'} className={styles.icon} />
        </button>
        <button
          type="button"
          className={styles.iconButton}
          aria-label="Good answer"
          title="Good answer"
          aria-pressed={liked.has(key)}
          onClick={() =>
            setLiked((now) => {
              const next = new Set(now);
              if (next.has(key)) next.delete(key);
              else next.add(key);
              say(next.has(key) ? 'Marked as a good answer' : 'Mark removed');
              return next;
            })
          }
        >
          <Icon name="thumb" className={styles.icon} />
        </button>
      </span>
    </div>
  );

  const bubble = (parts: DraftPart[]) => (
    <p className={styles.bubble} data-part="question">
      {parts.map((part, i) => (
        <span key={i}>
          {i > 0 && ' '}
          {typeof part === 'string' ? (
            part.trim()
          ) : (
            <span className={styles.token}>@{part.table}</span>
          )}
        </span>
      ))}
    </p>
  );

  return (
    <div
      ref={root}
      className={`${styles.root} ${className}`}
      data-part="stage"
      data-bare={bare || undefined}
      data-color-scheme={colorScheme}
      style={{ '--thread-max': `${maxHeight}px` } as CSSProperties}
      onPointerDownCapture={take}
      onKeyDownCapture={take}
      onWheel={take}
      onPointerMove={(event) => {
        if (event.pointerType !== 'touch') pause();
      }}
    >
      <section
        className={styles.window}
        data-part="window"
        aria-label={bare ? `Ask ${assistant}` : undefined}
        aria-labelledby={bare ? undefined : `${uid}-title`}
      >
        {!bare && (
          <header className={styles.header} data-part="header">
            <Sparkle className={styles.headSpark} />
            <h2 id={`${uid}-title`} className={styles.title}>
              {title}
            </h2>
            <button
              type="button"
              className={styles.picker}
              aria-haspopup="menu"
              aria-expanded={menu?.id === 'model'}
              aria-label={`Model: ${model.name}`}
              data-demo="model"
              data-part="model-picker"
              onClick={(event) => openMenu('model', event.currentTarget)}
            >
              <span>{model.name}</span>
              <Icon name="chevronDown" className={styles.chevron} width={2} />
            </button>
            <button
              type="button"
              className={styles.iconButton}
              aria-label={copied === 'share' ? 'Link copied' : 'Share thread'}
              title="Share thread"
              data-part="share"
              onClick={() => copy('share', window.location.href, 'Link to the thread copied')}
            >
              <Icon name={copied === 'share' ? 'check' : 'share'} className={styles.icon} />
            </button>
          </header>
        )}

        {!bare && (
          <div ref={scroller} className={styles.scroller} data-part="thread">
            {thread && (
              <article className={styles.turn} aria-label={thread.question}>
                {bubble([thread.question])}
                {thread &&
                  thought(
                    'base',
                    thread.thought.seconds,
                    thread.thought.queries,
                    thoughtOpen,
                    () => setThoughtOpen((open) => !open),
                    false,
                    'thought',
                  )}
                <p className={styles.answer}>{thread.answer}</p>
                {sources('base', thread.sources)}
                {thread.chart && (
                  <LineChart
                    spec={thread.chart}
                    hidden={hidden}
                    onToggle={toggleSeries}
                    hover={hover}
                    onHover={setHover}
                  />
                )}
                {thread.table && <AnswerTable spec={thread.table} />}
                <p className={styles.answer}>{thread.followUp}</p>
                {actions('base', `${thread.answer}\n\n${thread.followUp}`, thread.suggestion)}
              </article>
            )}

            {turns.map((turn) => {
              const all = words(turn.answer.text);
              const writing = turn.phase === 'writing';
              const finished = turn.phase === 'done';
              const text = all.slice(0, turn.shown).join('');
              return (
                <article
                  key={turn.id}
                  className={styles.turn}
                  data-part="new-turn"
                  aria-label={textOf(turn.parts)}
                  aria-busy={!finished && turn.phase !== 'stopped'}
                >
                  {bubble(turn.parts)}
                  {thought(
                    String(turn.id),
                    turn.seconds,
                    turn.answer.queries,
                    openTurns.has(turn.id),
                    () =>
                      setOpenTurns((now) => {
                        const next = new Set(now);
                        if (next.has(turn.id)) next.delete(turn.id);
                        else next.add(turn.id);
                        return next;
                      }),
                    turn.phase === 'thinking',
                  )}
                  {(text || writing) && (
                    <p className={styles.answer} data-part="streaming">
                      {text}
                      {writing && <span className={styles.caret} aria-hidden="true" />}
                    </p>
                  )}
                  {turn.phase === 'stopped' && (
                    <p className={styles.stopped}>Stopped before the end of the answer.</p>
                  )}
                  {finished && (
                    <div className={styles.reveal}>
                      {sources(String(turn.id), turn.answer.sources)}
                      {turn.answer.bars && <AnswerBars spec={turn.answer.bars} />}
                      {turn.answer.table && <AnswerTable spec={turn.answer.table} />}
                      {actions(String(turn.id), turn.answer.text)}
                    </div>
                  )}
                </article>
              );
            })}
          </div>
        )}

        <div ref={composer} className={styles.composer} data-part="composer">
          {/* A press anywhere in the box writes in the field. */}
          <div
            className={styles.field}
            onClick={(event) => {
              if (event.detail > 0 && event.target === event.currentTarget) field.current?.focus();
            }}
          >
            {draft.map((part, i) =>
              typeof part === 'string' ? (
                <span key={i} className={styles.draftText}>
                  {part}
                </span>
              ) : (
                <span key={i} className={styles.token} data-part="token">
                  @{part.table}
                </span>
              ),
            )}
            <input
              ref={field}
              className={styles.input}
              value={input}
              placeholder={draft.length ? '' : `Ask ${assistant} · @ for a table`}
              aria-label={`Ask ${assistant}${draft.length ? `: ${textOf(draft)}` : ''}`}
              role="combobox"
              aria-autocomplete="list"
              aria-expanded={mentionOpen}
              aria-controls={`${uid}-tables`}
              aria-activedescendant={
                mentionOpen && options.length ? `${uid}-table-${current}` : undefined
              }
              data-demo="input"
              autoComplete="off"
              spellCheck={false}
              onChange={(event) => {
                setInput(event.target.value);
                setDismissed(false);
                setActive(0);
              }}
              onKeyDown={onFieldKey}
              onBlur={() => setDismissed(true)}
              onFocus={() => setDismissed(false)}
            />
          </div>

          <div
            className={styles.mention}
            data-part="mention-menu"
            hidden={!mentionOpen}
            style={{ left: mentionLeft }}
          >
            <p className={styles.mentionHead} id={`${uid}-tables-label`}>
              Tables
            </p>
            <ul role="listbox" id={`${uid}-tables`} aria-labelledby={`${uid}-tables-label`}>
              {options.map((table, i) => (
                <li
                  key={table.name}
                  id={`${uid}-table-${i}`}
                  role="option"
                  aria-selected={i === current}
                  className={styles.mentionItem}
                  data-demo={`mention-${table.name}`}
                  onPointerDown={(event) => event.preventDefault()}
                  onPointerMove={() => setActive(i)}
                  onClick={(event) => choose(table.name, event.detail > 0)}
                >
                  <Icon name="table" className={styles.mentionIcon} />
                  <span className={styles.mentionName}>{table.name}</span>
                  <span className={styles.mentionRows}>{table.rows}</span>
                  {i === current && <Icon name="enter" className={styles.mentionEnter} />}
                </li>
              ))}
            </ul>
            {mentionOpen && !options.length && (
              <p className={styles.mentionEmpty}>No table matches “{query}”</p>
            )}
          </div>

          <div className={styles.tools} data-part="tools">
            <button
              type="button"
              className={styles.tool}
              aria-label="Mention a table"
              title="Mention a table"
              onClick={() => {
                setInput((now) => `${now}${now && !now.endsWith(' ') ? ' ' : ''}@`);
                setDismissed(false);
                field.current?.focus();
              }}
            >
              <Icon name="plus" className={styles.icon} />
            </button>
            <div
              className={styles.formats}
              role="radiogroup"
              aria-label="Answer format"
              data-part="formats"
            >
              {FORMATS.map((f) => (
                <button
                  key={f.id}
                  type="button"
                  role="radio"
                  className={styles.format}
                  aria-checked={format === f.id}
                  aria-label={f.label}
                  title={f.label}
                  tabIndex={format === f.id ? 0 : -1}
                  data-format={f.id}
                  data-demo={`format-${f.id}`}
                  onClick={() => setFormat(f.id)}
                  onKeyDown={onFormatKey}
                >
                  <Icon name={f.icon} className={styles.icon} />
                </button>
              ))}
            </div>
            <button
              type="button"
              className={styles.rangeButton}
              aria-haspopup="menu"
              aria-expanded={menu?.id === 'range'}
              data-demo="range"
              data-part="range"
              onClick={(event) => openMenu('range', event.currentTarget)}
            >
              <Icon name="calendar" className={styles.icon} />
              <span>{rangeInfo.label}</span>
              <Icon name="chevronDown" className={styles.chevron} width={2} />
            </button>
            <button
              type="button"
              role="switch"
              aria-checked={compare}
              className={styles.compare}
              data-part="compare"
              onClick={() => {
                setCompare((on) => !on);
                say(compare ? 'No comparison' : 'Comparing with last week');
              }}
            >
              <span>vs last week</span>
              <span className={styles.track} aria-hidden="true">
                <span className={styles.thumb} />
              </span>
            </button>
            <span className={styles.toolsEnd}>
              <button
                type="button"
                className={styles.mic}
                aria-label={listening ? 'Stop dictation' : 'Dictate'}
                aria-pressed={listening}
                title="Dictate"
                onClick={() => setListening((on) => !on)}
              >
                <Icon name="mic" className={styles.icon} />
              </button>
              {live ? (
                <button
                  type="button"
                  className={styles.send}
                  aria-label="Stop the answer"
                  data-part="send"
                  onClick={stop}
                >
                  <StopSquare className={styles.sendIcon} />
                </button>
              ) : (
                <button
                  type="button"
                  className={styles.send}
                  aria-label="Send"
                  aria-disabled={!canSend}
                  data-demo="send"
                  data-part="send"
                  onClick={send}
                >
                  <Icon name="arrowUp" className={styles.sendIcon} width={2.2} />
                </button>
              )}
            </span>
          </div>
        </div>
      </section>

      {menu?.id === 'model' && (
        <Menu
          anchor={menu.anchor}
          label="Model"
          align="end"
          takeFocus={menu.byReader}
          onClose={closeMenu}
        >
          {models.map((m) => (
            <MenuItem
              key={m.id}
              radio
              checked={m.id === model.id}
              trail={`${m.seconds} s`}
              onSelect={() => {
                setModel(m);
                say(`${m.name} answers next`);
                closeMenu(true);
              }}
            >
              <span className={styles.modelName}>{m.name}</span>
              <span className={styles.modelNote}>{m.note}</span>
            </MenuItem>
          ))}
        </Menu>
      )}
      {menu?.id === 'range' && (
        <Menu anchor={menu.anchor} label="Range" takeFocus={menu.byReader} onClose={closeMenu}>
          {RANGES.map((r) => (
            <MenuItem
              key={r.id}
              radio
              checked={r.id === range}
              onSelect={() => {
                setRange(r.id);
                say(`Answers cover the ${r.label.toLowerCase()}`);
                closeMenu(true);
              }}
            >
              {r.label}
            </MenuItem>
          ))}
        </Menu>
      )}

      <p className={styles.srOnly} aria-live="polite">
        {message}
      </p>
      <div className={styles.pointerLayer}>
        <DemoPointer
          ref={pointer}
          className={styles.pointer}
          arrowClass={styles.arrow}
          handClass={styles.hand}
        />
      </div>
    </div>
  );
}
```

### insight-thread/charts.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useId,
  useRef,
  useState,
  type CSSProperties,
  type KeyboardEvent as ReactKeyboardEvent,
  type PointerEvent as ReactPointerEvent,
} from 'react';
import type { BarSpec, LineChartSpec, TableSpec } from './data';
import styles from './insight-thread.module.css';

/*
 * The charts in the thread, hand-drawn:
 *
 * - LineChart, the annotated one: a line per series, the dropping (or jumping) one red from the
 *   day it leaves its expected level, a dashed line where it was expected and the gap hatched
 *   between them with its size, a marker on the day something shipped, values at the ends, and a
 *   crosshair with the day's values under the pointer or the arrow keys. It is drawn in real px
 *   (its width read by a ResizeObserver), so the text never stretches; labels and the tooltip are
 *   HTML over it.
 * - AnswerBars and AnswerTable: the short answers the composer gets back.
 */

type Point = { x: number; y: number };

/** The width of a box in layout px (a scaled gallery card leaves it alone), kept in step. */
function useWidth<T extends HTMLElement>() {
  const ref = useRef<T>(null);
  const [width, setWidth] = useState(0);
  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    const read = () => setWidth(element.clientWidth);
    read();
    const observer = new ResizeObserver(read);
    observer.observe(element);
    return () => observer.disconnect();
  }, []);
  return [ref, width] as const;
}

/** A smooth line through the points: each span a cubic whose handles follow its neighbours. */
function smooth(points: Point[], from = 0, to = points.length - 1) {
  const f = (n: number) => n.toFixed(1);
  let d = `M${f(points[from].x)} ${f(points[from].y)}`;
  for (let i = from; i < to; i += 1) {
    const a = points[i - 1] ?? points[i];
    const p = points[i];
    const b = points[i + 1];
    const c = points[i + 2] ?? b;
    const k = 1 / 6;
    d += `C${f(p.x + (b.x - a.x) * k)} ${f(p.y + (b.y - a.y) * k)} ${f(b.x - (c.x - p.x) * k)} ${f(
      b.y - (c.y - p.y) * k,
    )} ${f(b.x)} ${f(b.y)}`;
  }
  return d;
}

/** The chart's frame at a width: room on the left for the axis, on the right for the end labels. */
function frame(width: number) {
  const narrow = width > 0 && width < 460;
  // Under 360 px the end labels drop the series' names: the legend says them.
  const tiny = width > 0 && width < 360;
  return {
    tiny,
    height: narrow ? 190 : 214,
    pad: { left: tiny ? 34 : 40, right: tiny ? 52 : narrow ? 82 : 108, top: 16, bottom: 30 },
  };
}

/** Where day `i` of `n` sits across a chart `width` px wide (the demo points at it). */
export function chartX(width: number, i: number, n: number) {
  const { pad } = frame(width);
  return pad.left + (i / (n - 1)) * Math.max(40, width - pad.left - pad.right);
}

const signed = (n: number) => `${n > 0 ? '+' : n < 0 ? '–' : ''}${Math.abs(Math.round(n))}`;

export function LineChart({
  spec,
  hidden,
  onToggle,
  hover,
  onHover,
}: {
  spec: LineChartSpec;
  /** The series turned off in the legend, by id. */
  hidden: string[];
  onToggle: (id: string) => void;
  /** The day under the crosshair. */
  hover: number | null;
  onHover: (index: number | null) => void;
}) {
  const uid = useId();
  const [box, width] = useWidth<HTMLDivElement>();
  const n = spec.days.length;
  const { height, pad, tiny } = frame(width);
  const plotW = Math.max(40, width - pad.left - pad.right);
  const plotH = height - pad.top - pad.bottom;
  const x = (i: number) => pad.left + (i / (n - 1)) * plotW;
  const y = (v: number) => pad.top + ((spec.max - v) / (spec.max - spec.min)) * plotH;
  // The series that leaves its level is drawn last, over the others.
  const shown = spec.series
    .filter((s) => !hidden.includes(s.id))
    .sort((a, b) => Number(Boolean(a.anomaly)) - Number(Boolean(b.anomaly)));
  const last = n - 1;

  // The values at the right end, pushed apart so none overlap.
  const ends = shown
    .map((s) => ({ s, at: y(s.values[last]) }))
    .sort((a, b) => a.at - b.at)
    .reduce<{ s: (typeof shown)[number]; at: number }[]>((list, item) => {
      const above = list[list.length - 1];
      list.push({ ...item, at: above ? Math.max(item.at, above.at + 21) : item.at });
      return list;
    }, []);

  // Where the marker's label goes: under the lines, or over them when they run low.
  const marker = spec.marker;
  const markerLow =
    marker && shown.some((s) => (s.values[marker.index] - spec.min) / (spec.max - spec.min) < 0.35);

  const point = (event: ReactPointerEvent<HTMLDivElement>) => {
    const rect = event.currentTarget.getBoundingClientRect();
    const scale = rect.width / event.currentTarget.offsetWidth || 1;
    const px = (event.clientX - rect.left) / scale;
    onHover(Math.max(0, Math.min(last, Math.round(((px - pad.left) / plotW) * last))));
  };
  const onKeyDown = (event: ReactKeyboardEvent) => {
    const now = hover ?? -1;
    const to =
      event.key === 'ArrowRight'
        ? Math.min(last, now + 1)
        : event.key === 'ArrowLeft'
          ? Math.max(0, now < 0 ? last : now - 1)
          : event.key === 'Home'
            ? 0
            : event.key === 'End'
              ? last
              : null;
    if (to !== null) {
      event.preventDefault();
      onHover(to);
    } else if (event.key === 'Escape' && hover !== null) {
      event.stopPropagation();
      onHover(null);
    }
  };

  const reading =
    hover === null
      ? ''
      : `${spec.days[hover]}: ${shown.map((s) => `${s.name} ${s.values[hover]}%`).join(', ')}`;

  const tipLeft = hover !== null && x(hover) > width * 0.58;

  return (
    <figure className={styles.chartCard} data-part="chart">
      <figcaption className={styles.chartHead}>
        <span className={styles.chartTitle}>{spec.title}</span>
        <span className={styles.legend} role="group" aria-label="Series shown">
          {spec.series.map((s) => (
            <button
              key={s.id}
              type="button"
              className={styles.legendItem}
              data-tone={s.tone}
              data-demo={`legend-${s.id}`}
              aria-pressed={!hidden.includes(s.id)}
              onClick={() => onToggle(s.id)}
            >
              <span className={styles.swatch} aria-hidden="true" />
              {s.name}
            </button>
          ))}
        </span>
      </figcaption>

      <div
        ref={box}
        className={styles.plot}
        style={{ height }}
        data-part="plot"
        data-demo="plot"
        tabIndex={0}
        role="group"
        aria-label={`${spec.title}. Arrow keys read each day.`}
        aria-describedby={`${uid}-describe`}
        onPointerMove={point}
        onPointerDown={point}
        onPointerLeave={(event) => {
          if (event.pointerType !== 'touch') onHover(null);
        }}
        onKeyDown={onKeyDown}
        onBlur={() => onHover(null)}
      >
        {width > 0 && (
          <svg width={width} height={height} className={styles.chartSvg} aria-hidden="true">
            <defs>
              <pattern
                id={`${uid}-hatch`}
                width="6"
                height="6"
                patternUnits="userSpaceOnUse"
                patternTransform="rotate(45)"
              >
                <line x1="0" y1="0" x2="0" y2="6" className={styles.hatchLine} />
              </pattern>
            </defs>

            {spec.ticks.map((tick) => (
              <g key={tick}>
                <line
                  x1={pad.left}
                  x2={x(last)}
                  y1={y(tick)}
                  y2={y(tick)}
                  className={styles.grid}
                />
                <text x={pad.left - 8} y={y(tick)} dy="0.34em" className={styles.axisText}>
                  {tick}%
                </text>
              </g>
            ))}
            <text x={x(0)} y={height - 6} className={styles.axisText} textAnchor="start">
              {spec.days[0]}
            </text>
            <text x={x(last)} y={height - 6} className={styles.axisText} textAnchor="end">
              {spec.days[last]}
            </text>

            {marker && (
              <line
                x1={x(marker.index)}
                x2={x(marker.index)}
                y1={pad.top}
                y2={pad.top + plotH}
                className={styles.markerLine}
              />
            )}

            {shown.map((s) => {
              const points = s.values.map((v, i) => ({ x: x(i), y: y(v) }));
              const a = s.anomaly;
              if (!a)
                return (
                  <path key={s.id} d={smooth(points)} className={styles.line} data-tone={s.tone} />
                );
              const expected = y(a.expected);
              return (
                <g key={s.id}>
                  <path
                    d={`${smooth(points, a.from)}L${x(last)} ${expected}L${x(a.from)} ${expected}Z`}
                    className={styles.gapTint}
                  />
                  <path
                    d={`${smooth(points, a.from)}L${x(last)} ${expected}L${x(a.from)} ${expected}Z`}
                    fill={`url(#${uid}-hatch)`}
                  />
                  <line
                    x1={x(a.from)}
                    x2={x(last)}
                    y1={expected}
                    y2={expected}
                    className={styles.expected}
                    data-tone={s.tone}
                  />
                  <circle
                    cx={x(last)}
                    cy={expected}
                    r="4"
                    className={styles.ring}
                    data-tone={s.tone}
                  />
                  <path d={smooth(points, 0, a.from)} className={styles.line} data-tone={s.tone} />
                  <path d={smooth(points, a.from)} className={styles.line} data-tone="red" />
                  {points.slice(a.from + 1, last).map((p, i) => (
                    <circle key={i} cx={p.x} cy={p.y} r="3" className={styles.dot} />
                  ))}
                </g>
              );
            })}

            {shown.map((s) => (
              <circle
                key={s.id}
                cx={x(last)}
                cy={y(s.values[last])}
                r="4.5"
                className={styles.endDot}
                data-tone={s.anomaly ? 'red' : s.tone}
              />
            ))}

            {hover !== null && (
              <g>
                <line
                  x1={x(hover)}
                  x2={x(hover)}
                  y1={pad.top - 4}
                  y2={pad.top + plotH}
                  className={styles.crosshair}
                />
                {shown.map((s) => (
                  <circle
                    key={s.id}
                    cx={x(hover)}
                    cy={y(s.values[hover])}
                    r="4.5"
                    className={styles.hoverDot}
                    data-tone={s.anomaly && hover >= s.anomaly.from ? 'red' : s.tone}
                  />
                ))}
              </g>
            )}
          </svg>
        )}

        {width > 0 &&
          ends.map(({ s, at }) => (
            <span
              key={s.id}
              className={styles.endLabel}
              data-tone={s.anomaly ? 'red' : s.tone}
              data-alert={s.anomaly ? '' : undefined}
              style={{ left: x(last) + 12, top: at }}
              aria-hidden="true"
            >
              <b>{s.values[last]}%</b>
              {!tiny && ` ${s.name}`}
            </span>
          ))}

        {width > 0 &&
          shown
            .filter((s) => s.anomaly)
            .map((s) => {
              const a = s.anomaly!;
              const gap = s.values[last] - a.expected;
              return (
                <span
                  key={s.id}
                  className={styles.gapLabel}
                  style={{
                    right: width - x(last) + 10,
                    top: y(a.expected) + (y(s.values[last]) - y(a.expected)) * 0.36,
                  }}
                  aria-hidden="true"
                >
                  {signed(gap)} pts <span>vs expected</span>
                </span>
              );
            })}

        {width > 0 && marker && (
          <span
            className={styles.markerLabel}
            data-at={markerLow ? 'top' : 'bottom'}
            style={{
              left: Math.max(4, Math.min(x(marker.index), width - 70)),
              top: markerLow ? pad.top + 4 : pad.top + plotH - 4,
            }}
            aria-hidden="true"
          >
            <b>{marker.label}</b> {marker.sub}
          </span>
        )}

        {width > 0 && hover !== null && (
          <span
            className={styles.tip}
            data-part="chart-tip"
            data-side={tipLeft ? 'left' : 'right'}
            style={{ left: x(hover), top: pad.top }}
            aria-hidden="true"
          >
            <b className={styles.tipDay}>{spec.days[hover]}</b>
            {[...shown]
              .sort((a, b) => b.values[hover] - a.values[hover])
              .map((s) => (
                <span key={s.id} className={styles.tipRow}>
                  <span
                    className={styles.swatch}
                    data-tone={s.anomaly && hover >= s.anomaly.from ? 'red' : s.tone}
                  />
                  <span className={styles.tipName}>{s.name}</span>
                  <span className={styles.tipValue}>{s.values[hover]}%</span>
                </span>
              ))}
          </span>
        )}
      </div>

      <p id={`${uid}-describe`} className={styles.srOnly}>
        {spec.describe}
      </p>
      <p className={styles.srOnly} aria-live="polite">
        {reading}
      </p>
      <div className={styles.chartFoot}>
        <span>{spec.caption}</span>
        <span className={styles.headline}>{spec.headline}</span>
      </div>
    </figure>
  );
}

export function AnswerBars({ spec }: { spec: BarSpec }) {
  const unit = spec.unit;
  return (
    <figure className={styles.bars} data-part="answer-bars">
      <figcaption className={styles.barsTitle}>{spec.title}</figcaption>
      <ul className={styles.barList}>
        {spec.bars.map((bar) => {
          const fell = bar.value < bar.before - 4;
          return (
            <li key={bar.label} className={styles.barRow}>
              <span className={styles.barLabel}>{bar.label}</span>
              <span className={styles.barTrack} aria-hidden="true">
                <span
                  className={styles.barFill}
                  data-fell={fell || undefined}
                  style={{ '--share': bar.value / spec.max } as CSSProperties}
                />
                {spec.marks && (
                  <span
                    className={styles.barMark}
                    style={{ '--share': bar.before / spec.max } as CSSProperties}
                  />
                )}
              </span>
              <span className={styles.barValue}>
                {Math.round(bar.value)}
                {unit}
                {spec.marks && (
                  <span className={styles.barBefore}>
                    {' '}
                    <span className={styles.srOnly}>, was </span>
                    <span aria-hidden="true">· </span>
                    {Math.round(bar.before)}
                    {unit}
                  </span>
                )}
              </span>
            </li>
          );
        })}
      </ul>
      <p className={styles.barsFoot}>{spec.caption}</p>
    </figure>
  );
}

export function AnswerTable({ spec }: { spec: TableSpec }) {
  return (
    <figure className={styles.answerTable} data-part="answer-table">
      <div className={styles.tableScroll} tabIndex={0} role="region" aria-label={spec.caption}>
        <table>
          <thead>
            <tr>
              {spec.columns.map((column, i) => (
                <th key={column} scope="col" data-num={i > 0 || undefined}>
                  {column}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {spec.rows.map((row, r) => (
              <tr key={r}>
                {row.map((cell, i) =>
                  i === 0 ? (
                    <th key={i} scope="row">
                      {typeof cell === 'string' ? cell : cell.text}
                    </th>
                  ) : (
                    <td
                      key={i}
                      data-num=""
                      data-tone={typeof cell === 'string' ? undefined : cell.tone}
                    >
                      {typeof cell === 'string' ? cell : cell.text}
                    </td>
                  ),
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <figcaption className={styles.barsFoot}>{spec.caption}</figcaption>
    </figure>
  );
}
```

### insight-thread/insight-thread.module.css

```css
/* Insight thread (insight-thread.tsx): an analytics assistant's window on a grey stage, near-black
   by night and white by day. The header, the thread in an inset panel that scrolls on its own,
   and the composer with its tools under it. The charts (charts.tsx) use the same tokens.

   Colours are the tokens below, light-dark(light, dark) where the two differ: the component takes
   the color-scheme it inherits from the page, or the one its colorScheme prop sets
   (data-color-scheme). */

.root {
  --stage: #e9e9ec;
  --window: #ffffff;
  --panel: #f7f7f8;
  --line: #e7e7ea;
  --line-2: #dcdce1;
  --ink: #18181b;
  --ink-2: #66666e;
  --ink-3: #6d6d73;
  --bubble: #ededf0;
  --chip: #ffffff;
  --hover: #f1f1f3;
  --card: #ffffff;
  --grid: #d9d9de;
  --menu: #ffffff;
  --menu-active: #f0f0f3;
  --token-bg: #e5eeff;
  --token-ink: #1f5fd6;
  --seg-on: #e6eeff;
  --accent: #2e6ddd;
  --switch-off: #949499;
  --send: #18181b;
  --send-ink: #ffffff;
  --mic: #ededf0;
  --green: #138758;
  --violet: #7c5cf0;
  --amber: #a36a05;
  --red: #ca362c;
  --blue: #2f6fe0;
  --red-bg: #fdecea;
  --red-edge: #f5c3be;
  --tip: #ffffff;
  --shadow: rgb(0 0 0 / 0.12);
  --hatch-tint: rgb(220 59 48 / 0.08);
  /* The same on both schemes. */
  --focus: #6d8cff;
  --pointer: #1c1c1e;
  --pointer-edge: #fff;
  --pointer-shadow: rgb(0 0 0 / 0.3);
  --sans: var(--body, Inter, ui-sans-serif, system-ui, sans-serif);
  --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace;
}
@supports (color: light-dark(#fff, #000)) {
  .root {
    --stage: light-dark(#e9e9ec, #2a2a2d);
    --window: light-dark(#ffffff, #141414);
    --panel: light-dark(#f7f7f8, #1b1b1b);
    --line: light-dark(#e7e7ea, #282828);
    --line-2: light-dark(#dcdce1, #333334);
    --ink: light-dark(#18181b, #ebebeb);
    --ink-2: light-dark(#66666e, #a8a8aa);
    --ink-3: light-dark(#6d6d73, #a3a3a5);
    --bubble: light-dark(#ededf0, #272727);
    --chip: light-dark(#ffffff, #1d1d1d);
    --hover: light-dark(#f1f1f3, #252526);
    --card: light-dark(#ffffff, #181818);
    --grid: light-dark(#d9d9de, #343436);
    --menu: light-dark(#ffffff, #2a2a2a);
    --menu-active: light-dark(#f0f0f3, #3a3a3a);
    --token-bg: light-dark(#e5eeff, #1a2c48);
    --token-ink: light-dark(#1f5fd6, #67a6ff);
    --seg-on: light-dark(#e6eeff, #1c2b42);
    --accent: light-dark(#2e6ddd, #4b8dff);
    --switch-off: light-dark(#949499, #3a3a3c);
    --send: light-dark(#18181b, #f4f4f4);
    --send-ink: light-dark(#ffffff, #111111);
    --mic: light-dark(#ededf0, #2a2a2b);
    --green: light-dark(#138758, #3fcf8e);
    --violet: light-dark(#7c5cf0, #9c88f7);
    --amber: light-dark(#a36a05, #f3b23f);
    --red: light-dark(#ca362c, #f25a4e);
    --blue: light-dark(#2f6fe0, #5b9cff);
    --red-bg: light-dark(#fdecea, #3a1715);
    --red-edge: light-dark(#f5c3be, #5d2420);
    --tip: light-dark(#ffffff, #262626);
    --shadow: light-dark(rgb(0 0 0 / 0.12), rgb(0 0 0 / 0.55));
    --hatch-tint: light-dark(rgb(220 59 48 / 0.08), rgb(242 90 78 / 0.1));
  }
}
.root[data-color-scheme='light'] {
  color-scheme: light;
}
.root[data-color-scheme='dark'] {
  color-scheme: dark;
}
.root[data-color-scheme='system'] {
  color-scheme: light dark;
}

.root {
  position: relative;
  container-type: inline-size;
  width: 100%;
  padding: 32px 28px;
  overflow: hidden;
  overflow: clip;
  border-radius: 18px;
  background: var(--stage);
  color: var(--ink);
  font-family: var(--sans);
  font-size: 14px;
  line-height: 1.4;
  -webkit-tap-highlight-color: transparent;
}
/* The composer alone: room above it for the tables menu. */
.root[data-bare] {
  display: grid;
  align-content: end;
  min-height: 300px;
}
:where(.root) :where(button, input) {
  font: inherit;
  color: inherit;
}
.root button {
  cursor: pointer;
}
.root [hidden] {
  display: none !important;
}
.root :focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 1px;
}
.root svg {
  flex: none;
  display: block;
}
.srOnly {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
.icon {
  width: 16px;
  height: 16px;
}
.chevron {
  width: 13px;
  height: 13px;
  color: var(--ink-2);
}

/* ---- The window ------------------------------------------------------------------------------- */

.window {
  position: relative;
  display: grid;
  max-width: 760px;
  margin: 0 auto;
  border: 1px solid var(--line);
  border-radius: 18px;
  background: var(--window);
  box-shadow: 0 24px 60px -28px var(--shadow);
}

.header {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
  padding: 14px 16px 12px 18px;
}
.headSpark {
  width: 17px;
  height: 17px;
  color: var(--blue);
}
.title {
  flex: 1;
  min-width: 0;
  margin: 0 0 0 4px;
  overflow: hidden;
  font-size: 16.5px;
  font-weight: 500;
  letter-spacing: -0.01em;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.picker {
  display: inline-flex;
  flex: none;
  align-items: center;
  gap: 10px;
  height: 30px;
  padding: 0 10px 0 12px;
  border: 1px solid var(--line-2);
  border-radius: 9px;
  background: none;
  color: var(--ink-2) !important;
  font-size: 13.5px;
}
.picker:hover,
.picker[aria-expanded='true'],
.picker[data-over] {
  background: var(--hover);
  color: var(--ink) !important;
}
.iconButton {
  display: grid;
  flex: none;
  place-items: center;
  width: 32px;
  height: 30px;
  padding: 0;
  border: 1px solid var(--line-2);
  border-radius: 9px;
  background: none;
  color: var(--ink-2) !important;
}
.iconButton:hover,
.iconButton[data-over] {
  background: var(--hover);
  color: var(--ink) !important;
}
.iconButton[aria-pressed='true'] {
  border-color: color-mix(in oklab, var(--accent) 45%, var(--line-2));
  background: var(--seg-on);
  color: var(--accent) !important;
}

/* ---- The thread ------------------------------------------------------------------------------- */

.scroller {
  max-height: var(--thread-max, 560px);
  margin: 0 5px;
  padding: 16px 14px 14px;
  overflow-y: auto;
  border: 1px solid var(--line);
  border-radius: 13px;
  background: var(--panel);
  scrollbar-width: thin;
  overscroll-behavior: contain;
}
.turn {
  display: grid;
  gap: 12px;
}
.turn + .turn {
  margin-top: 22px;
  padding-top: 20px;
  border-top: 1px solid var(--line);
}
.bubble {
  justify-self: end;
  max-width: 82%;
  margin: 0 0 4px;
  padding: 9px 13px;
  border-radius: 13px;
  background: var(--bubble);
  font-size: 15px;
  line-height: 1.45;
}
.token {
  display: inline-block;
  padding: 1px 7px 2px;
  border-radius: 6px;
  background: var(--token-bg);
  color: var(--token-ink);
  font-weight: 500;
  line-height: 1.35;
  white-space: nowrap;
}

.thought {
  display: grid;
  gap: 8px;
}
.thoughtToggle {
  display: inline-flex;
  justify-self: start;
  align-items: center;
  gap: 8px;
  min-height: 26px;
  margin-left: -4px;
  padding: 0 8px 0 4px;
  border: 0;
  border-radius: 7px;
  background: none;
  color: var(--ink-2) !important;
  font-size: 13.5px;
  text-align: left;
}
.thoughtToggle:hover,
.thoughtToggle[data-over] {
  color: var(--ink) !important;
}
.thoughtChevron {
  width: 13px;
  height: 13px;
  transition: transform 0.18s ease;
}
.thoughtToggle[aria-expanded='true'] .thoughtChevron {
  transform: rotate(90deg);
}
.thinking {
  background: linear-gradient(90deg, var(--ink-3) 30%, var(--ink) 50%, var(--ink-3) 70%) 0 0 / 300%
    100%;
  background-clip: text;
  color: transparent;
  animation: shimmer 1.6s linear infinite;
}
@keyframes shimmer {
  to {
    background-position: -150% 0;
  }
}
.queries {
  display: grid;
  gap: 2px;
  margin: 0 0 2px 6px;
  padding: 2px 0 2px 14px;
  border-left: 1px solid var(--line-2);
  list-style: none;
}
.query {
  display: grid;
  grid-template-columns: 14px minmax(0, 1fr) auto;
  align-items: center;
  gap: 9px;
  min-height: 26px;
  font-size: 12px;
}
.queryIcon {
  width: 14px;
  height: 14px;
  color: var(--ink-3);
}
.sql {
  overflow: hidden;
  color: var(--ink-2);
  font-family: var(--mono);
  font-size: 11.5px;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.queryRows {
  color: var(--ink-3);
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}
.query[data-running] .queryRows {
  color: var(--accent);
}

.answer {
  margin: 0;
  font-size: 15px;
  line-height: 1.58;
  text-wrap: pretty;
}
.caret {
  display: inline-block;
  width: 7px;
  height: 15px;
  margin-left: 2px;
  border-radius: 2px;
  background: var(--accent);
  vertical-align: -2px;
  animation: blink 1s steps(2, start) infinite;
}
@keyframes blink {
  to {
    visibility: hidden;
  }
}
.stopped {
  margin: 0;
  color: var(--ink-3);
  font-size: 13px;
  font-style: italic;
}
.reveal {
  display: grid;
  gap: 12px;
  animation: rise 0.3s ease;
}
@keyframes rise {
  from {
    opacity: 0;
    transform: translateY(4px);
  }
}

/* The sources: chips with a preview. */
.sources {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 2px 0;
  padding: 0;
  list-style: none;
}
.sourceItem {
  position: relative;
}
.source {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  height: 29px;
  padding: 0 12px 0 10px;
  border: 1px solid var(--line-2);
  border-radius: 8px;
  background: var(--chip);
  color: var(--ink) !important;
  font-size: 13.5px;
}
.source:hover,
.source[aria-describedby],
.source[data-over] {
  background: var(--hover);
}
.sourceIcon {
  width: 15px;
  height: 15px;
  color: var(--ink-2);
}
.preview {
  position: absolute;
  top: calc(100% + 6px);
  left: 0;
  z-index: 4;
  display: grid;
  gap: 6px;
  width: max-content;
  max-width: min(300px, 80cqi);
  padding: 10px 12px 11px;
  border: 1px solid var(--line-2);
  border-radius: 10px;
  background: var(--menu);
  box-shadow: 0 14px 34px -12px var(--shadow);
  font-size: 12.5px;
  animation: rise 0.14s ease;
}
.previewHead {
  display: flex;
  align-items: center;
  gap: 7px;
  font-size: 13px;
}
.previewHead b {
  font-weight: 600;
}
.previewMeta {
  color: var(--ink-3);
}
.previewColumns {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
.previewColumns code {
  padding: 1px 6px;
  border-radius: 5px;
  background: var(--hover);
  color: var(--ink-2);
  font-family: var(--mono);
  font-size: 11px;
}
.previewLine {
  color: var(--ink-2);
  line-height: 1.45;
}

/* The suggestion, copy and thumbs up. */
.actions {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-top: 2px;
}
.suggestion {
  display: inline-flex;
  align-items: center;
  gap: 9px;
  height: 31px;
  padding: 0 13px 0 11px;
  border: 1px solid var(--line-2);
  border-radius: 9px;
  background: var(--chip);
  font-size: 13.5px;
}
.suggestion:hover:not(:disabled),
.suggestion[data-over] {
  background: var(--hover);
}
.suggestion:disabled {
  cursor: default;
  opacity: 0.5;
}
.suggestionSpark {
  width: 15px;
  height: 15px;
  color: var(--blue);
}
.actionsEnd {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

/* ---- The annotated chart (charts.tsx) --------------------------------------------------------- */

.chartCard {
  display: grid;
  gap: 6px;
  margin: 4px 0 2px;
  padding: 12px 12px 10px;
  border: 1px solid var(--line);
  border-radius: 13px;
  background: var(--card);
}
.chartHead {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 4px 12px;
  padding: 0 0 0 0;
}
.chartTitle {
  color: var(--ink-2);
  font-size: 13px;
  font-weight: 500;
}
.legend {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
  margin-right: -6px;
}
.legendItem {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  height: 24px;
  padding: 0 6px;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--ink-2) !important;
  font-size: 13px;
}
.legendItem:hover,
.legendItem[data-over] {
  background: var(--hover);
}
.legendItem[aria-pressed='false'] {
  color: var(--ink-3) !important;
  text-decoration: line-through;
}
.legendItem[aria-pressed='false'] .swatch {
  background: none;
  box-shadow: inset 0 0 0 1.5px var(--ink-3);
}
.swatch {
  flex: none;
  width: 9px;
  height: 9px;
  border-radius: 2.5px;
  background: var(--tone);
}
.root [data-tone='green'] {
  --tone: var(--green);
}
.root [data-tone='violet'] {
  --tone: var(--violet);
}
.root [data-tone='amber'] {
  --tone: var(--amber);
}
.root [data-tone='red'] {
  --tone: var(--red);
}
.root [data-tone='blue'] {
  --tone: var(--blue);
}

.plot {
  position: relative;
  margin: 0 -2px;
  border-radius: 8px;
  outline-offset: 2px;
  touch-action: pan-y;
}
.chartSvg {
  overflow: visible;
}
.grid {
  stroke: var(--grid);
  stroke-width: 1;
  stroke-dasharray: 1 4;
  stroke-linecap: round;
}
.axisText {
  fill: var(--ink-3);
  font-size: 12px;
  text-anchor: end;
  font-variant-numeric: tabular-nums;
}
.line {
  fill: none;
  stroke: var(--tone);
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
}
.expected {
  stroke: var(--tone);
  stroke-width: 1.6;
  stroke-dasharray: 4 4;
  opacity: 0.85;
}
.ring {
  fill: var(--card);
  stroke: var(--tone);
  stroke-width: 1.8;
}
.gapTint {
  fill: var(--hatch-tint);
}
.hatchLine {
  stroke: var(--red);
  stroke-width: 1.1;
  opacity: 0.5;
}
.dot {
  fill: var(--card);
  stroke: var(--red);
  stroke-width: 1.8;
}
.endDot {
  fill: var(--tone);
  stroke: color-mix(in oklab, var(--tone) 35%, var(--card));
  stroke-width: 3;
  paint-order: stroke;
}
.markerLine {
  stroke: var(--ink-3);
  stroke-width: 1.2;
  stroke-dasharray: 2 3;
}
.crosshair {
  stroke: var(--ink-2);
  stroke-width: 1;
}
.hoverDot {
  fill: var(--tone);
  stroke: var(--card);
  stroke-width: 2.5;
}
.endLabel {
  position: absolute;
  display: flex;
  align-items: center;
  gap: 5px;
  height: 22px;
  color: var(--ink-2);
  font-size: 13px;
  white-space: nowrap;
  transform: translateY(-50%);
  pointer-events: none;
}
.endLabel b {
  color: var(--tone);
  font-weight: 500;
  font-variant-numeric: tabular-nums;
}
.endLabel[data-alert] {
  margin-left: -4px;
  padding: 0 8px;
  border-radius: 6px;
  background: var(--red-bg);
  color: var(--red);
}
.gapLabel,
.markerLabel {
  position: absolute;
  display: inline-flex;
  align-items: center;
  gap: 5px;
  height: 24px;
  padding: 0 9px;
  border-radius: 7px;
  font-size: 13px;
  white-space: nowrap;
  pointer-events: none;
}
.gapLabel {
  border: 1px solid var(--red-edge);
  background: var(--red-bg);
  color: var(--red);
  font-variant-numeric: tabular-nums;
  transform: translateY(-50%);
}
.markerLabel {
  border: 1px solid var(--line);
  background: var(--tip);
  color: var(--ink-2);
  transform: translate(-50%, -100%);
}
.markerLabel[data-at='top'] {
  transform: translate(-50%, 0);
}
.markerLabel b {
  color: var(--ink);
  font-weight: 500;
}
.tip {
  position: absolute;
  z-index: 2;
  display: grid;
  gap: 4px;
  min-width: 128px;
  padding: 8px 10px 9px;
  border: 1px solid var(--line-2);
  border-radius: 9px;
  background: var(--tip);
  box-shadow: 0 12px 28px -10px var(--shadow);
  font-size: 12.5px;
  transform: translateX(12px);
  pointer-events: none;
}
.tip[data-side='left'] {
  transform: translateX(calc(-100% - 12px));
}
.tipDay {
  margin-bottom: 1px;
  font-weight: 600;
}
.tipRow {
  display: grid;
  grid-template-columns: 9px 1fr auto;
  align-items: center;
  gap: 8px;
}
.tipName {
  color: var(--ink-2);
}
.tipValue {
  font-variant-numeric: tabular-nums;
}
.chartFoot {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 2px 12px;
  padding-top: 6px;
  color: var(--ink-3);
  font-size: 12.5px;
}
.headline {
  color: var(--ink-2);
  font-weight: 500;
}

/* The answers' bars and tables. */
.bars,
.answerTable {
  display: grid;
  gap: 10px;
  margin: 2px 0;
  padding: 12px 14px;
  border: 1px solid var(--line);
  border-radius: 12px;
  background: var(--card);
}
.barsTitle {
  color: var(--ink-2);
  font-size: 13px;
  font-weight: 500;
}
.barList {
  display: grid;
  gap: 8px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.barRow {
  display: grid;
  grid-template-columns: minmax(84px, 22%) minmax(0, 1fr) 92px;
  align-items: center;
  gap: 12px;
  font-size: 13px;
}
.barLabel {
  overflow: hidden;
  color: var(--ink-2);
  text-overflow: ellipsis;
  white-space: nowrap;
}
.barTrack {
  position: relative;
  height: 12px;
  border-radius: 4px;
  background: var(--hover);
}
.barFill {
  position: absolute;
  inset: 0 auto 0 0;
  width: calc(var(--share) * 100%);
  border-radius: 4px;
  background: var(--green);
  transform-origin: left;
  animation: grow 0.5s cubic-bezier(0.3, 0.7, 0.3, 1);
}
.barFill[data-fell] {
  background: var(--red);
}
@keyframes grow {
  from {
    transform: scaleX(0);
  }
}
.barMark {
  position: absolute;
  top: -3px;
  bottom: -3px;
  left: calc(var(--share) * 100% - 1px);
  width: 2px;
  border-radius: 1px;
  background: var(--ink);
}
.barValue {
  font-variant-numeric: tabular-nums;
  text-align: right;
  white-space: nowrap;
}
.barBefore {
  color: var(--ink-3);
}
.barsFoot {
  margin: 0;
  color: var(--ink-3);
  font-size: 12px;
}
.tableScroll {
  overflow-x: auto;
  border-radius: 6px;
}
.answerTable table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}
.answerTable th,
.answerTable td {
  padding: 7px 10px;
  border-bottom: 1px solid var(--line);
  text-align: left;
}
.answerTable thead th {
  padding-top: 2px;
  color: var(--ink-3);
  font-size: 12px;
  font-weight: 500;
}
.answerTable tbody th {
  font-weight: 500;
}
.answerTable tbody tr:last-child > * {
  border-bottom: 0;
}
.answerTable [data-num] {
  text-align: right;
}
.answerTable td[data-tone='down'] {
  color: var(--red);
}
.answerTable td[data-tone='up'] {
  color: var(--green);
}
.answerTable td[data-tone='flat'] {
  color: var(--ink-3);
}

/* ---- The composer ----------------------------------------------------------------------------- */

.composer {
  position: relative;
  display: grid;
  gap: 12px;
  padding: 14px 16px 16px;
}
.field {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px 6px;
  min-height: 34px;
  padding: 0 2px;
  font-size: 15.5px;
  cursor: text;
}
.draftText {
  white-space: pre-wrap;
}
.field .token {
  padding: 3px 8px 4px;
}
.input {
  flex: 1;
  min-width: 120px;
  height: 32px;
  padding: 0;
  border: 0;
  outline: none !important;
  background: none;
  font-size: 15.5px !important;
  caret-color: var(--accent);
}
.input::placeholder {
  color: var(--ink-3);
}
.mention {
  position: absolute;
  bottom: calc(100% - 10px);
  z-index: 5;
  display: grid;
  width: 260px;
  padding: 6px;
  border: 1px solid var(--line-2);
  border-radius: 12px;
  background: var(--menu);
  box-shadow: 0 18px 40px -12px var(--shadow);
  animation: rise 0.14s ease;
}
.root[data-bare] .mention {
  bottom: calc(100% + 4px);
}
.mention ul {
  display: grid;
  gap: 2px;
  margin: 0;
  padding: 0;
  list-style: none;
}
.mentionHead {
  margin: 0;
  padding: 5px 10px 6px;
  color: var(--ink-3);
  font-size: 12.5px;
}
.mentionItem {
  display: flex;
  align-items: center;
  gap: 10px;
  height: 36px;
  padding: 0 10px;
  border-radius: 8px;
  cursor: pointer;
}
.mentionItem[aria-selected='true'],
.mentionItem[data-over] {
  background: var(--menu-active);
}
.mentionIcon {
  width: 16px;
  height: 16px;
  color: var(--ink-2);
}
.mentionName {
  font-size: 15px;
}
.mentionRows {
  flex: 1;
  color: var(--ink-3);
  font-size: 12.5px;
  font-variant-numeric: tabular-nums;
}
.mentionEnter {
  width: 15px;
  height: 15px;
  color: var(--ink-2);
}
.mentionEmpty {
  margin: 0;
  padding: 6px 10px 8px;
  color: var(--ink-2);
  font-size: 13px;
}

.tools {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}
.tool,
.rangeButton,
.compare {
  display: inline-flex;
  align-items: center;
  height: 30px;
  border: 1px solid var(--line-2);
  border-radius: 8px;
  background: none;
  color: var(--ink-2) !important;
  font-size: 13.5px;
}
.tool {
  justify-content: center;
  width: 30px;
  padding: 0;
}
.tool:hover,
.rangeButton:hover,
.rangeButton[aria-expanded='true'],
.compare:hover,
.rangeButton[data-over],
.compare[data-over] {
  background: var(--hover);
  color: var(--ink) !important;
}
.formats {
  display: inline-flex;
  gap: 2px;
  height: 30px;
  padding: 2px;
  border: 1px solid var(--line-2);
  border-radius: 8px;
}
.format {
  display: grid;
  place-items: center;
  width: 30px;
  padding: 0;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--ink-2) !important;
}
.format:hover,
.format[data-over] {
  color: var(--ink) !important;
}
.format[aria-checked='true'] {
  background: var(--seg-on);
  color: var(--accent) !important;
}
.rangeButton {
  gap: 8px;
  padding: 0 9px 0 10px;
}
.rangeButton > span {
  color: var(--ink);
}
.compare {
  gap: 10px;
  padding: 0 4px 0 11px;
}
.compare > span:first-child {
  color: var(--ink);
}
.track {
  position: relative;
  width: 34px;
  height: 20px;
  border-radius: 10px;
  background: var(--switch-off);
  transition: background 0.18s ease;
}
.thumb {
  position: absolute;
  top: 2px;
  left: 2px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #fff;
  box-shadow: 0 1px 2px rgb(0 0 0 / 0.3);
  transition: transform 0.18s ease;
}
.compare[aria-checked='true'] .track {
  background: var(--accent);
}
.compare[aria-checked='true'] .thumb {
  transform: translateX(14px);
}
.toolsEnd {
  display: flex;
  gap: 10px;
  margin-left: auto;
}
.mic,
.send {
  display: grid;
  place-items: center;
  width: 34px;
  height: 34px;
  padding: 0;
  border: 0;
  border-radius: 50%;
}
.mic {
  background: var(--mic);
  color: var(--ink-2) !important;
}
.mic:hover {
  color: var(--ink) !important;
}
.mic[aria-pressed='true'] {
  background: var(--red-bg);
  color: var(--red) !important;
  box-shadow: 0 0 0 0 var(--red-edge);
  animation: listen 1.2s ease-out infinite;
}
@keyframes listen {
  to {
    box-shadow: 0 0 0 8px transparent;
  }
}
.send {
  background: var(--send);
  color: var(--send-ink) !important;
}
.send[aria-disabled='true'] {
  cursor: default;
  opacity: 0.35;
}
.send[data-over] {
  transform: scale(0.94);
}
.sendIcon {
  width: 18px;
  height: 18px;
}

/* ---- Menus ------------------------------------------------------------------------------------ */

.menu {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 6;
  display: grid;
  min-width: 190px;
  padding: 5px;
  border: 1px solid var(--line-2);
  border-radius: 11px;
  outline: none;
  background: var(--menu);
  box-shadow: 0 16px 36px -10px var(--shadow);
  animation: rise 0.14s ease;
}
.menuItem {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: 32px;
  padding: 5px 9px;
  border: 0;
  border-radius: 7px;
  outline: none;
  background: none;
  font-size: 13.5px;
  text-align: left;
}
.menuItem:hover,
.menuItem:focus-visible,
.menuItem[data-over] {
  background: var(--menu-active);
}
.menuText {
  display: grid;
  flex: 1;
  white-space: nowrap;
}
.menuTrail {
  color: var(--ink-3);
  font-size: 12px;
  font-variant-numeric: tabular-nums;
}
.menuCheck {
  width: 15px;
  height: 15px;
  color: var(--accent);
}
.menuLabel {
  padding: 6px 9px 4px;
  color: var(--ink-3);
  font-size: 12px;
}
.modelName {
  color: var(--ink);
}
.modelNote {
  color: var(--ink-3);
  font-size: 12px;
}

/* ---- Narrow ----------------------------------------------------------------------------------- */

@container (max-width: 560px) {
  .root {
    padding: 12px 10px;
  }
  .header {
    padding: 12px 12px 10px 14px;
  }
  .title {
    font-size: 15px;
  }
  .scroller {
    margin: 0 4px;
    padding: 14px 10px 12px;
  }
  .bubble,
  .answer {
    font-size: 14.5px;
  }
  .chartCard {
    margin-inline: -4px;
    padding: 10px 8px 8px;
  }
  .chartTitle,
  .legendItem {
    font-size: 12.5px;
  }
  .endLabel,
  .gapLabel,
  .markerLabel {
    font-size: 12px;
  }
  .gapLabel span {
    display: none;
  }
  .barRow {
    grid-template-columns: 76px minmax(0, 1fr) auto;
    gap: 8px;
  }
  .composer {
    padding: 12px 12px 14px;
  }
  .rangeButton > span {
    display: none;
  }
  .rangeButton {
    padding: 0 7px;
  }
  .compare {
    padding-left: 9px;
  }
  .toolsEnd {
    gap: 8px;
  }
}
@container (max-width: 400px) {
  /* The title gets its own row; the picker and Share go under it, at the right. */
  .header {
    flex-wrap: wrap;
    row-gap: 8px;
  }
  .title {
    flex-basis: calc(100% - 40px);
    white-space: normal;
    line-height: 1.3;
  }
  .picker {
    margin-left: auto;
  }
  .tools {
    gap: 6px;
  }
  .compare > span:first-child {
    font-size: 12.5px;
  }
  .query {
    grid-template-columns: 14px minmax(0, 1fr);
  }
  .queryRows {
    grid-column: 2;
    margin-top: -6px;
  }
  .actionsEnd {
    margin-left: auto;
  }
}

/* ---- The demo's pointer ----------------------------------------------------------------------- */

.pointerLayer {
  position: absolute;
  inset: 0;
  z-index: 8;
  pointer-events: none;
}
.pointer {
  width: 20px;
  height: 20px;
}
.hand {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .arrow {
  visibility: hidden;
}
.pointer[data-glyph='hand'] .hand {
  visibility: visible;
}

@media (prefers-reduced-motion: reduce) {
  .thoughtChevron,
  .track,
  .thumb {
    transition: none;
  }
  .thinking,
  .caret,
  .reveal,
  .preview,
  .mention,
  .menu,
  .barFill,
  .mic[aria-pressed='true'] {
    animation: none;
  }
}
```

### insight-thread/data.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The insight thread's content: the thread it opens on (a question, the queries the assistant
 * ran, its answer, the sources and an annotated chart), the tables the composer can mention, and
 * the answers it writes for new questions. Answers are read from the question's words, the
 * tables it mentions, the format, the range and the comparison, so every option changes them.
 */

export type Tone = 'green' | 'violet' | 'amber' | 'red' | 'blue';

/** One line of the annotated chart. */
export type Series = {
  id: string;
  name: string;
  tone: Tone;
  /** One value a day, in percent. */
  values: number[];
  /** From this day on the line runs off the level it was expected at: drawn red, the gap hatched. */
  anomaly?: { from: number; expected: number };
};

export type LineChartSpec = {
  title: string;
  /** The day labels, one per value. */
  days: string[];
  series: Series[];
  /** A vertical marker on a day: a release, an incident. */
  marker?: { index: number; label: string; sub: string };
  /** The y axis, in percent. */
  min: number;
  max: number;
  ticks: number[];
  /** Under the chart, left: what it covers. Right: the headline. */
  caption: string;
  headline: string;
  /** What the chart shows, in words, for screen readers. */
  describe: string;
};

/** A table cell: text, or a change coloured by its direction. */
export type Cell = string | { text: string; tone: 'up' | 'down' | 'flat' };
export type TableSpec = { columns: string[]; rows: Cell[][]; caption: string };

/** A short bar chart in an answer: each bar now, and where it was before. */
export type BarSpec = {
  title: string;
  bars: { label: string; value: number; before: number }[];
  max: number;
  unit: '%' | '';
  /** Ticks on the bars where they were before. */
  marks: boolean;
  caption: string;
};

export type Query = { sql: string; rows: string; ms: number };

export type Source = {
  id: string;
  kind: 'table' | 'doc';
  name: string;
  /** The preview's first line: rows and freshness, or the doc's date. */
  meta: string;
  /** A table's columns, or a doc's lines. */
  lines: string[];
};

export type Thread = {
  title: string;
  question: string;
  thought: { seconds: number; queries: Query[] };
  answer: string;
  sources: Source[];
  chart?: LineChartSpec;
  /** In place of the chart. */
  table?: TableSpec;
  followUp: string;
  /** A suggested next question, as a chip. */
  suggestion: string;
};

export type Format = 'text' | 'chart' | 'table';
export type RangeId = '7d' | '30d' | '90d';
export type Model = { id: string; name: string; note: string; seconds: number };

export const RANGES: { id: RangeId; label: string; phrase: string }[] = [
  { id: '7d', label: 'Last 7 days', phrase: 'over the last 7 days' },
  { id: '30d', label: 'Last 30 days', phrase: 'over the last 30 days' },
  { id: '90d', label: 'Last 90 days', phrase: 'over the last 90 days' },
];

export const MODELS: Model[] = [
  { id: 'wren-2', name: 'Wren 2', note: 'Reads, queries and charts', seconds: 9 },
  { id: 'wren-2-fast', name: 'Wren 2 Fast', note: 'Quick answers, one query', seconds: 3 },
  { id: 'wren-2-deep', name: 'Wren 2 Deep', note: 'Checks its work twice', seconds: 26 },
];

/** The tables the composer's @ menu lists. */
export const TABLES: { name: string; rows: string }[] = [
  { name: 'signups', rows: '12.4k rows' },
  { name: 'events', rows: '2.1M rows' },
  { name: 'sessions', rows: '418k rows' },
  { name: 'accounts', rows: '9.8k rows' },
];

const TABLE_SOURCES: Record<string, Source> = {
  events: {
    id: 'events',
    kind: 'table',
    name: 'events',
    meta: '2.1M rows · synced 4 min ago',
    lines: ['user_id', 'platform', 'step', 'app_version', 'ts'],
  },
  signups: {
    id: 'signups',
    kind: 'table',
    name: 'signups',
    meta: '12.4k rows · synced 4 min ago',
    lines: ['user_id', 'platform', 'channel', 'verified_at', 'created_at'],
  },
  sessions: {
    id: 'sessions',
    kind: 'table',
    name: 'sessions',
    meta: '418k rows · synced 12 min ago',
    lines: ['session_id', 'user_id', 'platform', 'started_at', 'length_s'],
  },
  accounts: {
    id: 'accounts',
    kind: 'table',
    name: 'accounts',
    meta: '9.8k rows · synced 1 h ago',
    lines: ['account_id', 'plan', 'seats', 'region', 'created_at'],
  },
};

const RELEASE_LOG: Source = {
  id: 'release_log',
  kind: 'doc',
  name: 'release_log',
  meta: 'Doc · edited Oct 13',
  lines: [
    '2.14 · Oct 13 · Android: verification links open in the in-app browser.',
    '2.13 · Sep 29 · Faster cold start on iOS and Android.',
  ],
};

const OCT = (from: number, count: number) =>
  Array.from({ length: count }, (_, i) => `Oct ${from + i}`);

/** The thread it opens on: activation fell after a release. */
export const ACTIVATION: Thread = {
  title: 'Activation drop, last 14 days',
  question: 'Why did activation drop last week?',
  thought: {
    seconds: 12,
    queries: [
      {
        sql: "select step, platform, count(*) from events where ts >= 'Oct 6' group by 1, 2",
        rows: '42 rows',
        ms: 820,
      },
      {
        sql: 'select day, platform, avg(verified_at is not null) from signups group by 1, 2',
        rows: '42 rows',
        ms: 310,
      },
      {
        sql: "select version, shipped_at, notes from release_log where shipped_at >= 'Oct 1'",
        rows: '1 row',
        ms: 90,
      },
    ],
  },
  answer:
    'Activation fell from 41% to 33%. Nearly all of the loss is at email verification, and it is all in Android sign-ups since the 2.14 release.',
  sources: [TABLE_SOURCES.events, TABLE_SOURCES.signups, RELEASE_LOG],
  chart: {
    title: 'Email verified, by platform',
    days: OCT(6, 14),
    series: [
      {
        id: 'android',
        name: 'Android',
        tone: 'green',
        values: [79, 79, 78, 80, 79, 79, 79, 79, 66, 53, 48, 45, 46, 44],
        anomaly: { from: 7, expected: 79 },
      },
      {
        id: 'ios',
        name: 'iOS',
        tone: 'violet',
        values: [85, 85, 84, 86, 85, 85, 86, 85, 85, 84, 85, 86, 85, 85],
      },
      {
        id: 'web',
        name: 'Web',
        tone: 'amber',
        values: [90, 90, 89, 91, 90, 90, 91, 90, 89, 90, 91, 90, 90, 91],
      },
    ],
    marker: { index: 7, label: '2.14 shipped', sub: 'Oct 13' },
    min: 30,
    max: 96,
    ticks: [40, 60, 80],
    caption: 'Daily, Oct 6 – 19 · dashed = expected',
    headline: 'Activated 33% · was 41%',
    describe:
      'Line chart of the share of sign-ups who verified their email, by day from October 6 to 19. Web holds near 90% and iOS near 85%. Android holds near 79% until release 2.14 ships on October 13, then falls to 44% by October 19, 35 points under its expected level.',
  },
  followUp:
    'Since 2.14, Android opens the verification link in an in-app browser that drops the session, and a third of those users never return to the app. Sending the link back to the system browser, as 2.13 did, should win back most of the drop.',
  suggestion: 'Compare 2.13 vs 2.14',
};

/** A second thread: a spike, not a drop. */
export const REFUNDS: Thread = {
  title: 'Refund spike on Tuesday',
  question: 'Why did refunds jump on Tuesday?',
  thought: {
    seconds: 8,
    queries: [
      {
        sql: "select day, method, refunds / orders from payments where day >= 'Oct 13' group by 1, 2",
        rows: '21 rows',
        ms: 640,
      },
      {
        sql: "select reason, count(*) from refunds where day = 'Oct 21' group by 1 order by 2 desc",
        rows: '6 rows',
        ms: 210,
      },
    ],
  },
  answer:
    'Refunds on card orders spiked on Tuesday to 24%, against a usual 6%. Wallet and bank transfer orders stayed flat, and most of Tuesday’s refunds give the same reason: charged twice.',
  sources: [
    {
      id: 'payments',
      kind: 'table',
      name: 'payments',
      meta: '86k rows · synced 2 min ago',
      lines: ['order_id', 'method', 'amount', 'status', 'day'],
    },
    {
      id: 'incident',
      kind: 'doc',
      name: 'incident_2207',
      meta: 'Doc · opened Oct 21',
      lines: ['Oct 21 · 09:40 · Card retries sent twice after a gateway timeout.'],
    },
  ],
  chart: {
    title: 'Refund rate, by payment method',
    days: OCT(13, 9),
    series: [
      {
        id: 'card',
        name: 'Card',
        tone: 'blue',
        values: [6, 5, 6, 6, 5, 6, 6, 6, 24],
        anomaly: { from: 7, expected: 6 },
      },
      { id: 'wallet', name: 'Wallet', tone: 'violet', values: [4, 4, 3, 4, 4, 3, 4, 4, 4] },
      { id: 'bank', name: 'Bank', tone: 'amber', values: [2, 2, 2, 3, 2, 2, 2, 2, 3] },
    ],
    marker: { index: 7, label: 'Gateway timeout', sub: 'Oct 20, 21:50' },
    min: 0,
    max: 30,
    ticks: [0, 10, 20],
    caption: 'Daily, Oct 13 – 21 · dashed = expected',
    headline: 'Refunds 9.1% · usually 4.4%',
    describe:
      'Line chart of the refund rate by payment method, by day from October 13 to 21. Wallet stays near 4% and bank transfer near 2%. Card holds near 6% until a gateway timeout late on October 20, then jumps to 24% on October 21, 18 points over its expected level.',
  },
  followUp:
    'The timeout made the checkout retry card charges it had already taken. Refunding the duplicates is under way; a retry key on the gateway call would stop it happening again.',
  suggestion: 'List the double charges',
};

/** A thread answered with a table instead of a chart. */
export const CHURN: Thread = {
  title: 'September churn by plan',
  question: 'Which plans churned most in September?',
  thought: {
    seconds: 6,
    queries: [
      {
        sql: "select plan, count(*) filter (where cancelled_at >= 'Sep 1') from accounts group by 1",
        rows: '4 rows',
        ms: 380,
      },
    ],
  },
  answer:
    'Starter lost the most accounts in September, 6.8% of them, up from 4.9% in August. Team and Business churned less than the month before.',
  sources: [TABLE_SOURCES.accounts],
  table: {
    columns: ['Plan', 'Accounts', 'Churned', 'Rate', 'vs August'],
    rows: [
      ['Starter', '5,412', '368', '6.8%', { text: '+1.9 pts', tone: 'down' }],
      ['Team', '2,960', '89', '3.0%', { text: '–0.4 pts', tone: 'up' }],
      ['Business', '1,204', '17', '1.4%', { text: '–0.2 pts', tone: 'up' }],
      ['Enterprise', '231', '1', '0.4%', { text: '0.0 pts', tone: 'flat' }],
    ],
    caption: 'September 2026 · churn is accounts cancelled over accounts at the start',
  },
  followUp:
    'Two thirds of the Starter cancellations came in the first 30 days, most of them from the annual-to-monthly switch in the pricing page test.',
  suggestion: 'Show Starter by signup month',
};

/** What the assistant writes back to a new question. */
export type Answer = {
  text: string;
  queries: Query[];
  sources: Source[];
  bars?: BarSpec;
  table?: TableSpec;
};

/** The figures a range shows: the full drop over a week, diluted over longer ranges. */
const DILUTE: Record<RangeId, number> = { '7d': 1, '30d': 0.45, '90d': 0.18 };
const COUNT: Record<RangeId, number> = { '7d': 1, '30d': 4.3, '90d': 12.9 };

const pct = (n: number) => `${Math.round(n)}%`;
const pts = (n: number) => `${n > 0 ? '+' : n < 0 ? '–' : ''}${Math.abs(Math.round(n))} pts`;
const thousands = (n: number) => Math.round(n).toLocaleString('en-US');

type Row = { label: string; value: number; before: number; count: number };

function shape(
  rows: Row[],
  {
    title,
    head,
    metric,
    range,
    compare,
    format,
  }: {
    title: string;
    head: string;
    metric: string;
    range: RangeId;
    compare: boolean;
    format: Format;
  },
): Pick<Answer, 'bars' | 'table'> {
  const mixed = rows.map((row) => ({
    ...row,
    value: row.before - (row.before - row.value) * DILUTE[range],
    count: row.count * COUNT[range],
  }));
  const label = RANGES.find((r) => r.id === range)!.label;
  if (format === 'chart')
    return {
      bars: {
        title,
        bars: mixed.map(({ label, value, before }) => ({ label, value, before })),
        max: 100,
        unit: '%',
        marks: compare,
        caption: compare ? `${label} · ticks mark last week` : label,
      },
    };
  if (format === 'table')
    return {
      table: {
        columns: [head, 'Sign-ups', metric, ...(compare ? ['vs last week'] : [])],
        rows: mixed.map((row) => [
          row.label,
          thousands(row.count),
          pct(row.value),
          ...(compare
            ? [
                {
                  text: pts(row.value - row.before),
                  tone:
                    Math.round(row.value - row.before) < 0
                      ? ('down' as const)
                      : Math.round(row.value - row.before) > 0
                        ? ('up' as const)
                        : ('flat' as const),
                },
              ]
            : []),
        ]),
        caption: label,
      },
    };
  return {};
}

/**
 * The answer to a new question. It reads the question for a breakdown by channel or a
 * comparison of versions; anything else gets activation by platform.
 */
export function answerFor({
  question,
  mentions,
  format,
  range,
  compare,
  model,
}: {
  question: string;
  mentions: string[];
  format: Format;
  range: RangeId;
  compare: boolean;
  model: Model;
}): Answer {
  const q = question.toLowerCase();
  const phrase = RANGES.find((r) => r.id === range)!.phrase;
  const sources = mentions.map((name) => TABLE_SOURCES[name]).filter(Boolean);
  const plus = (list: Source[]) => [
    ...sources,
    ...list.filter((s) => !sources.some((m) => m.id === s.id)),
  ];
  const one = <T>(list: T[]) => (model.id === 'wren-2-fast' ? list.slice(0, 1) : list);

  if (/channel|source|utm/.test(q)) {
    const rows: Row[] = [
      { label: 'Paid social', value: 41, before: 77, count: 3120 },
      { label: 'Organic', value: 46, before: 79, count: 4870 },
      { label: 'Referral', value: 52, before: 80, count: 1960 },
      { label: 'Partner', value: 74, before: 81, count: 1380 },
    ];
    const worst = rows[0];
    const now = worst.before - (worst.before - worst.value) * DILUTE[range];
    return {
      text: `Android sign-ups from paid social took the biggest hit ${phrase}: ${pct(now)} verified their email, ${compare ? 'against' : 'down from'} ${pct(worst.before)}${compare ? ' last week' : ''}. Partner sign-ups barely moved, because partner accounts are verified by single sign-on and never get the link.`,
      queries: one([
        {
          sql: `select channel, avg(verified_at is not null) from signups where platform = 'android' group by 1`,
          rows: '4 rows',
          ms: 280,
        },
        {
          sql: `select channel, count(*) from signups where created_at >= now() - interval '${range.replace('d', ' days')}' group by 1`,
          rows: '4 rows',
          ms: 190,
        },
      ]),
      sources: plus([TABLE_SOURCES.signups]),
      ...shape(rows, {
        title: 'Android email verified, by channel',
        head: 'Channel',
        metric: 'Verified',
        range,
        compare,
        format,
      }),
    };
  }

  if (/2\.13|compare|version|release/.test(q)) {
    const rows: Row[] = [
      { label: 'Code sent', value: 97, before: 98, count: 2410 },
      { label: 'Link opened', value: 52, before: 81, count: 1250 },
      { label: 'Back in app', value: 45, before: 80, count: 1085 },
      { label: 'Verified', value: 44, before: 79, count: 1060 },
    ];
    return {
      text: `Side by side, 2.14 sends the code as reliably as 2.13, but only ${pct(52)} of Android users open the link, against ${pct(81)} on 2.13. After that the steps hold, so the loss is all at the link.`,
      queries: one([
        {
          sql: "select app_version, step, count(*) from events where platform = 'android' and app_version in ('2.13', '2.14') group by 1, 2",
          rows: '8 rows',
          ms: 540,
        },
      ]),
      sources: plus([TABLE_SOURCES.events, RELEASE_LOG]),
      ...(format === 'chart'
        ? {
            bars: {
              title: 'Android verification steps, 2.14',
              bars: rows.map(({ label, value, before }) => ({ label, value, before })),
              max: 100,
              unit: '%' as const,
              marks: true,
              caption: '2.14 · ticks mark 2.13',
            },
          }
        : format === 'table'
          ? {
              table: {
                columns: ['Step', '2.13', '2.14', 'Change'],
                rows: rows.map((row) => [
                  row.label,
                  pct(row.before),
                  pct(row.value),
                  {
                    text: pts(row.value - row.before),
                    tone: row.value - row.before <= -2 ? ('down' as const) : ('flat' as const),
                  },
                ]),
                caption: 'Android users who started verification',
              },
            }
          : {}),
    };
  }

  const rows: Row[] = [
    { label: 'Android', value: 24, before: 39, count: 5240 },
    { label: 'iOS', value: 41, before: 42, count: 3910 },
    { label: 'Web', value: 38, before: 40, count: 3250 },
  ];
  const android = rows[0].before - (rows[0].before - rows[0].value) * DILUTE[range];
  return {
    text: `Activation ${phrase} is lowest on Android, at ${pct(android)}${compare ? `, from ${pct(rows[0].before)} last week` : ''}. iOS and Web are within two points of where they were, so the drop is still the Android verification link.`,
    queries: one([
      {
        sql: 'select platform, avg(activated) from signups group by 1',
        rows: '3 rows',
        ms: 240,
      },
      {
        sql: "select platform, count(*) from events where step = 'activated' group by 1",
        rows: '3 rows',
        ms: 410,
      },
    ]),
    sources: plus([TABLE_SOURCES.signups]),
    ...shape(rows, {
      title: 'Activated, by platform',
      head: 'Platform',
      metric: 'Activated',
      range,
      compare,
      format,
    }),
  };
}
```

### insight-thread/menu.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import {
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
  type KeyboardEvent as ReactKeyboardEvent,
  type ReactNode,
} from 'react';
import { Icon } from './glyphs';
import styles from './insight-thread.module.css';

/*
 * The menus: placed on the stage under their trigger (over it when there is no room below), in
 * the stage's own px, since a gallery card may scale the whole stage. The arrows, Home and End
 * move between items; Escape closes and gives the focus back; a press elsewhere closes.
 */

const ITEMS = '[role="menuitem"], [role="menuitemradio"]';

export function Menu({
  anchor,
  label,
  align = 'start',
  takeFocus,
  onClose,
  children,
}: {
  anchor: HTMLElement;
  label: string;
  align?: 'start' | 'end';
  /** Moves the focus to the checked or first item: when the reader opened it, not the demo. */
  takeFocus: boolean;
  /** `back`: give the focus back to the trigger. */
  onClose: (back: boolean) => void;
  children: ReactNode;
}) {
  const box = useRef<HTMLDivElement>(null);
  const [at, setAt] = useState<{ x: number; y: number } | null>(null);

  useLayoutEffect(() => {
    const menu = box.current;
    const frame = menu?.offsetParent as HTMLElement | null;
    if (!frame || !menu) return;
    const place = () => {
      const s = frame.getBoundingClientRect();
      const scale = s.width / frame.offsetWidth || 1;
      const a = anchor.getBoundingClientRect();
      const left = (a.left - s.left) / scale;
      const right = (a.right - s.left) / scale;
      const top = (a.top - s.top) / scale;
      const bottom = (a.bottom - s.top) / scale;
      const w = menu.offsetWidth;
      const h = menu.offsetHeight;
      let x = align === 'end' ? right - w : left;
      x = Math.max(8, Math.min(x, frame.clientWidth - w - 8));
      let y = bottom + 6;
      if (y + h > frame.clientHeight - 8 && top - h - 6 > 8) y = top - h - 6;
      setAt({ x, y });
    };
    place();
    const observer = new ResizeObserver(place);
    observer.observe(menu);
    return () => observer.disconnect();
  }, [anchor, align]);

  useEffect(() => {
    if (!takeFocus || !at) return;
    box.current
      ?.querySelector<HTMLElement>('[aria-checked="true"], [role^="menuitem"]')
      ?.focus({ preventScroll: true });
    // Only when it first shows.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [takeFocus, at === null]);

  useEffect(() => {
    const away = (event: PointerEvent) => {
      const target = event.target as Node;
      if (box.current?.contains(target) || anchor.contains(target)) return;
      onClose(false);
    };
    document.addEventListener('pointerdown', away);
    return () => document.removeEventListener('pointerdown', away);
  }, [anchor, onClose]);

  const onKeyDown = (event: ReactKeyboardEvent) => {
    const items = [...(box.current?.querySelectorAll<HTMLElement>(ITEMS) ?? [])];
    const index = items.indexOf(document.activeElement as HTMLElement);
    const move = (to: number) => {
      event.preventDefault();
      items[(to + items.length) % items.length]?.focus();
    };
    if (event.key === 'ArrowDown') move(index + 1);
    else if (event.key === 'ArrowUp') move(index - 1);
    else if (event.key === 'Home') move(0);
    else if (event.key === 'End') move(items.length - 1);
    else if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      onClose(true);
    } else if (event.key === 'Tab') onClose(false);
  };

  return (
    <div
      ref={box}
      role="menu"
      tabIndex={-1}
      aria-label={label}
      className={styles.menu}
      data-part="menu"
      style={{
        transform: at ? `translate(${at.x}px, ${at.y}px)` : undefined,
        visibility: at ? undefined : 'hidden',
      }}
      onKeyDown={onKeyDown}
    >
      {children}
    </div>
  );
}

export function MenuItem({
  onSelect,
  checked,
  radio,
  tone,
  demo,
  lead,
  trail,
  children,
}: {
  onSelect: () => void;
  checked?: boolean;
  /** One of a set: it shows a check when chosen. */
  radio?: boolean;
  tone?: 'danger';
  demo?: string;
  /** Before the text: an icon, a face. */
  lead?: ReactNode;
  /** At the right end: a count. */
  trail?: ReactNode;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      role={radio ? 'menuitemradio' : 'menuitem'}
      aria-checked={radio ? !!checked : undefined}
      tabIndex={-1}
      className={styles.menuItem}
      data-tone={tone}
      data-demo={demo}
      onClick={onSelect}
    >
      {lead}
      <span className={styles.menuText}>{children}</span>
      {trail !== undefined && <span className={styles.menuTrail}>{trail}</span>}
      {radio && checked && <Icon name="check" className={styles.menuCheck} width={2.2} />}
    </button>
  );
}

export function MenuLabel({ children }: { children: ReactNode }) {
  return (
    <div className={styles.menuLabel} role="presentation">
      {children}
    </div>
  );
}
```

### insight-thread/glyphs.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

/*
 * The thread's line icons: a 24-unit box, drawn with currentColor. The sparkle is filled.
 */

const PATHS = {
  chevronDown: 'M7 10l5 5 5-5',
  chevronRight: 'M10 7l5 5-5 5',
  share: 'M12 15V4M7.5 8.5 12 4l4.5 4.5M5 13v6.5h14V13',
  table: 'M4 5h16v14H4zM4 10h16M10 10v9',
  doc: 'M7 3.5h7l4 4V20.5H7zM14 3.5V8h4',
  copy: 'M9 9h11v11H9zM5 15V4h11',
  thumb:
    'M7.5 10.5v9M7.5 10.5l3.6-6.3c1.2 0 2.2 1 2.1 2.3l-.4 3.2h5c1.1 0 1.9 1 1.7 2.1l-1.2 6.2c-.2.9-1 1.5-1.9 1.5H7.5M7.5 10.5H4v9h3.5',
  plus: 'M12 5v14M5 12h14',
  lines: 'M5 7h14M5 12h14M5 17h9',
  bars: 'M5 4v15.5h15M9 16v-5M13 16V8M17 16v-7',
  calendar: 'M4.5 6h15v14h-15zM4.5 10h15M8.5 3.5v4M15.5 3.5v4',
  mic: 'M12 3.5a3 3 0 0 0-3 3v5a3 3 0 0 0 6 0v-5a3 3 0 0 0-3-3zM6 11.5a6 6 0 0 0 12 0M12 17.5v3',
  arrowUp: 'M12 19V5M6.5 10.5 12 5l5.5 5.5',
  enter: 'M19 6v5a3 3 0 0 1-3 3H6M9.5 10.5 6 14l3.5 3.5',
  check: 'M5 12.5l4.5 4.5L19 7.5',
  query:
    'M5 6c0-1.4 3.1-2.5 7-2.5s7 1.1 7 2.5-3.1 2.5-7 2.5S5 7.4 5 6zM5 6v12c0 1.4 3.1 2.5 7 2.5s7-1.1 7-2.5V6M5 12c0 1.4 3.1 2.5 7 2.5s7-1.1 7-2.5',
} as const;

export type IconName = keyof typeof PATHS;

export function Icon({
  name,
  className,
  width = 1.75,
}: {
  name: IconName;
  className?: string;
  width?: number;
}) {
  return (
    <svg
      viewBox="0 0 24 24"
      className={className}
      fill="none"
      stroke="currentColor"
      strokeWidth={width}
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d={PATHS[name]} />
    </svg>
  );
}

/** The assistant's sparkle: a four-pointed star with concave sides. */
export function Sparkle({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden="true">
      <path
        d="M12 2.5c.5 4.6 2.9 7 9.5 9.5-6.6 2.5-9 4.9-9.5 9.5-.5-4.6-2.9-7-9.5-9.5 6.6-2.5 9-4.9 9.5-9.5z"
        fill="none"
        stroke="currentColor"
        strokeWidth="1.7"
        strokeLinejoin="round"
      />
    </svg>
  );
}

/** A square to stop an answer. */
export function StopSquare({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" className={className} aria-hidden="true">
      <rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" />
    </svg>
  );
}
```

### insight-thread/demo-pointer.tsx

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import type { CSSProperties, Ref } from 'react';

/*
 * The demo's pointer, and the steps that move it. A demo is a script of awaited steps: wait, or
 * glide the pointer somewhere. Stopping the demo (the reader takes over, or it scrolls away) ends
 * the step in progress at once: its promise rejects, which ends the script right there, and the
 * pointer fades out.
 *
 * Each glide is a curved flight played by the Web Animations API, so nothing runs frame by frame.
 * The points of the flight are handed to whoever wants to move along with it. The arrow and the
 * hand are HTML boxes
 * that swap by their visibility: a change of style inside an SVG would lay the SVG out again.
 */

export type Point = { x: number; y: number };

/** A glide's path and timing, for an animation that plays along with it. */
export type Flight = { points: Point[]; timing: KeyframeAnimationOptions };

export type Demo = {
  /** Resolves after `ms`. */
  wait: (ms: number) => Promise<void>;
  /** Glides the pointer to `to`, in the stage's own px, in `ms`; `along` gets the flight. */
  glide: (to: Point, ms: number, along?: (flight: Flight) => void) => Promise<void>;
  /** Shows the arrow, or the hand a link shows. */
  glyph: (name: 'arrow' | 'hand') => void;
};

/** What a stopped demo's pending step rejects with. */
class Stopped extends Error {}

/** Where the arrow's tip is, as shares of its box: the point the pointer stands on. */
const TIP: Point = { x: 0.15, y: 0.1 };

/** How many points a flight is drawn through. */
const SAMPLES = 24;

/** Plays `script` with the pointer over `stage`; returns the function that stops it. */
export function runDemo(
  stage: HTMLElement,
  pointer: HTMLElement,
  script: (demo: Demo) => Promise<void>,
): () => void {
  let alive = true;
  let flight: Animation | null = null;
  // The stylesheet sizes the pointer from the stage's width; its tip is where it stands.
  const tip = { x: pointer.offsetWidth * TIP.x, y: pointer.offsetHeight * TIP.y };
  const place = ({ x, y }: Point) => `translate(${x - tip.x}px, ${y - tip.y}px)`;
  const timers = new Set<number>();
  const pending = new Set<() => void>();
  // The pointer comes in from the lower right.
  let at: Point = { x: stage.offsetWidth * 0.8, y: stage.offsetHeight * 0.9 };

  /** Settles like `promise`, or rejects as soon as the demo stops. */
  const step = (promise: Promise<unknown>) =>
    new Promise<void>((resolve, reject) => {
      if (!alive) return reject(new Stopped());
      const cancel = () => reject(new Stopped());
      pending.add(cancel);
      promise.then(
        () => {
          pending.delete(cancel);
          if (alive) resolve();
        },
        () => {
          pending.delete(cancel);
          reject(new Stopped());
        },
      );
    });

  const wait = (ms: number) =>
    step(
      new Promise<void>((resolve) => {
        const timer = window.setTimeout(() => {
          timers.delete(timer);
          resolve();
        }, ms);
        timers.add(timer);
      }),
    );

  const glide: Demo['glide'] = (to, ms, along) => {
    const from = at;
    at = to;
    const dx = to.x - from.x;
    const dy = to.y - from.y;
    // A gentle curve, as a hand moves: the control point sits off the straight line.
    const bend = { x: (from.x + to.x) / 2 - dy * 0.18, y: (from.y + to.y) / 2 + dx * 0.18 };
    const points: Point[] = [];
    for (let i = 0; i <= SAMPLES; i += 1) {
      const t = i / SAMPLES;
      const u = 1 - t;
      points.push({
        x: u * u * from.x + 2 * u * t * bend.x + t * t * to.x,
        y: u * u * from.y + 2 * u * t * bend.y + t * t * to.y,
      });
    }
    const timing: KeyframeAnimationOptions = {
      duration: ms,
      easing: 'cubic-bezier(0.45, 0, 0.25, 1)',
    };
    flight?.cancel();
    // Where it rests once the flight is over.
    pointer.style.transform = place(to);
    flight = pointer.animate(
      points.map((point) => ({ transform: place(point) })),
      timing,
    );
    along?.({ points, timing });
    return step(flight.finished);
  };

  const glyph: Demo['glyph'] = (name) => {
    pointer.dataset.glyph = name;
  };

  pointer.dataset.glyph = 'arrow';
  pointer.style.transform = place(at);
  pointer.style.opacity = '1';
  script({ wait, glide, glyph }).catch((error: unknown) => {
    if (!(error instanceof Stopped)) throw error;
  });

  return () => {
    if (!alive) return;
    alive = false;
    timers.forEach((timer) => window.clearTimeout(timer));
    flight?.cancel();
    pending.forEach((cancel) => cancel());
    pointer.style.opacity = '0';
  };
}

/**
 * The pointer's box: it moves, on a layer of its own. Its size comes from its class, its colours
 * from the stage's tokens (insight-thread.module.css).
 */
const POINTER: CSSProperties = {
  position: 'absolute',
  top: 0,
  left: 0,
  zIndex: 2,
  display: 'block',
  pointerEvents: 'none',
  opacity: 0,
  transition: 'opacity 0.3s ease',
  filter: 'drop-shadow(0 1px 1.5px var(--pointer-shadow))',
  willChange: 'transform',
};

/** One glyph over the other, each filling the box. */
const GLYPH: CSSProperties = { position: 'absolute', inset: 0, display: 'block' };
const DRAWING: CSSProperties = {
  display: 'block',
  width: '100%',
  height: '100%',
  overflow: 'visible',
};
/** The arrow is dark on a white edge, the hand white on a dark one, as the system draws them. */
const ARROW: CSSProperties = { fill: 'var(--pointer)', stroke: 'var(--pointer-edge)' };
const HAND: CSSProperties = { fill: 'var(--pointer-edge)', stroke: 'var(--pointer)' };

/**
 * The pointer the demo moves around: an arrow, or a pointing hand over what it can press. It is
 * decorative: what it does shows on the thread itself. The stylesheet shows one glyph at a time,
 * from the box's data-glyph.
 */
export function DemoPointer({
  ref,
  className,
  arrowClass,
  handClass,
}: {
  ref: Ref<HTMLSpanElement>;
  className?: string;
  arrowClass?: string;
  handClass?: string;
}) {
  return (
    <span ref={ref} className={className} style={POINTER} aria-hidden="true">
      <span className={arrowClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          <path
            d="M3 2v14.5l3.6-3.3 2.6 5.6 2.4-1.1-2.6-5.5h5.2z"
            style={ARROW}
            strokeWidth="1.3"
            strokeLinejoin="round"
          />
        </svg>
      </span>
      <span className={handClass} style={GLYPH}>
        <svg viewBox="0 0 20 20" style={DRAWING}>
          {/* The tip of the finger sits where the arrow's tip is. */}
          <path
            d="M6.4 3.3c0-.8.6-1.4 1.3-1.4S9 2.5 9 3.3v5.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.5c.2-.5.6-.8 1.2-.8.7 0 1.2.5 1.2 1.2v.7c.2-.4.6-.7 1.1-.7.7 0 1.2.5 1.2 1.2v3.5c0 2.8-1.9 4.9-4.6 4.9h-1.2c-1.8 0-3.1-.8-4.1-2.3l-2.6-3.9c-.4-.6-.2-1.3.4-1.7.6-.3 1.3-.2 1.7.4l.6.9z"
            style={HAND}
            strokeWidth="1.1"
            strokeLinejoin="round"
            transform="translate(-4.7 0.1)"
          />
        </svg>
      </span>
    </span>
  );
}
```

### insight-thread/use-autoplay.ts

```tsx
// Copyright (c) 2026 Bruno Delorence. MIT License.

'use client';

import { useCallback, useEffect, useRef, useState } from 'react';

/*
 * When a demo may play on its own: while part of it is on screen and the tab is visible, never
 * under reduced motion, and never again once the reader has used it. `take()` (a press, a key or
 * the wheel) hands it to the reader for good, until the component remounts. `pause()` (the
 * pointer moving over it) only holds it, and it carries on `idle` ms after the pointer stops.
 */
export function useAutoplay<T extends HTMLElement>(idle = 6000) {
  const ref = useRef<T>(null);
  const [visible, setVisible] = useState(false);
  const [reduced, setReduced] = useState(true);
  const [taken, setTaken] = useState(false);
  const [paused, setPaused] = useState(false);
  const timer = useRef(0);

  useEffect(() => {
    const element = ref.current;
    if (!element) return;
    let onScreen = false;
    const update = () => setVisible(onScreen && !document.hidden);
    const observer = new IntersectionObserver(
      ([entry]) => {
        onScreen = entry.isIntersecting;
        update();
      },
      { threshold: 0.3 },
    );
    observer.observe(element);
    document.addEventListener('visibilitychange', update);
    const motion = window.matchMedia('(prefers-reduced-motion: reduce)');
    const readMotion = () => setReduced(motion.matches);
    readMotion();
    motion.addEventListener('change', readMotion);
    return () => {
      observer.disconnect();
      document.removeEventListener('visibilitychange', update);
      motion.removeEventListener('change', readMotion);
    };
  }, []);

  const take = useCallback(() => {
    setTaken(true);
    window.clearTimeout(timer.current);
  }, []);
  const pause = useCallback(() => {
    setPaused(true);
    window.clearTimeout(timer.current);
    timer.current = window.setTimeout(() => setPaused(false), idle);
  }, [idle]);
  useEffect(() => () => window.clearTimeout(timer.current), []);

  return { ref, take, pause, visible, reduced, playing: visible && !reduced && !taken && !paused };
}
```