Skip to content

fix(agent-core-v2): stop background subagents cleanly when the session shuts down - #5583

Merged
7Sageer merged 1 commit into
mainfrom
fix/subagent-stop-reason
Nov 27, 2026
Merged

7Sageer merged 1 commit into
mainfrom
fix/subagent-stop-reason

Conversation

@RealKai42

Copy link
Copy Markdown
Collaborator

Requirement or Bug

用户在后台子 agent 还在跑的时候关掉产品,会碰上两个问题:

  • 重新打开会话后,agent 收到的任务通知里写着 count files was stopped. Reason: [object Object],停止原因是乱码。
  • ACP 编辑器(Zed 等)关掉 kimi acp 时进程崩溃,退出码 1,stderr 是 Error: InstantiationService has been disposed。

这个 PR 之后,停止原因读不出来时通知里就不写原因;kimi acp 照常以 0 退出。这两个问题是 E2E 场景(见 #5582)在这次补的场景里发现的。

Bug Reproduction Steps

  1. 让主 agent 启动一个后台子 agent(Agent,run_in_background: true),子 agent 的模型请求一直不返回。
  2. 主回合结束后正常退出产品:TUI 用 /exit,ACP 由编辑器关掉连接。
  3. 修复前:
    • TUI:再打开会话、发一条消息,模型请求里的任务通知是 count files was stopped. Reason: [object Object]。
    • ACP:kimi acp exited with code 1,stderr 末尾是 InstantiationService has been disposed,栈从 stopChildTasks 经 AbortSignal.onAbort 出来。

E2E 复现:TESTKIT_CLI_BUILD=dist pnpm --filter @moonshot-ai/e2e exec playwright test --project=tui --project=acp scenarios/conversation/reopening-with-an-unfinished-background-task-waits-for-the-user.spec.ts。修复前 TUI 红在 not.toContain('[object Object]'),ACP 红在重启前的收尾检查;修复后两个面都绿。

Root Cause

两处根因不同,都发生在退出时中止后台子 agent 的那一刻。

  1. packages/agent-core-v2/src/agent/tools/agent/agentTool.ts:子 agent 被中止时,停止原因用 String(reason) 转字符串。退出时传进来的中止原因既不是字符串,也不是 Error,于是成了 [object Object],写进任务字段,之后进了通知。同一个文件里已有的 errorMessage(),以及核心包 packages/core/src/tool/tool-executor.ts 的 stopReasonText(),对这种原因都返回 undefined。
  2. packages/agent-core-v2/src/session/subagent/runAgentTurn.ts:中止监听器 onAbort 调用 stopChildTasks(target, …),后者在里面才执行 target.accessor.get(IAgentTaskService)。退出时子 agent 的作用域先被释放,这次查找就抛错。stopChildTasks 是 async 函数,抛错变成了被拒绝的 promise;finally 里那次补调 onAbort() 产生的 promise 没人 await,成了未处理的拒绝,kimi acp 因此退出。

都是根本修复:1 改用已有的 errorMessage();2 在 awaitRunCompletion 一开始、作用域还活着时取到任务服务,中止时直接用它,不再去已释放的作用域里查。

Code Changes

 agentTool: catch (error) when the signal aborted
   status = 'killed'
-  stopReason = string ? reason : Error ? reason.message : String(reason)
+  stopReason = errorMessage(signal.reason)     // undefined for other values

 runAgentTurn.awaitRunCompletion
+  tasks = target.accessor.get(IAgentTaskService)   // while the scope is alive
   onAbort
     loop.cancel(…)
-    stopChildTasks(target, loop, reason)            // looks the service up at abort time
+    stopChildTasks(tasks, loop, reason)
-  awaitQuiescent(target, loop)
+  awaitQuiescent(tasks, loop)

另外:scripts/checks/baselines/oxlint-ratchet.json 少了一条 agentTool.ts 的 no-unsafe-assignment,删掉的那行 String(reason) 正是它;新增的 E2E 场景 tests/e2e/scenarios/conversation/reopening-with-an-unfinished-background-task-waits-for-the-user.spec.ts 从 #5582 挪到这里,和修复一起合入。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
后台子 agent 因为一个不是字符串、也不是 Error 的中止原因停止时,任务通知里的原因 Reason: [object Object] 不写原因(count files killed.) 无:[object Object] 不携带任何信息 —
字符串或 Error 作为中止原因(用户停止、超时等) 写原因 不变 — —
编辑器关掉 kimi acp 时有后台子 agent 在跑 以退出码 1 崩溃 以 0 退出 无 —
子 agent 回合正常结束、超时、被用户停止 现有行为 不变:取任务服务的时机提前了,取到的是同一个服务实例 — —

受影响的面:TUI、print 模式、Desktop、Web(都会在退出时中止后台子 agent),ACP(崩溃只在这里出现)。

验证:

  • E2E 新场景在 TUI、ACP 上修复前红、修复后绿(本机 macOS,构建产物);Desktop、Web 交给 CI。
  • packages/agent-core-v2/test/session、test/agent/task、test/features/swarm 共 37 个文件、773 条全过。
  • pnpm lint 通过(按 ratchet 降了一条基线)。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

…n shuts down

Closing the product while a background subagent runs aborted it twice wrong.
The Agent tool turned a non-Error abort reason into "[object Object]" and
wrote it into the task notification the agent reads after the session is
reopened. And the abort listener looked up the task service on the subagent
scope after that scope had been disposed, so the rejected cleanup went
unhandled and kimi acp exited with code 1.

Read the reason with the existing errorMessage() helper, and resolve the task
service once while the scope is alive. The new E2E scenario reopens a session
whose background subagent was still running and checks that the product does
not call the model on its own and reports the stopped task once, readably.
@changeset-bot

changeset-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 2360ede

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/kimi-code Patch
@moonshot-ai/agent-core-v2 Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T18:23:42.809323Z 2360ede PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@2360ede
npx https://pkg.pr.new/@moonshot-ai/kimi-code@2360ede

commit: 2360ede

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2360ede7cb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

expect(requests[2]?.texts('user').join('\n').split('source_kind="background_task"')).toHaveLength(2);
expect(requests[2]?.texts('user').join('\n')).not.toContain('[object Object]');
expect(requests[2]?.userTextsSinceReply.at(-1)).toBe('What happened to the count?');
expect(model.requests('subagent')).toHaveLength(1);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep scenario request assertions on the main lane

This assertion directly inspects the subagent request lane, contrary to the explicit review-enforced rule in tests/e2e/AGENTS.md that scenarios only assert model.requests('main'). Keep this scenario's request assertions on the main lane; the existing held-request cancellation check already observes the background request being aborted, while the main-lane assertions verify the restored session's behavior.

AGENTS.md reference: tests/e2e/AGENTS.md:L52-L52

Useful? React with 👍 / 👎.

@7Sageer
7Sageer merged commit 74475df into main Nov 27, 2026
29 checks passed
@7Sageer
7Sageer deleted the fix/subagent-stop-reason branch November 27, 2026 03:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants