Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(composer): preserve newer drafts after command completion

yuxino559c01b4d11e
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
index 39069fd6b..46e046541 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
@@ -23,6 +23,7 @@ import {
draftOwnerSessionId,
flushScheduledHomeDraftAdopt,
pruneComposerDrafts,
+ snapshotComposerDraft,
readComposerDraft,
writeComposerDraft,
} from "../../../../lib/composer-draft-cache";
@@ -80,7 +81,7 @@ export type ComposerDraftController = {
) => void;
snapshotReferences: (sourceSessionId: string) => ComposerDraftSnapshot["fileReferences"];
draftSnapshot: (text: string) => ComposerDraftSnapshot;
- clearDraftForKey: (key: string) => void;
+ clearDraftForKey: (key: string, submitted?: ComposerDraftSnapshot) => void;
restoreDraftForKey: (key: string, snapshot: ComposerDraftSnapshot) => void;
};
@@ -572,10 +573,25 @@ export function useComposerDraft({
...(token ? { token } : {}),
}));
- const clearDraftForKey = (key: string) => {
+ const clearDraftForKey = (key: string, submitted?: ComposerDraftSnapshot) => {
+ const currentKey = draftKeyForSession(useAppStore.getState().activeSessionId);
+ // Command completion owns only its submitted draft, including when the
+ // user has left this session and its newer draft now lives in the cache.
+ if (submitted) {
+ const current = currentKey === key && ref.current
+ ? snapshotComposerDraft(readLiveDraft(), fileReferencesRef.current, key)
+ : readComposerDraft(key);
+ if (!current || current.text.trim() !== submitted.text ||
+ current.fileReferences.length !== submitted.fileReferences.length ||
+ current.fileReferences.some((reference, index) => {
+ const expected = submitted.fileReferences[index];
+ return reference.path !== expected.path || reference.name !== expected.name ||
+ reference.kind !== expected.kind || reference.mimeType !== expected.mimeType ||
+ reference.token !== expected.token;
+ })) return;
+ }
invalidatePromptEnhancement();
deleteComposerDraft(key);
- const currentKey = draftKeyForSession(useAppStore.getState().activeSessionId);
if (currentKey !== key) return;
deletedReferencesRef.current.clear();
valueRef.current = "";
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
index ab33c78a4..7fd58ebde 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts
@@ -207,6 +207,7 @@ export function useComposerSubmit({
}
invalidatePromptEnhancement();
const submittedDraftKey = draftKey;
+ const submittedDraft = draft.draftSnapshot(text);
// Slash dispatch stays local for builtin and extension commands, while
// templates, skills, and unknown aliases continue as normal prompt text. A
// command source that cannot be read is a third case: the composer cannot
@@ -247,7 +248,7 @@ export function useComposerSubmit({
),
draft.draftSnapshot(visibleCommandBody),
);
- if (accepted) draft.clearDraftForKey(submittedDraftKey);
+ if (accepted) draft.clearDraftForKey(submittedDraftKey, submittedDraft);
} catch (error) {
showToast(error instanceof Error ? error.message : String(error), {
variant: "error",
@@ -258,7 +259,7 @@ export function useComposerSubmit({
if (command.kind === "extension") {
try {
await runExtensionCommand(command.name, commandBody);
- draft.clearDraftForKey(submittedDraftKey);
+ draft.clearDraftForKey(submittedDraftKey, submittedDraft);
} catch (error) {
showToast(error instanceof Error ? error.message : String(error), {
variant: "error",
@@ -270,7 +271,7 @@ export function useComposerSubmit({
try {
if (command.kind === "builtin") await runPaletteCommand(command.id);
else await api.executeCommand(command.id);
- draft.clearDraftForKey(submittedDraftKey);
+ draft.clearDraftForKey(submittedDraftKey, submittedDraft);
} catch (error) {
showToast(error instanceof Error ? error.message : String(error), {
variant: "error",
@@ -284,8 +285,7 @@ export function useComposerSubmit({
showToast(t("errors.MODEL_NOT_CONFIGURED"), { variant: "error" });
return;
}
- const submittedDraft = draft.draftSnapshot(text);
- draft.clearDraftForKey(submittedDraftKey);
+ draft.clearDraftForKey(submittedDraftKey, submittedDraft);
const accepted = steering
? await steerPrompt(inlineContent, submittedDraft)
: await sendPrompt(inlineContent, submittedDraft);
diff --git a/apps/desktop/test/composer-draft-cache.test.mjs b/apps/desktop/test/composer-draft-cache.test.mjs
index 193905202..1ad9d1eba 100644
--- a/apps/desktop/test/composer-draft-cache.test.mjs
+++ b/apps/desktop/test/composer-draft-cache.test.mjs
@@ -146,10 +146,10 @@ test("composer hydrates from the shared cache and persists across unmount and hi
test("composer handles home drafts, deleted sessions, and async sends by key", () => {
assert.match(composer, /pruneComposerDrafts\(\[/);
assert.match(composer, /HOME_DRAFT_KEY,/);
- assert.match(composer, /const clearDraftForKey = \(key: string\)/);
+ assert.match(composer, /const clearDraftForKey = \(key: string, submitted\?: ComposerDraftSnapshot\)/);
assert.match(composer, /deleteComposerDraft\(key\)/);
assert.match(composer, /draftKeyForSession\(useAppStore\.getState\(\)\.activeSessionId\)/);
assert.match(composer, /const submittedDraftKey = draftKey/);
- assert.match(composer, /clearDraftForKey\(submittedDraftKey\)/);
+ assert.match(composer, /clearDraftForKey\(submittedDraftKey, submittedDraft\)/);
assert.doesNotMatch(composer, /if \(accepted\) clearDraft\(\);/);
});
diff --git a/apps/desktop/test/composer-send-state.test.mjs b/apps/desktop/test/composer-send-state.test.mjs
index 728b9d150..037447970 100644
--- a/apps/desktop/test/composer-send-state.test.mjs
+++ b/apps/desktop/test/composer-send-state.test.mjs
@@ -248,10 +248,10 @@ test("send clears the composer before the round trip and restores a rejected dra
/if \(!steering && !modelReady\) \{\s*showToast\(t\("errors\.MODEL_NOT_CONFIGURED"\), \{ variant: "error" \}\);\s*return;\s*\}/,
);
// Optimistic clear, restore on rejection. The clear must precede the await.
- const clearAt = submit.indexOf("draft.clearDraftForKey(submittedDraftKey);\n const accepted = steering");
+ const clearAt = submit.indexOf("draft.clearDraftForKey(submittedDraftKey, submittedDraft);\n const accepted = steering");
assert.ok(clearAt > 0, "draft must be cleared before awaiting sendPrompt");
assert.match(submit, /if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/);
- assert.doesNotMatch(submit, /if \(accepted\) draft\.clearDraftForKey\(submittedDraftKey\);\s*\};/);
+ assert.doesNotMatch(submit, /if \(accepted\) draft\.clearDraftForKey\(submittedDraftKey, submittedDraft\);\s*\};/);
const restore = draftHook.match(
/const restoreDraftForKey = \(key: string, snapshot: ComposerDraftSnapshot\) => \{[\s\S]*?\n \};/,
)?.[0] ?? "";
@@ -273,7 +273,7 @@ test("mode slash prefixes send the trailing prompt and retain failed drafts", ()
assert.match(submit, /const isModeCommand =/);
assert.match(
submit,
- /if \(isModeCommand && commandBody\)[\s\S]*?await runPaletteCommand\(command\.id\);[\s\S]*?const accepted = await sendPrompt\([\s\S]*?draft\.draftSnapshot\(visibleCommandBody\)[\s\S]*?if \(accepted\) draft\.clearDraftForKey\(submittedDraftKey\);/,
+ /if \(isModeCommand && commandBody\)[\s\S]*?await runPaletteCommand\(command\.id\);[\s\S]*?const accepted = await sendPrompt\([\s\S]*?draft\.draftSnapshot\(visibleCommandBody\)[\s\S]*?if \(accepted\) draft\.clearDraftForKey\(submittedDraftKey, submittedDraft\);/,
);
assert.match(
submit,
@@ -281,7 +281,7 @@ test("mode slash prefixes send the trailing prompt and retain failed drafts", ()
);
assert.match(
submit,
- /const submittedDraft = draft\.draftSnapshot\(text\);\s*draft\.clearDraftForKey\(submittedDraftKey\);\s*const accepted = steering[\s\S]*?await steerPrompt\(inlineContent, submittedDraft\)[\s\S]*?await sendPrompt\(inlineContent, submittedDraft\);\s*if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/,
+ /const submittedDraft = draft\.draftSnapshot\(text\);[\s\S]*?draft\.clearDraftForKey\(submittedDraftKey, submittedDraft\);\s*const accepted = steering[\s\S]*?await steerPrompt\(inlineContent, submittedDraft\)[\s\S]*?await sendPrompt\(inlineContent, submittedDraft\);\s*if \(!accepted\) draft\.restoreDraftForKey\(submittedDraftKey, submittedDraft\);/,
);
assert.match(store, /draft\?: ComposerDraftSnapshot/);
const sendPrompt = queueSlice.slice(
diff --git a/docs/spec/04-ux/04-builtin-commands.md b/docs/spec/04-ux/04-builtin-commands.md
index cb49a86ab..43f4b52c3 100644
--- a/docs/spec/04-ux/04-builtin-commands.md
+++ b/docs/spec/04-ux/04-builtin-commands.md
@@ -98,6 +98,11 @@ the composer draft. Former builtin aliases are no longer resolved and are
handled as ordinary unknown slash text unless supplied by another command
source.
+When a command completes, it clears only the draft submitted with that command.
+Text or attachments edited while it runs remain available, including when the
+user switches sessions before completion. An unchanged command draft still
+clears on success; failed dispatch preserves the draft.
+
## 8. Composer skill entries
Active built-in, plugin, and user-owned Skills also surface in the composer `/`
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index e8603bab2..59f18155f 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -1387,6 +1387,19 @@ identify the platform validation still needed.
coverage in `scripts/e2e/composer-paste.tsx` (`pnpm test:e2e:composer-paste`);
full UI scenario Draft
+#### E2E-011c-1: Preserve newer drafts after command completion
+
+- **Steps**: In session A, submit `/compact` and hold the local model response.
+ Replace the command text with a new draft, then release the response. Repeat
+ with an image added to the unchanged command text, and with navigation to B
+ before completion. Finally run the command without editing its draft.
+- **Expected**: Completion preserves the newer text and image attachments in A;
+ B's draft is untouched. Returning to A restores its newer draft. An unchanged
+ submitted command draft clears after success.
+- **Coverage**: `scripts/e2e/composer-submission.tsx`, executed by
+ `pnpm test:e2e:composer-paste`; real desktop recording uses isolated data and
+ a local model with a controlled response delay.
+
#### E2E-011d: New task creates an immediate durable empty slot
- **Preconditions**: Provider configured; at least one real session exists so
diff --git a/docs/zh-CN/spec/04-ux/04-builtin-commands.md b/docs/zh-CN/spec/04-ux/04-builtin-commands.md
index 0726076f1..9bd8c0059 100644
--- a/docs/zh-CN/spec/04-ux/04-builtin-commands.md
+++ b/docs/zh-CN/spec/04-ux/04-builtin-commands.md
@@ -83,6 +83,9 @@ type CommandExecutionResult =
只执行本地切换。提示正文仍是可见的用户回合;dispatch 失败不会清除输入框草稿。
旧的内置别名不再解析,除非由其他命令来源提供,否则会作为普通未知斜杠文本处理。
+命令完成时,只清除该命令提交时的草稿。执行期间新写的文字或新改的附件必须保留,
+即使用户在完成前切换了会话。未发生变化的命令草稿仍在成功后清空;执行失败时保留草稿。
+
## 8. 输入框中的 Skill 项
当前激活的内置、插件和用户 Skill 也会显示在输入框的 `/` 菜单中。它们使用精确的
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.md
index ac4a34adc..aef460368 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
@@ -645,6 +645,17 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备
- **状态**:覆盖源级回归(`app-store-sidebar.test.mjs`);
完整的 UI 场景草稿
+#### E2E-011c-1:命令完成后保留新草稿
+
+- **步骤**:在会话 A 发送 `/compact`,暂缓本地模型响应。将命令文字替换为新草稿,
+ 然后释放响应。分别重复测试:在未修改的命令文字旁添加图片、在完成前切换至 B,
+ 以及执行期间不修改草稿。
+- **预期**:命令完成后,A 的新文字与图片附件仍然保留;B 的草稿不受影响。返回 A
+ 仍可看到新草稿。没有变化的命令草稿在成功后正常清空。
+- **覆盖**:`scripts/e2e/composer-submission.tsx`,由
+ `pnpm test:e2e:composer-paste` 执行;真实桌面录屏使用隔离数据,以及响应时间受控的
+ 本地模型。
+
### 对话顶部栏
#### E2E-087:对话顶部栏在聊天路径上呈现
diff --git a/scripts/e2e/composer-submission.tsx b/scripts/e2e/composer-submission.tsx
index 8aabc8275..ab7822b6f 100644
--- a/scripts/e2e/composer-submission.tsx
+++ b/scripts/e2e/composer-submission.tsx
@@ -111,6 +111,60 @@ export async function verifyComposerSubmission(imagePath: string, i18n: i18n) {
api.composerCommands = originalComposerCommands;
useAppStore.setState({ showToast: originalShowToast });
}
+ // A local command can finish after the user has started their next draft.
+ // Keep the real command dispatcher/store; delay only the compact API edge.
+ const originalCompact = api.compact;
+ const originalCommands = api.composerCommands;
+ api.composerCommands = async () => ({ commands: [{
+ id: "builtin.agent.compact", name: "compact", title: "Compact", kind: "builtin",
+ }] });
+ try {
+ for (const change of ["text", "attachment", "switch", "unchanged"] as const) {
+ let finish!: () => void;
+ let started!: () => void;
+ const entered = new Promise<void>((resolve) => { started = resolve; });
+ api.compact = async () => {
+ started();
+ await new Promise<void>((resolve) => { finish = resolve; });
+ return { accepted: true };
+ };
+ flushSync(() => useAppStore.setState({ activeSessionId: sessionId, isRunning: false }));
+ prefill("/compact", []);
+ await painted();
+ sendButton().click();
+ await entered;
+ await painted();
+ if (change === "attachment") {
+ prefill("/compact", [attachment]);
+ } else if (change !== "unchanged") {
+ editor().textContent = "Next message written during compaction";
+ flushSync(() => editor().dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" })));
+ }
+ await painted();
+ if (change === "switch") {
+ flushSync(() => useAppStore.setState({ activeSessionId: "other-draft-session" }));
+ await painted();
+ editor().textContent = "Destination draft";
+ flushSync(() => editor().dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText" })));
+ }
+ finish();
+ await painted();
+ await painted();
+ if (change === "switch") {
+ assert(editor().textContent === "Destination draft", "command completion must not clear the destination draft");
+ flushSync(() => useAppStore.setState({ activeSessionId: sessionId }));
+ await painted();
+ }
+ assert(editor().textContent === (change === "unchanged" ? "" : change === "attachment" ? "/compact" : "Next message written during compaction"),
+ `completed command must preserve a newer ${change} draft: ${JSON.stringify(editor().textContent)}`);
+ if (change === "attachment") assert(host.querySelectorAll(".composer-image-attachment").length === 1,
+ "completed command must preserve an image added while it was running");
+ }
+ } finally {
+ api.compact = originalCompact;
+ api.composerCommands = originalCommands;
+ deleteComposerDraft("other-draft-session");
+ }
} finally {
flushSync(() => root.unmount());
host.remove();