Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(chat): copy assistant reply + collapse process into a single outer fold (#2151)
Naiyuan Qingc784a6a9eee1
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsxindex b7aa4e5558..0c21266777 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -1,25 +1,34 @@"use client";import { useState, useRef } from "react";+import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";import { cn } from "@multica/ui/lib/utils";import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { Button } from "@multica/ui/components/ui/button";import {Collapsible,CollapsibleContent,CollapsibleTrigger,} from "@multica/ui/components/ui/collapsible";-import { ChevronRight, ChevronDown, Brain, AlertCircle, AlertTriangle } from "lucide-react";+import {+ Tooltip,+ TooltipTrigger,+ TooltipContent,+} from "@multica/ui/components/ui/tooltip";+import { ChevronRight, ChevronDown, Brain, AlertCircle, AlertTriangle, Copy } from "lucide-react";import { useScrollFade } from "@multica/ui/hooks/use-scroll-fade";import { useAutoScroll } from "@multica/ui/hooks/use-auto-scroll";import { taskMessagesOptions } from "@multica/core/chat/queries";import { Markdown } from "@multica/views/common/markdown";+import { copyMarkdown } from "../../editor";import type { AgentAvailability } from "@multica/core/agents";import type { ChatMessage, ChatPendingTask, TaskMessagePayload, TaskFailureReason } from "@multica/core/types";import type { ChatTimelineItem } from "@multica/core/chat";import { failureReasonLabel } from "../../agents/components/tabs/task-failure";import { TaskStatusPill } from "./task-status-pill";import { formatElapsedMs } from "../lib/format";+import { splitTimeline, extractCopyText } from "../lib/copy-text";import { useT } from "../../i18n";// ─── Public component ────────────────────────────────────────────────────@@ -73,11 +82,15 @@ export function ChatMessageList({* than issue-detail's px-8 because the chat window can be narrow. */}<div className="mx-auto w-full max-w-4xl px-5 py-4 space-y-4">{messages.map((msg) => (- <MessageBubble key={msg.id} message={msg} />+ <MessageBubble+ key={msg.id}+ message={msg}+ isPending={!!pendingTaskId && msg.task_id === pendingTaskId}+ />))}{hasLive && (<div className="w-full space-y-1.5">- <TimelineView items={liveTimeline} />+ <TimelineView items={liveTimeline} isStreaming /></div>)}{showStatusPill && pendingTask && (@@ -132,7 +145,7 @@ function toTimelineItem(m: TaskMessagePayload): ChatTimelineItem {// ─── Message bubbles ─────────────────────────────────────────────────────-function MessageBubble({ message }: { message: ChatMessage }) {+function MessageBubble({ message, isPending }: { message: ChatMessage; isPending: boolean }) {if (message.role === "user") {return (<div className="flex justify-end">@@ -149,13 +162,15 @@ function MessageBubble({ message }: { message: ChatMessage }) {);}- return <AssistantMessage message={message} />;+ return <AssistantMessage message={message} isPending={isPending} />;}function AssistantMessage({message,+ isPending,}: {message: ChatMessage;+ isPending: boolean;}) {const taskId = message.task_id;@@ -193,13 +208,79 @@ function AssistantMessage({<Markdown>{message.content}</Markdown></div>)}+ <MessageFooter+ message={message}+ timeline={timeline}+ isPending={isPending}+ />+ </div>+ );+}++// Inline footer row beneath the assistant reply: "Replied in 38s · [Copy]".+// Action icons live here (not as a hover-floating overlay) so they're+// discoverable on first read and don't shift content. Buttons stay quiet+// (muted) until hover. Copy is suppressed during streaming because the+// final text is still being appended.+function MessageFooter({+ message,+ timeline,+ isPending,+}: {+ message: ChatMessage;+ timeline: ChatTimelineItem[];+ isPending: boolean;+}) {+ const showCopy = !isPending;+ if (message.elapsed_ms == null && !showCopy) return null;+ return (+ <div className="flex items-center gap-1.5">{message.elapsed_ms != null && (<ElapsedCaption variant="replied" elapsedMs={message.elapsed_ms} />)}+ {showCopy && <MessageCopyButton message={message} timeline={timeline} />}</div>);}+function MessageCopyButton({+ message,+ timeline,+}: {+ message: ChatMessage;+ timeline: ChatTimelineItem[];+}) {+ const { t } = useT("chat");+ const handleCopy = async () => {+ try {+ await copyMarkdown(extractCopyText(message, timeline));+ toast.success(t(($) => $.message_list.copied_toast));+ } catch {+ toast.error(t(($) => $.message_list.copy_failed_toast));+ }+ };+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-xs"+ className="text-muted-foreground/70 hover:text-foreground"+ onClick={handleCopy}+ aria-label={t(($) => $.message_list.copy_action)}+ />+ }+ >+ <Copy />+ </TooltipTrigger>+ <TooltipContent side="top">+ {t(($) => $.message_list.copy_action)}+ </TooltipContent>+ </Tooltip>+ );+}+// Persisted "Replied in 38s" / "Failed after 12s" line under the assistant// bubble. Reads `elapsed_ms` straight off the chat_message — server computes// it once at task completion, so this caption is identical across reloads@@ -220,7 +301,7 @@ function ElapsedCaption({? t(($) => $.message_list.replied_in, { elapsed: formatElapsedMs(elapsedMs) }): t(($) => $.message_list.failed_after, { elapsed: formatElapsedMs(elapsedMs) });return (- <div className={cn("text-[11px] text-muted-foreground/80", className)}>+ <div className={cn("text-xs text-muted-foreground/80", className)}>{text}</div>);@@ -259,7 +340,7 @@ function FailureBubble({<div className="text-destructive/90">{label}</div>{rawError.trim() && (<Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="mt-0.5 flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors">+ <CollapsibleTrigger className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors">{open ? (<ChevronDown className="size-3" />) : (@@ -268,7 +349,7 @@ function FailureBubble({<span>{t(($) => $.message_list.show_details)}</span></CollapsibleTrigger><CollapsibleContent>- <pre className="mt-1 max-h-40 overflow-auto rounded bg-muted/40 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">+ <pre className="mt-1 max-h-40 overflow-auto rounded bg-muted/40 p-2 text-xs text-muted-foreground whitespace-pre-wrap break-all">{rawError}</pre></CollapsibleContent>@@ -284,70 +365,49 @@ function FailureBubble({);}-// ─── Timeline: flat interleaved text + collapsible tool groups ───────────--interface TimelineSegment {- kind: "text" | "tools";+// ─── Timeline: outer process fold + final text (Conductor-style) ─────────+//+// splitTimeline (lib/copy-text.ts) carves the items into:+// preface — text before the first thinking/tool item+// middle — first → last non-text item (inclusive, may sandwich text)+// final — text after the last non-text item+//+// We render preface + final outside an outer Collapsible ("X steps") that+// wraps middle. The inner row Collapsibles (ThinkingRow / ToolCallRow /+// ToolResultRow) are unchanged — clicking them toggles independently of+// the outer fold. Copy mirrors what's visible when the outer fold is+// closed: preface + final, never middle. See extractCopyText for the+// authoritative copy logic.++function TimelineView({+ items,+ isStreaming,+}: {items: ChatTimelineItem[];-}--/** Split items into segments: consecutive non-text → "tools", consecutive text → merged "text". */-function segmentTimeline(items: ChatTimelineItem[]): TimelineSegment[] {- const segments: TimelineSegment[] = [];- let toolBuf: ChatTimelineItem[] = [];- let textBuf: ChatTimelineItem[] = [];-- const flushTools = () => {- if (toolBuf.length > 0) {- segments.push({ kind: "tools", items: toolBuf });- toolBuf = [];- }- };-- const flushText = () => {- if (textBuf.length > 0) {- segments.push({ kind: "text", items: textBuf });- textBuf = [];- }- };-- for (const item of items) {- if (item.type === "text") {- flushTools();- textBuf.push(item);- } else {- flushText();- toolBuf.push(item);- }- }- flushText();- flushTools();- return segments;-}--function TimelineView({ items }: { items: ChatTimelineItem[] }) {- const segments = segmentTimeline(items);+ isStreaming?: boolean;+}) {+ const { preface, middle, final } = splitTimeline(items);return (<>- {segments.map((seg, i) =>- seg.kind === "text" ? (- <div key={seg.items[0]!.seq} className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">- <Markdown>{seg.items.map((t) => t.content ?? "").join("")}</Markdown>- </div>- ) : (- <ToolGroupCollapsible- key={seg.items[0]!.seq}- items={seg.items}- defaultOpen={i === segments.length - 1}- />- ),+ {preface.length > 0 && (+ <div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">+ <Markdown>{preface.map((t) => t.content ?? "").join("")}</Markdown>+ </div>+ )}+ {middle.length > 0 && (+ <OuterProcessFold items={middle} defaultOpen={!!isStreaming} />+ )}+ {final.length > 0 && (+ <div className="text-sm leading-relaxed prose prose-sm dark:prose-invert max-w-none">+ <Markdown>{final.map((t) => t.content ?? "").join("")}</Markdown>+ </div>)}</>);}-function ToolGroupCollapsible({+function OuterProcessFold({items,defaultOpen,}: {@@ -355,27 +415,47 @@ function ToolGroupCollapsible({defaultOpen?: boolean;}) {const { t } = useT("chat");+ // useState seeds once at mount — subsequent renders never overwrite the+ // user's manual toggle. The streaming → completed transition unmounts+ // the live <TimelineView> and mounts the persisted AssistantMessage's+ // own <TimelineView>, so the persisted instance starts closed (default)+ // even if the live one was open. That's the desired collapsed-default.const [open, setOpen] = useState(defaultOpen ?? false);- const toolCount = items.filter((i) => i.type === "tool_use").length;- const label = t(($) => $.message_list.tools, { count: toolCount });+ const stepCount = items.length;return (<Collapsible open={open} onOpenChange={setOpen}>- <CollapsibleTrigger className="flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors">+ <CollapsibleTrigger className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors">{open ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}- <span>{label}</span>+ <span>{t(($) => $.message_list.process_steps, { count: stepCount })}</span></CollapsibleTrigger><CollapsibleContent><div className="mt-1 rounded-lg border bg-muted/20 p-2 space-y-0.5">- {items.map((item) => (- <ItemRow key={item.seq} item={item} />- ))}+ {items.map((item) =>+ item.type === "text" ? (+ <MiddleTextRow key={item.seq} item={item} />+ ) : (+ <ItemRow key={item.seq} item={item} />+ ),+ )}</div></CollapsibleContent></Collapsible>);}+// Intermediate text segment rendered inside the outer fold. Visually+// down-shifted (xs / muted) so it reads as part of the agent's process,+// not the final answer — the final answer renders below the fold at full+// prose size.+function MiddleTextRow({ item }: { item: ChatTimelineItem }) {+ return (+ <div className="py-0.5 text-xs text-muted-foreground prose prose-sm dark:prose-invert max-w-none [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">+ <Markdown>{item.content ?? ""}</Markdown>+ </div>+ );+}+// ─── Individual item rows ────────────────────────────────────────────────function ItemRow({ item }: { item: ChatTimelineItem }) {@@ -442,7 +522,7 @@ function ToolCallRow({ item }: { item: ChatTimelineItem }) {</CollapsibleTrigger>{hasInput && (<CollapsibleContent>- <pre className="ml-[18px] mt-0.5 max-h-32 overflow-auto rounded bg-muted/50 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">+ <pre className="ml-[18px] mt-0.5 max-h-32 overflow-auto rounded bg-muted/50 p-2 text-xs text-muted-foreground whitespace-pre-wrap break-all">{JSON.stringify(item.input, null, 2)}</pre></CollapsibleContent>@@ -473,7 +553,7 @@ function ToolResultRow({ item }: { item: ChatTimelineItem }) {</span></CollapsibleTrigger><CollapsibleContent>- <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/50 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-all">+ <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/50 p-2 text-xs text-muted-foreground whitespace-pre-wrap break-all">{output.length > 4000 ? output.slice(0, 4000) + "\n... (truncated)" : output}</pre></CollapsibleContent>@@ -495,7 +575,7 @@ function ThinkingRow({ item }: { item: ChatTimelineItem }) {<span className="text-muted-foreground italic truncate">{preview}</span></CollapsibleTrigger><CollapsibleContent>- <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/30 p-2 text-[11px] text-muted-foreground whitespace-pre-wrap break-words">+ <pre className="ml-[18px] mt-0.5 max-h-40 overflow-auto rounded bg-muted/30 p-2 text-xs text-muted-foreground whitespace-pre-wrap break-words">{text}</pre></CollapsibleContent>diff --git a/packages/views/chat/lib/copy-text.test.ts b/packages/views/chat/lib/copy-text.test.tsnew file mode 100644index 0000000000..70937f77e0--- /dev/null+++ b/packages/views/chat/lib/copy-text.test.ts@@ -0,0 +1,134 @@+import { describe, it, expect } from "vitest";+import type { ChatMessage } from "@multica/core/types";+import type { ChatTimelineItem } from "@multica/core/chat";+import { splitTimeline, extractCopyText } from "./copy-text";++const text = (seq: number, content: string): ChatTimelineItem => ({+ seq,+ type: "text",+ content,+});++const thinking = (seq: number, content = "..."): ChatTimelineItem => ({+ seq,+ type: "thinking",+ content,+});++const tool = (seq: number, name = "Read"): ChatTimelineItem => ({+ seq,+ type: "tool_use",+ tool: name,+ input: { path: "/x" },+});++const message = (content: string): ChatMessage => ({+ id: "m1",+ chat_session_id: "s1",+ role: "assistant",+ content,+ task_id: "t1",+ created_at: "2026-05-06T00:00:00Z",+});++describe("splitTimeline", () => {+ it("treats an all-text timeline as final (no fold)", () => {+ const items = [text(1, "hello"), text(2, "world")];+ expect(splitTimeline(items)).toEqual({+ preface: [],+ middle: [],+ final: items,+ });+ });++ it("treats an all-non-text timeline as middle with no final", () => {+ const items = [thinking(1), tool(2), thinking(3)];+ const out = splitTimeline(items);+ expect(out.preface).toEqual([]);+ expect(out.middle).toEqual(items);+ expect(out.final).toEqual([]);+ });++ it("standard shape: thinking → tool → text → tool → final-text", () => {+ const t1 = thinking(1);+ const u1 = tool(2);+ const x1 = text(3, "intermediate");+ const u2 = tool(4);+ const f1 = text(5, "final answer");+ const out = splitTimeline([t1, u1, x1, u2, f1]);+ expect(out.preface).toEqual([]);+ expect(out.middle).toEqual([t1, u1, x1, u2]);+ expect(out.final).toEqual([f1]);+ });++ it("collects multiple trailing text segments into final", () => {+ const u = tool(1);+ const f1 = text(2, "para 1");+ const f2 = text(3, "para 2");+ const out = splitTimeline([u, f1, f2]);+ expect(out.middle).toEqual([u]);+ expect(out.final).toEqual([f1, f2]);+ });++ it("collects leading text into preface", () => {+ const p = text(1, "preface");+ const u = tool(2);+ const f = text(3, "final");+ const out = splitTimeline([p, u, f]);+ expect(out.preface).toEqual([p]);+ expect(out.middle).toEqual([u]);+ expect(out.final).toEqual([f]);+ });+});++describe("extractCopyText", () => {+ it("falls back to message.content when timeline is empty (legacy)", () => {+ expect(extractCopyText(message("legacy body"), [])).toBe("legacy body");+ });++ it("returns concatenated text segments for an all-text timeline", () => {+ expect(+ extractCopyText(message(""), [text(1, "hello"), text(2, "world")]),+ ).toBe("hello\n\nworld");+ });++ it("returns only the final text for the standard tool-using shape", () => {+ expect(+ extractCopyText(message(""), [+ thinking(1),+ tool(2),+ text(3, "intermediate — should be excluded"),+ tool(4),+ text(5, "final answer"),+ ]),+ ).toBe("final answer");+ });++ it("includes preface and final, excludes middle text", () => {+ expect(+ extractCopyText(message(""), [+ text(1, "preface"),+ tool(2),+ text(3, "middle — excluded"),+ tool(4),+ text(5, "final"),+ ]),+ ).toBe("preface\n\nfinal");+ });++ it("falls back to message.content when timeline has no text items", () => {+ expect(+ extractCopyText(message("fallback body"), [thinking(1), tool(2)]),+ ).toBe("fallback body");+ });++ it("joins multiple trailing text segments with blank-line separators", () => {+ expect(+ extractCopyText(message(""), [+ tool(1),+ text(2, "para 1"),+ text(3, "para 2"),+ ]),+ ).toBe("para 1\n\npara 2");+ });+});diff --git a/packages/views/chat/lib/copy-text.ts b/packages/views/chat/lib/copy-text.tsnew file mode 100644index 0000000000..98bc19e5ef--- /dev/null+++ b/packages/views/chat/lib/copy-text.ts@@ -0,0 +1,54 @@+import type { ChatMessage } from "@multica/core/types";+import type { ChatTimelineItem } from "@multica/core/chat";++/**+ * Split an assistant timeline into three regions for the conductor-style fold:+ * preface — text items before the first thinking/tool/error item+ * middle — everything from the first to the last non-text item (inclusive),+ * including any text items sandwiched between them+ * final — text items after the last non-text item+ *+ * UI renders preface above the outer fold, middle inside the fold (with each+ * row keeping its existing inner Collapsible), and final below the fold.+ * Copy concatenates preface + final — the fold's contents are intentionally+ * omitted, mirroring what's visible when the fold is closed.+ */+export function splitTimeline(items: ChatTimelineItem[]): {+ preface: ChatTimelineItem[];+ middle: ChatTimelineItem[];+ final: ChatTimelineItem[];+} {+ const firstNonTextIdx = items.findIndex((i) => i.type !== "text");+ if (firstNonTextIdx === -1) {+ return { preface: [], middle: [], final: items };+ }+ let lastNonTextIdx = items.length - 1;+ while (lastNonTextIdx >= 0 && items[lastNonTextIdx]!.type === "text") {+ lastNonTextIdx--;+ }+ return {+ preface: items.slice(0, firstNonTextIdx),+ middle: items.slice(firstNonTextIdx, lastNonTextIdx + 1),+ final: items.slice(lastNonTextIdx + 1),+ };+}++/**+ * Markdown source the Copy action puts on the clipboard. By design this is+ * the user-visible answer only — anything inside the outer fold (thinking,+ * tool calls, sandwiched intermediate text) is dropped. Falls back to+ * `message.content` for legacy messages without a timeline and for the+ * pathological all-non-text shape so Copy never produces an empty string.+ */+export function extractCopyText(+ message: ChatMessage,+ timeline: ChatTimelineItem[],+): string {+ if (timeline.length === 0) return message.content ?? "";+ const { preface, final } = splitTimeline(timeline);+ const pieces = [...preface, ...final]+ .map((i) => i.content ?? "")+ .filter((s) => s.length > 0);+ if (pieces.length === 0) return message.content ?? "";+ return pieces.join("\n\n");+}diff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex a02f37d3e2..50216c84ba 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -19,7 +19,12 @@"tools_one": "{{count}} tool","tools_other": "{{count}} tools","tool_result_named": "{{tool}} result: ",- "tool_result_unnamed": "result: "+ "tool_result_unnamed": "result: ",+ "process_steps_one": "{{count}} step",+ "process_steps_other": "{{count}} steps",+ "copy_action": "Copy",+ "copied_toast": "Copied",+ "copy_failed_toast": "Copy failed"},"session_history": {"back_tooltip": "Back",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex 0abcd571ec..65da561a21 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -17,7 +17,11 @@"task_failed_fallback": "task 失败","tools_other": "{{count}} 个工具","tool_result_named": "{{tool}} 结果:",- "tool_result_unnamed": "结果:"+ "tool_result_unnamed": "结果:",+ "process_steps_other": "{{count}} 步",+ "copy_action": "复制",+ "copied_toast": "已复制",+ "copy_failed_toast": "复制失败"},"session_history": {"back_tooltip": "返回",