A local-first multi-agent app development platform, built on PenguinHarness
feat(ui,web): streaming replies reveal per theme — Frost fades in from a glow, Console types (#898)
Yaowei Zhengbdd5f9d88077
diff --git a/changelog/unreleased/2026-09-30-streaming-reveal.md b/changelog/unreleased/2026-09-30-streaming-reveal.mdnew file mode 100644index 00000000..d43f6ed4--- /dev/null+++ b/changelog/unreleased/2026-09-30-streaming-reveal.md@@ -0,0 +1,26 @@+# Streaming replies come in the way the theme reveals them++- **Date:** 2026-09-30+- **Type:** feature+- **Scope:** `web`, `ui`, `ui-gallery`++[中文版](2026-09-30-streaming-reveal.zh.md)++An assistant reply that is still streaming now appears the way the active theme reveals text: Frost fades new text in from a soft glow, Console types it out, and Primer shows each piece the moment it arrives, as before.++## How each theme reveals a reply++- **Frost** lets the reply in word by word, at about 220 characters a second. Its last lines rise out of a soft glow tinted with the accent, which fades once the reply is complete. There is no cursor.+- **Console** types the reply out character by character, at about 90 characters a second, behind a solid block cursor.+- **Primer** is unchanged: text shows as it lands, followed by the pulsing bar.+- With reduced motion on (the system setting, or the gallery's switch), every theme shows text as it arrives, with no glow and no blinking.++## Pacing in Frost and Console++- When the model streams faster than the theme's pace, the reveal speeds up and never falls more than about 1.5 seconds behind. When the stream ends, the rest comes in at the same pace, not all at once.+- Half-typed Markdown does not flicker: a list mark, a heading mark, a code fence or a table rule appears together with the first text after it, so a paragraph never flashes as a heading and a code block opens on its first line. Code highlighting and formulas are applied once the reply is fully shown.+- A reply's stop reason, and a subagent reply's file list, appear once the reply is fully shown.++## Gallery++- Foundations gained a **Streaming** page: a scripted reply plays in bursty chunks under the chosen theme, with a Replay button. A **Chat · streaming** surface keeps a reply streaming in the real app, on a loop.diff --git a/changelog/unreleased/2026-09-30-streaming-reveal.zh.md b/changelog/unreleased/2026-09-30-streaming-reveal.zh.mdnew file mode 100644index 00000000..3df540b0--- /dev/null+++ b/changelog/unreleased/2026-09-30-streaming-reveal.zh.md@@ -0,0 +1,26 @@+# 流式回答按主题的方式显现++- **Date:** 2026-09-30+- **Type:** feature+- **Scope:** `web`, `ui`, `ui-gallery`++[English](2026-09-30-streaming-reveal.md)++仍在流式输出的助手回答,现在按当前主题的方式显现:白领(Frost)让新文字从一层柔和的微光中淡入,极客(Console)逐字打出,通用(Primer)与以前一样,文字一到就显示。++## 各主题怎样显现回答++- **白领**:按词显现,每秒约 220 个字符。末尾几行从带强调色的柔和微光中浮现,回答完整后微光淡去。不显示光标。+- **极客**:逐字打出,每秒约 90 个字符,末尾跟着一个实心块状光标。+- **通用**:不变,文字一到就显示,后面跟着闪烁的竖条。+- 开启减少动效(系统设置或画廊里的开关)时,所有主题都在文字到达时直接显示,没有微光,光标也不闪烁。++## 白领与极客的节奏++- 模型输出快于主题的节奏时,显现会加速,落后始终不超过约 1.5 秒。流结束后,剩余部分按同样的节奏显现完毕,而不是一下子全部出现。+- 写到一半的 Markdown 不会闪烁:列表标记、标题标记、代码围栏或表格分隔行会和其后的第一段文字一起出现,段落不会闪成标题,代码块从第一行开始展开。代码高亮与公式在回答完整显示后才渲染。+- 回答的停止原因,以及子智能体回答的文件列表,在回答完整显示后才出现。++## 画廊++- 「基础 › 组件」下新增 **流式输出** 一页:在所选主题下,把一段预设回答按突发式的分块播放出来,并提供重播按钮。新增 **对话 · 流式输出** 场景,在真实应用里循环播放一段流式回答。diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.tsindex c43b19b5..8a8b2596 100644--- a/packages/ui-gallery/src/app/mock/fixtures.ts+++ b/packages/ui-gallery/src/app/mock/fixtures.ts@@ -179,8 +179,8 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {),createdAt: iso(ago(90)),updatedAt: iso(ago(1, 30)),- activeSessionCount: 3,- sessionCount: 11,+ activeSessionCount: 4,+ sessionCount: 12,sessionActivity: activity(7, 6),toolCount: 6,version: 14,@@ -452,6 +452,16 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {lastActiveAt: iso(ago(0, 0)),},),+ session(+ IDS.sessions.streaming,+ IDS.agents.docs,+ L("讲解引用校验", "Explain the citation guard"),+ ago(0, 2.5),+ {+ status: "running",+ lastActiveAt: iso(ago(0, 0)),+ },+ ),session(IDS.sessions.runningTool,IDS.agents.docs,diff --git a/packages/ui-gallery/src/app/mock/ids.ts b/packages/ui-gallery/src/app/mock/ids.tsindex dcd5ec30..88ffb0df 100644--- a/packages/ui-gallery/src/app/mock/ids.ts+++ b/packages/ui-gallery/src/app/mock/ids.ts@@ -14,6 +14,8 @@ export const IDS = {runningTool: "s-link-check",/** A Task mid-run: the model thinking, the text still streaming in. */thinking: "s-release-plan",+ /** A Task mid-run: the reply streaming in, played on a loop while the Session is watched. */+ streaming: "s-citation-guard",/** A Task waiting on a human: a command that needs approval. */approval: "s-publish",/** Older conversations that fill the list. */@@ -40,6 +42,7 @@ export const ALL_SESSION_IDS: readonly string[] = [IDS.sessions.done,IDS.sessions.runningTool,IDS.sessions.thinking,+ IDS.sessions.streaming,IDS.sessions.approval,...IDS.sessions.older,IDS.sessions.archived,diff --git a/packages/ui-gallery/src/app/mock/store.ts b/packages/ui-gallery/src/app/mock/store.tsindex 736fd0b8..d951b800 100644--- a/packages/ui-gallery/src/app/mock/store.ts+++ b/packages/ui-gallery/src/app/mock/store.ts@@ -2,7 +2,8 @@* The in-memory demo store one framed app runs against: the fixtures as mutable state, the* two event channels the app subscribes to (the user channel and one per Session), and the* scripts that keep a running Session running — the executing command, the thinking that- * keeps growing, the command waiting for approval — and stream a reply when a message is sent.+ * keeps growing, the reply that streams on a loop, the command waiting for approval — and+ * stream a reply when a message is sent.** One store per document (a frame is a document), created on first use for the frame's* language, and re-creatable for tests. Nothing here touches the DOM.@@ -11,6 +12,7 @@ import type { ServerEvent, SessionInfo } from "@prismshadow/penguin-server/api";import { buildFixtures, DEFAULT_MODEL } from "./fixtures";import type { DemoFixtures } from "./fixtures";import { IDS } from "./ids";+import { streamScript } from "./stream-script";import {abortEvent,approvalDecision,@@ -24,6 +26,8 @@ import {runningToolTranscript,scriptedReply,shortTranscript,+ streamingAnswer,+ streamingTranscript,thinkingBeats,thinkingTranscript,tokenUsage,@@ -42,6 +46,13 @@ import type { Lang, OmniMessage, StreamHandlers } from "./types";/** The one epoch every id of this store carries: a frame never reconnects to another server. */const EPOCH = "g1";+/** The streaming Session's loop: the wait before a round's stream opens (after the rewind). */+export const REPLY_LEAD_MS = 700;+/** How long the settled reply stays up before the loop rewinds it. */+export const REPLY_HOLD_MS = 2600;+/** The wait between a round's last delta and the fragment's close. */+export const REPLY_CLOSE_MS = 160;+/** A channel: subscribers, and the running id the server stamps on every event. */class Channel {private seq = 0;@@ -83,6 +94,8 @@ interface Live {channel: Channel;/** Timers of a running script, cleared on abort or dispose. */timers: number[];+ /** The history length the looping reply rewinds to (the streaming Session only). */+ loopFrom?: number;}export class DemoStore {@@ -103,6 +116,7 @@ export class DemoStore {[IDS.sessions.done]: doneTranscript(lang, now, ref),[IDS.sessions.runningTool]: runningToolTranscript(lang, now, ref),[IDS.sessions.thinking]: thinkingTranscript(lang, now, ref),+ [IDS.sessions.streaming]: streamingTranscript(lang, now, ref),[IDS.sessions.approval]: approvalTranscript(lang, now, ref),};for (const row of this.f.sessions) {@@ -111,6 +125,8 @@ export class DemoStore {shortTranscript(lang, row.sessionId, Date.parse(row.createdAt), ref);this.live.set(row.sessionId, { transcript, channel: new Channel(), timers: [] });}+ const streaming = this.live.get(IDS.sessions.streaming);+ if (streaming) streaming.loopFrom = streaming.transcript.history.length;}// ---- Sessions --------------------------------------------------------------------------@@ -131,17 +147,27 @@ export class DemoStore {liveTail(sessionId: string): { cursor: string; fragments: OmniMessage[] } | undefined {const live = this.live.get(sessionId);if (!live || !live.transcript.running) return undefined;- const open = live.transcript.openThinking;- const fragments = open- ? [- partial(open.startedAt, {- type: "partial_thinking",- role: "assistant",- event_type: "start",- thinking: open.text,- }),- ]- : [];+ const fragments: OmniMessage[] = [];+ const thinking = live.transcript.openThinking;+ if (thinking)+ fragments.push(+ partial(thinking.startedAt, {+ type: "partial_thinking",+ role: "assistant",+ event_type: "start",+ thinking: thinking.text,+ }),+ );+ const text = live.transcript.openText;+ if (text)+ fragments.push(+ partial(text.startedAt, {+ type: "partial_text",+ role: "assistant",+ event_type: "start",+ text: text.text,+ }),+ );return { cursor: live.channel.cursor, fragments };}@@ -222,6 +248,7 @@ export class DemoStore {const pending = live.transcript.pendingApproval;if (pending) live.channel.event({ type: "approval_request", toolCall: pending }, handlers);if (sessionId === IDS.sessions.thinking) this.keepThinking(live);+ if (sessionId === IDS.sessions.streaming) this.keepStreaming(sessionId, live);}private setStatus(sessionId: string, state: SessionInfo["status"]): void {@@ -285,6 +312,54 @@ export class DemoStore {this.schedule(live, 1600, tick);}+ /**+ * The streaming Session's reply, on a loop while its Task runs. Each round opens the text+ * fragment, streams the answer in bursty deltas (stream-script.ts; the round number seeds it,+ * so no two rounds share a rhythm), closes the fragment with the complete message, and holds+ * it on screen. Then the round is rewound out of the history, and the channel says+ * `resync_required`, the server's own "refetch the history" signal, so the page rebuilds+ * without the old answer and the next round streams in its place. The transcript never grows.+ */+ private keepStreaming(sessionId: string, live: Live): void {+ const from = live.loopFrom;+ if (from === undefined || live.timers.length > 0) return;+ if (this.session(sessionId)?.status !== "running") return;+ const answer = streamingAnswer(this.lang);+ const text = (eventType: "start" | "delta" | "stop", delta: string) =>+ partial(0, { type: "partial_text", role: "assistant", event_type: eventType, text: delta });+ let round = 0;+ const play = () => {+ // Every timer of the previous round has fired; the array holds this round's alone.+ live.timers = [];+ round += 1;+ let at = REPLY_LEAD_MS;+ this.schedule(live, at, () => {+ live.transcript.openText = { startedAt: Date.now(), text: "" };+ this.emit(live, text("start", ""));+ });+ for (const chunk of streamScript(answer, round)) {+ at += chunk.gap;+ this.schedule(live, at, () => {+ if (live.transcript.openText) live.transcript.openText.text += chunk.text;+ this.emit(live, text("delta", chunk.text));+ });+ }+ at += REPLY_CLOSE_MS;+ this.schedule(live, at, () => {+ delete live.transcript.openText;+ this.emit(live, text("stop", ""));+ this.emit(live, assistantText(0, answer));+ });+ at += REPLY_HOLD_MS;+ this.schedule(live, at, () => {+ live.transcript.history.length = from;+ live.channel.event({ type: "resync_required" });+ play();+ });+ };+ play();+ }+/*** A sent message: the Session runs, the prompt is echoed as the user's text, then the* scripted reply streams and the Session settles. The first turn of a new Session also@@ -317,6 +392,22 @@ export class DemoStore {if (!live || !row || row.status === "idle") return;this.stopScript(sessionId);if (live.transcript.openThinking) delete live.transcript.openThinking;+ const open = live.transcript.openText;+ if (open) {+ // The streamed part stays, closed as aborted, as the engine records a cut-off reply.+ delete live.transcript.openText;+ this.emit(+ live,+ partial(0, {+ type: "partial_text",+ role: "assistant",+ event_type: "stop",+ text: "",+ stop_reason: "aborted",+ }),+ );+ if (open.text !== "") this.emit(live, assistantText(0, open.text, "aborted"));+ }if (live.transcript.pendingApproval) {delete live.transcript.pendingApproval;row.pendingApprovalCount = 0;diff --git a/packages/ui-gallery/src/app/mock/stream-script.ts b/packages/ui-gallery/src/app/mock/stream-script.tsnew file mode 100644index 00000000..a1f5d292--- /dev/null+++ b/packages/ui-gallery/src/app/mock/stream-script.ts@@ -0,0 +1,76 @@+/**+ * A streamed reply, scripted: cuts a text into the deltas a real model stream delivers, which+ * arrive in bursts rather than one even token at a time. Sizes vary: mostly a token or three,+ * sometimes a burst of several words the network held back. Gaps vary too: mostly tens of+ * milliseconds, now and then a stall of half a second, after which a burst comes. The script is+ * seeded, so one seed always yields the same script: the library's streaming board replays the+ * same rhythm under every theme, and a test can hold it.+ *+ * No DOM and no timers here: the players (the streaming board, the demo store's looping Session)+ * schedule the steps themselves.+ */++export interface StreamChunk {+ /** The delta's text. */+ text: string;+ /** Milliseconds after the previous delta; for the first, after the stream opens. */+ gap: number;+}++/** mulberry32: a small seeded generator, uniform in [0, 1). */+export function seededRandom(seed: number): () => number {+ let state = seed >>> 0;+ return () => {+ state = (state + 0x6d2b79f5) >>> 0;+ let t = state;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** Han characters and CJK punctuation, which a model emits a character or two per token. */+const HAN = "\\u2e80-\\u9fff\\uf900-\\ufaff\\uff00-\\uffef\\u3000-\\u303f";++/**+ * A token: one or two Han characters, or a run of anything else up to the next space, either+ * with its trailing whitespace; or a leading run of whitespace. Every character falls in one+ * alternative, so the tokens join back into the text exactly.+ */+const TOKEN = new RegExp(`[${HAN}]{1,2}\\s*|[^\\s${HAN}]+\\s*|\\s+`, "g");++export function streamTokens(text: string): string[] {+ return text.match(TOKEN) ?? [];+}++/** The first delta's wait: the model's time to first token, long enough to see the empty reply. */+export const FIRST_GAP_MS = 420;++/** One delta in twelve waits on a stall; the one after a stall is always a burst. */+const STALL_ODDS = 1 / 12;+/** Besides those, one delta in seven is a burst. */+const BURST_ODDS = 1 / 7;++/** The deltas `text` streams as under `seed`: same seed, same script. */+export function streamScript(text: string, seed = 1): StreamChunk[] {+ const random = seededRandom(seed);+ const between = (min: number, max: number) => min + Math.floor(random() * (max - min + 1));+ const tokens = streamTokens(text);+ const chunks: StreamChunk[] = [];+ let next = 0;+ while (next < tokens.length) {+ const first = chunks.length === 0;+ const stall = !first && random() < STALL_ODDS;+ const burst = stall || random() < BURST_ODDS;+ const size = burst ? between(4, 9) : between(1, 3);+ const gap = first ? FIRST_GAP_MS : stall ? between(320, 720) : between(24, 110);+ chunks.push({ text: tokens.slice(next, next + size).join(""), gap });+ next += size;+ }+ return chunks;+}++/** How long a script takes from the stream's opening to its last delta. */+export function scriptDuration(chunks: readonly StreamChunk[]): number {+ return chunks.reduce((sum, chunk) => sum + chunk.gap, 0);+}diff --git a/packages/ui-gallery/src/app/mock/transcripts.ts b/packages/ui-gallery/src/app/mock/transcripts.tsindex f320994a..e53996f6 100644--- a/packages/ui-gallery/src/app/mock/transcripts.ts+++ b/packages/ui-gallery/src/app/mock/transcripts.ts@@ -6,6 +6,7 @@** - a tool call with no `tool_call_output` yet is a running tool (the card's timer ticks);* - an open `partial_thinking` fragment, carried as the live tail, is running thinking;+ * - an open `partial_text` fragment, carried the same way, is a reply streaming in;* - a tool call the stream has escalated with `approval_request` is waiting on a human.*/import { IDS } from "./ids";@@ -50,8 +51,11 @@ export const meta = (export const userText = (ms: number, text: string): OmniMessage =>model(ms, { type: "text", role: "user", text });-export const assistantText = (ms: number, text: string): OmniMessage =>- model(ms, { type: "text", role: "assistant", text, stop_reason: "completed" });+export const assistantText = (+ ms: number,+ text: string,+ stopReason: "completed" | "aborted" = "completed",+): OmniMessage => model(ms, { type: "text", role: "assistant", text, stop_reason: stopReason });export const thinking = (ms: number, text: string): OmniMessage =>model(ms, { type: "thinking", role: "assistant", thinking: text, stop_reason: "completed" });@@ -157,6 +161,8 @@ interface Copy {runningTool: { prompt: string; thinking: string; readOutput: string; title: string };thinking: { prompt: string; sentences: string[]; title: string };approval: { prompt: string; thinking: string; title: string; allowed: string; denied: string };+ /** The streaming Session's turn; the library's streaming board plays its answer too. */+ streaming: { prompt: string; thinking: string; title: string; answer: string };reply: { thinking: string; text: string[]; title: string };older: Record<string, { prompt: string; answer: string }>;}@@ -218,6 +224,24 @@ Nothing else in the corpus changed, so the index rebuild took 12.4 ms [1].denied:"Not published. The package is built and ready in `dist/`; run the publish yourself when you want it out.",},+ streaming: {+ title: "Explain the citation guard",+ prompt: "Walk me through how the retriever decides what it may cite.",+ thinking:+ "I read src/rag.ts earlier in this session, so I can answer from it: the ranking, then the existence check that guards every citation.",+ answer: `The retriever answers in two passes: it ranks the corpus with BM25, then drops every hit whose source file no longer exists, so a citation always opens a real file.++- **Walk**: \`buildIndex\` reads every Markdown file under \`corpus/\`.+- **Rank**: \`rank\` keeps the six best matches for the question.+- **Guard**: a hit is cited only if \`fs.existsSync\` finds its file.++\`\`\`ts+const hits = rank("How do I configure hooks?", index);+const cited = hits.filter((hit) => fs.existsSync(hit.source));+\`\`\`++To change what comes first, tune \`k1\` and \`b\` in \`src/rag.ts\`; the guard stays as it is.`,+ },reply: {title: "A question about the corpus",thinking:@@ -328,6 +352,24 @@ rank("如何配置 hooks?", index)[0].source;"已发布 `@penguinharness/[email protected]`。注册表已列出新版本,压缩包 48.2 KB。",denied: "没有发布。包已经构建好放在 `dist/`,需要时自行运行发布命令即可。",},+ streaming: {+ title: "讲解引用校验",+ prompt: "讲讲检索模块是怎么决定哪些内容可以引用的。",+ thinking:+ "这个会话前面读过 src/rag.ts,可以直接据此回答:先是排序,再是守住每条引用的存在性校验。",+ answer: `检索分两步回答:先用 BM25 给语料库排序,再丢掉源文件已经不存在的命中,所以每条引用都能打开一个真实文件。++- **扫描**:\`buildIndex\` 读取 \`corpus/\` 下的每个 Markdown 文件。+- **排序**:\`rank\` 为问题保留最匹配的六条。+- **校验**:只有 \`fs.existsSync\` 找得到文件的命中才会被引用。++\`\`\`ts+const hits = rank("如何配置 hooks?", index);+const cited = hits.filter((hit) => fs.existsSync(hit.source));+\`\`\`++想调整排在前面的结果,就改 \`src/rag.ts\` 里的 \`k1\` 和 \`b\`;校验这一步保持不变。`,+ },reply: {title: "关于语料库的一个问题",thinking: "答案在语料库里。打开检索模块,引用原文里的规则,而不是转述。",@@ -405,6 +447,8 @@ export interface Transcript {history: OmniMessage[];/** An open thinking fragment the live tail carries (running thinking). */openThinking?: { startedAt: number; text: string };+ /** An open text fragment the live tail carries (a reply streaming in). */+ openText?: { startedAt: number; text: string };/** A tool call awaiting a human decision. */pendingApproval?: ToolCallMessage;running: boolean;@@ -497,6 +541,25 @@ export function thinkingTranscript(lang: Lang, now: number, ref: ModelRef): Tran};}+/**+ * A Task mid-run whose reply is streaming: the prompt and the settled thinking are history; the+ * answer itself is played by the store, in a loop, while the Session is watched.+ */+export function streamingTranscript(lang: Lang, now: number, ref: ModelRef): Transcript {+ const c = COPY[lang].streaming;+ const t0 = now - 20_000;+ const s = (sec: number) => t0 + sec * 1000;+ return {+ running: true,+ history: [+ meta(s(0), IDS.sessions.streaming, ref, IDS.workspace),+ userText(s(0), c.prompt),+ requestBegin(s(0.3)),+ thinking(s(5), c.thinking),+ ],+ };+}+/** A Task waiting on a human: the publish command awaits approval. */export function approvalTranscript(lang: Lang, now: number, ref: ModelRef): Transcript {const c = COPY[lang].approval;@@ -659,5 +722,8 @@ export function approvalOutcome(: { output: "Tool call denied by user.", text: c.denied };}+/** The Markdown answer the streaming Session streams, and the library's streaming board plays. */+export const streamingAnswer = (lang: Lang): string => COPY[lang].streaming.answer;+/** The sentences the thinking session keeps adding, one per beat, cycling. */export const thinkingBeats = (lang: Lang): readonly string[] => COPY[lang].thinking.sentences;diff --git a/packages/ui-gallery/src/app/surfaces.ts b/packages/ui-gallery/src/app/surfaces.tsindex 6c6833ee..d95f9dae 100644--- a/packages/ui-gallery/src/app/surfaces.ts+++ b/packages/ui-gallery/src/app/surfaces.ts@@ -22,6 +22,7 @@ export const SURFACE_IDS = ["chat","chat-running","chat-thinking",+ "chat-streaming","chat-approval","chat-new","agents",@@ -57,6 +58,7 @@ export const SURFACES: readonly Surface[] = [{ id: "chat", group: "conversation", route: "/chat/s-hooks-index" },{ id: "chat-running", group: "conversation", route: "/chat/s-link-check" },{ id: "chat-thinking", group: "conversation", route: "/chat/s-release-plan" },+ { id: "chat-streaming", group: "conversation", route: "/chat/s-citation-guard" },{ id: "chat-approval", group: "conversation", route: "/chat/s-publish" },{ id: "chat-new", group: "conversation", route: "/chat" },{ id: "agents", group: "workbench", route: "/agents" },diff --git a/packages/ui-gallery/src/library/boards.tsx b/packages/ui-gallery/src/library/boards.tsxindex ee52e5fe..cb422c56 100644--- a/packages/ui-gallery/src/library/boards.tsx+++ b/packages/ui-gallery/src/library/boards.tsx@@ -23,6 +23,7 @@ import { InputsBoard } from "./boards/inputs";import { LoadingBoard } from "./boards/loading";import { NoticesBoard } from "./boards/notices";import { PickersBoard } from "./boards/pickers";+import { StreamingBoard } from "./boards/streaming";import { TabsBoard } from "./boards/tabs";import { ToastsBoard } from "./boards/toasts";import { TooltipsBoard } from "./boards/tooltips";@@ -40,6 +41,7 @@ export const BOARDS: Readonly<Record<TopicId, ComponentType>> = {badges: BadgesBoard,empty: EmptyBoard,loading: LoadingBoard,+ streaming: StreamingBoard,charts: ChartsBoard,avatars: AvatarsBoard,files: FilesBoard,diff --git a/packages/ui-gallery/src/library/boards/streaming.tsx b/packages/ui-gallery/src/library/boards/streaming.tsxnew file mode 100644index 00000000..b02e3752--- /dev/null+++ b/packages/ui-gallery/src/library/boards/streaming.tsx@@ -0,0 +1,150 @@+/**+ * 流式输出: an assistant reply as it streams in, under the current theme's reveal. A scripted+ * Markdown answer (the streaming demo Session's, src/app/mock/transcripts.ts) arrives in bursty+ * chunks (src/app/mock/stream-script.ts) and goes to the app's own reply body, which paces the+ * reveal by the theme's `--ui-stream-reveal` and `--ui-stream-rate`: Primer shows each chunk at+ * once, Frost fades it in by word under a glowing veil, Console types it out behind a block+ * caret. It plays once on load and again on Replay, always on the same seed, so every theme+ * replays the same chunks at the same gaps and the reveals compare. The caption names the mode+ * read from this frame root.+ *+ * The box is the finished reply's height from the first chunk on (an invisible copy of it+ * shares the live reply's grid cell), so the frame does not grow line by line as text arrives.+ */+import { useEffect, useMemo, useState } from "react";+import { STREAM_REVEALS } from "@prismshadow/penguin-ui";+import type { StreamReveal } from "@prismshadow/penguin-ui";+import { usePrefersReducedMotion } from "../../../../web/src/components/ui/use-reduced-motion";+import { AssistantReplyBody } from "../../../../web/src/features/chat/assistant-reply-body";+import { streamScript } from "../../app/mock/stream-script";+import { streamingAnswer } from "../../app/mock/transcripts";+import { BoardGroup, ReplayButton } from "../../foundations/shared";+import { useGallery } from "../../state";++/** The board's one seed: the same chunks at the same gaps under every theme. */+export const BOARD_SEED = 5;++const isStreamReveal = (value: string): value is StreamReveal =>+ (STREAM_REVEALS as readonly string[]).includes(value);++interface StreamTokens {+ /** The `--ui-stream-reveal` keyword as computed, trimmed; empty when unset. */+ reveal: string;+ /** `--ui-stream-rate` in characters a second; 0 when unset or not a number. */+ rate: number;+}++function readStreamTokens(): StreamTokens {+ const computed = getComputedStyle(document.documentElement);+ const reveal = computed.getPropertyValue("--ui-stream-reveal").trim();+ const rate = Number.parseFloat(computed.getPropertyValue("--ui-stream-rate"));+ return { reveal, rate: Number.isFinite(rate) ? rate : 0 };+}++/** The current theme's stream tokens, read again when the root's theme attributes change. */+function useStreamTokens(): StreamTokens | null {+ const [tokens, setTokens] = useState<StreamTokens | null>(null);+ useEffect(() => {+ const update = () => setTokens(readStreamTokens());+ update();+ const observer = new MutationObserver(update);+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class", "data-theme", "data-motion", "style"],+ });+ return () => observer.disconnect();+ }, []);+ return tokens;+}++/**+ * Plays `text` as the script cuts it: the text received so far, and whether the stream is still+ * open. `run` restarts it from nothing.+ */+function useScriptedStream(text: string, run: number): { text: string; streaming: boolean } {+ const chunks = useMemo(() => streamScript(text, BOARD_SEED), [text]);+ // Where each chunk ends in the text: the chunks join back into it exactly.+ const ends = useMemo(() => {+ let end = 0;+ return chunks.map((chunk) => {+ end += chunk.text.length;+ return end;+ });+ }, [chunks]);+ const [received, setReceived] = useState(0);++ useEffect(() => {+ setReceived(0);+ let count = 0;+ let timer = 0;+ const step = () => {+ count += 1;+ setReceived(count);+ const next = chunks[count];+ if (next) timer = window.setTimeout(step, next.gap);+ };+ const first = chunks[0];+ if (first) timer = window.setTimeout(step, first.gap);+ return () => window.clearTimeout(timer);+ }, [chunks, run]);++ return {+ text: received === 0 ? "" : text.slice(0, ends[received - 1]),+ streaming: received < chunks.length,+ };+}++/** The current theme's mode, by name: the keyword, what it does, and its pace when it has one. */+function StreamCaption({ tokens }: { tokens: StreamTokens }) {+ const { S } = useGallery();+ const t = S.library.streaming;+ const { reveal, rate } = tokens;+ const known = isStreamReveal(reveal);+ // Either signal the theme honours: the operating system's preference or the root's switch+ // (a change to the switch reaches here through the token reader's observer).+ const reduced =+ usePrefersReducedMotion() || document.documentElement.dataset.motion === "reduced";+ return (+ <p className="lib-caption">+ <code className="gf-mono">--ui-stream-reveal: {reveal || S.section.unset}</code>+ {" · "}+ {known ? t.modes[reveal] : t.unset}+ {known && reveal !== "instant" && rate > 0 && ` · ${t.rate(rate)}`}+ {reduced && ` · ${t.reduced}`}+ </p>+ );+}++export function StreamingBoard() {+ const { S, state } = useGallery();+ const t = S.library.streaming;+ const answer = streamingAnswer(state.lang);+ const [run, setRun] = useState(0);+ const stream = useScriptedStream(answer, run);+ const tokens = useStreamTokens();++ return (+ <div className="gf-board">+ <BoardGroup+ title={t.reply}+ aside={stream.streaming ? t.receiving : t.received}+ action={<ReplayButton onClick={() => setRun((n) => n + 1)} />}+ >+ <div className="lib-box lib-stream">+ <div className="lib-stream-sizer" aria-hidden inert>+ <AssistantReplyBody text={answer} streaming={false} />+ </div>+ <div className="lib-stream-live">+ {/* A replay mounts a fresh reply, so no pacing state carries over. */}+ <AssistantReplyBody key={run} text={stream.text} streaming={stream.streaming} />+ </div>+ </div>+ {tokens === null ? (+ <p className="lib-caption">{S.intro.resolving}</p>+ ) : (+ <StreamCaption tokens={tokens} />+ )}+ </BoardGroup>+ </div>+ );+}diff --git a/packages/ui-gallery/src/library/library.css b/packages/ui-gallery/src/library/library.cssindex 9de63b77..af0e4dea 100644--- a/packages/ui-gallery/src/library/library.css+++ b/packages/ui-gallery/src/library/library.css@@ -154,6 +154,21 @@ html[data-framed] body {.lib-box[data-narrow] {max-width: 18rem;}+/* The streaming board's reply at a chat column's measure: the live reply laid over an invisible+ copy of the finished one in a single grid cell, so the box is the finished reply's height from+ the first chunk on and the frame never grows line by line. */+.lib-stream {+ display: grid;+ max-width: 46rem;+ padding: 0.25rem 1.25rem;+}+.lib-stream > * {+ grid-area: 1 / 1;+ min-width: 0;+}+.lib-stream-sizer {+ visibility: hidden;+}/* A line a row truncates, for the tooltip board. */.lib-truncated {display: block;diff --git a/packages/ui-gallery/src/library/topics.ts b/packages/ui-gallery/src/library/topics.tsindex 9e976c30..55020779 100644--- a/packages/ui-gallery/src/library/topics.ts+++ b/packages/ui-gallery/src/library/topics.ts@@ -23,6 +23,7 @@ export const TOPIC_IDS = ["badges","empty","loading",+ "streaming","charts","avatars","files",@@ -57,6 +58,7 @@ export const TOPICS: readonly Topic[] = [component("badges"),component("empty"),component("loading"),+ component("streaming"),component("charts"),component("avatars"),component("files"),diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.tsindex 5775394b..c8afa76d 100644--- a/packages/ui-gallery/src/strings-en.ts+++ b/packages/ui-gallery/src/strings-en.ts@@ -55,6 +55,12 @@ export const en: GalleryStrings = {"A Task mid-run: the model is thinking; the thinking row shows the running state and the text keeps growing.",how: "Sidebar › a session row with the running mark.",},+ "chat-streaming": {+ title: "Chat · streaming",+ description:+ "A Task mid-run: the answer is streaming in and reveals the way the current theme does it; once done it holds for a moment and streams again, on a loop.",+ how: "Sidebar › a session row with the running mark.",+ },"chat-approval": {title: "Chat · awaiting approval",description:@@ -328,6 +334,7 @@ export const en: GalleryStrings = {"a notice strip or toast, coloured by its tone: info, success, warning, danger or neutral","ui-chart": "a chart: its grid, axes, lines, areas, bars and points","ui-scrim": "the dimmed layer behind a dialog, drawer or sheet",+ "ui-stream": "a reply that is still streaming: each theme decides how new text appears",},hookSamples: {menu: ["Pin", "Rename", "Delete"],@@ -424,6 +431,11 @@ export const en: GalleryStrings = {description: "The placeholder for a list or detail with nothing in it, with an action.",},loading: { title: "Loading", description: "The spinner and the skeletons." },+ streaming: {+ title: "Streaming",+ description:+ "How an assistant reply reveals as it streams in: Primer shows it at once, Frost fades it in word by word with a soft glow, Console types it out.",+ },charts: {title: "Charts",description:@@ -630,6 +642,19 @@ export const en: GalleryStrings = {list: "List",card: "Card",},+ streaming: {+ reply: "Assistant reply",+ receiving: "Receiving…",+ received: "All received",+ modes: {+ instant: "shows text the moment it arrives, with no motion",+ fade: "fades in word by word, the last lines rising out of a softly glowing accent veil",+ typewriter: "types out character by character behind a solid block caret",+ },+ unset: "treated as instant",+ rate: (perSecond) => `about ${Math.round(perSecond)} characters a second`,+ reduced: "reduced motion is on, so the reply shows as it arrives",+ },charts: {parts: {primitives: "Primitives",diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.tsindex 12dfce7d..beb8ec21 100644--- a/packages/ui-gallery/src/strings.ts+++ b/packages/ui-gallery/src/strings.ts@@ -9,7 +9,7 @@* the component library's topics (src/library/topics.ts), in both dictionaries; a test checks* each covers every id.*/-import type { HookName, ThemeId, ToneName } from "@prismshadow/penguin-ui";+import type { HookName, StreamReveal, ThemeId, ToneName } from "@prismshadow/penguin-ui";import type { TextSize } from "@prismshadow/penguin-ui/boot";import type { SurfaceGroupId, SurfaceId } from "./app/surfaces";import type { ChartToken } from "./library/chart-tokens";@@ -73,6 +73,12 @@ export const zh = {description: "任务进行中:模型正在思考,思考行显示运行状态,文字仍在增长。",how: "侧栏 › 带运行标记的会话行。",},+ "chat-streaming": {+ title: "对话 · 流式输出",+ description:+ "任务进行中:回答正在流式到达,按当前主题的方式显现;答完停留片刻后重新开始,循环播放。",+ how: "侧栏 › 带运行标记的会话行。",+ },"chat-approval": {title: "对话 · 待审批",description: "任务等待人工:一条命令需要批准,允许或拒绝之后任务继续并结束。",@@ -333,6 +339,7 @@ export const zh = {"ui-notice": "提示条与弹出通知:按语气(信息、成功、警告、错误、中性)着色","ui-chart": "统计图:网格、坐标轴、折线、面积、柱与数据点","ui-scrim": "对话框、抽屉与面板背后的遮罩层",+ "ui-stream": "正在流式输出的回答:各主题决定新文字如何出现",} as Record<HookName, string>,hookSamples: {menu: ["置顶", "重命名", "删除"] as readonly string[],@@ -410,6 +417,11 @@ export const zh = {},empty: { title: "空状态", description: "列表或详情为空时的占位文字,可带操作。" },loading: { title: "加载", description: "转圈与骨架屏。" },+ streaming: {+ title: "流式输出",+ description:+ "助手回答随流到达时怎样显现:通用即时显示,白领按词淡入、带一层微光,极客逐字打出。",+ },charts: {title: "图表",description:@@ -597,6 +609,19 @@ export const zh = {list: "列表",card: "卡片",},+ streaming: {+ reply: "助手回答",+ receiving: "正在接收…",+ received: "已全部到达",+ modes: {+ instant: "即时:文字一到就显示,不加动效",+ fade: "淡入:按词显现,末尾几行从带强调色微光的渐变里浮现",+ typewriter: "打字机:逐字打出,末尾跟着一个实心块状光标",+ } as Record<StreamReveal, string>,+ unset: "按即时处理",+ rate: (perSecond: number) => `每秒约 ${Math.round(perSecond)} 字`,+ reduced: "已开启减少动态效果,回答到达即显示",+ },charts: {parts: {primitives: "绘图原语",diff --git a/packages/ui-gallery/test/demo-store.test.ts b/packages/ui-gallery/test/demo-store.test.tsindex 59800510..5619d726 100644--- a/packages/ui-gallery/test/demo-store.test.ts+++ b/packages/ui-gallery/test/demo-store.test.ts@@ -9,8 +9,9 @@ import { catalogEntryFor } from "../../core/dist/state/model-catalog.js";import { catalogDelta } from "../../web/src/features/models/catalog-sync";import { buildFixtures } from "../src/app/mock/fixtures";import { ALL_SESSION_IDS, IDS } from "../src/app/mock/ids";-import { resetStore } from "../src/app/mock/store";-import { TOOL_CALL_IDS } from "../src/app/mock/transcripts";+import { REPLY_CLOSE_MS, REPLY_HOLD_MS, REPLY_LEAD_MS, resetStore } from "../src/app/mock/store";+import { scriptDuration, streamScript } from "../src/app/mock/stream-script";+import { streamingAnswer, TOOL_CALL_IDS } from "../src/app/mock/transcripts";import { payloadOf } from "../src/app/mock/types";import type { OmniMessage, StreamHandlers } from "../src/app/mock/types";@@ -34,6 +35,13 @@ function shape(value: unknown): unknown {/** A message's payload type, the session_meta record reading as its own kind. */const typeOf = (m: OmniMessage): string => payloadOf(m)?.type ?? "session_meta";+/** The text deltas among `messages`, in order. */+const textDeltas = (messages: OmniMessage[]): string[] =>+ messages.flatMap((m) => {+ const p = payloadOf(m);+ return p?.type === "partial_text" && p.event_type === "delta" ? [p.text] : [];+ });+/** A subscriber that keeps what it is sent. */function collector(): StreamHandlers & { messages: OmniMessage[]; events: ServerEvent[] } {const messages: OmniMessage[] = [];@@ -68,7 +76,14 @@ describe("the fixtures", () => {.filter((s) => s.status === "running").map((s) => s.sessionId).sort(),- ).toEqual([IDS.sessions.approval, IDS.sessions.runningTool, IDS.sessions.thinking].sort());+ ).toEqual(+ [+ IDS.sessions.approval,+ IDS.sessions.runningTool,+ IDS.sessions.thinking,+ IDS.sessions.streaming,+ ].sort(),+ );});it("carry the whole built-in catalog, settled: the app's sync check finds nothing to add or update", () => {@@ -131,6 +146,53 @@ describe("the running states", () => {expect(grown.cursor).not.toBe(tail.cursor);});+ it("a reply streaming on a loop: bursty deltas, the complete answer, then a rewind, a resync and the next round", () => {+ vi.useFakeTimers();+ const store = resetStore({ lang: "zh", signedIn: true, now: NOW });+ const id = IDS.sessions.streaming;+ const base = store.transcript(id)!.history.length;+ const answer = streamingAnswer("zh");+ const sub = collector();+ store.channel(id)!.subscribe(sub);+ store.onSubscribe(id, sub);+ // A second subscription (a remount) joins the running loop rather than starting another.+ store.onSubscribe(id, sub);+ expect(sub.events[0]).toEqual({ type: "task_state", state: "running" });++ // Mid-round, the live tail carries the open fragment with exactly what has streamed.+ vi.advanceTimersByTime(REPLY_LEAD_MS + 1500);+ const streamed = textDeltas(sub.messages).join("");+ expect(streamed.length).toBeGreaterThan(0);+ expect(answer.startsWith(streamed)).toBe(true);+ expect(store.liveTail(id)!.fragments.at(-1)!.payload).toEqual({+ type: "partial_text",+ role: "assistant",+ event_type: "start",+ text: streamed,+ });++ // The round closes with the complete answer in the history, cut as the first seed's script.+ const round = REPLY_LEAD_MS + scriptDuration(streamScript(answer, 1)) + REPLY_CLOSE_MS;+ vi.advanceTimersByTime(round - (REPLY_LEAD_MS + 1500));+ expect(textDeltas(sub.messages)).toEqual(streamScript(answer, 1).map((c) => c.text));+ expect(store.transcript(id)!.history.length).toBe(base + 1);+ expect(store.transcript(id)!.history.at(-1)!.payload).toMatchObject({ text: answer });+ expect(store.liveTail(id)!.fragments).toEqual([]);++ // After the hold it is rewound out of the history, the page is told to refetch, and the next+ // round opens a fresh fragment.+ vi.advanceTimersByTime(REPLY_HOLD_MS);+ expect(store.transcript(id)!.history.length).toBe(base);+ expect(sub.events.at(-1)).toEqual({ type: "resync_required" });+ vi.advanceTimersByTime(REPLY_LEAD_MS);+ const starts = sub.messages.filter((m) => {+ const p = payloadOf(m);+ return p?.type === "partial_text" && p.event_type === "start";+ });+ expect(starts).toHaveLength(2);+ expect(store.session(id)?.status).toBe("running");+ });+it("an approval pending: the subscription is told, and a decision runs the command and settles", () => {vi.useFakeTimers();const store = resetStore({ lang: "en", signedIn: true, now: NOW });diff --git a/packages/ui-gallery/test/library.test.ts b/packages/ui-gallery/test/library.test.tsindex a479572d..62487296 100644--- a/packages/ui-gallery/test/library.test.ts+++ b/packages/ui-gallery/test/library.test.ts@@ -6,7 +6,7 @@import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";-import { TOKEN_NAMES } from "@prismshadow/penguin-ui";+import { STREAM_REVEALS, TOKEN_NAMES } from "@prismshadow/penguin-ui";import { HOME_SURFACE } from "../src/app/surfaces";import { SEEDED_KEYS } from "../src/app/frame";import {@@ -60,6 +60,7 @@ describe("the library's topics", () => {"badges","empty","loading",+ "streaming","charts","avatars","files",@@ -236,6 +237,37 @@ describe("the charts board", () => {});});+describe("the streaming board", () => {+ it("plays the streaming Session's answer through the app's reply body, on one seed, with a replay", () => {+ const board = read("../src/library/boards/streaming.tsx");+ expect(board).toMatch(+ /import \{ AssistantReplyBody \} from "\.\.\/\.\.\/\.\.\/\.\.\/web\/src\/features\/chat\/assistant-reply-body";/,+ );+ expect(board).toMatch(/streamScript\(text, BOARD_SEED\)/);+ expect(board).toMatch(/const answer = streamingAnswer\(state\.lang\);/);+ expect(board).toMatch(+ /<AssistantReplyBody key=\{run\} text=\{stream\.text\} streaming=\{stream\.streaming\} \/>/,+ );+ expect(board).toMatch(/<ReplayButton onClick=\{\(\) => setRun\(\(n\) => n \+ 1\)\} \/>/);+ });++ it("names the current theme's mode, read from the frame root's computed style", () => {+ const board = read("../src/library/boards/streaming.tsx");+ expect(board).toMatch(/getComputedStyle\(document\.documentElement\)/);+ expect(board).toMatch(/getPropertyValue\("--ui-stream-reveal"\)/);+ expect(board).toMatch(/getPropertyValue\("--ui-stream-rate"\)/);+ expect(board).toMatch(/new MutationObserver\(update\)/);+ // Every keyword the package lists is named in both dictionaries.+ for (const S of [zh, en]) {+ const t = S.library.streaming;+ expect(Object.keys(t.modes).sort()).toEqual([...STREAM_REVEALS].sort());+ for (const text of [t.reply, t.receiving, t.received, t.unset, t.reduced, t.rate(90)])+ expect(text.trim()).not.toBe("");+ for (const text of Object.values(t.modes)) expect(text.trim()).not.toBe("");+ }+ });+});+describe("the library frame's sizing", () => {it("measures what is painted, overlays included, and swallows the resizes it asks for", () => {const page = read("../src/library/page.tsx");diff --git a/packages/ui-gallery/test/stream-script.test.ts b/packages/ui-gallery/test/stream-script.test.tsnew file mode 100644index 00000000..3cbd914c--- /dev/null+++ b/packages/ui-gallery/test/stream-script.test.ts@@ -0,0 +1,42 @@+/**+ * The streamed-reply script: a seed always cuts a text into the same deltas, the deltas join+ * back into the text exactly, and the rhythm is bursty the way a real stream is — uneven sizes,+ * uneven gaps, stalls among them.+ */+import { describe, expect, it } from "vitest";+import { FIRST_GAP_MS, streamScript, streamTokens } from "../src/app/mock/stream-script";+import type { StreamChunk } from "../src/app/mock/stream-script";+import { streamingAnswer } from "../src/app/mock/transcripts";++const joined = (chunks: readonly StreamChunk[]) => chunks.map((chunk) => chunk.text).join("");++describe("the stream script", () => {+ it("is seeded: the same seed cuts the same script, another seed another", () => {+ for (const lang of ["en", "zh"] as const) {+ const answer = streamingAnswer(lang);+ expect(streamScript(answer, 5)).toEqual(streamScript(answer, 5));+ expect(streamScript(answer, 5)).not.toEqual(streamScript(answer, 6));+ }+ });++ it("joins back into the text exactly, in both languages", () => {+ for (const lang of ["en", "zh"] as const) {+ const answer = streamingAnswer(lang);+ expect(streamTokens(answer).join("")).toBe(answer);+ for (const seed of [1, 2, 3, 5]) expect(joined(streamScript(answer, seed))).toBe(answer);+ }+ // Han text streams a character or two per token; Latin text a word with its space.+ expect(streamTokens("检索分两步 BM25 ok")).toEqual(["检索", "分两", "步 ", "BM25 ", "ok"]);+ });++ it("arrives in bursts: uneven sizes and gaps, with stalls, after the first token's wait", () => {+ const script = streamScript(streamingAnswer("en"), 1);+ expect(script[0]!.gap).toBe(FIRST_GAP_MS);+ const rest = script.slice(1);+ const tokens = script.map((chunk) => streamTokens(chunk.text).length);+ expect(Math.min(...tokens)).toBeLessThanOrEqual(2);+ expect(Math.max(...tokens)).toBeGreaterThanOrEqual(4);+ expect(rest.some((chunk) => chunk.gap < 120)).toBe(true);+ expect(rest.some((chunk) => chunk.gap >= 320)).toBe(true);+ });+});diff --git a/packages/ui-gallery/test/surfaces.test.ts b/packages/ui-gallery/test/surfaces.test.tsindex 78a11e7b..66257626 100644--- a/packages/ui-gallery/test/surfaces.test.ts+++ b/packages/ui-gallery/test/surfaces.test.ts@@ -29,6 +29,7 @@ describe("the surfaces", () => {it("cover the surfaces the owner named, and the home page frames one of them", () => {for (const id of ["chat",+ "chat-streaming","agents","plugins","models",@@ -96,6 +97,7 @@ describe("the surfaces", () => {expect(surfaceById("chat")?.route).toBe(`/chat/${IDS.sessions.done}`);expect(surfaceById("chat-running")?.route).toBe(`/chat/${IDS.sessions.runningTool}`);expect(surfaceById("chat-thinking")?.route).toBe(`/chat/${IDS.sessions.thinking}`);+ expect(surfaceById("chat-streaming")?.route).toBe(`/chat/${IDS.sessions.streaming}`);expect(surfaceById("chat-approval")?.route).toBe(`/chat/${IDS.sessions.approval}`);expect(surfaceById("settings")?.route).toBe(`/chat/${IDS.sessions.done}`);expect(surfaceById("agent-settings")?.route).toBe(`/agents/${IDS.agents.docs}`);diff --git a/packages/ui/src/hooks.ts b/packages/ui/src/hooks.tsindex 8741ca25..4d6ff19e 100644--- a/packages/ui/src/hooks.ts+++ b/packages/ui/src/hooks.ts@@ -31,6 +31,8 @@* | `ui-notice` | a notice: a toast, an inline notice strip | `data-tone="info" \| "success" \| "warning" \| "danger" \| "neutral"`; children may carry `data-slot="icon" \| "title" \| "body" \| "actions"` |* | `ui-chart` | a chart's root (its `<svg>`) | parts carry `data-part="grid" \| "axis" \| "series" \| "area" \| "bar" \| "point" \| "label"`; a series may carry `data-series="<n>"` |* | `ui-scrim` | the dimmed layer behind a dialog, drawer or sheet | — |+ * | `ui-stream` | the body of an assistant reply, which may still be | `data-state="streaming" \| "done"`; while streaming, the markdown blocks are followed by the stream's edge, a direct child `data-slot="caret"`, and then by anything the host appends |+ * | | streaming | |** `ui-shell` is the one place a theme may paint a field of colour: Frost paints the navigation* column a soft grey beside a near-white main column, flat (its earlier warm field and floating@@ -104,6 +106,21 @@* leave the dim as it is; Frost blurs the page behind it, the reference's frosted backdrop — a* backdrop filter never reaches the element's own descendants, so a panel inside the scrim stays* sharp. It moves only with the host's fade, so reduced motion needs nothing from it.+ *+ * `ui-stream` (2026-09-30) is how a theme shows a reply arriving. The host is the reply's body:+ * it stays `data-state="streaming"` until its paced reveal (`--ui-stream-reveal` /+ * `--ui-stream-rate`, tokens.ts) has caught up with the stream, and until then renders the+ * stream's edge — the caret slot — as a direct child right after the markdown blocks; whatever+ * else it holds (a stop reason, a files card) comes after the caret, and the Web App's host holds+ * those back until `done`. Primer changes nothing: the+ * host's own pulsing caret glyph stays. Frost hides the caret and lets the trailing lines surface+ * through a soft veil — a gradient from nothing to the page's colour over the last three lines,+ * with a faint glow in the accent's wash behind them — drawn only while the caret is the host's+ * last child, so the veil covers the text and never what the host appends after it; on `done`+ * the veil eases away over the reveal duration instead of snapping off. Console draws the caret+ * as a solid block cursor in the body ink, a mono cell wide, blinking in steps, and runs a last+ * paragraph in so the cursor follows its last character; nothing else moves. Under reduced+ * motion the caret holds still and Frost draws no veil.*/export const HOOKS = ["ui-glass",@@ -120,6 +137,7 @@ export const HOOKS = ["ui-notice","ui-chart","ui-scrim",+ "ui-stream",] as const;export type HookName = (typeof HOOKS)[number];diff --git a/packages/ui/src/testing/deslop.ts b/packages/ui/src/testing/deslop.tsindex c17651a0..d523e101 100644--- a/packages/ui/src/testing/deslop.ts+++ b/packages/ui/src/testing/deslop.ts@@ -1029,8 +1029,13 @@ const pageHeaderCheck: Check = (analysis) =>const fullSelector = (rule: CssStyleRule) => [...rule.parents, rule.selector].join(" ");-/** Transition shorthand items; a missing property is `all`, as in CSS. */-function transitionItems(value: string): { property: string; duration: string | null }[] {+/**+ * Transition shorthand items; a missing property is `all`, as in CSS. `discrete` marks an item+ * that carries `allow-discrete`: a property that cannot interpolate, flipped at one instant.+ */+function transitionItems(+ value: string,+): { property: string; duration: string | null; discrete: boolean }[] {const items: string[] = [];let depth = 0;let current = "";@@ -1049,7 +1054,9 @@ function transitionItems(value: string): { property: string; duration: string |.map((item) => {let property: string | null = null;let duration: string | null = null;+ let discrete = false;for (const part of item.match(/[\w-]+\((?:[^()]|\([^()]*\))*\)|\S+/g) ?? []) {+ if (part === "allow-discrete") discrete = true;if (DURATION_TOKEN.test(part) || milliseconds(part) !== null) duration ??= part;else if (property === null &&@@ -1061,19 +1068,32 @@ function transitionItems(value: string): { property: string; duration: string |property = part;}}- return { property: property ?? "all", duration };+ return { property: property ?? "all", duration, discrete };});}const declarations = (analysis: FileAnalysis) =>analysis.cssRules.flatMap((rule) => rule.declarations.map((decl) => ({ rule, decl })));+/**+ * The one discrete hold rule 1 lets through: a `.ui-stream` recipe's veil keeps its gradient+ * while its opacity fades out on `done`, by naming `background-image` in a shorthand item with+ * `allow-discrete` (user decision, 2026-09-30). A discrete transition interpolates nothing — the+ * image is swapped at one instant, and with a `step-end` timing that instant is the end of the+ * fade — so the finished reply settles instead of snapping, and nothing moves that the rule+ * guards. Anywhere else, or without `allow-discrete`, `background-image` is off the set as ever.+ */+const DISCRETE_HOLD = { property: "background-image", selector: /\.ui-stream\b/ } as const;+/** Rule 1: `transition` / `transition-property` naming `all` (or nothing) or a property off the set. */const cssTransitionCheck: Check = (analysis, policy) =>- declarations(analysis).flatMap(({ decl }) => {+ declarations(analysis).flatMap(({ rule, decl }) => {+ const hold = DISCRETE_HOLD.selector.test(fullSelector(rule));const properties =decl.name === "transition"- ? transitionItems(decl.value).map((item) => item.property)+ ? transitionItems(decl.value)+ .filter((item) => !(hold && item.discrete && item.property === DISCRETE_HOLD.property))+ .map((item) => item.property): decl.name === "transition-property"? decl.value.split(",")@@ -1163,11 +1183,16 @@ const cssHookMonoCheck: Check = (analysis) =>* is the signal that a step is in progress (user decision, 2026-09-29) — never the resting* states, so a finished transcript carries no wash. A third, `.ui-chart`, may paint one as a* MASK: a line's area fading towards the baseline — a gradient that carries the data's shape,- * not atmosphere (user decision, 2026-09-29). A gradient on any other hook, as a background or- * as a mask, is still the tell. A gradient in app CSS that is not a hook (the context bar's- * hatch, which carries meaning) is review.+ * not atmosphere (user decision, 2026-09-29). A fourth, the STREAMING state of `.ui-stream`,+ * paints the veil a reply surfaces through while it arrives — the gradient is how its newest+ * lines read as fading in (user decision, 2026-09-30) — and, like the activity row's, never on+ * the finished reply: the `done` state's rule may hold the image only through its fade-out, by+ * the discrete transition rule 1 allows, and never declares one. A gradient on any other hook,+ * as a background or as a mask, is still the tell. A gradient in app CSS that is not a hook (the+ * context bar's hatch, which carries meaning) is review.*/-const GRADIENT_RECIPES = /\.ui-shell\b|\.ui-activity\[data-state="running"\]|\.ui-chart\b/;+const GRADIENT_RECIPES =+ /\.ui-shell\b|\.ui-activity\[data-state="running"\]|\.ui-chart\b|\.ui-stream\[data-state="streaming"\]/;const cssDecorationCheck: Check = (analysis) =>declarations(analysis).flatMap(({ rule, decl }) => {diff --git a/packages/ui/src/theme.css b/packages/ui/src/theme.cssindex d64bb20a..243ecf1d 100644--- a/packages/ui/src/theme.css+++ b/packages/ui/src/theme.css@@ -366,6 +366,17 @@:root[data-motion="reduced"] :is(.ui-activity, .ui-activity *)::after {animation: none;}+/* The `ui-stream` recipes animate the stream's caret (Console's stepped blink; Primer's is the+ host's own pulse) and ease a layer drawn on the host itself (Frost's veil leaving on `done`),+ so both are named: the caret holds still and a layer goes at once. The reveal's pace is the+ app's, which shows the whole text under either signal; Frost also draws no veil then. */+:root[data-motion="reduced"] .ui-stream [data-slot="caret"],+:root[data-motion="reduced"] .ui-stream::before,+:root[data-motion="reduced"] .ui-stream::after,+:root[data-motion="reduced"] .ui-stream li::after {+ animation: none;+ transition: none;+}@media (prefers-reduced-motion: reduce) {:is([data-presence], [data-backdrop], [data-reveal], .ui-live) {animation: none;@@ -378,6 +389,13 @@:is(.ui-activity, .ui-activity *)::after {animation: none;}+ .ui-stream [data-slot="caret"],+ .ui-stream::before,+ .ui-stream::after,+ .ui-stream li::after {+ animation: none;+ transition: none;+ }}/* The `ui-tree` depth ladder, shared by the themes' recipes: a row or a branch carryingdiff --git a/packages/ui/src/themes/geek.css b/packages/ui/src/themes/geek.cssindex 30934a9f..b0e1a26f 100644--- a/packages/ui/src/themes/geek.css+++ b/packages/ui/src/themes/geek.css@@ -335,8 +335,9 @@/* Motion: colour changes stay quick and smooth (E2B's 100ms held to the 120ms floor everytheme's state changes share); everything that appears, leaves or resizes jumps. A layerenters in three frames over 120ms and leaves in two over 60ms, with no slide, no scale and- no blur; a streamed chunk is simply there (a zero reveal); the sidebar's width jumps- through four steps; the live signals tick. */+ no blur; an appended chunk or row is simply there (a zero reveal — a streaming reply is+ paced by the typewriter below instead); the sidebar's width jumps through four steps;+ the live signals tick. */--ui-dur-fast: 120ms;--ui-dur-base: 150ms;--ui-dur-slow: 260ms;@@ -358,6 +359,12 @@--ui-dur-layout: 160ms;--ui-ease-layout: steps(4, end);+ /* Streaming: a reply is typed out a character at a time, 90 a second — about one and a+ half characters a frame, so the line visibly runs on behind the block cursor the+ `ui-stream` recipe draws, the way a terminal prints. */+ --ui-stream-reveal: typewriter;+ --ui-stream-rate: 90;+/* Icons */--ui-icon-stroke: 1.4;--ui-icon-cap: butt;@@ -485,8 +492,8 @@* `animate-spin` and `.ui-frame` redraw a card's box.** Console gives a recipe to: eyebrow (its ink; the rung is theme.css's), display, live, frame,- * underline-nav, shell, icon-decor, tree, field, activity, notice, chart. `.ui-glass` and- * `.ui-scrim` are no-ops here: the overlay is opaque through the glass tokens, and the page+ * underline-nav, shell, icon-decor, tree, field, activity, notice, chart, stream. `.ui-glass`+ * and `.ui-scrim` are no-ops here: the overlay is opaque through the glass tokens, and the page* behind a dialog is dimmed, not blurred.*/@@ -759,6 +766,49 @@}}+ /* A reply still arriving is typed out behind a block cursor, the way a terminal prints (the+ reveal paces it a character at a time): the stream's caret is a solid cell in the body+ ink, one character of the chrome's mono face wide, with the host's own glyph painted out.+ While the text so far ends in a paragraph, that paragraph runs in — it lays out inline+ with the caret after it — so the cursor sits right after its last character; after a list+ the last item draws the cell itself (below); after a table or a code block it waits at the+ start of the next line, like a prompt. The cursor+ blinks in the theme's stepped live signal, and nothing else moves: no veil, no fade. Under+ reduced motion it holds still (theme.css). */+ :root[data-theme="geek"] .ui-stream[data-state="streaming"] > p:has(+ [data-slot="caret"]) {+ display: inline;+ }+ /* After a list the cursor belongs at the end of its last item, not on a line of its own: the+ item draws the block cell itself, and the host's caret slot steps aside. */+ :root[data-theme="geek"]+ .ui-stream[data-state="streaming"]+ > :is(ul, ol):has(+ [data-slot="caret"])+ > li:last-child::after {+ content: "";+ display: inline-block;+ inline-size: 1ch;+ block-size: 1.2em;+ margin-inline-start: 1px;+ vertical-align: text-bottom;+ background-color: var(--ui-fg);+ animation: ui-geek-signal 1s var(--ui-live-timing) infinite;+ }+ :root[data-theme="geek"] .ui-stream[data-state="streaming"] > :is(ul, ol) + [data-slot="caret"] {+ display: none;+ }+ :root[data-theme="geek"] .ui-stream > [data-slot="caret"] {+ display: inline-block;+ inline-size: 1ch;+ block-size: 1.2em;+ vertical-align: text-bottom;+ overflow: hidden;+ font-family: var(--ui-font-ui);+ color: transparent;+ -webkit-text-fill-color: transparent;+ background-color: var(--ui-fg);+ animation: ui-geek-signal 1s var(--ui-live-timing) infinite;+ }+/* A notice is a status line, the way a console prints one: a bracketed tone tag in the tone'sink — `[ OK ]`, `[WARN]`, `[FAIL]` — in the chrome face at the start, the message beside itin the reading face, nothing round it, painted in the page's own colour (quiet on the page,diff --git a/packages/ui/src/themes/github.css b/packages/ui/src/themes/github.cssindex fa77436f..81af8ecd 100644--- a/packages/ui/src/themes/github.css+++ b/packages/ui/src/themes/github.css@@ -347,6 +347,11 @@--ui-dur-layout: 200ms;--ui-ease-layout: var(--ui-ease-in-out);+ /* ---- Streaming: today's reply — the text shows as it lands, under the host's own pulsing+ caret; no pace, so no rate. ---- */+ --ui-stream-reveal: instant;+ --ui-stream-rate: 0;+/* ---- Icons ---- */--ui-icon-stroke: 1.7;--ui-icon-cap: round;@@ -481,7 +486,8 @@* card with a muted head, the accent bar under a tab, the sidebar's muted fill beside the* canvas, monochrome icons, a bordered tree box with the host's own indent, a form's label* above its control and a settings row's label beside it, a plain row for a step of the- * agent's work, a plain dim behind a dialog — so no recipe is written for those, and none may+ * agent's work, a plain dim behind a dialog, a streaming reply under the host's own pulsing+ * caret glyph — so no recipe is written for those, and none may* be until a Primer polish wave changes that look on purpose (the 2026-09-30 lift of the light* chart steps and the knob's hairline was such a change, made in tokens, not recipes). The* two rules every theme shares (the eyebrow on the h6 rung,diff --git a/packages/ui/src/themes/modern.css b/packages/ui/src/themes/modern.cssindex ddcdfc5b..c8e39907 100644--- a/packages/ui/src/themes/modern.css+++ b/packages/ui/src/themes/modern.css@@ -337,6 +337,12 @@--ui-dur-layout: 320ms;--ui-ease-layout: cubic-bezier(0.22, 1, 0.36, 1);+ /* Streaming: a reply surfaces word by word at about 220 characters a second — quick enough+ never to hold a fast model back for long, even enough to read as a calm flow — through+ the soft veil the `ui-stream` recipe draws over its trailing lines. */+ --ui-stream-reveal: fade;+ --ui-stream-rate: 220;+/* Icons */--ui-icon-stroke: 1.6;--ui-icon-cap: round;@@ -485,9 +491,9 @@* `animate-spin`, `.ui-glass` replace a panel's opaque fill and `.ui-shell` re-paint the* window's columns.*- * Frost gives all fourteen a recipe: glass, eyebrow (its ink; the rung is theme.css's),+ * Frost gives all fifteen a recipe: glass, eyebrow (its ink; the rung is theme.css's),* display, live, frame, underline-nav, shell, icon-decor, tree, field, activity, notice, chart,- * scrim.+ * scrim, stream.*//* Frosted transient layer: menus, popovers, tooltips and the floating composer — the small@@ -759,6 +765,58 @@}}+ /* A reply still arriving surfaces through a soft veil, so the newest words read as fading in+ (the reveal paces them word by word): over the trailing three lines a gradient runs from+ nothing to the page's own colour at a little over half strength, above a faint glow in the+ accent's wash that fades out towards every edge — no line, no box, no band where the veil+ stops. The text moving up through it is the only motion; each line brightens as it leaves.+ The veil is the host's `::after`, drawn only while the stream's caret is the host's last+ child: the caret marks where the text ends, so what the host appends after it (a stop+ reason, a files card) is never veiled; the caret itself is not shown. On `done` — or once+ something follows the caret — the veil eases away over the reveal duration: the fade runs+ on opacity, and a discrete `step-end` transition holds the gradient until the fade is over,+ so the last lines settle into full ink instead of snapping. A reply that mounts finished+ carries only an empty, transparent layer. Under reduced motion the veil is not drawn. */+ :root[data-theme="modern"] .ui-stream {+ position: relative;+ }+ :root[data-theme="modern"] .ui-stream > [data-slot="caret"] {+ display: none;+ }+ :root[data-theme="modern"] .ui-stream::after {+ content: "";+ position: absolute;+ inset: 0;+ pointer-events: none;+ background-size: 100% 3lh;+ background-position: bottom;+ background-repeat: no-repeat;+ opacity: 0;+ transition:+ opacity var(--ui-dur-reveal) var(--ui-ease-out),+ background-image var(--ui-dur-reveal) step-end allow-discrete;+ }+ :root[data-theme="modern"]+ .ui-stream[data-state="streaming"]:has(> [data-slot="caret"]:last-child)::after {+ opacity: 1;+ background-image:+ linear-gradient(+ to bottom,+ transparent,+ color-mix(in srgb, var(--ui-canvas) 55%, transparent)+ ),+ radial-gradient(closest-side, var(--ui-accent-muted), transparent);+ transition: opacity var(--ui-dur-reveal) var(--ui-ease-out);+ }+ :root[data-theme="modern"][data-motion="reduced"] .ui-stream::after {+ display: none;+ }+ @media (prefers-reduced-motion: reduce) {+ :root[data-theme="modern"] .ui-stream::after {+ display: none;+ }+ }+/* A notice is a soft card: the overlay surface under the overlay's shadow, no coloured borderand no tinted fill — the tone is one small dot of its ink at the start (a toast is a button;the dot is its `::before`, which a button draws too). The dot sits out of the flow,diff --git a/packages/ui/src/tokens.ts b/packages/ui/src/tokens.tsindex 801c0d02..368f99d8 100644--- a/packages/ui/src/tokens.ts+++ b/packages/ui/src/tokens.ts@@ -6,8 +6,9 @@* `themes/geek.css` gives **every** name below a value in **both** modes (light and dark): its* base rule declares all of them with the light values, and its dark rule declares only the names* whose value dark changes — a group that does not vary by mode (shape, families, type scale,- * density, motion, icons) lives once, in the base rule. The contract test parses the three files- * and diffs each mode (the base rule plus that mode's own) against {@link TOKEN_NAMES}. Components+ * density, motion, streaming, icons) lives once, in the base rule. The contract test parses the+ * three files and diffs each mode (the base rule plus that mode's own) against+ * {@link TOKEN_NAMES}. Components* read these names only — through the semantic Tailwind utilities `theme.css` bridges* (`bg-surface`, `text-fg-muted`, `border-line`, …) or through `var(--ui-*)` directly — and never* branch on which theme is active.@@ -43,6 +44,9 @@* rules in `theme.css` for `data-presence`, `data-backdrop`, `data-reveal` and* `data-layout-motion`; a theme picks a quick fade, a soft spring or a `steps()` jump by value* alone. `--ui-dur-fast` / `base` / `slow` stay the state-change durations a component may name.+ * A reply that is still streaming is paced by the two streaming tokens (`--ui-stream-reveal`,+ * `--ui-stream-rate`) and dressed by the `ui-stream` hook: Primer shows it as it lands, Frost+ * lets it surface word by word through a soft veil, Console types it out behind a block cursor.*//** Stable, lowercase theme ids. Display names (Primer / Frost / Console) are UI copy, not ids. */@@ -501,6 +505,17 @@ export const TOKEN_GROUPS = ["--ui-ease-layout",],},+ {+ id: "stream",+ title: "Streaming — how a reply is revealed",+ // What the app's stream-reveal hook reads, once per theme, to pace an assistant reply that+ // is still arriving: the reveal (`instant` shows the text as it lands, `fade` reveals it word+ // by word, `typewriter` character by character — the exact keywords) and its rate, a plain+ // number of characters per second (0 where the reveal is `instant` and no rate applies).+ // The look of the arriving text is the `ui-stream` hook's (hooks.ts); these two say only+ // how fast it arrives. Neither varies by mode.+ names: ["--ui-stream-reveal", "--ui-stream-rate"],+ },{id: "icons",title: "Icons",@@ -533,6 +548,15 @@ export const TOKEN_NAMES: readonly TokenName[] = TOKEN_GROUPS.flatMap((group): readonly TokenName[] => group.names,);+/**+ * The keywords `--ui-stream-reveal` takes, exactly: `instant` (a streaming reply shows as it+ * lands), `fade` (it is revealed word by word) and `typewriter` (character by character), the+ * last two at `--ui-stream-rate` characters per second. A value outside the list reads as+ * `instant`, so a reader never paces text a theme did not ask to pace.+ */+export const STREAM_REVEALS = ["instant", "fade", "typewriter"] as const;+export type StreamReveal = (typeof STREAM_REVEALS)[number];+/** `var(--ui-…)` for a contract name — for inline styles and SVG attributes that cannot take a class. */export function tokenVar(name: TokenName): `var(${TokenName})` {return `var(${name})`;diff --git a/packages/ui/test/deslop.test.ts b/packages/ui/test/deslop.test.tsindex 31ebea7b..7dee0efb 100644--- a/packages/ui/test/deslop.test.ts+++ b/packages/ui/test/deslop.test.ts@@ -270,6 +270,18 @@ describe("the rule checks, on known shapes", () => {expect(found("theme.css", ".a { transition-property: width, border-radius; }")).toEqual(["1:transition-property: border-radius",]);+ // The stream's veil may hold its gradient through its fade-out with a discrete transition;+ // the same hold on another hook, or an interpolating one on the stream, is refused.+ const hold =+ "opacity var(--ui-dur-reveal) var(--ui-ease-out), background-image var(--ui-dur-reveal) step-end allow-discrete";+ expect(found("t.css", `:root .ui-stream::after { transition: ${hold}; }`)).toEqual([]);+ expect(+ found(+ "t.css",+ `:root .ui-frame::after { transition: ${hold}; }\n` ++ ":root .ui-stream::after { transition: opacity 150ms, background-image 150ms; }",+ ),+ ).toEqual(["1:transition: background-image", "1:transition: background-image"]);});it("rule 2 — hover and press transforms", () => {@@ -521,6 +533,19 @@ describe("the rule checks, on known shapes", () => {':root .ui-activity[data-state="done"] { background: linear-gradient(red, blue); }',),).toEqual(['18::root .ui-activity[data-state="done"] { background: …gradient() }']);+ // A streaming reply's veil may paint one too (its newest lines fade in through it); the+ // finished reply, or the stream's rules outside the streaming state, may not.+ expect(+ found(+ "t.css",+ ':root .ui-stream[data-state="streaming"]:has(> [data-slot="caret"]:last-child)::after { background-image: linear-gradient(transparent, #000), radial-gradient(closest-side, red, transparent); }\n' ++ ":root .ui-stream::after { background-image: linear-gradient(red, blue); }\n" ++ ':root .ui-stream[data-state="done"]::after { mask-image: linear-gradient(red, blue); }',+ ),+ ).toEqual([+ "18::root .ui-stream::after { background-image: …gradient() }",+ '18::root .ui-stream[data-state="done"]::after { mask-image: …gradient() }',+ ]);// A chart may paint a gradient as a mask (an area's fade, a bar's hatch); a mask gradient on// any other hook is the tell like a background one.expect(diff --git a/packages/ui/test/hooks.test.ts b/packages/ui/test/hooks.test.tsindex 74ab4597..0be907a9 100644--- a/packages/ui/test/hooks.test.ts+++ b/packages/ui/test/hooks.test.ts@@ -12,9 +12,10 @@* rules) and `ui-field` (a labelled control row, which Console sets as a table row) — and the* eleventh, `ui-activity` (a step of the agent's work: Frost sweeps a highlight across its label,* Console renders a transcript; user decision, 2026-09-29), the twelfth and thirteenth,- * `ui-notice` and `ui-chart` (notices and charts that differ per theme; the same day), and the- * fourteenth, `ui-scrim` (the dimmed backdrop behind a dialog, which Frost blurs; 2026-09-30).- * This suite holds the source to it:+ * `ui-notice` and `ui-chart` (notices and charts that differ per theme; the same day), the+ * fourteenth, `ui-scrim` (the dimmed backdrop behind a dialog, which Frost blurs; 2026-09-30),+ * and the fifteenth, `ui-stream` (an assistant reply as it arrives: Frost's soft veil, Console's+ * block cursor; the same day). This suite holds the source to it:** - no `ui-*` class in markup, and no `.ui-*` selector in a stylesheet, outside the list — in the* package, the web app and the gallery;@@ -33,8 +34,9 @@* `data-role` is one of the four the recipes tint apart, `.ui-activity` names its kind* (`thinking` / `tool`), its state (`running` / `done` / `error`) and its slots (`label`,* `detail`, `progress`), `.ui-notice` its tone (the five) and its slots (`icon`, `title`,- * `body`, `actions`), and a chart's parts are the seven the recipes style, wherever a- * `data-part` is written.+ * `body`, `actions`), `.ui-stream` its state (`streaming` / `done`) and its one slot+ * (`caret`), and a chart's parts are the seven the recipes style, wherever a `data-part` is+ * written.*/import { existsSync } from "node:fs";import { join } from "node:path";@@ -60,6 +62,7 @@ const APPENDIX_A = ["ui-notice","ui-chart","ui-scrim",+ "ui-stream",];/**@@ -128,6 +131,9 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {// The dimmed backdrop (2026-09-30): a sibling behind a sheet or drawer, or the full-viewport// overlay a modal, the command palette, the harness overlay and the lightbox sit in."ui-scrim": ["Modal", "Sheet", "Drawer", "CommandPalette", "HarnessHistoryOverlay", "Lightbox"],+ // An assistant reply as it arrives (2026-09-30): the reply body the transcript renders and the+ // gallery frames on its own.+ "ui-stream": ["AssistantReplyBody"],};/** CSS keywords that start with `ui-` and are not classes. */@@ -143,6 +149,8 @@ const ACTIVITY_STATES = new Set(["running", "done", "error"]);const ACTIVITY_SLOTS = new Set(["label", "detail", "progress"]);const NOTICE_TONES = new Set(["info", "success", "warning", "danger", "neutral"]);const NOTICE_SLOTS = new Set(["icon", "title", "body", "actions"]);+const STREAM_STATES = new Set(["streaming", "done"]);+const STREAM_SLOTS = new Set(["caret"]);/** A chart's parts, wherever a chart's children are written (a mark component draws into the frame's svg). */const CHART_PARTS = new Set(["grid", "axis", "series", "area", "bar", "point", "label"]);/** The icon renderers: a `decor` prop on one of these is the decorative-icon hook applied. */@@ -198,7 +206,7 @@ function childSlots(element: JsxElementInfo): { slot: string; child: JsxElementIdescribe("style hooks", () => {const hooks = new Set<string>(HOOKS);- it("are the fourteen of Appendix A, each with its hosts", () => {+ it("are the fifteen of Appendix A, each with its hosts", () => {expect([...HOOKS].sort()).toEqual([...APPENDIX_A].sort());expect(Object.keys(HOSTS).sort()).toEqual([...APPENDIX_A].sort());});@@ -337,6 +345,22 @@ describe("style hooks", () => {}}}+ // A streaming reply names its state, as a literal the recipes select on or an+ // expression; its one direct-child slot is the stream's edge, the caret (Frost's veil+ // stops there, Console's cursor is drawn on it).+ if (names.has("ui-stream")) {+ const state = element.attributes.get("data-state");+ if (state !== null && (typeof state !== "string" || !STREAM_STATES.has(state))) {+ problems.push(+ `${at} .ui-stream needs data-state="streaming|done", has ${String(state)}`,+ );+ }+ for (const { slot } of childSlots(element)) {+ if (!STREAM_SLOTS.has(slot)) {+ problems.push(`${at} .ui-stream slot "${slot}" is not caret`);+ }+ }+ }// A chart's parts are written wherever a mark is drawn, inside the frame's svg or by a// component that renders into it: every literal `data-part` is one the recipes style.const part = element.attributes.get("data-part");@@ -469,4 +493,27 @@ describe("the hook checks, on known shapes", () => {const field = analysis.elements.find((e) => e.classes.some((t) => t.utility === "ui-field"))!;expect(childSlots(field).map((s) => s.slot)).toEqual(["label", "control"]);});++ it("read a stream's state and its caret as the recipes do", () => {+ // The state is usually an expression (the check accepts it and judges only a literal); the+ // caret is a direct child even when it is rendered conditionally.+ const analysis = analyzeFile(+ file(+ "d.tsx",+ [+ "export function AssistantReplyBody({ revealing }: { revealing: boolean }) {",+ " return (",+ ' <div className="ui-stream" data-state={revealing ? "streaming" : "done"}>',+ " <p>text</p>",+ ' {revealing && <span data-slot="caret" aria-hidden />}',+ " </div>",+ " );",+ "}",+ ].join("\n"),+ ),+ );+ const host = analysis.elements.find((e) => e.classes.some((t) => t.utility === "ui-stream"))!;+ expect(host.attributes.get("data-state")).toBeNull();+ expect(childSlots(host).map((s) => s.slot)).toEqual(["caret"]);+ });});diff --git a/packages/ui/test/token-contract.test.ts b/packages/ui/test/token-contract.test.tsindex 107df650..09daef31 100644--- a/packages/ui/test/token-contract.test.ts+++ b/packages/ui/test/token-contract.test.ts@@ -26,6 +26,7 @@ import {import {ACCENT_PRESETS,DEFAULT_THEME_ID,+ STREAM_REVEALS,THEME_ACCENT_PRESETS,THEME_IDS,THEME_MODES,@@ -332,8 +333,9 @@ describe("the theme-identities revision of the contract (2026-09-19)", () => {expect(TOKEN_GROUPS.find((group) => group.id === "shell")?.names.length).toBe(9);// 215, plus the integration round's four (the emphasis ink and the switch's three), plus// the chart round's nine (two more series, the reference line, six geometry names), plus- // the bar outline's three, plus the knob's hairline edge (2026-09-30).- expect(TOKEN_NAMES.length).toBe(232);+ // the bar outline's three, plus the knob's hairline edge, plus the streaming pair+ // (2026-09-30).+ expect(TOKEN_NAMES.length).toBe(234);});it("adds the structure group behind the tree and field hooks (round 2)", () => {@@ -641,6 +643,52 @@ describe("the chart style tokens (round 7)", () => {});});+describe("the streaming tokens (2026-09-30)", () => {+ // A reply that is still arriving is paced by the app from two tokens it reads once per theme:+ // the reveal, one of the exact keywords it knows, and the rate in characters per second, a+ // plain number it can parse (0 only where nothing is paced). Neither varies by mode.+ const stream = TOKEN_GROUPS.find((group) => group.id === "stream");++ it("names the reveal and its rate", () => {+ expect(stream?.names).toEqual(["--ui-stream-reveal", "--ui-stream-rate"]);+ expect([...STREAM_REVEALS]).toEqual(["instant", "fade", "typewriter"]);+ });++ it("gives every theme and mode a keyword the app knows and a rate it can parse", () => {+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ for (const mode of THEME_MODES) {+ const values = new Map([...theme.analysis.modes.light, ...theme.analysis.modes[mode]]);+ const at = `${theme.id} ${mode}`;+ const reveal = values.get("--ui-stream-reveal");+ const rate = values.get("--ui-stream-rate") ?? "";+ expect(STREAM_REVEALS as readonly string[], `${at} --ui-stream-reveal`).toContain(reveal);+ expect(rate, `${at} --ui-stream-rate is a plain number`).toMatch(/^\d+(?:\.\d+)?$/);+ if (reveal !== "instant") {+ expect(Number(rate), `${at} a paced reveal needs a rate`).toBeGreaterThan(0);+ }+ }+ // One value for both modes: the dark rule leaves the pair to the base rule.+ expect(theme.analysis.modes.dark.has("--ui-stream-reveal"), theme.id).toBe(false);+ expect(theme.analysis.modes.dark.has("--ui-stream-rate"), theme.id).toBe(false);+ }+ });++ it("reveals Primer as today (instant), Frost by fading and Console by typing", () => {+ const expected: Readonly<Record<ThemeId, string>> = {+ github: "instant",+ modern: "fade",+ geek: "typewriter",+ };+ for (const theme of THEMES) {+ if (theme.status !== "filled") continue;+ expect(theme.analysis.modes.light.get("--ui-stream-reveal"), theme.id).toBe(+ expected[theme.id],+ );+ }+ });+});+describe("the themes' own faces (round 6)", () => {// THEME_FONTS is what the Fonts page states as a theme's defaults; it must be what the theme// file's stacks name first — a bundled family by its declared name, or, for `System`, a stackdiff --git a/packages/web/src/features/chat/assistant-reply-body.tsx b/packages/web/src/features/chat/assistant-reply-body.tsxnew file mode 100644index 00000000..1d183486--- /dev/null+++ b/packages/web/src/features/chat/assistant-reply-body.tsx@@ -0,0 +1,47 @@+/**+ * An assistant reply's body in the transcript: the Markdown, the streaming caret, and whatever+ * the item adds once the reply is whole. MessageItem renders every reply through it, and the+ * gallery renders it on its own, so a theme's reveal is seen exactly as the transcript shows it.+ *+ * The body is the `ui-stream` host: `data-state` is `streaming` while the reply is still coming+ * in — the stream is open, or the paced reveal (use-stream-reveal.ts) has not caught up with it+ * — and `done` after, and the caret is its `caret` slot. Primer gives the hook nothing and+ * reveals instantly, so the body renders as it always has; Frost fades the new text in under a+ * soft veil at the body's foot, and Console types it out behind a block caret.+ *+ * Markdown renders the revealed prefix, so code blocks and lists grow as they are typed. It+ * stays in its streaming mode (no highlighting, no KaTeX; see md.tsx) until the reveal is done,+ * and `children` (the stop reason, a nested reply's files card) wait for the same moment, so+ * nothing lands under text that is still coming in.+ */+import type { ReactNode } from "react";+import { Md } from "./md";+import { StreamingCaret } from "./streaming-caret";+import { useStreamReveal } from "./use-stream-reveal";++export function AssistantReplyBody({+ text,+ streaming,+ children,+}: {+ /** The reply's text received so far. */+ text: string;+ /** The stream is still open. */+ streaming: boolean;+ /** Rendered after the reply once it is fully revealed. */+ children?: ReactNode;+}) {+ const revealed = useStreamReveal(text, streaming);+ const live = streaming || revealed.length < text.length;+ return (+ <div+ className="ui-stream md-body anim-msg my-3 font-sans text-base leading-relaxed text-gray-800 dark:text-gray-100"+ data-state={live ? "streaming" : "done"}+ >+ {/* Re-renders the revealed text directly while live; memoized, so a settled reply skips the re-parse, and code blocks highlight once on settle (see md.tsx). */}+ <Md text={revealed} streaming={live} />+ {live && <StreamingCaret />}+ {!live && children}+ </div>+ );+}diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsxindex 002f244b..2f8fbe8f 100644--- a/packages/web/src/features/chat/message-item.tsx+++ b/packages/web/src/features/chat/message-item.tsx@@ -11,7 +11,7 @@ import { formatMessageTime } from "../../lib/format";import { STAT_ICONS } from "../../lib/stat-icons";import { splitAttachments } from "../../lib/attachments";import type { ChatItem, ReconnectItem } from "../../lib/omni/stream-model";-import { Md } from "./md";+import { AssistantReplyBody } from "./assistant-reply-body";import { GlyphIcon } from "../../components/ui/glyph-icon";import { CopyButton } from "../../components/ui/copy-button";import { ZoomableImage } from "../../components/ui/image-zoom";@@ -362,11 +362,10 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo// footer, and rendering both would pop up two copy buttons in the same spot. The stats// line's copy grabs **all** of this turn's assistant text (see collectTaskAssistant),// which is more useful than copying segment by segment.+ // The body (Markdown, caret, the theme's reveal) is AssistantReplyBody; the stop reason+ // and a nested reply's files card follow the text once it is fully revealed.return (- <div className="md-body anim-msg my-3 font-sans text-base leading-relaxed text-gray-800 dark:text-gray-100">- {/* Re-renders the accumulated text directly while streaming (a key point of the contract implementation); memoized so settled messages skip the re-parse, and code blocks highlight once on settle (see md.tsx). */}- <Md text={item.text} streaming={item.streaming} />- {item.streaming && <span className="animate-pulse text-gray-400">▌</span>}+ <AssistantReplyBody text={item.text} streaming={item.streaming}>{item.stopReason && item.stopReason !== "completed" && (<span className="ml-1 font-mono text-xs text-gray-400">[{item.stopReason}]</span>)}@@ -379,7 +378,7 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCoonOpenFile={ctx.onOpenFile}/>)}- </div>+ </AssistantReplyBody>);case "thinking":return <ThinkingBlock item={item} />;diff --git a/packages/web/src/features/chat/stream-reveal.ts b/packages/web/src/features/chat/stream-reveal.tsnew file mode 100644index 00000000..0d9e7423--- /dev/null+++ b/packages/web/src/features/chat/stream-reveal.ts@@ -0,0 +1,216 @@+/**+ * The pacing of a streaming reply's reveal, as pure functions of the text and the clock, so it+ * is testable without a DOM or a frame loop (use-stream-reveal.ts drives it once per animation+ * frame).+ *+ * The state holds a cursor, in characters, that moves through the text received so far at the+ * theme's rate. What the reader sees is the text up to the cursor, cut where Markdown renders+ * cleanly:+ *+ * - `typewriter` cuts at the cursor, character by character;+ * - `fade` cuts at the last word boundary before it (every CJK character is a word of its own),+ * so whole words come in at the same characters-per-second pace;+ * - both hold back a line that so far carries only block syntax (`-`, `1.`, `#`, a fence's+ * backticks, a table's rule), and never split a run of `*`, `_`, `~` or backticks. A lone `-`+ * under a paragraph would render the paragraph as a heading for a frame, an empty `#` an empty+ * heading, two backticks an inline code span; each of those turns into something else one+ * character later, which reads as flicker. The held characters come in with the first+ * character that settles the line.+ *+ * The reveal never trails the stream by more than {@link REVEAL_MAX_LAG_MS}: every arrival+ * carries a deadline, and when the rate would miss one the cursor speeds up just enough to meet+ * it — smoothly, never by a jump. When the stream ends, the rest comes in at the same rate+ * under the same deadlines. At the live edge, while the stream is open and its last arrival is+ * younger than the deadline, a partial word or a syntax-only line waits for the next delta.+ */+import type { StreamRevealMode } from "../../lib/stream-style";++/** The most the reveal may trail the stream: text that arrived this long ago is on screen. */+export const REVEAL_MAX_LAG_MS = 1500;++/** One arrival not yet fully revealed: where it ends in the text and when it must be showing. */+export interface RevealDue {+ readonly end: number;+ readonly by: number;+}++export interface RevealState {+ /** The text received so far. */+ readonly text: string;+ /** The reveal cursor, in characters; fractional between frames. */+ readonly cursor: number;+ /** Arrivals the cursor has not passed yet, oldest first. */+ readonly due: readonly RevealDue[];+ /** When the latest arrival's deadline falls: until then the live edge may hold a partial word. */+ readonly settleBy: number;+ /** The clock at the last step, ms. */+ readonly at: number;+}++/** A reveal with nothing left to show: the whole text is on screen. */+export function settledReveal(text: string, now: number): RevealState {+ return { text, cursor: text.length, due: [], settleBy: now, at: now };+}++/**+ * A reply's reveal when it first renders. A settled reply, or one with nothing to pace with,+ * shows whole. A streaming one normally starts empty (the fragment opens before its first+ * delta); if it mounts with text already in it — a reload or a switch back into a running+ * Session — only the last {@link REVEAL_MAX_LAG_MS} of it at the rate is revealed again, so+ * the text the reader has already seen does not type itself out a second time.+ */+export function startReveal(+ text: string,+ now: number,+ pace: { streaming: boolean; rate: number },+): RevealState {+ if (!pace.streaming || pace.rate <= 0) return settledReveal(text, now);+ const cursor = Math.max(0, text.length - (pace.rate * REVEAL_MAX_LAG_MS) / 1000);+ return {+ text,+ cursor,+ due: cursor < text.length ? [{ end: text.length, by: now + REVEAL_MAX_LAG_MS }] : [],+ settleBy: now + REVEAL_MAX_LAG_MS,+ at: now,+ };+}++/** The length of the prefix two strings share. */+function sharedPrefix(a: string, b: string): number {+ const n = Math.min(a.length, b.length);+ let i = 0;+ while (i < n && a.charCodeAt(i) === b.charCodeAt(i)) i++;+ return i;+}++/**+ * New text arrived. An extension of the old text queues its new tail under a fresh deadline.+ * Text that replaced the old (the complete message settling a fragment with different+ * content) keeps what the two share: the cursor falls back to the shared prefix if it was past+ * it, and the rest reveals as new.+ */+export function receiveText(state: RevealState, text: string, now: number): RevealState {+ if (text === state.text) return state;+ const kept = text.startsWith(state.text) ? state.text.length : sharedPrefix(state.text, text);+ const cursor = Math.min(state.cursor, kept);+ const due = state.due+ .map((d) => (d.end > kept ? { end: kept, by: d.by } : d))+ .filter((d) => d.end > cursor);+ const grew = text.length > kept;+ if (grew) due.push({ end: text.length, by: now + REVEAL_MAX_LAG_MS });+ return {+ text,+ cursor,+ due,+ settleBy: grew ? now + REVEAL_MAX_LAG_MS : state.settleBy,+ // A reveal that had caught up was not stepping: its clock restarts now, or the time it sat+ // idle would count as reveal time and the new text would show at once.+ at: state.cursor >= state.text.length ? now : state.at,+ };+}++/**+ * Moves the cursor to `now`: `rate` characters per second, or faster where an arrival's+ * deadline needs it — the cursor then heads for that arrival's end so as to reach it exactly at+ * the deadline. A step past a deadline lands on the arrival's end.+ */+export function stepReveal(state: RevealState, now: number, rate: number): RevealState {+ const length = state.text.length;+ if (now <= state.at) return state;+ if (state.cursor >= length) return { ...state, due: [], at: now };+ const dt = now - state.at;+ let cursor = state.cursor + (rate * dt) / 1000;+ for (const d of state.due) {+ const left = d.by - state.at;+ const needed = left <= dt ? d.end : state.cursor + ((d.end - state.cursor) * dt) / left;+ if (needed > cursor) cursor = needed;+ }+ cursor = Math.min(cursor, length);+ return { ...state, cursor, due: state.due.filter((d) => d.end > cursor), at: now };+}++/** Rounding slack for the fractional cursor, far below one character. */+const CURSOR_EPSILON = 1e-6;+/** Whitespace, where a word ends. */+const SPACE = /\s/;+/** CJK ideographs, kana, Hangul, CJK and fullwidth punctuation: each one is a word for `fade`. */+const WIDE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uff00-\uffef]/;+/** How far back `fade` looks for a word boundary before giving up and cutting mid-token. */+const WORD_LOOKBACK = 48;+/** Characters whose runs mean something different by length (`*` / `**`, `` ` `` / ` ``` `). */+const RUN_MARKS = "*_~`";+/**+ * A line of block syntax and nothing else yet: list and heading marks, a quote, a fence's+ * backticks, a table's pipes and rule, a setext underline, an ordered list's number. A single+ * character class, so it runs in linear time on any line.+ */+const SYNTAX_ONLY_LINE = /^[\s>*+\-#`~=_|:.)[\]\d]*$/;++/** Whether `fade` may cut the text at `p`: after whitespace, or beside a CJK character. */+function isWordBoundary(text: string, p: number): boolean {+ if (p <= 0) return true;+ const before = text[p - 1]!;+ if (SPACE.test(before) || WIDE.test(before)) return true;+ return p < text.length && WIDE.test(text[p]!);+}++/**+ * Where to cut the text for a cursor at `n`: the mode's granularity, then the Markdown guards+ * (see the header). Never past the text; may pass `n` only to finish a run of marks.+ */+export function revealCut(text: string, n: number, mode: StreamRevealMode): number {+ const length = text.length;+ let p = Math.max(0, Math.min(length, Math.floor(n)));+ if (mode === "fade") {+ const floor = Math.max(0, p - WORD_LOOKBACK);+ let q = p;+ while (q > floor && !isWordBoundary(text, q)) q--;+ if (isWordBoundary(text, q)) p = q;+ }+ // Never between the two halves of a surrogate pair (an emoji would show as a broken glyph).+ if (p > 0 && p < length) {+ const code = text.charCodeAt(p - 1);+ if (code >= 0xd800 && code <= 0xdbff) p++;+ }+ // Never inside a run of marks: finish the run.+ if (p > 0 && p < length && text[p - 1] === text[p] && RUN_MARKS.includes(text[p]!)) {+ const mark = text[p];+ while (p < length && text[p] === mark) p++;+ }+ // Hold back a line that is block syntax only so far.+ const lineStart = p === 0 ? 0 : text.lastIndexOf("\n", p - 1) + 1;+ const line = text.slice(lineStart, p);+ if (line.trim() !== "" && SYNTAX_ONLY_LINE.test(line)) p = lineStart;+ return p;+}++/**+ * How many characters of the text to show at `now`. Instant shows everything. A paced reveal+ * shows the text cut at the cursor; once the cursor has caught up, the whole text shows when the+ * stream has ended or its last arrival is past its deadline, and otherwise the live edge is cut+ * like any other point (a partial word or a syntax-only line waits for the next delta).+ */+export function visibleLength(+ state: RevealState,+ mode: StreamRevealMode,+ streaming: boolean,+ now: number,+): number {+ const length = state.text.length;+ if (mode === "instant") return length;+ // The cursor sums fractions frame by frame; the epsilon keeps 4.9999999999999996 from reading+ // as 4.+ const cursor = Math.min(length, state.cursor + CURSOR_EPSILON);+ if (cursor >= length && (!streaming || now >= state.settleBy)) return length;+ return revealCut(state.text, cursor, mode);+}++/**+ * How often a paced reveal hands React a new prefix, ms, by the length on screen. Every prefix+ * re-parses the whole reply's Markdown, so the cadence falls as the reply grows: about 30 frames+ * a second up to ~3,300 characters, down to the stream's own ~8 a second (its 120 ms commit+ * interval) from ~12,000 on — never more parse work than today's stream for a long reply.+ */+export function revealFrameMs(length: number): number {+ return Math.min(120, Math.max(33, length / 100));+}diff --git a/packages/web/src/features/chat/streaming-caret.tsx b/packages/web/src/features/chat/streaming-caret.tsxnew file mode 100644index 00000000..fc0235e8--- /dev/null+++ b/packages/web/src/features/chat/streaming-caret.tsx@@ -0,0 +1,13 @@+/**+ * The caret after a reply that is still coming in. It is the `caret` slot of the `ui-stream`+ * host (AssistantReplyBody), so each theme decides what it is: Primer keeps this soft pulsing+ * bar, Frost hides it behind its fading veil, Console draws a solid block. Decorative: the+ * reply's own text is what a screen reader reads.+ */+export function StreamingCaret() {+ return (+ <span data-slot="caret" aria-hidden="true" className="animate-pulse text-gray-400">+ ▌+ </span>+ );+}diff --git a/packages/web/src/features/chat/use-stream-reveal.ts b/packages/web/src/features/chat/use-stream-reveal.tsnew file mode 100644index 00000000..8865fecc--- /dev/null+++ b/packages/web/src/features/chat/use-stream-reveal.ts@@ -0,0 +1,98 @@+/**+ * `useStreamReveal(text, streaming)`: the part of a streaming reply's text to show right now,+ * paced by the active theme's `--ui-stream-reveal` and `--ui-stream-rate` (lib/stream-style.ts).+ *+ * Under `instant` — Primer, a theme without the tokens, or reduced motion by either signal — it+ * returns `text` itself and runs nothing: the reply renders exactly as it always has. Under+ * `fade` or `typewriter` a requestAnimationFrame loop walks the pacing in stream-reveal.ts and+ * hands React a new prefix only when the visible length changes, at most once per+ * {@link revealFrameMs} (the whole reply's Markdown re-parses on each), and stops once the+ * whole text is showing; new text restarts it. When `streaming` turns false the loop keeps+ * going until the rest is revealed at the rate, so the caller treats the reply as live while+ * the returned prefix is shorter than `text`.+ *+ * The pacing state lives in a ref the loop advances and the render reads; a counter state+ * re-renders the owner when the prefix changes. A theme switch mid-stream carries on from+ * whatever was on screen: under `instant` the ref is kept level with the text, so switching to a+ * paced theme paces only what arrives next.+ */+import { useEffect, useRef, useState } from "react";+import { usePrefersReducedMotion } from "../../components/ui/use-reduced-motion";+import { effectiveReveal, useStreamStyle } from "../../lib/stream-style";+import {+ receiveText,+ revealFrameMs,+ settledReveal,+ startReveal,+ stepReveal,+ visibleLength,+} from "./stream-reveal";+import type { RevealState } from "./stream-reveal";++interface Pacer {+ state: RevealState;+ /** The length the last render was handed. */+ shown: number;+ /** When `shown` last changed, on the frame clock. */+ shownAt: number;+}++export function useStreamReveal(text: string, streaming: boolean): string {+ const style = useStreamStyle();+ const reduced = usePrefersReducedMotion();+ const mode = effectiveReveal(style, reduced);+ const rate = style.rate;+ const paced = mode !== "instant";++ const pacerRef = useRef<Pacer | null>(null);+ if (pacerRef.current === null) {+ const now = performance.now();+ const state = startReveal(text, now, { streaming: streaming && paced, rate });+ pacerRef.current = { state, shown: visibleLength(state, mode, streaming, now), shownAt: now };+ }+ const [, rerender] = useState(0);++ useEffect(() => {+ const pacer = pacerRef.current!;+ const now = performance.now();+ if (!paced) {+ // Nothing to pace: stay level with the text, so a switch to a paced theme starts here.+ pacer.state = settledReveal(text, now);+ pacer.shown = text.length;+ return;+ }+ pacer.state = receiveText(pacer.state, text, now);+ // Text that replaced a longer one is already whole on screen (the render clamps to it).+ if (pacer.shown > text.length) pacer.shown = text.length;+ let frame = 0;+ const tick = (clock: number) => {+ frame = 0;+ // A frame's timestamp can precede the performance.now() read above.+ const at = Math.max(clock, pacer.state.at);+ pacer.state = stepReveal(pacer.state, at, rate);+ // Never take back what is on screen: an edge released at its deadline (a partial word, a+ // lone list mark) would otherwise vanish when the next delta makes it a cut point again.+ const next = Math.max(visibleLength(pacer.state, mode, streaming, at), pacer.shown);+ if (+ next !== pacer.shown &&+ (next >= text.length || at - pacer.shownAt >= revealFrameMs(next))+ ) {+ pacer.shown = next;+ pacer.shownAt = at;+ rerender((n) => n + 1);+ }+ if (pacer.shown < text.length) frame = requestAnimationFrame(tick);+ };+ if (pacer.shown < text.length) frame = requestAnimationFrame(tick);+ return () => {+ if (frame !== 0) cancelAnimationFrame(frame);+ };+ }, [text, streaming, paced, mode, rate]);++ if (!paced) return text;+ const pacer = pacerRef.current;+ // The pacing state may still hold the previous text for this render (the effect catches it up+ // after the commit); a prefix of the previous text is a prefix of this one unless the text was+ // replaced, and the next frame corrects that case.+ return pacer.shown >= text.length ? text : text.slice(0, pacer.shown);+}diff --git a/packages/web/src/lib/stream-style.ts b/packages/web/src/lib/stream-style.tsnew file mode 100644index 00000000..79706569--- /dev/null+++ b/packages/web/src/lib/stream-style.ts@@ -0,0 +1,134 @@+/**+ * How the active theme reveals a streaming reply: the `--ui-stream-*` tokens, read off the+ * root's computed style, for the one part CSS cannot do alone — pacing how much of the text+ * has arrived on screen. The theme's CSS draws the rest (the `ui-stream` hook's veil or caret).+ *+ * - `--ui-stream-reveal`: `instant` (each delta shows as it arrives), `fade` (new text is let+ * in word by word) or `typewriter` (character by character). Missing or unknown → `instant`.+ * - `--ui-stream-rate`: characters per second of a paced reveal (`fade` paces its words at this+ * rate too). Missing, zero or not a number → no pacing.+ *+ * Read the way lib/chart-style.ts reads the chart tokens: one MutationObserver on <html> drops+ * the cached record when the theme, mode or accent changes, a subscriber gets the same object+ * while nothing it reads changed, and nothing here ever writes. The record also carries the+ * gallery's reduced-motion switch (`data-motion="reduced"` on <html>), the second of the two+ * signals the theme CSS honours beside the media query.+ */+import { useSyncExternalStore } from "react";++export type StreamRevealMode = "instant" | "fade" | "typewriter";++export interface StreamStyle {+ /** How new text comes in. */+ reveal: StreamRevealMode;+ /** Characters per second of a paced reveal; 0 when the theme sets none. */+ rate: number;+ /** The root asks for reduced motion (`data-motion="reduced"`). */+ reducedMotion: boolean;+}++/** What a document without the theme sheet reveals with: every delta at once, as before. */+export const DEFAULT_STREAM_STYLE: StreamStyle = {+ reveal: "instant",+ rate: 0,+ reducedMotion: false,+};++/** Far past any reading pace: a larger value is a typo, and is held to this. */+const MAX_RATE = 5000;++/**+ * The record, from a reader of custom properties (`getPropertyValue` on the root's computed+ * style) and the root's `data-motion` attribute.+ */+export function readStreamStyle(+ read: (name: string) => string,+ motion: string | null,+): StreamStyle {+ const keyword = read("--ui-stream-reveal")+ .trim()+ .replace(/^["']|["']$/g, "");+ const rate = Number.parseFloat(read("--ui-stream-rate"));+ return {+ reveal: keyword === "fade" || keyword === "typewriter" ? keyword : "instant",+ rate: Number.isFinite(rate) && rate > 0 ? Math.min(rate, MAX_RATE) : 0,+ reducedMotion: motion === "reduced",+ };+}++/**+ * The mode a reply is actually revealed in: `instant` whenever there is nothing to pace with (no+ * rate) or the reader asked for less motion by either signal — the root's switch in the record,+ * or the operating system's preference, which the caller passes.+ */+export function effectiveReveal(+ style: StreamStyle,+ prefersReducedMotion: boolean,+): StreamRevealMode {+ if (style.rate <= 0 || style.reducedMotion || prefersReducedMotion) return "instant";+ return style.reveal;+}++/** Whether two records reveal the same way. */+export function sameStreamStyle(a: StreamStyle, b: StreamStyle): boolean {+ return a.reveal === b.reveal && a.rate === b.rate && a.reducedMotion === b.reducedMotion;+}++/**+ * The next record to hand out: `previous` itself when nothing changed, so a subscriber sees the+ * same object and React re-renders nothing. <html> changes for many reasons that are not the+ * theme; a new object on each of those would restart every streaming reply's pacing loop.+ */+export function nextStreamStyle(previous: StreamStyle | null, read: StreamStyle): StreamStyle {+ return previous !== null && sameStreamStyle(previous, read) ? previous : read;+}++let cached: StreamStyle | null = null;+const listeners = new Set<() => void>();+let observer: MutationObserver | null = null;++/** Reads the root's tokens and motion switch. Reading never writes. */+function readRoot(): StreamStyle {+ const root = document.documentElement;+ const computed = getComputedStyle(root);+ return readStreamStyle(+ (name) => computed.getPropertyValue(name),+ root.getAttribute("data-motion"),+ );+}++function snapshot(): StreamStyle {+ if (cached === null) cached = readRoot();+ return cached;+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ if (observer === null) {+ // No one watched <html> while no reply was mounted: catch up once, keeping the same object+ // when nothing changed in the meantime.+ if (cached !== null) cached = nextStreamStyle(cached, readRoot());+ observer = new MutationObserver(() => {+ const next = nextStreamStyle(cached, readRoot());+ if (next === cached) return;+ cached = next;+ for (const l of listeners) l();+ });+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class", "data-theme", "data-accent", "data-motion", "style"],+ });+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0) {+ observer?.disconnect();+ observer = null;+ }+ };+}++/** The active theme's stream style; a reply re-renders when the theme or motion switch changes. */+export function useStreamStyle(): StreamStyle {+ return useSyncExternalStore(subscribe, snapshot, () => DEFAULT_STREAM_STYLE);+}diff --git a/packages/web/test/deslop.test.ts b/packages/web/test/deslop.test.tsindex ef6b2958..1ffa425f 100644--- a/packages/web/test/deslop.test.ts+++ b/packages/web/test/deslop.test.ts@@ -107,7 +107,7 @@ const ALLOWLIST: DeslopAllowlist = {"features/chat/drop-zone.tsx": { 18: [1, "W7"] },"features/chat/live-duration.tsx": { 6: [1, "W4"] },"features/chat/memory-view.tsx": { 13: [2, "W6"] },- "features/chat/message-item.tsx": { 4: [2, "W6"], 6: [1, "W6"], 13: [3, "W6"] },+ "features/chat/message-item.tsx": { 4: [2, "W6"], 13: [3, "W6"] },"features/chat/message-stream.tsx": { 11: [2, "W1b"] },"features/chat/model-picker-modal.tsx": { 12: [1, "W10"] },"features/chat/shortcuts-folder.tsx": { 12: [1, "W7"] },diff --git a/packages/web/test/stream-reveal.test.ts b/packages/web/test/stream-reveal.test.tsnew file mode 100644index 00000000..8692b183--- /dev/null+++ b/packages/web/test/stream-reveal.test.ts@@ -0,0 +1,346 @@+/**+ * The streaming reveal: the theme's stream tokens (lib/stream-style.ts), the pacing+ * (features/chat/stream-reveal.ts) and the reply body that applies them.+ *+ * The pacing is a pure function of an explicit clock, so these tests drive the clock+ * themselves, frame by frame, the way use-stream-reveal.ts does from requestAnimationFrame:+ * typewriter by character, fade by word, the 1.5 s backlog cap, finishing at the rate after the+ * stream ends, and `instant` (Primer, no tokens, reduced motion) showing the text whole. The+ * suite renders no React, so the body's markup is pinned against its source at the bottom.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import {+ DEFAULT_STREAM_STYLE,+ effectiveReveal,+ nextStreamStyle,+ readStreamStyle,+} from "../src/lib/stream-style";+import type { StreamRevealMode } from "../src/lib/stream-style";+import {+ REVEAL_MAX_LAG_MS,+ receiveText,+ revealCut,+ revealFrameMs,+ startReveal,+ stepReveal,+ visibleLength,+} from "../src/features/chat/stream-reveal";+import type { RevealState } from "../src/features/chat/stream-reveal";++const FRAME = 16;++const reader = (tokens: Record<string, string>) => (name: string) => tokens[name] ?? "";++/** A reply that opened empty at `t = 0` and has just received `text`. */+function opened(text: string, rate: number, at = 0): RevealState {+ return receiveText(startReveal("", 0, { streaming: true, rate }), text, at);+}++/** What shows at `t` after stepping frame by frame from the state's clock. */+function showAt(+ state: RevealState,+ t: number,+ rate: number,+ mode: StreamRevealMode,+ streaming = true,+): { state: RevealState; shown: string } {+ let s = state;+ for (let at = s.at + FRAME; at < t; at += FRAME) s = stepReveal(s, at, rate);+ s = stepReveal(s, t, rate);+ return { state: s, shown: s.text.slice(0, visibleLength(s, mode, streaming, t)) };+}++interface Chunk {+ at: number;+ text: string;+}++/**+ * Plays a stream frame by frame: each chunk is received at its own time, the stream closes at+ * `closeAt`, and every frame records the visible length and the text received so far.+ */+function play(opts: {+ chunks: readonly Chunk[];+ closeAt: number;+ until: number;+ rate: number;+ mode: StreamRevealMode;+}): { t: number; shown: number; received: number }[] {+ let state = startReveal("", 0, { streaming: true, rate: opts.rate });+ let received = "";+ let next = 0;+ const frames: { t: number; shown: number; received: number }[] = [];+ for (let t = FRAME; t <= opts.until; t += FRAME) {+ while (next < opts.chunks.length && opts.chunks[next]!.at <= t) {+ const chunk = opts.chunks[next++]!;+ received += chunk.text;+ state = receiveText(state, received, Math.max(chunk.at, state.at));+ }+ state = stepReveal(state, t, opts.rate);+ const streaming = t < opts.closeAt;+ const shown = visibleLength(state, opts.mode, streaming, t);+ frames.push({ t, shown, received: received.length });+ }+ return frames;+}++describe("readStreamStyle", () => {+ it("reads the two tokens a theme defines", () => {+ expect(+ readStreamStyle(+ reader({ "--ui-stream-reveal": " typewriter", "--ui-stream-rate": " 90" }),+ null,+ ),+ ).toEqual({ reveal: "typewriter", rate: 90, reducedMotion: false });+ expect(+ readStreamStyle(reader({ "--ui-stream-reveal": "fade", "--ui-stream-rate": "220" }), null),+ ).toMatchObject({ reveal: "fade", rate: 220 });+ });++ it("reads a missing, unknown or unusable token as instant with no pace", () => {+ expect(readStreamStyle(reader({}), null)).toEqual(DEFAULT_STREAM_STYLE);+ expect(+ readStreamStyle(reader({ "--ui-stream-reveal": "wiggle", "--ui-stream-rate": "x" }), null),+ ).toEqual(DEFAULT_STREAM_STYLE);+ expect(readStreamStyle(reader({ "--ui-stream-rate": "-5" }), null).rate).toBe(0);+ });++ it("carries the root's reduced-motion switch", () => {+ expect(readStreamStyle(reader({}), "reduced").reducedMotion).toBe(true);+ expect(readStreamStyle(reader({}), "full").reducedMotion).toBe(false);+ });++ it("hands out the same record while nothing it reads changed", () => {+ const first = readStreamStyle(reader({ "--ui-stream-reveal": "fade" }), null);+ const again = readStreamStyle(reader({ "--ui-stream-reveal": "fade" }), null);+ expect(nextStreamStyle(first, again)).toBe(first);+ const changed = readStreamStyle(reader({ "--ui-stream-reveal": "typewriter" }), null);+ expect(nextStreamStyle(first, changed)).toBe(changed);+ });+});++describe("effectiveReveal", () => {+ const typewriter = { reveal: "typewriter", rate: 90, reducedMotion: false } as const;++ it("paces in the theme's mode when it has a rate", () => {+ expect(effectiveReveal(typewriter, false)).toBe("typewriter");+ expect(effectiveReveal({ ...typewriter, reveal: "fade", rate: 220 }, false)).toBe("fade");+ });++ it("is instant with no rate, and under reduced motion by either signal", () => {+ expect(effectiveReveal({ ...typewriter, rate: 0 }, false)).toBe("instant");+ expect(effectiveReveal({ ...typewriter, reducedMotion: true }, false)).toBe("instant");+ expect(effectiveReveal(typewriter, true)).toBe("instant");+ expect(effectiveReveal(DEFAULT_STREAM_STYLE, false)).toBe("instant");+ });+});++describe("the paced reveal", () => {+ it("types character by character at the rate", () => {+ const s = opened("Hello world", 100);+ const early = showAt(s, 50, 100, "typewriter");+ expect(early.shown).toBe("Hello");+ expect(showAt(early.state, 80, 100, "typewriter").shown).toBe("Hello wo");+ });++ it("fades word by word at the same characters-per-second pace", () => {+ const s = opened("Hello world", 100);+ expect(showAt(s, 50, 100, "fade").shown).toBe("");+ const first = showAt(s, 60, 100, "fade");+ expect(first.shown).toBe("Hello ");+ // Caught up at the live edge: the partial last word waits for the next delta…+ const edge = showAt(first.state, 200, 100, "fade");+ expect(edge.shown).toBe("Hello ");+ // …and shows once the stream has ended, or once its arrival is past the deadline.+ expect(visibleLength(edge.state, "fade", false, 200)).toBe(11);+ expect(showAt(edge.state, REVEAL_MAX_LAG_MS, 100, "fade").shown).toBe("Hello world");+ });++ it("treats every CJK character as a word of its own", () => {+ expect(showAt(opened("你好世界", 100), 20, 100, "fade").shown).toBe("你好");+ });++ it("shows the text whole when instant", () => {+ const s = opened("Hello world", 100);+ expect(visibleLength(s, "instant", true, 0)).toBe(11);+ // No rate: nothing to pace with, so the reply starts, and stays, whole.+ const unpaced = startReveal("Hello", 0, { streaming: true, rate: 0 });+ expect(visibleLength(unpaced, "fade", true, 0)).toBe(5);+ });++ it("returns the whole text under reduced motion, whatever the theme asks for", () => {+ const frost = { reveal: "fade", rate: 220, reducedMotion: false } as const;+ const s = opened("Hello world", frost.rate);+ // The operating system's preference, then the root's switch.+ expect(visibleLength(s, effectiveReveal(frost, true), true, 0)).toBe(11);+ const switched = effectiveReveal({ ...frost, reducedMotion: true }, false);+ expect(visibleLength(s, switched, true, 0)).toBe(11);+ });++ it("speeds up smoothly so a burst is on screen within the lag cap", () => {+ const text = "abc ".repeat(750); // 3,000 characters in one burst+ let s = opened(text, 10);+ let last = 0;+ let t = 0;+ let largest = 0;+ while (t < REVEAL_MAX_LAG_MS) {+ t += FRAME;+ s = stepReveal(s, t, 10);+ const shown = visibleLength(s, "typewriter", true, t);+ expect(shown).toBeGreaterThanOrEqual(last);+ largest = Math.max(largest, shown - last);+ last = shown;+ if (t === 752) expect(shown).toBeGreaterThan(1400); // halfway there at halfway through+ }+ expect(last).toBe(3000);+ // At 10 characters a second it would have shown 15; it got there in even frames instead.+ expect(largest).toBeLessThanOrEqual(40);+ });++ it("never trails a fast stream by more than the cap, and eases along without jumps", () => {+ const chunk = "lorem ipsum dolor sit amet ok "; // 30 characters, every 100 ms: 300 a second+ const chunks = Array.from({ length: 50 }, (_, i) => ({ at: i * 100, text: chunk }));+ const frames = play({ chunks, closeAt: 5000, until: 8000, rate: 50, mode: "typewriter" });+ const arrivedBy = (time: number) =>+ time < 0 ? 0 : Math.min(1500, (Math.floor(time / 100) + 1) * chunk.length);+ let previous = 0;+ for (const f of frames) {+ expect(f.shown).toBeGreaterThanOrEqual(arrivedBy(f.t - REVEAL_MAX_LAG_MS));+ expect(f.shown).toBeLessThanOrEqual(f.received);+ expect(f.shown - previous).toBeLessThanOrEqual(12);+ previous = f.shown;+ }+ // Still revealing after the stream closed, and done once the last deadline passed.+ expect(frames.find((f) => f.t === 5008)!.shown).toBeLessThan(1500);+ expect(frames.find((f) => f.t === 6400)!.shown).toBe(1500);+ });++ it("finishes the rest at the rate once the stream ends, without jumping to the end", () => {+ // 100 characters: few enough that the rate, not the lag cap, sets the pace.+ const text = "abcd ".repeat(20);+ const s = opened(text, 100);+ const half = showAt(s, 496, 100, "typewriter", false);+ expect(half.shown.length).toBeGreaterThanOrEqual(45);+ expect(half.shown.length).toBeLessThanOrEqual(55);+ expect(showAt(half.state, 1008, 100, "typewriter", false).shown).toBe(text);+ });++ it("does not count time spent caught up as reveal time", () => {+ const caughtUp = showAt(opened("Hello", 100), 1000, 100, "typewriter").state;+ const s = receiveText(caughtUp, "Hello world", 10_000);+ expect(showAt(s, 10_016, 100, "typewriter").shown).toBe("Hello ");+ });++ it("falls back to the shared prefix when the text is replaced", () => {+ const shown = showAt(opened("Hello world", 100), 2000, 100, "typewriter", false).state;+ const replaced = receiveText(shown, "Hello there!", 2000);+ expect(replaced.cursor).toBe(6);+ expect(showAt(replaced, 2030, 100, "typewriter").shown).toBe("Hello the");+ });++ it("starts a reply that mounts mid-stream near its end, and a settled one whole", () => {+ const text = "a".repeat(1000);+ expect(startReveal(text, 0, { streaming: true, rate: 100 }).cursor).toBe(850);+ expect(startReveal(text, 0, { streaming: false, rate: 100 }).cursor).toBe(1000);+ expect(startReveal("", 0, { streaming: true, rate: 100 }).cursor).toBe(0);+ });++ it("hands React fewer prefixes as the reply grows", () => {+ expect(revealFrameMs(0)).toBe(33);+ expect(revealFrameMs(6000)).toBe(60);+ expect(revealFrameMs(50_000)).toBe(120);+ });+});++describe("revealCut (half-typed Markdown)", () => {+ /** The text shown when the cursor has reached the end of `upTo`, a prefix of `text`. */+ const cut = (text: string, upTo: string) =>+ text.slice(0, revealCut(text, upTo.length, "typewriter"));++ it("holds a list mark until the item has text, so a paragraph never flips to a heading", () => {+ const text = "Steps:\n- install\n- run";+ expect(cut(text, "Steps:\n-")).toBe("Steps:\n");+ expect(cut(text, "Steps:\n- ")).toBe("Steps:\n");+ expect(cut(text, "Steps:\n- i")).toBe("Steps:\n- i");+ expect(cut("1. one\n2. two", "1. one\n2")).toBe("1. one\n");+ });++ it("holds a heading's marks, a quote's and a table's rule until text follows", () => {+ expect(cut("## Setup", "#")).toBe("");+ expect(cut("## Setup", "## ")).toBe("");+ expect(cut("## Setup", "## S")).toBe("## S");+ expect(cut("> quoted", "> ")).toBe("");+ const table = "| a | b |\n|---|---|\n| x | y |";+ expect(cut(table, "| a | b |\n|---|-")).toBe("| a | b |\n");+ expect(cut(table, "| a | b |\n|---|---|\n| x")).toBe("| a | b |\n|---|---|\n| x");+ });++ it("opens a fence with its info string or first line, and closes it only when whole", () => {+ const text = "```ts\nconst a = 1;\n```\nafter";+ expect(cut(text, "``")).toBe("");+ expect(cut(text, "```")).toBe("");+ expect(cut(text, "```t")).toBe("```t");+ expect(cut(text, "```ts\nconst a = 1;\n``")).toBe("```ts\nconst a = 1;\n");+ expect(cut(text, "```ts\nconst a = 1;\n```\na")).toBe("```ts\nconst a = 1;\n```\na");+ const bare = "```\nx\n```";+ expect(cut(bare, "```\n")).toBe("```\n");+ expect(cut(bare, "```\nx")).toBe("```\nx");+ });++ it("never splits a run of marks or a surrogate pair", () => {+ expect(cut("a **b** c", "a *")).toBe("a **");+ expect(cut("use `x`", "use `")).toBe("use `");+ expect(cut("a😀b", "a\ud83d")).toBe("a😀");+ });++ it("leaves plain text where the cursor is", () => {+ expect(cut("plain words here", "plain wo")).toBe("plain wo");+ });+});++/**+ * Source of the reply body, its caret and the item that renders it. The suite renders no React,+ * so the markup the theme recipes select on is pinned against the text that writes it.+ */+const read = (p: string) => readFileSync(fileURLToPath(new URL(p, import.meta.url)), "utf8");+const body = read("../src/features/chat/assistant-reply-body.tsx");+const caret = read("../src/features/chat/streaming-caret.tsx");+const item = read("../src/features/chat/message-item.tsx");+const hook = read("../src/features/chat/use-stream-reveal.ts");++describe("the reply body (source contract)", () => {+ it("is the ui-stream host, streaming until the reveal has caught up and done after", () => {+ expect(body).toMatch(/className="ui-stream md-body /);+ expect(body).toContain('data-state={live ? "streaming" : "done"}');+ expect(body).toContain("const revealed = useStreamReveal(text, streaming);");+ expect(body).toContain("const live = streaming || revealed.length < text.length;");+ });++ it("renders the revealed prefix, in Markdown's streaming mode while live", () => {+ expect(body).toContain("<Md text={revealed} streaming={live} />");+ });++ it("shows the caret slot while live, and the item's extras only once the reply is whole", () => {+ expect(body).toContain("{live && <StreamingCaret />}");+ expect(body).toContain("{!live && children}");+ expect(caret).toContain('data-slot="caret"');+ expect(caret).toContain('aria-hidden="true"');+ // Primer's caret as it always was: a soft pulsing bar in the muted ink.+ expect(caret).toContain('className="animate-pulse text-gray-400"');+ expect(caret).toContain("▌");+ });++ it("is how the transcript renders every assistant reply", () => {+ expect(item).toContain("<AssistantReplyBody text={item.text} streaming={item.streaming}>");+ expect(item).not.toContain("▌");+ expect(item).not.toMatch(/<Md\b/);+ });++ it("drives the pacing from animation frames and cancels them on cleanup", () => {+ expect(hook).toContain("requestAnimationFrame(tick)");+ expect(hook).toContain("cancelAnimationFrame(frame)");+ expect(hook).toMatch(/if \(!paced\) return text;/);+ });+});