Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(desktop): copy the full conversation history
yuxinoe7c132cd94fd
diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsxindex 2fa0fc44d..00f71bec2 100644--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx@@ -20,6 +20,8 @@ import { useTranscriptScroll } from "./hooks/useTranscriptScroll";import type { TranscriptSearchTarget } from "../../../lib/transcript-reading";import { TranscriptSearchContext } from "../../../lib/transcript-search-context";import { DisclosureAnchorContext } from "../../../lib/disclosure-anchor-context";+import { api } from "../../../lib/api";+import { mergeLiveSessionMessages } from "../../../lib/session-transcript";import { conversationPlainText } from "../../../lib/chat-transcript-text";import {TranscriptMenuProvider,@@ -89,6 +91,7 @@ function TranscriptBody({const { t } = useTranslation();const openTranscriptMenu = useTranscriptMenu();const { copyText, selectText } = useChatTextActions();+ const showToast = useAppStore((state) => state.showToast);const transcriptRunning = isRunning && !readingWindow;const latestTurnResult = useAppStore((state) =>sessionId ? state.latestTurnResults[sessionId] : undefined,@@ -180,15 +183,30 @@ function TranscriptBody({conversation rather than one message, so it is the only surface that cancopy the whole thread.*/+ const copyConversation = async () => {+ if (!sessionId) return;+ try {+ // Explicit copy reads the full session without changing the reading window.+ const { session } = await api.getSession(sessionId);+ if (!session) throw new Error("Session unavailable");+ await copyText(conversationPlainText(+ mergeLiveSessionMessages(session.messages ?? [], messages),+ { user: t("chat.speakerYou"), assistant: t("chat.speakerAssistant") },+ ));+ } catch {+ showToast(t("chat.copyFailed"), { variant: "error" });+ }+ };+const onContextMenu = (event: ReactMouseEvent<HTMLDivElement>) => {openTranscriptMenu(event, {label: t("chat.conversationMenu"),items: conversationMenuItems({t,- conversation: conversationPlainText(messages, {- user: t("chat.speakerYou"),- assistant: t("chat.speakerAssistant"),- }),+ canCopy: Boolean(sessionId) && (hasMoreBefore || hasMoreAfter || messages.some(+ (message) => (message.role === "user" || message.role === "assistant") && message.content.trim(),+ )),+ onCopyConversation: () => void copyConversation(),scrollRef,contentRef,actions: { copyText, selectText },diff --git a/apps/desktop/src/features/chat/transcript/menu-items.tsx b/apps/desktop/src/features/chat/transcript/menu-items.tsxindex 03c6e4ccb..122920cf2 100644--- a/apps/desktop/src/features/chat/transcript/menu-items.tsx+++ b/apps/desktop/src/features/chat/transcript/menu-items.tsx@@ -186,15 +186,17 @@ export function assistantTurnMenuItems({*/export function conversationMenuItems({t,- conversation,+ canCopy,+ onCopyConversation,scrollRef,contentRef,actions,onReturnToLatest,}: {t: TFunction;- /** Labelled dialogue text; empty means nothing worth copying. */- conversation: string;+ /** The loaded window or older/newer history contains dialogue to copy. */+ canCopy: boolean;+ onCopyConversation: () => void;scrollRef: { current: HTMLElement | null };contentRef: { current: HTMLElement | null };actions: MenuItemActions;@@ -206,9 +208,9 @@ export function conversationMenuItems({id: "copy-conversation",label: t("chat.copyConversation"),icon: copyIcon(),- disabled: !conversation,+ disabled: !canCopy,// The labelled thread is the action; a live selection belongs to Copy on a turn.- onSelect: () => actions.copyText(conversation),+ onSelect: () => onCopyConversation(),},{id: "select-conversation",diff --git a/apps/desktop/test/chat-context-menu-items.test.mjs b/apps/desktop/test/chat-context-menu-items.test.mjsindex a9e0c199c..bf7267418 100644--- a/apps/desktop/test/chat-context-menu-items.test.mjs+++ b/apps/desktop/test/chat-context-menu-items.test.mjs@@ -133,7 +133,8 @@ test("a streaming assistant turn without a settled answer offers no items", () =test("the conversation menu copies the thread and keeps scroll actions", () => {const items = conversationMenuItems({t,- conversation: "You:\nHi",+ canCopy: true,+ onCopyConversation: noop,scrollRef: { current: null },contentRef: { current: null },actions,@@ -151,7 +152,8 @@ test("the conversation menu copies the thread and keeps scroll actions", () => {test("an empty conversation disables copy instead of writing a blank clipboard", () => {const items = conversationMenuItems({t,- conversation: "",+ canCopy: false,+ onCopyConversation: noop,scrollRef: { current: null },contentRef: { current: null },actions,@@ -190,7 +192,8 @@ test("copy conversation ignores a live selection", () => {};const items = conversationMenuItems({t,- conversation: "You:\nHi",+ canCopy: true,+ onCopyConversation: () => copyActions.copyText("You:\nHi"),scrollRef: { current: null },contentRef: { current: null },actions: copyActions,diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex dcbb67c58..e9a024f80 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1720,7 +1720,10 @@ Single message render — either user (plaintext) or assistant (markdown streaminothing. Copy on a speaking-turn menu writes the live selection in thatturn captured when the menu opened; a collapsed caret, or a selectionoutside the row, falls back to the whole turn.- Copy conversation still writes the labelled thread. Copying from the+ Copy conversation reads the complete session on demand, including unloaded+ history and untruncated message text, and preserves the visible in-flight+ tail. It does not change the reading window or scroll position. A failed+ read reports an error without copying partial history. Copying from themenu reports through the toast host because the surface closes as soonas the item runs.Fork creates and activates an independent session whose snapshot ends at thediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 97391bece..add8396df 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3554,6 +3554,14 @@ identify the platform validation still needed.`chat-context-menu-items.test.mjs`, `chat-context-menu-surface.test.mjs`);full UI scenario Draft+- **Full-history regression**: Open a 140-message session without scrolling+ back and choose Copy conversation. The clipboard must contain messages+ 1–140, not only the loaded tail. Repeat from a search context window and+ with a truncated long message. Preserve visible in-flight text; a failed+ history read must report an error and leave the clipboard unchanged.+ Copy must not load history until selected or change the reading position.+ Run `node scripts/e2e-copy-conversation.mjs`.+#### E2E-060b: Neutral gray accent across chrome- **Preconditions**: App running in dark and light themes; plugins page and adiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex dd447e675..c7adbf303 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1232,7 +1232,7 @@ row 而不是在转录本中添加树镶边。Retry/Regenerate 启动,root 用户轮流保留在实时记录中tail 不得将该寻呼机从用户气泡中移动或分离。寻呼机是消息操作工具栏的一部分:默认隐藏,并与复制一起在行悬停或键盘聚焦时显示。- 右键用户消息或助手回合会打开与悬停操作相同的词汇(复制、选中文本,以及该行自己的编辑 / 删除 / 重新生成 / 分叉 / 版本项),作为文档级、指针锚定的菜单。右键空白记录、系统行、权限卡或结果卡会打开对话菜单:复制整个对话、选中对话文本、滚动到顶部、跳到最新。引用、批注、打开侧边聊天仍按 ADR 0268 退役。流式或空助手回合若没有可提供的项则不打开菜单。说话回合上的「复制」写入打开菜单时该行内的选中文本;光标折叠或选区在行外时退回整段。复制整个对话仍写入带说话人标签的整段对话。菜单项的复制结果走 toast,因为表面在项执行时就会关闭。+ 右键用户消息或助手回合会打开与悬停操作相同的词汇(复制、选中文本,以及该行自己的编辑 / 删除 / 重新生成 / 分叉 / 版本项),作为文档级、指针锚定的菜单。右键空白记录、系统行、权限卡或结果卡会打开对话菜单:复制整个对话、选中对话文本、滚动到顶部、跳到最新。引用、批注、打开侧边聊天仍按 ADR 0268 退役。流式或空助手回合若没有可提供的项则不打开菜单。说话回合上的「复制」写入打开菜单时该行内的选中文本;光标折叠或选区在行外时退回整段。复制整个对话按需读取完整会话,包含尚未加载的历史和未截断的消息文本,并保留当前可见的生成中回复,输出仍带说话人标签。复制不改变阅读窗口或滚动位置;读取失败时提示错误,不复制残缺历史。菜单项的复制结果走 toast,因为表面在项执行时就会关闭。Fork 创建并激活一个独立的会话,其快照结束于选择辅助响应,需要一个空闲源,然后留下源的转录本、实时运行时和提供程序缓存状态保持不变 (D134)。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 5ef8346c6..10013465d 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -2225,6 +2225,8 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的`chat-context-menu-items.test.mjs`、`chat-context-menu-surface.test.mjs`);完整 UI 场景草稿+- **完整历史回归**:打开包含 140 条消息的会话,不向上翻页,选择复制整个对话;剪贴板必须包含第 1–140 条消息。从搜索上下文窗口和长消息截断预览重复验证。保留当前可见的生成中文字;读取失败时提示错误,剪贴板保持不变。仅在选择复制后读取完整历史,不改变阅读位置。运行 `node scripts/e2e-copy-conversation.mjs`。+#### E2E-060b:镀铬中性灰色调- **先决条件**:应用程序在深色和浅色主题中运行;插件页面和diff --git a/scripts/e2e-copy-conversation.mjs b/scripts/e2e-copy-conversation.mjsnew file mode 100644index 000000000..4ac15958f--- /dev/null+++ b/scripts/e2e-copy-conversation.mjs@@ -0,0 +1,38 @@+#!/usr/bin/env node+// Real Chromium selection and production message components; no host or provider.+import { spawnSync } from "node:child_process";+import { createRequire } from "node:module";+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const desktop = join(root, "apps/desktop");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const cache = join(root, ".cache/copy-conversation");+await mkdir(cache, { recursive: true });+const temp = await mkdtemp(join(cache, "run-"));+await require("esbuild").build({+ entryPoints: [join(root, "scripts/e2e/copy-conversation.tsx")],+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "iife",+ loader: { ".css": "empty" }, jsx: "automatic", define: { "process.env.NODE_ENV": '"production"' },+ alias: { react: join(desktop, "node_modules/react"), "react-dom": join(desktop, "node_modules/react-dom") },+ nodePaths: [join(desktop, "node_modules")],+});+await writeFile(join(temp, "index.html"), '<!doctype html><html><body><script src="renderer.js"></script></body></html>');+await writeFile(join(temp, "main.cjs"), `+const {app,BrowserWindow}=require('electron');+app.setPath('userData',require('node:path').join(__dirname,'profile'));+app.disableHardwareAcceleration();+app.whenReady().then(async()=>{+ try {+ const win=new BrowserWindow({show:false,webPreferences:{backgroundThrottling:false,sandbox:true,contextIsolation:true}});+ await win.loadFile(require('node:path').join(__dirname,'index.html'));+ console.log(await win.webContents.executeJavaScript('globalThis.copyConversationProbe()'));+ app.exit(0);+ } catch(error) { console.error(error); app.exit(1); }+});`);+const result = spawnSync(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { stdio: "inherit", timeout: 30000 });+if (result.error) throw result.error;+process.exitCode = result.status ?? 1;diff --git a/scripts/e2e/copy-conversation.tsx b/scripts/e2e/copy-conversation.tsxnew file mode 100644index 000000000..545d0f07a--- /dev/null+++ b/scripts/e2e/copy-conversation.tsx@@ -0,0 +1,89 @@+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "../../packages/i18n/src/index";+import { ChatTranscript } from "../../apps/desktop/src/features/chat/transcript/ChatTranscript";+import { api } from "../../apps/desktop/src/lib/api";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import type { UiMessage } from "../../packages/shared/src/index";++const check = (ok: boolean, label: string) => { if (!ok) throw new Error(label); };+const settle = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));+const find = <T extends HTMLElement>(selector: string) => {+ const node = document.querySelector<T>(selector);+ if (!node) throw new Error(`Missing ${selector}`);+ return node;+};++Object.assign(globalThis, { copyConversationProbe: async () => {+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ const messages: UiMessage[] = Array.from({ length: 140 }, (_, index) => ({+ id: `m${index}`, role: index % 2 ? "assistant" : "user",+ content: `HISTORY-${String(index + 1).padStart(3, "0")}`,+ createdAt: new Date(1700000000000 + index * 1000).toISOString(), status: "complete",+ }));+ let copied: string[] = [];+ let requested: string[] = [];+ let failRead = false;+ // Only the persistence/clipboard boundaries are replaced; the menu and transcript are real.+ api.getSession = async (id, options) => {+ check(options === undefined, "Copy still requests a bounded history page");+ requested.push(id);+ if (failRead) throw new Error("Read unavailable");+ return { session: { id, title: "History", mode: "agent", createdAt: messages[0].createdAt,+ updatedAt: messages.at(-1)!.createdAt, messageCount: messages.length,+ thinkingLevel: "off", permissionMode: "inherit", messages } };+ };+ Object.defineProperty(navigator, "clipboard", { value: { writeText: async (text: string) => { copied.push(text); } } });+ const container = document.createElement("div");+ container.style.cssText = "width:900px;height:600px";+ document.body.append(container);+ const root = createRoot(container);+ const render = async (visible: UiMessage[], more: boolean, reading = false) => {+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><ChatTranscript+ sessionId="history" messages={visible} hasMoreBefore={more} hasMoreAfter={reading}+ readingWindow={reading} isRunning={false} paneVisible={true}+ /></I18nextProvider>));+ await settle();+ };+ const copy = async () => {+ flushSync(() => find(".thread-scroll").dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 10, clientY: 10 })));+ await settle();+ const button = find<HTMLButtonElement>('[data-context-menu-item="copy-conversation"]');+ check(!button.disabled, "Copy disabled despite older conversation history");+ flushSync(() => button.click());+ await settle();+ };+ const assertComplete = () => {+ const ids = copied.at(-1)?.match(/HISTORY-\d{3}/g) ?? [];+ check(ids.length === 140 && ids[0] === "HISTORY-001" && ids.at(-1) === "HISTORY-140",+ `Copy returned ${ids.length} messages, starting with ${ids[0]}`);+ };+ await render(messages.slice(-100), true);+ check(requested.length === 0, "Opening a transcript eagerly loads full history");+ await copy(); assertComplete();+ check(requested[0] === "history", "Copy read another session");+ await render(messages.slice(50, 60), true, true);+ await copy(); assertComplete();+ await render([{ ...messages[139], role: "tool", content: "tool output" }], true);+ await copy(); assertComplete();+ // A bounded UI text preview must not replace the complete stored text.+ const fullText = messages[139].content + " full stored text";+ messages[139] = { ...messages[139], content: fullText };+ await render([{ ...messages[139], content: "truncated preview" }], false);+ await copy();+ check(copied.at(-1)!.includes(fullText), "Copy used truncated preview text");+ // Preserve a visible streaming tail that has not reached persistence yet.+ await render([...messages.slice(-2), { id: "live", role: "assistant", content: "LIVE TAIL", status: "streaming", createdAt: "2030-01-01T00:00:00Z" }], true);+ await copy();+ check(copied.at(-1)!.endsWith("LIVE TAIL"), "Copy lost the visible in-flight tail");+ const beforeFailure = copied.length;+ failRead = true;+ await copy();+ check(copied.length === beforeFailure, "A failed read wrote partial history to the clipboard");+ check(useAppStore.getState().toasts.some(toast => toast.variant === "error"), "A failed read gave no error feedback");+ root.unmount();+ return "PASS: full history, search window, tool-only page, full text, live tail and read failure";+} });