Skip to content

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

fix(composer): keep the turn running when Stop fails

vastsafd88dccf8f50
diff --git a/apps/desktop/src/features/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index f8e474dfb..18df5716d 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -951,7 +951,9 @@ export function useAppShellRuntime() {
break;
}
case "abort":
- void abort();
+ void abort().catch((error) => {
+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });
+ });
break;
case "toggleWindow":
// The same native action the menu item runs (D438): hide the window
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index 00a63dc04..321207955 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -250,7 +250,9 @@ export function ComposerToolbar({
tooltip={t("chat.stopGenerating")}
ariaLabel={t("chat.stopGenerating")}
disabled={!stopAllowed}
- onClick={() => void abort()}
+ onClick={() => void abort().catch((error) => {
+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });
+ })}
>
<IconStop size={14} />
</TooltipButton>
diff --git a/apps/desktop/src/stores/slices/transcript-slice.ts b/apps/desktop/src/stores/slices/transcript-slice.ts
index 1a320c729..9075d343b 100644
--- a/apps/desktop/src/stores/slices/transcript-slice.ts
+++ b/apps/desktop/src/stores/slices/transcript-slice.ts
@@ -8,6 +8,7 @@ import { api } from "../../lib/api";
import { resolveComposerSmartStop } from "../../lib/composer-smart-stop";
import {
clearSessionPermissions,
+ removePermission,
sessionPermissions,
} from "../../lib/pending-permissions";
import {
@@ -507,16 +508,18 @@ export function createTranscriptSlice({
.slice(submittedDraft?.messageCountBeforeSend ?? 0)
.findLast((message) => message.role === "user")?.steering;
const stoppedAtMs = Date.now();
+ let createdAbortResolution: Promise<boolean> | undefined;
if (submittedDraft && !submittedDraft.abortResolution) {
- submittedDraft.abortResolution = new Promise<boolean>((resolve) => {
+ createdAbortResolution = new Promise<boolean>((resolve) => {
submittedDraft.resolveAbort = resolve;
});
+ submittedDraft.abortResolution = createdAbortResolution;
}
const pendingForSession = sessionPermissions(
stateBeforeAbort.pendingPermissions,
sessionId,
);
- await Promise.allSettled([
+ const [abortResult, ...denials] = await Promise.allSettled([
api.abort(sessionId),
...pendingForSession.map((permission) =>
api.resolvePermission({
@@ -525,6 +528,33 @@ export function createTranscriptSlice({
}),
),
]);
+ if (abortResult.status === "rejected") {
+ // The turn is still running: keep its rows, running state and the
+ // submitted draft so Stop can be retried. Only a waiter this call
+ // created is released, so a submission awaiting it does not hang.
+ if (createdAbortResolution && submittedDraft?.abortResolution === createdAbortResolution) {
+ submittedDraft.resolveAbort?.(false);
+ delete submittedDraft.abortResolution;
+ delete submittedDraft.resolveAbort;
+ }
+ // A denial the Host accepted (or a request it no longer holds) is
+ // settled even though the abort failed; its card must not linger.
+ const settled = pendingForSession.filter((_, index) => {
+ const denial = denials[index];
+ return denial?.status === "fulfilled" ||
+ (denial?.reason as { code?: unknown } | undefined)?.code === "NOT_FOUND";
+ });
+ if (settled.length) {
+ set((current) => ({
+ pendingPermissions: settled.reduce(
+ (permissions, permission) =>
+ removePermission(permissions, sessionId, permission.requestId),
+ current.pendingPermissions,
+ ),
+ }));
+ }
+ throw abortResult.reason;
+ }
set((current) => ({
pendingPermissions: clearSessionPermissions(
current.pendingPermissions,
diff --git a/apps/desktop/test/composer-send-state.test.mjs b/apps/desktop/test/composer-send-state.test.mjs
index 54222c237..b15c463d3 100644
--- a/apps/desktop/test/composer-send-state.test.mjs
+++ b/apps/desktop/test/composer-send-state.test.mjs
@@ -67,7 +67,7 @@ test("composer send/stop button follows draft content and the visible session's
assert.match(composer, /const runActive = isRunning \|\| executionActive;/);
assert.match(composer, /const isRunning = useAppStore\(\(s\) => s\.isRunning\);/);
assert.match(submitSlot, /stopGenerating/);
- assert.match(submitSlot, /onClick=\{\(\) => void abort\(\)\}/);
+ assert.match(submitSlot, /onClick=\{\(\) => void abort\(\)\.catch/);
assert.doesNotMatch(composerRight, /\{runActive \? \(/);
const modelIndex = composerRight.indexOf("<ComposerModelPicker");
const transformIndex = composerRight.indexOf("composerTransforms.map");
diff --git a/apps/desktop/test/composer-stop-rejection.test.mjs b/apps/desktop/test/composer-stop-rejection.test.mjs
new file mode 100644
index 000000000..18305a111
--- /dev/null
+++ b/apps/desktop/test/composer-stop-rejection.test.mjs
@@ -0,0 +1,97 @@
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createTranscriptSlice } = await import("../src/stores/slices/transcript-slice.ts");
+const { createSessionRuntime } = await import("../src/stores/runtime/session-runtime.ts");
+const { api } = await import("../src/lib/api.ts");
+
+// Based on the reproduction in #2234 by yg2224.
+
+function fixture(overrides = {}) {
+ let state = {
+ activeSessionId: "session",
+ sessions: [{ id: "session", source: "desktop" }],
+ messages: [],
+ isRunning: true,
+ runningSessions: { session: true },
+ retainedTranscripts: {},
+ pendingPermissions: {},
+ sessionHistory: {},
+ ...overrides,
+ };
+ const access = {
+ get: () => state,
+ set: patch => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },
+ };
+ const runtime = createSessionRuntime(access);
+ const slice = createTranscriptSlice({ ...access, runtime, flushPendingSessionConfiguration: async () => {} });
+ return { runtime, slice, state: () => state };
+}
+
+test("a failed Stop keeps the turn running and its submitted draft for retry", async t => {
+ const rows = [
+ { id: "prompt", role: "user", content: "work" },
+ { id: "answer", role: "assistant", content: "partial", status: "streaming" },
+ ];
+ const f = fixture({ messages: rows });
+ const submitted = { messageCountBeforeSend: 0, draft: { text: "work", fileReferences: [] } };
+ f.runtime.submittedComposerDrafts.set("session", submitted);
+ t.mock.method(api, "abort", async () => { throw new Error("host disconnected"); });
+ await assert.rejects(f.slice.abort(), /host disconnected/);
+ assert.equal(f.state().isRunning, true);
+ assert.equal(f.state().runningSessions.session, true);
+ assert.equal(f.state().messages, rows);
+ assert.equal(f.runtime.submittedComposerDrafts.get("session"), submitted);
+ assert.equal(submitted.abortResolution, undefined, "a failed stop must not leave a pending abort waiter");
+
+ t.mock.method(api, "abort", async () => ({ ok: true }));
+ await f.slice.abort();
+ assert.equal(f.state().isRunning, false);
+ assert.equal(f.state().runningSessions.session, false);
+ assert.equal(f.state().messages[1].status, "aborted");
+ assert.equal(f.runtime.submittedComposerDrafts.has("session"), false);
+});
+
+test("a failed Stop releases a submission already waiting on its abort", async t => {
+ const f = fixture();
+ const submitted = { messageCountBeforeSend: 0, draft: { text: "work", fileReferences: [] } };
+ f.runtime.submittedComposerDrafts.set("session", submitted);
+ let reject;
+ t.mock.method(api, "abort", () => new Promise((_, fail) => { reject = fail; }));
+ const stopping = f.slice.abort();
+ const waiter = submitted.abortResolution;
+ assert.ok(waiter, "Stop registers an abort waiter for the submission");
+ reject(new Error("Stop rejected"));
+ await assert.rejects(stopping, /Stop rejected/);
+ assert.equal(await waiter, false);
+});
+
+test("a failed Stop does not replace a newer submitted draft", async t => {
+ const f = fixture();
+ const newer = { messageCountBeforeSend: 0, draft: { text: "new submission", fileReferences: [] } };
+ let reject;
+ t.mock.method(api, "abort", () => new Promise((_, fail) => { reject = fail; }));
+ const stopping = f.slice.abort();
+ f.runtime.submittedComposerDrafts.set("session", newer);
+ reject(new Error("Stop rejected"));
+ await assert.rejects(stopping, /Stop rejected/);
+ assert.equal(f.runtime.submittedComposerDrafts.get("session"), newer);
+ assert.equal(f.state().isRunning, true);
+});
+
+test("a failed Stop drops only the permission cards whose denial the Host settled", async t => {
+ const denied = { requestId: "denied", sessionId: "session" };
+ const gone = { requestId: "gone", sessionId: "session" };
+ const unreachable = { requestId: "unreachable", sessionId: "session" };
+ const f = fixture({ pendingPermissions: { session: [denied, gone, unreachable] } });
+ t.mock.method(api, "abort", async () => { throw new Error("Stop rejected"); });
+ t.mock.method(api, "resolvePermission", async ({ requestId }) => {
+ if (requestId === "denied") return { ok: true };
+ if (requestId === "gone") throw Object.assign(new Error("NOT_FOUND"), { code: "NOT_FOUND" });
+ throw new Error("disconnected");
+ });
+ await assert.rejects(f.slice.abort(), /Stop rejected/);
+ assert.deepEqual(f.state().pendingPermissions.session, [unreachable]);
+ assert.equal(f.state().isRunning, true);
+});
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index a5b3f8aef..516be0094 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3326,6 +3326,10 @@ reasoning-level control.
returns to the textarea and file references return as leaf-name chips; their
canonical paths never become textarea text. After a reply begins, Abort keeps
the partial transcript and restores no draft.
+ If the stop request itself fails, the turn stays running: its rows, Stop
+ control and submitted draft are unchanged, an error toast is shown, and Stop
+ can be retried. Permission cards whose denial the Host already settled are
+ removed; the rest stay pending.
- Stop never clears queued prompts. Removing a row is explicit; the queue itself
is Host-owned and durable (D386 / ADR 0213, ADR 0265), so a restart restores it
in delivery order, held until the desktop attaches as the owner.
diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.md
index 243461b8d..93b6d28a4 100644
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@ -2179,6 +2179,7 @@ MainChat 底部的输入区域,用于撰写和发送提示。支持多行输
返回到文本区域,文件引用作为叶名片返回;他们的
规范路径永远不会成为文本区域文本。回复开始后,Abort 保持
部分抄本,不恢复草稿。
+ 停止请求本身失败时,轮次保持运行:消息行、停止按钮和已提交草稿不变,显示错误提示,可再次停止。Host 已处理拒绝的权限卡片会移除,其余保持待处理。
- `turn_end` 不是空闲信号。发送和主机持久性仍然被阻止
通过后续的工具转动和阻止自动检查点生成
直到 `agent_end` 或 `error`;草稿和运行时选择器保持可编辑状态