A local-first multi-agent app development platform, built on PenguinHarness
feat(web): selected conversation text gets a right-click menu — Copy, and Add to conversation (#784)
Yaowei Zheng87b4e23dbf6a
diff --git a/changelog/unreleased/2026-09-17-chat-selection-menu.md b/changelog/unreleased/2026-09-17-chat-selection-menu.mdnew file mode 100644index 00000000..30d6bb99--- /dev/null+++ b/changelog/unreleased/2026-09-17-chat-selection-menu.md@@ -0,0 +1,43 @@+# Selected conversation text gets a right-click menu: Copy, and Add to conversation++- **Date:** 2026-09-17+- **Type:** feature+- **Scope:** `web`+- **PR:** [#784](https://github.com/Prism-Shadow/penguin-harness/pull/784)++[中文版](2026-09-17-chat-selection-menu.zh.md)++Text selected in a conversation's message stream now answers a right-click with the app's own+menu instead of the browser's. The desktop app, where Electron shows no context menu of its own,+gained a way to copy conversation text through it.++## Menu++- The menu opens at the pointer when the selection is not blank and lies wholly inside the message+ stream: user messages, replies and tool output all count. Shift+F10 or the Menu key opens it at+ the end of the selection, and Escape hands focus back to where it was.+- **Copy** writes the selected text to the clipboard and confirms with a "Copied" toast.+- **Add to conversation** stages the selection as a chip above the composer's text box, the same+ way the Files panel stages a quoted range. The chip is labelled with the start of the excerpt+ and its tooltip shows the whole excerpt. Nothing already typed changes and nothing is sent; on+ send, the excerpt goes as a Markdown blockquote ahead of the typed text.+- The text stays selected after either action.+- While the menu is open, the stream stops auto-scrolling to follow new output, so during a live+ reply the menu stays where it opened. Scrolling the stream yourself still closes it. Closing the+ menu resumes following, and a view that was at the bottom catches up to it.+- The browser's own menu stays where the app's does not apply: with nothing selected, when the+ selection runs outside the stream (into the composer, for example), when it is built from+ several ranges (Firefox's Ctrl+drag), and on editable fields. A touch or pen press-and-hold is+ left to the operating system's selection menu.+- In the Agents panel, a child conversation's stream offers the same menu, and Add to conversation+ stages into that child's composer.++## Details++- `ComposerReference` gained an `excerpt` kind with no path. The composer chip moved into its own+ `ReferenceChip` component, which draws the excerpt with the quotation glyph.+- `restoreSelection` moved out of the Files panel into a shared module that both menus use.+- The stream's follow model (`stream-follow.ts`) gained a hold. While held, no streaming update+ snaps the view to the bottom; the user's own scrolling still decides whether the view follows.+- A new dictionary key `common.copy` ("复制" / "Copy") labels the Copy row. The add row reuses+ `files.addToChat`.diff --git a/changelog/unreleased/2026-09-17-chat-selection-menu.zh.md b/changelog/unreleased/2026-09-17-chat-selection-menu.zh.mdnew file mode 100644index 00000000..96219104--- /dev/null+++ b/changelog/unreleased/2026-09-17-chat-selection-menu.zh.md@@ -0,0 +1,35 @@+# 对话文字选中后支持右键菜单:复制、添加到对话++- **Date:** 2026-09-17+- **Type:** feature+- **Scope:** `web`+- **PR:** [#784](https://github.com/Prism-Shadow/penguin-harness/pull/784)++[English](2026-09-17-chat-selection-menu.md)++在会话消息流中选中文字后右键,现在弹出应用自己的菜单,而不是浏览器菜单。桌面端的 Electron 本身不提供右键+菜单,也由此获得了复制对话文字的途径。++## 菜单++- 选区非空且完整落在消息流内时(用户消息、回复正文与工具输出均可),菜单在指针处打开。Shift+F10 或菜单键+ 在选区末尾打开同一菜单,Esc 关闭后焦点回到原处。+- 「复制」把选中文字写入剪贴板,并以「已复制」toast 确认。+- 「添加到对话」把选区作为一枚 chip 暂存在输入框文本区上方,方式与文件面板暂存所选代码段相同。chip 的标签+ 取摘录开头,悬停显示完整摘录。已输入的内容不受影响,也不会发送;发送时摘录以 Markdown 引用块排在所输入的+ 正文之前。+- 两项操作后选区保持高亮。+- 菜单打开期间,消息流暂停自动滚动跟随新输出,因此在回复实时生成时菜单也停在打开处;用户自己滚动消息流仍会+ 关闭菜单。菜单关闭后恢复跟随,原本停在底部的视图随即追到底部。+- 应用菜单不适用的场合保留浏览器菜单:没有选区、选区越出消息流(例如延伸到输入框)、选区由多个区段组成+ (如 Firefox 的 Ctrl+拖拽)、以及在可编辑控件上。触屏与触控笔长按交给操作系统自带的选区菜单。+- 智能体面板中子会话的消息流提供同一菜单,「添加到对话」暂存到该子会话的输入框。++## 细节++- `ComposerReference` 新增不带路径的 `excerpt` 类型。输入框的 chip 拆分为独立的 `ReferenceChip` 组件,摘录+ 使用引号图标。+- `restoreSelection` 从文件面板移入共享模块,两个菜单共用。+- 消息流的跟随模型(`stream-follow.ts`)新增暂停输入:暂停期间任何流式更新都不会把视图滚到底部,是否跟随仍由+ 用户自己的滚动决定。+- 新增词条 `common.copy`(「复制」/ "Copy")作为「复制」一项的文案,「添加到对话」沿用 `files.addToChat`。diff --git a/packages/web/e2e/selection-menu.spec.mjs b/packages/web/e2e/selection-menu.spec.mjsnew file mode 100644index 00000000..2e3a9754--- /dev/null+++ b/packages/web/e2e/selection-menu.spec.mjs@@ -0,0 +1,243 @@+/**+ * The conversation's selection menu: text selected in the message stream answers a secondary+ * click (and Shift+F10) with the app's own menu — 复制 / 添加到对话 — instead of the browser's.+ * - 添加到对话 stages the excerpt as a chip in the composer (its tooltip is the whole excerpt),+ * types nothing into the draft, sends nothing, and leaves the text selected; sending then+ * carries the excerpt as a Markdown blockquote ahead of what was typed.+ * - 复制 writes the selection to the clipboard and confirms with a toast.+ * - With nothing selected, or a selection that runs out of the stream, the app's menu stays shut.+ * The mock's default branch drives it: one tool call, then the reply whose first paragraph is+ * "Command finished; the result looks as expected." (mock-llm.mjs).+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const U = "selectionuser";+const P = "password123";+const SENTENCE = "Command finished; the result looks as expected.";++/** Selects the reply paragraph reading SENTENCE — or, with `runOut`, from it to the end of the page. */+async function selectReply(page, runOut = false) {+ await page.evaluate(+ ({ sentence, runOut }) => {+ const p = [...document.querySelectorAll("p")].find(+ (el) => el.textContent?.trim() === sentence,+ );+ if (!p) throw new Error("reply paragraph not found");+ const range = document.createRange();+ if (runOut) {+ range.setStart(p, 0);+ range.setEnd(document.body, document.body.childNodes.length);+ } else {+ range.selectNodeContents(p);+ }+ const selection = window.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ },+ { sentence: SENTENCE, runOut },+ );+}++const selectedText = (page) => page.evaluate(() => window.getSelection()?.toString() ?? "");++test("selected conversation text offers Copy and Add to conversation", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]+ .projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },+ })+ ).json();++ await page.goto(`${BASE}/chat/${sess.session.sessionId}`);+ const composer = page.getByPlaceholder(/输入消息/);+ await composer.waitFor();+ await composer.fill("check the directory");+ await page.getByRole("button", { name: "发送" }).click();+ const reply = page.getByText(SENTENCE, { exact: true });+ await expect(reply).toBeVisible({ timeout: 30_000 });++ const copyRow = page.getByRole("button", { name: "复制", exact: true });+ const addRow = page.getByRole("button", { name: "添加到对话", exact: true });++ // Nothing selected: the app's menu stays shut and the browser keeps its own.+ await page.evaluate(() => window.getSelection()?.removeAllRanges());+ await reply.click({ button: "right" });+ await expect(addRow).toHaveCount(0);++ // A selection that runs out of the stream: still the browser's menu.+ await selectReply(page, true);+ await reply.click({ button: "right" });+ await expect(addRow).toHaveCount(0);++ // A selection inside the reply: the app's menu, Copy first.+ await selectReply(page);+ await reply.click({ button: "right" });+ await expect(copyRow).toBeVisible();+ await expect(addRow).toBeVisible();+ await addRow.click();++ // Staged as a chip whose tooltip is the whole excerpt. The draft stays empty, nothing was+ // sent, the menu has closed, and the text is still selected.+ const chip = page.locator(`span[title="${SENTENCE}"]`);+ await expect(chip).toBeVisible();+ await expect(composer).toHaveValue("");+ await expect(addRow).toHaveCount(0);+ await expect.poll(() => selectedText(page)).toBe(SENTENCE);++ // Copy: the selection reaches the clipboard, confirmed with a toast.+ await reply.click({ button: "right" });+ await copyRow.click();+ await expect(page.getByText("已复制")).toBeVisible();+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(SENTENCE);+ await expect.poll(() => selectedText(page)).toBe(SENTENCE);++ // The keyboard reaches the same menu from inside the stream, and Escape hands focus back.+ const replyCopy = page.getByRole("button", { name: "复制回复" }).first();+ await replyCopy.focus();+ await selectReply(page);+ await page.keyboard.press("Shift+F10");+ await expect(addRow).toBeVisible();+ await page.keyboard.press("Escape");+ await expect(addRow).toHaveCount(0);+ await expect(replyCopy).toBeFocused();++ // Sending carries the excerpt as a blockquote ahead of what was typed, and the chip goes.+ await composer.fill("Why did it pass?");+ await page.getByRole("button", { name: "发送" }).click();+ await expect(page.getByText(`> ${SENTENCE}`)).toBeVisible();+ await expect(chip).toHaveCount(0);+});++test("an open selection menu holds a live reply's auto-follow, and closing it catches up", async ({+ page,+}) => {+ // A short window, so the conversation overflows it and following actually has to scroll.+ await page.setViewportSize({ width: 1280, height: 640 });+ await provisionAndLogin(page.request, U, P);+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]+ .projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },+ })+ ).json();++ await page.goto(`${BASE}/chat/${sess.session.sessionId}`);+ const composer = page.getByPlaceholder(/输入消息/);+ await composer.waitFor();+ // A first round fills the view: the mock's tool call and its long reply.+ await composer.fill("check the directory");+ await page.getByRole("button", { name: "发送" }).click();+ await expect(page.getByText(SENTENCE, { exact: true })).toBeVisible({ timeout: 30_000 });++ // The live reply: "slow text test" streams chunk-1 … chunk-40, one every 200ms.+ await composer.fill("slow text test");+ await page.getByRole("button", { name: "发送" }).click();+ const liveReply = page.getByText(/chunk-3 /).first();+ await expect(liveReply).toBeVisible({ timeout: 30_000 });++ /** The main stream's scroll position (outline.spec reaches the container the same way). */+ const metrics = () =>+ page.evaluate(() => {+ const c = document.querySelector("[data-outline-anchor]").closest(".overflow-y-auto");+ return {+ top: c.scrollTop,+ height: c.scrollHeight,+ fromBottom: c.scrollHeight - c.scrollTop - c.clientHeight,+ };+ });+ /** How many chunks the live reply shows so far. */+ const chunks = () =>+ page.evaluate(() => {+ const found = document.body.innerText.match(/chunk-(\d+)/g) ?? [];+ return found.length === 0 ? 0 : Math.max(...found.map((c) => Number(c.slice(6))));+ });++ // Following: the view rides the bottom as chunks arrive.+ await expect.poll(async () => (await metrics()).fromBottom).toBeLessThanOrEqual(1);++ // Select the prompt of the live round and right-click it with the mouse alone — a locator+ // click would first scroll the target into view. Retried: a snap's scroll event from just+ // before the click can still land after the menu opened, and a scroll that moves the menu's+ // anchor closes it, which is the behaviour the hold must not take away from the user.+ const addRow = page.getByRole("button", { name: "添加到对话", exact: true });+ await expect(async () => {+ const at = await page.evaluate(() => {+ const stream = document.querySelector("[data-outline-anchor]").closest(".overflow-y-auto");+ const p = [...stream.querySelectorAll("p")].find(+ (el) => el.textContent?.trim() === "slow text test",+ );+ if (!p) throw new Error("prompt bubble not found");+ const range = document.createRange();+ range.selectNodeContents(p);+ const selection = window.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ const r = p.getBoundingClientRect();+ return { x: r.left + r.width / 2, y: r.top + r.height / 2 };+ });+ await page.mouse.click(at.x, at.y, { button: "right" });+ await expect(addRow).toBeVisible({ timeout: 1_000 });+ }).toPass({ timeout: 10_000 });+ /** Where the menu panel is pinned (its fixed viewport coordinates). */+ const pinnedAt = () =>+ addRow.evaluate((row) => {+ const panel = row.parentElement;+ return { left: panel.style.left, top: panel.style.top, bottom: panel.style.bottom };+ });+ const menuAt = await pinnedAt();+ const held = await metrics();+ const chunksAtOpen = await chunks();++ // Chunks keep arriving under the open menu until the content has grown: the view stays+ // where it was — no longer at the bottom — and the menu stays open where it opened.+ await expect+ .poll(async () => (await metrics()).height, { timeout: 7_000 })+ .toBeGreaterThan(held.height);+ expect(await chunks()).toBeGreaterThan(chunksAtOpen);+ await expect(addRow).toBeVisible();+ expect(await pinnedAt()).toEqual(menuAt);+ const during = await metrics();+ expect(during.top).toBe(held.top);+ expect(during.fromBottom).toBeGreaterThan(1);++ // Closing the menu resumes following: the view catches up to the bottom.+ await page.keyboard.press("Escape");+ await expect(addRow).toHaveCount(0);+ await expect.poll(async () => (await metrics()).fromBottom).toBeLessThanOrEqual(1);+});diff --git a/packages/web/src/components/ui/text-selection.ts b/packages/web/src/components/ui/text-selection.tsnew file mode 100644index 00000000..f9c86a23--- /dev/null+++ b/packages/web/src/components/ui/text-selection.ts@@ -0,0 +1,28 @@+/**+ * Putting a text selection back after a menu acted on it — shared by the two menus that act on+ * selected text: the Files panel preview's and the conversation's.+ *+ * Both menus hand the selection to the composer, and the composer focuses its textarea to take+ * it; focusing a text field drops whatever the document had selected. Contributing a quote to+ * the conversation is not an edit to what was quoted, and losing the highlight would cost the+ * reader their place, so the highlight is restored by hand afterwards.+ */++/**+ * Puts `range` back as the document's one selection, a frame after the caller hands text to+ * the composer: the composer focuses its textarea inside a requestAnimationFrame of its own,+ * scheduled first, and that focus is what clears the selection this restores.+ *+ * A range whose ends have since left the document is dropped rather than re-applied — the+ * content it was read from is no longer on screen, and re-selecting detached nodes would+ * either throw or select nothing.+ */+export function restoreSelection(range: Range): void {+ requestAnimationFrame(() => {+ if (!range.startContainer.isConnected || !range.endContainer.isConnected) return;+ const selection = window.getSelection();+ if (selection === null) return;+ selection.removeAllRanges();+ selection.addRange(range);+ });+}diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex ac1b1741..6f6acd3f 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -96,8 +96,7 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";import { Button } from "../../components/ui/button";import { Dropdown } from "../../components/ui/dropdown";import { GlyphIcon } from "../../components/ui/glyph-icon";-import { CheckIcon, ChevronDown, FILE_ICON, QUOTE_ICON } from "../../components/ui/icons";-import { FOLDER_ICON } from "../../components/ui/group-list";+import { CheckIcon, ChevronDown } from "../../components/ui/icons";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { noAutofill } from "../../components/ui/input";import { toastError, toastInfo } from "../../components/ui/toast";@@ -130,8 +129,8 @@ import { modelWindowBelowCompactionLimit } from "../../lib/context";import { toneStrip } from "../../lib/tone";import { splitDroppedFiles } from "../../lib/file-drop";import { splitBySize } from "../../lib/upload-limits";-import { lineSuffix } from "../../lib/workspace-tree";import type { ComposerReference } from "../../lib/workspace-tree";+import { ReferenceChip } from "./reference-chip";const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];@@ -763,40 +762,10 @@ function withReferences(references: readonly ComposerReference[], typed: string)return [...references.map((r) => r.text), typed].filter((part) => part !== "").join("\n\n");}-/**- * A staged reference, split for display: the entry's own name, and the quoted lines as a- * `:from-to` suffix. The `file:line` form rather than a worded one — it is the shape every editor- * and stack trace already uses, it needs no translating, and a chip has no room for a sentence.- *- * Returned in two pieces because the chip draws them differently: a long name ellipsizes, and the- * line numbers must not go with it. They are the smaller half and the half the name does not- * already say.- */-function referenceParts(reference: ComposerReference): { name: string; lines: string } {- const name = reference.path.split("/").pop() ?? reference.path;- const lines =- reference.fromLine === undefined || reference.toLine === undefined- ? ""- : lineSuffix(reference.fromLine, reference.toLine);- return { name, lines };-}--/** The whole of what a chip stands for, for its tooltip and its accessible name: path and lines. */-function referenceTitle(reference: ComposerReference): string {- return `${reference.path}${referenceParts(reference).lines}`;-}--/** A directory, a file, or a passage carried in from one — each says what the chip stands for. */-const REFERENCE_ICON: Record<ComposerReference["kind"], string> = {- dir: FOLDER_ICON,- file: FILE_ICON,- quote: QUOTE_ICON,-};-/*** What a parent can ask of a mounted composer, handed over through ChatInput's `controlRef`.* Two entries: a surface that composes a whole prompt puts it in this composer instead of- * submitting it on its own, and a surface that contributes one reference splices it into+ * submitting it on its own, and a surface that contributes one reference stages it beside* whatever is already being typed.*/export interface ComposerControl {@@ -808,9 +777,9 @@ export interface ComposerControl {*/fillPrompt: (prompt: string, pinnedSkills: readonly string[]) => void;/**- * Stage what the Files panel contributes as a chip rather than typing it into the draft — a- * file, a directory, or a quoted range. The text rides the message when it is sent; what the- * composer shows is the thing it points at.+ * Stage a contribution as a chip rather than typing it into the draft — a file, a directory+ * or a quoted range from the Files panel, or an excerpt selected in the conversation. The+ * text rides the message when it is sent; what the composer shows is the thing it points at.*/addReference: (reference: ComposerReference) => void;}@@ -2604,42 +2573,19 @@ export function ChatInput({</span>);})}- {/* Staged from the Files panel: a file, a directory, or a quoted range. 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) => {- const { name, lines } = referenceParts(reference);- const title = referenceTitle(reference);- return (- <span- key={i}- title={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"- aria-label={`${S.files.removeReference} ${title}`}- onClick={() => {- setReferences((prev) => prev.filter((_, j) => j !== i));- 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 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>)}diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex e401360d..fe1f89f6 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -1308,10 +1308,10 @@ export function ChatPage() {composerRef.current?.fillPrompt(text, []);}, []);/**- * The Files panel's exit into the conversation: a `@path` reference, or a fenced block- * around what was selected in a preview, spliced into the draft at the caret. Nothing is- * sent and nothing already typed is disturbed — the panel contributes a line to a message- * the user is writing.+ * The Files panel's exit into the conversation — a `@path` reference, or a fenced block+ * around what was selected in a preview — and the message stream's, an excerpt of the+ * conversation selected in it. Nothing is sent and nothing already typed is disturbed: the+ * surface contributes a part of a message the user is writing.*//** Staged as a chip, so the draft keeps whatever the user was in the middle of writing. */const addComposerReference = useCallback((reference: ComposerReference) => {@@ -2232,6 +2232,10 @@ export function ChatPage() {version={stream.version}ctx={ctx}scrollElRef={streamScrollRef}+ // The selection menu's "Add to conversation": the excerpt is staged+ // in this composer as a chip, the same way the Files panel stages a+ // quoted range.+ onAddExcerpt={addComposerReference}// Scroll-up backfill of older history windows (tail-first// loading): near-top scrolling prepends the previous window,// scroll position anchored (see MessageStream).diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex 470b05ea..fa449843 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -3,7 +3,8 @@* bottom while streaming — an upward swipe immediately pauses follow, and scrolling back near* the bottom resumes it (see stream-follow.ts for the exact rule).* StreamRenderContext threads the pending-approval map and approval callback down to tool- * cards at any nesting depth.+ * cards at any nesting depth. Text selected in the stream gets the app's own context menu+ * (Copy / Add to conversation — see stream-selection-menu.tsx).*/import { useEffect, useLayoutEffect, useRef, useState } from "react";import type { ReactNode, RefObject } from "react";@@ -19,6 +20,8 @@ import { WorkGroup, isWorkItem } from "./work-group";import { createStreamFollow, stickToBottom } from "./stream-follow";import type { StreamFollow } from "./stream-follow";import type { ForkTarget } from "./task-stats-line";+import { useStreamSelectionMenu } from "./stream-selection-menu";+import type { ComposerReference } from "../../lib/workspace-tree";/** Context passed down to nested rendering (pending approvals + approval submit callback + current origin chain). */export interface StreamRenderContext {@@ -201,6 +204,7 @@ export function MessageStream({scrollElRef,outline,older,+ onAddExcerpt,}: {items: ChatItem[];/** View-model version number (a repaint signal for in-place updates that also drives auto-scroll). */@@ -216,8 +220,15 @@ export function MessageStream({outline?: ReactNode;/** Scroll-up backfill of older history windows; omitted = the whole transcript is loaded (no top affordance). */older?: OlderHistoryControls;+ /**+ * Stages text selected in the stream in this conversation's composer, as a chip (the+ * selection menu's "Add to conversation"). Required: every stream this app renders belongs+ * to a conversation with a composer.+ */+ onAddExcerpt: (reference: ComposerReference) => void;}) {const scrollRef = useRef<HTMLDivElement>(null);+ const selectionMenu = useStreamSelectionMenu(onAddExcerpt);// An upward-swipe intent immediately exits auto-follow; scrolling back near the bottom resumes it — see stream-follow.ts (#75) for the exact rule.const followRef = useRef<StreamFollow | null>(null);const follow = (followRef.current ??= createStreamFollow());@@ -293,9 +304,27 @@ export function MessageStream({syncJump();};+ // The selection menu holds the view while it is open: it hangs off a point in the content, and+ // a snap during a live reply would scroll that point out from under it (the menu then closes,+ // as it does for any scroll that moves its anchor). Declared before the commit snap below so a+ // commit that opens the menu applies the hold first. Releasing it catches a view that was+ // following up with whatever arrived meanwhile; the user's own scrolling during the hold still+ // decides whether it was following (see stream-follow.ts).+ const menuOpen = selectionMenu.open;+ useLayoutEffect(() => {+ follow.hold(menuOpen);+ if (menuOpen) return;+ const el = scrollRef.current;+ if (el && follow.snaps && !returningRef.current) stickToBottom(el, follow);+ syncJump();+ // syncJump is recreated per render; the effect keys on the menu's open state only.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [menuOpen, follow]);+// Layout effect (not useEffect): the stick-to-bottom snap must land before paint, otherwise// fast streams show the bottom edge "catching up" by the growth of each commit. Suppressed- // during the animated return — the glide owns the scroll position until it arrives.+ // during the animated return — the glide owns the scroll position until it arrives — and+ // while the selection menu holds the view (follow.snaps).// Every snap goes through stickToBottom, which reports the landed position to the follow// model synchronously — the snap's async scroll event otherwise races late content growth// and could misinitialize follow as "parked above the bottom" right after entering a@@ -307,15 +336,16 @@ export function MessageStream({// content growth (same pre-paint timing as the stick snap, so nothing flashes).// Keyed on the prepend count — ordinary streaming growth at the bottom must not// shift the view. lastHeightRef is refreshed every commit, so at the prepend commit- // it still holds the pre-prepend height. Skipped while sticking (the snap below- // owns the position; a prepend while stuck at the bottom cannot move the tail).+ // it still holds the pre-prepend height. Skipped while the snap below owns the+ // position (a prepend while stuck at the bottom cannot move the tail); a held view is+ // anchored like any other, since nothing snaps it.const prepended = older?.prependedCount ?? 0;- if (el && prepended > lastPrependedRef.current && !follow.stick && !returningRef.current) {+ if (el && prepended > lastPrependedRef.current && !follow.snaps && !returningRef.current) {el.scrollTop += el.scrollHeight - lastHeightRef.current;}lastPrependedRef.current = prepended;if (el) lastHeightRef.current = el.scrollHeight;- if (el && follow.stick && !returningRef.current) stickToBottom(el, follow);+ if (el && follow.snaps && !returningRef.current) stickToBottom(el, follow);syncJump();// syncJump is recreated per render; the effect intentionally keys on stream growth only.// eslint-disable-next-line react-hooks/exhaustive-deps@@ -333,7 +363,7 @@ export function MessageStream({if (!el || typeof ResizeObserver === "undefined") return;const ro = new ResizeObserver(() => {lastHeightRef.current = el.scrollHeight;- if (follow.stick && !returningRef.current) stickToBottom(el, follow);+ if (follow.snaps && !returningRef.current) stickToBottom(el, follow);syncJump();});ro.observe(el);@@ -392,7 +422,13 @@ export function MessageStream({ref={(el) => {scrollRef.current = el;if (scrollElRef) scrollElRef.current = el;+ selectionMenu.hostRef(el);}}+ // A selection inside the stream answers a secondary click with the app's own menu;+ // everything else keeps the browser's (see stream-selection-menu.tsx).+ onPointerDown={selectionMenu.hostProps.onPointerDown}+ onContextMenu={selectionMenu.hostProps.onContextMenu}+ onKeyDown={selectionMenu.hostProps.onKeyDown}onScroll={onScroll}onWheel={(e) => {follow.wheel(e.deltaY);@@ -451,6 +487,7 @@ export function MessageStream({</div></div>{outline}+ {selectionMenu.panel}{/* Back-to-bottom (shows once the user scrolls away from content below the fold): floatsjust above the composer; clicking returns to the bottom and re-enters follow, so theview keeps tracking the live stream. */}diff --git a/packages/web/src/features/chat/reference-chip.tsx b/packages/web/src/features/chat/reference-chip.tsxnew file mode 100644index 00000000..624751a3--- /dev/null+++ b/packages/web/src/features/chat/reference-chip.tsx@@ -0,0 +1,88 @@+/**+ * 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.+ */+import { S } from "../../lib/strings";+import { excerptLabel } from "../../lib/selection-menu";+import { lineSuffix } from "../../lib/workspace-tree";+import type { ComposerReference } from "../../lib/workspace-tree";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { FOLDER_ICON } from "../../components/ui/group-list";+import { FILE_ICON, QUOTE_ICON } from "../../components/ui/icons";++/**+ * A staged reference, split for display: its name, and the quoted lines as a `:from-to` suffix.+ * The `file:line` form rather than a worded one — it is the shape every editor and stack trace+ * already uses, it needs no translating, and a chip has no room for a sentence.+ *+ * Returned in two pieces because the chip draws them differently: a long name ellipsizes, and the+ * line numbers must not go with it. They are the smaller half and the half the name does not+ * already say. An excerpt has no path and no lines, so its name is the excerpt's own start.+ */+function referenceParts(reference: ComposerReference): { name: string; lines: string } {+ if (reference.kind === "excerpt") return { name: excerptLabel(reference.excerpt), lines: "" };+ const name = reference.path.split("/").pop() ?? reference.path;+ const lines =+ reference.fromLine === undefined || reference.toLine === undefined+ ? ""+ : lineSuffix(reference.fromLine, reference.toLine);+ return { name, lines };+}++/** The whole of what a chip stands for, for its tooltip: path and lines, or the whole excerpt. */+function referenceTitle(reference: ComposerReference): string {+ if (reference.kind === "excerpt") return reference.excerpt;+ return `${reference.path}${referenceParts(reference).lines}`;+}++/**+ * A directory, a file, or a passage carried in — each says what the chip stands for. An excerpt+ * of the conversation is a quotation too, only carried in from the conversation above rather+ * than from a file.+ */+const REFERENCE_ICON: Record<ComposerReference["kind"], string> = {+ dir: FOLDER_ICON,+ file: FILE_ICON,+ quote: QUOTE_ICON,+ excerpt: QUOTE_ICON,+};++export function ReferenceChip({+ reference,+ onRemove,+}: {+ reference: ComposerReference;+ /** The chip's ×: unstages the reference. */+ onRemove: () => void;+}) {+ const { name, lines } = referenceParts(reference);+ const title = referenceTitle(reference);+ return (+ <span+ title={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-0.5 text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:hover:text-gray-200"+ >+ ×+ </button>+ </span>+ );+}diff --git a/packages/web/src/features/chat/stream-follow.ts b/packages/web/src/features/chat/stream-follow.tsindex cc824407..4f596fca 100644--- a/packages/web/src/features/chat/stream-follow.ts+++ b/packages/web/src/features/chat/stream-follow.ts@@ -20,6 +20,11 @@* landed position synchronously: the snap's own scroll event only arrives at the next* rendering update, and content growing in between (an image decoding, a font swap) would* otherwise make that first event look like a historical position and wrongly exit follow.+ * - Hold: something anchored to the content can hold the view still — the selection menu hangs+ * off a point in the stream, and a snap would move that point out from under it. A hold only+ * defers acting on the intent (`snaps`); it never changes the intent (`stick`), so the user's+ * own scrolling still exits or resumes follow during a hold, and releasing it lets a view that+ * was following catch up with whatever arrived meanwhile.*/export interface ScrollMetrics {scrollTop: number;@@ -28,8 +33,12 @@ export interface ScrollMetrics {}export interface StreamFollow {- /** Whether it should currently auto-stick to bottom on streaming updates. */+ /** Whether the user's intent is to follow: auto-stick to bottom on streaming updates. */readonly stick: boolean;+ /** Whether a streaming update may snap the view to the bottom right now: following, and not held. */+ readonly snaps: boolean;+ /** Hold the view where it is (true) or release it (false); see the header for what a hold leaves alone. */+ hold(held: boolean): void;/** wheel: deltaY < 0 is scroll-up intent, exits follow immediately. */wheel(deltaY: number): void;touchStart(clientY: number): void;@@ -44,12 +53,19 @@ export interface StreamFollow {export function createStreamFollow(): StreamFollow {let stick = true;+ let held = false;let lastTop: number | null = null;let touchY: number | null = null;return {get stick() {return stick;},+ get snaps() {+ return stick && !held;+ },+ hold(next) {+ held = next;+ },wheel(deltaY) {if (deltaY < 0) stick = false;},diff --git a/packages/web/src/features/chat/stream-selection-menu.tsx b/packages/web/src/features/chat/stream-selection-menu.tsxnew file mode 100644index 00000000..9f3a2e96--- /dev/null+++ b/packages/web/src/features/chat/stream-selection-menu.tsx@@ -0,0 +1,245 @@+/**+ * The conversation's own menu for selected text: a secondary click — or Shift+F10, or the+ * keyboard's Menu key — on a selection inside the message stream offers Copy and Add to+ * conversation. The rules (which gestures it takes, which rows it shows, where a keyboard-opened+ * menu hangs, what an excerpt becomes) are pure and live in lib/selection-menu.ts; this half+ * reads the DOM and runs the rows.+ *+ * It is the Files panel preview's selection menu applied to the conversation, and it borrows+ * that menu's parts instead of copying them: `useRowContextMenu` for the anchored open state+ * and its dismissal, the `Dropdown` in `anchorRect` mode for the panel, the overflow-menu row+ * styling, and `restoreSelection` for the highlight. It is also what gives the desktop app a+ * copy menu for conversation text, since Electron raises no context menu of its own.+ *+ * Whatever the rules decline is left to the browser untouched: `preventDefault` runs only once+ * the rules have taken the gesture, inside the stream's own handler, so a right-click with no+ * selection, on a field, or on a selection that runs out of the stream still gets the native+ * menu. A touch or pen press-and-hold is declined outright — the OS selection menu owns that+ * gesture — which is why none of the hook's press-and-hold handlers are spread here.+ */+import { useRef, useState } from "react";+import type {+ KeyboardEvent as ReactKeyboardEvent,+ MouseEvent as ReactMouseEvent,+ PointerEvent as ReactPointerEvent,+ ReactNode,+} from "react";+import { S } from "../../lib/strings";+import { STAT_ICONS } from "../../lib/stat-icons";+import { contextMenuAnchor, isContextMenuKey } from "../../lib/context-menu";+import type { AnchorRect, ContextMenuEventLike } from "../../lib/context-menu";+import {+ SELECTION_MENU_ITEMS,+ excerptReference,+ opensSelectionMenu,+ selectionEndAnchor,+} from "../../lib/selection-menu";+import type { ComposerReference } from "../../lib/workspace-tree";+import { useRowContextMenu } from "../../components/ui/context-menu";+import { writeClipboard } from "../../components/ui/copy-button";+import { Dropdown } from "../../components/ui/dropdown";+import { ADD_TO_CHAT_ICON } from "../../components/ui/icons";+import { overflowMenuGlyph, overflowMenuRowClass } from "../../components/ui/session-row-menu";+import { restoreSelection } from "../../components/ui/text-selection";+import { toastSuccess } from "../../components/ui/toast";++/** The selection a gesture opened the menu on, captured before anything could collapse it. */+export interface CapturedSelection {+ /** What was selected, as the selection itself reads it. */+ text: string;+ /**+ * The range, cloned at the gesture: the live one follows the document's selection, which the+ * composer clears the moment it takes focus to receive the excerpt.+ */+ range: Range;+}++/**+ * The menu's rows, in SELECTION_MENU_ITEMS order. Copy writes the selection to the clipboard+ * and confirms with a toast: a row closes under the pointer, so it cannot carry the copy+ * button's at-the-control feedback (the Files panel's copy-path row confirms the same way).+ * Add to conversation hands the excerpt to the composer as a chip; nothing already typed is+ * touched and nothing is sent.+ */+export function SelectionMenuRows({+ selection,+ onAddExcerpt,+ onDone,+}: {+ selection: CapturedSelection;+ /** Stages the excerpt in this conversation's composer. */+ onAddExcerpt: (reference: ComposerReference) => void;+ /** Runs after either row has acted: closes the panel and puts the highlight back. */+ onDone: (selection: CapturedSelection) => void;+}) {+ return (+ <>+ {SELECTION_MENU_ITEMS.map((item) =>+ item === "copy" ? (+ <button+ key={item}+ type="button"+ className={overflowMenuRowClass}+ onClick={() => {+ writeClipboard(selection.text);+ toastSuccess(S.common.copied);+ onDone(selection);+ }}+ >+ {overflowMenuGlyph(STAT_ICONS.copy)}+ {S.common.copy}+ </button>+ ) : (+ <button+ key={item}+ type="button"+ className={overflowMenuRowClass}+ onClick={() => {+ onAddExcerpt(excerptReference(selection.text));+ onDone(selection);+ }}+ >+ {overflowMenuGlyph(ADD_TO_CHAT_ICON)}+ {S.files.addToChat}+ </button>+ ),+ )}+ </>+ );+}++/** A viewport box as the anchoring rules take it. */+const toAnchor = (r: DOMRect): AnchorRect => ({+ top: r.top,+ bottom: r.bottom,+ left: r.left,+ right: r.right,+});++/** Fields whose own context menu (paste, spelling) is the one that belongs to them. */+const EDITABLE_SELECTOR =+ "input, textarea, select, [contenteditable]:not([contenteditable='false'])";++/** Is the node inside such a field? */+function inEditable(node: Node): boolean {+ const element = node instanceof Element ? node : node.parentElement;+ return element !== null && element.closest(EDITABLE_SELECTOR) !== null;+}++export interface StreamSelectionMenu {+ /** Whether the menu is open: the stream holds its auto-follow while it is (see stream-follow.ts). */+ open: boolean;+ /** Attach to the stream's scroll container: the element a selection has to lie inside. */+ hostRef: (el: HTMLElement | null) => void;+ /** Spread onto the same element. */+ hostProps: {+ onPointerDown: (e: ReactPointerEvent) => void;+ onContextMenu: (e: ReactMouseEvent) => void;+ onKeyDown: (e: ReactKeyboardEvent) => void;+ };+ /** The portaled panel: render it anywhere in the stream's own tree. */+ panel: ReactNode;+}++export function useStreamSelectionMenu(+ onAddExcerpt: (reference: ComposerReference) => void,+): StreamSelectionMenu {+ // The row hook's anchor state and dismissal, with the stream as its "row": its owner is what a+ // scroll must move for the panel to close, and that is the stream's own scroll.+ const menu = useRowContextMenu();+ const [captured, setCaptured] = useState<CapturedSelection | null>(null);+ /**+ * The pointer that last pressed inside the stream. A `contextmenu` event is a PointerEvent in+ * current Chromium, which names its pointer itself; elsewhere it is a plain MouseEvent, and+ * the press that preceded it is the only witness to whether a finger raised it.+ */+ const lastPointer = useRef("");+ /** Where Escape hands focus back: the element inside the stream that held it when the menu opened, if any. */+ const focusBefore = useRef<HTMLElement | null>(null);++ /** Opens the menu on the document's selection if the rules take this gesture; returns whether it did. */+ const openOnSelection = (+ target: EventTarget | null,+ gesture: ContextMenuEventLike,+ pointerType: string,+ ): boolean => {+ const host = menu.anchorOwner();+ // Events raised in the portaled panel reach this handler through React's tree; only a+ // gesture that really happened inside the stream counts.+ if (host === null || !(target instanceof Node) || !host.contains(target)) return false;+ const selection = window.getSelection();+ const range =+ selection !== null && selection.rangeCount > 0 && !selection.isCollapsed+ ? selection.getRangeAt(0)+ : null;+ // The text is the whole selection's, so the rules take its range count too: a selection+ // of several ranges reads text this one range cannot vouch for (see opensSelectionMenu).+ const selectedText = range !== null && selection !== null ? selection.toString() : "";+ const opens = opensSelectionMenu({+ selectedText,+ rangeCount: selection?.rangeCount ?? 0,+ firstRangeInStream: range !== null && host.contains(range.commonAncestorContainer),+ pointerType,+ onEditable: inEditable(target),+ });+ if (!opens || range === null) return false;+ const next: CapturedSelection = { text: selectedText, range: range.cloneRange() };+ setCaptured(next);+ const active = document.activeElement;+ focusBefore.current = active instanceof HTMLElement && host.contains(active) ? active : null;+ // Put back at once, as the Files preview does: the press that asked for the menu, and the+ // panel taking focus, can each collapse the highlight the menu is about to act on.+ restoreSelection(next.range);+ const lineBoxes = Array.from(range.getClientRects(), toAnchor);+ menu.openAt(+ contextMenuAnchor(+ gesture,+ selectionEndAnchor(lineBoxes, toAnchor(range.getBoundingClientRect())),+ ),+ );+ return true;+ };++ const hostProps: StreamSelectionMenu["hostProps"] = {+ onPointerDown: (e) => {+ lastPointer.current = e.pointerType;+ },+ onContextMenu: (e) => {+ const named = (e.nativeEvent as MouseEvent & { pointerType?: unknown }).pointerType;+ const pointerType = typeof named === "string" && named !== "" ? named : lastPointer.current;+ if (openOnSelection(e.target, e, pointerType)) e.preventDefault();+ },+ onKeyDown: (e) => {+ if (!isContextMenuKey(e)) return;+ // No pointer: the anchoring rule reads (0, 0) with no button as the keyboard asking.+ if (openOnSelection(e.target, { button: 0, clientX: 0, clientY: 0 }, "")) e.preventDefault();+ },+ };++ const done = (selection: CapturedSelection) => {+ menu.close();+ // Scheduled after the composer's own focus frame (addReference schedules that one first),+ // so the highlight comes back after the focus that cleared it.+ restoreSelection(selection.range);+ };++ const panel = (+ <Dropdown+ open={menu.open && captured !== null}+ setOpen={menu.setOpen}+ portal={{ direction: "down", align: "left" }}+ anchorRect={menu.anchor}+ anchorOwner={menu.anchorOwner}+ returnFocus={() => focusBefore.current}+ className="contents"+ menuClass="w-max min-w-36 max-w-[calc(100vw-2rem)]"+ button={null}+ >+ {captured !== null && (+ <SelectionMenuRows selection={captured} onAddExcerpt={onAddExcerpt} onDone={done} />+ )}+ </Dropdown>+ );++ return { open: menu.open && captured !== null, hostRef: menu.rowRef, hostProps, panel };+}diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsxindex e2b08e85..5e475d22 100644--- a/packages/web/src/features/chat/subagents-view.tsx+++ b/packages/web/src/features/chat/subagents-view.tsx@@ -20,7 +20,8 @@* conversation visible (found by walking the origin chain); the graph simply has no* highlighted node.*/-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type { RefObject } from "react";import { useNavigate } from "react-router";import type {ApprovalMode,@@ -38,6 +39,7 @@ import { apiErrorText } from "../../lib/api-error";import { S } from "../../lib/strings";import type { NestedSessionMeta, StreamModel } from "../../lib/omni/stream-model";import { ChatInput } from "./chat-input";+import type { ComposerControl } from "./chat-input";import { AgentAvatar } from "../../components/ui/agent-avatar";import { EmptyState } from "../../components/ui/empty-state";import { GlyphIcon } from "../../components/ui/glyph-icon";@@ -57,6 +59,7 @@ import type { TopologyNode } from "./agent-topology";import { AgentTopologyView } from "./agent-topology-view";import { MessageStream } from "./message-stream";import type { StreamRenderContext } from "./message-stream";+import type { ComposerReference } from "../../lib/workspace-tree";interface Selection {sessionId: string;@@ -104,6 +107,12 @@ export function SubagentsView({const { sessions } = useSessions();const navigate = useNavigate();const [selected, setSelected] = useState<Selection | null>(null);+ // The selected child's composer, for the stream above it: "Add to conversation" in the+ // child's selection menu stages the excerpt there, in the conversation it was selected in.+ const childComposerRef = useRef<ComposerControl | null>(null);+ const addChildExcerpt = useCallback((reference: ComposerReference) => {+ childComposerRef.current?.addReference(reference);+ }, []);// A chip click focuses that child (fresh-object identity: re-clicking the same chip re-fires).useEffect(() => {@@ -271,12 +280,14 @@ export function SubagentsView({items={activeModel.items}version={version}ctx={childCtx}+ onAddExcerpt={addChildExcerpt}/>)}</div>{/* Keyed by child too: switching nodes must not carry a half-typed message over. */}<SubagentComposerkey={`composer-${active.sessionId}`}+ controlRef={childComposerRef}sessionId={session.sessionId}childSessionId={active.sessionId}running={activeRunning}@@ -318,6 +329,7 @@ function countDeliveredInputs(model: StreamModel): number {* only the child's current run. All of it lands on the same core channel input_subagent uses.*/function SubagentComposer({+ controlRef,sessionId,childSessionId,running,@@ -330,6 +342,8 @@ function SubagentComposer({modeSaving,fallbackThinkingLevel,}: {+ /** Handed to the ChatInput: the child stream's selection menu stages excerpts through it. */+ controlRef: RefObject<ComposerControl | null>;sessionId: string;childSessionId: string;running: boolean;@@ -395,6 +409,7 @@ function SubagentComposer({<div className="shrink-0 border-t border-gray-100 px-2 pb-2 pt-2 dark:border-gray-800/60"><ChatInputvariant="subagent"+ controlRef={controlRef}status={running ? "running" : "idle"}onSend={async (input: TaskInputPart[]) => {const text = inputdiff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex e7da8975..8def7d1f 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -124,6 +124,7 @@ import {import { Input, noAutofill, panelSearchClass } from "../../components/ui/input";import { ZoomableImage } from "../../components/ui/image-zoom";import { SkeletonList } from "../../components/ui/skeleton";+import { restoreSelection } from "../../components/ui/text-selection";import { Tooltip } from "../../components/ui/tooltip";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { ICON_SIZE } from "../../lib/icon-scale";@@ -356,25 +357,6 @@ interface PreviewSelection {range: Range;}-/**- * Puts `range` back as the document's one selection, a frame after the caller hands text to- * the composer: the composer focuses its textarea inside a requestAnimationFrame of its own,- * scheduled first, and that focus is what clears the selection this restores.- *- * A range whose ends have since left the document is dropped rather than re-applied — the- * preview it was read from is no longer on screen, and re-selecting detached nodes would- * either throw or select nothing.- */-function restoreSelection(range: Range): void {- requestAnimationFrame(() => {- if (!range.startContainer.isConnected || !range.endContainer.isConnected) return;- const selection = window.getSelection();- if (selection === null) return;- selection.removeAllRanges();- selection.addRange(range);- });-}-/*** The text selected inside `host`, or null when there is none, when it lies elsewhere on the* page, or when it is only whitespace. `lines` are the rendered source lines to measure thediff --git a/packages/web/src/lib/selection-menu.ts b/packages/web/src/lib/selection-menu.tsnew file mode 100644index 00000000..548d7c52--- /dev/null+++ b/packages/web/src/lib/selection-menu.ts@@ -0,0 +1,108 @@+/**+ * Pure rules of the conversation's selection menu (features/chat/stream-selection-menu.tsx):+ * when a secondary click in the message stream opens the app's own menu instead of the+ * browser's, which rows that menu offers, where it hangs when the keyboard asked for it, and+ * what an excerpt becomes once it is added to the conversation. Kept free of the DOM so they+ * can be tested in this package's node-only vitest environment.+ */+import { isLongPressPointer } from "./context-menu";+import type { AnchorRect } from "./context-menu";+import type { ExcerptReference } from "./workspace-tree";++/** What the rules need to know about a gesture and the selection it found. */+export interface SelectionMenuRequest {+ /** The document's selected text at the gesture (`Selection.toString()`); "" when nothing is selected. */+ selectedText: string;+ /** How many ranges the selection holds (`Selection.rangeCount`). */+ rangeCount: number;+ /** Both ends of the selection's first range lie inside the message stream. */+ firstRangeInStream: boolean;+ /** The pointer behind the gesture ("mouse", "pen", "touch"), or "" when the keyboard asked. */+ pointerType: string;+ /** The gesture landed on an editable field (an input, a textarea, contenteditable). */+ onEditable: boolean;+}++/**+ * Whether the app's menu takes this gesture. Everything it declines keeps the browser's own+ * menu, so the rule declines whenever there is doubt:+ * - a touch or pen press-and-hold, because the mobile OS raises a selection menu of its own+ * for that gesture, and a second menu would fight it;+ * - a gesture on a field, whose own menu (paste, spelling) is the one that belongs there;+ * - no selection, a blank one, or one that runs past the stream — into the composer, say —+ * because then there is no conversation text to act on, or not only conversation text;+ * - a selection built from several ranges (Firefox's Ctrl+drag), even when the first of them+ * lies inside the stream: the text such a selection reads is every range's text, so one+ * range in the composer would ride into the clipboard and into the excerpt, and putting the+ * highlight back afterwards can only restore the one range that was captured.+ */+export function opensSelectionMenu(request: SelectionMenuRequest): boolean {+ if (isLongPressPointer(request.pointerType)) return false;+ if (request.onEditable) return false;+ if (request.rangeCount !== 1 || !request.firstRangeInStream) return false;+ return request.selectedText.trim() !== "";+}++/** One row of the selection menu. */+export type SelectionMenuItem = "copy" | "addToConversation";++/** The rows, in order. */+export const SELECTION_MENU_ITEMS: readonly SelectionMenuItem[] = ["copy", "addToConversation"];++/**+ * Where a keyboard-opened menu hangs: a zero-width point at the right edge of the selection's+ * last line box, which is where a caret at the selection's end would sit — a keyboard user has+ * no pointer to hang it from. `lineBoxes` are the range's client rects in document order, and+ * `bounds` its bounding rect, for a range that reports no line boxes.+ */+export function selectionEndAnchor(+ lineBoxes: readonly AnchorRect[],+ bounds: AnchorRect,+): AnchorRect {+ const last = lineBoxes.at(-1) ?? bounds;+ return { top: last.top, bottom: last.bottom, left: last.right, right: last.right };+}++/** How many characters of an excerpt the chip's label keeps before its ellipsis. */+export const EXCERPT_LABEL_CHARS = 32;++/**+ * The selection as the conversation carries it: line endings made `\n`, and what a drag picks+ * up at either end — blank lines before the text, whitespace after it — dropped. Everything in+ * between stays as it was selected, indentation included.+ */+export function normalizeExcerpt(selectedText: string): string {+ return selectedText+ .replace(/\r\n?/g, "\n")+ .replace(/^(?:[ \t]*\n)+/, "")+ .replace(/\s+$/, "");+}++/**+ * The chip's label: the excerpt's start on one line — every run of whitespace, line breaks+ * included, folded to one space — cut after EXCERPT_LABEL_CHARS characters with an ellipsis.+ * The chip ellipsizes again to fit its own width; this bounds what its label and its accessible+ * name have to carry. Counted in code points, so a cut never splits a character in two.+ */+export function excerptLabel(excerpt: string): string {+ const chars = [...excerpt.replace(/\s+/g, " ").trim()];+ if (chars.length <= EXCERPT_LABEL_CHARS) return chars.join("");+ return `${chars.slice(0, EXCERPT_LABEL_CHARS).join("").trimEnd()}…`;+}++/**+ * The excerpt as a Markdown blockquote: every line behind `> `, and a blank line as a bare `>`,+ * so the quote runs on through it instead of ending there.+ */+export function excerptBlockquote(excerpt: string): string {+ return excerpt+ .split("\n")+ .map((line) => (line.trim() === "" ? ">" : `> ${line}`))+ .join("\n");+}++/** What "Add to conversation" stages: the normalized excerpt, carried into the message as a blockquote. */+export function excerptReference(selectedText: string): ExcerptReference {+ const excerpt = normalizeExcerpt(selectedText);+ return { kind: "excerpt", excerpt, text: excerptBlockquote(excerpt) };+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 7150e1ce..08c1a803 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -422,6 +422,8 @@ export const en: Strings = {retry: "Retry",unknownError: "Request failed, please try again later",requiredField: "This field is required",+ /** A menu row that copies what it acts on (the conversation's selection menu); the confirmation is `copied`. */+ copy: "Copy",copied: "Copied",/** Accessible name of the circled "?" that discloses a section or field explanation. */moreInfo: "More info",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex a615e1a5..e9ba481b 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -429,6 +429,8 @@ export const zh = {retry: "重试",unknownError: "请求失败,请稍后重试",requiredField: "此项必填",+ /** A menu row that copies what it acts on (the conversation's selection menu); the confirmation is `copied`. */+ copy: "复制",copied: "已复制",/** Accessible name of the circled "?" that discloses a section or field explanation. */moreInfo: "说明",diff --git a/packages/web/src/lib/workspace-tree.ts b/packages/web/src/lib/workspace-tree.tsindex da664cce..15c7c2f0 100644--- a/packages/web/src/lib/workspace-tree.ts+++ b/packages/web/src/lib/workspace-tree.ts@@ -522,16 +522,20 @@ export function writeWrapLines(wrap: boolean, storage?: TreePreferenceStorage):// -------------------------------------------------------------- composer references/**- * Something the Files panel hands the composer: what it points at, and the text the message- * carries once it is sent.+ * Something a surface hands the composer: what it points at, and the text the message carries+ * once it is sent. The Files panel hands a Workspace entry or a quoted range of one; the+ * conversation's own selection menu hands an excerpt of the conversation.*- * The text is deliberately kept out of the textarea. What the panel contributes is a whole- * thing — a file, a directory, a quoted range — and the draft is where the person is writing;- * splicing the one into the other buries what they were saying under what they were pointing- * at. The composer shows a chip naming it instead, the same shape `/agent` and `/skill` already- * stage their picks in.+ * The text is deliberately kept out of the textarea. What a surface contributes is a whole+ * thing — a file, a directory, a quoted range, an excerpt — and the draft is where the person is+ * writing; splicing the one into the other buries what they were saying under what they were+ * pointing at. The composer shows a chip naming it instead, the same shape `/agent` and `/skill`+ * already stage their picks in.*/-export interface ComposerReference {+export type ComposerReference = WorkspaceReference | ExcerptReference;++/** A Workspace entry, or a quoted range of one — what the Files panel hands the composer. */+export interface WorkspaceReference {/** Which glyph the chip wears, and what its label means. */kind: "file" | "dir" | "quote";/** Workspace-relative path: the chip's label comes from its last segment, its tooltip from the whole. */@@ -543,6 +547,18 @@ export interface ComposerReference {toLine?: number;}+/**+ * Text selected in the conversation itself. It has no path to name it by, so the chip is+ * labelled by the excerpt's own start and its tooltip is the whole excerpt.+ */+export interface ExcerptReference {+ kind: "excerpt";+ /** The selected text, as the selection read it: the chip's label and tooltip come from this. */+ excerpt: string;+ /** What goes into the message: the excerpt as a Markdown blockquote. */+ text: string;+}+/*** A file name split for display: the stem, and the extension with its dot still on it.*diff --git a/packages/web/test/message-stream.test.ts b/packages/web/test/message-stream.test.tsindex 7e87ca66..f62bd64e 100644--- a/packages/web/test/message-stream.test.ts+++ b/packages/web/test/message-stream.test.ts@@ -55,6 +55,8 @@ describe("MessageStream links", () => {],version: 1,ctx,+ // Every stream belongs to a conversation with a composer to stage an excerpt in.+ onAddExcerpt: () => {},}),);const tags = anchors(html);diff --git a/packages/web/test/selection-menu.test.ts b/packages/web/test/selection-menu.test.tsnew file mode 100644index 00000000..f039b945--- /dev/null+++ b/packages/web/test/selection-menu.test.ts@@ -0,0 +1,146 @@+/**+ * lib/selection-menu.ts: the rules behind the conversation's menu for selected text.+ *+ * Which gestures it takes matters as much in the negative as in the positive: everything it+ * declines keeps the browser's own menu, so a rule that took a touch press-and-hold, a+ * right-click in a field, or a selection that runs into the composer would take a menu away+ * from someone who needed it. The excerpt half pins what reaches the model: the blockquote+ * the message carries, and the label the chip shows instead of it.+ */+import { describe, expect, it } from "vitest";+import {+ EXCERPT_LABEL_CHARS,+ SELECTION_MENU_ITEMS,+ excerptBlockquote,+ excerptLabel,+ excerptReference,+ normalizeExcerpt,+ opensSelectionMenu,+ selectionEndAnchor,+} from "../src/lib/selection-menu";+import type { SelectionMenuRequest } from "../src/lib/selection-menu";++/** A right-click on a selection of reply text: the case the menu exists for. */+const REQUEST: SelectionMenuRequest = {+ selectedText: "npm run build",+ rangeCount: 1,+ firstRangeInStream: true,+ pointerType: "mouse",+ onEditable: false,+};++describe("opensSelectionMenu", () => {+ it("takes a secondary click on a selection inside the stream", () => {+ expect(opensSelectionMenu(REQUEST)).toBe(true);+ });++ it("takes the keyboard's request too, which names no pointer", () => {+ expect(opensSelectionMenu({ ...REQUEST, pointerType: "" })).toBe(true);+ });++ it("leaves a touch or pen press-and-hold to the OS selection menu", () => {+ expect(opensSelectionMenu({ ...REQUEST, pointerType: "touch" })).toBe(false);+ expect(opensSelectionMenu({ ...REQUEST, pointerType: "pen" })).toBe(false);+ });++ it("leaves the browser's menu alone when nothing, or only whitespace, is selected", () => {+ expect(opensSelectionMenu({ ...REQUEST, selectedText: "" })).toBe(false);+ expect(opensSelectionMenu({ ...REQUEST, selectedText: " \n\t " })).toBe(false);+ });++ it("declines a selection that runs out of the stream, into the composer for one", () => {+ expect(opensSelectionMenu({ ...REQUEST, firstRangeInStream: false })).toBe(false);+ });++ it("declines a selection of several ranges, even with the first one inside the stream", () => {+ // Firefox's Ctrl+drag builds one: the text read from such a selection is every range's,+ // so a second range in the composer would ride into the clipboard and into the excerpt,+ // and the highlight put back afterwards could only be the one range that was captured.+ expect(opensSelectionMenu({ ...REQUEST, rangeCount: 2 })).toBe(false);+ expect(opensSelectionMenu({ ...REQUEST, rangeCount: 0 })).toBe(false);+ });++ it("declines a gesture on a field, whose own menu (paste, spelling) belongs there", () => {+ expect(opensSelectionMenu({ ...REQUEST, onEditable: true })).toBe(false);+ });+});++describe("SELECTION_MENU_ITEMS", () => {+ it("is Copy, then Add to conversation", () => {+ expect(SELECTION_MENU_ITEMS).toEqual(["copy", "addToConversation"]);+ });+});++describe("selectionEndAnchor", () => {+ const box = (top: number, left: number, right: number) => ({+ top,+ bottom: top + 20,+ left,+ right,+ });++ it("hangs a keyboard-opened menu at the end of the selection's last line", () => {+ // Two lines: the menu belongs at the right edge of the second, where a caret would sit.+ expect(selectionEndAnchor([box(100, 40, 600), box(120, 40, 230)], box(100, 40, 600))).toEqual({+ top: 120,+ bottom: 140,+ left: 230,+ right: 230,+ });+ });++ it("falls back to the bounding box when the range reports no line boxes", () => {+ expect(selectionEndAnchor([], box(300, 10, 90))).toEqual({+ top: 300,+ bottom: 320,+ left: 90,+ right: 90,+ });+ });+});++describe("normalizeExcerpt", () => {+ it("drops what a drag picks up at either end, and nothing in between", () => {+ expect(normalizeExcerpt("\n \n indented line\n\nnext\n \n")).toBe(" indented line\n\nnext");+ });++ it("makes every line ending a newline", () => {+ expect(normalizeExcerpt("a\r\nb\rc")).toBe("a\nb\nc");+ });+});++describe("excerptBlockquote", () => {+ it("quotes every line, and keeps a blank line inside the quote", () => {+ expect(excerptBlockquote("first\n\n second")).toBe("> first\n>\n> second");+ });+});++describe("excerptLabel", () => {+ it("keeps a short excerpt whole, on one line", () => {+ expect(excerptLabel("fix the\n build")).toBe("fix the build");+ });++ it("cuts a long excerpt after its first characters, with an ellipsis", () => {+ const long = "The build fails because the server bundle imports a type-only module.";+ const label = excerptLabel(long);+ expect(label.endsWith("…")).toBe(true);+ expect([...label].length).toBeLessThanOrEqual(EXCERPT_LABEL_CHARS + 1);+ expect(long.startsWith(label.slice(0, -1))).toBe(true);+ });++ it("counts characters, not UTF-16 units, so a cut never splits one", () => {+ const label = excerptLabel("中".repeat(EXCERPT_LABEL_CHARS) + "文😀😀");+ expect(label).toBe(`${"中".repeat(EXCERPT_LABEL_CHARS)}…`);+ expect(excerptLabel("😀".repeat(EXCERPT_LABEL_CHARS))).toBe("😀".repeat(EXCERPT_LABEL_CHARS));+ });+});++describe("excerptReference", () => {+ it("stages the normalized excerpt and carries it into the message as a blockquote", () => {+ expect(excerptReference("\nRun the migration first.\nThen restart.\n")).toEqual({+ kind: "excerpt",+ excerpt: "Run the migration first.\nThen restart.",+ text: "> Run the migration first.\n> Then restart.",+ });+ });+});diff --git a/packages/web/test/stream-follow.test.ts b/packages/web/test/stream-follow.test.tsindex 630c50bd..8f2e12b1 100644--- a/packages/web/test/stream-follow.test.ts+++ b/packages/web/test/stream-follow.test.ts@@ -5,8 +5,13 @@* user can scroll back down to resume; content-shrink clamping isn't* misread as an upward scroll. Plus stickToBottom: programmatic snaps report the* landed position synchronously, so content growth racing the snap's async scroll- * event can't make entering a conversation land off-bottom.+ * event can't make entering a conversation land off-bottom. Plus the hold: while the+ * selection menu is open the view does not snap, the user's own scrolling still decides+ * the intent, and a release catches a following view up with what arrived meanwhile.*/+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { createStreamFollow, stickToBottom } from "../src/features/chat/stream-follow";@@ -169,3 +174,78 @@ describe("stickToBottom", () => {expect(f.stick).toBe(true);});});++describe("hold", () => {+ it("defers the snap without touching the intent, and the release catches a following view up", () => {+ const f = createStreamFollow();+ const el = fakeContainer(2000, 460);+ stickToBottom(el, f);+ expect(f.snaps).toBe(true);+ // The selection menu opens during a live reply: nothing may snap now.+ f.hold(true);+ expect(f.snaps).toBe(false);+ // Chunks grow the content below the view; the view stays put, and staying put is not an+ // upward scroll, so the intent to follow survives the hold.+ el.scrollHeight += 300;+ f.scrolled(el.metrics());+ expect(f.stick).toBe(true);+ expect(f.snaps).toBe(false);+ expect(el.scrollTop).toBe(1540);+ // The menu closes: the view snaps again, straight to the new bottom.+ f.hold(false);+ expect(f.snaps).toBe(true);+ stickToBottom(el, f);+ expect(el.scrollTop).toBe(1840);+ expect(f.stick).toBe(true);+ });++ it("lets the user's own upward scroll during a hold exit follow, so the release leaves the view there", () => {+ const f = createStreamFollow();+ const el = fakeContainer(2000, 460);+ stickToBottom(el, f);+ f.hold(true);+ f.wheel(-3);+ el.scrollTop = 900;+ f.scrolled(el.metrics());+ f.hold(false);+ expect(f.stick).toBe(false);+ expect(f.snaps).toBe(false);+ });++ it("lets the user's own return to the bottom during a hold resume follow, which the release acts on", () => {+ const f = createStreamFollow();+ const el = fakeContainer(2000, 460);+ stickToBottom(el, f);+ el.scrollTop = 900; // parked above the bottom before the menu opened+ f.scrolled(el.metrics());+ f.hold(true);+ el.scrollTop = 1500; // scrolled back within 80px of the bottom+ f.scrolled(el.metrics());+ expect(f.snaps).toBe(false);+ f.hold(false);+ expect(f.snaps).toBe(true);+ });++ it("releases a view that was not following to not following", () => {+ const f = createStreamFollow();+ f.scrolled({ scrollHeight: 2000, clientHeight: 460, scrollTop: 1000 });+ f.hold(true);+ f.hold(false);+ expect(f.stick).toBe(false);+ expect(f.snaps).toBe(false);+ });++ it("is what the message stream snaps by, held while its selection menu is open", () => {+ // The rules above bind the stream only while every snap it makes asks `snaps` rather than+ // `stick`, and the hold follows the menu's open state.+ const stream = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), "../src/features/chat/message-stream.tsx"),+ "utf8",+ );+ expect(stream).toContain("const menuOpen = selectionMenu.open;");+ expect(stream).toContain("follow.hold(menuOpen);");+ const snaps = stream.match(/if \(([^)]*?)\) stickToBottom\(el, follow\);/g) ?? [];+ expect(snaps.length).toBeGreaterThanOrEqual(3);+ for (const snap of snaps) expect(snap).toContain("follow.snaps");+ });+});diff --git a/packages/web/test/stream-selection-menu.test.ts b/packages/web/test/stream-selection-menu.test.tsnew file mode 100644index 00000000..486b69f0--- /dev/null+++ b/packages/web/test/stream-selection-menu.test.ts@@ -0,0 +1,150 @@+/**+ * The conversation's selection menu, rendered (react-dom/server static markup, and the rows'+ * own element tree for their click handlers — node env, no DOM): the rows it draws, and what+ * each does with the selection it was opened on. "Add to conversation" stages a chip+ * through the composer's control — the same `addReference` the Files panel stages through —+ * and that chip shows the excerpt rather than a path; Copy writes the selection and confirms+ * with a toast, the menu-row convention.+ *+ * Reading the selection off the page and anchoring the panel are DOM work this environment+ * cannot run; the rules deciding both are pinned in selection-menu.test.ts.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { createElement, isValidElement } from "react";+import type { ReactElement, ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { SelectionMenuRows } from "../src/features/chat/stream-selection-menu";+import type { CapturedSelection } from "../src/features/chat/stream-selection-menu";+import type { ComposerControl } from "../src/features/chat/chat-input";+import { ReferenceChip } from "../src/features/chat/reference-chip";+import { QUOTE_ICON } from "../src/components/ui/icons";+import { excerptLabel } from "../src/lib/selection-menu";+import type { ComposerReference } from "../src/lib/workspace-tree";+import { S, setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";++/** Toasts raised during a test (the real store would leave its dismiss timers running). */+const toasts = vi.hoisted(() => [] as string[]);++vi.mock("../src/components/ui/toast", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../src/components/ui/toast")>();+ return {+ ...actual,+ toastSuccess: (text: string) => {+ toasts.push(text);+ },+ };+});++const EXCERPT = "Run the migration first.\nThen restart the server so it picks up the new schema.";++/** A selection as the stream captures it: the text as selected (a trailing newline included). */+const SELECTION: CapturedSelection = { text: `${EXCERPT}\n`, range: {} as Range };++type Row = ReactElement<{ onClick: () => void; children: ReactNode }>;++/** The rows as the component returns them, to reach their click handlers. */+function rows(props: Parameters<typeof SelectionMenuRows>[0]): Row[] {+ const fragment = SelectionMenuRows(props) as ReactElement<{ children: ReactNode }>;+ return ([] as ReactNode[]).concat(fragment.props.children).filter(isValidElement) as Row[];+}++/** A row's visible label: its text children, without the glyph. */+const label = (row: Row) =>+ ([] as ReactNode[])+ .concat(row.props.children)+ .filter((child): child is string => typeof child === "string")+ .join("");++afterEach(() => {+ setActiveStrings(zh);+ toasts.length = 0;+ vi.unstubAllGlobals();+});++describe("SelectionMenuRows", () => {+ it("draws Copy, then Add to conversation", () => {+ const html = renderToStaticMarkup(+ createElement(SelectionMenuRows, {+ selection: SELECTION,+ onAddExcerpt: () => {},+ onDone: () => {},+ }),+ );+ const copy = html.indexOf(`${S.common.copy}</button>`);+ const add = html.indexOf(`${S.files.addToChat}</button>`);+ expect(copy).toBeGreaterThan(-1);+ expect(add).toBeGreaterThan(copy);+ });++ it("follows the UI language", () => {+ setActiveStrings(en);+ const html = renderToStaticMarkup(+ createElement(SelectionMenuRows, {+ selection: SELECTION,+ onAddExcerpt: () => {},+ onDone: () => {},+ }),+ );+ expect(html).toContain("Copy</button>");+ expect(html).toContain("Add to conversation</button>");+ });+});++describe("Add to conversation", () => {+ it("stages the excerpt as a chip through the composer's control, and nothing else", () => {+ const staged: ComposerReference[] = [];+ const fillPrompt = vi.fn();+ const control: ComposerControl = {+ fillPrompt,+ addReference: (reference) => {+ staged.push(reference);+ },+ };+ const onDone = vi.fn();+ const add = rows({ selection: SELECTION, onAddExcerpt: control.addReference, onDone }).find(+ (row) => label(row) === S.files.addToChat,+ );+ add!.props.onClick();++ // One reference, carried into the message as a blockquote; the draft itself is never filled.+ expect(staged).toEqual([+ {+ kind: "excerpt",+ excerpt: EXCERPT,+ text: "> Run the migration first.\n> Then restart the server so it picks up the new schema.",+ },+ ]);+ expect(fillPrompt).not.toHaveBeenCalled();+ // Then the panel closes and the highlight is put back, with the same selection.+ expect(onDone).toHaveBeenCalledExactlyOnceWith(SELECTION);++ // The chip the composer draws for it: the excerpt's start as its label, the whole excerpt+ // as its tooltip, the quotation glyph — and no path, because an excerpt has none.+ const chip = renderToStaticMarkup(+ createElement(ReferenceChip, { reference: staged[0]!, onRemove: () => {} }),+ );+ const name = excerptLabel(EXCERPT);+ expect(name.endsWith("…")).toBe(true);+ expect(chip).toContain(`title="${EXCERPT}"`);+ expect(chip).toContain(`>${name}</span>`);+ expect(chip).toContain(`d="${QUOTE_ICON}"`);+ expect(chip).toContain(`aria-label="${S.files.removeReference} ${name}"`);+ });+});++describe("Copy", () => {+ it("writes the selection as it was selected, and confirms with a toast", () => {+ const writeText = vi.fn(async () => {});+ vi.stubGlobal("navigator", { clipboard: { writeText } });+ const onDone = vi.fn();+ const copy = rows({ selection: SELECTION, onAddExcerpt: () => {}, onDone }).find(+ (row) => label(row) === S.common.copy,+ );+ copy!.props.onClick();++ expect(writeText).toHaveBeenCalledExactlyOnceWith(SELECTION.text);+ expect(toasts).toEqual([S.common.copied]);+ expect(onDone).toHaveBeenCalledExactlyOnceWith(SELECTION);+ });+});