A local-first multi-agent app development platform, built on PenguinHarness
refactor(ui,web): W6 — the chat transcript and the composer move into the UI package (#905)
Yaowei Zheng683e6e81bf23
diff --git a/changelog/unreleased/2026-09-30-ui-migration-w6.md b/changelog/unreleased/2026-09-30-ui-migration-w6.mdnew file mode 100644index 00000000..a6789ea4--- /dev/null+++ b/changelog/unreleased/2026-09-30-ui-migration-w6.md@@ -0,0 +1,42 @@+# The chat transcript and the composer move into the shared UI package++- **Date:** 2026-09-30+- **Type:** refactor+- **Scope:** `ui`, `web`, `ui-gallery`++[中文版](2026-09-30-ui-migration-w6.zh.md)++W6 of the UI-package migration lifts the conversation into `@prismshadow/penguin-ui`: the package draws the transcript and the composer, and the Web App keeps the Session state, sending and the model catalog.++## What moved++- **Transcript:**+ - `MessageBubble`, `MessageMeta` and `MessageImage`.+ - `AssistantText` and `StreamingCaret`, the streamed reply; the streaming reveal's pacing moves with them.+ - `ChangesCard`, now drawing both the message files card and the memory changes card.+- **Agent work:** `WorkGroup`, `ThinkingBlock`, `StepBanner`, `ToolCallCard`, `ApprovalButtons` and `ApprovalBlock`, and `SubagentChip`. The web keeps thin Session containers for each.+- **Composer:**+ - `ComposerCard`, `ChipRow`, `ToolbarTrigger`, `SendButton`, `SlashMenu` and `SlashPicker`.+ - `TagInput` and `Chip`, and `MenuSelect` for the composer's selects.+ - `ContextRing`, and `ModelSelect`, the model picker's trigger (the picker itself is the Web App's model-picker dialog). The web's catalog-bound picker is `ModelCatalogSelect`.+- **Company channel:** `ChannelRun` and `ChannelBubble`.++## Details++- A new token, `--ui-fill-neutral`, is the neutral fill that message bubbles and chips sit on. In every theme it takes the bubble grey used before this change, so Console keeps its filled bubbles.+- The composer keeps its neutral focus ring in every theme.+- The Trace and transcript tool rows no longer pulse their placeholder, and the stop button is a neutral square with a red glyph.++## Visible changes in the default theme (Primer)++- **Text and ink:**+ - Transcript and composer inks are one step darker in light mode (gray-800 → gray-900) and one step lighter in dark mode.+ - 10–11 px captions become 12 px: message times, the stats footer, subagent ids and the attachment size.+- **Step banner:** its title is 12 px sentence case instead of 11 px uppercase.+- **Composer:**+ - The send button takes the accent fill.+ - The stop button changes from a red tint to a neutral fill with a red glyph.+ - Toolbar hover fills are lighter.+ - Reference chips are 24 px tall like the other chips.+- **Chat header:** the Session title in the header is 14 px, the nearest heading size (was 15 px).+- **Company channel:** your own bubble is a light wash of the link colour, and names and times are 12 px.diff --git a/changelog/unreleased/2026-09-30-ui-migration-w6.zh.md b/changelog/unreleased/2026-09-30-ui-migration-w6.zh.mdnew file mode 100644index 00000000..c8fb097f--- /dev/null+++ b/changelog/unreleased/2026-09-30-ui-migration-w6.zh.md@@ -0,0 +1,42 @@+# 对话记录与输入区迁入共享 UI 包++- **Date:** 2026-09-30+- **Type:** refactor+- **Scope:** `ui`, `web`, `ui-gallery`++[English](2026-09-30-ui-migration-w6.md)++UI 包迁移的 W6 把对话拆分进 `@prismshadow/penguin-ui`:对话记录与输入区的呈现由包负责,Session 状态、发送与模型目录留在 Web App。++## 迁入的内容++- **对话记录**:+ - `MessageBubble`、`MessageMeta`、`MessageImage`。+ - 流式回答 `AssistantText` 与 `StreamingCaret`,流式显现的节奏随之迁入。+ - `ChangesCard`,现同时用于消息文件卡与记忆变更卡。+- **Agent 的工作过程**:`WorkGroup`、`ThinkingBlock`、`StepBanner`、`ToolCallCard`、`ApprovalButtons` 与 `ApprovalBlock`、`SubagentChip`;Web App 为每个组件保留一个很薄的 Session 容器。+- **输入区**:+ - `ComposerCard`、`ChipRow`、`ToolbarTrigger`、`SendButton`、`SlashMenu`、`SlashPicker`。+ - `TagInput` 与 `Chip`,以及输入区的选择框 `MenuSelect`。+ - `ContextRing`,以及模型选择器的触发按钮 `ModelSelect`(选择器本身是 Web App 的模型选择对话框);Web App 中绑定模型目录的选择器改名为 `ModelCatalogSelect`。+- **公司频道**:`ChannelRun` 与 `ChannelBubble`。++## 细节++- 新增令牌 `--ui-fill-neutral`:消息气泡与标签片所用的中性填充。各主题取改动前的气泡灰,因此 Console 的气泡仍有底色。+- 输入区在各主题下保留原有的中性焦点环。+- Trace 与对话中工具行的占位不再脉动;停止按钮改为中性底加红色图标。++## 通用主题下可见的变化++- **文字与墨色**:+ - 对话与输入区的墨色在浅色下深一级(gray-800 → gray-900),深色下浅一级。+ - 10–11 px 的说明改为 12 px:消息时间、统计行、子 Agent 编号、附件大小。+- **步骤横幅**:标题改为 12 px 的句首大写,不再是 11 px 全大写。+- **输入区**:+ - 发送按钮取强调色填充。+ - 停止按钮由红色浅底改为中性底加红色图标。+ - 工具栏按钮的悬停底色变浅。+ - 引用标签片与其他标签片同为 24 px 高。+- **对话页头**:Session 标题为 14 px,取最接近的标题字阶(原 15 px)。+- **公司频道**:自己的气泡改为链接色的浅色晕染,名字与时间为 12 px。diff --git a/packages/ui-gallery/src/library/boards/charts.tsx b/packages/ui-gallery/src/library/boards/charts.tsxindex 2a9e5fae..3d187d20 100644--- a/packages/ui-gallery/src/library/boards/charts.tsx+++ b/packages/ui-gallery/src/library/boards/charts.tsx@@ -18,7 +18,7 @@ import type {TraceToolSpan,UsageSeriesPoint,} from "@prismshadow/penguin-server/api";-import { Legend, Ring, Sparkline, TokenDonut } from "@prismshadow/penguin-ui";+import { ContextRing, Legend, Ring, Sparkline, TokenDonut } from "@prismshadow/penguin-ui";import type { LegendItem, RingSegment, ToneName } from "@prismshadow/penguin-ui";import { humanizeTokens } from "../../../../web/src/lib/format";import { TimelineChart } from "../../../../web/src/features/traces/timeline-chart";@@ -102,6 +102,9 @@ const SPEND: readonly { ratio: number; tone: ToneName }[] = [{ ratio: 1.2, tone: "danger" },];+/** The composer's context ring at rest, past its attention mark and past its danger mark. */+const CONTEXT_SHARES = [0.62, 0.9, 0.99] as const;+/** A whole split into shares, each in its series slot. */const SHARES: readonly RingSegment[] = [0.34, 0.22, 0.18, 0.12].map((value, series) => ({value,@@ -265,8 +268,14 @@ export function ChartsBoard() {))}<Ring segments={[]} max={1} size={40} width={4} label={t.ringNoBudget} /><Ring segments={SHARES} max={1} size={40} width={6} label={t.ringShares} />- <span className="lib-cell text-fg-subtle">- <Ring segments={[{ value: 0.62 }]} max={1} size={12} width={2} trackOpacity={0.25} />+ <span className="lib-cell">+ {CONTEXT_SHARES.map((ratio) => (+ <ContextRing+ key={ratio}+ ratio={ratio}+ label={t.ringContextAt(Math.round(ratio * 100))}+ />+ ))}<span className="lib-caption">{t.ringContext}</span></span></div>diff --git a/packages/ui-gallery/src/library/boards/streaming.tsx b/packages/ui-gallery/src/library/boards/streaming.tsxindex 9406a961..c6ff0e31 100644--- a/packages/ui-gallery/src/library/boards/streaming.tsx+++ b/packages/ui-gallery/src/library/boards/streaming.tsx@@ -1,20 +1,19 @@/*** 流式输出: 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.+ * chunks (src/app/mock/stream-script.ts) and goes to the package's AssistantText — the body the+ * app renders every reply through — 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, usePrefersReducedMotion } from "@prismshadow/penguin-ui";+import { AssistantText, STREAM_REVEALS, usePrefersReducedMotion } from "@prismshadow/penguin-ui";import type { StreamReveal } from "@prismshadow/penguin-ui";-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";@@ -131,11 +130,11 @@ export function StreamingBoard() {><div className="lib-box lib-stream"><div className="lib-stream-sizer" aria-hidden inert>- <AssistantReplyBody text={answer} streaming={false} />+ <AssistantText 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} />+ <AssistantText key={run} text={stream.text} streaming={stream.streaming} /></div></div>{tokens === null ? (diff --git a/packages/ui-gallery/src/strings-en.ts b/packages/ui-gallery/src/strings-en.tsindex ebb28ad2..ff4b8d1f 100644--- a/packages/ui-gallery/src/strings-en.ts+++ b/packages/ui-gallery/src/strings-en.ts@@ -869,11 +869,12 @@ export const en: GalleryStrings = {},ring: "Ring gauge",ringHint:- "One arc against a budget in the budget's tone (under, near, over); without a budget the track stands alone; the composer's 12 px context ring takes the ink around it; several arcs split a whole into shares.",+ "One arc against a budget in the budget's tone (under, near, over); without a budget the track stands alone; several arcs split a whole into shares. The composer's context ring (ContextRing) stays in the muted ink to 80 %, turns to attention past it and to danger past 95 %.",ringSpend: (percent) => `Spend at ${percent}% of the budget`,ringNoBudget: "No budget set",ringShares: "Shares of a whole",ringContext: "Context ring",+ ringContextAt: (percent) => `Context ${percent}% full`,legend: "Legend",legendHint:"A row under a chart: pointing at one item fades the others, and an item that explains a line's shape stays out of it. A list legend prints each item's figures after its label and pins a row on click.",diff --git a/packages/ui-gallery/src/strings.ts b/packages/ui-gallery/src/strings.tsindex 89fd2fb5..b03e0d53 100644--- a/packages/ui-gallery/src/strings.ts+++ b/packages/ui-gallery/src/strings.ts@@ -834,11 +834,12 @@ export const zh = {},ring: "环形仪表",ringHint:- "一段弧对照预算,按预算状态着色(未超、将超、已超);未设预算只剩底环;输入框的 12 px 上下文圆环沿用所在处的墨色;多段弧表示各部分占比。",+ "一段弧对照预算,按预算状态着色(未超、将超、已超);未设预算只剩底环;多段弧表示各部分占比。输入框的上下文圆环(ContextRing)在 80% 以内取次要墨色,超过 80% 转为提醒色,超过 95% 转为危险色。",ringSpend: (percent: number) => `支出占预算 ${percent}%`,ringNoBudget: "未设预算",ringShares: "各部分占比",ringContext: "上下文圆环",+ ringContextAt: (percent: number) => `上下文已用 ${percent}%`,legend: "图例",legendHint:"图表下方的一行图例:指向某项时其余各项淡出;说明线形的一项不参与高亮。列表图例在标签后列出数值,点击可固定一行。",diff --git a/packages/ui-gallery/test/library.test.ts b/packages/ui-gallery/test/library.test.tsindex a78b5985..7a4c7841 100644--- a/packages/ui-gallery/test/library.test.ts+++ b/packages/ui-gallery/test/library.test.ts@@ -289,6 +289,36 @@ describe("the content board", () => {});});+describe("the streaming board", () => {+ it("plays the streaming Session's answer through the package's reply body, on one seed, with a replay", () => {+ const board = read("../src/library/boards/streaming.tsx");+ expect(board).toMatch(/import \{ AssistantText, [^}]*\} from "@prismshadow\/penguin-ui";/);+ expect(board).not.toMatch(/web\/src\/features\/chat/);+ expect(board).toMatch(/streamScript\(text, BOARD_SEED\)/);+ expect(board).toMatch(/const answer = streamingAnswer\(state\.lang\);/);+ expect(board).toMatch(+ /<AssistantText 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 layout and data boards", () => {it("show every layout and data component from the package, and nothing from the app", () => {const boards = {@@ -333,37 +363,6 @@ describe("the layout and data boards", () => {});});-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/src/components/chat/approval-block/approval-block.tsx b/packages/ui/src/components/chat/approval-block/approval-block.tsxnew file mode 100644index 00000000..755e9973--- /dev/null+++ b/packages/ui/src/components/chat/approval-block/approval-block.tsx@@ -0,0 +1,103 @@+/**+ * A tool call waiting on a person's decision: the call's name and the arguments it will run+ * with, and the two buttons that decide it.+ *+ * The block is always on screen while the call waits, whatever its card's collapsed state, so the+ * reader never has to open anything to find what they are approving. Below `sm` the argument+ * preview wraps in full (no truncation, no inner scroll — the block may grow): the person must be+ * able to read the whole command before deciding. From `sm` up it stays one line. A file tool's+ * decoded payload (what it will write) follows in a scrollable block, since a bare path does not+ * say what is being approved.+ *+ * The buttons are words at every breakpoint: an action a person presses reads as "Allow" and+ * "Deny", never as a glyph. Both stay disabled while the decision is being submitted.+ */+import { useState } from "react";+import { Button } from "../../actions/button/button";++export type ApprovalChoice = "allow" | "deny";++/** The two buttons' words. */+export interface ApprovalLabels {+ allow: string;+ deny: string;+}++export function ApprovalButtons({+ onDecide,+ labels,+}: {+ /** Submits the decision; the buttons stay disabled until it settles. */+ onDecide: (decision: ApprovalChoice) => Promise<void>;+ labels: ApprovalLabels;+}) {+ const [busy, setBusy] = useState(false);++ const decide = async (decision: ApprovalChoice) => {+ setBusy(true);+ try {+ await onDecide(decision);+ } finally {+ setBusy(false);+ }+ };++ return (+ <div className="flex items-center gap-2">+ <Button size="sm" variant="primary" disabled={busy} onClick={() => void decide("allow")}>+ {labels.allow}+ </Button>+ <Button size="sm" disabled={busy} onClick={() => void decide("deny")}>+ {labels.deny}+ </Button>+ </div>+ );+}++/** What a waiting call asks of the person: the arguments to read and the decision to make. */+export interface ApprovalRequest {+ /** The one-line argument preview: the command, the file path, or the raw arguments. */+ preview: string;+ /** A file tool's decoded payload (the rewrite it will make), shown in full; null for others. */+ payload?: string | null;+ onDecide: (decision: ApprovalChoice) => Promise<void>;+ labels: ApprovalLabels;+}++export interface ApprovalBlockProps extends ApprovalRequest {+ /** The call's name as shown on its row (an alias, when the caller resolves one). */+ name: string;+ /** The tool's own name when `name` is an alias: the name chip's tooltip. */+ nameTooltip?: string;+}++export function ApprovalBlock({+ name,+ nameTooltip,+ preview,+ payload,+ onDecide,+ labels,+}: ApprovalBlockProps) {+ return (+ <div className="border-t border-line-muted bg-tone-attention-bg px-3 py-2">+ <div className="mb-2 flex items-start gap-2 sm:items-center">+ <span+ data-tooltip={nameTooltip}+ className="shrink-0 rounded-md bg-surface px-1.5 py-0.5 font-mono text-xs font-semibold text-fg"+ >+ {name}+ </span>+ <span className="min-w-0 flex-1 whitespace-pre-wrap break-all font-mono text-xs text-fg-muted sm:truncate">+ {preview}+ </span>+ </div>+ {payload !== undefined && payload !== null && (+ <pre className="mb-2 max-h-72 overflow-auto whitespace-pre-wrap break-all rounded-md bg-surface/70 px-2 py-1.5 text-xs leading-5 text-fg">+ {payload}+ </pre>+ )}+ <ApprovalButtons onDecide={onDecide} labels={labels} />+ </div>+ );+}diff --git a/packages/web/src/features/chat/assistant-reply-body.tsx b/packages/ui/src/components/chat/assistant-text/assistant-text.tsxsimilarity index 70%rename from packages/web/src/features/chat/assistant-reply-body.tsxrename to packages/ui/src/components/chat/assistant-text/assistant-text.tsxindex edfd99ce..358e8f11 100644--- a/packages/web/src/features/chat/assistant-reply-body.tsx+++ b/packages/ui/src/components/chat/assistant-text/assistant-text.tsx@@ -1,44 +1,42 @@/*** 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+ * the caller adds once the reply is whole. The Web App 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+ * reveals instantly, so the body renders as a plain reply; 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 the UI package's Md) 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.+ * stays in its streaming mode (no highlighting, no KaTeX; see prose.tsx) until the reveal is+ * done, and `children` (a 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 "@prismshadow/penguin-ui";+import { Md } from "../../content/prose/prose";import { StreamingCaret } from "./streaming-caret";import { useStreamReveal } from "./use-stream-reveal";-export function AssistantReplyBody({- text,- streaming,- children,-}: {+export interface AssistantTextProps {/** 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;-}) {+}++export function AssistantText({ text, streaming, children }: AssistantTextProps) {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"+ className="ui-stream md-body anim-msg my-3 font-sans text-base leading-relaxed text-fg"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 the UI package's Md). */}+ {/* 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 prose.tsx). */}<Md text={revealed} streaming={live} />{live && <StreamingCaret />}{!live && children}diff --git a/packages/web/src/features/chat/stream-reveal.ts b/packages/ui/src/components/chat/assistant-text/stream-reveal.tssimilarity index 98%rename from packages/web/src/features/chat/stream-reveal.tsrename to packages/ui/src/components/chat/assistant-text/stream-reveal.tsindex 0d9e7423..8fa9f2f0 100644--- a/packages/web/src/features/chat/stream-reveal.ts+++ b/packages/ui/src/components/chat/assistant-text/stream-reveal.ts@@ -23,7 +23,7 @@* 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";+import type { StreamReveal } from "../../../tokens";/** The most the reveal may trail the stream: text that arrived this long ago is on screen. */export const REVEAL_MAX_LAG_MS = 1500;@@ -158,7 +158,7 @@ function isWordBoundary(text: string, p: number): boolean {* 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 {+export function revealCut(text: string, n: number, mode: StreamReveal): number {const length = text.length;let p = Math.max(0, Math.min(length, Math.floor(n)));if (mode === "fade") {@@ -192,7 +192,7 @@ export function revealCut(text: string, n: number, mode: StreamRevealMode): numb*/export function visibleLength(state: RevealState,- mode: StreamRevealMode,+ mode: StreamReveal,streaming: boolean,now: number,): number {diff --git a/packages/web/src/lib/stream-style.ts b/packages/ui/src/components/chat/assistant-text/stream-style.tssimilarity index 83%rename from packages/web/src/lib/stream-style.tsrename to packages/ui/src/components/chat/assistant-text/stream-style.tsindex 66dd1b8d..a231caf8 100644--- a/packages/web/src/lib/stream-style.ts+++ b/packages/ui/src/components/chat/assistant-text/stream-style.ts@@ -8,19 +8,20 @@* - `--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 the UI package's useChartStyle 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.+ * Read the way chart-style.ts reads the chart tokens: one MutationObserver on <html> drops the+ * cached record when anything there changes, a subscriber gets the same object while nothing it+ * reads changed, and nothing here ever writes. The observer watches every attribute rather than+ * naming the theme's — reading the tokens is what tells a real change from any other write, and+ * a component never asks which theme is active. The record also carries the root's+ * reduced-motion switch (`data-motion="reduced"` on <html>, the gallery's), the second of the+ * two signals the theme CSS honours beside the media query.*/import { useSyncExternalStore } from "react";--export type StreamRevealMode = "instant" | "fade" | "typewriter";+import type { StreamReveal } from "../../../tokens";export interface StreamStyle {/** How new text comes in. */- reveal: StreamRevealMode;+ reveal: StreamReveal;/** Characters per second of a paced reveal; 0 when the theme sets none. */rate: number;/** The root asks for reduced motion (`data-motion="reduced"`). */@@ -61,10 +62,7 @@ export function readStreamStyle(* 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 {+export function effectiveReveal(style: StreamStyle, prefersReducedMotion: boolean): StreamReveal {if (style.rate <= 0 || style.reducedMotion || prefersReducedMotion) return "instant";return style.reveal;}@@ -114,10 +112,7 @@ function subscribe(listener: () => void): () => void {cached = next;for (const l of listeners) l();});- observer.observe(document.documentElement, {- attributes: true,- attributeFilter: ["class", "data-theme", "data-accent", "data-motion", "style"],- });+ observer.observe(document.documentElement, { attributes: true });}return () => {listeners.delete(listener);diff --git a/packages/ui/src/components/chat/assistant-text/streaming-caret.tsx b/packages/ui/src/components/chat/assistant-text/streaming-caret.tsxnew file mode 100644index 00000000..59acce34--- /dev/null+++ b/packages/ui/src/components/chat/assistant-text/streaming-caret.tsx@@ -0,0 +1,20 @@+/**+ * The caret after a reply that is still coming in: a live signal (`ui-live`, `data-live="caret"`)+ * and the `caret` slot of the `ui-stream` host (AssistantText), 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 that blinks in steps. It is the one pulse the transcript's text carries, and it+ * holds still under reduced motion. Decorative: the reply's own text is what a screen reader+ * reads.+ */+export function StreamingCaret() {+ return (+ <span+ data-slot="caret"+ data-live="caret"+ aria-hidden="true"+ className="ui-live animate-pulse text-fg-subtle"+ >+ ▌+ </span>+ );+}diff --git a/packages/web/src/features/chat/use-stream-reveal.ts b/packages/ui/src/components/chat/assistant-text/use-stream-reveal.tssimilarity index 95%rename from packages/web/src/features/chat/use-stream-reveal.tsrename to packages/ui/src/components/chat/assistant-text/use-stream-reveal.tsindex b78bb03d..f5bde770 100644--- a/packages/web/src/features/chat/use-stream-reveal.ts+++ b/packages/ui/src/components/chat/assistant-text/use-stream-reveal.ts@@ -1,6 +1,6 @@/*** `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).+ * paced by the active theme's `--ui-stream-reveal` and `--ui-stream-rate` (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@@ -17,8 +17,8 @@* paced theme paces only what arrives next.*/import { useEffect, useRef, useState } from "react";-import { usePrefersReducedMotion } from "@prismshadow/penguin-ui";-import { effectiveReveal, useStreamStyle } from "../../lib/stream-style";+import { usePrefersReducedMotion } from "../../../motion/use-reduced-motion";+import { effectiveReveal, useStreamStyle } from "./stream-style";import {receiveText,revealFrameMs,diff --git a/packages/ui/src/components/chat/changes-card/changes-card.tsx b/packages/ui/src/components/chat/changes-card/changes-card.tsxnew file mode 100644index 00000000..7926e7e6--- /dev/null+++ b/packages/ui/src/components/chat/changes-card/changes-card.tsx@@ -0,0 +1,172 @@+/**+ * The card at the foot of a Task that lists the files it touched — the files its reply names,+ * the memories it wrote — one row per file (visual reference: Codex's "files changed" card).+ *+ * A header strip names the rows, counted, beside the card's glyph, with room for one text action+ * at its end (open the list the rows come from). Each row leads with a glyph, shows the path with+ * its directory faded and its name in bold, and may end with a mark for what happened to the file+ * (written, edited). A row that opens something is a button whose right end says in words what a+ * click does — a trailing chevron would read as expand — and a row with nothing to open is plain+ * text. Past `foldAt` rows the card folds, behind a row that unfolds it.+ *+ * The card is a transcript card, so it carries the `ui-frame` hook with its header as the `head`+ * slot and the rows as the `body`: a theme draws it the way it draws a tool call's card.+ */+import { useState } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import { Chevron } from "../../icons/chevron/chevron";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { namedHint } from "../../overlays/tooltip/tooltip";++/**+ * A path split in two: the directory faded, the file name in bold. The directory has+ * `shrink-[9999]` and gives way first, the name truncates only after it — both can truncate, so+ * the row never overflows its container on a narrow panel.+ */+export function PathLabel({ path }: { path: string }) {+ const slash = path.lastIndexOf("/");+ const dir = slash >= 0 ? path.slice(0, slash + 1) : "";+ const name = slash >= 0 ? path.slice(slash + 1) : path;+ return (+ <span className="flex min-w-0 items-baseline font-mono text-sm">+ {dir && <span className="min-w-0 shrink-[9999] truncate text-fg-subtle">{dir}</span>}+ <span className="min-w-0 truncate font-semibold text-fg">{name}</span>+ </span>+ );+}++export interface ChangesCardRow {+ /** Unique within the card. */+ id: string;+ /** The file's path, relative to where the reader knows it from. */+ path: string;+ /** The row's leading glyph, a 24×24 line path. */+ glyph: string;+ /**+ * What the leading glyph says when it says more than "a file" (a memory's scope): its tooltip+ * and its screen-reader text.+ */+ glyphLabel?: string;+ /** A mark at the row's end for what happened to the file, named by its label. */+ mark?: { glyph: string; label: string };+ /** A row that opens: its tooltip — its full path, or what a click on it does. */+ tooltip?: string;+ /** Opens the row's file; a row without it is plain text. */+ onOpen?: () => void;+}++export interface ChangesCardProps {+ /** The header's glyph, a 24×24 line path. */+ glyph: string;+ /** What the rows are, counted ("3 files"). */+ title: string;+ /** A text action at the header's end. */+ action?: { label: string; onClick: () => void };+ rows: readonly ChangesCardRow[];+ /** What a click on a row does, in the words the row shows at its end ("Preview"). */+ openHint: string;+ /** The fold row's words while rows are folded away, given how many. */+ showMore: (hidden: number) => string;+ /** The fold row's words once the card is unfolded. */+ showLess: string;+ /** How many rows show while the card is folded. */+ foldAt?: number;+}++/** A file row's box, and the hover fill of a row that opens. */+const ROW = "flex w-full items-center gap-2 px-3 py-2 text-left";+const ROW_HOVER = "transition-colors duration-150 hover:bg-surface-muted";++export function ChangesCard({+ glyph,+ title,+ action,+ rows,+ openHint,+ showMore,+ showLess,+ foldAt = 3,+}: ChangesCardProps) {+ const [expanded, setExpanded] = useState(false);+ if (rows.length === 0) return null;++ const visible = expanded ? rows : rows.slice(0, foldAt);+ const hidden = rows.length - visible.length;++ const rowInner = (row: ChangesCardRow) => (+ <>+ {row.glyphLabel !== undefined ? (+ <span data-tooltip={row.glyphLabel} className="shrink-0 text-fg-subtle">+ <GlyphIcon d={row.glyph} size={ICON_SIZE.rowLead} />+ <span className="sr-only">{row.glyphLabel}</span>+ </span>+ ) : (+ <GlyphIcon d={row.glyph} size={ICON_SIZE.rowLead} className="shrink-0 text-fg-subtle" />+ )}+ <PathLabel path={row.path} />+ <span className="min-w-0 flex-1" />+ {row.mark !== undefined && (+ <span {...namedHint(row.mark.label)} className="shrink-0 text-fg-subtle">+ <GlyphIcon d={row.mark.glyph} size={ICON_SIZE.inlineGlyph} />+ </span>+ )}+ </>+ );++ return (+ <div className="ui-frame anim-msg my-3 overflow-hidden rounded-xl border border-line bg-surface">+ <div+ data-slot="head"+ className="flex items-center gap-2 border-b border-line-muted bg-surface-muted px-3 py-2"+ >+ <GlyphIcon d={glyph} size={ICON_SIZE.rowLead} className="shrink-0 text-fg-subtle" />+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{title}</span>+ {action !== undefined && (+ <button+ type="button"+ onClick={action.onClick}+ className="shrink-0 cursor-pointer text-xs text-fg-subtle transition-colors duration-150 hover:text-fg-muted"+ >+ {action.label}+ </button>+ )}+ </div>+ <div data-slot="body" className="divide-y divide-line-muted">+ {visible.map((row) =>+ row.onOpen !== undefined ? (+ <button+ key={row.id}+ type="button"+ data-tooltip={row.tooltip}+ onClick={row.onOpen}+ className={`group ${ROW} ${ROW_HOVER} cursor-pointer`}+ >+ {rowInner(row)}+ {/* A span, not a nested button: the row itself is the button. */}+ <span+ aria-hidden+ className="shrink-0 text-xs text-fg-subtle transition-colors duration-150 group-hover:text-fg-muted"+ >+ {openHint}+ </span>+ </button>+ ) : (+ <div key={row.id} className={ROW}>+ {rowInner(row)}+ </div>+ ),+ )}+ {(hidden > 0 || expanded) && rows.length > foldAt && (+ <button+ type="button"+ onClick={() => setExpanded((v) => !v)}+ className={`flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-fg-muted ${ROW_HOVER}`}+ >+ {expanded ? showLess : showMore(hidden)}+ <Chevron open={expanded} className="text-fg-subtle" size={ICON_SIZE.chevronDense} />+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/components/chat/channel-bubble/channel-bubble.css b/packages/ui/src/components/chat/channel-bubble/channel-bubble.cssnew file mode 100644index 00000000..00edaa82--- /dev/null+++ b/packages/ui/src/components/chat/channel-bubble/channel-bubble.css@@ -0,0 +1,18 @@+/*+ * Inside a channel bubble (channel-bubble.tsx). The Markdown typography prints inline code and+ * table rules in the neutral tint (prose.css), and somebody else's bubble is that same tint, so+ * inside it those marks would disappear into their own colour. One step deeper puts them back,+ * on both bubble surfaces. Fenced blocks need nothing: `.md-body pre` carries a border and its+ * own fill, and the code inside it is transparent — the `:not(pre) >` shape keeps this off it.+ *+ * Plain CSS on tokens, unlayered, like prose.css: the rules it adjusts are unlayered, which a+ * utility in a cascade layer could never override. Each selector here out-weighs the one it+ * adjusts (`.md-body code`, `.md-body :where(th, td)`), so the order the two stylesheets are+ * emitted in does not matter.+ */+.channel-bubble :not(pre) > code {+ background-color: var(--ui-line-emphasis);+}+.channel-bubble :is(th, td) {+ border-color: var(--ui-line-emphasis);+}diff --git a/packages/ui/src/components/chat/channel-bubble/channel-bubble.tsx b/packages/ui/src/components/chat/channel-bubble/channel-bubble.tsxnew file mode 100644index 00000000..d8f24c40--- /dev/null+++ b/packages/ui/src/components/chat/channel-bubble/channel-bubble.tsx@@ -0,0 +1,178 @@+/**+ * A company channel's stream, drawn the way every chat client draws one: `ChannelRun` is one+ * sender's run of consecutive messages, and `ChannelBubble` is one message in it.+ *+ * Somebody else's run stands on the left: the avatar once, top-aligned so that it sits beside the+ * sender's name — with whatever the caller hangs after the name, such as a relay chip — and the+ * run's bubbles under both, in the column the name starts. Who is speaking is one mark, so the two+ * halves of it stay on one line: an avatar tied to the run's last bubble would drift a screenful+ * below its own name as soon as a message runs long. The reader's own run stands on the right in+ * its own tint, with no avatar and no name; a screen reader hears `ownLabel` instead, since a side+ * and a colour are not something every reader can read.+ *+ * Each bubble carries its own time at its end, inside it, bottom-aligned: on a one-line message it+ * lands beside the words, on a longer one it settles into the bottom-right corner, and it never+ * overlaps the body. A time that only appeared on hover would be one a touch reader never sees, and+ * one time per run would leave every later message in a long run unstamped. The body is Markdown in+ * the compact reading box; what the caller renders into it is its own (a channel keeps its+ * `@mentions` as chips), and `footer` sits under it — the chips for what the message refers to.+ *+ * The two surfaces. Somebody else's bubble is the neutral tone's tint. The reader's own is a wash+ * of the link ink over the canvas — the theme's identity blue in the default theme — rather than+ * a status tone, because which side of a conversation wrote a message is an identity, not a+ * judgement, and rather than the accent, which is grey in the default theme, where a wash of it+ * is the neutral bubble again. A message that names the reader is marked by its mention chip+ * alone: a tinted bubble would read as a state of the whole message.+ *+ * channel-bubble.css deepens the inline-code chip and the table rules inside a bubble, which the+ * Markdown typography prints in the neutral tint the bubble itself is drawn in.+ */+import type { ReactNode } from "react";+import { ICON_GAP } from "../../../icon-scale";+import { AgentAvatar } from "../../icons/avatars/agent-avatar";+import { avatarInitial } from "../../icons/avatars/avatar";+import "../../content/prose/prose.css";+import "./channel-bubble.css";++/** Who speaks a run. */+export interface ChannelSender {+ /** An employee (the agent's tinted tile) or a person (the initial on the foreground ink). */+ kind: "agent" | "user";+ /** The stable id: an agent's tile colour hashes it; the initial falls back to it on no name. */+ id: string;+ /** The display name: the run's header, and the avatar's initial. */+ name: string;+}++/** The avatar that leads somebody else's run, in pixels: a tile, one rung above a line glyph. */+const RUN_AVATAR_PX = 28;++/** The run's leading tile. Decorative: the name beside it is what names the sender. */+function SenderAvatar({ sender }: { sender: ChannelSender }) {+ if (sender.kind === "agent") {+ return (+ <AgentAvatar+ id={sender.id}+ name={sender.name}+ size={RUN_AVATAR_PX}+ className="shrink-0 rounded-md"+ />+ );+ }+ return (+ <span+ aria-hidden+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-fg text-xs font-bold text-canvas"+ >+ {avatarInitial(sender.name, sender.id)}+ </span>+ );+}++export interface ChannelRunProps {+ /** Who is speaking. */+ sender: ChannelSender;+ /** The reader's own run: on the right, in its own tint, with neither an avatar nor a name. */+ own?: boolean;+ /**+ * What a screen reader hears in place of the name on the reader's own run ("You"); the sender's+ * name when omitted.+ */+ ownLabel?: string;+ /** After the name on somebody else's run: a relay chip, with its tooltip. */+ meta?: ReactNode;+ /** The run's bubbles, in order. */+ children: ReactNode;+}++/** One sender's run of consecutive messages. */+export function ChannelRun({ sender, own = false, ownLabel, meta, children }: ChannelRunProps) {+ return (+ <div className={`flex items-start ${ICON_GAP.card} py-1.5`}>+ {!own && <SenderAvatar sender={sender} />}+ <div className={`flex min-w-0 flex-1 flex-col gap-1 ${own ? "items-end" : "items-start"}`}>+ {own ? (+ <span className="sr-only">{ownLabel ?? sender.name}</span>+ ) : (+ <div className={`flex max-w-full flex-wrap items-baseline ${ICON_GAP.row} px-1 text-xs`}>+ <span className="truncate font-semibold text-fg-muted">{sender.name}</span>+ {meta}+ </div>+ )}+ {children}+ </div>+ </div>+ );+}++/** The two bubble surfaces; see the module comment for why the reader's own is the link's wash. */+const SURFACE = {+ other: "bg-fill-neutral text-fg",+ own: "bg-[color-mix(in_srgb,var(--ui-fg-link)_12%,var(--ui-canvas))] text-fg",+} as const;++/**+ * A bubble's corners: 2xl all round, except on the last bubble of a run, where the corner nearest+ * the run's tail is squared — bottom-left on somebody else's side of the stream, bottom-right on+ * the reader's own. Every corner is named rather than layering a per-corner utility over the+ * all-corner one, so the result does not depend on which of the two the stylesheet emits last.+ */+function corners(own: boolean, last: boolean): string {+ if (!last) return "rounded-2xl";+ return own+ ? "rounded-bl-2xl rounded-br-sm rounded-tl-2xl rounded-tr-2xl"+ : "rounded-bl-sm rounded-br-2xl rounded-tl-2xl rounded-tr-2xl";+}++export interface ChannelBubbleProps {+ /** The reader's own message: its side's tint and its tail corner. */+ own?: boolean;+ /** The last bubble of its run: the corner nearest the run's tail is squared. */+ last?: boolean;+ /** The clock time printed at the bubble's end ("14:05"). */+ time: string;+ /** What a screen reader hears for the time, in place of the printed clock ("Sent at …"). */+ timeLabel: string;+ /** The full date and time, the printed clock's tooltip. */+ timeTooltip?: string;+ /** Under the body, inside the bubble: the chips for what the message refers to. */+ footer?: ReactNode;+ /** The element id, so a reference elsewhere in the stream can scroll to this message. */+ id?: string;+ /** The message body, rendered into the compact Markdown reading box. */+ children: ReactNode;+}++/** One message of a run. */+export function ChannelBubble({+ own = false,+ last = false,+ time,+ timeLabel,+ timeTooltip,+ footer,+ id,+ children,+}: ChannelBubbleProps) {+ return (+ <div+ id={id}+ data-side={own ? "own" : "other"}+ className={`channel-bubble max-w-[75%] px-3 py-1.5 text-sm leading-relaxed ${corners(own, last)} ${own ? SURFACE.own : SURFACE.other}`}+ >+ <div className={`flex items-end ${ICON_GAP.menu}`}>+ <div className="min-w-0 flex-1">+ <div className="md-body md-compact">{children}</div>+ {footer}+ </div>+ <span+ data-tooltip={timeTooltip}+ className="shrink-0 text-xs tabular-nums text-tone-neutral-fg"+ >+ <span className="sr-only">{timeLabel}</span>+ <span aria-hidden>{time}</span>+ </span>+ </div>+ </div>+ );+}diff --git a/packages/ui/src/components/chat/composer/composer.tsx b/packages/ui/src/components/chat/composer/composer.tsxnew file mode 100644index 00000000..f4d904a7--- /dev/null+++ b/packages/ui/src/components/chat/composer/composer.tsx@@ -0,0 +1,230 @@+/**+ * The composer's pieces: the card a message is written in, the chips staged above its text, the+ * one action button, and the slash list with the pickers a slash command opens. The toolbar's+ * triggers are `ToolbarTrigger` (toolbar-trigger.tsx) and the pickers behind them `MenuSelect`.+ *+ * - `ComposerCard` is one bordered card: the chip row, then the text body — a textarea that grows+ * with what is typed, up to about six lines, then scrolls — then a single toolbar row that never+ * shares a line with the text. The toolbar's left group (a tight cluster of icon triggers, then a+ * muted hint) is the part allowed to give way: it scrolls sideways on a narrow card, so the right+ * group (status, model, the action button) always stays on screen. The card is a size container,+ * so the toolbar collapses by the card's own width rather than the viewport's; it takes the+ * theme's input focus ring while anything inside it has focus, and carries the glass hook of the+ * layer floating over the conversation.+ * - `ChipRow` is the row of chips above the text body (`TagInput` in the composer's place).+ * - `SendButton` is the action button: the accent square with the send arrow, or the stop square+ * while a run can be stopped.+ * - `SlashMenu` is the list a `/` opens above the card: commands in the mono face, what each does+ * muted after it, the keyboard's row highlighted and kept in view.+ * - `SlashPicker` is the titled panel a switch command opens in the same place, holding the+ * caller's picker.+ *+ * The composer's behaviour — sending, slash matching, paste and drop, drafts — is the caller's;+ * these draw it.+ */+import type { ReactNode, Ref, TextareaHTMLAttributes } from "react";+import { menuPanelClass } from "../../overlays/menu-panel/menu-panel";+import { TagInput } from "../../forms/tag-input/tag-input";+import { MenuTitle } from "../menu-select/menu-select";++/** The text body's attributes: everything but its look and its starting height. */+export type ComposerTextareaProps = Omit<+ TextareaHTMLAttributes<HTMLTextAreaElement>,+ "className" | "rows"+> & { ref?: Ref<HTMLTextAreaElement> };++export function ComposerCard({+ chips,+ textarea,+ tools,+ hint,+ actions,+}: {+ /** The chip row above the text body (`ChipRow`); nothing is drawn when absent. */+ chips?: ReactNode;+ /** The text body: a controlled textarea, two lines high to begin with. */+ textarea: ComposerTextareaProps;+ /** The icon triggers leading the toolbar, set as one tight cluster. */+ tools?: ReactNode;+ /** A muted line after them (how to reach the slash commands), shown once the card is wide. */+ hint?: string;+ /** The right group: status, model and the action button; it never shrinks. */+ actions?: ReactNode;+}) {+ const { ref, ...text } = textarea;+ return (+ <div className="ui-glass @container rounded-lg border border-line-emphasis bg-surface px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-fg-muted focus-within:ring-2 focus-within:ring-fg-subtle/30">+ {chips}+ {/* The body rung rather than the form controls' small one: this is a typing surface for+ prose the user composes and re-reads, and the toolbar under it is the small rung. */}+ <textarea+ ref={ref}+ rows={2}+ {...text}+ className="block max-h-44 min-h-[60px] w-full resize-none bg-transparent px-1 py-0.5 font-sans text-base leading-6 placeholder:text-fg-subtle focus:outline-none disabled:cursor-not-allowed disabled:opacity-60"+ />+ <div className="mt-1 flex items-center justify-between gap-2 text-xs">+ <div className="no-scrollbar flex min-w-0 flex-1 items-center gap-2 overflow-x-auto">+ <div className="flex shrink-0 items-center gap-px">{tools}</div>+ {hint !== undefined && hint !== "" && (+ <span+ data-tooltip={hint}+ data-tooltip-content="text"+ className="hidden min-w-0 truncate text-fg-subtle @lg:block"+ >+ {hint}+ </span>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-2">{actions}</div>+ </div>+ </div>+ );+}++/** The chip row above the composer's text body. */+export function ChipRow(props: Omit<Parameters<typeof TagInput>[0], "variant" | "className">) {+ return <TagInput {...props} className="mb-1" />;+}++/**+ * The composer's one action button. `send` is the accent square with the up arrow, greyed while+ * there is nothing to send; `stop` is a neutral square holding the stop mark in the danger ink,+ * never disabled — a run can always be stopped.+ */+export function SendButton({+ action,+ label,+ disabled = false,+ onClick,+}: {+ action: "send" | "stop";+ /** The accessible name and tooltip: what pressing it does now (send, steer, queue, stop). */+ label: string;+ disabled?: boolean;+ onClick: () => void;+}) {+ const stop = action === "stop";+ return (+ <button+ type="button"+ data-tooltip={label}+ aria-label={label}+ disabled={stop ? false : disabled}+ onClick={onClick}+ className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${+ stop+ ? "bg-fill-neutral text-tone-danger-fg hover:bg-tone-danger-bg"+ : "bg-accent text-accent-fg hover:bg-accent-hover disabled:cursor-not-allowed disabled:bg-line disabled:text-fg-subtle"+ }`}+ >+ {stop ? (+ <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden className="block">+ <rect x="2" y="2" width="10" height="10" rx="2" fill="currentColor" />+ </svg>+ ) : (+ <svg+ width="17"+ height="17"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ className="block"+ >+ <path d="M12 19V5M5 12l7-7 7 7" />+ </svg>+ )}+ </button>+ );+}++/** One command in the slash list. */+export interface SlashMenuItem {+ /** The command as typed, `/compact`. */+ command: string;+ /** What it does; a long one truncates, whole in its tooltip. */+ description: string;+}++/**+ * The slash list, opening upward from the composer's top edge. Its height is the caller's+ * measure of the room above (`maxHeight`), and the list scrolls inside it, so a long list never+ * runs off the top; the highlighted row keeps itself in view as the keyboard walks it.+ */+export function SlashMenu({+ items,+ active,+ onActiveChange,+ onRun,+ maxHeight,+}: {+ items: readonly SlashMenuItem[];+ /** The highlighted row's index. */+ active: number;+ /** The pointer moved onto a row. */+ onActiveChange: (index: number) => void;+ /** A row was pressed. */+ onRun: (index: number) => void;+ maxHeight?: number;+}) {+ return (+ <div+ style={{ maxHeight }}+ className={`ui-glass ${menuPanelClass} absolute bottom-full left-0 z-40 mb-1.5 w-80 max-w-[calc(100vw-2rem)] overscroll-contain`}+ >+ {items.map((item, i) => (+ <button+ key={item.command}+ type="button"+ ref={i === active ? (el) => el?.scrollIntoView({ block: "nearest" }) : undefined}+ onMouseEnter={() => onActiveChange(i)}+ onClick={() => onRun(i)}+ className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${+ i === active ? "bg-line-muted" : ""+ }`}+ >+ <span className="shrink-0 font-mono text-fg">{item.command}</span>+ <span+ data-tooltip={item.description}+ data-tooltip-content="text"+ className="min-w-0 flex-1 truncate text-xs text-fg-muted"+ >+ {item.description}+ </span>+ </button>+ ))}+ </div>+ );+}++/**+ * The panel a switch command opens where the slash list was: a title bar naming the switch, then+ * the caller's picker. It has no trigger of its own, so dismissing it (a click outside, Escape) is+ * the caller's; `ref` is the panel, for that outside test.+ */+export function SlashPicker({+ title,+ maxHeight,+ ref,+ children,+}: {+ title: ReactNode;+ maxHeight?: number;+ ref?: Ref<HTMLDivElement>;+ children: ReactNode;+}) {+ return (+ <div+ ref={ref}+ style={{ maxHeight }}+ className="anim-pop absolute bottom-full left-0 z-40 mb-1.5 flex w-80 max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-md border border-line bg-overlay py-1 shadow-lg"+ >+ <MenuTitle>{title}</MenuTitle>+ {children}+ </div>+ );+}diff --git a/packages/ui/src/components/chat/composer/toolbar-trigger.tsx b/packages/ui/src/components/chat/composer/toolbar-trigger.tsxnew file mode 100644index 00000000..80d3098a--- /dev/null+++ b/packages/ui/src/components/chat/composer/toolbar-trigger.tsx@@ -0,0 +1,98 @@+/**+ * A toolbar trigger: the compact button a composer's toolbar opens its pickers from. Two shapes,+ * one look — muted ink that darkens on hover over a soft fill, nothing that moves:+ *+ * - the icon square (no `label`): one glyph at the icon-button rung, with an optional count on its+ * corner (the skills picked for the message);+ * - the pill (`label`): a leading mark, the words and, with `caret`, the dense caret. The words+ * hide while the card holding the toolbar is narrower than its `@md` width, leaving the mark,+ * so a crowded toolbar keeps every control and the tooltip still says what the pill holds.+ *+ * The accessible name is the caller's, and the tooltip unless a longer one is given; the words on+ * a pill are the current value, not the control's name.+ */+import type { ReactNode } from "react";+import { ICON_SIZE } from "../../../icon-scale";+import { Count } from "../../feedback/badge/badge";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { ChevronDown } from "../../icons/marks/marks";++export interface ToolbarTriggerProps {+ /** The mark: a registry path drawn at the shape's rung, or a node the caller sized (a logo). */+ glyph: string | ReactNode;+ /** The pill's words — the current value. Without them the trigger is the icon square. */+ label?: ReactNode;+ /** The pill's trailing caret. */+ caret?: boolean;+ /** A count on the square's corner; nothing is drawn at 0. */+ badge?: number;+ /** The accessible name. */+ ariaLabel: string;+ /** The tooltip, when it says more than the name (the name with its value). */+ tooltip?: string;+ disabled?: boolean;+ /** How far a pill may grow before its words truncate. */+ width?: "sm" | "md";+ /** Whether the picker it opens is open. */+ expanded?: boolean;+ /** What it opens, when that is not a menu the caller wraps it in (a dialog). */+ ariaHaspopup?: "dialog" | "listbox" | "menu";+ onClick?: () => void;+ /** State a caller or a test reads back off the button (`data-level`). */+ [data: `data-${string}`]: string | number | boolean | undefined;+}++/** The ink, fill and motion both shapes share. */+const LOOK =+ "rounded-md text-fg-muted transition-colors duration-150 hover:bg-surface-muted hover:text-fg disabled:cursor-not-allowed disabled:opacity-50";++const PILL_WIDTH = { sm: "max-w-36", md: "max-w-44" } as const;++export function ToolbarTrigger({+ glyph,+ label,+ caret = false,+ badge = 0,+ ariaLabel,+ tooltip,+ disabled = false,+ width = "sm",+ expanded,+ ariaHaspopup,+ onClick,+ ...data+}: ToolbarTriggerProps) {+ const pill = label !== undefined && label !== null;+ const mark =+ typeof glyph === "string" ? (+ <GlyphIcon d={glyph} {...(pill ? {} : { size: ICON_SIZE.iconButton })} className="shrink-0" />+ ) : (+ glyph+ );+ return (+ <button+ {...data}+ type="button"+ aria-label={ariaLabel}+ data-tooltip={tooltip ?? ariaLabel}+ {...(expanded !== undefined ? { "aria-expanded": expanded } : {})}+ {...(ariaHaspopup !== undefined ? { "aria-haspopup": ariaHaspopup } : {})}+ disabled={disabled}+ onClick={onClick}+ className={+ pill+ ? `flex h-8 ${PILL_WIDTH[width]} shrink-0 items-center gap-1.5 px-2 text-xs ${LOOK}`+ : `relative flex h-8 w-8 shrink-0 items-center justify-center ${LOOK}`+ }+ >+ {mark}+ {pill && <span className="hidden min-w-0 truncate @md:block">{label}</span>}+ {pill && caret && <ChevronDown size={ICON_SIZE.caretDense} />}+ {!pill && badge > 0 && (+ <span className="absolute -right-1 -top-0.5">+ <Count n={badge} />+ </span>+ )}+ </button>+ );+}diff --git a/packages/ui/src/components/chat/context-ring/context-ring.tsx b/packages/ui/src/components/chat/context-ring/context-ring.tsxnew file mode 100644index 00000000..8aabc8ff--- /dev/null+++ b/packages/ui/src/components/chat/context-ring/context-ring.tsx@@ -0,0 +1,101 @@+/**+ * The composer's context ring: how full the model's context is, as one arc in the toolbar's own+ * square. It is a single-colour reading of the whole — no parts — that stays in the muted ink+ * until 80 %, turns to the attention tone past it and to danger past 95 %, so the warning is the+ * ring's colour and never a number beside it.+ *+ * `unknown` (a compaction has just finished and nothing has been measured since) draws the empty+ * track in the muted ink: nothing measured is not the same as measured empty, so it never draws a+ * full-looking zero.+ *+ * The ring draws no numbers, so its accessible name — the caller's `label` — carries them, and is+ * its tooltip too. Given `onClick` the ring is the button that opens whatever the caller hangs off+ * it (the app's context breakdown), with `ref` on that button for the caller's panel to anchor to;+ * its hover paints the square and never the ring, whose colour is the reading. Without it the ring+ * is a named image.+ */+import type { Ref } from "react";+import type { ToneName } from "../../../tokens";+import { Ring } from "../../charts/ring/ring";++/** The share past which the ring turns to the attention tone. */+export const CONTEXT_RING_ATTENTION = 0.8;+/** The share past which it turns to danger. */+export const CONTEXT_RING_DANGER = 0.95;++/** The ring's warning tones. */+export type ContextRingTone = Extract<ToneName, "attention" | "danger">;++/** The ring's tone for a share of the context (0–1), or null for the calm, muted ring. */+export function contextRingTone(ratio: number, unknown = false): ContextRingTone | null {+ if (unknown || !(ratio > CONTEXT_RING_ATTENTION)) return null;+ return ratio > CONTEXT_RING_DANGER ? "danger" : "attention";+}++const INK: Record<ContextRingTone, string> = {+ attention: "text-tone-attention-fg",+ danger: "text-tone-danger-fg",+};++export function ContextRing({+ ratio,+ unknown = false,+ label,+ onClick,+ expanded,+ controls,+ ref,+}: {+ /** How full the context is, 0–1 (clamped). */+ ratio: number;+ /** Nothing has been measured since the context was last replaced: an empty track. */+ unknown?: boolean;+ /** The accessible name and tooltip: the share, and the figures it was computed from. */+ label: string;+ /** Makes the ring a button. */+ onClick?: () => void;+ /** With `onClick`: whether what it opens is open. */+ expanded?: boolean;+ /** With `onClick`: the id of what it opens. */+ controls?: string;+ /** With `onClick`: the button element, for a panel anchored to it. */+ ref?: Ref<HTMLButtonElement>;+}) {+ const share = unknown || !Number.isFinite(ratio) ? 0 : Math.min(1, Math.max(0, ratio));+ const tone = contextRingTone(share, unknown);+ const ink = tone === null ? "text-fg-subtle" : INK[tone];+ // A 12px ring under a 2px stroke in the square's ink: the track is that ink faded, so the+ // warning ladder above recolours the whole ring. Decorative — the square carries the name.+ const ring = (+ <Ring+ segments={share > 0 ? [{ value: share }] : []}+ max={1}+ size={12}+ width={2}+ trackOpacity={0.25}+ />+ );+ // The toolbar's icon square, the size of the controls beside it.+ const square = `flex h-8 w-8 shrink-0 items-center justify-center ${ink}`;+ if (onClick === undefined) {+ return (+ <span data-tooltip={label} aria-label={label} role="img" className={square}>+ {ring}+ </span>+ );+ }+ return (+ <button+ ref={ref}+ type="button"+ data-tooltip={label}+ aria-label={label}+ {...(expanded !== undefined ? { "aria-expanded": expanded } : {})}+ {...(controls !== undefined ? { "aria-controls": controls } : {})}+ onClick={onClick}+ className={`${square} rounded-md transition-colors duration-150 hover:bg-surface-muted`}+ >+ {ring}+ </button>+ );+}diff --git a/packages/ui/src/components/chat/menu-select/menu-select.tsx b/packages/ui/src/components/chat/menu-select/menu-select.tsxnew file mode 100644index 00000000..75cfb7ef--- /dev/null+++ b/packages/ui/src/components/chat/menu-select/menu-select.tsx@@ -0,0 +1,171 @@+/**+ * The toolbar select: a `ToolbarTrigger` that opens a menu of choices in the shared panel — the+ * pickers along a composer's toolbar (a thinking level, the input add-ons, the skills a message+ * is sent with) and any row of compact controls like them.+ *+ * The panel may open with a title bar naming the control (`title`), since its rows are only the+ * choices' own short names. The rows are the Menu family's at the small rung: a leading glyph,+ * the label with an optional muted `detail` running on after it on the same line (and giving way+ * first), and the check on the chosen one. Below them, either a muted footnote (`note`) or a row+ * of settings under a rule (`footer`). A picker whose body is not a list of choices — a search+ * over a long list — passes it as `children` instead of `options`.+ *+ * `value` is the chosen choice, or the chosen ones: with `multiple` every row is a toggle, marked+ * pressed while it is on. A pick closes the menu unless `keepOpen`; the trigger toggles it, and+ * the Dropdown underneath closes it on Escape and on a click outside. The panel is portaled, so a+ * toolbar that scrolls sideways cannot clip it, and it opens `up` from a composer docked at the+ * page's foot, `down` from one with the room below.+ *+ * The rows are plain buttons, as in every picker the app opens from a toolbar: the choices keep+ * the names they are found by.+ */+import { useState } from "react";+import type { ReactNode } from "react";+import { Dropdown } from "../../overlays/dropdown/dropdown";+import { MenuItem } from "../../overlays/menu/menu";+import { ToolbarTrigger } from "../composer/toolbar-trigger";+import type { ToolbarTriggerProps } from "../composer/toolbar-trigger";++export interface MenuSelectOption<V extends string> {+ value: V;+ label: ReactNode;+ /** A registry path (drawn muted and decorative) or a node the caller sized. */+ glyph?: string | ReactNode;+ /** Muted words after the label on the same line: what the choice does. */+ detail?: ReactNode;+ /** Listed, greyed out and inert (the menu still opens). */+ disabled?: boolean;+ /** A muted note at the row's end. */+ trailing?: ReactNode;+}++/** A menu's title bar: the control's name above rows that carry only the choices' own names. */+export function MenuTitle({ children }: { children: ReactNode }) {+ return (+ <div className="border-b border-line-muted px-3 pb-1.5 pt-0.5 text-xs font-semibold text-fg-muted">+ {children}+ </div>+ );+}++/** Whether an optional slot has anything to draw. */+const shown = (node: ReactNode): boolean => node !== undefined && node !== null && node !== "";++/** What `MenuSelect` opens: the title, the rows (or the caller's body), a note or a footer. */+export interface MenuSelectBodyProps<V extends string> {+ /** The title bar's text. */+ title?: ReactNode;+ options?: readonly MenuSelectOption<V>[];+ /** The chosen choice, or the chosen ones; null while there is nothing to show yet. */+ value?: V | readonly V[] | null;+ /** A row was picked. */+ onPick?: (value: V) => void;+ /** Every row is a toggle (`aria-pressed`), so several may be on at once. */+ multiple?: boolean;+ /** A muted footnote under the rows. */+ note?: ReactNode;+ /** A row of settings under a rule, after the rows. */+ footer?: ReactNode;+ /** The panel's body in place of `options` (a search over a long list). */+ children?: ReactNode;+}++/** The open panel's contents, on their own: what `MenuSelect` renders inside its Dropdown. */+export function MenuSelectBody<V extends string>({+ title,+ options,+ value,+ onPick,+ multiple = false,+ note,+ footer,+ children,+}: MenuSelectBodyProps<V>) {+ const chosen = (v: V): boolean => (Array.isArray(value) ? value.includes(v) : value === v);+ return (+ <>+ {shown(title) && <MenuTitle>{title}</MenuTitle>}+ {children ??+ options?.map((option) => (+ <MenuItem+ key={option.value}+ density="sm"+ {...(multiple ? { "aria-pressed": chosen(option.value) } : {})}+ disabled={option.disabled ?? false}+ checked={chosen(option.value)}+ glyph={option.glyph}+ label={+ shown(option.detail) ? (+ <>+ {option.label} <span className="text-fg-subtle">{option.detail}</span>+ </>+ ) : (+ option.label+ )+ }+ trailing={option.trailing}+ onSelect={() => onPick?.(option.value)}+ />+ ))}+ {shown(note) && (+ <div className="max-w-56 border-t border-line-muted px-3 pb-1 pt-1.5 text-xs leading-snug text-fg-subtle">+ {note}+ </div>+ )}+ {shown(footer) && <div className="mt-1 border-t border-line-muted pt-1">{footer}</div>}+ </>+ );+}++export function MenuSelect<V extends string>({+ trigger,+ title,+ options,+ value,+ onChange,+ multiple = false,+ keepOpen = false,+ note,+ footer,+ children,+ direction = "up",+ align = "left",+ menuClass = "w-max min-w-36",+}: Omit<MenuSelectBodyProps<V>, "onPick"> & {+ /** The button: its mark, words, name and state (the open state is the menu's own). */+ trigger: Omit<ToolbarTriggerProps, "expanded" | "onClick">;+ onChange?: (value: V) => void;+ /** A pick leaves the menu open (a checklist being filled in). */+ keepOpen?: boolean;+ direction?: "up" | "down";+ /** Which of the panel's edges lines up with the trigger's. */+ align?: "left" | "right";+ /** The panel's width classes; placement is measured from the trigger. */+ menuClass?: string;+}) {+ const [open, setOpen] = useState(false);+ return (+ <Dropdown+ open={open}+ setOpen={setOpen}+ menuClass={menuClass}+ portal={{ direction, align }}+ button={<ToolbarTrigger {...trigger} expanded={open} onClick={() => setOpen(!open)} />}+ >+ <MenuSelectBody<V>+ title={title}+ options={options}+ value={value}+ multiple={multiple}+ note={note}+ footer={footer}+ onPick={(picked) => {+ if (!keepOpen) setOpen(false);+ onChange?.(picked);+ }}+ >+ {children}+ </MenuSelectBody>+ </Dropdown>+ );+}diff --git a/packages/ui/src/components/chat/message-bubble/message-bubble.tsx b/packages/ui/src/components/chat/message-bubble/message-bubble.tsxnew file mode 100644index 00000000..ccb79415--- /dev/null+++ b/packages/ui/src/components/chat/message-bubble/message-bubble.tsx@@ -0,0 +1,171 @@+/**+ * The transcript's messages that are not the agent's reply (that one is `AssistantText`): what+ * the person sent, and the one-line notices the run leaves between turns.+ *+ * - `MessageRow` is a message the person sent: a column on the right, with its footer under it.+ * A prompt that starts a Task takes a turn's room; a steer delivered inside a running Task is+ * tighter, since it starts nothing.+ * - `MessageBubble` is the chrome, in four variants: `user`, the prompt's text in a tinted+ * bubble; `image`, an image sent with it, in the same bubble with a thin inset; `steering`,+ * a lighter bordered chip for a steer, marked by the person glyph and a short label, with the+ * images and files it carried inside it; and `notice`, a quiet mono line — an abort, a failed+ * request, a reconnect with its controls — in the muted ink or, for a reconnect, the attention+ * ink.+ * - `MessageMeta` is the footer: the time and a copy button. From `sm` up it is invisible but+ * takes its room (`opacity-0`, not `hidden`), and surfaces while the pointer is over the row or+ * focus is inside it — hover alone would leave a keyboard user a copy button that is focusable+ * but never shown, and `hidden` would shove everything below down each time it appeared. Below+ * `sm` it is always shown: touch has no hover.+ * - `MessageImage` is an image in a bubble or a chip: it opens large on a click.+ *+ * Wrapping: a message is `wrap-anywhere` — long unbroken strings (attachment paths, long URLs)+ * wrap inside the bubble on a narrow screen instead of overflowing, and unlike `break-words` it+ * also shrinks the min-content width, so a pathological token cannot stretch the bubble itself.+ * Ordinary words still break only when a token cannot fit on a line.+ */+import type { ReactNode } from "react";+import { CopyButton } from "../../actions/copy-button/copy-button";+import { GlyphIcon } from "../../icons/glyph-icon/glyph-icon";+import { ICONS } from "../../icons/icons";+import { ZoomableImage } from "../../overlays/lightbox/lightbox";++/** How far a bubble may reach across the transcript. */+const WIDTH = "max-w-[88%] md:max-w-[75%]";++/** A message the person sent: right-aligned, with its footer under it. */+export function MessageRow({+ spacing = "turn",+ children,+}: {+ /** `turn` for a prompt; `steer` for a steer inside a running Task. */+ spacing?: "turn" | "steer";+ children?: ReactNode;+}) {+ return (+ <div+ className={`anim-msg group ${spacing === "turn" ? "my-4" : "my-2"} flex flex-col items-end`}+ >+ {children}+ </div>+ );+}++export type MessageBubbleVariant = "user" | "image" | "steering" | "notice";++export interface MessageBubbleProps {+ variant: MessageBubbleVariant;+ /** The message: its text (`user`, `steering`, `notice`) or its image (`image`). */+ children?: ReactNode;+ /** `steering`: the word that marks the chip as a steer, set before its text. */+ label?: string;+ /** `steering`: the images it carried, laid out in a wrapping row under the text. */+ media?: ReactNode;+ /** `steering`: the files it carried (a files notice), under the images. */+ attachments?: ReactNode;+ /** `notice`: `neutral` for an abort or a failed request, `attention` for a reconnect. */+ tone?: "neutral" | "attention";+ /** `notice`: controls at the end of the line (retry now, give up). */+ actions?: ReactNode;+}++export function MessageBubble({+ variant,+ children,+ label,+ media,+ attachments,+ tone = "neutral",+ actions,+}: MessageBubbleProps) {+ switch (variant) {+ case "user":+ return (+ <div className={`${WIDTH} rounded-lg bg-fill-neutral px-4 py-2.5`}>+ <p className="wrap-anywhere font-sans whitespace-pre-wrap text-base leading-relaxed text-fg">+ {children}+ </p>+ </div>+ );+ case "image":+ return <div className={`${WIDTH} rounded-lg bg-fill-neutral p-1.5`}>{children}</div>;+ case "steering":+ return (+ <div+ className={`flex ${WIDTH} flex-col gap-1.5 rounded-md border border-line-emphasis bg-fill-neutral px-3 py-1.5`}+ >+ <div className="flex items-start gap-1.5">+ <GlyphIcon d={ICONS.user} className="mt-1 shrink-0 text-fg-subtle" />+ <p className="wrap-anywhere font-sans whitespace-pre-wrap text-sm leading-relaxed text-fg">+ {label !== undefined && (+ <span className="mr-1.5 text-xs font-semibold text-fg-muted">{label}</span>+ )}+ {children}+ </p>+ </div>+ {media !== undefined && <div className="flex flex-wrap justify-end gap-1.5">{media}</div>}+ {attachments !== undefined && <div className="flex justify-end">{attachments}</div>}+ </div>+ );+ case "notice":+ return (+ <p+ className={`anim-msg my-1 font-mono text-xs ${+ tone === "attention" ? "text-tone-attention-fg" : "text-fg-muted"+ } ${actions !== undefined ? "flex flex-wrap items-center gap-x-2 gap-y-1" : ""}`}+ >+ {children}+ {actions !== undefined && (+ <span className="flex shrink-0 items-center gap-1.5">{actions}</span>+ )}+ </p>+ );+ }+}++/** An image the person sent, in its bubble (`bubble`) or among a steer's (`chip`, smaller). */+export function MessageImage({+ src,+ alt,+ size = "bubble",+}: {+ src: string;+ alt: string;+ size?: "bubble" | "chip";+}) {+ return (+ <ZoomableImage+ src={src}+ alt={alt}+ className={+ size === "bubble"+ ? "max-h-48 max-w-full rounded-control"+ : "max-h-28 max-w-full rounded-control"+ }+ />+ );+}++/** A message's footer: its time, and a copy button when there is text to copy. */+export function MessageMeta({+ time,+ copy,+ align = "end",+}: {+ /** When the message was sent, formatted by the caller. */+ time?: string;+ /** What the copy button copies, and its name. An image has nothing to copy, so no button. */+ copy?: { text: string; label: string };+ /** Which edge the footer keeps to: the message's side. */+ align?: "start" | "end";+}) {+ return (+ <div+ className={`flex h-5 items-center gap-2 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:opacity-0 ${+ align === "end" ? "justify-end" : "justify-start"+ }`}+ >+ {time !== undefined && <span className="text-xs text-fg-subtle">{time}</span>}+ {copy !== undefined && <CopyButton text={copy.text} label={copy.label} />}+ </div>+ );+}diff --git a/packages/ui/src/components/chat/model-select/model-select.tsx b/packages/ui/src/components/chat/model-select/model-select.tsxnew file mode 100644index 00000000..934dc4ba--- /dev/null+++ b/packages/ui/src/components/chat/model-select/model-select.tsx@@ -0,0 +1,78 @@+/**+ * The model picker's trigger: the control a model is chosen from, showing the chosen model's+ * provider logo and name. What it opens is the caller's — a dialog (the app's model picker, with+ * its search and provider rail) — and the trigger only reports whether that is open. Two shapes:+ *+ * - `pill`: the composer's toolbar pill (`ToolbarTrigger`: logo, name, caret; the name hides on a+ * narrow card, leaving the logo, and the tooltip still names the model);+ * - `form`: a dialog's form field (the shared `FormPickerTrigger`, full width, Input-styled).+ *+ * Every word is the caller's: the name it shows, its accessible name and its tooltip.+ */+import { FormPickerTrigger } from "../../forms/select/form-picker";+import { ProviderLogo } from "../../icons/logos/provider-logo";+import { ToolbarTrigger } from "../composer/toolbar-trigger";++export interface ModelSelectProps {+ /** The trigger's words: the chosen model's name, or what stands in for none. */+ label: string;+ /** The trigger's logo; null draws none (no provider is being named). */+ provider: string | null;+ /** The form field's words read as a placeholder. */+ muted?: boolean;+ /** The trigger's accessible name. */+ ariaLabel: string;+ /** The trigger's tooltip: the name with the model in it. */+ tooltip: string;+ disabled?: boolean;+ /** The composer's toolbar pill, or a dialog's form field. */+ variant?: "pill" | "form";+ /** Whether the dialog it opens is open. */+ expanded: boolean;+ onClick: () => void;+}++export function ModelSelect({+ label,+ provider,+ muted = false,+ ariaLabel,+ tooltip,+ disabled = false,+ variant = "pill",+ expanded,+ onClick,+}: ModelSelectProps) {+ const logo =+ provider === null ? null : <ProviderLogo provider={provider} className="h-4 w-4 shrink-0" />;+ if (variant === "form") {+ return (+ <FormPickerTrigger+ size="sm"+ expanded={expanded}+ onClick={onClick}+ leading={logo}+ label={label}+ muted={muted}+ title={tooltip}+ ariaLabel={ariaLabel}+ ariaHaspopup="dialog"+ disabled={disabled}+ />+ );+ }+ return (+ <ToolbarTrigger+ glyph={logo}+ label={label}+ caret+ width="md"+ ariaLabel={ariaLabel}+ tooltip={tooltip}+ ariaHaspopup="dialog"+ disabled={disabled}+ expanded={expanded}+ onClick={onClick}+ />+ );+}diff --git a/packages/ui/src/components/chat/step-banner/step-banner.tsx b/packages/ui/src/components/chat/step-banner/step-banner.tsxnew file mode 100644index 00000000..2e1fad34--- /dev/null+++ b/packages/ui/src/components/chat/step-banner/step-banner.tsx@@ -0,0 +1,130 @@+/**+ * The transcript's process banner (an MCP connection, a compaction): the work group's header+ * anatomy on a card of its own — the same card, the same sticky title bar (status icon, short+ * title, one-line detail, duration, chevron at the far right), so running, success and failure+ * are one row with only the icon and the detail changing. The duration follows the detail the+ * way the work group's count and duration do: the live clock while running, the settled span+ * once finished. A body makes the row expandable; collapsing while the stuck header sits above+ * the fold scrolls the card back into view.+ *+ * Expand policy, the work group's: the body opens while the step runs, so its rows are visible+ * as they are appended, and closes itself once the step settles, leaving the one-line summary+ * the row exists to be. The body's own rows never open with it. Once the reader toggles it, the+ * row is theirs: a later automatic change never fights them.+ *+ * The title is sentence case on the small rung, like the work group's; a banner is not a step+ * of the agent's work, so it carries no activity hook.+ */+import { useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import { Chevron } from "../../icons/chevron/chevron";+import { StatusIcon } from "../../icons/status-icon/status-icon";+import type { RunState } from "../../icons/status-icon/status-icon";+import { DurationSlot } from "../../feedback/duration-slot/duration-slot";+import {+ DISCLOSURE_CARD_CLASS,+ DISCLOSURE_HEADER_ROW_CLASS,+ DISCLOSURE_HEADER_STICKY_CLASS,+ DISCLOSURE_HEADER_TITLE_CLASS,+} from "../../layout/disclosure-row/disclosure-row";++export interface StepBannerProps {+ state: RunState;+ /** The constant short label in the title slot. */+ title: string;+ /** One line of status or result; truncates, with the full text as its tooltip. */+ detail?: string;+ /** While running, a live clock ticks from this timestamp. */+ liveSinceMs?: number;+ /** The settled wall time, once finished. */+ durationMs?: number;+ /** The expandable body; its presence adds the chevron (open while running, closed once settled). */+ children?: ReactNode;+}++export function StepBanner({+ state,+ title,+ detail,+ liveSinceMs,+ durationMs,+ children,+}: StepBannerProps) {+ const running = state === "running";+ const [open, setOpen] = useState(running);+ const userToggled = useRef(false);+ const rootRef = useRef<HTMLDivElement>(null);+ const expandable = children !== undefined && children !== null;++ // Before any manual toggle, follow "is this step still running"; afterwards the reader's choice+ // stands, so a finished row they opened stays open and one they closed mid-run stays closed.+ useEffect(() => {+ if (!userToggled.current) setOpen(running);+ }, [running]);++ const showDuration = running+ ? liveSinceMs !== undefined+ : durationMs !== undefined && durationMs > 0;++ const header = (+ <>+ <StatusIcon state={state} />+ <span+ className={`${DISCLOSURE_HEADER_TITLE_CLASS} ${running ? "text-tone-success-fg" : "text-fg-muted"}`}+ >+ {title}+ </span>+ {/* Detail then duration, left-aligned after the title; the trailing spacer pins the+ chevron to the right edge. min-w-0 (not flex-1) lets a long detail truncate while a+ short one keeps the duration snug against it. */}+ {detail !== undefined && (+ <span+ data-tooltip={detail}+ data-tooltip-content="code"+ className="min-w-0 truncate font-mono text-xs text-fg-subtle"+ >+ {detail}+ </span>+ )}+ {showDuration && (+ <DurationSlot running={running} sinceMs={liveSinceMs} durationMs={durationMs} />+ )}+ <span className="min-w-0 flex-1" />+ {expandable && <Chevron open={open} className="text-fg-subtle" />}+ </>+ );++ return (+ // The card clips rather than hides its overflow: the sticky header must stick to the+ // message list's scrollport, and an overflow-hidden ancestor would become its scroll+ // container instead.+ <div ref={rootRef} className={DISCLOSURE_CARD_CLASS}>+ {expandable ? (+ <button+ type="button"+ aria-expanded={open}+ onClick={() => {+ userToggled.current = true;+ // Collapsing while the header is stuck: bring the (now header-only) card back into+ // view once React commits; `nearest` makes every other case a no-op.+ const willClose = open;+ setOpen((v) => !v);+ if (willClose) {+ requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));+ }+ }}+ className={`${DISCLOSURE_HEADER_STICKY_CLASS} ${DISCLOSURE_HEADER_ROW_CLASS}`}+ >+ {header}+ </button>+ ) : (+ <div className="flex w-full items-center gap-2 bg-surface-muted px-3 py-2 text-left">+ {header}+ </div>+ )}+ {expandable && open && (+ <div className="anim-fade divide-y divide-line-muted border-t border-line">{children}</div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/components/chat/subagent-chip/subagent-chip.tsx b/packages/ui/src/components/chat/subagent-chip/subagent-chip.tsxnew file mode 100644index 00000000..88abeea4--- /dev/null+++ b/packages/ui/src/components/chat/subagent-chip/subagent-chip.tsx@@ -0,0 +1,64 @@+/**+ * The subagent row: what a spawned child session leaves in the parent's transcript (the child's+ * own conversation lives elsewhere, in the app's subagents panel). A full-width bar in the family+ * of the transcript's other collapsed rows — the work group's header, the thinking row: a ruled+ * box on the muted ground, content left-aligned — holding the agent's avatar, its name and a short+ * session id, the spinner while the child runs, and an attention dot while an approval is pending+ * anywhere under it, so a nested approval stays discoverable with the panel closed. Pressing it+ * opens the child.+ *+ * The row's accessible name is the caller's (it folds in the waiting state the dot shows); the+ * spinner and the dot are decoration beside it.+ */+import { AgentAvatar } from "../../icons/avatars/agent-avatar";+import { Dot } from "../../icons/dot/dot";+import { Spinner } from "../../icons/spinner/spinner";++export interface SubagentChipProps {+ /** The child's agent, by name. */+ label: string;+ /** The row's accessible name and tooltip ("Subagent Researcher · Awaiting approval"). */+ name: string;+ /** What the avatar's colour hashes: the agent id, or the session id when none is known. */+ avatarId: string;+ /** A short id after the name (the child session's), telling two runs of one agent apart. */+ tag?: string;+ /** The child is running: the spinner shows. */+ running: boolean;+ /** An approval waits somewhere under the child: the attention dot shows. */+ pending: boolean;+ onOpen?: () => void;+}++export function SubagentChip({+ label,+ name,+ avatarId,+ tag,+ running,+ pending,+ onOpen,+}: SubagentChipProps) {+ return (+ <button+ type="button"+ aria-label={name}+ data-tooltip={name}+ onClick={onOpen}+ className="flex w-full items-center gap-2 rounded-md border border-line bg-surface-muted px-3 py-2 text-left transition-colors duration-150 hover:bg-line-muted"+ >+ <AgentAvatar id={avatarId} name={label} size={16} />+ <span className="min-w-0 truncate text-xs font-medium text-fg">{label}</span>+ {tag !== undefined && tag !== "" && (+ <span className="shrink-0 font-mono text-xs text-fg-subtle">{tag}</span>+ )}+ {running && (+ <span aria-hidden className="flex shrink-0 text-fg-subtle">+ <Spinner size="xs" label="" />+ </span>+ )}+ {pending && <Dot tone="attention" />}+ <span className="min-w-0 flex-1" />+ </button>+ );+}diff --git a/packages/ui/src/components/chat/thinking-block/thinking-block.tsx b/packages/ui/src/components/chat/thinking-block/thinking-block.tsxnew file mode 100644index 00000000..00fe29bb--- /dev/null+++ b/packages/ui/src/components/chat/thinking-block/thinking-block.tsx@@ -0,0 +1,71 @@+/**+ * The thinking row: one step inside a work group — status icon, "Thinking", the elapsed time —+ * that expands to the full thinking text. It is the shared disclosure row, so its metrics and+ * colour states are the ones every other disclosure row uses, and it shares the run-state icons+ * (in progress, done, failed) with the tool-call rows. As a step of the agent's work it carries+ * the activity hook.+ */+import {+ DISCLOSURE_BODY_MD_CLASS,+ DisclosureRow,+ activityState,+} from "../../layout/disclosure-row/disclosure-row";+import { LiveDuration, formatDuration } from "../../feedback/duration-slot/duration-slot";+import { StatusIcon } from "../../icons/status-icon/status-icon";+import type { RunState } from "../../icons/status-icon/status-icon";+import { Md } from "../../content/prose/prose";++export interface ThinkingBlockProps {+ /** Running while the text streams, failed when it stopped short, done otherwise. */+ state: Extract<RunState, "running" | "done" | "failed">;+ /** The status icon's accessible name and tooltip ("Running", "Done", the stop reason). */+ stateLabel?: string;+ /** The row's label ("Thinking"). */+ label: string;+ /** The thinking text, Markdown; it streams while the row runs. */+ text: string;+ /** When the thinking started: the live clock's origin while it runs. */+ startedAtMs?: number;+ /** The settled duration, once finished. */+ durationMs?: number;+ /** Why a failed step stopped, shown in brackets after the duration. */+ stopReason?: string;+}++export function ThinkingBlock({+ state,+ stateLabel,+ label,+ text,+ startedAtMs,+ durationMs,+ stopReason,+}: ThinkingBlockProps) {+ const streaming = state === "running";+ return (+ <DisclosureRow+ sticky+ activity={{ kind: "thinking", state: activityState(state) }}+ icon={<StatusIcon state={state} label={stateLabel} />}+ label={label}+ trailing={+ <>+ <span data-slot="detail" className="shrink-0 font-mono text-xs text-fg-muted">+ {streaming ? (+ <LiveDuration sinceMs={startedAtMs} />+ ) : durationMs !== undefined ? (+ formatDuration(durationMs)+ ) : null}+ </span>+ {state === "failed" && stopReason !== undefined && (+ <span className="font-mono text-xs text-fg-subtle">[{stopReason}]</span>+ )}+ </>+ }+ >+ <div className={`anim-fade ${DISCLOSURE_BODY_MD_CLASS}`}>+ <Md text={text} streaming={streaming} />+ </div>+ </DisclosureRow>+ );+}diff --git a/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsx b/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsxnew file mode 100644index 00000000..85d5bbf3--- /dev/null+++ b/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsx@@ -0,0 +1,221 @@+/**+ * A tool call in the transcript: one line by default — status icon, the tool's name, a one-line+ * subtitle, the duration (a live clock while it runs) — that expands to the call's full arguments,+ * its output and any images it returned. A call waiting on a person's decision shows its+ * approval block under the row whatever the collapsed state, and a footer (a spawned subagent's+ * row) is always shown below the details.+ *+ * The row names no outcome in words: the status icon, with the caller's state label as its+ * accessible name and tooltip, is the one carrier of how the call ended or was decided, and a+ * waiting call's hourglass is enough because its approval block is on screen. The row's right end+ * holds one thing at a time: a marker saying where the call's work went ("background"), or an+ * action the caller offers on a running call (send it to the background). An action is a text+ * button with no padding of its own, so a row carrying one measures like a row without.+ *+ * Stacked sticky, the second level (the thinking row's): while the expanded output scrolls, the+ * row pins right below the stuck work-group header, on an opaque ground. Collapsing from stuck+ * lands the view back on the row. As a step of the agent's work the row carries the activity+ * hook: the tool's name is its label, the subtitle and the duration its details.+ *+ * Copy is the caller's: the name (an alias, when it resolves one), the subtitle, the state label,+ * the marker, the action, the approval buttons' words and the images' alt text all arrive as+ * props. What the caller decides from the call's own data — the preview, the payload, the+ * duration's segments — does too; this component only lays them out.+ */+import { useRef, useState } from "react";+import type { ReactNode } from "react";+import { useUiStrings } from "../../../strings";+import { Button } from "../../actions/button/button";+import { Chevron } from "../../icons/chevron/chevron";+import { StatusIcon } from "../../icons/status-icon/status-icon";+import type { RunState } from "../../icons/status-icon/status-icon";+import { LiveDuration, formatDuration } from "../../feedback/duration-slot/duration-slot";+import {+ ActivityProgress,+ DISCLOSURE_OUTPUT_PRE_CLASS,+ DISCLOSURE_ROW_CLASS,+ DISCLOSURE_ROW_STICKY_CLASS,+ activityState,+} from "../../layout/disclosure-row/disclosure-row";+import { ZoomableImage } from "../../overlays/lightbox/lightbox";+import { ApprovalBlock } from "../approval-block/approval-block";+import { StreamingCaret } from "../assistant-text/streaming-caret";+import type { ApprovalRequest } from "../approval-block/approval-block";++/**+ * The duration slot: a settled span, or a live clock counting from `sinceMs` on top of an earlier+ * settled segment (`offsetMs`); a live clock with no known start shows an ellipsis.+ */+export type ToolCallDuration =+ { live: false; ms: number } | { live: true; sinceMs?: number; offsetMs?: number };++export interface ToolCallCardProps {+ /** Running (arguments streaming or executing), waiting (on an approval), or settled. */+ state: RunState;+ /** The status icon's accessible name and tooltip: the state, the decision, the stop reason. */+ stateLabel?: string;+ /** The tool's name as shown. */+ name: string;+ /** The tool's own name when `name` is an alias: its tooltip. */+ nameTooltip?: string;+ /** The human-readable line beside the name (the call's description, a file path). */+ subtitle?: string | null;+ duration?: ToolCallDuration;+ /** A word at the row's right end saying where the call's work went. */+ marker?: string;+ /** An action at the row's right end, in the marker's slot. */+ action?: { label: string; hint?: string; onClick: () => void };+ /** The call waits on a decision: the approval block shows under the row. */+ pending?: ApprovalRequest;+ /** The call's arguments as sent, shown in full when expanded. */+ argumentsText?: string;+ /** The call's output so far. */+ output?: string;+ /** The output is still arriving: a caret follows it. */+ outputStreaming?: boolean;+ /** Images the call returned, shown as thumbnails that zoom when pressed. */+ images?: { srcs: readonly string[]; alt: string };+ /** Always shown below the details, whatever the collapsed state (a subagent's row). */+ footer?: ReactNode;+ /** The chevron's name while collapsed; the interface's word for "expand" by default. */+ expandLabel?: string;+ /** The chevron's name while expanded; the interface's word for "collapse" by default. */+ collapseLabel?: string;+}++export function ToolCallCard({+ state,+ stateLabel,+ name,+ nameTooltip,+ subtitle,+ duration,+ marker,+ action,+ pending,+ argumentsText,+ output,+ outputStreaming = false,+ images,+ footer,+ expandLabel,+ collapseLabel,+}: ToolCallCardProps) {+ const strings = useUiStrings();+ const [open, setOpen] = useState(false);+ const rootRef = useRef<HTMLDivElement>(null);++ // Shared by the row and the chevron beside it: two buttons, one disclosure. Collapsing while+ // the row is stuck lands the view back on the row.+ const toggleOpen = (): void => {+ const willClose = open;+ setOpen((v) => !v);+ if (willClose) {+ requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));+ }+ };++ return (+ <div ref={rootRef}>+ <div+ className={`ui-activity ${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}+ data-kind="tool"+ data-state={activityState(state)}+ >+ <button+ type="button"+ aria-expanded={open}+ onClick={toggleOpen}+ className="flex min-w-0 flex-1 items-center gap-2 self-stretch text-left"+ >+ <StatusIcon state={state} label={stateLabel} />+ <span+ data-tooltip={nameTooltip}+ data-tooltip-content="code"+ data-slot="label"+ className="shrink-0 truncate font-mono text-xs font-semibold text-fg"+ >+ {name}+ </span>+ {subtitle && (+ <span data-slot="detail" className="min-w-0 shrink truncate text-xs text-fg-muted">+ {subtitle}+ </span>+ )}+ <span data-slot="detail" className="shrink-0 font-mono text-xs text-fg-muted">+ {duration === undefined ? null : duration.live ? (+ <LiveDuration sinceMs={duration.sinceMs} offsetMs={duration.offsetMs} />+ ) : (+ formatDuration(duration.ms)+ )}+ </span>+ <ActivityProgress running={state === "running"} />+ <span className="min-w-0 flex-1" />+ </button>+ {marker !== undefined && (+ <span className="shrink-0 font-mono text-xs text-fg-subtle">{marker}</span>+ )}+ {action !== undefined && (+ // The row's own type size and no padding, so the row measures the same with it; a+ // sibling of the row button, since a button cannot hold another.+ <Button+ variant="link"+ size="sm"+ title={action.hint}+ onClick={action.onClick}+ className="shrink-0"+ >+ {action.label}+ </Button>+ )}+ {/* Named for what it does, like every chevron toggle: naming it after the tool would give+ the row two buttons under one name. */}+ <button+ type="button"+ aria-expanded={open}+ aria-label={open ? (collapseLabel ?? strings.collapse) : (expandLabel ?? strings.expand)}+ onClick={toggleOpen}+ className="flex shrink-0 items-center self-stretch"+ >+ <Chevron open={open} className="text-fg-subtle" />+ </button>+ </div>++ {pending !== undefined && (+ <ApprovalBlock name={name} nameTooltip={nameTooltip} {...pending} />+ )}++ {open && (+ <div className="anim-fade">+ {argumentsText && (+ // Wrapped in full, no height cap and no scrollbar: the arguments are what the call+ // means, and an inner scroll would fight the transcript's own.+ <pre className="whitespace-pre-wrap break-all border-t border-line-muted bg-surface-inset px-3 py-2 text-xs text-fg-muted">+ {argumentsText}+ </pre>+ )}+ {(output || outputStreaming) && (+ <pre className={DISCLOSURE_OUTPUT_PRE_CLASS}>+ {output}+ {outputStreaming && <StreamingCaret />}+ </pre>+ )}+ {images !== undefined && images.srcs.length > 0 && (+ <div className="flex flex-wrap gap-2 border-t border-line-muted px-3 py-2">+ {images.srcs.map((src, i) => (+ <ZoomableImage+ key={i}+ src={src}+ alt={images.alt}+ className="max-h-40 max-w-full rounded-md border border-line"+ />+ ))}+ </div>+ )}+ </div>+ )}++ {footer !== undefined && footer !== null && <div className="px-3 py-2">{footer}</div>}+ </div>+ );+}diff --git a/packages/ui/src/components/chat/work-group/work-group.tsx b/packages/ui/src/components/chat/work-group/work-group.tsxnew file mode 100644index 00000000..cbec73db--- /dev/null+++ b/packages/ui/src/components/chat/work-group/work-group.tsx@@ -0,0 +1,171 @@+/**+ * The work group: a run of consecutive work steps (thinking rows, tool calls) folded under one+ * header, the transcript's "what the agent did" between two pieces of its reply.+ *+ * Expand policy, two layers deep: the group opens while it runs and closes itself once it is+ * done, and the rows inside it stay closed — the reader sees that a step happened and how long it+ * took, not its contents, until they ask. A manual toggle is respected from then on. A step+ * waiting on an approval forces the body open, since the approval buttons live in it.+ *+ * The header is a title bar of its own (the muted ground, a short title that doubles as the+ * state), a different layer from the rows on the surface below it, so the parent and its+ * children read apart. It is sticky against the transcript's scrollport, so a long open group can+ * be collapsed from anywhere inside it; this is the first of two stacked sticky levels, the row+ * being read pinning right below it. Collapsing while the header is stuck lands the view back on+ * the group.+ *+ * The duration is the span of the steps (the earliest start to the latest end), reconstructible+ * from the steps' own timestamps: while a step is in flight its end is not known, so a live clock+ * extends the span to now; with nothing in flight the value is the settled span. A group that+ * merely stays open between steps does not tick, or the number would climb past the span and+ * snap back when the group settles.+ *+ * Three hooks: the card is a frame (its header the head, its rows the body), the header is a+ * step of the agent's work (thinking only, or tool work), and the rows hang off the header one+ * level down as a tree, so a theme may join them to it with connector rules instead of the box.+ * Each row is wrapped rather than marked on its own root, because a step also renders outside a+ * group.+ */+import { useEffect, useRef, useState } from "react";+import type { Key, ReactNode } from "react";+import { Chevron } from "../../icons/chevron/chevron";+import { StatusIcon } from "../../icons/status-icon/status-icon";+import { DurationSlot } from "../../feedback/duration-slot/duration-slot";+import {+ ActivityProgress,+ DISCLOSURE_CARD_CLASS,+ DISCLOSURE_HEADER_ROW_CLASS,+ DISCLOSURE_HEADER_STICKY_CLASS,+ DISCLOSURE_HEADER_TITLE_CLASS,+} from "../../layout/disclosure-row/disclosure-row";+import type { ActivityMark } from "../../layout/disclosure-row/disclosure-row";++/** One step in the group, keyed for React. */+export interface WorkGroupRow {+ key: Key;+ content: ReactNode;+}++export interface WorkGroupProps {+ /**+ * The group's state: running while the model may still add a step (the caller decides — a+ * trailing group of a running task counts), done once it cannot. The body follows it until the+ * reader toggles the group.+ */+ running: boolean;+ /** A step is in flight right now: the duration ticks and the progress slot shows. */+ stepRunning: boolean;+ /** What the header's activity mark names: thinking only, or tool work. */+ kind: ActivityMark["kind"];+ /** The header's title, which doubles as its state ("Running", "Done"). */+ title: string;+ /** The step count as words ("3 steps"); omitted for a group of thinking only. Hidden below `sm`. */+ count?: string;+ /** When the earliest step started: the live clock's origin while a step is in flight. */+ startMs?: number;+ /** The settled span, shown once nothing is in flight. */+ durationMs?: number;+ /** A step waits on an approval: the body is forced open. */+ pending?: boolean;+ rows: readonly WorkGroupRow[];+}++export function WorkGroup({+ running,+ stepRunning,+ kind,+ title,+ count,+ startMs,+ durationMs,+ pending = false,+ rows,+}: WorkGroupProps) {+ const [open, setOpen] = useState(running);+ const userToggled = useRef(false);+ const rootRef = useRef<HTMLDivElement>(null);++ // Before any manual toggle, follow the header's own state: open while the group works, closed+ // the moment it is done. The caller's `running` bridges the gaps between two steps, so the+ // group closes once and stays closed rather than flickering on every step.+ useEffect(() => {+ if (!userToggled.current) setOpen(running);+ }, [running]);++ const shown = open || pending;+ const showDuration = stepRunning+ ? startMs !== undefined+ : durationMs !== undefined && durationMs > 0;++ return (+ // The card clips rather than hides its overflow: an overflow-hidden ancestor would become the+ // sticky header's scroll container, and the header would stick to the card instead of the+ // transcript. Clipping keeps the rounded corners without that.+ <div ref={rootRef} className={`ui-frame ${DISCLOSURE_CARD_CLASS}`}>+ <button+ type="button"+ data-group-header+ aria-expanded={shown}+ onClick={() => {+ userToggled.current = true;+ // Collapsing while the header is stuck: the group's top sits above the fold, so bring+ // the (now header-only) group back into view once React commits. A forced-open group+ // keeps its body, so that click moves nothing.+ const willClose = open && !pending;+ setOpen((v) => !v);+ if (willClose) {+ requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));+ }+ }}+ className={`ui-activity ${DISCLOSURE_HEADER_STICKY_CLASS} ${DISCLOSURE_HEADER_ROW_CLASS}`}+ data-slot="head"+ data-kind={kind}+ data-state={running ? "running" : "done"}+ >+ <StatusIcon state={running ? "running" : "done"} />+ <span+ data-slot="label"+ className={`${DISCLOSURE_HEADER_TITLE_CLASS} ${running ? "text-tone-success-fg" : "text-fg-muted"}`}+ >+ {title}+ </span>+ {/* Below sm the count goes: the header must stay one uncut line on a phone. */}+ {count !== undefined && (+ <span+ data-slot="detail"+ className="hidden shrink-0 font-mono text-xs text-fg-subtle sm:inline"+ >+ {count}+ </span>+ )}+ {showDuration && (+ <DurationSlot+ data-slot="detail"+ running={stepRunning}+ sinceMs={startMs}+ durationMs={durationMs}+ />+ )}+ <ActivityProgress running={stepRunning} />+ <span className="min-w-0 flex-1" />+ <Chevron open={shown} className="text-fg-subtle" />+ </button>+ {shown && (+ <div+ data-slot="body"+ className="ui-tree anim-fade divide-y divide-line-muted border-t border-line"+ >+ {rows.map((row, index) => (+ <div+ key={row.key}+ data-depth="1"+ data-last={index === rows.length - 1 ? "true" : undefined}+ >+ {row.content}+ </div>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/components/forms/tag-input/tag-input.tsx b/packages/ui/src/components/forms/tag-input/tag-input.tsxnew file mode 100644index 00000000..3a0b3d33--- /dev/null+++ b/packages/ui/src/components/forms/tag-input/tag-input.tsx@@ -0,0 +1,153 @@+/**+ * Chips with remove buttons: one staged value per chip — an agent a message is handed to, a model+ * it forks onto, a skill it invokes, a file it quotes or carries along — each naming what it+ * stands for in a word or two and taking itself back with its ×.+ *+ * `Chip` is one chip, `TagInput` a wrapping row of them. A chip holds a leading mark the caller+ * sized (an avatar, a provider logo, a glyph), a label that gives way when the chip runs out of+ * room, an optional suffix kept whole after it (a quoted range's lines) and an optional muted+ * readout (a file's size). Two weights:+ *+ * - `soft` (the default) — the neutral tint, for something staged on the draft;+ * - `outline` — the hairline on the muted surface, for a file carried along with it; a row of+ * these spaces its chips wider.+ *+ * A chip with a `control` holds an inline control after its label (a goal's budget picker): the+ * label keeps its width and the control gives way, a rule parts the two, and the tooltip names+ * the label alone so it never covers the control.+ *+ * The remove button is named by the caller, because "remove" alone does not say what goes; a chip+ * given no name for it has no remove button.+ */+import type { ReactNode } from "react";++export type ChipVariant = "soft" | "outline";++export interface ChipProps {+ /** What the chip stands for; it truncates first when the chip runs out of room. */+ label: ReactNode;+ /** The leading mark, sized by the caller. */+ glyph?: ReactNode;+ /** Kept whole after the label, in the label's ink (a quoted range's `:12-30`). */+ suffix?: ReactNode;+ /** A muted readout after the label, in the mono face (a file's size). */+ meta?: ReactNode;+ /** The whole of what the chip stands for, on hover (a path, a description). */+ tooltip?: string;+ /** Set the chip in the mono face: it names an id, a file or a command. */+ mono?: boolean;+ variant?: ChipVariant;+ /** An inline control after the label; see the module header. */+ control?: ReactNode;+ /** The remove button's accessible name; without it the chip has no remove button. */+ removeLabel?: string;+ onRemove?: () => void;+}++const VARIANT: Record<ChipVariant, string> = {+ soft: "bg-fill-neutral py-0.5",+ outline: "border border-line bg-surface-muted py-1",+};++/** How wide a chip may grow before its label truncates. */+const WIDTH: Record<ChipVariant, string> = { soft: "max-w-48", outline: "max-w-56" };++export function Chip({+ label,+ glyph,+ suffix,+ meta,+ tooltip,+ mono = false,+ variant = "soft",+ control,+ removeLabel,+ onRemove,+}: ChipProps) {+ const inline = control !== undefined && control !== null;+ return (+ <span+ {...(tooltip !== undefined && !inline ? { "data-tooltip": tooltip } : {})}+ className={`anim-pop flex ${inline ? "max-w-full" : WIDTH[variant]} items-center gap-1 rounded-md ${VARIANT[variant]} pl-2 pr-1 text-xs text-fg ${mono ? "font-mono" : ""}`}+ >+ {inline ? (+ <>+ <span+ {...(tooltip !== undefined ? { "data-tooltip": tooltip } : {})}+ className="flex shrink-0 items-center gap-1"+ >+ {glyph}+ <span>{label}</span>+ </span>+ <span aria-hidden className="mx-0.5 h-4 w-px shrink-0 bg-line-emphasis" />+ {control}+ </>+ ) : (+ <>+ {glyph}+ <span className="min-w-0 truncate">{label}</span>+ {suffix !== undefined && suffix !== null && suffix !== "" && (+ <span className="shrink-0">{suffix}</span>+ )}+ {meta !== undefined && meta !== null && meta !== "" && (+ <span className="shrink-0 font-mono text-fg-subtle">{meta}</span>+ )}+ </>+ )}+ {removeLabel !== undefined && (+ // The box is the line's height and a hair either side of the ×, so the chip keeps one+ // height whatever it holds.+ <button+ type="button"+ aria-label={removeLabel}+ onClick={onRemove}+ className="flex h-5 shrink-0 items-center rounded px-0.5 text-fg-subtle transition-colors duration-150 hover:text-fg"+ >+ ×+ </button>+ )}+ </span>+ );+}++/** One chip of a `TagInput`, keyed; its remove button reports the key to the row's `onRemove`. */+export interface TagInputChip extends Omit<ChipProps, "onRemove" | "variant"> {+ key: string;+}++export function TagInput({+ chips,+ onRemove,+ leading,+ trailing,+ variant = "soft",+ className = "",+}: {+ chips: readonly TagInputChip[];+ /** A chip's × was pressed. */+ onRemove?: (key: string) => void;+ /** Chips the caller draws itself, before the listed ones (a chip with its own control). */+ leading?: ReactNode;+ /** Chips the caller draws itself, after the listed ones. */+ trailing?: ReactNode;+ variant?: ChipVariant;+ /** Layout only (a margin); the row's look is the family's. */+ className?: string;+}) {+ return (+ <div+ className={`flex flex-wrap ${variant === "outline" ? "gap-2" : "items-center gap-1"} ${className}`}+ >+ {leading}+ {chips.map(({ key, ...chip }) => (+ <Chip+ key={key}+ {...chip}+ variant={variant}+ {...(onRemove !== undefined ? { onRemove: () => onRemove(key) } : {})}+ />+ ))}+ {trailing}+ </div>+ );+}diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.tsindex bddce2ee..af7f52a1 100644--- a/packages/ui/src/components/icons/icons.ts+++ b/packages/ui/src/components/icons/icons.ts@@ -45,6 +45,8 @@ export const ICONS = {*/robotPair:"M7.3 4.2V2.2M3.8 4.2h7a2.2 2.2 0 0 1 2.2 2.2v5.8a2.2 2.2 0 0 1-2.2 2.2h-7a2.2 2.2 0 0 1-2.2-2.2V6.4a2.2 2.2 0 0 1 2.2-2.2zM4.6 9.2h.01M10 9.2h.01M18.6 14.8v-1.7M16.5 14.8h4.2a1.7 1.7 0 0 1 1.7 1.7v3.8a1.7 1.7 0 0 1-1.7 1.7h-4.2a1.7 1.7 0 0 1-1.7-1.7v-3.8a1.7 1.7 0 0 1 1.7-1.7zM17.3 18.4h.01M20.5 18.4h.01",+ /** A person: head and shoulders (lucide user). The person at the keyboard, beside the agent. */+ user: "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0",/*** The cerebrum from the side: the lobed outline, then the gyri inside it. The drawing was* authored with the whole figure shifted a little down the box; the shift is baked into the@@ -231,6 +233,19 @@ export const ICONS = {plus: "M12 5v14M5 12h14",/** A magnifier: a lens and its handle. The search box's leading mark and the toggle that opens one. */search: "M21 21l-4.35-4.35M17 11a6 6 0 1 1-12 0 6 6 0 0 1 12 0z",+ /**+ * An arrow that turns back on itself: the head at the left, the shaft looping round beneath it.+ * Bring it back — the undo reading, not the bin's: what it takes back is returned, not thrown+ * away.+ */+ undo: "M9 14L4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11",+ /** A picture: the rounded frame, and a mountain line across its lower half. */+ image:+ "M6 5h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM3 15l5-5 4 4 3-3 6 6",+ /** Three sliders set at different heights (feather sliders): how something behaves, adjustable. */+ sliders: "M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6",+ /** A four-pointed spark: effort and thought, the dial a model thinks harder on. */+ sparkle: "M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z",// --- Direction ----------------------------------------------------------------------------diff --git a/packages/ui/src/hooks.ts b/packages/ui/src/hooks.tsindex 9f61e2fa..d6c5aa10 100644--- a/packages/ui/src/hooks.ts+++ b/packages/ui/src/hooks.ts@@ -16,13 +16,15 @@* | ------------------ | -------------------------------------------------------- | ----------------------------------------------------- |* | `ui-glass` | a transient layer over content: menus, popovers, the | — |* | | modal card, the floating composer, a sticky page header | |+ * | | hosts: `ComposerCard` and its `SlashMenu`, `Modal`, | |+ * | | `Dropdown`, the selects, popovers and tooltips | |* | `ui-eyebrow` | a group label naming the items below it (never directly | — |* | | above an `h1`–`h4`); hosts: `Text variant="eyebrow"`, | |* | | the sidebar's and group headers' labels | |* | `ui-display` | the one display title of a page or hero | only on an `h1` or `[aria-level="1"]` |* | | hosts: `Heading level={1} display`, `PageHeader`'s title | |* | `ui-live` | motion for something that is running right now | `data-live="dot" \| "caret" \| "spinner" \| "bar"` |- * | | hosts: the Spinner, a pulsing Dot | |+ * | | hosts: the Spinner, a pulsing Dot, the streaming caret | |* | `ui-frame` | a ruled box with a head, a body, a foot and panes | children carry `data-slot="head" \| "body" \| "foot" \| "pane"` |* | | hosts: the transcript's cards, the code block, `Card`, | |* | | a framed `Table` | |@@ -113,20 +115,20 @@* 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.+ * `ui-stream` (2026-09-30) is how a theme shows a reply arriving. The host is the reply's body+ * (`AssistantText`): 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, `StreamingCaret`, itself a `ui-live` caret —+ * 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 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",diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.tsindex 2324bf42..09840f8d 100644--- a/packages/ui/src/index.ts+++ b/packages/ui/src/index.ts@@ -156,3 +156,34 @@ export * from "./components/charts/legend/legend";// W8-B — the command palette: the search box over the caller's actions, and its filter.export * from "./components/overlays/command-palette/command-palette";++// W6-A1 — the transcript's messages: what the person sent and the run's notice lines, the+// assistant reply with its caret and the theme-paced reveal behind it, and the changes card.+// The reveal's pacing (stream-reveal.ts) stays inside the family: its hook is the door.+export * from "./components/chat/message-bubble/message-bubble";+export * from "./components/chat/assistant-text/assistant-text";+export * from "./components/chat/assistant-text/streaming-caret";+export * from "./components/chat/assistant-text/use-stream-reveal";+export * from "./components/chat/assistant-text/stream-style";+export * from "./components/chat/changes-card/changes-card";++// W6-A2 — the transcript's work: the work group and its rows (the thinking row, the tool call and+// the approval block it holds), the process banner and the subagent row.+export * from "./components/chat/work-group/work-group";+export * from "./components/chat/thinking-block/thinking-block";+export * from "./components/chat/tool-call-card/tool-call-card";+export * from "./components/chat/approval-block/approval-block";+export * from "./components/chat/step-banner/step-banner";+export * from "./components/chat/subagent-chip/subagent-chip";++// W6-B — the composer: its card, chip row, toolbar triggers, action button and slash list, the+// toolbar select, the context ring, the model picker, and the chips with remove buttons.+export * from "./components/chat/composer/composer";+export * from "./components/chat/composer/toolbar-trigger";+export * from "./components/chat/menu-select/menu-select";+export * from "./components/chat/context-ring/context-ring";+export * from "./components/chat/model-select/model-select";+export * from "./components/forms/tag-input/tag-input";++// W6-C — the company channel: a sender's run of messages and its bubbles.+export * from "./components/chat/channel-bubble/channel-bubble";diff --git a/packages/ui/src/testing/render.ts b/packages/ui/src/testing/render.tsindex 225c7a21..413c759b 100644--- a/packages/ui/src/testing/render.ts+++ b/packages/ui/src/testing/render.ts@@ -9,7 +9,9 @@ import { renderToStaticMarkup } from "react-dom/server";/** The element's initial render as an HTML string. */export function renderStatic(element: ReactElement): string {- return renderToStaticMarkup(element);+ // React 19's server renderer prepends a preload hint for an eager image; it is the renderer's+ // resource hint, not the component's markup, so the tests never see it.+ return renderToStaticMarkup(element).replace(/^(?:<link rel="preload"[^>]*\/>)+/, "");}/**diff --git a/packages/ui/src/theme.css b/packages/ui/src/theme.cssindex 65956279..df48ddce 100644--- a/packages/ui/src/theme.css+++ b/packages/ui/src/theme.css@@ -70,6 +70,7 @@--color-canvas: var(--ui-canvas);--color-surface: var(--ui-surface);--color-surface-muted: var(--ui-surface-muted);+ --color-fill-neutral: var(--ui-fill-neutral);--color-surface-inset: var(--ui-inset);--color-overlay: var(--ui-overlay);diff --git a/packages/ui/src/themes/geek.css b/packages/ui/src/themes/geek.cssindex ec715372..1dce1794 100644--- a/packages/ui/src/themes/geek.css+++ b/packages/ui/src/themes/geek.css@@ -82,6 +82,7 @@--ui-canvas: #fbfafa;--ui-surface: var(--ui-canvas);--ui-surface-muted: #f4f2f2;+ --ui-fill-neutral: var(--color-gray-100);--ui-inset: #f0eeee;--ui-overlay: var(--ui-canvas);--ui-overlay-backdrop: rgb(19 16 16 / 0.28);@@ -411,6 +412,7 @@steps up, an inset steps down */--ui-canvas: #131010;--ui-surface-muted: #221f1f;+ --ui-fill-neutral: var(--color-gray-800);--ui-inset: #0d0b0b;--ui-overlay-backdrop: rgb(0 0 0 / 0.6);diff --git a/packages/ui/src/themes/github.css b/packages/ui/src/themes/github.cssindex 238a6ae2..bea1fd26 100644--- a/packages/ui/src/themes/github.css+++ b/packages/ui/src/themes/github.css@@ -64,6 +64,7 @@--ui-canvas: #ffffff;--ui-surface: #ffffff;--ui-surface-muted: var(--color-gray-50);+ --ui-fill-neutral: var(--color-gray-100);--ui-inset: var(--color-gray-50);--ui-overlay: #ffffff;--ui-overlay-backdrop: oklab(0% 0 0 / 0.45); /* = bg-black/45, alpha exactly .45 */@@ -421,6 +422,7 @@--ui-canvas: var(--color-gray-950);--ui-surface: var(--color-gray-900);--ui-surface-muted: #202020;+ --ui-fill-neutral: var(--color-gray-800);--ui-inset: #0e0e0e;--ui-overlay: var(--color-gray-900);diff --git a/packages/ui/src/themes/modern.css b/packages/ui/src/themes/modern.cssindex ea2801d1..8c907fc3 100644--- a/packages/ui/src/themes/modern.css+++ b/packages/ui/src/themes/modern.css@@ -58,6 +58,7 @@--ui-canvas: #fafafa;--ui-surface: #ffffff;--ui-surface-muted: #f3f4f5;+ --ui-fill-neutral: var(--color-gray-100);--ui-inset: #f5f6f7;--ui-overlay: #ffffff;--ui-overlay-backdrop: rgb(24 25 27 / 0.4);@@ -389,6 +390,7 @@--ui-canvas: #1b1c1e;--ui-surface: #232426;--ui-surface-muted: #2a2b2e;+ --ui-fill-neutral: var(--color-gray-800);--ui-inset: #161718;--ui-overlay: #262729;--ui-overlay-backdrop: rgb(0 0 0 / 0.55);diff --git a/packages/ui/src/tokens.ts b/packages/ui/src/tokens.tsindex 12b3d3c4..8facdad2 100644--- a/packages/ui/src/tokens.ts+++ b/packages/ui/src/tokens.ts@@ -175,6 +175,9 @@ export const TOKEN_GROUPS = ["--ui-canvas","--ui-surface","--ui-surface-muted",+ // The filled neutral surface a message bubble or a chip sits on: a surface, not a tone —+ // Console empties its tone fills, and a bubble must keep its fill there.+ "--ui-fill-neutral","--ui-inset","--ui-overlay","--ui-overlay-backdrop",@@ -517,7 +520,7 @@ export const TOKEN_GROUPS = [{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+ // What AssistantText's 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).diff --git a/packages/ui/test/assistant-text.test.ts b/packages/ui/test/assistant-text.test.tsnew file mode 100644index 00000000..c2bd1053--- /dev/null+++ b/packages/ui/test/assistant-text.test.ts@@ -0,0 +1,41 @@+/**+ * AssistantText and StreamingCaret (src/components/chat/assistant-text/): the reply body is the+ * `ui-stream` host, streaming with the caret as its last child until the reply is whole, and+ * holding back whatever the caller appends until then. Rendered once, without a theme sheet, so+ * the reveal is instant — the pacing itself is stream-reveal.test.ts.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { AssistantText } from "../src/components/chat/assistant-text/assistant-text";+import { StreamingCaret } from "../src/components/chat/assistant-text/streaming-caret";+import { classTokens, renderStatic } from "../src/testing";++const reply = (streaming: boolean) =>+ renderStatic(+ createElement(AssistantText, { text: "Hello **world**", streaming }, "[max_tokens]"),+ );++describe("AssistantText", () => {+ it("streams with the caret as the host's last child, and holds the caller's extras back", () => {+ const html = reply(true);+ expect(html).toMatch(/^<div class="ui-stream md-body [^"]*" data-state="streaming">/);+ expect(html).toContain("<strong>world</strong>");+ expect(html).toMatch(/<span data-slot="caret"[^>]*>▌<\/span><\/div>$/);+ expect(html).not.toContain("[max_tokens]");+ });++ it("settles to done: no caret, and the extras after the text", () => {+ const html = reply(false);+ expect(html).toContain('data-state="done"');+ expect(html).not.toContain('data-slot="caret"');+ expect(html).toMatch(/<\/p>\[max_tokens\]<\/div>$/);+ });+});++describe("StreamingCaret", () => {+ it("is a decorative live caret, pulsing in the subtle ink", () => {+ const html = renderStatic(createElement(StreamingCaret));+ expect(html).toContain('data-slot="caret" data-live="caret" aria-hidden="true"');+ expect(classTokens(html)).toEqual(["animate-pulse", "text-fg-subtle", "ui-live"]);+ });+});diff --git a/packages/ui/test/changes-card.test.ts b/packages/ui/test/changes-card.test.tsnew file mode 100644index 00000000..ba25d166--- /dev/null+++ b/packages/ui/test/changes-card.test.ts@@ -0,0 +1,83 @@+/**+ * ChangesCard and PathLabel (src/components/chat/changes-card/changes-card.tsx): the card at a+ * Task's foot listing the files it touched — a transcript frame with a counted header, rows that+ * say in words what a click does, plain rows when nothing opens, and a fold past a few rows.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ChangesCard, PathLabel } from "../src/components/chat/changes-card/changes-card";+import type { ChangesCardProps } from "../src/components/chat/changes-card/changes-card";+import { classTokens, renderStatic } from "../src/testing";++const open = () => {};+const card = (props: Partial<ChangesCardProps> = {}) =>+ renderStatic(+ createElement(ChangesCard, {+ glyph: "M0 0h24",+ title: "2 files",+ rows: [+ { id: "a", path: "src/a.ts", glyph: "M1 1h1", tooltip: "src/a.ts", onOpen: open },+ { id: "b", path: "b.md", glyph: "M2 2h1" },+ ],+ openHint: "Preview",+ showMore: (n: number) => `Show ${n} more`,+ showLess: "Show less",+ ...props,+ }),+ );++describe("ChangesCard", () => {+ it("is a transcript frame: a counted header strip over the rows", () => {+ const html = card();+ expect(html).toMatch(/^<div class="ui-frame [^"]*"><div data-slot="head"/);+ expect(html).toContain('<div data-slot="body"');+ expect(html).toContain(">2 files</span>");+ });++ it("makes a row that opens a button naming its action, and one that does not plain text", () => {+ const html = card();+ const opener = /<button type="button" data-tooltip="src\/a\.ts"[^>]*>[\s\S]*?Preview<\/span>/;+ expect(html).toMatch(opener);+ expect(html).toMatch(/<div class="[^"]*">(?:(?!<button)[\s\S])*b\.md/);+ expect(html.match(/Preview/g)).toHaveLength(1);+ });++ it("puts a header action in words, and names a row's glyph and mark", () => {+ const html = card({+ action: { label: "Open list", onClick: open },+ rows: [+ {+ id: "m",+ path: "prefs.md",+ glyph: "M3 3h1",+ glyphLabel: "User memory",+ mark: { glyph: "M4 4h1", label: "Written" },+ onOpen: open,+ },+ ],+ });+ expect(html).toMatch(/<button type="button" class="[^"]*">Open list<\/button>/);+ expect(html).toContain('<span class="sr-only">User memory</span>');+ expect(html).toContain('role="img" aria-label="Written" data-tooltip="Written"');+ });++ it("folds past the first rows behind a row that counts the rest", () => {+ const rows = ["a", "b", "c", "d", "e"].map((id) => ({ id, path: `${id}.ts`, glyph: "M0 0" }));+ const html = card({ rows });+ expect(html).toContain("c.ts");+ expect(html).not.toContain("d.ts");+ expect(html).toContain("Show 2 more");+ });++ it("draws nothing without rows", () => {+ expect(card({ rows: [] })).toBe("");+ });+});++describe("PathLabel", () => {+ it("fades the directory and sets the name in bold, both able to truncate", () => {+ const html = renderStatic(createElement(PathLabel, { path: "src/lib/a.ts" }));+ expect(html).toMatch(/>src\/lib\/<\/span><span class="[^"]*font-semibold[^"]*">a\.ts</);+ expect(classTokens(html)).toEqual(expect.arrayContaining(["shrink-[9999]", "truncate"]));+ });+});diff --git a/packages/ui/test/channel-bubble.test.ts b/packages/ui/test/channel-bubble.test.tsnew file mode 100644index 00000000..b9376efe--- /dev/null+++ b/packages/ui/test/channel-bubble.test.ts@@ -0,0 +1,127 @@+/**+ * ChannelRun and ChannelBubble (src/components/chat/channel-bubble/channel-bubble.tsx): a sender's+ * run of messages — the avatar and the name once, or only a screen reader's word on the reader's+ * own side — and one message in it, with its time, its tail corner and its surface; and the+ * stylesheet that deepens inline code and table rules inside it.+ */+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ChannelBubble, ChannelRun } from "../src/components/chat/channel-bubble/channel-bubble";+import type {+ ChannelBubbleProps,+ ChannelRunProps,+} from "../src/components/chat/channel-bubble/channel-bubble";+import { classTokens, renderStatic } from "../src/testing";+import { SRC_DIR } from "./helpers/paths";++const DIR = join(SRC_DIR, "components/chat/channel-bubble");+const read = (name: string) => readFileSync(join(DIR, name), "utf8");++const run = (props: Partial<ChannelRunProps> = {}) =>+ renderStatic(+ createElement(ChannelRun, {+ sender: { kind: "agent", id: "ceo", name: "Chief" },+ children: createElement("p", null, "bubbles"),+ ...props,+ }),+ );++const bubble = (props: Partial<ChannelBubbleProps> = {}) =>+ renderStatic(+ createElement(ChannelBubble, {+ time: "14:05",+ timeLabel: "发送于 9/30 14:05",+ timeTooltip: "9/30 14:05",+ children: createElement("p", null, "body"),+ ...props,+ }),+ );++describe("ChannelRun", () => {+ it("leads somebody else's run with the avatar and the name once, then what follows it", () => {+ const html = run({ meta: createElement("span", null, "Relay · hop 2") });+ expect(html).toMatch(/<svg[^>]*aria-hidden="true"/);+ expect(html).toContain(">Chief</span>");+ expect(html).toContain("Relay · hop 2");+ expect(html.indexOf("Chief")).toBeLessThan(html.indexOf("bubbles"));+ expect(classTokens(html)).toEqual(expect.arrayContaining(["items-start", "text-fg-muted"]));+ expect(html).not.toContain("sr-only");+ });++ it("draws a person as a decorative initial tile on the foreground ink", () => {+ const html = run({ sender: { kind: "user", id: "u1", name: "dana" } });+ expect(html).toMatch(+ /<span aria-hidden="true" class="[^"]*bg-fg[^"]*text-canvas[^"]*">D<\/span>/,+ );+ expect(html).not.toContain("<svg");+ });++ it("puts the reader's own run on the right, with a screen reader's word for the name", () => {+ const html = run({ own: true, ownLabel: "你" });+ expect(html).toContain('<span class="sr-only">你</span>');+ expect(html).not.toContain("<svg");+ expect(html).not.toContain("Chief");+ expect(classTokens(html)).toContain("items-end");+ // Without a word of its own, the sender's name is what a screen reader hears.+ expect(run({ own: true })).toContain('<span class="sr-only">Chief</span>');+ });+});++describe("ChannelBubble", () => {+ it("prints the body in the compact reading box, the footer under it, the time at its end", () => {+ const html = bubble({ id: "m-1", footer: createElement("span", null, "refs") });+ expect(html).toMatch(/^<div id="m-1" data-side="other" class="channel-bubble /);+ expect(html).toContain('<div class="md-body md-compact"><p>body</p></div><span>refs</span>');+ expect(html).toContain(+ '<span data-tooltip="9/30 14:05" class="shrink-0 text-xs tabular-nums ' ++ 'text-tone-neutral-fg"><span class="sr-only">发送于 9/30 14:05</span>' ++ '<span aria-hidden="true">14:05</span></span>',+ );+ expect(classTokens(html)).toEqual(expect.arrayContaining(["bg-fill-neutral", "text-fg"]));+ });++ it("squares the corner nearest the run's tail, on the last bubble only", () => {+ const tokens = (own: boolean, last: boolean) => classTokens(bubble({ own, last }));+ expect(tokens(false, false)).toContain("rounded-2xl");+ expect(tokens(false, false).some((t) => /^rounded-[bt][lr]-/.test(t))).toBe(false);+ expect(tokens(false, true)).toEqual(+ expect.arrayContaining(["rounded-bl-sm", "rounded-br-2xl"]),+ );+ expect(tokens(true, true)).toEqual(expect.arrayContaining(["rounded-br-sm", "rounded-bl-2xl"]));+ });++ it("tints the reader's own bubble with the link ink's wash over the canvas, not a tone", () => {+ const html = bubble({ own: true });+ expect(html).toContain('data-side="own"');+ expect(classTokens(html)).toContain(+ "bg-[color-mix(in_srgb,var(--ui-fg-link)_12%,var(--ui-canvas))]",+ );+ expect(classTokens(html).some((t) => t.startsWith("bg-tone-"))).toBe(false);+ });+});++describe("the channel bubble stylesheet", () => {+ const rules = read("channel-bubble.css").replace(/\/\*[\s\S]*?\*\//g, "");++ it("is loaded by the component, with the Markdown typography it adjusts", () => {+ const source = read("channel-bubble.tsx");+ expect(source).toMatch(/import "\.\/channel-bubble\.css";/);+ expect(source).toMatch(/import "\.\.\/\.\.\/content\/prose\/prose\.css";/);+ });++ it("stays unlayered, so it out-ranks the unlayered Markdown rules, and reads tokens only", () => {+ expect(rules).not.toMatch(/@layer|@apply|@reference|@import/);+ expect(rules).not.toMatch(/#[0-9a-f]{3,8}\b|\brgb\(|\boklch\(|--color-|\.dark\b/i);+ });++ it("deepens inline code, never a fenced block's, and the table rules, one step", () => {+ expect(rules).toMatch(+ /\.channel-bubble :not\(pre\) > code \{\s*background-color: var\(--ui-line-emphasis\);/,+ );+ expect(rules).toMatch(+ /\.channel-bubble :is\(th, td\) \{\s*border-color: var\(--ui-line-emphasis\);/,+ );+ });+});diff --git a/packages/ui/test/composer.test.ts b/packages/ui/test/composer.test.tsnew file mode 100644index 00000000..3221ee64--- /dev/null+++ b/packages/ui/test/composer.test.ts@@ -0,0 +1,197 @@+/**+ * The composer family (src/components/chat/composer): the card with its text body and one-row+ * toolbar, the action button's two faces, the slash list and the picker panel a switch command+ * opens, and the toolbar trigger's two shapes. Every word comes from the caller.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import {+ ChipRow,+ ComposerCard,+ SendButton,+ SlashMenu,+ SlashPicker,+} from "../src/components/chat/composer/composer";+import { ToolbarTrigger } from "../src/components/chat/composer/toolbar-trigger";+import { classTokens, renderStatic } from "../src/testing";++const noop = () => {};++describe("ComposerCard", () => {+ const card = (hint?: string) =>+ renderStatic(+ createElement(ComposerCard, {+ chips: createElement("p", null, "CHIPS"),+ textarea: { value: "draft", placeholder: "Type a message", onChange: noop },+ tools: createElement("button", { type: "button" }, "TOOL"),+ ...(hint !== undefined ? { hint } : {}),+ actions: createElement("button", { type: "button" }, "ACTION"),+ }),+ );++ it("is the glass card, sized by its own width, ringed while anything in it has focus", () => {+ const tokens = classTokens(card());+ expect(tokens).toEqual(+ expect.arrayContaining([+ "ui-glass",+ "@container",+ "bg-surface",+ "focus-within:ring-2",+ "focus-within:ring-fg-subtle/30",+ ]),+ );+ });++ it("stacks the chips, a two-line text body, then the toolbar: tools, hint, actions", () => {+ const html = card("Type / for commands");+ const textarea = /<textarea\b[^>]*>/.exec(html)?.[0] ?? "";+ expect(textarea).toContain('rows="2"');+ expect(textarea).toContain('placeholder="Type a message"');+ const order = ["CHIPS", "<textarea", "TOOL", "Type / for commands", "ACTION"].map((s) =>+ html.indexOf(s),+ );+ expect(order).toEqual([...order].sort((a, b) => a - b));+ expect(order.every((i) => i >= 0)).toBe(true);+ // The hint shows only once the card is wide enough, and names itself on hover.+ expect(html).toContain('data-tooltip="Type / for commands"');+ expect(classTokens(html)).toContain("@lg:block");+ });++ it("draws no hint when there is none", () => {+ expect(card()).not.toContain("@lg:block");+ });+});++describe("ChipRow", () => {+ it("is the soft chip row, spaced off the text body below it", () => {+ const html = renderStatic(+ createElement(ChipRow, {+ chips: [{ key: "a", label: "research", removeLabel: "Remove research" }],+ }),+ );+ expect(classTokens(html)).toEqual(expect.arrayContaining(["mb-1", "gap-1", "items-center"]));+ expect(html).toContain('aria-label="Remove research"');+ });+});++describe("SendButton", () => {+ it("sends on the accent square, named and hinted by what it does now", () => {+ const html = renderStatic(+ createElement(SendButton, { action: "send", label: "Send", onClick: noop }),+ );+ expect(html).toContain('aria-label="Send"');+ expect(html).toContain('data-tooltip="Send"');+ expect(classTokens(html)).toEqual(expect.arrayContaining(["bg-accent", "text-accent-fg"]));+ expect(html).not.toContain('disabled=""');+ });++ it("greys out while there is nothing to send", () => {+ const html = renderStatic(+ createElement(SendButton, { action: "send", label: "Send", disabled: true, onClick: noop }),+ );+ expect(html).toContain('disabled=""');+ });++ it("stops on a neutral square in the danger ink, and can always be pressed", () => {+ const html = renderStatic(+ createElement(SendButton, { action: "stop", label: "Stop", disabled: true, onClick: noop }),+ );+ expect(html).toContain('aria-label="Stop"');+ expect(html).not.toContain('disabled=""');+ const tokens = classTokens(html);+ expect(tokens).toEqual(expect.arrayContaining(["bg-fill-neutral", "text-tone-danger-fg"]));+ // No icon in a tint of itself: the danger tint arrives on hover only.+ expect(tokens).not.toContain("bg-tone-danger-bg");+ expect(html).toContain("<rect");+ });+});++describe("SlashMenu", () => {+ const menu = renderStatic(+ createElement(SlashMenu, {+ items: [+ { command: "/compact", description: "Compress the context" },+ { command: "/goal", description: "Work towards a goal" },+ ],+ active: 1,+ onActiveChange: noop,+ onRun: noop,+ maxHeight: 200,+ }),+ );++ it("opens as a glass menu panel over the composer, capped at the room above it", () => {+ expect(classTokens(menu)).toEqual(+ expect.arrayContaining(["ui-glass", "absolute", "bottom-full", "overscroll-contain"]),+ );+ expect(menu).toContain("max-height:200px");+ });++ it("lists each command in the mono face, what it does truncating after it", () => {+ expect(menu).toContain(">/compact</span>");+ expect(menu).toContain('data-tooltip="Compress the context"');+ expect(classTokens(menu)).toEqual(expect.arrayContaining(["font-mono", "truncate"]));+ });++ it("highlights the keyboard's row alone", () => {+ const rows = menu.split("<button").slice(1);+ expect(rows).toHaveLength(2);+ expect(classTokens(`<b${rows[0]!}`)).not.toContain("bg-line-muted");+ expect(classTokens(`<b${rows[1]!}`)).toContain("bg-line-muted");+ });+});++describe("SlashPicker", () => {+ it("names the switch in a title bar above the caller's picker", () => {+ const html = renderStatic(+ createElement(SlashPicker, {+ title: "Switch model",+ children: createElement("p", null, "PICKER"),+ }),+ );+ expect(html.indexOf("Switch model")).toBeLessThan(html.indexOf("PICKER"));+ expect(classTokens(html)).toEqual(expect.arrayContaining(["bottom-full", "bg-overlay"]));+ });+});++describe("ToolbarTrigger", () => {+ it("is an icon square named by the caller, its tooltip the name unless given another", () => {+ const html = renderStatic(+ createElement(ToolbarTrigger, { glyph: "M12 5v14M5 12h14", ariaLabel: "Add" }),+ );+ expect(html).toContain('aria-label="Add"');+ expect(html).toContain('data-tooltip="Add"');+ expect(classTokens(html)).toEqual(expect.arrayContaining(["h-8", "w-8"]));+ expect(html).not.toContain("aria-expanded");+ });++ it("carries a count on its corner, and none at zero", () => {+ const three = renderStatic(+ createElement(ToolbarTrigger, { glyph: "M12 5v14", ariaLabel: "Skills", badge: 3 }),+ );+ expect(classTokens(three)).toContain("tabular-nums");+ expect(three).toContain(">3</span>");+ const none = renderStatic(+ createElement(ToolbarTrigger, { glyph: "M12 5v14", ariaLabel: "Skills", badge: 0 }),+ );+ expect(classTokens(none)).not.toContain("tabular-nums");+ });++ it("as a pill shows its value, hidden on a narrow card, with the caret", () => {+ const html = renderStatic(+ createElement(ToolbarTrigger, {+ glyph: "M12 5v14",+ label: "High",+ caret: true,+ ariaLabel: "Thinking level",+ tooltip: "Thinking level: High",+ expanded: false,+ }),+ );+ expect(html).toContain('aria-label="Thinking level"');+ expect(html).toContain('data-tooltip="Thinking level: High"');+ expect(html).toContain('aria-expanded="false"');+ expect(html).toContain(">High</span>");+ expect(classTokens(html)).toEqual(expect.arrayContaining(["hidden", "@md:block", "max-w-36"]));+ });+});diff --git a/packages/ui/test/context-ring.test.ts b/packages/ui/test/context-ring.test.tsnew file mode 100644index 00000000..f0f5cad0--- /dev/null+++ b/packages/ui/test/context-ring.test.ts@@ -0,0 +1,65 @@+/**+ * The composer's context ring (src/components/chat/context-ring/context-ring.tsx): one arc of the+ * context's fill in the muted ink, turning to attention past 80 % and to danger past 95 %; an+ * unmeasured context an empty track, never a full-looking zero; the caller's words as its name+ * and tooltip, once, on the square that holds it — a named image, or the button its panel opens+ * from.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ContextRing, contextRingTone } from "../src/components/chat/context-ring/context-ring";+import { classTokens, renderStatic } from "../src/testing";++type Props = Parameters<typeof ContextRing>[0];+const ring = (props: Props) => renderStatic(createElement(ContextRing, props));++describe("contextRingTone", () => {+ it("stays calm to 80 %, warns past it, and turns to danger past 95 %", () => {+ expect(contextRingTone(0)).toBeNull();+ expect(contextRingTone(0.8)).toBeNull();+ expect(contextRingTone(0.81)).toBe("attention");+ expect(contextRingTone(0.95)).toBe("attention");+ expect(contextRingTone(0.96)).toBe("danger");+ // Nothing measured is not a reading at all.+ expect(contextRingTone(0.99, true)).toBeNull();+ });+});++describe("ContextRing", () => {+ it("is a named image carrying its figures, named once", () => {+ const html = ring({ ratio: 0.4, label: "Context usage 40% · 51k/128k" });+ expect(html).toMatch(/^<span data-tooltip="Context usage 40% · 51k\/128k"/);+ expect(html).toContain('role="img"');+ // The ring inside is decoration: the square carries the one name and the one tooltip.+ expect(html.match(/data-tooltip=/g)).toHaveLength(1);+ expect(html).toContain('aria-hidden="true"');+ expect(classTokens(html)).toContain("text-fg-subtle");+ });++ it("inks the whole ring by the warning ladder", () => {+ expect(classTokens(ring({ ratio: 0.9, label: "x" }))).toContain("text-tone-attention-fg");+ expect(classTokens(ring({ ratio: 0.99, label: "x" }))).toContain("text-tone-danger-fg");+ });++ it("draws an unmeasured context as the empty track, in the calm ink", () => {+ const html = ring({ ratio: 0.99, unknown: true, label: "Context usage unknown" });+ expect(html).not.toContain('data-part="series"');+ expect(classTokens(html)).toContain("text-fg-subtle");+ });++ it("becomes the button its panel opens from, painting only the square on hover", () => {+ const html = ring({+ ratio: 0.5,+ label: "Context usage 50%",+ onClick: () => {},+ expanded: false,+ controls: "panel-1",+ });+ expect(html).toMatch(/^<button type="button"/);+ expect(html).toContain('aria-expanded="false"');+ expect(html).toContain('aria-controls="panel-1"');+ expect(classTokens(html)).toEqual(+ expect.arrayContaining(["h-8", "w-8", "hover:bg-surface-muted"]),+ );+ });+});diff --git a/packages/ui/test/hooks.test.ts b/packages/ui/test/hooks.test.tsindex 76102c18..9df599dc 100644--- a/packages/ui/test/hooks.test.ts+++ b/packages/ui/test/hooks.test.ts@@ -70,20 +70,22 @@ const APPENDIX_A = [* gallery frames as they are (the package itself renders none). A component is listed only while* it exists: the last test below fails on a host no scanned file declares.*- * Glass is for the layers that float over the page (the composer card, dialogs, menus, popovers,- * tooltips); the eyebrow and display rungs for the sidebar's list label and the page titles; live- * marks for the spinner, a pulsing state dot and the machines page's working marks; frames for- * the transcript's cards, the code block, the page's cards and a table that is its own box; the- * shell for the app layout; a decorative icon for the rows and headers whose label already says- * what the icon says (sidebar rows and group headers, a nav row's glyph in a rail, a menu row's- * glyph, a tab, an empty state) — a session row is not a host, its avatar and marks carry- * information; a tree for a file tree and a work group's steps; a field for a settings row;- * activity for the transcript's work in progress (the work group's header, a tool call, the- * thinking row).+ * Glass is for the layers that float over the page (the composer card and its slash list, dialogs,+ * menus, popovers, tooltips); the eyebrow and display rungs for the sidebar's list label and the page titles; live+ * marks for the spinner, a pulsing state dot, the machines page's working marks and the caret of+ * a reply still streaming in; frames for the transcript's cards, the code block, the page's cards+ * and a table that is its own box; the shell for the app layout; a decorative icon for the rows+ * and headers whose label already says what the icon says (sidebar rows and group headers, a nav+ * row's glyph in a rail, a menu row's glyph, a tab, an empty state) — a session row is not a host,+ * its avatar and marks carry information; a tree for a file tree and a work group's steps; a field+ * for a settings row; activity for the transcript's work in progress (the work group's header, a+ * tool call, the thinking row).*/const HOSTS: Readonly<Record<string, readonly string[]>> = {+ // The composer's card and the slash list that opens over it (W6) float with the menus."ui-glass": [- "ChatInput",+ "ComposerCard",+ "SlashMenu","Modal","Dropdown","Select",@@ -95,13 +97,12 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {],// `Text` carries it for its eyebrow role (W5), the one door a group label takes in new code."ui-eyebrow": ["Sidebar", "GroupHeader", "PagedDialog", "Text"],- // The page titles are `PageHeader`'s; the draft view's hero still writes its own until its- // wave (W6).+ // The page titles are `PageHeader`'s; the draft view's hero writes its own."ui-display": ["Heading", "PageHeader", "EmptyState", "DraftView"],- "ui-live": ["Spinner", "Dot", "Stepper", "MachineCard", "ProgressBar"],- // The transcript's cards and the code block, and the page-level boxes (W4): the card and a- // table that is its own box.- "ui-frame": ["ToolCallCard", "WorkGroup", "CodeBlock", "Card", "Table"],+ "ui-live": ["Spinner", "Dot", "Stepper", "MachineCard", "ProgressBar", "StreamingCaret"],+ // The transcript's cards (the tool call, the work group, the changes card at a Task's foot) and+ // the code block, and the page-level boxes (W4): the card and a table that is its own box.+ "ui-frame": ["ToolCallCard", "WorkGroup", "ChangesCard", "CodeBlock", "Card", "Table"],"ui-underline-nav": ["Tabs"],"ui-shell": ["AppLayout"],"ui-icon-decor": [@@ -131,7 +132,7 @@ const HOSTS: Readonly<Record<string, readonly string[]>> = {"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"],+ "ui-stream": ["AssistantText"],};/** CSS keywords that start with `ui-` and are not classes. */@@ -501,7 +502,7 @@ describe("the hook checks, on known shapes", () => {file("d.tsx",[- "export function AssistantReplyBody({ revealing }: { revealing: boolean }) {",+ "export function AssistantText({ revealing }: { revealing: boolean }) {"," return (",' <div className="ui-stream" data-state={revealing ? "streaming" : "done"}>'," <p>text</p>",diff --git a/packages/ui/test/menu-select.test.ts b/packages/ui/test/menu-select.test.tsnew file mode 100644index 00000000..1d005b25--- /dev/null+++ b/packages/ui/test/menu-select.test.ts@@ -0,0 +1,79 @@+/**+ * The toolbar select (src/components/chat/menu-select/menu-select.tsx): a toolbar trigger over a+ * portaled menu. The open panel's contents are `MenuSelectBody`, rendered here on their own (a+ * static render has no `document.body` to portal into): a title bar naming the control, rows that+ * stay plain buttons named by the choices, the check on the chosen one, toggles marked pressed,+ * a muted detail after a label, and a footnote or a settings footer under a rule.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { MenuSelect, MenuSelectBody } from "../src/components/chat/menu-select/menu-select";+import { classTokens, renderStatic } from "../src/testing";++const LEVELS = [+ { value: "low", label: "Low" },+ { value: "high", label: "High" },+];++describe("MenuSelectBody", () => {+ it("names the control in a title bar and checks the chosen row", () => {+ const html = renderStatic(+ createElement(MenuSelectBody<string>, {+ title: "Thinking level",+ options: LEVELS,+ value: "high",+ note: "Changing it costs the cached context.",+ }),+ );+ expect(html.indexOf("Thinking level")).toBeLessThan(html.indexOf("Low"));+ const rows = html.split("<button").slice(1);+ expect(rows).toHaveLength(2);+ // Plain buttons named by the choice: the pickers are found by these names.+ expect(rows.every((row) => !row.includes("role="))).toBe(true);+ expect(rows[0]).not.toContain("<svg");+ expect(rows[1]).toContain("<svg");+ expect(html.indexOf("High")).toBeLessThan(html.indexOf("Changing it costs"));+ expect(classTokens(html)).toEqual(expect.arrayContaining(["text-xs", "text-fg-subtle"]));+ });++ it("marks every toggle's state, and runs a muted detail after its label", () => {+ const html = renderStatic(+ createElement(MenuSelectBody<string>, {+ options: [+ { value: "image", label: "Image", detail: "Attach a picture" },+ { value: "goal", label: "Goal", detail: "Loop until done", disabled: true },+ ],+ value: ["goal"],+ multiple: true,+ footer: createElement("div", null, "SETTINGS"),+ }),+ );+ expect(html).toContain('aria-pressed="false"');+ expect(html).toContain('aria-pressed="true"');+ expect(html).toContain('<span class="text-fg-subtle">Attach a picture</span>');+ expect(html).toContain('disabled=""');+ expect(html.indexOf("Loop until done")).toBeLessThan(html.indexOf("SETTINGS"));+ });++ it("draws the caller's body in place of the rows", () => {+ const html = renderStatic(+ createElement(MenuSelectBody<string>, { children: createElement("p", null, "LIST") }),+ );+ expect(html).toBe("<p>LIST</p>");+ });+});++describe("MenuSelect", () => {+ it("renders only its trigger while closed, reporting the closed state", () => {+ const html = renderStatic(+ createElement(MenuSelect<string>, {+ trigger: { glyph: "M12 5v14", label: "High", caret: true, ariaLabel: "Thinking level" },+ options: LEVELS,+ value: "high",+ }),+ );+ expect(html).toContain('aria-label="Thinking level"');+ expect(html).toContain('aria-expanded="false"');+ expect(html).not.toContain("Low");+ });+});diff --git a/packages/ui/test/message-bubble.test.ts b/packages/ui/test/message-bubble.test.tsnew file mode 100644index 00000000..872278f6--- /dev/null+++ b/packages/ui/test/message-bubble.test.ts@@ -0,0 +1,95 @@+/**+ * MessageRow, MessageBubble, MessageImage and MessageMeta+ * (src/components/chat/message-bubble/message-bubble.tsx): what the person sent, on the right with+ * its footer under it, and the run's one-line notices. Every word arrives as a prop.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ICONS } from "../src/components/icons/icons";+import {+ MessageBubble,+ MessageImage,+ MessageMeta,+ MessageRow,+} from "../src/components/chat/message-bubble/message-bubble";+import { classTokens, renderStatic } from "../src/testing";++describe("MessageRow", () => {+ it("right-aligns a message and is the hover group its footer reveals on", () => {+ const turn = classTokens(renderStatic(createElement(MessageRow, null, "x")));+ expect(turn).toEqual(expect.arrayContaining(["group", "items-end", "my-4"]));+ const steer = classTokens(renderStatic(createElement(MessageRow, { spacing: "steer" }, "x")));+ expect(steer).toContain("my-2");+ });+});++describe("MessageBubble", () => {+ it("sets a prompt's text in a tinted bubble that wraps long tokens", () => {+ const html = renderStatic(createElement(MessageBubble, { variant: "user" }, "hello"));+ expect(classTokens(html)).toEqual(+ expect.arrayContaining(["bg-fill-neutral", "max-w-[88%]", "wrap-anywhere", "text-fg"]),+ );+ expect(html).toMatch(/<p [^>]*>hello<\/p><\/div>$/);+ });++ it("marks a steer with the person glyph and its label, with what it carried inside", () => {+ const html = renderStatic(+ createElement(+ MessageBubble,+ {+ variant: "steering",+ label: "Steering",+ media: createElement("img", { alt: "shot" }),+ attachments: createElement("p", null, "a.pdf"),+ },+ "go on",+ ),+ );+ expect(html).toContain(`d="${ICONS.user}"`);+ expect(html).toMatch(/>Steering<\/span>go on<\/p>/);+ expect(html.indexOf('alt="shot"')).toBeLessThan(html.indexOf("a.pdf"));+ });++ it("draws a notice in the muted ink, a reconnect in the attention ink with its controls last", () => {+ const quiet = renderStatic(createElement(MessageBubble, { variant: "notice" }, "Aborted"));+ expect(classTokens(quiet)).toEqual(expect.arrayContaining(["font-mono", "text-fg-muted"]));+ const html = renderStatic(+ createElement(+ MessageBubble,+ {+ variant: "notice",+ tone: "attention",+ actions: createElement("button", { type: "button" }, "Retry now"),+ },+ createElement("span", null, "Reconnecting"),+ ),+ );+ expect(classTokens(html)).toContain("text-tone-attention-fg");+ expect(html).toMatch(/<span>Reconnecting<\/span><span [^>]*><button [^>]*>Retry now<\/button>/);+ });+});++describe("MessageImage", () => {+ it("opens large on a click, on the inner radius of the bubble it sits in", () => {+ const html = renderStatic(createElement(MessageImage, { src: "/a.png", alt: "Image" }));+ expect(html).toMatch(/^<button type="button" class="block cursor-zoom-in">/);+ expect(classTokens(html)).toEqual(expect.arrayContaining(["max-h-48", "rounded-control"]));+ });+});++describe("MessageMeta", () => {+ it("shows the time and a copy button named by its label, revealed on the row's hover", () => {+ const html = renderStatic(+ createElement(MessageMeta, { time: "10:24", copy: { text: "hi", label: "Copy message" } }),+ );+ expect(html).toContain(">10:24</span>");+ expect(html).toContain('aria-label="Copy message"');+ expect(classTokens(html)).toEqual(+ expect.arrayContaining(["sm:opacity-0", "group-hover:opacity-100", "justify-end"]),+ );+ });++ it("has no copy button when there is nothing to copy", () => {+ expect(renderStatic(createElement(MessageMeta, { time: "10:24" }))).not.toContain("<button");+ });+});diff --git a/packages/ui/test/model-select.test.ts b/packages/ui/test/model-select.test.tsnew file mode 100644index 00000000..c0345c82--- /dev/null+++ b/packages/ui/test/model-select.test.ts@@ -0,0 +1,48 @@+/**+ * The model picker's trigger (src/components/chat/model-select/model-select.tsx): the composer's+ * pill or a dialog's form field, named and hinted by the caller, announcing the dialog it opens+ * and whether that is open; no logo where no provider is named.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ModelSelect } from "../src/components/chat/model-select/model-select";+import { classTokens, renderStatic } from "../src/testing";++describe("ModelSelect", () => {+ const trigger = (+ variant: "pill" | "form",+ provider: string | null = "openai",+ expanded = false,+ ) =>+ renderStatic(+ createElement(ModelSelect, {+ label: "GPT",+ provider,+ ariaLabel: "Choose model",+ tooltip: "Choose model: GPT",+ variant,+ expanded,+ onClick: () => {},+ }),+ );++ it("is the toolbar pill: the logo, the name hidden on a narrow card, the caret", () => {+ const html = trigger("pill");+ expect(html).toContain('aria-label="Choose model"');+ expect(html).toContain('data-tooltip="Choose model: GPT"');+ expect(html).toContain('aria-haspopup="dialog"');+ expect(html).toContain('aria-expanded="false"');+ expect(html).toContain(">GPT</span>");+ expect(classTokens(html)).toEqual(expect.arrayContaining(["@md:block", "max-w-44"]));+ expect(trigger("pill", "openai", true)).toContain('aria-expanded="true"');+ });++ it("is a dialog's form field, and draws no logo where no provider is named", () => {+ const named = trigger("form");+ expect(named).toContain('aria-label="Choose model"');+ expect(named).toContain('aria-haspopup="dialog"');+ expect(classTokens(named)).toContain("w-full");+ const svgs = (html: string) => html.match(/<svg/g)?.length ?? 0;+ expect(svgs(trigger("form", null))).toBe(svgs(named) - 1);+ });+});diff --git a/packages/ui/test/step-banner.test.ts b/packages/ui/test/step-banner.test.tsnew file mode 100644index 00000000..046620a2--- /dev/null+++ b/packages/ui/test/step-banner.test.ts@@ -0,0 +1,34 @@+/**+ * StepBanner (src/components/chat/step-banner/step-banner.tsx): the process banner opens while its+ * step runs and is a plain header once settled with no body; its title is sentence case on the+ * small rung, and as no step of the agent's work it carries no activity hook.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { StepBanner } from "../src/components/chat/step-banner/step-banner";+import type { StepBannerProps } from "../src/components/chat/step-banner/step-banner";+import { classTokens, renderStatic } from "../src/testing";++const banner = (props: Partial<StepBannerProps>) =>+ renderStatic(createElement(StepBanner, { state: "done", title: "Compacted", ...props }));++describe("StepBanner", () => {+ it("opens its body while running", () => {+ const html = banner({ state: "running", children: "tool groups" });+ expect(html).toContain('aria-expanded="true"');+ expect(html).toContain("tool groups");+ });++ it("is a plain header once settled with no body, its detail and duration after the title", () => {+ const html = banner({ detail: "12 tools", durationMs: 1500 });+ expect(html).not.toContain("aria-expanded");+ expect(html).toMatch(/>Compacted<\/span><span data-tooltip="12 tools"[^>]*>12 tools<\/span>/);+ expect(html).toContain(">1.5s</span>");+ });++ it("sets its title in sentence case, without the activity hook", () => {+ const tokens = classTokens(banner({ state: "running", children: "body" }));+ expect(tokens).not.toContain("uppercase");+ expect(tokens).not.toContain("ui-activity");+ });+});diff --git a/packages/web/test/stream-reveal.test.ts b/packages/ui/test/stream-reveal.test.tssimilarity index 83%rename from packages/web/test/stream-reveal.test.tsrename to packages/ui/test/stream-reveal.test.tsindex 8692b183..f4b8e63d 100644--- a/packages/web/test/stream-reveal.test.ts+++ b/packages/ui/test/stream-reveal.test.ts@@ -1,23 +1,25 @@/**- * 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 streaming reveal behind AssistantText (components/chat/assistant-text/): the theme's stream+ * tokens (stream-style.ts), the pacing (stream-reveal.ts) and the hook that drives it+ * (use-stream-reveal.ts).** 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.+ * suite runs no frame loop, so the hook's use of one is pinned against its source at the bottom;+ * the body's markup is assistant-text.test.ts.*/import { readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";+import { join } from "node:path";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";+} from "../src/components/chat/assistant-text/stream-style";+import type { StreamReveal } from "../src/tokens";import {REVEAL_MAX_LAG_MS,receiveText,@@ -26,8 +28,9 @@ import {startReveal,stepReveal,visibleLength,-} from "../src/features/chat/stream-reveal";-import type { RevealState } from "../src/features/chat/stream-reveal";+} from "../src/components/chat/assistant-text/stream-reveal";+import type { RevealState } from "../src/components/chat/assistant-text/stream-reveal";+import { SRC_DIR } from "./helpers/paths";const FRAME = 16;@@ -43,7 +46,7 @@ function showAt(state: RevealState,t: number,rate: number,- mode: StreamRevealMode,+ mode: StreamReveal,streaming = true,): { state: RevealState; shown: string } {let s = state;@@ -66,7 +69,7 @@ function play(opts: {closeAt: number;until: number;rate: number;- mode: StreamRevealMode;+ mode: StreamReveal;}): { t: number; shown: number; received: number }[] {let state = startReveal("", 0, { streaming: true, rate: opts.rate });let received = "";@@ -301,43 +304,15 @@ describe("revealCut (half-typed Markdown)", () => {});/**- * 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.+ * Source of the hook. The suite runs no frame loop, so the loop it drives 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/);- });+const hook = readFileSync(+ join(SRC_DIR, "components/chat/assistant-text/use-stream-reveal.ts"),+ "utf8",+);+describe("the reveal hook (source contract)", () => {it("drives the pacing from animation frames and cancels them on cleanup", () => {expect(hook).toContain("requestAnimationFrame(tick)");expect(hook).toContain("cancelAnimationFrame(frame)");diff --git a/packages/ui/test/subagent-chip.test.ts b/packages/ui/test/subagent-chip.test.tsnew file mode 100644index 00000000..3879cb15--- /dev/null+++ b/packages/ui/test/subagent-chip.test.ts@@ -0,0 +1,38 @@+/**+ * SubagentChip (src/components/chat/subagent-chip/subagent-chip.tsx): the row is named by the+ * caller (the name folds in the waiting state), and its spinner and attention dot are decoration+ * beside that name.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { SubagentChip } from "../src/components/chat/subagent-chip/subagent-chip";+import { renderStatic } from "../src/testing";++const chip = (running: boolean, pending: boolean) =>+ renderStatic(+ createElement(SubagentChip, {+ label: "Researcher",+ name: pending ? "Subagent Researcher · Awaiting approval" : "Subagent Researcher",+ avatarId: "researcher",+ tag: "a1b2",+ running,+ pending,+ }),+ );++describe("SubagentChip", () => {+ it("is a button named by the caller, showing the agent and the short id", () => {+ const html = chip(false, false);+ expect(html).toMatch(/^<button type="button" aria-label="Subagent Researcher"/);+ expect(html).toContain(">Researcher</span>");+ expect(html).toContain(">a1b2</span>");+ expect(html).not.toContain('data-live="spinner"');+ });++ it("shows a hidden spinner while running and a hidden dot while an approval waits", () => {+ const html = chip(true, true);+ expect(html).toContain('aria-label="Subagent Researcher · Awaiting approval"');+ expect(html).toMatch(/<span aria-hidden="true" class="[^"]*"><svg role="status"/);+ expect(html).toMatch(/<span aria-hidden="true" style="width:6px;height:6px"/);+ });+});diff --git a/packages/ui/test/tag-input.test.ts b/packages/ui/test/tag-input.test.tsnew file mode 100644index 00000000..1d91c76d--- /dev/null+++ b/packages/ui/test/tag-input.test.ts@@ -0,0 +1,89 @@+/**+ * The chips with remove buttons (src/components/forms/tag-input/tag-input.tsx): a chip names what+ * it stands for and takes itself back with a × the caller names; its label gives way while a+ * suffix stays whole; a chip holding a control keeps its tooltip off the control; the two weights+ * space their rows apart.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { Chip, TagInput } from "../src/components/forms/tag-input/tag-input";+import { classTokens, renderStatic } from "../src/testing";++describe("Chip", () => {+ it("names its remove button with the caller's words, and has none without them", () => {+ const removable = renderStatic(+ createElement(Chip, { label: "notes.md", removeLabel: "Remove notes.md" }),+ );+ expect(removable).toContain('aria-label="Remove notes.md"');+ expect(removable).toContain(">×</button>");+ const fixed = renderStatic(createElement(Chip, { label: "notes.md" }));+ expect(fixed).not.toContain("<button");+ });++ it("truncates the label and keeps the suffix and the readout whole after it", () => {+ const html = renderStatic(+ createElement(Chip, {+ label: "server.ts",+ suffix: ":12-30",+ meta: "4 KB",+ tooltip: "src/server.ts:12-30",+ mono: true,+ }),+ );+ expect(html).toContain('data-tooltip="src/server.ts:12-30"');+ expect(html).toContain('<span class="min-w-0 truncate">server.ts</span>');+ expect(html).toContain('<span class="shrink-0">:12-30</span>');+ expect(html.indexOf("server.ts<")).toBeLessThan(+ html.indexOf('<span class="shrink-0">:12-30</span>'),+ );+ expect(classTokens(html)).toEqual(+ expect.arrayContaining(["font-mono", "bg-fill-neutral", "text-fg-subtle"]),+ );+ });++ it("with a control, names the label part alone and parts it from the control with a rule", () => {+ const html = renderStatic(+ createElement(Chip, {+ label: "Goal",+ tooltip: "Keep working until it is done",+ control: createElement("button", { type: "button" }, "Budget"),+ }),+ );+ const tooltip = html.indexOf('data-tooltip="Keep working until it is done"');+ expect(tooltip).toBeGreaterThan(html.indexOf("<span"));+ expect(html.startsWith("<span data-tooltip=")).toBe(false);+ expect(html).toContain('aria-hidden="true"');+ expect(html.indexOf("Goal")).toBeLessThan(html.indexOf("Budget"));+ expect(classTokens(html)).toContain("max-w-full");+ });+});++describe("TagInput", () => {+ const chips = [+ { key: "a", label: "alpha", removeLabel: "Remove alpha" },+ { key: "b", label: "beta" },+ ];++ it("draws each chip in order, between the caller's leading and trailing chips", () => {+ const html = renderStatic(+ createElement(TagInput, {+ chips,+ leading: createElement("i", null, "FIRST"),+ trailing: createElement("i", null, "LAST"),+ }),+ );+ const order = ["FIRST", "alpha", "beta", "LAST"].map((s) => html.indexOf(s));+ expect(order).toEqual([...order].sort((x, y) => x - y));+ expect(html.match(/<button/g)).toHaveLength(1);+ });++ it("packs soft chips tight and spaces bordered ones wider", () => {+ const soft = classTokens(renderStatic(createElement(TagInput, { chips })));+ expect(soft).toEqual(expect.arrayContaining(["gap-1", "bg-fill-neutral"]));+ const outline = classTokens(+ renderStatic(createElement(TagInput, { chips, variant: "outline" })),+ );+ expect(outline).toEqual(expect.arrayContaining(["gap-2", "border", "border-line"]));+ expect(outline).not.toContain("bg-fill-neutral");+ });+});diff --git a/packages/ui/test/thinking-block.test.ts b/packages/ui/test/thinking-block.test.tsnew file mode 100644index 00000000..4b7b4024--- /dev/null+++ b/packages/ui/test/thinking-block.test.ts@@ -0,0 +1,39 @@+/**+ * ThinkingBlock (src/components/chat/thinking-block/thinking-block.tsx): a thinking step for the+ * activity hook, its state named by the caller's label, its stop reason shown when it failed. The+ * expanded body's classes are the web app's `disclosure-body` test.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { ThinkingBlock } from "../src/components/chat/thinking-block/thinking-block";+import type { ThinkingBlockProps } from "../src/components/chat/thinking-block/thinking-block";+import { renderStatic } from "../src/testing";++const row = (props: Partial<ThinkingBlockProps>) =>+ renderStatic(+ createElement(ThinkingBlock, {+ state: "done",+ stateLabel: "Done",+ label: "Thinking",+ text: "the plan",+ durationMs: 800,+ ...props,+ }),+ );++describe("ThinkingBlock", () => {+ it("is a collapsed thinking step with its settled duration", () => {+ const html = row({});+ expect(html).toMatch(/class="ui-activity [^"]*" data-kind="thinking" data-state="done"/);+ expect(html).toContain('aria-label="Done"');+ expect(html).toMatch(/data-slot="label"[^>]*>Thinking</);+ expect(html).toContain(">800ms</span>");+ expect(html).not.toContain("the plan");+ });++ it("reads a failed step as an error and shows why it stopped", () => {+ const html = row({ state: "failed", stateLabel: "aborted", stopReason: "aborted" });+ expect(html).toContain('data-state="error"');+ expect(html).toContain(">[aborted]</span>");+ });+});diff --git a/packages/ui/test/token-contract.test.ts b/packages/ui/test/token-contract.test.tsindex 942f40ce..e90a55f8 100644--- a/packages/ui/test/token-contract.test.ts+++ b/packages/ui/test/token-contract.test.ts@@ -336,9 +336,10 @@ 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, plus the streaming pair- // (2026-09-30), plus the update mark's fill (W1, the same day).- expect(TOKEN_NAMES.length).toBe(235);+ // the bar outline's three, plus the knob's hairline edge (2026-09-30), plus the update+ // mark's fill (W1, the same day), plus the streaming pair (the same day), plus the neutral+ // fill of bubbles and chips (W6, the same day).+ expect(TOKEN_NAMES.length).toBe(236);});it("adds the structure group behind the tree and field hooks (round 2)", () => {diff --git a/packages/ui/test/tool-call-card.test.ts b/packages/ui/test/tool-call-card.test.tsnew file mode 100644index 00000000..b68ecf68--- /dev/null+++ b/packages/ui/test/tool-call-card.test.ts@@ -0,0 +1,84 @@+/**+ * ToolCallCard (src/components/chat/tool-call-card/tool-call-card.tsx) and the approval block it+ * holds (src/components/chat/approval-block/approval-block.tsx): the activity hook's markup, the+ * chevron named in the interface's words, and a waiting call's block — on screen while the card+ * is collapsed, with the preview, the payload and the two decisions in the caller's words.+ */+import { createElement } from "react";+import type { ReactElement } from "react";+import { describe, expect, it } from "vitest";+import { ToolCallCard } from "../src/components/chat/tool-call-card/tool-call-card";+import type { ToolCallCardProps } from "../src/components/chat/tool-call-card/tool-call-card";+import { DEFAULT_UI_STRINGS, UiStringsProvider } from "../src/strings";+import { renderStatic } from "../src/testing";++const zh = { ...DEFAULT_UI_STRINGS, expand: "展开", collapse: "折叠" };+const inZh = (element: ReactElement) =>+ renderStatic(createElement(UiStringsProvider, { strings: zh }, element));++const card = (props: Partial<ToolCallCardProps>) =>+ inZh(+ createElement(ToolCallCard, {+ state: "done",+ stateLabel: "Done",+ name: "Run command",+ nameTooltip: "exec_command",+ argumentsText: '{"cmd":"ls -la"}',+ ...props,+ }),+ );++describe("ToolCallCard", () => {+ it("is a tool step for the activity hook, its name the label slot", () => {+ const html = card({ state: "running", subtitle: "List the files" });+ expect(html).toMatch(/class="ui-activity [^"]*" data-kind="tool" data-state="running"/);+ expect(html).toMatch(/data-tooltip="exec_command"[^>]*data-slot="label"[^>]*>Run command</);+ expect(html).toMatch(/data-slot="detail"[^>]*>List the files</);+ expect(html).toContain('data-slot="progress"');+ });++ it("starts collapsed, its chevron named for what pressing it does", () => {+ const html = card({});+ expect(html).toContain('aria-expanded="false" aria-label="展开"');+ expect(html).not.toContain("ls -la");+ });++ it("reads a waiting call's approval as a running step, with no progress slot", () => {+ const html = card({ state: "waiting" });+ expect(html).toContain('data-state="running"');+ expect(html).not.toContain('data-slot="progress"');+ });++ it("shows a live clock with no known start as a still ellipsis", () => {+ const html = card({ state: "running", duration: { live: true } });+ expect(html).toMatch(/data-slot="detail"[^>]*>…</);+ expect(html).not.toContain("animate-pulse");+ });++ it("shows a waiting call's approval block while collapsed, in the caller's words", () => {+ const html = card({+ state: "waiting",+ pending: {+ preview: "$ ls -la",+ payload: "file_path: a.txt",+ onDecide: async () => {},+ labels: { allow: "允许", deny: "拒绝" },+ },+ });+ expect(html).toContain('aria-expanded="false"');+ expect(html).toContain(">$ ls -la</span>");+ expect(html).toContain("file_path: a.txt</pre>");+ expect(html).toMatch(/<button[^>]*>允许<\/button>/);+ expect(html).toMatch(/<button[^>]*>拒绝<\/button>/);+ });++ it("holds the marker or the action at the row's end, and the footer below", () => {+ expect(card({ marker: "background" })).toContain(">background</span>");+ const html = card({+ action: { label: "Send to background", hint: "Keep it running", onClick: () => {} },+ footer: "subagent row",+ });+ expect(html).toMatch(/data-tooltip="Keep it running"[^>]*>Send to background<\/button>/);+ expect(html).toContain("subagent row");+ });+});diff --git a/packages/ui/test/work-group.test.ts b/packages/ui/test/work-group.test.tsnew file mode 100644index 00000000..b0ac47f3--- /dev/null+++ b/packages/ui/test/work-group.test.ts@@ -0,0 +1,59 @@+/**+ * WorkGroup (src/components/chat/work-group/work-group.tsx): the frame, activity and tree hooks'+ * markup, and the expand policy's first render — open while running, closed once done, forced+ * open by a pending approval. The app's container decides the state; this reads what it draws.+ */+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { WorkGroup } from "../src/components/chat/work-group/work-group";+import type { WorkGroupProps } from "../src/components/chat/work-group/work-group";+import { renderStatic } from "../src/testing";++const group = (props: Partial<WorkGroupProps>) =>+ renderStatic(+ createElement(WorkGroup, {+ running: false,+ stepRunning: false,+ kind: "tool",+ title: "Done",+ rows: [+ { key: 1, content: "first step" },+ { key: 2, content: "second step" },+ ],+ ...props,+ }),+ );++describe("WorkGroup", () => {+ it("opens while running, with the rows one tree level under the header and the last one marked", () => {+ const html = group({ running: true, stepRunning: true, title: "Running", count: "2 steps" });+ expect(html).toMatch(/<div class="ui-frame [^"]*"><button type="button" data-group-header/);+ expect(html).toContain('aria-expanded="true"');+ expect(html).toContain('data-slot="head" data-kind="tool" data-state="running"');+ expect(html).toContain(">Running</span>");+ expect(html).toContain(">2 steps</span>");+ expect(html).toContain('data-slot="progress"');+ expect(html).toMatch(/<div data-slot="body" class="ui-tree [^"]*">/);+ expect(html).toContain('<div data-depth="1">first step</div>');+ expect(html).toContain('<div data-depth="1" data-last="true">second step</div>');+ });++ it("starts collapsed once done, and settles its duration with no progress slot", () => {+ const html = group({ durationMs: 2300 });+ expect(html).toContain('aria-expanded="false"');+ expect(html).toContain('data-state="done"');+ expect(html).toContain(">2.3s</span>");+ expect(html).not.toContain('data-slot="progress"');+ expect(html).not.toContain("first step");+ });++ it("is forced open by a pending approval, whose buttons live in the body", () => {+ const html = group({ pending: true });+ expect(html).toContain('aria-expanded="true"');+ expect(html).toContain("first step");+ });++ it("names a group of thinking only as thinking work", () => {+ expect(group({ kind: "thinking" })).toContain('data-kind="thinking"');+ });+});diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex 7e3cccd0..7b03a960 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -46,7 +46,7 @@ import {dispatchChatDefaultsChanged,type ChatDefaultsChangedDetail,} from "../../features/chat/chat-defaults-event";-import { ModelSelect, modelLabel } from "../../features/chat/model-select";+import { ModelCatalogSelect, modelLabel } from "../../features/chat/model-select";import { SELECTABLE_THINKING_LEVELS } from "../../features/chat/thinking-level";import { WorkspaceSelect } from "../../features/chat/workspace-select";import { sameModelRef } from "../../features/models/model-grouping";@@ -498,7 +498,7 @@ function MembersSection({ projectId, isOwner }: { projectId: string; isOwner: bo* delete zone): the `[default_chat]` block (Agent / Workspace / approval mode / thinking* level) plus the Project's default model, laid out as a compact responsive two-column* grid. Workspace and model reuse the chat draft's own pickers — WorkspaceSelect (the- * folder finder, a modal stacked on this one) and ModelSelect (the composer's model+ * folder finder, a modal stacked on this one) and ModelCatalogSelect (the composer's model* picker, a dialog too) — with their `form` trigger variant, so the controls line up with* the dialog's Input/Select while what they open stays exactly the composer's.* The model default is SINGLE-SOURCED with the models page — the picker renders and writes@@ -700,7 +700,7 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne<>{/* The composer's model picker (provider logo + name, opening the model-pickerdialog); the default row carries the S.models.default marker. */}- <ModelSelect+ <ModelCatalogSelectmodels={models.models}value={modelRef}defaultModel={models.defaultModel}diff --git a/packages/web/src/features/benchmark/use-benchmark-modal.tsx b/packages/web/src/features/benchmark/use-benchmark-modal.tsxindex 0651ffdc..1f4db3cd 100644--- a/packages/web/src/features/benchmark/use-benchmark-modal.tsx+++ b/packages/web/src/features/benchmark/use-benchmark-modal.tsx@@ -8,7 +8,7 @@* Send stays the user's move. A Benchmark can score several agents, so which one is under test* is a choice here; the baseline and the default target follow that choice. The model of the* conversation that carries the work out is picked with the Project settings' own model picker- * (ModelSelect in its form variant, the one the new-chat defaults and the schedule form use),+ * (ModelCatalogSelect in its form variant, the one the new-chat defaults and the schedule form use),* preset to the Project's default model. The new conversation opens with the Skills its tab* rests on preselected — the evaluator on both tabs, the optimizer on its own — so the* `[use_skills]` block names them on send and the model reads them before it acts; a model@@ -42,7 +42,7 @@ import { S } from "../../lib/strings";import { formatScore } from "../../lib/format";import { agentDisplayName, useProject } from "../../state/project";import { PromptFold, composeAiPrompt, pickDefaultAgent, useAiBridge } from "../ai-create";-import { ModelSelect } from "../chat/model-select";+import { ModelCatalogSelect } from "../chat/model-select";import { defaultTargetScore, latestScoreOfAgent } from "./benchmark-metrics";import { MAX_RUNS, evaluateTail, optimizeTail } from "./benchmark-prompts";import type { EvaluateParams, OptimizeParams } from "./benchmark-prompts";@@ -205,7 +205,7 @@ export function UseBenchmarkModal({{models !== null && models.models.length === 0 ? (<p className="text-xs text-gray-400">{S.models.empty}</p>) : (- <ModelSelect+ <ModelCatalogSelectmodels={models?.models ?? []}value={modelRef}{...(defaultModel !== undefined ? { defaultModel } : {})}diff --git a/packages/web/src/features/chat/agent-topology-view.tsx b/packages/web/src/features/chat/agent-topology-view.tsxindex 75371617..5796a880 100644--- a/packages/web/src/features/chat/agent-topology-view.tsx+++ b/packages/web/src/features/chat/agent-topology-view.tsx@@ -7,9 +7,8 @@* Each child node shows its wall-clock elapsed time (ticking while it runs, frozen at its last* activity when done — never a sum of its items); the root carries no stamps and shows none.*/-import { AgentAvatar, LiveDuration, StatusIcon } from "@prismshadow/penguin-ui";+import { AgentAvatar, DurationSlot, StatusIcon } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";-import { humanizeDuration } from "../../lib/format";import { layoutTopology, NODE_H, NODE_W } from "./agent-topology";import type { TopologyNode } from "./agent-topology";@@ -66,7 +65,7 @@ export function AgentTopologyView({data-tooltip={tooltip}onClick={() => onSelect(node)}style={{ left: x, top: y, width: NODE_W, height: NODE_H }}- className={`absolute flex flex-col justify-center gap-0.5 rounded-md border bg-white px-2 text-left transition-colors duration-150 dark:bg-gray-900 ${+ className={`absolute flex flex-col justify-center gap-px rounded-md border bg-white px-2 text-left transition-colors duration-150 dark:bg-gray-900 ${selected? "border-brand-500 ring-1 ring-brand-500": "border-gray-200 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-700 dark:hover:border-gray-600 dark:hover:bg-gray-800/60"@@ -80,17 +79,13 @@ export function AgentTopologyView({{/* Elapsed: ticking from first appearance while running, frozen at the settledspan when done; omitted when the stamps are unknown (always for the root).Decorative next to the label — the aria-label pins the accessible name. */}- {node.running- ? node.startedMs !== undefined && (- <span className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">- <LiveDuration sinceMs={node.startedMs} />- </span>- )- : node.elapsedMs !== undefined && (- <span className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">- {humanizeDuration(node.elapsedMs)}- </span>- )}+ {(node.running ? node.startedMs !== undefined : node.elapsedMs !== undefined) && (+ <DurationSlot+ running={node.running}+ sinceMs={node.startedMs}+ durationMs={node.elapsedMs}+ />+ )}{/* Status is already part of the button's accessible name: keep the glyph decorative. */}<StatusIcon state={node.running ? "running" : "done"} size="xs" /></span>@@ -100,7 +95,7 @@ export function AgentTopologyView({Nodes without one (the root, a standalone child, an omitted description) dropthe line and the single row centers itself in the box instead. */}{node.description !== null && (- <span className="w-full truncate pl-[24px] text-[10px] leading-tight text-gray-400 dark:text-gray-500">+ <span className="w-full truncate pl-[24px] text-xs leading-tight text-fg-subtle">{node.description}</span>)}diff --git a/packages/web/src/features/chat/approval-buttons.tsx b/packages/web/src/features/chat/approval-buttons.tsxdeleted file mode 100644index b09fd1c8..00000000--- a/packages/web/src/features/chat/approval-buttons.tsx+++ /dev/null@@ -1,40 +0,0 @@-/**- * Approval buttons: appear on the- * corresponding tool card when always-ask is set and there's a pending approval; the decision- * is submitted via POST /api/sessions/:s/approvals/:toolCallId.- */-import { useState } from "react";-import { Button } from "@prismshadow/penguin-ui";-import { S } from "../../lib/strings";--export function ApprovalButtons({- onDecide,-}: {- onDecide: (decision: "allow" | "deny") => Promise<void>;-}) {- const [busy, setBusy] = useState(false);-- const decide = async (decision: "allow" | "deny") => {- setBusy(true);- try {- await onDecide(decision);- } finally {- setBusy(false);- }- };-- // Text at every breakpoint (per review): action buttons the user presses must read as words —- // "Allow" and "Deny" — never as bare glyphs; iconic shorthand is reserved for- // passive indicators. The buttons live on their own row under the (wrapping) argument- // preview, so the words cost no width the pending card doesn't already have.- return (- <div className="flex items-center gap-2">- <Button size="sm" variant="primary" disabled={busy} onClick={() => void decide("allow")}>- {S.chat.approve}- </Button>- <Button size="sm" disabled={busy} onClick={() => void decide("deny")}>- {S.chat.deny}- </Button>- </div>- );-}diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 54bfe314..a5d0a317 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -7,8 +7,8 @@* indicator) + Model + send (up arrow);* In draft state (Session not yet created), when models/onChangeModel are supplied, the model* selector sits to the left of the send button (provider logo + name; it opens the model-picker- * dialog — search, provider-group rail, configured-key-first listing — see ModelSelect) — once- * the Session is created the model is locked, and the same spot switches to a read-only+ * dialog — search, provider-group rail, configured-key-first listing — see ModelCatalogSelect)+ * — once the Session is created the model is locked, and the same spot switches to a read-only* logo + name display;* Draft state also renders a thinking-level picker left of the model selector (backed by the* Agent settings: picking a level writes through to the Agent config and applies to the session@@ -63,6 +63,12 @@* phone viewport never pushes the action button off-screen.* Renders only the card body itself: outer positioning such as bottom-docking or vertical* centering is decided by the page.+ *+ * This module is the composer's container: the draft, sending, attachments, slash matching, IME,+ * paste and drop, history recall and the draft cache live here. What it draws with is the UI+ * package's composer family — `ComposerCard`, `ChipRow` and `Chip`, the `MenuSelect` pickers on+ * `ToolbarTrigger`s, `SendButton`, `SlashMenu` and `SlashPicker` — and the model picker bound to+ * the catalog (model-select.tsx) and the context gauge (context-gauge.tsx).*/import {useCallback,@@ -92,21 +98,27 @@ import {Button,CheckIcon,ChevronDown,+ Chip,+ ChipRow,+ ComposerCard,Dropdown,GlyphIcon,ICONS,- ICON_GAP,ICON_SIZE,- MenuItem,+ MenuSelect,NoticeStrip,PickerList,ProviderLogo,+ SendButton,+ SlashMenu,+ SlashPicker,+ TagInput,ZoomableImage,- menuPanelClass,noAutofill,toastError,toastInfo,} from "@prismshadow/penguin-ui";+import type { MenuSelectOption, TagInputChip } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { formatBytes, humanizeTokens } from "../../lib/format";import { useLocale } from "../../state/locale";@@ -118,7 +130,7 @@ import { SkillPickList } from "../skills/skill-pick-list";import { toggleSkillName } from "../skills/skill-selection";import { sameModelRef } from "../models/model-grouping";import { filterAgents, stagedSendRoute } from "./agent-handoff";-import { ModelSelect, modelLabel } from "./model-select";+import { ModelCatalogSelect, modelLabel } from "./model-select";import { ModelPickerModal } from "./model-picker-modal";import { matchSlash, removeSlashToken } from "./slash-token";import { SELECTABLE_THINKING_LEVELS, thinkingLevelLabel } from "./thinking-level";@@ -193,41 +205,6 @@ function AgentMenuList({);}-/**- * Popup frame of the `/agent` switch picker: the upward-opening panel and its title bar (`/model`- * opens the model-picker dialog instead). It opens upward from the composer and is height-capped to- * the room actually measured above it (see upwardMaxH), so it can never render off-screen; the- * panel has no trigger button of its own, so dismissal (click-outside / Escape) is handled by the- * host.- */-function SwitchPickerPanel({- panelRef,- maxHeight,- title,- children,-}: {- panelRef: RefObject<HTMLDivElement | null>;- maxHeight: number | undefined;- title: string;- children: ReactNode;-}) {- return (- <div- ref={panelRef}- style={{ maxHeight }}- className="anim-pop absolute bottom-full left-0 z-40 mb-1.5 flex w-80 max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-md border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-900"- >- <div className="border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400">- {title}- </div>- {children}- </div>- );-}--/** Spark glyph for the thinking-level picker (24x24 line path, consistent with the toolbar icon set). */-const SPARK_ICON = "M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9L12 3z";-/*** Conversation-time thinking-level picker, used in two places. Both variants list only the* concrete levels (per review: a title bar names the control; short names only, no@@ -260,56 +237,34 @@ function ThinkingLevelSelect({/** Footnote under the rows — the session variant's pre-pick reminder: a change applies right away but invalidates the model's cached context, so compacting first is recommended. */note?: string;}) {- const [open, setOpen] = useState(false);const label =value === null ? "…" : (thinkingLevelLabel(S.chat.thinkingLevelNames, value) ?? "—");+ // The one surface that annotates: a menu row is where the tier is CHOSEN, so it names the wire+ // value the pick will send. The trigger stays the plain name — in zh that is+ // 低/中/高/极高/最高, in en the annotation is a no-op. The title bar names the control; the+ // rows are the tiers.+ const options: MenuSelectOption<string>[] = SELECTABLE_THINKING_LEVELS.map((level) => ({+ value: level,+ label: S.chat.thinkingLevelMenuName(S.chat.thinkingLevelNames[level] ?? level, level),+ }));return (- <Dropdown- open={open}- setOpen={setOpen}- menuClass="w-max min-w-36"- portal={{ direction, align: "right" }}- button={- <button- type="button"- data-tooltip={`${S.chat.thinkingLevel}:${label}`}- aria-label={S.chat.thinkingLevel}- disabled={disabled || value === null}- onClick={() => setOpen(!open)}- className="flex h-8 max-w-36 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <GlyphIcon d={SPARK_ICON} className="shrink-0" />- {/* When the card is narrower than @md, only the icon remains (title shows the full state). */}- <span className="hidden min-w-0 truncate @md:block">{label}</span>- <ChevronDown size={ICON_SIZE.caretDense} />- </button>- }- >- {/* Title bar: names the control (the rows themselves are just the tier names). */}- <div className="border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400">- {S.chat.thinkingLevel}- </div>- {SELECTABLE_THINKING_LEVELS.map((level) => (- <MenuItem- key={level}- density="sm"- checked={level === value}- onSelect={() => {- onChange(level);- setOpen(false);- }}- // The one surface that annotates: a menu row is where the tier is CHOSEN, so it- // names the wire value the pick will send. The trigger above stays the plain- // name — in zh that is 低/中/高/极高/最高, in en the annotation is a no-op.- label={S.chat.thinkingLevelMenuName(S.chat.thinkingLevelNames[level] ?? level, level)}- />- ))}- {note && (- <div className="max-w-56 border-t border-gray-100 px-3 pb-1 pt-1.5 text-[11px] leading-snug text-gray-400 dark:border-gray-800 dark:text-gray-500">- {note}- </div>- )}- </Dropdown>+ <MenuSelect<string>+ trigger={{+ glyph: ICONS.sparkle,+ label,+ caret: true,+ ariaLabel: S.chat.thinkingLevel,+ tooltip: `${S.chat.thinkingLevel}:${label}`,+ disabled: disabled || value === null,+ }}+ title={S.chat.thinkingLevel}+ options={options}+ value={value}+ onChange={onChange}+ note={note}+ direction={direction}+ align="right"+ />);}@@ -326,9 +281,6 @@ function initialSteerMode(): SteerMode {return localStorage.getItem(STEER_MODE_KEY) === "followup" ? "followup" : "steer";}-/** Sliders icon (24×24 line path) for the mid-run send-mode settings row. */-const SLIDERS_ICON = "M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6";-/*** The mid-run send mode row, rendered as the "+" menu's settings footer: Steer (default) /* Queue as a follow-up, the full explanation hover-only via each pill's title (the toolbar's@@ -364,14 +316,14 @@ function SteerModeRow({);return (<div className="flex w-full items-center gap-2 px-3 py-1 text-xs">- <GlyphIcon d={SLIDERS_ICON} className="shrink-0 text-gray-400 dark:text-gray-500" />+ <GlyphIcon d={ICONS.sliders} className="shrink-0 text-gray-400 dark:text-gray-500" /><span className="min-w-0 flex-1 truncate text-gray-600 dark:text-gray-400">{S.chat.steerModeLabel}</span><divrole="group"aria-label={S.chat.steerModeLabel}- className="flex shrink-0 items-center gap-0.5"+ className="flex shrink-0 items-center gap-px">{modeButton("steer", S.chat.steerModeSteer, S.chat.steerModeSteerHint)}{modeButton("followup", S.chat.steerModeFollowUp, S.chat.steerModeFollowUpHint)}@@ -381,9 +333,8 @@ function SteerModeRow({}/**- * Multi-select skills dropdown (bottom toolbar, after approval mode): styled like the model- * selector — button = book icon + "Skills" label + selected-count badge (no badge at 0; when the- * card is narrower than @md the label hides, leaving just icon + badge); the menu body is the+ * Multi-select skills dropdown (bottom toolbar, after approval mode): the book icon in the ++ * button's square, the selected count on its corner (none at 0); the menu body is the* shared SkillPickList (search box + toggle rows), without its bulk row — picking skills to send* a message with is a per-message act on a handful of names, not a set to fill in. Multi-select* semantics: clicking a row toggles its selection and **the menu stays open**; closes on Escape /@@ -403,35 +354,20 @@ function SkillSelect({disabled: boolean;direction?: "up" | "down";}) {- const [open, setOpen] = useState(false);+ // Icon only, the + button's square; the selected count rides the corner (the chip row above+ // the input mirrors the selection too). The panel is unmounted while closed, so its search box+ // starts empty on every open. As wide as reasonably possible so descriptions stay readable;+ // portal placement clamps it to the viewport.return (- <Dropdown- open={open}- setOpen={setOpen}- // As wide as reasonably possible so descriptions stay readable; portal placement clamps- // it to the viewport, so the old hand-tuned anchor-offset clamps are no longer needed.+ <MenuSelect+ trigger={{+ glyph: BOOK_ICON,+ ariaLabel: S.chat.skillsSelect,+ badge: selected.length,+ disabled,+ }}+ direction={direction}menuClass="w-[26rem]"- portal={{ direction, align: "left" }}- button={- <button- type="button"- aria-label={S.chat.skillsSelect}- data-tooltip={S.chat.skillsSelect}- disabled={disabled}- // The panel is unmounted while closed, so its search box starts empty on every open.- onClick={() => setOpen(!open)}- // Icon only, the + button's square; the selected count rides the corner.- className="relative flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <GlyphIcon d={BOOK_ICON} size={15} className="shrink-0" />- {/* Selected-count badge (the chip row above the input mirrors the selection too). */}- {selected.length > 0 && (- <span className="absolute -top-0.5 -right-0.5 min-w-3.5 rounded-full bg-gray-200 px-1 text-center font-mono text-[9px] leading-3.5 font-semibold text-gray-700 dark:bg-gray-700 dark:text-gray-200">- {selected.length}- </span>- )}- </button>- }><SkillPickListskills={skills}@@ -439,17 +375,10 @@ function SkillSelect({onToggle={onToggle}emptyHint={S.chat.skillsEmptyHint}/>- </Dropdown>+ </MenuSelect>);}-/**- * Picture glyph (24×24 line path) for the "+" menu's image-upload entry: the framing rectangle- * and the mountain line as two subpaths of one `d`, since GlyphIcon renders a single `<path>`.- */-const IMAGE_ICON =- "M6 5h12a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM3 15l5-5 4 4 3-3 6 6";-/** One entry of the composer's "+" extension menu. */interface PlusMenuItem {key: string;@@ -480,52 +409,26 @@ function PlusMenu({footer?: ReactNode;direction?: "up" | "down";}) {- const [open, setOpen] = useState(false);+ // Every entry is a toggle marked while engaged, and a pick closes the menu before it acts —+ // an upload entry opens the file dialog, which must happen inside the click. The description+ // runs on after the name, muted, and is what gives way when the row runs out of room.return (- <Dropdown- open={open}- setOpen={setOpen}- // Placement is portal-driven like the rest of the toolbar (its scroll container would- // clip an absolutely-positioned panel); only size classes belong here.+ <MenuSelect+ trigger={{ glyph: ICONS.plus, ariaLabel: S.chat.plusMenu }}+ options={items.map((item) => ({+ value: item.key,+ glyph: item.icon,+ label: item.label,+ detail: item.desc,+ disabled: item.disabled ?? false,+ }))}+ value={items.filter((item) => item.active).map((item) => item.key)}+ multiple+ onChange={(key) => items.find((item) => item.key === key)?.onSelect()}+ footer={footer}+ direction={direction}menuClass="w-72"- portal={{ direction, align: "left" }}- button={- <button- type="button"- aria-label={S.chat.plusMenu}- data-tooltip={S.chat.plusMenu}- onClick={() => setOpen(!open)}- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- <GlyphIcon d={ICONS.plus} size={15} className="shrink-0" />- </button>- }- >- {items.map((item) => (- <MenuItem- key={item.key}- density="sm"- aria-pressed={item.active}- disabled={item.disabled}- checked={item.active}- onSelect={() => {- setOpen(false);- item.onSelect();- }}- glyph={item.icon}- // The description runs on after the name, muted, and is what gives way when the- // row runs out of room.- label={- <>- {item.label} <span className="text-gray-400 dark:text-gray-500">{item.desc}</span>- </>- }- />- ))}- {footer && (- <div className="mt-1 border-t border-gray-100 pt-1 dark:border-gray-800">{footer}</div>- )}- </Dropdown>+ />);}@@ -581,14 +484,6 @@ function steeringSummary(p: { text: string; images: number; files: number }): streturn parts.join(" \u00b7 ");}-/**- * Curved-back arrow glyph (24×24 line path) for the recall control: arrowhead at the left,- * the shaft looping back beneath it — the undo reading, not the trash-can one. A recalled- * message is not discarded, it comes back to the composer, and the icon has to say that on- * its own (owner directive: this control carries no text).- */-const RECALL_ICON = "M9 14L4 9l5-5M4 9h10.5a5.5 5.5 0 0 1 0 11H11";-/*** One queued-message hint line (undelivered steering / queued follow-up) with its recall* button (#287): the button withdraws the message server-side and puts its content back into@@ -623,7 +518,7 @@ function QueuedMessageLine({onClick={onRecall}className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-40 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200">- <GlyphIcon d={RECALL_ICON} size={13} />+ <GlyphIcon d={ICONS.undo} size={13} /></button>)}</div>@@ -2045,6 +1940,152 @@ export function ChatInput({const imageInputRef = useRef<HTMLInputElement>(null);const attachmentInputRef = useRef<HTMLInputElement>(null);+ /**+ * The staged chips the chip row lists: the /agent handoff target (the Agent avatar — the+ * identity tile used everywhere Agents are picked — and its id, so the chip reads as "this+ * goes to that Agent" without spelling the sentence out), the /model switch (provider logo and+ * model name, matching the composer's own model display; sending forks the conversation onto+ * it), and the selected skills.+ */+ const switchChips: TagInputChip[] = [+ ...(target !== null+ ? [+ {+ key: "target",+ label: target.agentId,+ mono: true,+ glyph: (+ <AgentAvatar+ id={target.agentId}+ name={agentDisplayName(target)}+ size={13}+ className="shrink-0 rounded-sm"+ />+ ),+ tooltip: S.chat.handoffTargetTitle(agentDisplayName(target)),+ removeLabel: S.chat.handoffRemove,+ },+ ]+ : []),+ ...(pendingModel !== null+ ? [+ {+ key: "model",+ label: modelLabel(pendingModel),+ glyph: (+ <ProviderLogo provider={pendingModel.provider} className="h-3.5 w-3.5 shrink-0" />+ ),+ tooltip: S.chat.modelSwitchTargetTitle(modelLabel(pendingModel)),+ removeLabel: S.chat.modelSwitchRemove,+ },+ ]+ : []),+ ...selectedSkills.map((name) => {+ const meta = skills.find((sk) => sk.name === name);+ return {+ key: `skill:${name}`,+ label: name,+ mono: true,+ glyph: <SkillIcon icon={meta?.icon} size={13} className="shrink-0 text-fg-muted" />,+ ...(meta ? { tooltip: localizedShortText(locale, meta) } : {}),+ removeLabel: `${S.chat.skillRemove} ${name}`,+ };+ }),+ ];+ /** A staged chip's ×: the switch chips hand the caret back to the text, a skill just drops. */+ const removeChip = (key: string) => {+ if (key === "target") {+ setTarget(null);+ onHandoffTargetChange?.(null);+ textareaRef.current?.focus();+ } else if (key === "model") {+ stageModel(null);+ textareaRef.current?.focus();+ } else if (key.startsWith("skill:")) {+ toggleSkill(key.slice("skill:".length));+ }+ };++ /** The goal chip's budget: a value button whose editor opens as a fixed upward popover. */+ const goalBudgetPicker = (+ <Dropdown+ open={goalBudgetOpen}+ setOpen={setGoalBudgetEditorOpen}+ onEscape={cancelGoalBudget}+ className="min-w-0"+ menuClass="bottom-full left-1/2 -ml-32 mb-2 w-64 max-w-[calc(100vw-2rem)] origin-bottom"+ button={+ <button+ type="button"+ aria-label={goalBudgetSummary}+ aria-expanded={goalBudgetOpen}+ onClick={() => setGoalBudgetEditorOpen(!goalBudgetOpen)}+ className="flex h-5 min-w-0 items-center gap-1 rounded px-1.5 text-xs text-gray-600 transition-colors duration-150 hover:bg-white/80 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white"+ >+ <span className="truncate">{goalBudgetSummary}</span>+ <ChevronDown size={ICON_SIZE.caretDense} />+ </button>+ }+ >+ <div className="px-3 py-2">+ <label+ htmlFor="goal-budget-input"+ className="block text-xs font-medium text-gray-700 dark:text-gray-200"+ >+ {S.chat.goalBudgetLabel}+ </label>+ <div className="mt-1.5 flex items-center gap-1.5">+ <input+ id="goal-budget-input"+ autoFocus+ value={goalBudgetDraft}+ onChange={(e) => setGoalBudgetDraft(e.target.value)}+ onFocus={(e) => e.currentTarget.select()}+ onKeyDown={(e) => {+ // Escape is handled at the window level (Dropdown onEscape →+ // cancelGoalBudget), so it cancels no matter where focus sits.+ if (e.key === "Enter") {+ e.preventDefault();+ e.stopPropagation();+ saveGoalBudget();+ }+ }}+ placeholder={S.chat.goalBudgetPlaceholder}+ aria-invalid={goalBudgetDraftInvalid}+ aria-describedby="goal-budget-hint"+ {...noAutofill}+ data-tooltip={goalBudgetDraftInvalid ? S.chat.goalBudgetInvalid : S.chat.goalBudgetHint}+ className={`min-w-0 flex-1 rounded-md border bg-white px-2 py-1 font-mono text-xs leading-5 placeholder:text-gray-400 focus:outline-none focus:ring-2 dark:bg-gray-950 dark:placeholder:text-gray-500 ${+ goalBudgetDraftInvalid+ ? "border-red-400 text-red-600 focus:border-red-500 focus:ring-red-400/20 dark:border-red-500 dark:text-red-400"+ : "border-gray-300 text-gray-800 focus:border-gray-500 focus:ring-gray-400/20 dark:border-gray-700 dark:text-gray-100 dark:focus:border-gray-500"+ }`}+ />+ <button+ type="button"+ aria-label={S.chat.goalBudgetSave}+ data-tooltip={S.chat.goalBudgetSave}+ disabled={goalBudgetDraftInvalid}+ onClick={saveGoalBudget}+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-35 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"+ >+ <CheckIcon size={14} />+ </button>+ </div>+ <p+ id="goal-budget-hint"+ className={`mt-1.5 text-xs leading-4 ${+ goalBudgetDraftInvalid+ ? "text-red-500 dark:text-red-400"+ : "text-gray-400 dark:text-gray-500"+ }`}+ >+ {goalBudgetDraftInvalid ? S.chat.goalBudgetInvalid : S.chat.goalBudgetHint}+ </p>+ </div>+ </Dropdown>+ );+return (<div className="relative" ref={anchorRef}>{/* Drag-and-drop upload: mounted with the composer (chat page and draft page alike, and@@ -2057,33 +2098,13 @@ export function ChatInput({scrolling, so a long skill list never pushes the menu's top edge out of view; the activerow keeps itself scrolled into view. */}{slashOpen && (- <div- style={{ maxHeight: upwardMaxH }}- className={`ui-glass ${menuPanelClass} absolute bottom-full left-0 z-40 mb-1.5 w-80 max-w-[calc(100vw-2rem)] overscroll-contain`}- >- {slashMatches.map((c, i) => (- <button- key={c.cmd}- type="button"- ref={c === activeSlash ? (el) => el?.scrollIntoView({ block: "nearest" }) : undefined}- onMouseEnter={() => setSlashIndex(i)}- onClick={() => c.run()}- className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm ${- c === activeSlash ? "bg-gray-100 dark:bg-gray-800" : ""- }`}- >- <span className="shrink-0 font-mono text-gray-800 dark:text-gray-200">{c.cmd}</span>- {/* Overly long descriptions (skill descriptions) are truncated: full text goes into the title. */}- <span- data-tooltip={c.desc}- data-tooltip-content="text"- className="min-w-0 flex-1 truncate text-xs text-gray-500 dark:text-gray-400"- >- {c.desc}- </span>- </button>- ))}- </div>+ <SlashMenu+ items={slashMatches.map((c) => ({ command: c.cmd, description: c.desc }))}+ active={Math.min(slashIndex, slashMatches.length - 1)}+ onActiveChange={setSlashIndex}+ onRun={(i) => slashMatches[i]?.run()}+ maxHeight={upwardMaxH}+ />)}{/* /model switch picker (session state): the same model-picker dialog the draft's model@@ -2108,17 +2129,13 @@ export function ChatInput({with the same staged semantics as /model — the pick becomes the target chip, andsending is what hands the conversation over. */}{agentSwitchOpen && (- <SwitchPickerPanel- panelRef={agentSwitchRef}- maxHeight={upwardMaxH}- title={S.chat.switchAgentTitle}- >+ <SlashPicker ref={agentSwitchRef} maxHeight={upwardMaxH} title={S.chat.switchAgentTitle}><AgentMenuListagents={agents}{...(currentAgentId !== undefined ? { currentAgentId } : {})}onPick={pickHandoffTarget}/>- </SwitchPickerPanel>+ </SlashPicker>)}{images.length > 0 && (@@ -2134,7 +2151,7 @@ export function ChatInput({type="button"aria-label={S.chat.removeImage}onClick={() => setImages((prev) => prev.filter((_, j) => j !== i))}- className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-gray-700 text-[10px] text-white transition-colors duration-150 hover:bg-gray-900"+ className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-gray-700 text-xs text-white transition-colors duration-150 hover:bg-gray-900">×</button>@@ -2148,33 +2165,19 @@ export function ChatInput({sanitizes it when writing to the scratchpad, and the message's banner then shows theon-disk name. */}{attachments.length > 0 && (- <div className="mb-2 flex flex-wrap gap-2">- {attachments.map((file, i) => (- <span- key={i}- data-tooltip={file.name}- className={`anim-pop flex max-w-56 items-center ${ICON_GAP.tight} rounded-md border border-gray-200 bg-gray-50 py-1 pl-2 pr-1 text-xs text-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200`}- >- <GlyphIcon- d={PAPERCLIP_ICON}- size={13}- className="shrink-0 text-gray-400 dark:text-gray-500"- />- <span className="min-w-0 truncate">{file.name}</span>- <span className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">- {formatBytes(file.size)}- </span>- <button- type="button"- aria-label={`${S.chat.removeFile} ${file.name}`}- onClick={() => setAttachments((prev) => prev.filter((_, j) => j !== i))}- className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"- >- ×- </button>- </span>- ))}- </div>+ <TagInput+ variant="outline"+ className="mb-2"+ chips={attachments.map((file, i) => ({+ key: String(i),+ label: file.name,+ glyph: <GlyphIcon d={PAPERCLIP_ICON} size={13} className="shrink-0 text-fg-subtle" />,+ meta: formatBytes(file.size),+ tooltip: file.name,+ removeLabel: `${S.chat.removeFile} ${file.name}`,+ }))}+ onRemove={(key) => setAttachments((prev) => prev.filter((_, j) => String(j) !== key))}+ />)}{/* The Agent's compaction threshold is above what this model can hold, so compaction fires@@ -2284,225 +2287,81 @@ export function ChatInput({))}+ {/* The hidden inputs behind the "+" menu's upload entries: kept mounted here (outside the+ menu, which unmounts its items on select) and clicked by those entries. The file picker+ has no `accept` — an attachment can be any type, the model reads it from disk. */}+ <input+ ref={imageInputRef}+ type="file"+ accept="image/*"+ multiple+ className="hidden"+ onChange={onPickFiles}+ />+ <input+ ref={attachmentInputRef}+ type="file"+ multiple+ disabled={goalOn}+ className="hidden"+ onChange={onPickAttachments}+ />+{/* Unified input card: the multi-line text body occupies the top area, with all controls- collected onto a single bottom row that never shares a line with the text.- @container: the bottom toolbar row collapses based on the **card's actual width**- (help text/button text visibility uses @md/@lg container breakpoints) — because the- card's width changes with the viewport and the Files panel squeezing it, viewport- breakpoints wouldn't judge it accurately. */}- <div className="ui-glass @container rounded-lg border border-gray-300 bg-white px-2.5 pb-2 pt-2 transition-[border-color,box-shadow] duration-200 focus-within:border-gray-500 focus-within:ring-2 focus-within:ring-gray-400/30 dark:border-gray-700 dark:bg-gray-900 dark:focus-within:border-gray-400">- {/* Chip row above the text body: the staged switch target (an /agent handoff or a- /model fork — never both), the selected skills, and whatever the Files panel has- contributed, all sharing the same chip look. Remove buttons recolor the x on hover- (no background wash). */}- {(target !== null ||+ collected onto a single bottom row that never shares a line with the text. The card+ collapses its toolbar by its own width (help text and button text hide under its+ container breakpoints) — the card's width changes with the viewport and with the Files+ panel squeezing it, so viewport breakpoints wouldn't judge it accurately. */}+ <ComposerCard+ chips={+ // Chip row above the text body: the goal chip, the staged switch target (an /agent+ // handoff or a /model fork — never both), the selected skills, and whatever the Files+ // panel has contributed, all sharing the same chip look.+ target !== null ||pendingModel !== null ||selectedSkills.length > 0 ||references.length > 0 ||- goalOn) && (- <div className="mb-1 flex flex-wrap items-center gap-1">- {/* Goal-mode chip: the budget stays compact as a value button; its editor is a- fixed upward popover so it never covers the objective textarea below. */}- {goalOn && (- <span className="anim-pop flex max-w-full items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200">- <span- className="flex shrink-0 items-center gap-1"- data-tooltip={S.chat.goalModeDesc}- >- <GlyphIcon d={GOAL_ICON} size={13} className="text-gray-500 dark:text-gray-400" />- <span>{S.chat.goalMode}</span>- </span>- <span- aria-hidden- className="mx-0.5 h-4 w-px shrink-0 bg-gray-300 dark:bg-gray-600"- />- <Dropdown- open={goalBudgetOpen}- setOpen={setGoalBudgetEditorOpen}- onEscape={cancelGoalBudget}- className="min-w-0"- menuClass="bottom-full left-1/2 -ml-32 mb-2 w-64 max-w-[calc(100vw-2rem)] origin-bottom"- button={- <button- type="button"- aria-label={goalBudgetSummary}- aria-expanded={goalBudgetOpen}- onClick={() => setGoalBudgetEditorOpen(!goalBudgetOpen)}- className="flex h-5 min-w-0 items-center gap-1 rounded px-1.5 text-xs text-gray-600 transition-colors duration-150 hover:bg-white/80 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-700 dark:hover:text-white"- >- <span className="truncate">{goalBudgetSummary}</span>- <ChevronDown size={ICON_SIZE.caretDense} />- </button>- }- >- <div className="px-3 py-2">- <label- htmlFor="goal-budget-input"- className="block text-xs font-medium text-gray-700 dark:text-gray-200"- >- {S.chat.goalBudgetLabel}- </label>- <div className="mt-1.5 flex items-center gap-1.5">- <input- id="goal-budget-input"- autoFocus- value={goalBudgetDraft}- onChange={(e) => setGoalBudgetDraft(e.target.value)}- onFocus={(e) => e.currentTarget.select()}- onKeyDown={(e) => {- // Escape is handled at the window level (Dropdown onEscape →- // cancelGoalBudget), so it cancels no matter where focus sits.- if (e.key === "Enter") {- e.preventDefault();- e.stopPropagation();- saveGoalBudget();- }- }}- placeholder={S.chat.goalBudgetPlaceholder}- aria-invalid={goalBudgetDraftInvalid}- aria-describedby="goal-budget-hint"- {...noAutofill}- data-tooltip={- goalBudgetDraftInvalid ? S.chat.goalBudgetInvalid : S.chat.goalBudgetHint- }- className={`min-w-0 flex-1 rounded-md border bg-white px-2 py-1 font-mono text-xs leading-5 placeholder:text-gray-400 focus:outline-none focus:ring-2 dark:bg-gray-950 dark:placeholder:text-gray-500 ${- goalBudgetDraftInvalid- ? "border-red-400 text-red-600 focus:border-red-500 focus:ring-red-400/20 dark:border-red-500 dark:text-red-400"- : "border-gray-300 text-gray-800 focus:border-gray-500 focus:ring-gray-400/20 dark:border-gray-700 dark:text-gray-100 dark:focus:border-gray-500"- }`}- />- <button- type="button"- aria-label={S.chat.goalBudgetSave}- data-tooltip={S.chat.goalBudgetSave}- disabled={goalBudgetDraftInvalid}- onClick={saveGoalBudget}- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:opacity-35 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"- >- <CheckIcon size={14} />- </button>- </div>- <p- id="goal-budget-hint"- className={`mt-1.5 text-[11px] leading-4 ${- goalBudgetDraftInvalid- ? "text-red-500 dark:text-red-400"- : "text-gray-400 dark:text-gray-500"- }`}- >- {goalBudgetDraftInvalid ? S.chat.goalBudgetInvalid : S.chat.goalBudgetHint}- </p>- </div>- </Dropdown>- <button- type="button"- aria-label={S.chat.goalRemove}- onClick={() => toggleGoal(false)}- className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"- >- ×- </button>- </span>- )}- {/* Staged /agent handoff target: the Agent avatar (the identity tile used- everywhere Agents are picked) + its id, so the chip reads as "this goes to that- Agent" without spelling the sentence out. */}- {target !== null && (- <span- data-tooltip={S.chat.handoffTargetTitle(agentDisplayName(target))}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"- >- <AgentAvatar- id={target.agentId}- name={agentDisplayName(target)}- size={13}- className="shrink-0 rounded-sm"- />- <span className="truncate">{target.agentId}</span>- <button- type="button"- aria-label={S.chat.handoffRemove}- onClick={() => {- setTarget(null);- onHandoffTargetChange?.(null);- textareaRef.current?.focus();- }}- className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"- >- ×- </button>- </span>- )}- {/* Staged /model switch: provider logo + model name, matching the composer's own- model display; sending forks the conversation onto it. */}- {pendingModel !== null && (- <span- data-tooltip={S.chat.modelSwitchTargetTitle(modelLabel(pendingModel))}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"- >- <ProviderLogo provider={pendingModel.provider} className="h-3.5 w-3.5 shrink-0" />- <span className="truncate">{modelLabel(pendingModel)}</span>- <button- type="button"- aria-label={S.chat.modelSwitchRemove}- onClick={() => {- stageModel(null);- textareaRef.current?.focus();- }}- className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"- >- ×- </button>- </span>- )}- {selectedSkills.map((name) => {- const meta = skills.find((sk) => sk.name === name);- return (- <span- key={name}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"- {...(meta ? { "data-tooltip": localizedShortText(locale, meta) } : {})}- >- <SkillIcon- icon={meta?.icon}- size={13}- className="shrink-0 text-gray-500 dark:text-gray-400"+ goalOn ? (+ <ChipRow+ leading={+ // Goal-mode chip: the budget stays compact as a value button; its editor is a+ // fixed upward popover so it never covers the objective textarea below.+ goalOn ? (+ <Chip+ label={S.chat.goalMode}+ glyph={<GlyphIcon d={GOAL_ICON} size={13} className="text-fg-muted" />}+ tooltip={S.chat.goalModeDesc}+ removeLabel={S.chat.goalRemove}+ onRemove={() => toggleGoal(false)}+ control={goalBudgetPicker}/>- <span className="truncate">{name}</span>- <button- type="button"- aria-label={`${S.chat.skillRemove} ${name}`}- onClick={() => toggleSkill(name)}- className="shrink-0 rounded p-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"- >- ×- </button>- </span>- );- })}- {/* Staged from the Files panel (a file, a directory, a quoted range) or from the- conversation's selection menu (an excerpt). The text itself never enters the- draft — the chip names what it points at, and the message carries it on send. */}- {references.map((reference, i) => (- <ReferenceChip- key={i}- reference={reference}- onRemove={() => {- setReferences((prev) => prev.filter((_, j) => j !== i));- textareaRef.current?.focus();- }}- />- ))}- </div>- )}-- {/* Multi-line input area (defaults to 2 lines, auto-grows, scrolls internally beyond the cap) */}- <textarea- ref={textareaRef}- rows={2}- value={text}- autoFocus={autoFocus}- onChange={(e) => {+ ) : undefined+ }+ chips={switchChips}+ onRemove={removeChip}+ trailing={+ // Staged from the Files panel (a file, a directory, a quoted range) or from the+ // conversation's selection menu (an excerpt). The text itself never enters the+ // draft — the chip names what it points at, and the message carries it on send.+ references.map((reference, i) => (+ <ReferenceChip+ key={i}+ reference={reference}+ onRemove={() => {+ setReferences((prev) => prev.filter((_, j) => j !== i));+ textareaRef.current?.focus();+ }}+ />+ ))+ }+ />+ ) : undefined+ }+ textarea={{+ ref: textareaRef,+ value: text,+ autoFocus,+ onChange: (e) => {const value = e.target.value;const caretNow = e.target.selectionStart ?? value.length;setText(value);@@ -2517,12 +2376,12 @@ export function ChatInput({const m = matchSlash(value, caretNow);return m && m.start === d ? d : null;});- }}+ },// Cursor movement (arrow keys/click) syncs to caret: the slash menu matches the token at the cursor.- onSelect={(e) => setCaret(e.currentTarget.selectionStart ?? 0)}- onKeyDown={onKeyDown}- onPaste={onPaste}- placeholder={+ onSelect: (e) => setCaret(e.currentTarget.selectionStart ?? 0),+ onKeyDown,+ onPaste,+ placeholder:running && followUpMode? narrow? S.chat.followUpPlaceholderShort@@ -2533,126 +2392,87 @@ export function ChatInput({: S.chat.steerPlaceholder: narrow? S.chat.inputPlaceholderShort- : S.chat.inputPlaceholder- }- // text-base, not the sm rung the form controls take: this is a full-height typing- // surface for prose the user composes and re-reads, not a field in a form, and the- // toolbar under it is already text-xs so the two do not compete.- className="block max-h-44 min-h-[60px] w-full resize-none bg-transparent px-1 py-0.5 font-sans text-base leading-6 placeholder:text-gray-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60 dark:placeholder:text-gray-500"- />-- {/* Bottom toolbar row — one line, two groups: the settings controls sit left, the- status/model/action controls right (`justify-between`). The left group is the only- one allowed to give way: `min-w-0` + horizontal scroll means a crowded phone- viewport scrolls those controls instead of pushing the right group (and with it the- action button) off-screen. The right group is `shrink-0` so the action button is- always reachable. */}- <div className="mt-1 flex items-center justify-between gap-2 text-xs">- <div className="no-scrollbar flex min-w-0 flex-1 items-center gap-2 overflow-x-auto">- {/* The image picker's actual input: kept mounted here (outside the menu, which- unmounts its items on select) and driven by the menu entry below. */}- <input- ref={imageInputRef}- type="file"- accept="image/*"- multiple- className="hidden"- onChange={onPickFiles}- />- {/* The file picker's actual input, same arrangement as the image one above; no- `accept` — an attachment can be any type, the model reads it from disk. */}- <input- ref={attachmentInputRef}- type="file"- multiple- disabled={goalOn}- className="hidden"- onChange={onPickAttachments}- />- {/* The three icon buttons — +, permission, skills — sit as one tight cluster: the- row's wider gap would read them as unrelated controls. */}- <div className="flex shrink-0 items-center gap-0.5">- {/* "+" extension menu, leading the row: input add-ons (image upload, file+ : S.chat.inputPlaceholder,+ }}+ tools={+ // The three icon buttons — +, permission, skills — sit as one tight cluster: the row's+ // wider gap would read them as unrelated controls.+ <>+ {/* "+" extension menu, leading the row: input add-ons (image upload, fileattachment, goal mode) plus the input settings footer (mid-run send mode —usable while running, which is exactly when it matters, so the button itselfnever disables). The uploads live in here rather than as their own toolbarbuttons: one 8x8 slot instead of three, which is the difference between thephone row scrolling and not. */}- {variant === "session" && (- <PlusMenu- items={[- {- key: "image",- icon: IMAGE_ICON,- label: S.chat.uploadImage,- // Without vision the images still send — as scratchpad file paths — so the- // entry stays usable and the hint says what will happen instead. Goal mode- // changes nothing here: a goal's images ride its first message as ordinary- // image input, so the model's vision decides how they arrive, exactly as- // for any other send.- desc: vision ? S.chat.uploadImageDesc : S.chat.imagesAsPathHint,- active: images.length > 0,- onSelect: () => imageInputRef.current?.click(),- },- {- key: "file",- icon: PAPERCLIP_ICON,- label: S.chat.uploadFile,- // The description doubles as the explanation of where the file ends up:- // it is filed into the session scratchpad and reached by path, never- // inlined into the conversation.- desc: S.chat.uploadFileDesc,- active: attachments.length > 0,- // Unlike images, a file cannot ride a goal: the server refuses file- // attachments on a goal request.- disabled: goalOn,- onSelect: () => attachmentInputRef.current?.click(),- },- {- key: "goal",- icon: GOAL_ICON,- label: S.chat.goalMode,- desc: S.chat.goalModeDesc,- active: goalOn,- disabled: running || compacting || busy,- onSelect: () => toggleGoal(!goalOn),- },- ]}- footer={<SteerModeRow steerMode={steerMode} onChangeSteerMode={setSteerMode} />}- direction={models && onChangeModel ? "down" : "up"}- />- )}- <PermissionSelect- approvalMode={approvalMode}- approvalModes={approvalModes}- sandbox={sandbox}- onChangeApprovalMode={onChangeApprovalMode}- onChangeSandbox={onChangeSandbox}- disabled={modeSaving}+ {variant === "session" && (+ <PlusMenu+ items={[+ {+ key: "image",+ icon: ICONS.image,+ label: S.chat.uploadImage,+ // Without vision the images still send — as scratchpad file paths — so the+ // entry stays usable and the hint says what will happen instead. Goal mode+ // changes nothing here: a goal's images ride its first message as ordinary+ // image input, so the model's vision decides how they arrive, exactly as+ // for any other send.+ desc: vision ? S.chat.uploadImageDesc : S.chat.imagesAsPathHint,+ active: images.length > 0,+ onSelect: () => imageInputRef.current?.click(),+ },+ {+ key: "file",+ icon: PAPERCLIP_ICON,+ label: S.chat.uploadFile,+ // The description doubles as the explanation of where the file ends up:+ // it is filed into the session scratchpad and reached by path, never+ // inlined into the conversation.+ desc: S.chat.uploadFileDesc,+ active: attachments.length > 0,+ // Unlike images, a file cannot ride a goal: the server refuses file+ // attachments on a goal request.+ disabled: goalOn,+ onSelect: () => attachmentInputRef.current?.click(),+ },+ {+ key: "goal",+ icon: GOAL_ICON,+ label: S.chat.goalMode,+ desc: S.chat.goalModeDesc,+ active: goalOn,+ disabled: running || compacting || busy,+ onSelect: () => toggleGoal(!goalOn),+ },+ ]}+ footer={<SteerModeRow steerMode={steerMode} onChangeSteerMode={setSteerMode} />}direction={models && onChangeModel ? "down" : "up"}/>- {/* Multi-select skills dropdown (after approval mode): selected state is conveyed via the button badge. */}- <SkillSelect- skills={skills}- selected={selectedSkills}- onToggle={toggleSkill}- disabled={running || compacting || busy}- direction={models && onChangeModel ? "down" : "up"}- />- </div>- {/* Help text: shown only when the card is wide enough (@lg); it never competes for- space on phones, where the group scrolls instead. */}- <span- data-tooltip={S.chat.slashHint}- data-tooltip-content="text"- className="hidden min-w-0 truncate text-gray-300 @lg:block dark:text-gray-600"- >- {S.chat.slashHint}- </span>- </div>-- {/* Right group: status + model + the single action button; never shrinks. */}- <div className="flex shrink-0 items-center gap-2">+ )}+ <PermissionSelect+ approvalMode={approvalMode}+ approvalModes={approvalModes}+ sandbox={sandbox}+ onChangeApprovalMode={onChangeApprovalMode}+ onChangeSandbox={onChangeSandbox}+ disabled={modeSaving}+ direction={models && onChangeModel ? "down" : "up"}+ />+ {/* Multi-select skills dropdown (after approval mode): selected state is conveyed via the button badge. */}+ <SkillSelect+ skills={skills}+ selected={selectedSkills}+ onToggle={toggleSkill}+ disabled={running || compacting || busy}+ direction={models && onChangeModel ? "down" : "up"}+ />+ </>+ }+ // Help text: shown only when the card is wide enough; it never competes for space on+ // phones, where the group scrolls instead.+ hint={S.chat.slashHint}+ actions={+ // Right group: status + model + the single action button; never shrinks.+ <>{/* Draft state (model still changeable = no session created yet) has no context usage to speak of: the ring isn't shown, it displays as usual once the session is created. */}{!onChangeModel && (<ContextGauge@@ -2690,7 +2510,7 @@ export function ChatInput({)}{/* Left of the send button: model selector in draft state; once the Session is created the model is locked, shown read-only (still with the provider logo). */}{models && onChangeModel ? (- <ModelSelect+ <ModelCatalogSelectmodels={models}value={modelRef}{...(defaultModel !== undefined ? { defaultModel } : {})}@@ -2739,44 +2559,15 @@ export function ChatInput({channel is open then, so the alternative was a permanently disabled Send sittingwhere the only available action belonged. Idle keeps the ordinary send button.Merging the pair keeps the running-state row within a 320px viewport. */}- <button- type="button"- data-tooltip={stopAction ? S.chat.stop : running ? midRunSendLabel : S.chat.send}- aria-label={stopAction ? S.chat.stop : running ? midRunSendLabel : S.chat.send}- disabled={stopAction ? false : running ? !canMidRunSend : !canSend}+ <SendButton+ action={stopAction ? "stop" : "send"}+ label={stopAction ? S.chat.stop : running ? midRunSendLabel : S.chat.send}+ disabled={running ? !canMidRunSend : !canSend}onClick={() => (stopAction ? void onStop() : void send())}- className={- stopAction- ? "flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-red-50 text-red-600 transition-colors duration-150 hover:bg-red-100 dark:bg-red-950/60 dark:text-red-400 dark:hover:bg-red-950"- : "flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-gray-900 text-white transition-colors duration-150 hover:bg-gray-700 disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-gray-300 dark:disabled:bg-gray-800 dark:disabled:text-gray-600"- }- >- {stopAction ? (- /* Stop (filled square) */- <svg width="14" height="14" viewBox="0 0 14 14" aria-hidden className="block">- <rect x="2" y="2" width="10" height="10" rx="2" fill="currentColor" />- </svg>- ) : (- /* Up arrow (send) */- <svg- width="17"- height="17"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden- className="block"- >- <path d="M12 19V5M5 12l7-7 7 7" />- </svg>- )}- </button>- </div>- </div>- </div>+ />+ </>+ }+ /></div>);}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex e2d54464..ec08c8dc 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -41,6 +41,7 @@ import {Dropdown,EmptyState,GlyphIcon,+ Heading,ICONS,ICON_GAP,ICON_SIZE,@@ -2066,11 +2067,12 @@ export function ChatPage() {)}{/* Thin top toolbar */}{selected && (- <div className="flex shrink-0 items-center gap-2.5 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800">+ <div className="flex shrink-0 items-center gap-2 border-b border-gray-200 px-3 py-2 md:px-4 dark:border-gray-800"><div className="flex min-w-0 flex-1 items-center gap-3">- <h1 className="flex min-w-0 font-sans text-[15px] font-semibold">+ {/* The page's h1 on the compact title rung: a toolbar title, not a display title. */}+ <Heading level={5} as="h1" className="flex min-w-0"><Truncated text={selected.title ?? S.chat.defaultSessionTitle} />- </h1>+ </Heading>{/* Session-level state: a turning hourglass while the run is active, and nothing atall once it settles — the conversation on screen is by definition read, and theunread dot is a sidebar affordance for the rows you are NOT looking at. The@@ -2236,7 +2238,7 @@ export function ChatPage() {from the usage fetch, so it can trail the live total mid-run andreconciles on idle. No-cost sessions omit the cost bullet entirely, asthe chip does. */}- <ul className="list-inside list-disc space-y-0.5 font-mono text-xs">+ <ul className="list-inside list-disc space-y-1 font-mono text-xs"><li>{S.chat.statTotalTokens} {hs.tokensText}{cacheHitRate !== null &&@@ -2298,7 +2300,7 @@ export function ChatPage() {)}<span className="min-w-0 flex-1"><Truncated text={p.cmd} className="font-mono text-xs" codeTooltip />- <span className="block truncate text-[11px] text-gray-400 dark:text-gray-500">+ <span className="block truncate text-xs text-gray-400 dark:text-gray-500">{formatDateTime(p.startedAt)}{p.pid !== null && ` · pid ${p.pid}`}{/* Detected service URL (output scan or port probe), running rows@@ -2333,7 +2335,7 @@ export function ChatPage() {</button>) : (<>- <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">+ <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">{S.chat.processExited}</span>{/* The row is the only handle on that process's captureddiff --git a/packages/web/src/features/chat/compaction-banner.tsx b/packages/web/src/features/chat/compaction-banner.tsxindex 6bc0e230..38e13a7d 100644--- a/packages/web/src/features/chat/compaction-banner.tsx+++ b/packages/web/src/features/chat/compaction-banner.tsx@@ -50,12 +50,12 @@ import {LiveDuration,Md,StatusIcon,+ StepBanner,} from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { humanizeDuration } from "../../lib/format";import type { CompactionItem } from "../../lib/omni/stream-model";import { compactionResultVisible, compactionSummaryText } from "../../lib/omni/compaction-summary";-import { StepBanner } from "./step-banner";/*** One body section: the thinking block's row (status icon + label + wall time + chevron) overdiff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsxindex 5a826892..4383c150 100644--- a/packages/web/src/features/chat/context-gauge.tsx+++ b/packages/web/src/features/chat/context-gauge.tsx@@ -1,5 +1,7 @@/**- * Context usage gauge in the composer toolbar, and the composition panel behind it.+ * Context usage gauge in the composer toolbar, and the composition panel behind it. The ring is+ * the UI package's `ContextRing`; this module decides what it fills against, names it, and opens+ * the panel from it.** The resting state is the ring alone: a **single-colour** indicator of total occupancy (no* bucketing), turning amber past 80% and red past 95%. The exact `used/basis` figures are not@@ -68,7 +70,7 @@ import { useEffect, useId, useRef, useState } from "react";import type { RefObject } from "react";import { createPortal } from "react-dom";import type { SessionContextResponse } from "@prismshadow/penguin-server/api";-import { ConfirmModal, Input, Legend, Ring, usePortalPanel } from "@prismshadow/penguin-ui";+import { ConfirmModal, ContextRing, Input, Legend, usePortalPanel } from "@prismshadow/penguin-ui";import { getSessionContext } from "../../api/endpoints";import {MIN_COMPACTION_THRESHOLD,@@ -82,7 +84,6 @@ import {} from "../../lib/context";import { formatPercent, humanizeTokens } from "../../lib/format";import { S } from "../../lib/strings";-import { toneInk } from "../../lib/tone";import { usePointerDrag } from "../dock/use-pointer-drag";import { contextComposition } from "./context-parts";import type { ContextPartKey } from "./context-parts";@@ -215,55 +216,26 @@ export function ContextGauge({}};- const color =- unknown || pct <= 0.8- ? "text-gray-400 dark:text-gray-500"- : pct > 0.95- ? toneInk.danger- : toneInk.attention;// The ring draws no numbers, so its accessible name carries them: the ratio AND the figures it// was computed from, which is all the subagent composer's panel-less ring can offer.const usageText = unknown? S.chat.contextUnknown: `${S.chat.contextUsage} ${Math.round(pct * 100)}% · ${humanizeTokens(now)}/${humanizeTokens(basis)}`;- // A 5px radius under a 2px stroke, in the shell's ink: the track is that ink faded, so the- // warning ladder above recolours the whole ring. Decorative — the shell carries the name.- const gauge = (- <Ring- segments={pct > 0 ? [{ value: pct }] : []}- max={1}- size={12}- width={2}- trackOpacity={0.25}- />- );- // Same box as every other icon control on this toolbar (h-8 w-8, matching the model selector- // and the send button): a 14px ring in a 23px hit area sat visibly short of its neighbours.- const shell = `flex h-8 w-8 shrink-0 items-center justify-center ${color}`;if (sessionId === undefined) {- return (- <span data-tooltip={usageText} aria-label={usageText} role="img" className={shell}>- {gauge}- </span>- );+ return <ContextRing ratio={pct} unknown={unknown} label={usageText} />;}return (<>- {/* Hover paints only a background, not the ink its neighbours also change: the ring's colour- is the warning ladder, and a hover tone would overwrite the very thing it reports. */}- <button+ <ContextRingref={triggerRef}- type="button"- data-tooltip={usageText}- aria-label={usageText}- aria-expanded={open}- aria-controls={panelId}+ ratio={pct}+ unknown={unknown}+ label={usageText}+ expanded={open}+ controls={panelId}onClick={() => (open ? closePanel() : setOpen(true))}- className={`${shell} rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}- >- {gauge}- </button>+ />{open &&position &&createPortal(diff --git a/packages/web/src/features/chat/conversation-outline.tsx b/packages/web/src/features/chat/conversation-outline.tsxindex 27d53978..aca9c9d1 100644--- a/packages/web/src/features/chat/conversation-outline.tsx+++ b/packages/web/src/features/chat/conversation-outline.tsx@@ -180,7 +180,7 @@ function RailOverflowMark({ edge }: { edge: "above" | "below" }) {<divdata-outline-overflow={edge}aria-hidden- className={`flex w-10 flex-col items-start gap-[3px] pl-4 ${edge === "above" ? "pb-1.5" : "pt-1.5"}`}+ className={`flex w-10 flex-col items-start gap-1 pl-4 ${edge === "above" ? "pb-1.5" : "pt-1.5"}`}>{[0, 1, 2].map((i) => (<span key={i} className="h-[2px] w-[2px] rounded-full bg-gray-300 dark:bg-gray-700" />diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex e9a1df28..5f1329b9 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -962,7 +962,7 @@ export function DraftView({/>{open && (- <ul className="mt-0.5 space-y-0.5 pl-4">+ <ul className="mt-0.5 space-y-1 pl-4">{folder.tasks.map((task) => {const copy = S.chat.exampleTasks[task.id];return (@@ -1008,7 +1008,7 @@ export function DraftView({* new version.*/const versionBadgeClass =- "ml-1.5 inline-block align-super text-[10px] leading-4 text-gray-400 dark:text-gray-500";+ "ml-1.5 inline-block align-super text-xs leading-4 text-gray-400 dark:text-gray-500";/*** Quiet version line under the brand subtitle: `vX.Y.Z · Last updated Jul 26`diff --git a/packages/web/src/features/chat/mcp-connect-banner.tsx b/packages/web/src/features/chat/mcp-connect-banner.tsxindex 4a1f03b8..3887d1e7 100644--- a/packages/web/src/features/chat/mcp-connect-banner.tsx+++ b/packages/web/src/features/chat/mcp-connect-banner.tsx@@ -11,11 +11,10 @@* warn-and-skip stance).*/import { useState } from "react";-import { Chevron, StatusIcon } from "@prismshadow/penguin-ui";+import { Chevron, StatusIcon, StepBanner } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { humanizeDuration } from "../../lib/format";import type { McpConnectItem, McpServerOutcome, McpToolSummary } from "../../lib/omni/stream-model";-import { StepBanner } from "./step-banner";/*** Owner server of a prefixed tool name (`mcp__<server>__<tool>`), matched against thediff --git a/packages/web/src/features/chat/memory-changes-card.tsx b/packages/web/src/features/chat/memory-changes-card.tsxindex a06a056d..d2134ad3 100644--- a/packages/web/src/features/chat/memory-changes-card.tsx+++ b/packages/web/src/features/chat/memory-changes-card.tsx@@ -1,24 +1,23 @@/*** Memory-change summary card, rendered right below the file-summary card at the end of a- * root Task (same visual family): one row per memory topic file the Task changed through- * the structured file tools, derived by the stream model (TaskStatsItem.memoryChanges —- * see lib/omni/memory-changes.ts for what qualifies and what is filtered).+ * root Task (the same card, the UI package's ChangesCard): one row per memory topic file the+ * Task changed through the structured file tools, derived by the stream model+ * (TaskStatsItem.memoryChanges — see lib/omni/memory-changes.ts for what qualifies and what is+ * filtered).*- * Clicking a row opens the Memory side panel directly on that memory's content; the- * header's "Open memory list" text action opens the panel on its list. A changed file that- * was deleted in a later turn is filtered out (deletedKeys) — the row disappears here just as- * it does from the panel's list; the whole card hides when nothing survives.+ * Clicking a row opens the Memory side panel directly on that memory's content; the header's+ * "Open memory list" text action opens the panel on its list. The action is words, in the rows'+ * own "View content" hint style: a brain glyph there would only repeat the card's own mark beside+ * it, and say nothing of where it leads. A changed file that was deleted in a later turn is+ * filtered out (deletedKeys) — the row disappears here just as it does from the panel's list;+ * the whole card hides when nothing survives.*/-import { useState } from "react";-import { Chevron, GlyphIcon, ICONS, ICON_SIZE, namedHint } from "@prismshadow/penguin-ui";+import { ChangesCard, ICONS } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import type { MemoryChangeRow } from "../../lib/omni/memory-changes";import { memoryRowKey } from "../../lib/omni/memory-changes";-import { PathLabel } from "./message-files-card";import { scopeGlyph } from "./memory-view";-const MAX_VISIBLE = 3;-export function MemoryChangesCard({rows,deletedKeys,@@ -33,94 +32,33 @@ export function MemoryChangesCard({/** Header text action: open the Memory panel on its list; the action doesn't render if this isn't wired up. */onOpenPanel?: () => void;}) {- const [expanded, setExpanded] = useState(false);const alive = deletedKeys ? rows.filter((row) => !deletedKeys.has(memoryRowKey(row))) : rows;if (alive.length === 0) return null;- const visible = expanded ? alive : alive.slice(0, MAX_VISIBLE);- const hidden = alive.length - visible.length;-- const rowInner = (row: MemoryChangeRow) => {- const glyph = scopeGlyph(row.scope, row.scopeKey);- return (- <>- <span data-tooltip={glyph.title} className="shrink-0 text-gray-400">- <GlyphIcon d={glyph.d} size={ICON_SIZE.rowLead} />- <span className="sr-only">{glyph.title}</span>- </span>- <PathLabel path={row.file} />- <span className="min-w-0 flex-1" />- <span- {...namedHint(row.op === "write" ? S.chat.memoryOpWrite : S.chat.memoryOpEdit)}- className="shrink-0 text-gray-400"- >- <GlyphIcon- d={row.op === "write" ? ICONS.filePlus : ICONS.penLine}- size={ICON_SIZE.inlineGlyph}- />- </span>- </>- );- };-return (- <div className="anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">- {/* Header bar, mirroring the file-summary card: "icon + N memory updates", plus the one- card-level action (rows navigate to their own content, so this doesn't duplicate them).- The action is words, in the rows' own "View content" hint style: a brain glyph here- would only repeat the card's own mark beside it, and say nothing of where it leads. */}- <div className="flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40">- <GlyphIcon d={ICONS.brain} size={ICON_SIZE.rowLead} className="shrink-0 text-gray-400" />- <span className="min-w-0 flex-1 truncate text-sm font-medium">- {S.chat.memoryChangesTitle(alive.length)}- </span>- {onOpenPanel && (- <button- type="button"- onClick={onOpenPanel}- className="shrink-0 cursor-pointer text-xs text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"- >- {S.chat.memoryOpenList}- </button>- )}- </div>- <div className="divide-y divide-gray-100 dark:divide-gray-800/60">- {visible.map((row) => {- const key = memoryRowKey(row);- return onLocateChange ? (- <button- key={key}- type="button"- data-tooltip={S.chat.memoryRowOpen}- onClick={() => onLocateChange(row)}- className="group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50"- >- {rowInner(row)}- {/* Right-aligned action hint, the file card's affordance (span, not a nested button: the row itself is the button). */}- <span- aria-hidden- className="shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300"- >- {S.chat.memoryRowOpen}- </span>- </button>- ) : (- <div key={key} className="flex w-full items-center gap-2 px-3 py-2">- {rowInner(row)}- </div>- );- })}- {(hidden > 0 || expanded) && alive.length > MAX_VISIBLE && (- <button- type="button"- onClick={() => setExpanded((v) => !v)}- className="flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50"- >- {expanded ? S.chat.showLess : S.chat.memoryShowMore(hidden)}- <Chevron open={expanded} className="text-gray-400" size={ICON_SIZE.chevronDense} />- </button>- )}- </div>- </div>+ <ChangesCard+ glyph={ICONS.brain}+ title={S.chat.memoryChangesTitle(alive.length)}+ {...(onOpenPanel ? { action: { label: S.chat.memoryOpenList, onClick: onOpenPanel } } : {})}+ rows={alive.map((row) => {+ const scope = scopeGlyph(row.scope, row.scopeKey);+ return {+ id: memoryRowKey(row),+ path: row.file,+ glyph: scope.d,+ glyphLabel: scope.title,+ mark:+ row.op === "write"+ ? { glyph: ICONS.filePlus, label: S.chat.memoryOpWrite }+ : { glyph: ICONS.penLine, label: S.chat.memoryOpEdit },+ ...(onLocateChange+ ? { tooltip: S.chat.memoryRowOpen, onOpen: () => onLocateChange(row) }+ : {}),+ };+ })}+ openHint={S.chat.memoryRowOpen}+ showMore={S.chat.memoryShowMore}+ showLess={S.chat.showLess}+ />);}diff --git a/packages/web/src/features/chat/memory-view.tsx b/packages/web/src/features/chat/memory-view.tsxindex 909b7765..7534b050 100644--- a/packages/web/src/features/chat/memory-view.tsx+++ b/packages/web/src/features/chat/memory-view.tsx@@ -14,7 +14,7 @@*/import { useEffect, useState } from "react";import type { SessionInfo } from "@prismshadow/penguin-server/api";-import { GlyphIcon, ICON_SIZE, Md, SkeletonList } from "@prismshadow/penguin-ui";+import { GlyphIcon, ICONS, ICON_SIZE, Md, SkeletonList } from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { formatRelativeDate } from "../../lib/format";@@ -25,8 +25,7 @@ import { useLocale } from "../../state/locale";import { buildMemoryList, memoryNavBack, memoryNavForRequest } from "./memory-nav";import type { MemoryNavMode, ScopeFiles } from "./memory-nav";-/** Person (User scope), folder (Workspace scope), boxed arrow (open the settings tab), left arrow (back to the list). */-const USER_ICON = "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z";+/** Folder (Workspace scope; the User scope is ICONS.user), boxed arrow (open the settings tab), left arrow (back). */const FOLDER_ICON = "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z";const OPEN_SETTINGS_ICON ="M14 4h6v6M20 4 10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3";@@ -35,7 +34,7 @@ const BACK_ICON = "M19 12H5m6-6-6 6 6 6";/** The scope glyph + tooltip pair, shared with the memory-changes card's rows. */export function scopeGlyph(scope: "user" | "workspace", scopeKey?: string) {return {- d: scope === "user" ? USER_ICON : FOLDER_ICON,+ d: scope === "user" ? ICONS.user : FOLDER_ICON,title: scope === "user" ? S.memory.userScope : S.chat.memoryScopeWorkspace(scopeKey ?? ""),};}@@ -144,7 +143,7 @@ export function ChatMemoryView({<GlyphIcon d={glyph.d} size={ICON_SIZE.rowLead} /><span className="sr-only">{glyph.title}</span></span>- <p className="min-w-0 flex-1 truncate font-mono text-[13px] font-semibold">+ <p className="min-w-0 flex-1 truncate font-mono text-sm font-semibold">{listedRow?.title ?? target.file}</p>{listedRow &&@@ -216,7 +215,7 @@ export function ChatMemoryView({<div className="flex items-center gap-2 px-3.5 py-1.5"><span className="shrink-0 text-gray-400"><GlyphIcon- d={group.scope === "user" ? USER_ICON : FOLDER_ICON}+ d={group.scope === "user" ? ICONS.user : FOLDER_ICON}size={ICON_SIZE.inlineGlyph}/></span>@@ -240,7 +239,7 @@ export function ChatMemoryView({className="flex w-full cursor-pointer items-center gap-3 px-3.5 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50"><div className="min-w-0 flex-1">- <p className="flex items-center gap-1.5 truncate font-mono text-[13px] font-medium text-gray-800 dark:text-gray-200">+ <p className="flex items-center gap-1.5 truncate font-mono text-sm font-medium text-gray-800 dark:text-gray-200">{row.changed !== undefined && (<spandata-tooltip={S.chat.memoryChangedMark}diff --git a/packages/web/src/features/chat/message-files-card.tsx b/packages/web/src/features/chat/message-files-card.tsxindex 96c95595..d16b9023 100644--- a/packages/web/src/features/chat/message-files-card.tsx+++ b/packages/web/src/features/chat/message-files-card.tsx@@ -1,11 +1,10 @@/**- * File summary card for a supplied assistant-text scope (visual reference: Codex's "files- * changed" card): the root conversation passes a completed Task's aggregated assistant text,- * while nested conversations — which don't produce task_stats — pass one settled assistant- * message to preserve their existing behavior. Extracts inline-code paths heuristically via- * isFilePathLike, normalizes them to Workspace-relative paths, confirms they actually exist via- * files/stat, and renders a light-background "N files" card whose rows open the Files panel.- * Collapses when there are more than 3 rows.+ * File summary card for a supplied assistant-text scope: the root conversation passes a+ * completed Task's aggregated assistant text, while nested conversations — which don't produce+ * task_stats — pass one settled assistant message to preserve their existing behavior. Extracts+ * inline-code paths heuristically via isFilePathLike, normalizes them to Workspace-relative+ * paths, confirms they actually exist via files/stat, and renders them as the UI package's+ * ChangesCard — an "N files" card whose rows open the Files panel, folded past 3 rows.** The card waits for stat results and doesn't render when no candidate exists. It intentionally* does not claim these files were changed: opaque exec_command shells provide no reliable@@ -13,12 +12,10 @@* currently openable.*/import { useEffect, useMemo, useState } from "react";-import { Chevron, GlyphIcon, ICONS, ICON_SIZE } from "@prismshadow/penguin-ui";+import { ChangesCard, ICONS } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { isFilePathLike, toWorkspaceRelative } from "../../lib/file-path";-const MAX_VISIBLE = 3;-/** Extracts file paths from inline code in raw Markdown (deduplicated, preserving order of appearance). */export function extractFilePaths(markdown: string): string[] {const out: string[] = [];@@ -32,28 +29,6 @@ export function extractFilePaths(markdown: string): string[] {return out;}-/** Path split into segments: directory prefix faded, filename bold (Codex-style). The directory- * segment has shrink-[9999] and collapses first, the filename segment truncates only after —- * both segments are truncatable, so the row never overflows its container on a narrow panel.- * Shared with the memory-changes card, which renders the same row family. */-export function PathLabel({ path }: { path: string }) {- const slash = path.lastIndexOf("/");- const dir = slash >= 0 ? path.slice(0, slash + 1) : "";- const name = slash >= 0 ? path.slice(slash + 1) : path;- return (- <span className="flex min-w-0 items-baseline font-mono text-sm">- {dir && (- <span className="min-w-0 shrink-[9999] truncate text-gray-400 dark:text-gray-500">- {dir}- </span>- )}- <span className="min-w-0 truncate font-semibold text-gray-800 dark:text-gray-100">- {name}- </span>- </span>- );-}-export function MessageFilesCard({text,workspace,@@ -99,59 +74,24 @@ export function MessageFilesCard({};}, [candidates, statFiles]);- const [expanded, setExpanded] = useState(false);if (paths === null || paths.length === 0) return null;- const visible = expanded ? paths : paths.slice(0, MAX_VISIBLE);- const hidden = paths.length - visible.length;-+ // Each row shows its full path as its tooltip (the row itself may truncate it), and says in+ // words that a click previews it — no card-level action: every row already has its own.return (- <div className="anim-msg my-3 overflow-hidden rounded-xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">- {/* Header bar: a single line of "icon + N files", light background to distinguish it from- the rows (Codex-style). No card-level action entry point — each row already has its own- "Preview", adding one to the header would just duplicate the row action. */}- <div className="flex items-center gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 dark:border-gray-800/60 dark:bg-gray-800/40">- <GlyphIcon d={ICONS.file} size={ICON_SIZE.rowLead} className="text-gray-400" />- <span className="min-w-0 flex-1 truncate text-sm font-medium">- {S.chat.filesInMessage(paths.length)}- </span>- </div>- {/* File row list: thin dividers within the card, clicking a row opens it in the Files panel preview. */}- <div className="divide-y divide-gray-100 dark:divide-gray-800/60">- {visible.map((path) => (- <button- key={path}- type="button"- data-tooltip={path}- onClick={() => onOpenFile(path)}- className="group flex w-full cursor-pointer items-center gap-2 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/50"- >- <GlyphIcon d={ICONS.file} size={ICON_SIZE.rowLead} className="text-gray-400" />- <PathLabel path={path} />- <span className="min-w-0 flex-1" />- {/* Right-aligned "click to preview" text: makes the row action explicit (a trailing- chevron would read as expand/collapse instead). The whole row is already a- <button> (buttons can't nest), so this uses a span, and the click still targets- the whole row. */}- <span- aria-hidden- className="shrink-0 text-xs text-gray-400 transition-colors duration-150 group-hover:text-gray-600 dark:text-gray-500 dark:group-hover:text-gray-300"- >- {S.chat.openPreview}- </span>- </button>- ))}- {(hidden > 0 || expanded) && paths.length > MAX_VISIBLE && (- <button- type="button"- onClick={() => setExpanded((v) => !v)}- className="flex w-full items-center gap-1.5 px-3 py-2 text-left text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-800/50"- >- {expanded ? S.chat.showLess : S.chat.showMoreFiles(hidden)}- <Chevron open={expanded} size={ICON_SIZE.chevronDense} />- </button>- )}- </div>- </div>+ <ChangesCard+ glyph={ICONS.file}+ title={S.chat.filesInMessage(paths.length)}+ rows={paths.map((path) => ({+ id: path,+ path,+ glyph: ICONS.file,+ tooltip: path,+ onOpen: () => onOpenFile(path),+ }))}+ openHint={S.chat.openPreview}+ showMore={S.chat.showMoreFiles}+ showLess={S.chat.showLess}+ />);}diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsxindex 18d0b4ff..c57e9669 100644--- a/packages/web/src/features/chat/message-item.tsx+++ b/packages/web/src/features/chat/message-item.tsx@@ -1,23 +1,32 @@/**- * Rendering dispatch for a single view-model item: user prompts are- * right-aligned brand bubbles (including image thumbnails), thinking collapsible blocks, text- * streamed as Markdown, tool cards, subagent cards, compaction banners, abort markers, and Task- * stats lines. Items have a light entrance animation.+ * Rendering dispatch for a single view-model item: user prompts are right-aligned bubbles+ * (including image thumbnails), thinking collapsible blocks, text streamed as Markdown, tool+ * cards, subagent cards, compaction banners, abort markers, and Task stats lines. Items have a+ * light entrance animation.+ *+ * The drawing is the UI package's (MessageRow / MessageBubble / MessageMeta for what the person+ * sent and the run's notice lines, AssistantText for a reply); what stays here is which item+ * becomes what, the text parsing that collapses harness blocks into banners, and the reconnect+ * line's countdown and controls.*/import { useEffect, useState } from "react";-import { CopyButton, GlyphIcon, ZoomableImage } from "@prismshadow/penguin-ui";+import {+ AssistantText,+ MessageBubble,+ MessageImage,+ MessageMeta,+ MessageRow,+} from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { useLocale } from "../../state/locale";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 { AssistantReplyBody } from "./assistant-reply-body";import { MessageFilesCard } from "./message-files-card";import { MemoryChangesCard } from "./memory-changes-card";-import { ThinkingBlock } from "./thinking-block";-import { ToolCallCard } from "./tool-call-card";-import { SubagentChip } from "./subagent-chip";+import { SessionThinking } from "./thinking-block";+import { SessionToolCall } from "./tool-call-card";+import { SessionSubagentChip } from "./subagent-chip";import { CompactionBanner } from "./compaction-banner";import { McpConnectBanner } from "./mcp-connect-banner";import { HandoffBanner, ModelSwitchBanner } from "./handoff-banner";@@ -37,47 +46,20 @@ import {import { parseSkillsMessage } from "./skill-use";import { TaskStatsLine } from "./task-stats-line";import type { StreamRenderContext } from "./message-stream";-import { toneInk } from "../../lib/tone";--/** User glyph (24×24 line path) for the mid-run steering chip. */-const USER_STEERING_ICON =- "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0";/**- * Message footer: timestamp + copy. At ≥sm it is **invisible but takes up space by default**- * (`sm:opacity-0` rather than `hidden`) — it surfaces on hovering the message list, and because- * the space is always reserved, surfacing it never pushes content below it down (using `hidden`- * would cause every item to jitter). Keyboard users can also reveal it via `focus-within`- * (otherwise the copy button would be focusable but never visible). Below sm the footer is- * always visible — hover doesn't exist on touch screens (and Tailwind v4 scopes hover: variants- * to `@media (hover: hover)`), so a hover-revealed footer would simply never appear on phones;- * same treatment as the AI reply's stats footer.- *- * When `text` is omitted, only the timestamp is shown, no copy button — there's no clear meaning- * to copying an image message.+ * The footer under a message the person sent (MessageMeta): its time in the reader's locale, and+ * a copy button when there is text to copy — none for an image or a files notice, where copying+ * has no clear meaning. The same hover reveal as the reply's stats footer, and always shown below+ * sm, where touch has no hover.*/-function MessageMeta({- atMs,- text,- align = "left",-}: {- atMs?: number;- text?: string;- align?: "left" | "right";-}) {+function SentMessageMeta({ atMs, copyText }: { atMs: number | undefined; copyText?: string }) {const { locale } = useLocale();return (- <div- className={`flex h-5 items-center gap-2 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:opacity-0 ${- align === "right" ? "justify-end" : "justify-start"- }`}- >- {atMs !== undefined && (- <span className="text-[11px] text-gray-400">{formatMessageTime(atMs, locale)}</span>- )}- {/* No copy button for image-only messages: copying an image message has no clear meaning. */}- {text !== undefined && <CopyButton text={text} label={S.chat.copyMessage} />}- </div>+ <MessageMeta+ {...(atMs !== undefined ? { time: formatMessageTime(atMs, locale) } : {})}+ {...(copyText !== undefined ? { copy: { text: copyText, label: S.chat.copyMessage } } : {})}+ />);}@@ -136,8 +118,41 @@ function ReconnectLine({ item, ctx }: { item: ReconnectItem; ctx: StreamRenderCoconst showControls =live && ctx.origin.length === 0 && (ctx.onRetryNow !== undefined || ctx.onGiveUp !== undefined);return (- <p- className={`anim-msg my-1 flex flex-wrap items-center gap-x-2 gap-y-1 font-mono text-xs ${toneInk.attention}`}+ <MessageBubble+ variant="notice"+ tone="attention"+ actions={+ showControls ? (+ <>+ {ctx.onRetryNow && (+ <button+ type="button"+ disabled={acted}+ onClick={() => {+ setActed(true);+ ctx.onRetryNow!();+ }}+ className="rounded border border-amber-300 px-1.5 py-0.5 text-xs font-medium text-amber-700 transition-colors duration-150 hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-amber-700 dark:text-amber-400 dark:hover:bg-amber-950/40"+ >+ {S.chat.reconnectRetryNow}+ </button>+ )}+ {ctx.onGiveUp && (+ <button+ type="button"+ disabled={acted}+ onClick={() => {+ setActed(true);+ ctx.onGiveUp!();+ }}+ className="rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-800"+ >+ {S.chat.reconnectGiveUp}+ </button>+ )}+ </>+ ) : undefined+ }><span>{S.chat.reconnect(@@ -149,37 +164,7 @@ function ReconnectLine({ item, ctx }: { item: ReconnectItem; ctx: StreamRenderCoitem.errorCode,)}</span>- {showControls && (- <span className="flex shrink-0 items-center gap-1.5">- {ctx.onRetryNow && (- <button- type="button"- disabled={acted}- onClick={() => {- setActed(true);- ctx.onRetryNow!();- }}- className="rounded border border-amber-300 px-1.5 py-0.5 text-[11px] font-medium text-amber-700 transition-colors duration-150 hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-50 dark:border-amber-700 dark:text-amber-400 dark:hover:bg-amber-950/40"- >- {S.chat.reconnectRetryNow}- </button>- )}- {ctx.onGiveUp && (- <button- type="button"- disabled={acted}- onClick={() => {- setActed(true);- ctx.onGiveUp!();- }}- className="rounded border border-gray-300 px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 dark:text-gray-400 dark:hover:bg-gray-800"- >- {S.chat.reconnectGiveUp}- </button>- )}- </span>- )}- </p>+ </MessageBubble>);}@@ -228,47 +213,28 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo{scheduled && <ScheduledBanner origin={scheduled.origin} />}{skills && <SkillsBanner names={skills.skills} />}{text && (- <div className="anim-msg group my-4 flex flex-col items-end">- <div className="max-w-[88%] rounded-lg bg-gray-100 px-4 py-2.5 md:max-w-[75%] dark:bg-gray-800">- {/* wrap-anywhere: long unbroken strings like attachment paths/long URLs wrap within the bubble on narrow (mobile) screens instead of overflowing; unlike break-words it also shrinks min-content, so a pathological token can't stretch the flex bubble itself. Normal words still only break when a token can't fit on a line. */}- <p className="wrap-anywhere font-sans whitespace-pre-wrap text-base leading-relaxed text-gray-900 dark:text-gray-100">- {text}- </p>- </div>- <MessageMeta- {...(item.atMs !== undefined ? { atMs: item.atMs } : {})}- text={text}- align="right"- />- </div>+ <MessageRow>+ <MessageBubble variant="user">{text}</MessageBubble>+ <SentMessageMeta atMs={item.atMs} copyText={text} />+ </MessageRow>)}{/* Files uploaded with this message: shown below the text in the same user-sidecontainer and with the same timestamp footer as uploaded images. The bytes live inthe session scratchpad, where the model opens them by path (goal mode never getshere: it takes text and images only). */}{files.length > 0 && (- <div className="anim-msg group my-4 flex flex-col items-end">+ <MessageRow><AttachedFilesBanner files={files} />- <MessageMeta- {...(item.atMs !== undefined ? { atMs: item.atMs } : {})}- align="right"- />- </div>+ <SentMessageMeta atMs={item.atMs} />+ </MessageRow>)}{images.map((src, i) => (- <div key={i} className="anim-msg group my-4 flex flex-col items-end">- <div className="max-w-[88%] rounded-lg bg-gray-100 p-1.5 md:max-w-[75%] dark:bg-gray-800">- <ZoomableImage- src={src}- alt={S.chat.imageAlt}- className="max-h-48 max-w-full rounded-md"- />- </div>- <MessageMeta- {...(item.atMs !== undefined ? { atMs: item.atMs } : {})}- align="right"- />- </div>+ <MessageRow key={i}>+ <MessageBubble variant="image">+ <MessageImage src={src} alt={S.chat.imageAlt} />+ </MessageBubble>+ <SentMessageMeta atMs={item.atMs} />+ </MessageRow>))}</>);@@ -301,58 +267,35 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo} = splitAttachments(item.text);const shown = [...steerImages, ...(item.images ?? [])];return (- <div className="anim-msg group my-2 flex flex-col items-end">- <div className="flex max-w-[88%] flex-col gap-1.5 rounded-md border border-gray-200 bg-gray-100 px-3 py-1.5 md:max-w-[75%] dark:border-gray-700 dark:bg-gray-800">- <div className="flex items-start gap-1.5">- <GlyphIcon- d={USER_STEERING_ICON}- className="mt-1 shrink-0 text-gray-400 dark:text-gray-500"- />- <p className="wrap-anywhere font-sans whitespace-pre-wrap text-sm leading-relaxed text-gray-800 dark:text-gray-100">- <span className="mr-1.5 text-xs font-semibold text-gray-500 dark:text-gray-400">- {S.chat.userSteering}- </span>- {steerText}- </p>- </div>- {shown.length > 0 && (- <div className="flex flex-wrap justify-end gap-1.5">- {shown.map((src, i) => (- <ZoomableImage- key={i}- src={src}- alt={S.chat.imageAlt}- className="max-h-28 max-w-full rounded-md"- />- ))}- </div>- )}- {steerFiles.length > 0 && (- <div className="flex justify-end">- <AttachedFilesBanner files={steerFiles} />- </div>- )}- </div>- <MessageMeta- {...(item.atMs !== undefined ? { atMs: item.atMs } : {})}- text={steerText}- align="right"- />- </div>+ <MessageRow spacing="steer">+ <MessageBubble+ variant="steering"+ label={S.chat.userSteering}+ {...(shown.length > 0+ ? {+ media: shown.map((src, i) => (+ <MessageImage key={i} src={src} alt={S.chat.imageAlt} size="chip" />+ )),+ }+ : {})}+ {...(steerFiles.length > 0+ ? { attachments: <AttachedFilesBanner files={steerFiles} /> }+ : {})}+ >+ {steerText}+ </MessageBubble>+ <SentMessageMeta atMs={item.atMs} copyText={steerText} />+ </MessageRow>);}case "user_image":return (- <div className="anim-msg group my-4 flex flex-col items-end">- <div className="max-w-[88%] rounded-lg bg-gray-100 p-1.5 md:max-w-[75%] dark:bg-gray-800">- <ZoomableImage- src={item.imageUrl}- alt={S.chat.imageAlt}- className="max-h-48 max-w-full rounded-md"- />- </div>- <MessageMeta {...(item.atMs !== undefined ? { atMs: item.atMs } : {})} align="right" />- </div>+ <MessageRow>+ <MessageBubble variant="image">+ <MessageImage src={item.imageUrl} alt={S.chat.imageAlt} />+ </MessageBubble>+ <SentMessageMeta atMs={item.atMs} />+ </MessageRow>);case "assistant_text":// Doesn't attach MessageMeta: this turn's reply timestamp and copy both belong to the@@ -360,10 +303,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.+ // The body (Markdown, caret, the theme's reveal) is AssistantText; the stop reason and a+ // nested reply's files card follow the text once it is fully revealed.return (- <AssistantReplyBody text={item.text} streaming={item.streaming}>+ <AssistantText 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>)}@@ -376,32 +319,29 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCoonOpenFile={ctx.onOpenFile}/>)}- </AssistantReplyBody>+ </AssistantText>);case "thinking":- return <ThinkingBlock item={item} />;+ return <SessionThinking item={item} />;case "tool_call":- return <ToolCallCard item={item} ctx={ctx} />;+ return <SessionToolCall item={item} ctx={ctx} />;case "subagent":// Standalone child session (no run_subagent card to bind to): same full-width shortcut// bar as the bound site — the conversation itself lives in the subagents panel.return (<div className="anim-msg my-2">- <SubagentChip sessionId={item.sessionId} model={item.model} running={false} ctx={ctx} />+ <SessionSubagentChip+ sessionId={item.sessionId}+ model={item.model}+ running={false}+ ctx={ctx}+ /></div>);case "abort":- return (- <p className="anim-msg my-1 font-mono text-xs text-gray-500 dark:text-gray-400">- {S.chat.aborted(item)}- </p>- );+ return <MessageBubble variant="notice">{S.chat.aborted(item)}</MessageBubble>;case "llm_error":- return (- <p className="anim-msg my-1 font-mono text-xs text-gray-500 dark:text-gray-400">- {S.chat.llmError(item.errorMessage)}- </p>- );+ return <MessageBubble variant="notice">{S.chat.llmError(item.errorMessage)}</MessageBubble>;case "reconnect":return <ReconnectLine item={item} ctx={ctx} />;case "compaction":diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex 92b2d0f2..c77fa1b3 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -17,7 +17,7 @@ import type { TaskStats } from "../../lib/omni/task-stats";import type { PendingApproval } from "./use-session-stream";import { MessageItem } from "./message-item";import { WorkspaceLinksProvider } from "./workspace-links";-import { WorkGroup, isWorkItem } from "./work-group";+import { SessionWorkGroup, isWorkItem } from "./work-group";import { createStreamFollow, stickToBottom } from "./stream-follow";import type { StreamFollow } from "./stream-follow";import type { ForkTarget } from "./task-stats-line";@@ -103,7 +103,7 @@ export function MessageItems({ items, ctx }: { items: ChatItem[]; ctx: StreamRenconst renderSeg = (seg: Seg, i: number): ReactNode =>seg.type === "group" ? (- <WorkGroup+ <SessionWorkGroupkey={`wg-${seg.items[0]!.id}`}items={seg.items}ctx={ctx}diff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsxindex b5e154a7..882c5fc1 100644--- a/packages/web/src/features/chat/model-select.tsx+++ b/packages/web/src/features/chat/model-select.tsx@@ -1,12 +1,14 @@/**- * The model picker's trigger, extracted from chat-input.tsx so every host offers the same- * picker: ModelSelect (provider logo + name + chevron), pill or form style. Either opens the- * model-picker dialog (model-picker-modal.tsx), which the in-session `/model` switch opens too.- * The composer's other switch picker, the `/agent` handoff, is the UI package's PickerList.+ * The model picker bound to the Project's model catalog: the UI package's `ModelSelect` draws the+ * trigger (provider logo + name), as the composer's toolbar pill or a dialog's form field, and+ * either opens the model-picker dialog (model-picker-modal.tsx), which the in-session `/model`+ * switch opens too. The chat composer, the Project settings' new-chat defaults, the schedule+ * form, the organization dialogs and the benchmark dialog all pick a model through it. The+ * composer's other switch picker, the `/agent` handoff, is the UI package's PickerList.*/import { useState } from "react";import type { ModelInfo, ModelRefDto } from "@prismshadow/penguin-server/api";-import { ChevronDown, FormPickerTrigger, ICON_SIZE, ProviderLogo } from "@prismshadow/penguin-ui";+import { ModelSelect } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { sameModelRef } from "../models/model-grouping";import { modelLabel } from "./model-picker-logic";@@ -18,11 +20,9 @@ import { ModelPickerModal } from "./model-picker-modal";export { modelLabel };/**- * Model selector (the chat composer's bottom-toolbar trigger, also hosted by the Project- * settings' new-chat-defaults section, the schedule form, the company dialogs and the benchmark- * dialog): the button shows the provider logo + name and opens the model-picker dialog (search,- * provider-group rail, key-configured-first listing, Free badge — documented there). A pick- * closes the dialog and reports `{ provider, modelId }` through `onChange`.+ * Model selector: the trigger shows the provider logo + name and opens the model-picker dialog+ * (search, provider-group rail, key-configured-first listing, Free badge — documented there). A+ * pick closes the dialog and reports `{ provider, modelId }` through `onChange`.** Two trigger variants, one dialog:* - "pill" (default): the composer's compact toolbar button — collapses to the logo alone@@ -32,9 +32,12 @@ export { modelLabel };* closes only the picker.** `emptyLabel` is for the one kind of host where an unpicked model is a decision and not a- * gap — the organization dialogs' "Project default"; see the prop.+ * gap — the organization dialogs, where an empty model means "follow the Project's default".+ * The picker still offers models only, so such a host carries its own way back to the empty+ * value; here the label is grayed as a placeholder and the provider logo is dropped, since no+ * provider is being named.*/-export function ModelSelect({+export function ModelCatalogSelect({models,value,defaultModel,@@ -49,82 +52,42 @@ export function ModelSelect({defaultModel?: ModelRefDto;onChange: (ref: ModelRefDto) => void;disabled: boolean;- /** Trigger style: the composer's toolbar pill (default), or a dialog form control (see the header comment). */+ /** Trigger style: the composer's toolbar pill (default), or a dialog form control. */variant?: "pill" | "form";- /**- * What the trigger reads while nothing is picked, for a host where "nothing" is itself a- * choice rather than an unfinished one — the organization dialogs, where an empty model- * means "follow the Project's default". The picker still offers models only, so such a host- * carries its own way back to the empty value; here the label is grayed as a placeholder- * and the provider logo is dropped, since no provider is being named.- */+ /** What the trigger reads while nothing is picked, where "nothing" is itself a choice. */emptyLabel?: string;}) {const [open, setOpen] = useState(false);const current = models.find((m) => sameModelRef(m, value));const unset = value === null && emptyLabel !== undefined;- // Display rule matches the model page's card: display name, or falls back to the upstream id (grouping is already conveyed by the provider logo).+ // Display rule matches the model page's card: display name, or falls back to the upstream id+ // (grouping is already conveyed by the provider logo).const label = current ? modelLabel(current) : (value?.modelId ?? emptyLabel ?? "…");- const logo = unset ? null : (- <ProviderLogo- provider={current?.provider ?? value?.provider ?? "custom"}- className="h-4 w-4 shrink-0"- />- );- const isDisabled = disabled || models.length === 0;- const picker = (- <ModelPickerModal- open={open}- onClose={() => setOpen(false)}- title={S.chat.chooseModel}- models={models}- value={value}- {...(defaultModel !== undefined ? { defaultModel } : {})}- onPick={(m) => {- onChange({ provider: m.provider, modelId: m.modelId });- setOpen(false);- }}- />- );- // Form: the shared full-width trigger (same look as Input/Select), used by every dialog picker.- if (variant === "form") {- return (- <>- <FormPickerTrigger- size="sm"- expanded={open}- onClick={() => setOpen(true)}- leading={logo}- label={label}- muted={unset}- title={`${S.chat.chooseModel}:${label}`}- ariaLabel={S.chat.chooseModel}- ariaHaspopup="dialog"- disabled={isDisabled}- />- {picker}- </>- );- }- // Pill: the composer's compact toolbar button.return (<>- <button- type="button"- data-tooltip={`${S.chat.chooseModel}:${label}`}- aria-label={S.chat.chooseModel}- aria-haspopup="dialog"- aria-expanded={open}- disabled={isDisabled}+ <ModelSelect+ label={label}+ provider={unset ? null : (current?.provider ?? value?.provider ?? "custom")}+ muted={unset}+ ariaLabel={S.chat.chooseModel}+ tooltip={`${S.chat.chooseModel}:${label}`}+ disabled={disabled || models.length === 0}+ variant={variant}+ expanded={open}onClick={() => setOpen(true)}- className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"- >- {logo}- {/* When the card is narrower than @md, only the provider logo remains (title shows the full name). */}- <span className="hidden min-w-0 truncate @md:block">{label}</span>- <ChevronDown size={ICON_SIZE.caretDense} />- </button>- {picker}+ />+ <ModelPickerModal+ open={open}+ onClose={() => setOpen(false)}+ title={S.chat.chooseModel}+ models={models}+ value={value}+ {...(defaultModel !== undefined ? { defaultModel } : {})}+ onPick={(m) => {+ onChange({ provider: m.provider, modelId: m.modelId });+ setOpen(false);+ }}+ /></>);}diff --git a/packages/web/src/features/chat/permission-select.tsx b/packages/web/src/features/chat/permission-select.tsxindex 0e299c4a..c0172219 100644--- a/packages/web/src/features/chat/permission-select.tsx+++ b/packages/web/src/features/chat/permission-select.tsx@@ -139,9 +139,10 @@ export function PermissionSelect({data-level={level}disabled={disabled}onClick={() => setOpen((v) => !v)}- // Icon only, the + button's square: the level is in the icon's shape and colour, and- // spelled out in the accessible name and the title.- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"+ // Icon only, the + button's square and its look (the package's ToolbarTrigger, which+ // this cannot be: that one dims while disabled): the level is in the icon's shape and+ // colour, and spelled out in the accessible name and the title.+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-fg-muted transition-colors duration-150 hover:bg-surface-muted hover:text-fg">{/* Keyed by level: a new level mounts a new icon, which swaps in. */}<span key={level} className={animate ? "anim-icon-swap" : undefined}>diff --git a/packages/web/src/features/chat/reference-chip.tsx b/packages/web/src/features/chat/reference-chip.tsxindex 309dacac..b9876fd5 100644--- a/packages/web/src/features/chat/reference-chip.tsx+++ b/packages/web/src/features/chat/reference-chip.tsx@@ -1,9 +1,10 @@/**- * A reference staged in the composer, drawn as a chip: what it points at — a Workspace file, a- * directory, a quoted range of a file, or an excerpt of the conversation — never the text the- * message will carry. The composer draws one per staged reference, above its text body.+ * A reference staged in the composer, drawn as the UI package's `Chip`: what it points at — a+ * Workspace file, a directory, a quoted range of a file, or an excerpt of the conversation —+ * never the text the message will carry. The composer draws one per staged reference, above its+ * text body.*/-import { GlyphIcon, ICONS } from "@prismshadow/penguin-ui";+import { Chip, GlyphIcon, ICONS } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { excerptLabel } from "../../lib/selection-menu";import { lineSuffix } from "../../lib/workspace-tree";@@ -56,31 +57,25 @@ export function ReferenceChip({}) {const { name, lines } = referenceParts(reference);const title = referenceTitle(reference);+ // The name gives way, the line numbers do not: they are four characters, and they are the half+ // the truncated name cannot tell you. The tooltip carries the whole path and the range together.return (- <span- data-tooltip={title}- className="anim-pop flex max-w-48 items-center gap-1 rounded-md bg-gray-100 py-0.5 pl-2 pr-1 font-mono text-xs text-gray-800 dark:bg-gray-800 dark:text-gray-200"- >- <GlyphIcon- d={REFERENCE_ICON[reference.kind]}- size={13}- className="shrink-0 text-gray-500 dark:text-gray-400"- />- {/* The name gives way, the line numbers do not: they are four characters, and they are- the half the truncated name cannot tell you. The tooltip carries the whole path and- the range together. */}- <span className="min-w-0 truncate">{name}</span>- {lines !== "" && <span className="shrink-0">{lines}</span>}- <button- type="button"- // An excerpt is named by its label here: its tooltip is the whole passage, which is- // far too long to announce as the name of a remove button.- aria-label={`${S.files.removeReference} ${reference.kind === "excerpt" ? name : title}`}- onClick={onRemove}- className="shrink-0 rounded p-px text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"- >- ×- </button>- </span>+ <Chip+ label={name}+ suffix={lines}+ glyph={+ <GlyphIcon+ d={REFERENCE_ICON[reference.kind]}+ size={13}+ className="shrink-0 text-fg-muted"+ />+ }+ tooltip={title}+ mono+ // An excerpt is named by its label here: its tooltip is the whole passage, which is far too+ // long to announce as the name of a remove button.+ removeLabel={`${S.files.removeReference} ${reference.kind === "excerpt" ? name : title}`}+ onRemove={onRemove}+ />);}diff --git a/packages/web/src/features/chat/step-banner.tsx b/packages/web/src/features/chat/step-banner.tsxdeleted file mode 100644index 218a281e..00000000--- a/packages/web/src/features/chat/step-banner.tsx+++ /dev/null@@ -1,137 +0,0 @@-/**- * Shared shell for the stream's process banners (MCP connect, compaction): strictly the- * "Reasoning & Tools" group-header anatomy (work-group.tsx) — same card, same sticky- * title bar (StatusIcon + short title + mono detail + duration slot + chevron at the far- * right), so running / success / failure are all the SAME row with only the icon and the- * one-line detail changing. Duration sits right after the detail like the group header's- * count+duration slots (LiveDuration ticking while running, the settled span with- * decimals once finished); the flexible spacer keeps the chevron pinned at the right- * edge. A body (e.g. the discovered-tool groups) makes the row expandable; collapsing while- * the sticky header is stuck scrolls the row back into view — the exact behavior of the- * work-group header.- *- * Expand policy, also the work group's (work-group.tsx): the body opens while the step runs,- * so its rows are visible as they are appended, and closes itself once the step settles —- * leaving the one-line summary the row exists to be. The body's own rows never open with it:- * the reader is shown that they are there, not their contents.- */-import { useEffect, useRef, useState } from "react";-import type { ReactNode } from "react";-import { Chevron, LiveDuration, StatusIcon } from "@prismshadow/penguin-ui";-import type { RunState } from "@prismshadow/penguin-ui";-import { humanizeDuration } from "../../lib/format";-import { toneInk } from "../../lib/tone";--export function StepBanner({- state,- title,- detail,- liveSinceMs,- durationMs,- children,-}: {- state: RunState;- /** Constant short label (the work-group header's title slot). */- title: string;- /** One-line status/result text; truncates with the full text as a tooltip. */- detail?: string;- /** Tick a live duration from this timestamp while running. */- liveSinceMs?: number;- /** Settled wall time once finished. */- durationMs?: number;- /** Expandable body; its presence adds the chevron (open while running, closed once settled). */- children?: ReactNode;-}) {- const running = state === "running";- const [open, setOpen] = useState(running);- const userToggled = useRef(false);- const rootRef = useRef<HTMLDivElement>(null);- const expandable = children !== undefined && children !== null;-- // Before any manual toggle, follow "is this step still running". Afterwards the row is the- // reader's: a later auto transition never fights them, so a finished row they opened to read- // stays open, and one they closed mid-run stays closed.- useEffect(() => {- if (!userToggled.current) setOpen(running);- }, [running]);-- const header = (- <>- <StatusIcon state={state} />- <span- className={`shrink-0 text-[11px] font-semibold tracking-wide uppercase ${running ? toneInk.busy : "text-gray-500 dark:text-gray-400"}`}- >- {title}- </span>- {/* Detail then duration, left-aligned after the title — the same slot order as the- group header's step count + duration; the trailing spacer pins the chevron to the- right edge. min-w-0 (not flex-1) lets a long detail truncate while a short one- keeps the duration snug against it. */}- {detail !== undefined && (- <span- data-tooltip={detail}- data-tooltip-content="code"- className="min-w-0 truncate font-mono text-xs text-gray-400"- >- {detail}- </span>- )}- {running- ? liveSinceMs !== undefined && (- <span className="shrink-0 font-mono text-xs text-gray-400">- <LiveDuration sinceMs={liveSinceMs} />- </span>- )- : durationMs !== undefined &&- durationMs > 0 && (- <span className="shrink-0 font-mono text-xs text-gray-400">- {humanizeDuration(durationMs)}- </span>- )}- <span className="min-w-0 flex-1" />- {expandable && <Chevron open={open} className="text-gray-400" />}- </>- );-- return (- // overflow-clip, not overflow-hidden: the sticky header below must stick to the message- // list's scrollport, and an overflow-hidden ancestor would become its scroll container- // (see work-group.tsx for the full reasoning).- <div- ref={rootRef}- className="anim-msg my-2 overflow-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900"- >- {expandable ? (- // Sticky offsets follow the work-group header exactly: -top-4 cancels the message- // list's py-4 so the bar pins at the visible top; z-[5] above the row level, below- // the stream's overlays; fully opaque background so scrolling rows can't bleed through.- <button- type="button"- aria-expanded={open}- onClick={() => {- userToggled.current = true;- // Collapsing while the header is stuck: bring the (now header-only) card back- // into view once React commits — `nearest` makes every other case a no-op.- const willClose = open;- setOpen((v) => !v);- if (willClose) {- requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));- }- }}- className="sticky -top-4 z-[5] flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800"- >- {header}- </button>- ) : (- <div className="flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left dark:bg-gray-900">- {header}- </div>- )}- {expandable && open && (- <div className="anim-fade divide-y divide-gray-100 border-t border-gray-200 dark:divide-gray-800/60 dark:border-gray-800">- {children}- </div>- )}- </div>- );-}diff --git a/packages/web/src/features/chat/streaming-caret.tsx b/packages/web/src/features/chat/streaming-caret.tsxdeleted file mode 100644index fc0235e8..00000000--- a/packages/web/src/features/chat/streaming-caret.tsx+++ /dev/null@@ -1,13 +0,0 @@-/**- * 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/subagent-chip.tsx b/packages/web/src/features/chat/subagent-chip.tsxindex 435a756c..ffdae64c 100644--- a/packages/web/src/features/chat/subagent-chip.tsx+++ b/packages/web/src/features/chat/subagent-chip.tsx@@ -1,14 +1,11 @@/**- * Subagent shortcut row: the only trace a spawned child session leaves in the main chat flow- * (the full nested conversation lives in the subagents side panel). A full-width bar styled- * like the stream's other collapsed rows (the thinking block / work-group header idiom:- * rounded border, muted background, left-aligned content) — agent avatar + resolved agent name- * + short session-id suffix — with a spinner while the child runs and an amber dot (also- * announced in the accessible name) while any approval is pending anywhere in the child's- * subtree, so a nested approval stays discoverable with the panel closed. Clicking opens the- * panel focused on this child via ctx.onOpenSubagent.+ * A spawned child session's row in the parent's stream, drawn by the shared UI package's+ * `SubagentChip`: this resolves the child's agent name from the Project's agents and sessions,+ * finds whether an approval waits anywhere in the child's subtree (so a nested approval stays+ * discoverable with the panel closed, and is announced in the row's name), and opens the+ * subagents panel focused on the child through ctx.onOpenSubagent.*/-import { AgentAvatar, Spinner } from "@prismshadow/penguin-ui";+import { SubagentChip } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { hasPendingWithinOrigin } from "../../lib/omni/stream-model";import type { StreamModel } from "../../lib/omni/stream-model";@@ -16,9 +13,8 @@ import { useProject } from "../../state/project";import { useSessions } from "../../state/sessions";import { resolveAgentLabel, shortSessionId } from "./agent-topology";import type { StreamRenderContext } from "./message-stream";-import { toneDot } from "../../lib/tone";-export function SubagentChip({+export function SessionSubagentChip({sessionId,model,running,@@ -34,39 +30,20 @@ export function SubagentChip({}) {const { agents } = useProject();const { sessions } = useSessions();+ const resolvedAgentId = model.meta?.agentId ?? agentId;const label =- resolveAgentLabel({ sessionId, agentId: model.meta?.agentId ?? agentId }, agents, sessions) ??- S.chat.subagent;+ resolveAgentLabel({ sessionId, agentId: resolvedAgentId }, agents, sessions) ?? S.chat.subagent;const pending = hasPendingWithinOrigin(ctx.pendingApprovals.keys(), [...ctx.origin, sessionId]);- const name = `${S.chat.subagent} ${label}${pending ? ` · ${S.chat.approvalWaiting}` : ""}`;return (- // Full-width bar, same visual family as the work-group header / thinking row (rounded-md- // border + muted background + px-3 py-2 left-aligned content) — not a compact pill, so the- // row lines up with the stream's other collapsed step rows.- <button- type="button"- aria-label={name}- data-tooltip={name}- onClick={() => ctx.onOpenSubagent?.(sessionId, ctx.origin)}- className="flex w-full items-center gap-2 rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-900/60 dark:hover:bg-gray-800/60"- >- <AgentAvatar id={model.meta?.agentId ?? agentId ?? sessionId} name={label} size={16} />- <span className="min-w-0 truncate text-xs font-medium text-gray-700 dark:text-gray-300">- {label}- </span>- {sessionId && (- <span className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">- {shortSessionId(sessionId)}- </span>- )}- {running && (- <Spinner size="xs" label={S.common.loading} className="text-gray-400 dark:text-gray-500" />- )}- {pending && (- <span aria-hidden className={`h-1.5 w-1.5 shrink-0 rounded-full ${toneDot.attention}`} />- )}- <span className="min-w-0 flex-1" />- </button>+ <SubagentChip+ label={label}+ name={`${S.chat.subagent} ${label}${pending ? ` · ${S.chat.approvalWaiting}` : ""}`}+ avatarId={resolvedAgentId ?? sessionId}+ {...(sessionId ? { tag: shortSessionId(sessionId) } : {})}+ running={running}+ pending={pending}+ onOpen={() => ctx.onOpenSubagent?.(sessionId, ctx.origin)}+ />);}diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsxindex 45551ef3..4d99f81a 100644--- a/packages/web/src/features/chat/subagents-view.tsx+++ b/packages/web/src/features/chat/subagents-view.tsx@@ -39,6 +39,7 @@ import {GlyphIcon,ICON_SIZE,StatusIcon,+ Text,toastError,} from "@prismshadow/penguin-ui";import { ApiError } from "../../api/client";@@ -210,9 +211,9 @@ export function SubagentsView({<div className="flex h-full min-h-0 flex-col">{/* Call graph of the displayed Task — latest by default, a chip's Task when pinned (capped height; scrolls both ways for deep/wide trees). */}<div className="shrink-0 border-b border-gray-200 px-3 pb-2 pt-1.5 dark:border-gray-800">- <p className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">+ <Text variant="eyebrow" className="mb-1.5">{S.subagentPanel.topologyLabel}- </p>+ </Text>{nodes.length > 1 ? (<div className="max-h-48 overflow-y-auto"><AgentTopologyView@@ -258,7 +259,7 @@ export function SubagentsView({</span><spandata-tooltip={active.sessionId}- className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500"+ className="shrink-0 font-mono text-xs text-fg-subtle">{shortSessionId(active.sessionId)}</span>diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsxindex ad601a57..a3425dfc 100644--- a/packages/web/src/features/chat/task-stats-line.tsx+++ b/packages/web/src/features/chat/task-stats-line.tsx@@ -108,7 +108,7 @@ export function TaskStatsLine({// The copy button sits outside the scrollable span, so it stays pinned at the row's end// instead of scrolling out of reach.return (- <div className="-mt-2 flex h-5 items-center justify-start gap-x-2 overflow-hidden whitespace-nowrap text-[11px] text-gray-400 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:gap-x-3 sm:opacity-0 dark:text-gray-500">+ <div className="-mt-2 flex h-5 items-center justify-start gap-x-2 overflow-hidden whitespace-nowrap text-xs text-fg-subtle transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:gap-x-3 sm:opacity-0"><span className="no-scrollbar flex min-w-0 items-center gap-x-2 overflow-x-auto sm:gap-x-3">{/* Timestamp leads: it's this reply's identity (when it was said), the stat numbers are anannotation. When this turn has no token_usage (reply was aborted), only the timestampdiff --git a/packages/web/src/features/chat/thinking-block.tsx b/packages/web/src/features/chat/thinking-block.tsxindex ade0ca1c..7fd47770 100644--- a/packages/web/src/features/chat/thinking-block.tsx+++ b/packages/web/src/features/chat/thinking-block.tsx@@ -1,57 +1,23 @@/**- * Thinking block: one row within the "Reasoning & Tools" group — status- * icon + "Thinking" + elapsed time, click to expand the full thinking text. Built on the- * shared disclosure shell (disclosure-row.tsx), so its row metrics and color states are the- * same source every other disclosure row uses; shares the running-state icons (in progress /- * done / failed) with tool cards.+ * A thinking item of the session's stream, drawn by the shared UI package's `ThinkingBlock`:+ * this binds the item's streaming and stop state to the row's run state and labels.*/-import {- DISCLOSURE_BODY_MD_CLASS,- DisclosureRow,- LiveDuration,- Md,- StatusIcon,- activityState,-} from "@prismshadow/penguin-ui";-import type { RunState } from "@prismshadow/penguin-ui";+import { ThinkingBlock } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";-import { humanizeDuration } from "../../lib/format";import type { ThinkingItem } from "../../lib/omni/stream-model";-export function ThinkingBlock({ item }: { item: ThinkingItem }) {+export function SessionThinking({ item }: { item: ThinkingItem }) {const failed = item.stopReason !== undefined && item.stopReason !== "completed";- const state: RunState = item.streaming ? "running" : failed ? "failed" : "done";- const stateLabel = item.streaming- ? S.chat.workRunning- : failed- ? item.stopReason- : S.chat.workDone;-+ const state = item.streaming ? "running" : failed ? "failed" : "done";return (- <DisclosureRow- sticky- activity={{ kind: "thinking", state: activityState(state) }}- icon={<StatusIcon state={state} label={stateLabel} />}+ <ThinkingBlock+ state={state}+ stateLabel={item.streaming ? S.chat.workRunning : failed ? item.stopReason : S.chat.workDone}label={S.chat.thinking}- trailing={- <>- <span- data-slot="detail"- className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400"- >- {item.streaming ? (- <LiveDuration sinceMs={item.startedAtMs} />- ) : item.durationMs !== undefined ? (- humanizeDuration(item.durationMs)- ) : null}- </span>- {failed && <span className="font-mono text-xs text-gray-400">[{item.stopReason}]</span>}- </>- }- >- <div className={`anim-fade ${DISCLOSURE_BODY_MD_CLASS}`}>- <Md text={item.thinking} streaming={item.streaming} />- </div>- </DisclosureRow>+ text={item.thinking}+ startedAtMs={item.startedAtMs}+ durationMs={item.durationMs}+ stopReason={failed ? item.stopReason : undefined}+ />);}diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsxindex 0be5ff4c..b242d04b 100644--- a/packages/web/src/features/chat/tool-call-card.tsx+++ b/packages/web/src/features/chat/tool-call-card.tsx@@ -1,45 +1,28 @@/**- * Tool call card: collapses to a single line by- * default — status icon + tool name + duration (a live-ticking timer while running) + a plain- * `[stop reason]` marker when the step did not finish cleanly; clicking expands full arguments- * and output; a bound subagent renders as a full-width shortcut row below them regardless of- * collapsed state (the child conversation itself lives in the subagents side panel; the row- * carries its own pending-approval dot, so the card no longer needs to auto-expand for nested- * approvals).+ * A tool call of the session's stream, drawn by the shared UI package's `ToolCallCard`: this+ * binds the stream item, the pending-approval map and the session's callbacks to the card, and+ * holds the tool-specific reading of the call's arguments (the previews below), which is the+ * app's knowledge of its tools, not the card's.** Duration accounting = **argument-generation segment + execution segment** (excludes time* spent waiting on human approval): the model streaming out arguments token by token is often* slower than the tool call itself, so reporting only the execution segment would badly* understate this step's cost. While waiting on approval, the already-settled generation- * segment is shown; the wait itself is marked by the amber hourglass icon alone, since the- * approval block below the row is always on screen and names the tool and its arguments.+ * segment is shown; the wait itself is marked by the hourglass icon alone, since the approval+ * block below the row is always on screen and names the tool and its arguments.*/-import { useMemo, useRef, useState } from "react";+import { useMemo } from "react";import { DETACHED_TOOL_NOTE_PREFIX } from "@prismshadow/penguin-core/interfaces";-import {- ActivityProgress,- Chevron,- DISCLOSURE_OUTPUT_PRE_CLASS,- DISCLOSURE_ROW_CLASS,- DISCLOSURE_ROW_STICKY_CLASS,- LiveDuration,- StatusIcon,- ZoomableImage,- activityState,- useElapsedPast,-} from "@prismshadow/penguin-ui";-import type { RunState } from "@prismshadow/penguin-ui";+import { ToolCallCard, useElapsedPast } from "@prismshadow/penguin-ui";+import type { RunState, ToolCallDuration } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";-import { humanizeDuration } from "../../lib/format";import { toolDisplayName } from "../../lib/tool-alias";import { stripAnsi } from "../../lib/strip-ansi";import { approvalKey } from "../../lib/omni/stream-model";import type { ToolCallItem } from "../../lib/omni/stream-model";-import { toneInk } from "../../lib/tone";-import { ApprovalButtons } from "./approval-buttons";import { useTheme } from "../../state/theme";import { agentIdFromRunSubagentArgs } from "./agent-topology";-import { SubagentChip } from "./subagent-chip";+import { SessionSubagentChip } from "./subagent-chip";import type { StreamRenderContext } from "./message-stream";/** Tools that accept the optional model-written `description` argument. */@@ -298,31 +281,21 @@ function extractStringField(argsJson: string, field: string): PartialField | nulreturn { value: out, complete: false };}-export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRenderContext }) {- const [open, setOpen] = useState(false);- const userToggled = useRef(false);- const rootRef = useRef<HTMLDivElement>(null);+export function SessionToolCall({ item, ctx }: { item: ToolCallItem; ctx: StreamRenderContext }) {const { toolAliases } = useTheme();// Matched by the current origin chain + toolCallId: prevents parent/child session tool_call_id collisions from lighting each other up.const pending = ctx.pendingApprovals.get(approvalKey(ctx.origin, item.toolCallId));- const preview = previewArguments(item.name, item.argumentsText);- // Display-only, and confined to the two render expressions below: every name-keyed- // decision on this card (DESCRIBED_TOOLS, FILE_TOOLS, the argument previews, the subagent- // chip) and everywhere else in the app (the tools config table, permission rules, the- // Trace viewer) keeps reading `item.name`, so an alias can never change what a call means.+ // Display-only, and confined to the name props below: every name-keyed decision on this card+ // (DESCRIBED_TOOLS, FILE_TOOLS, the argument previews, the subagent chip) and everywhere else in+ // the app (the tools config table, permission rules, the Trace viewer) keeps reading+ // `item.name`, so an alias can never change what a call means.const displayName = toolDisplayName(item.name, toolAliases);- // The tool's own name stays one hover away, for matching a Trace or writing a permission- // rule; when nothing was aliased the tooltip would only repeat the visible text.- const nameTitle = displayName === item.name ? undefined : item.name;// Escape sequences are stripped at render time only (the stored stream/trace data keeps its// raw bytes): hardened child envs should no longer produce any, but historical traces and// force-color programs still can (#102). Memoized — the aggregated output can be large and// grows on every streamed delta.const output = useMemo(() => stripAnsi(item.output), [item.output]);- // Settled once argument streaming stopped (or the complete call arrived): the subtitle's- // completeness gate is lifted — whatever is there is final.- const subtitle = headerSubtitle(item.name, item.argumentsText, !item.callStreaming);// Executing = the call has finished streaming, output hasn't arrived yet, and it's not waiting on approval (approval wait time doesn't count toward execution).const executing = item.callComplete && !item.outputComplete && !pending;// Whether the execution segment has run long enough for the "move to background" action (one@@ -351,7 +324,7 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen: failed? "failed": "done";- // Decision wording ("Approved · manual", "Denied · manual", …): carried ONLY by the left status+ // Decision wording ("Approved · manual", "Denied · manual", …): carried ONLY by the status// icon's title/aria-label — per review the row shows no visible decision text at any// breakpoint; the icon is the single source of truth for how the call was decided.const decisionText = item.decision@@ -371,16 +344,6 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRenconst denied =(item.decision === "deny" || item.decision === "forbidden") &&item.outputStopReason === "aborted";- // Shared by the row and the chevron beside it: two buttons, one disclosure. Collapsing- // while the row is stuck lands the view back on the row.- const toggleOpen = (): void => {- userToggled.current = true;- const willClose = open;- setOpen((v) => !v);- if (willClose) {- requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));- }- };const stateLabel = pending? S.chat.approvalWaiting: state === "running"@@ -390,231 +353,94 @@ export function ToolCallCard({ item, ctx }: { item: ToolCallItem; ctx: StreamRen: denied? (decisionText ?? undefined): (item.outputStopReason ?? item.callStopReason);+ // Total duration = argument generation + execution, excluding the approval wait: settled once+ // known; while executing, a live segment from the approval grant (or from call completion when+ // no approval was needed) on top of the generation baseline; while waiting on approval, frozen+ // at the settled generation segment; while the arguments stream, a live clock from their start+ // (an ellipsis when no start time is known).+ const duration: ToolCallDuration | undefined =+ item.durationMs !== undefined+ ? { live: false, ms: item.durationMs }+ : executing+ ? { live: true, sinceMs: item.approvalAtMs ?? item.callStartedAtMs, offsetMs: genMs }+ : pending+ ? genMs > 0+ ? { live: false, ms: genMs }+ : undefined+ : item.callStreaming+ ? { live: true, sinceMs: item.argStartedAtMs }+ : undefined;+ const sendToBackground = ctx.onSendToBackground;return (- <div ref={rootRef}>- {/* Collapsed row: status icon + tool name + total duration (generation + execution,- excluding approval wait) + the stop reason when the step did not finish cleanly.- Expand chevron on the right.-- Stacked sticky, second level (same as the thinking row): while this card's expanded- output scrolls, the row pins right BELOW the stuck group header (top-4 = the- header's -top-4 offset + its 2rem height) — the bar directly above the content is- always the section the reader is in, never a skipped level. Opaque background for- the stuck state; collapsing from stuck lands the view back on the row.-- The row spells out NO stop reason: it rendered `[reason]` markers (and before that,- Badge pills) until per-user-feedback review removed them — the red text read as- alarming repetition of what the left StatusIcon already signals. The icon plus its- title/aria stateLabel (which still names the raw reason) is the single carrier of- the outcome, same rule the decision wording above already follows. The known cost,- accepted deliberately: at a glance an aborted, timed-out, malformed or auth-failed- call all read as the icon's one failure tone, and on touch the distinction lives- only in the expanded output (when one exists) — the tooltip/aria and the Trace- viewer, which shows the raw stop reason per event, remain where the literal value- belongs.-- A pending call gets no "awaiting approval" text either: the approval block below is- always on screen while one is pending — it names the tool, shows the arguments and- carries the Allow/Deny buttons — so the row would only repeat it. The amber hourglass- StatusIcon (labeled) marks the wait, at every breakpoint.-- ui-activity: the row is a work step, so a theme may render it running or settled its- own way; the tool name is its label and the subtitle and duration its details. */}- <div- className={`ui-activity ${DISCLOSURE_ROW_STICKY_CLASS} ${DISCLOSURE_ROW_CLASS}`}- data-kind="tool"- data-state={activityState(state)}- >- <button- type="button"- aria-expanded={open}- onClick={toggleOpen}- className="flex min-w-0 flex-1 items-center gap-2 self-stretch text-left"- >- <StatusIcon state={state} label={stateLabel} />- <span- data-tooltip={nameTitle}- data-tooltip-content="code"- data-slot="label"- className="shrink-0 truncate font-mono text-xs font-semibold text-gray-700 dark:text-gray-300"- >- {displayName || S.chat.unknownTool}- </span>- {/* Human-readable subtitle: the model-written call description (command/subagent tools) or the file path (file tools). */}- {subtitle && (- <span- data-slot="detail"- className="min-w-0 shrink truncate text-xs text-gray-500 dark:text-gray-400"- >- {subtitle}- </span>- )}- <span- data-slot="detail"- className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400"- >- {item.durationMs !== undefined ? (- humanizeDuration(item.durationMs)- ) : executing ? (- // Execution timer: argument-generation baseline + a live segment starting from approval grant (or from call completion if no approval was needed).- <LiveDuration sinceMs={item.approvalAtMs ?? item.callStartedAtMs} offsetMs={genMs} />- ) : pending ? (- // No ticking while waiting on approval: frozen at the settled argument-generation segment.- genMs > 0 ? (- humanizeDuration(genMs)- ) : null- ) : item.callStreaming ? (- // Generating arguments: live-ticking timer (falls back to a pulsing ellipsis when no start time is known).- item.argStartedAtMs !== undefined ? (- <LiveDuration sinceMs={item.argStartedAtMs} />- ) : (- <span className="animate-pulse">…</span>- )- ) : null}- </span>- <ActivityProgress running={state === "running"} />- <span className="min-w-0 flex-1" />- </button>- {/* At the row's right end, on a call made with run_in_background or moved there: a- bracketed marker in the row's own mono type, the shape this row already used for an- outcome that needs a word. A glyph here would be the session list's count-of-many- mark doing duty for a single call, and it would say nothing to a reader who cannot- spend a hover on it. It takes the very slot the "send to background" action below- occupies — the two never show together, and a click on the action leaves the mark- in its place — so the row's right end holds one thing, right-aligned, rather than a- word after the duration and an action further along. The row's own status icon- keeps saying what the CALL did; this says where its work went. */}- {(isBackgroundCall(item.argumentsText) || isDetachedCall(item.output)) && (- <span className={`shrink-0 font-mono text-xs ${toneInk.muted}`}>- {S.chat.backgroundCall}- </span>- )}- {/* "Send to background" once the call has been executing for a while: the tool hands- its work back as a background task and the turn carries on. A sibling of the row- button rather than a child — a <button> cannot nest another — with the hover tint on- the whole row, so the two still read as one line. The app's inline text-action style:- a real <button> (it acts, it navigates nowhere) painted as a link. Text at the row's- own size and NO padding of its own, so a row carrying it measures exactly like one- that does not — an action that changed the row's height would break the rhythm of a- list of calls. It waits BACKGROUND_ACTION_DELAY_MS before appearing: a command that- returns in a few seconds never shows an action it would only take away again.-- No click guard: a second detach is a no-op on an already-fired controller, and once- the call closes the action unmounts on its own — which is also the feedback. */}- {showsBackgroundAction(+ <ToolCallCard+ state={state}+ stateLabel={stateLabel}+ name={displayName || S.chat.unknownTool}+ // The tool's own name stays one hover away, for matching a Trace or writing a permission+ // rule; when nothing was aliased the tooltip would only repeat the visible text.+ nameTooltip={displayName === item.name ? undefined : item.name}+ // Settled once argument streaming stopped (or the complete call arrived): the subtitle's+ // completeness gate is lifted — whatever is there is final.+ subtitle={headerSubtitle(item.name, item.argumentsText, !item.callStreaming)}+ duration={duration}+ // A call made with run_in_background, or moved there: the row says where its work went.+ marker={+ isBackgroundCall(item.argumentsText) || isDetachedCall(item.output)+ ? S.chat.backgroundCall+ : undefined+ }+ // "Send to background" once the call has been executing for a while: the tool hands its+ // work back as a background task and the turn carries on. No click guard: a second detach+ // is a no-op on an already-fired controller, and once the call closes the action unmounts+ // on its own — which is also the feedback.+ action={+ sendToBackground !== undefined &&+ showsBackgroundAction(item.name,item.argumentsText,executing,ctx.origin,executedPastDelay,- ) &&- ctx.onSendToBackground && (- <button- type="button"- data-tooltip={S.chat.sendToBackgroundHint}- onClick={() => void ctx.onSendToBackground?.(item.toolCallId)}- className="shrink-0 text-xs text-brand-600 underline-offset-2 hover:underline dark:text-brand-300"- >- {S.chat.sendToBackground}- </button>- )}- {/* Expand indicator on the right; clicking it toggles too (it is its own button, so the- row's action above stays reachable). Named for what it DOES, the way every other- chevron toggle here is: naming it after the tool would give the row two buttons under- one name, which no row-scoped query could then tell apart. */}- <button- type="button"- aria-expanded={open}- aria-label={open ? S.nav.collapseGroup : S.nav.expandGroup}- onClick={toggleOpen}- className="flex shrink-0 items-center self-stretch"- >- <Chevron open={open} className="text-gray-400" />- </button>- </div>-- {/* Pending approval: always visible regardless of collapsed state — shows the tool name and arguments so the user knows what they're approving. */}- {pending && (- <div className="border-t border-gray-100 bg-amber-50 px-3 py-2 dark:border-gray-800 dark:bg-amber-950/30">- {/* The user must be able to read the FULL command before deciding: below sm the- preview wraps in whole (expanded-args style: pre-wrap + break-all, no inner- scroll, the block may grow) — the one-line treatment resumes once decided, since- this pending block unmounts and only the truncating header subtitle remains. At- ≥sm the row stays one line (the desktop column is wide enough in practice). */}- <div className="mb-2 flex items-start gap-2 sm:items-center">- <span- data-tooltip={nameTitle}- className="shrink-0 rounded-md bg-white px-1.5 py-0.5 font-mono text-xs font-semibold text-gray-700 dark:bg-gray-900 dark:text-gray-300"- >- {displayName || S.chat.unknownTool}- </span>- <span className="min-w-0 flex-1 whitespace-pre-wrap break-all font-mono text-xs text-gray-600 sm:truncate dark:text-gray-400">- {preview}- </span>- </div>- {/* File tools: the one-line preview shows only the (shortened) path, but the user is- approving a concrete rewrite — render the decoded payload (old_string/new_string/- content) in the scrollable expanded style while pending. */}- {(() => {- const payload = pendingFilePayload(item.name, item.argumentsText);- return payload !== null ? (- <pre className="mb-2 max-h-72 overflow-auto whitespace-pre-wrap break-all rounded-md bg-white/70 px-2 py-1.5 text-xs leading-5 text-gray-700 dark:bg-gray-950/40 dark:text-gray-300">- {payload}- </pre>- ) : null;- })()}- <ApprovalButtons- onDecide={(decision) => ctx.onApprove(item.toolCallId, decision, ctx.origin)}- />- </div>- )}-- {/* Expanded details: full arguments / output */}- {open && (- <div className="anim-fade">- {item.argumentsText && (- // Arguments are shown as a fully wrapped block (no height cap, no scrollbar): the- // arguments are key to understanding this call, and tucking them into an inner- // scroll area would make them hard to read and fight with the message stream's own scroll.- <pre className="whitespace-pre-wrap break-all border-t border-gray-100 bg-gray-50 px-3 py-2 text-xs text-gray-600 dark:border-gray-800 dark:bg-gray-950/60 dark:text-gray-400">- {item.argumentsText}- </pre>- )}- {(item.output || item.outputStreaming) && (- <pre className={DISCLOSURE_OUTPUT_PRE_CLASS}>- {output}- {item.outputStreaming && <span className="animate-pulse">▌</span>}- </pre>- )}- {/* Tool output images (e.g. read_file on an image): shown as thumbnails, click to zoom (ZoomableImage). */}- {item.images && item.images.length > 0 && (- <div className="flex flex-wrap gap-2 border-t border-gray-100 px-3 py-2 dark:border-gray-800">- {item.images.map((src, i) => (- <ZoomableImage- key={i}- src={src}- alt={S.chat.toolImageAlt}- className="max-h-40 max-w-full rounded-md border border-gray-200 dark:border-gray-700"- />- ))}- </div>- )}- </div>- )}-- {/* Subagent row: always visible (unaffected by the tool card's collapsed state) below the expanded arguments/output — a full-width shortcut bar into the subagents panel; the nested conversation no longer renders inline. */}- {item.subagent && (- <div className="px-3 pb-2 pt-2">- <SubagentChip+ )+ ? {+ label: S.chat.sendToBackground,+ hint: S.chat.sendToBackgroundHint,+ onClick: () => void sendToBackground(item.toolCallId),+ }+ : undefined+ }+ pending={+ pending+ ? {+ preview: previewArguments(item.name, item.argumentsText),+ payload: pendingFilePayload(item.name, item.argumentsText),+ onDecide: (decision) => ctx.onApprove(item.toolCallId, decision, ctx.origin),+ labels: { allow: S.chat.approve, deny: S.chat.deny },+ }+ : undefined+ }+ argumentsText={item.argumentsText}+ output={output}+ outputStreaming={item.outputStreaming}+ images={+ item.images && item.images.length > 0+ ? { srcs: item.images, alt: S.chat.toolImageAlt }+ : undefined+ }+ // A bound subagent: a shortcut row into the subagents panel, shown whatever the card's+ // collapsed state (the nested conversation itself no longer renders inline).+ footer={+ item.subagent ? (+ <SessionSubagentChipsessionId={item.subagentSessionId ?? ""}model={item.subagent}running={!item.outputComplete}agentId={agentIdFromRunSubagentArgs(item.argumentsText)}ctx={ctx}/>- </div>- )}- </div>+ ) : undefined+ }+ />);}diff --git a/packages/web/src/features/chat/work-group.tsx b/packages/web/src/features/chat/work-group.tsxindex bba831c5..f88fdf9d 100644--- a/packages/web/src/features/chat/work-group.tsx+++ b/packages/web/src/features/chat/work-group.tsx@@ -1,42 +1,25 @@/**- * "Reasoning & Tools" group: collapses a run of consecutive thinking +- * tool-call items into one aggregated group.- * Expand policy, two layers deep: the group opens while it is running and closes itself once- * it is done, and the thinking/tool rows inside it are appended one at a time and stay closed- * — the reader is shown that a step happened and how long it took, not its contents, until- * they ask. A manual toggle by the user is respected afterward. A pending approval **forces it- * open** — otherwise the approval buttons would be unreachable.+ * The session's "Reasoning & Tools" group: binds a run of consecutive thinking and tool-call+ * items to the shared UI package's `WorkGroup`, which draws it and owns its expand policy.*- * Hierarchy: the group header is **a distinct title bar** (solid light-gray background + small- * uppercase status text), and the thinking/tool-call rows inside the group sit on the white- * area below it — the two are deliberately different layers, otherwise "Running"/"Done" would- * blend visually with the step rows and the parent-child relationship would be unreadable.+ * What is decided here is the group's state, from the stream model:*- * Status semantics: the group only counts as "Done" once the model stops calling tools. As long- * as this is still the last segment and the Task is running, the model could add another step- * at any moment (there can be a brief gap with no active item between two steps), so it always- * shows "Running"; it flips to "Done" only once a later message (e.g. body text) pushes the- * group away from the end, or the Task has actually finished.+ * - Running vs Done: the group only counts as done once the model stops calling tools. While it+ * is the last segment and the Task runs, the model could add another step at any moment (with+ * a brief gap between two steps where no item is active), so it shows "Running"; it flips to+ * "Done" once a later message pushes it away from the end, or the Task finishes. Following this+ * rather than the per-item activity is what keeps the group from collapsing between steps.+ * - A pending approval anywhere in the group forces it open: the approval buttons live inside.+ * - The duration is `summarizeWork`'s span; it ticks only while an item is in flight.*/-import { useEffect, useRef, useState } from "react";-import {- ActivityProgress,- Chevron,- DISCLOSURE_CARD_CLASS,- DISCLOSURE_HEADER_ROW_CLASS,- DISCLOSURE_HEADER_STICKY_CLASS,- DISCLOSURE_HEADER_TITLE_CLASS,- LiveDuration,- StatusIcon,-} from "@prismshadow/penguin-ui";+import { WorkGroup } from "@prismshadow/penguin-ui";+import type { WorkGroupProps } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";-import { humanizeDuration } from "../../lib/format";import { approvalKey } from "../../lib/omni/stream-model";import type { ChatItem } from "../../lib/omni/stream-model";import { MessageItem } from "./message-item";import type { StreamRenderContext } from "./message-stream";import { summarizeWork } from "./work-summary";-import { toneDot, toneInk, toneSurface } from "../../lib/tone";/** Item kinds that belong in the group: thinking and tool calls (subagent cards are nested inside the run_subagent tool card, not listed separately). */export function isWorkItem(item: ChatItem): boolean {@@ -62,7 +45,35 @@ function hasPendingApproval(items: ChatItem[], ctx: StreamRenderContext): boolea);}-export function WorkGroup({+/** The group's state as the package's `WorkGroup` takes it, minus the rows. */+export function useWorkGroupState(+ items: ChatItem[],+ ctx: StreamRenderContext,+ isLast: boolean,+): Omit<WorkGroupProps, "rows"> {+ // Whether any item is in flight right now — also the only window in which the group's span is+ // still growing, which the duration display depends on.+ const stepRunning = items.some((it) => itemActive(it, ctx));+ // Last segment + Task running = the model might still call another tool → Running, even with+ // no active item right now.+ const running = (isLast && ctx.taskRunning) || stepRunning;+ const { steps, durationMs, startMs } = summarizeWork(items);+ return {+ running,+ stepRunning,+ // A group of thinking only is thinking; anything with a tool call in it is tool work.+ kind: items.some((it) => it.kind === "tool_call") ? "tool" : "thinking",+ // The title doubles as status: "Running" while in progress, "Done" when finished.+ title: running ? S.chat.workRunning : S.chat.workDone,+ // A pure-thinking group (no tool calls) doesn't show "0 steps".+ ...(steps > 0 ? { count: S.chat.workGroupSteps(steps) } : {}),+ ...(startMs !== undefined ? { startMs } : {}),+ durationMs,+ pending: hasPendingApproval(items, ctx),+ };+}++export function SessionWorkGroup({items,ctx,isLast,@@ -72,163 +83,14 @@ export function WorkGroup({/** Whether this group is the last segment of the message stream (current turn still in progress): decides the default expanded/collapsed state. */isLast: boolean;}) {- // Whether any item is in flight right now — also the only window in which the group's span is- // still growing, which the duration display below depends on.- const itemsRunning = items.some((it) => itemActive(it, ctx));- // Last segment + Task running = the model might still call another tool → show Running (even if there's no active item right now).- const active = (isLast && ctx.taskRunning) || itemsRunning;- const pending = hasPendingApproval(items, ctx);- const [open, setOpen] = useState(active);- const userToggled = useRef(false);- const rootRef = useRef<HTMLDivElement>(null);-- // Before any manual toggle, follow the header's own Running/Done state: expanded while the- // group is working, collapsed the moment it is done — whether that is later messages pushing- // it away from the end mid-turn, or the Task ending on it. Deliberately `active` and not- // per-item `itemsRunning`: there can be a brief gap with no active item between two steps- // within a turn, and collapsing on that basis would flicker on every step and lose the- // internal expanded state — the "last segment + Task running" half of `active` bridges those- // gaps, so the group closes once and stays closed.- useEffect(() => {- if (!userToggled.current) setOpen(active);- }, [active]);-- // A pending approval must stay actionable: expand the group body regardless of collapsed state (the approval row lives inside it).- const shown = open || pending;- const { steps, durationMs, startMs } = summarizeWork(items);- // The header is a work step of its own for the activity hook: a group of thinking only is- // thinking, anything with a tool call in it is tool work.- const activityKind = items.some((it) => it.kind === "tool_call") ? "tool" : "thinking";-+ const state = useWorkGroupState(items, ctx, isLast);return (- // overflow-clip (not overflow-hidden): the header below is position:sticky, and an- // overflow-hidden ancestor is a scroll container — the header would then stick to this- // card instead of the message list's scrollport, i.e. not stick at all. `clip` keeps- // the exact same clipping (rounded corners included) without creating a scroll- // container, and a sticky element never leaves its containing block, so the stuck- // header itself is never clipped.- // ui-frame: the group is a framed box with a head (the header) and a body (the tree), so a- // theme that draws its transcript without boxes can take this one away.- <div ref={rootRef} className={`ui-frame ${DISCLOSURE_CARD_CLASS}`}>- {/* Group header: a distinct title bar (solid background), on a separate layer from the- step rows below it. Sticky against the message list's scrollport so a long expanded- group can be collapsed from anywhere inside it — without this, finding the start of- a long thinking/tool run means scrolling all the way back up. This is the FIRST of- two stacked sticky levels: the currently scrolled thinking/tool row pins right- below it at top-4 (see thinking-block.tsx / tool-call-card.tsx), so the bar- directly above the content is always the section being read — the group header- alone would skip a level. The background must stay fully opaque (the old dark- 900/60 read identically over the solid-900 card, but stuck over scrolling rows it- would let them bleed through); z above the row level (z-[4]), below the stream's- own overlays (back-to-bottom uses z-10). -top-4, not top-0: sticky offsets resolve- against the scrollport INSIDE the scroll container's padding, so top-0 pins a py-4- strip lower than the visible top and content scrolls through that gap; -top-4 is- the same rem unit as the container's py-4, cancelling exactly at every font scale- (the rows' top-4 = this offset plus the header's 2rem height, same reasoning). */}- <button- type="button"- data-group-header- aria-expanded={shown}- onClick={() => {- userToggled.current = true;- // Collapsing while the header is stuck: the group's real top edge sits above the- // fold, so after the body vanishes the viewport would land on unrelated content —- // bring the (now header-only) group back into view once React commits. `nearest`- // makes expanding and in-view collapsing a no-op. A forced-open pending approval- // keeps the body (shown stays true), so that click moves nothing either.- const willClose = open && !pending;- setOpen((v) => !v);- if (willClose) {- requestAnimationFrame(() => rootRef.current?.scrollIntoView({ block: "nearest" }));- }- }}- className={`ui-activity ${DISCLOSURE_HEADER_STICKY_CLASS} ${DISCLOSURE_HEADER_ROW_CLASS}`}- data-slot="head"- data-kind={activityKind}- data-state={active ? "running" : "done"}- >- <StatusIcon state={active ? "running" : "done"} />- {/* The title doubles as status: "Running" while in progress, "Done" when finished. */}- <span- data-slot="label"- className={`${DISCLOSURE_HEADER_TITLE_CLASS} ${active ? toneInk.busy : "text-gray-500 dark:text-gray-400"}`}- >- {active ? S.chat.workRunning : S.chat.workDone}- </span>- {/* A pure-thinking group (no tool calls) doesn't show "0 steps"; below sm the count is- dropped entirely (title on the header carries nothing extra — the header must stay- a single uncut line on phones). */}- {steps > 0 && (- <span- data-slot="detail"- className="hidden shrink-0 font-mono text-xs text-gray-400 sm:inline"- >- {S.chat.workGroupSteps(steps)}- </span>- )}- {/* Both states show the same quantity: the summarizeWork span (earliest item start →- latest item end). That's the canonical definition here — it's what work-summary.ts- documents, and unlike a group-open→now wall clock it is reconstructible from the- stored timestamps, so reloading the transcript reproduces the same number. While an- item is in flight its end isn't known yet, so the tick extends the span to *now*- (whole seconds); with nothing in flight the value freezes at the computed span, with- decimals — the same "don't tick through a wait we don't count" idiom as a tool card- parked on an approval. Ticking on while the group merely stays Running (the model- thinking between steps, or streaming its answer) would climb past the span and then- snap backwards the moment the group settles. */}- {itemsRunning- ? startMs !== undefined && (- <span data-slot="detail" className="shrink-0 font-mono text-xs text-gray-400">- <LiveDuration sinceMs={startMs} />- </span>- )- : durationMs > 0 && (- <span data-slot="detail" className="shrink-0 font-mono text-xs text-gray-400">- {humanizeDuration(durationMs)}- </span>- )}- {pending && !shown && (- <>- {/* Below sm the pill collapses to a bare amber dot (title/aria carry the meaning):- the text pill would push the header past one line on phones. role="img", not a- live region — same non-live semantics as the text pill, so re-renders don't- chatter at screen readers. */}- <span- className={`hidden shrink-0 rounded px-1 text-[10px] font-medium sm:inline ${toneSurface.attention}`}- >- {S.chat.approvalWaiting}- </span>- <span- role="img"- data-tooltip={S.chat.approvalWaiting}- aria-label={S.chat.approvalWaiting}- className={`h-1.5 w-1.5 shrink-0 rounded-full sm:hidden ${toneDot.attention}`}- />- </>- )}- <ActivityProgress running={itemsRunning} />- <span className="min-w-0 flex-1" />- <Chevron open={shown} className="text-gray-400" />- </button>- {/* ui-tree: the steps hang off the header one level down, so a theme may join them to- it with connector rules instead of the box. Each step is wrapped rather than marked- on its own root, because the thinking and tool rows also render outside a group. */}- {shown && (- <div- data-slot="body"- className="ui-tree anim-fade divide-y divide-gray-100 border-t border-gray-200 dark:divide-gray-800/60 dark:border-gray-800"- >- {items.map((item, index) => (- <div- key={item.id}- data-depth="1"- {...(index === items.length - 1 ? { "data-last": "true" } : {})}- >- <MessageItem item={item} ctx={ctx} />- </div>- ))}- </div>- )}- </div>+ <WorkGroup+ {...state}+ rows={items.map((item) => ({+ key: item.id,+ content: <MessageItem item={item} ctx={ctx} />,+ }))}+ />);}diff --git a/packages/web/src/features/company/channel-composer.tsx b/packages/web/src/features/company/channel-composer.tsxindex fbbbd3c6..d3a28575 100644--- a/packages/web/src/features/company/channel-composer.tsx+++ b/packages/web/src/features/company/channel-composer.tsx@@ -43,7 +43,7 @@ import type {DragEvent as ReactDragEvent,KeyboardEvent as ReactKeyboardEvent,} from "react";-import { Button, Dropdown, ICON_GAP, noAutofill } from "@prismshadow/penguin-ui";+import { Button, Dropdown, ICON_GAP, MenuLabel, noAutofill } from "@prismshadow/penguin-ui";import { S } from "../../lib/strings";import { PrincipalChip } from "./shared";import {@@ -437,11 +437,10 @@ export function ChannelComposer({<div id={listId} role="listbox" aria-label={S.company.channels.mentionPanel}>{rows.map(({ c, i, head }) => (<div key={c.principal}>- {head && (- <p className="px-2.5 pb-0.5 pt-1.5 text-[11px] font-medium text-gray-400 dark:text-gray-500">- {kindTitle(c.kind)}- </p>- )}+ {head && <MenuLabel>{kindTitle(c.kind)}</MenuLabel>}+ {/* An option rather than a MenuItem: the row must not take focus from the box+ (mouse-down is swallowed) and the walk is the box's own. Its inset is the menu+ rows', so it lines up under the group's label. */}<buttontype="button"role="option"@@ -450,14 +449,14 @@ export function ChannelComposer({onMouseDown={(e) => e.preventDefault()}onMouseEnter={() => setHighlight(i)}onClick={() => pick(c)}- className={`flex w-full items-center justify-between gap-3 px-2.5 py-1.5 text-left text-xs transition-colors duration-150 ${- i === highlight ? "bg-gray-100 dark:bg-gray-800" : ""+ className={`flex w-full items-center justify-between gap-3 px-3 py-1.5 text-left text-xs transition-colors duration-150 ${+ i === highlight ? "bg-line-muted" : ""}`}><span className="min-w-0 truncate"><PrincipalChip principal={c.principal} names={names} /></span>- <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">+ <span className="shrink-0 text-xs text-fg-subtle">{c.kind === "all"? S.company.channels.mentionAllDesc: c.kind === "employee"diff --git a/packages/web/src/features/company/channel-header.tsx b/packages/web/src/features/company/channel-header.tsxindex 7642edf2..6201c2a3 100644--- a/packages/web/src/features/company/channel-header.tsx+++ b/packages/web/src/features/company/channel-header.tsx@@ -24,6 +24,7 @@ import {ConfirmModal,Dropdown,GlyphIcon,+ Heading,ICONS,ICON_GAP,ICON_SIZE,@@ -157,15 +158,16 @@ function MemberPopover({<MemberAvatar member={m} size={ICON_SIZE.rowLead} /><Truncated text={m.name} className="min-w-0 flex-1" />{m.kind === "agent" && (- <button- type="button"+ <Button+ variant="ghost"+ size="xs"+ className="shrink-0"disabled={openingDesk !== null}onClick={() => onOpenDesk(m.principal)}- className={`flex shrink-0 items-center ${ICON_GAP.tight} rounded px-1.5 py-0.5 text-[11px] text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 disabled:opacity-60 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-100`}+ leading={<GlyphIcon d={DESK_ICON} size={ICON_SIZE.inlineGlyph} />}>- <GlyphIcon d={DESK_ICON} size={ICON_SIZE.inlineGlyph} />{S.company.openDesk}- </button>+ </Button>)}</div>))@@ -384,11 +386,14 @@ export function ChannelHeader({<div className="flex min-w-0 flex-1 items-baseline gap-x-3 gap-y-1">{/* The name is a direct child of the heading, with the "?" right after it — theanchoring every other title in the app uses (OrgPage's own header included), and- what test/disclosure-anchor.test.ts reads. The row clips rather than wraps: the- server caps a channel name at 100 characters and the tooltip carries it whole. */}- <h1+ what test/disclosure-anchor.test.ts reads. The page's one h1, set on the h4 rung:+ a header row's title, not a page's display title. The row clips rather than wraps:+ the server caps a channel name at 100 characters and the tooltip carries it whole. */}+ <Heading+ level={4}+ as="h1"data-tooltip={label}- className={`flex min-w-0 items-center overflow-hidden whitespace-nowrap ${ICON_GAP.row} text-[15px] font-semibold`}+ className={`flex min-w-0 items-center overflow-hidden whitespace-nowrap ${ICON_GAP.row}`}><span className="shrink-0 text-gray-400 dark:text-gray-500"><GlyphIcon d={channelGlyph(detail.channelId)} size={ICON_SIZE.rowLead} />@@ -403,7 +408,7 @@ export function ChannelHeader({</span><span className="mt-1.5 block">{S.company.channels.hopSummary}</span></InfoPopover>- </h1>+ </Heading>{/* The purpose reads as a subtitle on the same line, so the header stays one row. */}{purpose !== null && (<span@@ -510,7 +515,7 @@ export function ChannelHeader({missing. What that channel IS belongs to the header's "?", and repeating thewhole paragraph here made a menu out of an explanation. */}{allHands && detail.archived === false && (- <p className="px-2.5 py-1.5 text-[11px] text-gray-400 dark:text-gray-500">+ <p className="px-2.5 py-1.5 text-xs text-fg-subtle">{S.company.channels.allHandsNoArchive}</p>)}diff --git a/packages/web/src/features/company/channel-markdown.tsx b/packages/web/src/features/company/channel-markdown.tsxindex c2cfe27c..d624c1c4 100644--- a/packages/web/src/features/company/channel-markdown.tsx+++ b/packages/web/src/features/company/channel-markdown.tsx@@ -135,8 +135,8 @@ export function ChannelReaderProvider({/*** A mention as a chip: the resolved name after the `@`, the raw token in the tooltip;* attention-toned when it addresses the reader. The ordinary chip sits one step deeper than- * the app's usual grey fill, because the bubble it is printed on is that grey (channel-view's- * BUBBLE_SURFACE) and a chip the colour of its background is not a chip.+ * the app's usual grey fill, because the bubble it is printed on is that grey (the neutral+ * surface of the package's `ChannelBubble`) and a chip the colour of its background is not a chip.*/export function MentionChip({ raw, label, me }: { raw: string; label: string; me: boolean }) {return (diff --git a/packages/web/src/features/company/channel-view.tsx b/packages/web/src/features/company/channel-view.tsxindex eba216ec..8a70e373 100644--- a/packages/web/src/features/company/channel-view.tsx+++ b/packages/web/src/features/company/channel-view.tsx@@ -16,16 +16,11 @@* older stays behind "earlier", which prepends one day file per click.** The stream is drawn the way every chat client draws one, because a channel is read the way- * every chat is. Somebody else's run stands on the left: the avatar once, top-aligned so that- * it sits beside the sender's name — with the relay chip beside it from the second hop on, the- * whole @-chain rule in its tooltip — and the run's bubbles under both, in the column the name- * starts. Who is speaking is one mark, so the two halves of it stay on one line: an avatar tied- * to the run's last bubble drifts a screenful below its own name as soon as a message runs- * long. The reader's own run stands on the right in its own tint, with no avatar and no name- * (a screen reader gets one, since a side and a colour are not something every reader can- * read). Each bubble carries its own time at its bottom-right, inside it: a time that only- * appears on hover is a time a touch reader never sees, and one time per run leaves every- * later message in a long run unstamped.+ * every chat is: the UI package's ChannelRun and ChannelBubble draw a run and its messages —+ * somebody else's on the left under its avatar and name, the reader's own on the right in its+ * own tint, each bubble with its own time — and this view decides who is speaking, which side a+ * run stands on, and what hangs beside the name: the relay chip from the second hop on, the+ * whole @-chain rule in its tooltip.** A `system` line is one sentence, so it stays one muted line rather than a Markdown body: the* server writes it twice — as English text and as a structured notice — and the notice is what@@ -43,8 +38,9 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } frimport { useNavigate, useParams } from "react-router";import type { OrgChannelDetail, OrgChannelMessage } from "@prismshadow/penguin-server/api";import {- AgentAvatar,Button,+ ChannelBubble,+ ChannelRun,EmptyState,GlyphIcon,ICON_GAP,@@ -54,6 +50,7 @@ import {toastError,toastSuccess,} from "@prismshadow/penguin-ui";+import type { ChannelSender } from "@prismshadow/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";@@ -94,7 +91,7 @@ import {lastMessageId,messageCount,} from "./channel-stream";-import type { BubbleShape, ChannelDay, StreamItem } from "./channel-stream";+import type { ChannelDay, StreamItem } from "./channel-stream";import { parsePrincipal } from "./principals";/** What the first response fixes for this channel: today, the day list, and the read cursor the divider is drawn at. */@@ -108,35 +105,6 @@ interface StreamMeta {/** Downward arrow on the return-to-latest pill (lucide arrow-down). */const ARROW_DOWN_ICON = "M12 5v14M6 13l6 6 6-6";-/** The avatar that leads somebody else's run, in pixels — a tile, so one rung above a line glyph. */-const RUN_AVATAR_PX = 28;--/**- * The two bubble surfaces. The reader's own takes the app's brand blue rather than a tone from- * lib/tone.ts: which side of a conversation wrote a message is an identity, not a judgement,- * and a status hue would announce a state the message does not have. It is also the only tint- * that stays clearly apart from the neutral bubble under every accent — `--ui-accent` is grey- * in the default neutral theme, where a wash of it is the neutral bubble again.- */-const BUBBLE_SURFACE = {- other: "bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200",- own: "bg-brand-50 text-gray-900 dark:bg-brand-950 dark:text-gray-100",-} as const;--/**- * A bubble's corners: 2xl all round, except on the last bubble of a run, where the corner- * nearest the run's tail is squared — bottom-left on somebody else's side of the stream,- * bottom-right on the reader's own. Every corner is named rather than layering a per-corner- * utility over the all-corner one, so the result does not depend on which of the two the- * stylesheet emits last.- */-function bubbleCorners(shape: BubbleShape): string {- if (!shape.last) return "rounded-2xl";- return shape.own- ? "rounded-bl-2xl rounded-br-sm rounded-tl-2xl rounded-tr-2xl"- : "rounded-bl-sm rounded-br-2xl rounded-tl-2xl rounded-tr-2xl";-}-export function ChannelView() {const { projectId, orgId, org } = useOrg();const params = useParams<{ channelId: string }>();@@ -502,11 +470,11 @@ export function ChannelView() {: null;return (<div key={`day-${item.date}`} className={`flex items-center ${ICON_GAP.menu} py-3`}>- <span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" />- <span className="text-[11px] font-medium text-gray-500 dark:text-gray-400">+ <span className="h-px flex-1 bg-divider" />+ <span className="text-xs font-medium text-fg-muted">{dayLabel !== null ? `${dayLabel} · ${item.date}` : item.date}</span>- <span className="h-px flex-1 bg-gray-200 dark:bg-gray-800" />+ <span className="h-px flex-1 bg-divider" /></div>);}@@ -519,7 +487,7 @@ export function ChannelView() {aria-label={S.company.channels.unreadDivider}><span className={`h-px flex-1 ${toneDot.attention}`} />- <span className={`text-[11px] font-medium ${toneInk.attention}`}>+ <span className={`text-xs font-medium ${toneInk.attention}`}>{S.company.channels.unreadDivider}</span><span className={`h-px flex-1 ${toneDot.attention}`} />@@ -560,91 +528,48 @@ export function ChannelView() {}const first = item.messages[0]!;const p = parsePrincipal(item.sender);- const senderLabel = principalLabel(item.sender, names);- const own = isOwnRun(item.sender, me);+ // An employee's tile colour hashes its agent id, so a rename keeps the colour; every other+ // sender is drawn as a person's initial tile.+ const sender: ChannelSender = {+ kind: p.kind === "agent" ? "agent" : "user",+ id: p.kind === "agent" || p.kind === "user" ? p.id : item.sender,+ name: principalLabel(item.sender, names),+ };return (- <div key={first.id} className={`flex items-start ${ICON_GAP.card} py-1.5`}>- {/* One avatar per run, top-aligned so it lands beside the name row: a run is one person- speaking, and an avatar per line turns a burst of three into three arrivals. The- face and the name are one identity and have to be read as one — aligning the avatar- to the run's last bubble instead puts a ten-line message between them. */}- {!own &&- (p.kind === "agent" ? (- <AgentAvatar- id={p.id}- name={senderLabel}- size={RUN_AVATAR_PX}- className="shrink-0 rounded-md"- />- ) : (- <span- aria-hidden- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900"- >- {senderLabel.slice(0, 1).toUpperCase()}+ <ChannelRun+ key={first.id}+ sender={sender}+ own={isOwnRun(item.sender, me)}+ ownLabel={S.company.channels.you}+ meta={+ // The relay chip names what it is and carries the @-chain rule in its tooltip: "hop 3"+ // alone tells a reader nothing about why a message arrived.+ hopChipShown(item.hop) ? (+ <span data-tooltip={S.company.channels.hopInfo} className="text-fg-muted">+ {S.company.channels.hop(item.hop)}</span>- ))}- <div- className={`flex min-w-0 flex-1 flex-col gap-0.5 ${own ? "items-end" : "items-start"}`}- >- {own ? (- // The side and the tint are the whole of "this one is mine" on screen, and neither- // survives a screen reader: it gets the word instead.- <span className="sr-only">{S.company.channels.you}</span>- ) : (- <div- className={`flex max-w-full flex-wrap items-baseline ${ICON_GAP.row} px-1 text-[11px]`}+ ) : undefined+ }+ >+ {item.messages.map((m, i) => {+ const shape = bubbleShape(item, i, me);+ const at = formatDateTime(m.time);+ return (+ <ChannelBubble+ key={m.id}+ id={m.id}+ own={shape.own}+ last={shape.last}+ time={clockTime(m.time)}+ timeTooltip={at}+ timeLabel={S.company.channels.sentAt(at)}+ footer={renderRefs(m)}>- <span className="truncate font-semibold text-gray-700 dark:text-gray-300">- {senderLabel}- </span>- {/* The relay chip names what it is and carries the @-chain rule in its tooltip:- "hop 3" alone tells a reader nothing about why a message arrived. */}- {hopChipShown(item.hop) && (- <span- data-tooltip={S.company.channels.hopInfo}- className="text-gray-500 dark:text-gray-400"- >- {S.company.channels.hop(item.hop)}- </span>- )}- </div>- )}- {item.messages.map((m, i) => {- const shape = bubbleShape(item, i, me);- const at = formatDateTime(m.time);- return (- <div- key={m.id}- id={m.id}- /* A message that names the reader is marked by its mention chip alone: a- tinted bubble reads as a state of the whole message, and in a channel where- most messages name someone it turns the stream into a highlight. */- className={`channel-bubble max-w-[75%] px-3 py-1.5 text-sm leading-relaxed ${bubbleCorners(shape)} ${own ? BUBBLE_SURFACE.own : BUBBLE_SURFACE.other}`}- >- {/* The time is a column of its own at the bubble's end, bottom-aligned: on a- one-line message it lands beside the words, on a longer one it settles- into the bottom-right corner, and it never overlaps the body. */}- <div className={`flex items-end ${ICON_GAP.menu}`}>- <div className="min-w-0 flex-1">- <div className="md-body md-compact">- <ChannelMessageBody text={m.text} />- </div>- {renderRefs(m)}- </div>- <span- data-tooltip={at}- className="shrink-0 text-[11px] tabular-nums text-gray-600 dark:text-gray-400"- >- <span className="sr-only">{S.company.channels.sentAt(at)}</span>- <span aria-hidden>{clockTime(m.time)}</span>- </span>- </div>- </div>- );- })}- </div>- </div>+ <ChannelMessageBody text={m.text} />+ </ChannelBubble>+ );+ })}+ </ChannelRun>);};@@ -705,7 +630,7 @@ export function ChannelView() {</div>) : (messageCount(days) > 0 && (- <p className="py-2 text-center text-[11px] text-gray-400 dark:text-gray-500">+ <p className="py-2 text-center text-xs text-fg-subtle">{S.company.channels.noEarlier}</p>)@@ -798,7 +723,7 @@ function RefChip({type="button"data-tooltip={title}onClick={onClick}- className={`inline-flex items-center ${ICON_GAP.tight} rounded-full border border-gray-200 bg-white px-2 py-0.5 text-[11px] text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}+ className={`inline-flex items-center ${ICON_GAP.tight} rounded-full border border-gray-200 bg-white px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100`}>{icon !== undefined && <GlyphIcon d={icon} size={ICON_SIZE.inlineGlyph} />}{children}diff --git a/packages/web/src/features/company/org-dialogs.tsx b/packages/web/src/features/company/org-dialogs.tsxindex 1e3705f4..9f870e97 100644--- a/packages/web/src/features/company/org-dialogs.tsx+++ b/packages/web/src/features/company/org-dialogs.tsx@@ -62,7 +62,7 @@ import { useAuth } from "../../state/auth";import { useCompany } from "../../state/company";import { projectDisplayName, useProject } from "../../state/project";import { useTheme } from "../../state/theme";-import { ModelSelect, modelLabel } from "../chat/model-select";+import { ModelCatalogSelect, modelLabel } from "../chat/model-select";import { WorkspaceSelect } from "../chat/workspace-select";import { sameModelRef } from "../models/model-grouping";import { ErrorLine, MoneyPerMonthInput, OrgStatusPill } from "./shared";@@ -125,8 +125,8 @@ function useProjectModels(projectId: string, open: boolean) {}/**- * The model field: the App's own model picker (ModelSelect in its form shape — the same- * searchable, grouped, key-configured-first panel the chat composer and the Project's+ * The model field: the App's own model picker (ModelCatalogSelect in its form shape — the same+ * searchable, grouped, key-configured-first dialog the chat composer and the Project's* default-model setting open), with this field's two extra states around it.** Empty is a choice here, not a gap: it means "follow the Project's default", named after@@ -169,7 +169,7 @@ function ModelField({<FieldLabel block={false}>{S.company.modelField}</FieldLabel><InfoPopover label={S.company.modelField}>{S.company.modelInfo}</InfoPopover></span>- <ModelSelect+ <ModelCatalogSelectmodels={list}value={value}{...(models?.defaultModel !== undefined ? { defaultModel: models.defaultModel } : {})}diff --git a/packages/web/src/features/schedules/schedule-form-modal.tsx b/packages/web/src/features/schedules/schedule-form-modal.tsxindex e0d82c9d..63807e13 100644--- a/packages/web/src/features/schedules/schedule-form-modal.tsx+++ b/packages/web/src/features/schedules/schedule-form-modal.tsx@@ -39,7 +39,7 @@ import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useProject } from "../../state/project";-import { ModelSelect } from "../chat/model-select";+import { ModelCatalogSelect } from "../chat/model-select";import { WorkspaceSelect } from "../chat/workspace-select";import { sameModelRef } from "../models/model-grouping";import { itemModelRef } from "./schedule-upsert";@@ -95,7 +95,7 @@ function filterSessions(sessions: SessionInfo[], query: string): SessionInfo[] {/*** Searchable Session picker for the bind-to-Session mode: the shared FormPicker (same- * trigger look as ModelSelect/WorkspaceSelect) whose panel is the shared PickerList (search+ * trigger look as ModelCatalogSelect/WorkspaceSelect) whose panel is the shared PickerList (search* box + keyboard nav). The Agent's full Session list is fetched once when the picker first* opens — un-paged, mirroring how the form one-shots getModels — so search covers every* Session rather than only the sidebar's loaded active page. The stored value is still the@@ -218,7 +218,7 @@ function initialForm(editing: ScheduleItem | null, lockedSessionId: string | undsessionId: editing.sessionId ?? "",workspace: editing.workspace ?? "",// A schedule that follows the Project default stores no model; the default takes its- // place in the picker once the model list arrives (ModelSelect has no null state).+ // place in the picker once the model list arrives (ModelCatalogSelect has no null state).model: itemModelRef(editing),...pinned,};@@ -248,7 +248,7 @@ function ScheduleFormDialog({const [busy, setBusy] = useState(false);// Model dropdown data; a load failure doesn't block the form — falling back to "Project default" is fine.const [models, setModels] = useState<ModelInfo[]>([]);- // The Project default model reference, kept so ModelSelect can mark it and so the form can+ // The Project default model reference, kept so ModelCatalogSelect can mark it and so the form can// treat "the default is selected" as "follow the default" (omit the model from the body).const [defaultModel, setDefaultModel] = useState<ModelRefDto | null>(null);@@ -444,13 +444,13 @@ function ScheduleFormDialog({</div>) : (// New-Session mode: Model and Workspace use the same form-variant pickers as- // the Project default-settings dialog (ModelSelect / WorkspaceSelect), so the+ // the Project default-settings dialog (ModelCatalogSelect / WorkspaceSelect), so the// two surfaces read identically.<><div><FieldLabel>{S.schedule.model}</FieldLabel>{models.length > 0 ? (- <ModelSelect+ <ModelCatalogSelectmodels={models}value={form.model}{...(defaultModel ? { defaultModel } : {})}diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex a516fae3..0772ac08 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -488,16 +488,6 @@(`.code-*`), Shiki's dark palette and the KaTeX fixes live in the shared UI package, beside thecomponents that draw them: packages/ui/src/components/content/prose/prose.css. */-/* ---------- Channel message bubble (features/company/channel-view.tsx) ---------- */--/* A bubble's own surface is the grey the shared Markdown rules give inline code and table- rules, so inside a bubble those marks are printed on their own colour and disappear. One- step deeper puts them back, and reads on both bubble tints in both themes. Fenced blocks- need nothing: `.md-body pre` carries a border and its own lighter/darker fill, and the code- inside it is transparent. The `:not(pre) >` shape is what keeps this off them. */-.channel-bubble :not(pre) > code {- @apply bg-gray-200 dark:bg-gray-700;-}-.channel-bubble :is(th, td) {- @apply border-gray-300 dark:border-gray-700;-}+/* The company channel's bubble (`.channel-bubble`: the deeper inline-code chip and table rules+ inside it) lives in the shared UI package too, beside its component:+ packages/ui/src/components/chat/channel-bubble/channel-bubble.css. */diff --git a/packages/web/test/deslop.test.ts b/packages/web/test/deslop.test.tsindex 114aa8ef..2d0ea0a7 100644--- a/packages/web/test/deslop.test.ts+++ b/packages/web/test/deslop.test.ts@@ -35,13 +35,13 @@ const WEB = SCAN.files.filter((file) => file.root === "web");/*** The homes §3 names, as the web app spells them today. It has no Spinner of its own (the- * package's is the one), the chevron's rotation left with the chevron, and the sheet's and the- * drawer's motion with them (W3).+ * package's is the one), the chevron's rotation left with the chevron, the sheet's and the+ * drawer's motion with them (W3), and the streaming caret's pulse with the reply body (W6).*/const POLICY: DeslopPolicy = {transformMotion: ["dock-launcher.tsx"],entranceMotion: [],- pulseHomes: ["dot.tsx", "streaming-caret.tsx"],+ pulseHomes: ["dot.tsx"],spinnerHomes: [],tokensOnly: false,hexHomes: [],@@ -60,22 +60,9 @@ const ALLOWLIST: DeslopAllowlist = {"components/layout/app-layout.tsx": { 1: [1, "W7"] },"components/layout/sidebar.tsx": { 1: [3, "W7"], 12: [5, "W7"], 13: [2, "W7"], 14: [2, "W7"] },"features/builtin-browser/browser-tab-strip.tsx": { 12: [2, "W10"] },- "features/chat/agent-topology-view.tsx": { 12: [1, "W6"], 13: [3, "W6"] },- "features/chat/chat-input.tsx": { 7: [1, "W6"], 12: [7, "W6"], 13: [5, "W6"] },- "features/chat/chat-page.tsx": { 12: [2, "W6"], 13: [3, "W6"] },- "features/chat/conversation-outline.tsx": { 12: [1, "W6"] },- "features/chat/draft-view.tsx": { 12: [1, "W6"], 13: [1, "W6"] },"features/chat/drop-zone.tsx": { 18: [1, "W7"] },- "features/chat/memory-view.tsx": { 13: [2, "W6"] },- "features/chat/message-item.tsx": { 4: [2, "W6"], 13: [3, "W6"] },"features/chat/model-picker-modal.tsx": { 12: [1, "W10"] },"features/chat/shortcuts-folder.tsx": { 12: [1, "W7"] },- "features/chat/step-banner.tsx": { 13: [1, "W6"], 14: [2, "W6"] },- "features/chat/subagent-chip.tsx": { 13: [1, "W6"] },- "features/chat/subagents-view.tsx": { 13: [2, "W6"], 14: [2, "W6"] },- "features/chat/task-stats-line.tsx": { 13: [1, "W6"] },- "features/chat/tool-call-card.tsx": { 6: [2, "W6"] },- "features/chat/work-group.tsx": { 13: [1, "W6"] },"features/chat/workspace-browser.tsx": {1: [1, "W7"],12: [3, "W7"],@@ -84,9 +71,6 @@ const ALLOWLIST: DeslopAllowlist = {},"features/chat/workspace-finder.tsx": { 12: [6, "W10"] },"features/chat/workspace-tree-view.tsx": { 13: [1, "W7"] },- "features/company/channel-composer.tsx": { 13: [2, "W6"] },- "features/company/channel-header.tsx": { 13: [3, "W6"] },- "features/company/channel-view.tsx": { 12: [1, "W6"], 13: [6, "W6"] },"features/dock/dock-drag.tsx": { 3: [1, "W7"], 12: [1, "W7"] },"features/dock/dock-launcher.tsx": { 13: [1, "W7"], 18: [3, "W7"], 19: [4, "W7"] },"features/dock/dock-panel.tsx": { 1: [2, "W7"], 12: [2, "W7"] },diff --git a/packages/web/test/disclosure-body.test.ts b/packages/web/test/disclosure-body.test.tsindex f512e043..a88c4e62 100644--- a/packages/web/test/disclosure-body.test.ts+++ b/packages/web/test/disclosure-body.test.ts@@ -21,7 +21,10 @@ import { expectEveryRootScanned, expectSingleHome, scanSources, sourceFile } froconst SCAN = scanSources();-const thinking = sourceFile(SCAN, "packages/web/src/features/chat/thinking-block.tsx").text;+const thinking = sourceFile(+ SCAN,+ "packages/ui/src/components/chat/thinking-block/thinking-block.tsx",+).text;const compaction = sourceFile(SCAN, "packages/web/src/features/chat/compaction-banner.tsx").text;/**diff --git a/packages/web/test/icon-registry.test.ts b/packages/web/test/icon-registry.test.tsindex a8315602..d4cefc5b 100644--- a/packages/web/test/icon-registry.test.ts+++ b/packages/web/test/icon-registry.test.ts@@ -28,11 +28,9 @@ const ALLOWLIST: Readonly<Record<string, readonly [number, string]>> = {"components/layout/app-layout.tsx": [3, "W7"],"components/layout/sidebar.tsx": [4, "W7"],"features/chat/attached-files-banner.tsx": [1, "W6"],- "features/chat/chat-input.tsx": [5, "W6"],"features/chat/conversation-outline.tsx": [1, "W6"],"features/chat/goal-use.ts": [1, "W6"],- "features/chat/memory-view.tsx": [4, "W6"],- "features/chat/message-item.tsx": [1, "W6"],+ "features/chat/memory-view.tsx": [3, "W6"],"features/chat/message-stream.tsx": [1, "W6"],"features/chat/subagents-view.tsx": [1, "W6"],"features/chat/task-stats-line.tsx": [1, "W6"],diff --git a/packages/web/test/message-item.test.ts b/packages/web/test/message-item.test.tsnew file mode 100644index 00000000..889e6eaf--- /dev/null+++ b/packages/web/test/message-item.test.ts@@ -0,0 +1,27 @@+/**+ * How the transcript draws a message (src/features/chat/message-item.tsx): through the UI+ * package's reply body and bubbles, with no Markdown, caret or bubble chrome of its own — so a+ * theme's reveal and the package's tests cover what the transcript shows. vitest runs node-only+ * here, so the source is read.+ */+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const item = readFileSync(+ fileURLToPath(new URL("../src/features/chat/message-item.tsx", import.meta.url)),+ "utf8",+);++describe("the transcript's messages (source contract)", () => {+ it("renders every assistant reply through AssistantText", () => {+ expect(item).toContain("<AssistantText text={item.text} streaming={item.streaming}>");+ expect(item).not.toContain("▌");+ expect(item).not.toMatch(/<Md\b/);+ });++ it("draws what the person sent through the package's bubbles", () => {+ expect(item).toContain('<MessageBubble variant="user">{text}</MessageBubble>');+ expect(item).not.toContain("max-w-[88%]");+ });+});diff --git a/packages/web/test/tone.test.ts b/packages/web/test/tone.test.tsindex b3cee1b6..4affc538 100644--- a/packages/web/test/tone.test.ts+++ b/packages/web/test/tone.test.ts@@ -21,18 +21,32 @@ const STATUS_FILES = ["packages/ui/src/components/icons/status-icon/status-icon.tsx","packages/ui/src/components/icons/activity-icon/activity-icon.tsx","packages/ui/src/components/feedback/badge/badge.tsx",- "packages/web/src/features/chat/step-banner.tsx",+ "packages/ui/src/components/chat/step-banner/step-banner.tsx","packages/web/src/features/chat/goal-banner.tsx",+ "packages/ui/src/components/chat/subagent-chip/subagent-chip.tsx","packages/web/src/features/chat/subagent-chip.tsx","packages/web/src/features/builtin-browser/browser-layer.tsx","packages/web/src/features/builtin-browser/browser-tab-strip.tsx","packages/web/src/features/builtin-browser/browser-toolbar.tsx",];+/**+ * Status files that share their name with another root's file by design: a lifted component,+ * drawn by the package and bound to the app by a web container that kept the old path. Each is+ * found by its id instead of by a name no other root holds.+ */+const LIFTED: ReadonlySet<string> = new Set([+ "packages/ui/src/components/chat/subagent-chip/subagent-chip.tsx",+ "packages/web/src/features/chat/subagent-chip.tsx",+]);+describe("tone tokens", () => {it("scans every source root, and finds the tone module and each status file in one place", () => {expectEveryRootScanned(SCAN);- for (const id of ["packages/web/src/lib/tone.ts", ...STATUS_FILES]) expectSingleHome(SCAN, id);+ for (const id of ["packages/web/src/lib/tone.ts", ...STATUS_FILES]) {+ if (LIFTED.has(id)) sourceFile(SCAN, id);+ else expectSingleHome(SCAN, id);+ }});it("covers every tone in every map", () => {diff --git a/scripts/ui-migrate.json b/scripts/ui-migrate.jsonindex 3151659a..3ffe2d7a 100644--- a/scripts/ui-migrate.json+++ b/scripts/ui-migrate.json@@ -737,6 +737,118 @@}]},+ "W6": {+ "packages/web/src/features/chat/work-group": [+ {+ "owner": "W6-A2",+ "target": "packages/web/src/features/chat/work-group",+ "dest": "packages/web/src/features/chat/work-group.tsx",+ "names": ["WorkGroup→SessionWorkGroup"]+ }+ ],+ "packages/web/src/features/chat/thinking-block": [+ {+ "owner": "W6-A2",+ "target": "packages/web/src/features/chat/thinking-block",+ "dest": "packages/web/src/features/chat/thinking-block.tsx",+ "names": ["ThinkingBlock→SessionThinking"]+ }+ ],+ "packages/web/src/features/chat/tool-call-card": [+ {+ "owner": "W6-A2",+ "target": "packages/web/src/features/chat/tool-call-card",+ "dest": "packages/web/src/features/chat/tool-call-card.tsx",+ "names": ["ToolCallCard→SessionToolCall"]+ }+ ],+ "packages/web/src/features/chat/subagent-chip": [+ {+ "owner": "W6-A2",+ "target": "packages/web/src/features/chat/subagent-chip",+ "dest": "packages/web/src/features/chat/subagent-chip.tsx",+ "names": ["SubagentChip→SessionSubagentChip"]+ }+ ],+ "packages/web/src/features/chat/step-banner": [+ {+ "owner": "W6-A2",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/step-banner/step-banner.tsx",+ "names": ["StepBanner"]+ }+ ],+ "packages/web/src/features/chat/approval-buttons": [+ {+ "owner": "W6-A2",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/approval-block/approval-block.tsx",+ "names": ["ApprovalButtons"]+ }+ ],+ "packages/web/src/features/chat/assistant-reply-body": [+ {+ "owner": "W6-A1",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/assistant-text/assistant-text.tsx",+ "names": ["AssistantReplyBody→AssistantText"]+ }+ ],+ "packages/web/src/features/chat/streaming-caret": [+ {+ "owner": "W6-A1",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/assistant-text/streaming-caret.tsx",+ "names": ["StreamingCaret"]+ }+ ],+ "packages/web/src/features/chat/use-stream-reveal": [+ {+ "owner": "W6-A1",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/assistant-text/use-stream-reveal.ts",+ "names": ["useStreamReveal"]+ }+ ],+ "packages/web/src/lib/stream-style": [+ {+ "owner": "W6-A1",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/assistant-text/stream-style.ts",+ "names": [+ "StreamStyle",+ "DEFAULT_STREAM_STYLE",+ "readStreamStyle",+ "effectiveReveal",+ "sameStreamStyle",+ "nextStreamStyle",+ "useStreamStyle"+ ]+ },+ {+ "owner": "W6-A1",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/tokens.ts",+ "names": ["StreamRevealMode→StreamReveal"]+ }+ ],+ "packages/web/src/features/chat/message-files-card": [+ {+ "owner": "W6-A1",+ "target": "@prismshadow/penguin-ui",+ "dest": "packages/ui/src/components/chat/changes-card/changes-card.tsx",+ "names": ["PathLabel"]+ }+ ],+ "packages/web/src/features/chat/model-select": [+ {+ "owner": "W6-B",+ "target": "packages/web/src/features/chat/model-select",+ "dest": "packages/web/src/features/chat/model-select.tsx",+ "names": ["ModelSelect→ModelCatalogSelect"]+ }+ ]+ },"W8": {"packages/web/src/features/palette/command-palette": [{