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(chat): preserve complete text when editing long messages (#962)
Yuxino3570b70e325b
diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 8f9a9748d..d13d51b4f 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -1,6 +1,8 @@import {memo,useMemo,+ useEffect,+ useRef,useState,type MouseEvent as ReactMouseEvent,} from "react";@@ -40,6 +42,7 @@ export const MessageRow = memo(function MessageRow({const { t } = useTranslation();const openTranscriptMenu = useTranscriptMenu();const { copyText, selectText } = useChatTextActions();+ const prepareUserMessageEdit = useAppStore((s) => s.prepareUserMessageEdit);const editUserMessage = useAppStore((s) => s.editUserMessage);const activateMessageRevision = useAppStore((s) => s.activateMessageRevision);const deleteMessage = useAppStore((s) => s.deleteMessage);@@ -53,6 +56,9 @@ export const MessageRow = memo(function MessageRow({const editSeed =(editableUserMessage && message.command) || (message.content || "");const [editing, setEditing] = useState(false);+ const [loadingEdit, setLoadingEdit] = useState(false);+ const editRequest = useRef<AbortController | null>(null);+ useEffect(() => () => editRequest.current?.abort(), []);const [editValue, setEditValue] = useState(editSeed);const [retryingEdit, setRetryingEdit] = useState(false);const copyLabel = t("chat.copy");@@ -75,6 +81,34 @@ export const MessageRow = memo(function MessageRow({);return attachments.filter((attachment) => !inline.has(attachment.ref));}, [message.attachments, message.content, workspaceRoot]);+ const beginEdit = async () => {+ if (!editableUserMessage || isRunning || loadingEdit) return;+ const request = new AbortController();+ editRequest.current?.abort();+ editRequest.current = request;+ setLoadingEdit(true);+ // Subscribe synchronously: React can batch A→B→A into a single render.+ const unsubscribe = useAppStore.subscribe((state, previous) => {+ if (state.activeSessionId !== previous.activeSessionId ||+ state.selectingSessionId !== previous.selectingSessionId) request.abort();+ });+ request.signal.addEventListener("abort", () => {+ unsubscribe();+ if (editRequest.current === request) setLoadingEdit(false);+ }, { once: true });+ try {+ const full = await prepareUserMessageEdit(message.id, request.signal);+ if (!full || request.signal.aborted || editRequest.current !== request) return;+ setEditValue(full.command || full.content || "");+ setEditing(true);+ } finally {+ unsubscribe();+ if (editRequest.current === request) {+ editRequest.current = null;+ setLoadingEdit(false);+ }+ }+ };const cancelEdit = () => {setEditValue(editSeed);setEditing(false);@@ -103,16 +137,13 @@ export const MessageRow = memo(function MessageRow({selectTarget: event.currentTarget.querySelector<HTMLElement>(editing ? ".message-edit-input" : ".message-bubble",),- editable: editableUserMessage && !editing,+ editable: editableUserMessage && !editing && !loadingEdit,running: isRunning,revision: !editing && showRevisionPager? { count: revisionCount, active: activeRevision }: null,actions: { copyText, selectText },- onEdit: () => {- setEditValue(editSeed);- setEditing(true);- },+ onEdit: () => void beginEdit(),onDelete: () => void deleteMessage(message.id),onActivateRevision: (index) =>void activateMessageRevision(message.id, index),@@ -282,11 +313,8 @@ export const MessageRow = memo(function MessageRow({className="copy-btn icon"tooltip={editLabel}ariaLabel={editLabel}- disabled={isRunning}- onClick={() => {- setEditValue(editSeed);- setEditing(true);- }}+ disabled={isRunning || loadingEdit}+ onClick={() => void beginEdit()}><IconPencil size={13} /></TooltipButton>diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex 66d68c388..8cf9b4a80 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -228,6 +228,8 @@ export type AppState = {applyQueueChanged: (event: AgentQueueChangedEvent) => void;compactContext: () => Promise<void>;retryAssistantMessage: (messageId: string) => Promise<void>;+ /** Read canonical text before opening a user-message editor. */+ prepareUserMessageEdit: (messageId: string, signal?: AbortSignal) => Promise<UiMessage | null>;/** Replace a user prompt and regenerate from it. */editUserMessage: (messageId: string,diff --git a/apps/desktop/src/stores/runtime/transcript-action.ts b/apps/desktop/src/stores/runtime/transcript-action.tsindex 3a5941bbb..5ed9f478a 100644--- a/apps/desktop/src/stores/runtime/transcript-action.ts+++ b/apps/desktop/src/stores/runtime/transcript-action.ts@@ -6,10 +6,11 @@ export async function prepareTranscriptAction({ get, set }: StoreAccess,runtime: Pick<SessionRuntime, "loadFullSessionMessages" | "cacheSessionTranscript">,messageId: string,+ signal?: AbortSignal,) {const state = get();const id = state.activeSessionId;- if (!id || state.isRunning) return null;+ if (signal?.aborted || !id || state.isRunning) return null;const history = state.sessionHistory[id];if (!history?.hasMoreBefore && !history?.contentLimited &&state.messages.some((message) => message.id === messageId)) return state;@@ -19,12 +20,12 @@ export async function prepareTranscriptAction(// turn may have already appended a live tail while the read was pending.messages = await runtime.loadFullSessionMessages(id, false);} catch (error) {- if (get().activeSessionId === id)+ if (!signal?.aborted && get().activeSessionId === id)get().showToast(error instanceof Error ? error.message : String(error), { variant: "error" });return null;}const current = get();- if (!messages || current.activeSessionId !== id || current.isRunning || current.selectingSessionId ||+ if (signal?.aborted || !messages || current.activeSessionId !== id || current.isRunning || current.selectingSessionId ||current.messages !== state.messages) return null;if (!messages.some((message) => message.id === messageId)) return null;runtime.cacheSessionTranscript(id, messages, { messageStart: 0, hasMoreBefore: false });diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.tsindex b8c091744..52c26780d 100644--- a/apps/desktop/src/stores/slices/transcript-slice.ts+++ b/apps/desktop/src/stores/slices/transcript-slice.ts@@ -44,6 +44,7 @@ export function createTranscriptSlice({| "compactContext"| "retryAssistantMessage"| "editUserMessage"+ | "prepareUserMessageEdit"| "retryLastPrompt"| "clearError"| "activateMessageRevision"@@ -109,6 +110,14 @@ export function createTranscriptSlice({await get().editUserMessage(root.id, root.content, root.attachments);},+ prepareUserMessageEdit: async (messageId, signal) => {+ const prepared = await prepareTranscriptAction({ get, set }, runtime, messageId, signal);+ const state = get();+ if (!prepared || state.activeSessionId !== prepared.activeSessionId || state.isRunning) return null;+ const message = state.messages.find((candidate) => candidate.id === messageId);+ return message?.role === "user" && !message.sessionMessage ? message : null;+ },+editUserMessage: async (messageId, content, attachments) => {const prepared = await prepareTranscriptAction({ get, set }, runtime, messageId);const state = get();diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex e5dba31a1..47591babf 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1750,6 +1750,11 @@ Single message render — either user (plaintext) or assistant (markdown streamiFork creates and activates an independent session whose snapshot ends at theselected assistant response, requires an idle source, and leaves thatsource's transcript, live runtime, and provider cache state untouched (D134).+ Opening a user-message editor must hydrate canonical history before seeding the+ draft when the loaded transcript is partial or display-limited. Never seed an+ editable draft from clipped display text. Failed reads keep the editor closed+ and show an error; stale reads after navigation or a new turn cannot open it.+ Slash invocations still seed their original typed command.Edit belongs to the user turn: it swaps the prompt bubble for a focusedcomposer-radius editor filled with `--ds-tile-deep` (the same 8% mix as auser bubble) so it stays distinct from the pane without an outer shadow.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 53921df1f..627e382d5 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4745,6 +4745,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- **Milestone**: M5- **Status**: Unit-covered (`transcript-style.test.mjs`); full UI scenario Draft+- **Long-message regression**: Send a log longer than 65,536 characters as+ message text, reopen the saved chat, then Edit and resend with a short+ clarification. The editor and outgoing request must retain the final log+ lines, without a display truncation marker. A failed full-history read must+ show an error without opening a clipped editor; switching chats while the+ read is pending, including A→B→A with the same retained message array, must+ not open a stale editor or publish stale history. A fresh Edit after returning+ must still load the complete text and resend successfully. Automated coverage also+ preserves attachments and the typed slash-command seed.+#### E2E-069: Platform-specific sidebar header behavior- **Preconditions**: PI-Desktop is open with the expanded sidebar and a chatdiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 1c1a8d4aa..96ea92a2d 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1245,6 +1245,9 @@ row 而不是在转录本中添加树镶边。Fork 创建并激活一个独立的会话,其快照结束于选择辅助响应,需要一个空闲源,然后留下源的转录本、实时运行时和提供程序缓存状态保持不变 (D134)。+ 打开用户消息编辑器时,如果当前记录不完整或受显示长度限制,必须先读取完整历史,再填入草稿。+ 不得把截断的展示文本作为可编辑正文。读取失败时保持编辑器关闭并显示错误;切换会话或+ 开始新一轮后,过期读取不得打开编辑器。斜杠命令仍填入最初输入的命令。编辑属于用户回合:它将提示气泡替换为与底部输入框同族的composer 面板(`--ds-bg-composer` 填充、`--ds-composer-radius`,无描边,无阴影,D297)。文本区域嵌在面板内不加第二层底;底部 28px 工具条放本地化的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 93a6da29d..cb6d5b061 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@@ -3002,6 +3002,12 @@ PI-Desktop 图标;两个表面都不会暴露库存 Electron 名称或图标- **里程碑**:M5- **状态**:单位覆盖(`transcript-style.test.mjs`);完整的 UI 场景草稿+- **长消息回归**:将超过 65,536 字符的日志作为正文发送,重新打开已保存的聊天,+ 编辑并添加一句说明后重发。编辑框和发出的请求必须保留日志末尾,不得带入展示截断提示。+ 完整历史读取失败时显示错误,不打开截断编辑框;读取期间切换聊天(包括保留相同消息数组的+ A→B→A 切换)后不得打开过期编辑框或写入过期历史。返回后重新点击编辑仍可加载完整正文并重发。+ 自动化覆盖还验证附件和原始斜杠命令得到保留。+#### E2E-069:特定于平台的侧边栏标题行为- **先决条件**:PI-Desktop 已打开,并带有扩展的侧边栏和聊天室diff --git a/scripts/e2e/transcript-edit.tsx b/scripts/e2e/transcript-edit.tsxnew file mode 100644index 000000000..20e355678--- /dev/null+++ b/scripts/e2e/transcript-edit.tsx@@ -0,0 +1,111 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import type { UiMessage, SessionDetail } from "@pi-desktop/shared";+import { en } from "@pi-desktop/i18n";+import { MessageRow } from "../../apps/desktop/src/features/chat/transcript/MessageRow";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import { api } from "../../apps/desktop/src/lib/api";++function assert(value: unknown, message: string): asserts value {+ if (!value) throw new Error(message);+}+const painted = () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));++/** Enter from the actual Edit control; replace only the Host and prompt APIs. */+export async function transcriptEditProbe() {+ const initial = useAppStore.getState();+ const originalRead = api.getSession;+ const originalPrompt = api.prompt;+ const i18n = createInstance();+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });+ const host = document.createElement("div");+ document.body.append(host);+ const root = createRoot(host);+ const sessionId = "full-edit-fixture";+ const full: UiMessage = {+ id: "long-log", role: "user", createdAt: "2026-09-23T00:00:00Z",+ content: "INFO normal request\n".repeat(4000) + "FATAL payment timeout",+ attachments: [{ ref: "/fixture/screenshot.png", name: "screenshot.png", kind: "image", mimeType: "image/png" }],+ };+ const session: SessionDetail = {+ id: sessionId, title: "Log review", source: "pi-native", mode: "agent",+ permissionMode: "ask", thinkingLevel: "off", messageCount: 1,+ createdAt: full.createdAt, updatedAt: full.createdAt, messages: [full],+ };+ function Row() {+ const message = useAppStore((s) => s.messages[0]);+ return message ? <MessageRow message={message} isRunning={false} /> : null;+ }+ const sent: Parameters<typeof api.prompt>[0][] = [];+ const toasts: string[] = [];+ api.prompt = async (input) => { sent.push(input); return { accepted: true }; };+ try {+ for (const scenario of ["long", "slash", "read-failure", "switch", "round-trip"] as const) {+ const canonical = scenario === "slash" ? { ...full, command: "/review logs" } : full;+ let finish!: () => void;+ const readGate = new Promise<void>((resolve) => { finish = resolve; });+ api.getSession = async () => {+ await readGate;+ if (scenario === "read-failure") throw new Error("fixture read failed");+ return { session: { ...session, messages: [canonical] } };+ };+ flushSync(() => useAppStore.setState({+ activeSessionId: sessionId, selectingSessionId: null, isRunning: false,+ messages: [{ ...canonical, content: full.content.slice(0, 65500) + "[truncated for display]" }],+ sessionHistory: { [sessionId]: { messageStart: 0, hasMoreBefore: false, contentLimited: true } },+ pendingPlans: {}, showToast: (message) => { toasts.push(String(message)); },+ }));+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><Row key={scenario} /></I18nextProvider>));+ host.querySelector<HTMLButtonElement>('[aria-label="Edit and resend"]')!.click();+ await painted();+ assert(!host.querySelector(".message-edit-input"), "Edit must wait for full text instead of exposing clipped display text");+ if (scenario === "switch") flushSync(() => useAppStore.setState({ activeSessionId: "other-chat" }));+ const originalMessages = useAppStore.getState().messages;+ if (scenario === "round-trip") flushSync(() => {+ // Retained panes can return with the exact same message-array identity.+ useAppStore.setState({ activeSessionId: "other-chat" });+ useAppStore.setState({ activeSessionId: sessionId, messages: originalMessages });+ });+ finish();+ await painted();+ await painted();+ let editor = host.querySelector<HTMLTextAreaElement>(".message-edit-input");+ if (scenario === "round-trip") {+ assert(!editor, "A→B→A must invalidate the pending edit even when the message array is unchanged");+ assert(useAppStore.getState().messages === originalMessages, "cancelled edit must not publish stale history");+ host.querySelector<HTMLButtonElement>('[aria-label="Edit and resend"]')!.click();+ await painted();+ await painted();+ editor = host.querySelector<HTMLTextAreaElement>(".message-edit-input");+ }+ if (scenario === "read-failure" || scenario === "switch") {+ assert(!editor, `${scenario}: stale or failed read must not open an editor`);+ continue;+ }+ const expected = canonical.command || canonical.content;+ assert(editor?.value === expected, `${scenario}: editor must contain canonical text or the original slash invocation`);+ const revised = expected + "\nPlease focus on payment failures.";+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!;+ setter.call(editor, revised);+ flushSync(() => editor.dispatchEvent(new Event("input", { bubbles: true })));+ host.querySelector<HTMLButtonElement>(".message-edit-submit")!.click();+ await painted();+ await painted();+ const request = sent.at(-1);+ assert(request?.content === revised && request.truncateFromMessageId === full.id,+ `${scenario}: resend must preserve the complete edited content`);+ assert(request.attachments?.[0]?.path === full.attachments?.[0]?.ref,+ "editing must preserve image attachments");+ }+ assert(toasts.includes("fixture read failed"), "failed hydration must remain visible");+ return { fullTextAndResend: true, slashSeed: true, failedRead: true, sessionSwitch: true, roundTripNavigation: true };+ } finally {+ flushSync(() => root.unmount());+ host.remove();+ api.getSession = originalRead;+ api.prompt = originalPrompt;+ useAppStore.setState(initial, true);+ }+}diff --git a/scripts/e2e/transcript-render.tsx b/scripts/e2e/transcript-render.tsxindex cbbb9d886..8897987c9 100644--- a/scripts/e2e/transcript-render.tsx+++ b/scripts/e2e/transcript-render.tsx@@ -1,3 +1,4 @@+import { transcriptEditProbe } from "./transcript-edit";import { turnProcessProbe } from "./turn-process";import { transcriptStatusProbe } from "./transcript-status";import { createRoot } from "react-dom/client";@@ -230,6 +231,7 @@ globalThis.transcriptRenderProbe = async () => {taskLifecycleUpdated: true,taskTimingUpdated: true,turnProcess: await turnProcessProbe(),+ messageEditing: await transcriptEditProbe(),textUpdateDurationMs,};} finally {