Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(claude): 修复等待后台任务时插话无法送达
Dash459e12f4c551
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 667b8587df..37b6f458fa 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -9948,6 +9948,30 @@ describe('AgentInputCoordinator steer transaction', () => {}});+ // 2026-10-24 unit regression: an adapter steer rejection is not proof that+ // the product ended. Existing zombie coverage only tests a confirmed idle probe.+ it('preserves an active product when rejected steer still has a live continuation', async () => {+ const h = createHarness();+ const sid = 'steer-awaiting-background';+ const first = makeItem('q-1', 'background work');+ const second = makeItem('q-2', 'correction');+ h.coordinator.enqueue(sid, first);+ await flush();+ h.coordinator.enqueue(sid, second);+ h.steerToAgent.mockRejectedValueOnce(new Error('No active Claude turn to steer'));+ h.reconcileTurnIdle.mockReturnValueOnce(false);+ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(false);+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);+ expect(latestProjection(h.projections).pendingQueue.map((item) => item.clientId)).toEqual(['q-2']);+ // A genuine terminal, rather than the rejected steer, releases the next input.+ h.setRunning(false);+ h.coordinator.onTurnEvent(sid, 'done');+ await flush();+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);+ });+it('recovers from a zombie turn: NO_ACTIVE_TURN reconciles stale busy state and dispatches the fallback', async () => {// 场景: q-1 已派发但 turn 异常死亡 (done 事件丢失) —— coordinator 的// activeTurn 和 host busy tracker 双双 stale。修复前: 插话 → fallback →diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex 9effcde618..439e0b1ac6 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -2708,6 +2708,13 @@ export class AgentInputCoordinator {// maker-core 权威判定无活跃 turn — 先让 host 校准可能 stale 的 busy// tracker, 否则下面 fallback / drain 仍会被假忙挡住 (见 deps 注释)。this.deps.reconcileTurnIdle?.(sessionId);+ // A vendor can reject foreground steering while the product still owns+ // a background continuation. Only confirmed idle permits synthetic done.+ if (this.deps.isTurnRunning(sessionId)) {+ this.clearDirectSteeringItem(latest, item.clientId);+ this.emit(sessionId);+ return finishSteerRequest(false);+ }// 已派发的 activeTurn + 权威无活跃 turn ⇒ 那一轮其实已结束但 done// 事件丢失 (zombie turn)。合成 done 边界收掉它, 否则 fallback drain 会// 被这个尸体 activeTurn 永久挡住。pre-dispatch (send 还在飞) 的diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex b1e4c96a8c..c17c04e85b 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -7767,6 +7767,12 @@ function SessionScreenContent({ beforeSessionSwitchRef, newSessionActionRef }: Sprojection,projectionEpochAtRequestStart,);+ // The boolean ACK can also mean "kept for the next turn" on older hosts.+ // Inspect the authoritative queue rather than reporting that as delivery.+ if (remoteSessionStore.getInputProjection(sessionId).pendingQueue+ .some((entry) => entry.clientId === item.clientId)) {+ showTransientNotice(t('message.queue.steerQueued'));+ }return accepted;});};diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex ccbaf023e9..26dfccc0bf 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -234,6 +234,7 @@"cancel": "Cancel","edit": "Edit","steer": "Interject",+ "steerQueued": "Not delivered yet. Your message is still queued.","moveUp": "Move earlier","moveDown": "Move later","cancelSend": "Cancel send",diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex 47a56fd428..07105f1fcf 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -234,6 +234,7 @@"cancel": "キャンセル","edit": "編集","steer": "割り込み",+ "steerQueued": "まだ届いていません。メッセージはキューに残っています。","moveUp": "1つ前へ","moveDown": "1つ後ろへ","cancelSend": "送信をキャンセル",diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex a1934b1d04..89141bb6f5 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -234,6 +234,7 @@"cancel": "취소","edit": "편집","steer": "끼어들기",+ "steerQueued": "아직 전달되지 않았습니다. 메시지는 대기열에 남아 있습니다.","moveUp": "한 칸 앞으로","moveDown": "한 칸 뒤로","cancelSend": "전송 취소",diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 75a4895c4d..9b6d8a8449 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -234,6 +234,7 @@"cancel": "取消","edit": "编辑","steer": "插话",+ "steerQueued": "暂未送达,消息仍保留在队列中。","moveUp": "提前一位","moveDown": "延后一位","cancelSend": "取消发送",diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex 2aa6ec6c53..7cb153ae3c 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -234,6 +234,7 @@"cancel": "取消","edit": "編輯","steer": "插話",+ "steerQueued": "尚未送達,訊息仍保留在佇列中。","moveUp": "提前一位","moveDown": "延後一位","cancelSend": "取消傳送",diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex f742dbdbfb..8fb17ffbac 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -404,6 +404,11 @@ sessionRunningRetry 就停。每次因 replacement 关闭而重新入队都计不登记阻塞交互或人工续跑。回答只走原执行的 steer,结束/Stop/关闭/替换后作废,发送失败不重投新 turn。Claude 会把已排队的答案合并为下一 SDK 段:仅在答案已被接收时复用现有 continuation claim 保留产品边界,避免提前完成或重复完成;未回答不建 claim。+ Claude 前台已结束、仍等待后台任务的 continuation 也接受用户插话,送入原 SDK 输入队列;+ 已接收的补充归当前等待段,不能额外制造一个后继 claim,后台任务停止也不能丢弃补充。+ 插话被拒绝不等于产品结束,宿主必须复核实际运行态后才能合成结束边界。+ 回归见 `abort-stops-background-tasks.test.ts`、`background-steer.native.test.ts` 与 Desktop+ `agent-input-coordinator.test.ts`;原生测试使用真实 CLI 和本地模型端点,不消耗订阅额度。Pi 在原生 RPC 排队后再核对执行代次与取消信号,防止答案串到下一次执行。Claude 的本机 hook 与远端 root-only guard 禁止原生子代理直接提问;工具入口只接受宿主标明 `mcpCallerKind=root` 且 `mcpCallerAttested=true` 的请求,身份未知、diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.tsindex faaa5c8525..ebcb3c626a 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts@@ -509,6 +509,70 @@ describe('ClaudeCodeAgent abort stops background wake tasks', () => {await session.close().catch(() => undefined);});+ // 2026-10-24: Session.steer 在前台 result 后被 adapter 拒绝,手机消息永久排队。+ // unit: 现有 Stop/continuation 用例未覆盖这个输入窗口;捕获真实 adapter 输入队列,+ // 验证插话只提交一次、后台任务保留、最终只产生一个产品终态。+ it.each(['completed', 'stopped'] as const)('accepts a steer while awaiting a background task that later %s', async (status) => {+ const { agent, handle, stream, fakeQuery } = await startSessionWithStream(undefined, {+ autoCollect: false, capturePrompts: true,+ });+ const session = new Session({+ id: 'background-steer', agentKind: 'claude-code', workDir: path.join('workspace', 'repo'),+ handle, capabilities: agent.capabilities, logger: createNoopLogger(), turnStallMs: 0,+ });+ const seen: AgentEvent[] = [];+ session.onEvent((event) => seen.push(event));+ const prompt = sdkMock.query.mock.calls.at(-1)?.[0].prompt as AsyncIterable<unknown>;+ const submitted: unknown[] = [];+ const collecting = (async () => { for await (const value of prompt) submitted.push(value); })();+ try {+ await session.send('spawn background agent');+ stream.emit(taskStarted('worker', 'local_agent'));+ stream.emit(turnResult('waiting'));+ await waitFor(() => seen.some((event) => event.turnContinuationId !== undefined), 'awaiting background');+ await session.steer('reload the save without restarting');+ await waitFor(() => submitted.length === 2, 'steer accepted once');+ expect(submitted[1]).toMatchObject({ message: { content: 'reload the save without restarting' } });+ expect(handle.listBackgroundTasks?.().map((task) => task.taskId)).toEqual(['worker']);+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();+ stream.emit(taskNotification('worker', status));+ await waitFor(() => taskEvents(seen).length === 2, 'background terminal');+ expect(seen.filter(isProductTerminal)).toHaveLength(0);+ stream.emit(assistantText('using your correction'));+ stream.emit(turnResult('complete'));+ await waitFor(() => seen.filter(isProductTerminal).length === 1, 'product terminal');+ expect(session.isTurnRunning()).toBe(false);+ expect(submitted).toHaveLength(2);+ } finally {+ stream.end();+ await session.close();+ await collecting;+ }+ });++ it('does not deliver a waiting-turn steer when Stop wins during attachment conversion', async () => {+ const { handle, stream, events } = await startSessionWithStream();+ await handle.send({ type: 'user', content: 'background work' });+ stream.emit(taskStarted('worker', 'local_agent'));+ stream.emit(turnResult('waiting'));+ await waitFor(() => events.some((event) => event.turnContinuationId !== undefined), 'awaiting background');+ const resize = createDeferred<string>();+ const entered = createDeferred<void>();+ imageResizerMock.process.mockImplementationOnce(() => { entered.resolve(); return resize.promise; });+ const imagePath = path.join(os.tmpdir(), 'waiting-steer.png');+ const steer = handle.steer({ type: 'user', content: [{ type: 'image', path: imagePath }] });+ const rejected = expect(steer).rejects.toThrow('No active Claude turn to steer');+ await entered.promise;+ await handle.abort();+ resize.resolve(imagePath);+ await rejected;+ expect(events.filter(isProductTerminal)).toHaveLength(1);+ expect(handle.isTurnRunning?.()).toBe(false);+ stream.end();+ await handle.close();+ });+it('graceful stop sends only the SDK interrupt without closing or stopping background tasks', async () => {const { handle, stream, events, fakeQuery } = await startSessionWithStream();await handle.send({ type: 'user', content: 'long turn' });diff --git a/packages/maker-core/src/agents/claude-code/__tests__/background-steer.native.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/background-steer.native.test.tsnew file mode 100644index 0000000000..4c205dbf17--- /dev/null+++ b/packages/maker-core/src/agents/claude-code/__tests__/background-steer.native.test.ts@@ -0,0 +1,269 @@+/**+ * 2026-10-24 phone interruption regression, through real Session + Claude adapter + CLI.+ * Native tier (explicit CINDY_CLAUDE_TEST_BINARY): unit mocks cannot prove that the SDK+ * consumes another user input while its background Agent is still running. The model+ * endpoint is loopback and uses a fake key; the child response is explicitly released.+ */+import { mkdtemp, rm } from "node:fs/promises";+import { createServer, type ServerResponse } from "node:http";+import { tmpdir } from "node:os";+import path from "node:path";+import { describe, expect, it } from "vitest";+import { ClaudeCodeAgent } from "../index.js";+import { Session } from "../../../session.js";+import type { Logger } from "../../../interfaces/logger.js";+import type { AgentEvent } from "../../../types/events.js";++const binaryPath = process.env.CINDY_CLAUDE_TEST_BINARY;++describe.skipIf(!binaryPath)(+ "background interruption with real Claude runtime",+ () => {+ it("delivers a correction before the child completes and then settles once", async () => {+ const root = await mkdtemp(+ path.join(tmpdir(), "cindy-background-steer-native-"),+ );+ const seen: AgentEvent[] = [];+ let releaseChild: (() => void) | undefined;+ let parentRequests = 0;+ let correctionRequests = 0;+ let session: Session | undefined;+ let responseId = 0;+ const reply = (+ res: ServerResponse,+ model: string,+ content: Record<string, unknown>[],+ ) => {+ const stop = content.some((block) => block.type === "tool_use")+ ? "tool_use"+ : "end_turn";+ const events: Record<string, unknown>[] = [+ {+ type: "message_start",+ message: {+ id: `msg_${++responseId}`,+ type: "message",+ role: "assistant",+ model,+ content: [],+ stop_reason: null,+ usage: { input_tokens: 100, output_tokens: 0 },+ },+ },+ ];+ content.forEach((block, index) => {+ events.push({+ type: "content_block_start",+ index,+ content_block:+ block.type === "tool_use"+ ? { ...block, input: {} }+ : { type: "text", text: "" },+ });+ events.push({+ type: "content_block_delta",+ index,+ delta:+ block.type === "tool_use"+ ? {+ type: "input_json_delta",+ partial_json: JSON.stringify(block.input),+ }+ : { type: "text_delta", text: block.text },+ });+ events.push({ type: "content_block_stop", index });+ });+ events.push({+ type: "message_delta",+ delta: { stop_reason: stop },+ usage: { output_tokens: 10 },+ });+ events.push({ type: "message_stop" });+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.end(+ events+ .map(+ (event) =>+ `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`,+ )+ .join(""),+ );+ };+ const server = createServer(async (req, res) => {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ if (req.url?.includes("count_tokens")) {+ res.writeHead(200).end(JSON.stringify({ input_tokens: 100 }));+ return;+ }+ const body = JSON.parse(raw);+ const users = (body.messages ?? []).filter(+ (message: { role: string }) => message.role === "user",+ );+ const texts = users.flatMap(+ (message: {+ content: string | Array<{ type: string; text?: string }>;+ }) =>+ typeof message.content === "string"+ ? [message.content]+ : message.content+ .filter((block) => block.type === "text")+ .map((block) => block.text ?? ""),+ );+ if (texts.some((text: string) => text === "BACKGROUND_STEER_CHILD")) {+ releaseChild = () =>+ reply(res, body.model, [{ type: "text", text: "CHILD_DONE" }]);+ return;+ }+ if (+ texts.some((text: string) => text.includes("BACKGROUND_STEER_START"))+ ) {+ parentRequests++;+ const corrected = texts.some((text: string) =>+ text.includes("BACKGROUND_STEER_CORRECTION"),+ );+ if (corrected) correctionRequests++;+ reply(+ res,+ body.model,+ parentRequests === 1+ ? [+ {+ type: "tool_use",+ id: "tool_background_worker",+ name: "Agent",+ input: {+ description: "Controlled background worker",+ subagent_type: "general-purpose",+ prompt: "BACKGROUND_STEER_CHILD",+ run_in_background: true,+ },+ },+ ]+ : [+ {+ type: "text",+ text: corrected ? "CORRECTION_ACK" : "WAITING_FOR_CHILD",+ },+ ],+ );+ return;+ }+ reply(res, body.model, [{ type: "text", text: "OK" }]);+ });+ await new Promise<void>((resolve) =>+ server.listen(0, "127.0.0.1", resolve),+ );+ const port = (server.address() as { port: number }).port;+ const logger: Logger = {+ trace() {},+ debug() {},+ info() {},+ warn() {},+ error() {},+ fatal() {},+ child() {+ return logger;+ },+ };+ try {+ const agent = new ClaudeCodeAgent({+ binaryPath: binaryPath!,+ logger,+ runtimeConfig: { endpoint: `http://127.0.0.1:${port}` },+ auth: {+ getState: async () => ({ authenticated: true }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({+ ANTHROPIC_API_KEY: "invalid-loopback-test-key",+ CLAUDE_CONFIG_DIR: path.join(root, "config"),+ CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",+ DISABLE_TELEMETRY: "1",+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "0",+ }),+ },+ });+ const handle = await agent.startSession({+ sessionId: "native-background-steer",+ workingDir: root,+ model: "claude-sonnet-4-5-20250929",+ permissionMode: "bypassPermissions",+ });+ session = new Session({+ id: "native-background-steer",+ agentKind: "claude-code",+ workDir: root,+ handle,+ capabilities: agent.capabilities,+ logger,+ turnStallMs: 0,+ });+ session.onEvent((event) => seen.push(event));+ await session.send("BACKGROUND_STEER_START");+ await expect+ .poll(+ () =>+ seen.some(+ (event) =>+ event.type === "done" &&+ event.turnContinuationId !== undefined,+ ),+ { timeout: 30_000 },+ )+ .toBe(true);+ await expect+ .poll(() => Boolean(releaseChild), { timeout: 30_000 })+ .toBe(true);+ expect(session.isTurnRunning()).toBe(true);+ await session.steer("BACKGROUND_STEER_CORRECTION");+ await expect+ .poll(() => correctionRequests, { timeout: 30_000 })+ .toBe(1);+ expect(handle.listBackgroundTasks?.()).toHaveLength(1);+ await expect+ .poll(() => seen.filter((event) => event.type === "done").length, {+ timeout: 30_000,+ })+ .toBe(2);+ releaseChild!();+ releaseChild = undefined;+ await expect+ .poll(() => session!.isTurnRunning(), { timeout: 30_000 })+ .toBe(false);+ expect(+ seen.filter(+ (event) =>+ event.type === "done" && event.turnContinuationId === undefined,+ ),+ ).toHaveLength(1);+ expect(seen.filter((event) => event.type === "error")).toEqual([]);+ } catch (error) {+ console.error(+ "Native fixture state",+ JSON.stringify({+ parentRequests,+ correctionRequests,+ events: seen.map((event) => ({+ type: event.type,+ data: event.data,+ continuation: event.turnContinuationId,+ })),+ }),+ );+ throw error;+ } finally {+ releaseChild?.();+ await session?.close();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await rm(root, {+ recursive: true,+ force: true,+ maxRetries: 5,+ retryDelay: 100,+ });+ }+ }, 120_000);+ },+);diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 6a8304548e..2df98a3091 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -4697,7 +4697,7 @@ export class ClaudeCodeAgent extends BaseAgent {pendingBoundaryEvents: number;/** A later natural/synthetic done has closed the product turn. */settled: boolean;- /** A submitted async answer already accepted by the SDK input queue. */+ /** An async answer or waiting-turn steer accepted by the SDK input queue. */asyncAnswer?: boolean;};// Claims are created synchronously when the provider enqueues a `done`.@@ -4754,6 +4754,11 @@ export class ClaudeCodeAgent extends BaseAgent {activeContinuationId === null? null: continuationClaims.get(activeContinuationId) ?? null;+ // A foreground result can leave the same product waiting on background work.+ // Its live SDK input queue still accepts corrections during that interval.+ const hasSteerableTurn = (): boolean =>+ !closed && !turnState.interruptRequested && continuationCancellationGeneration === null &&+ (turnInFlight || activeContinuationClaim()?.state === 'awaiting');const releaseSettledContinuationClaim = (claim: ContinuationClaim): void => {if (!claim.settled || claim.pendingBoundaryEvents > 0) return;continuationClaims.delete(claim.id);@@ -6815,7 +6820,7 @@ export class ClaudeCodeAgent extends BaseAgent {throw new Error('Claude steer cancelled before acceptance');}if (sendOpts?.logTitle !== undefined) lastSendTitle = sendOpts.logTitle;- if (!turnInFlight) {+ if (!hasSteerableTurn()) {throw new Error('No active Claude turn to steer');}log.debug('steer ▶ user message', {@@ -6842,7 +6847,7 @@ export class ClaudeCodeAgent extends BaseAgent {if (sendOpts?.signal?.aborted) {throw new Error('Claude steer cancelled before acceptance');}- if (!turnInFlight) {+ if (!hasSteerableTurn()) {// Image resizing can take long enough for a fast turn to finish. Do not// silently route a stale "插话" into the next send path; the renderer// keeps the original queue/composer content and lets the user retry.@@ -6867,7 +6872,12 @@ export class ClaudeCodeAgent extends BaseAgent {// received it.throw new Error('No active Claude turn to steer: input queue is closed');}- if (sendOpts?.[ASYNC_QUESTION_ANSWER]) queuedAsyncAnswer = true;+ const awaitingClaim = activeContinuationClaim();+ if (awaitingClaim?.state === 'awaiting') {+ // This input belongs to the already claimed next segment, not another+ // successor. Stopping its last background task must not discard it.+ awaitingClaim.asyncAnswer = true;+ } else if (sendOpts?.[ASYNC_QUESTION_ANSWER]) queuedAsyncAnswer = true;appendActiveCapabilitySelectionText(userMessageTextForCapabilityRouting(message.content),);