Skip to content

fix(agent-core-v2): abort the UserPromptSubmit hook when its turn is cancelled - #5244

Merged
sailist merged 1 commit into
mainfrom
fix/abort-cancelled-prompt-submit-hook
Nov 27, 2026
Merged

sailist merged 1 commit into
mainfrom
fix/abort-cancelled-prompt-submit-hook

Conversation

@RealKai42

Copy link
Copy Markdown
Collaborator

Requirement or Bug

配置了 UserPromptSubmit hook 的用户,如果在 hook 还在运行时取消本轮(TUI 按 Esc、桌面端或 Web 点停止、KAP POST /sessions/{id}:cancel),hook 进程不会被终止,会一直跑到结束。它随后返回的 block 会作为 hook.result 推给客户端,还会进入下一次发给模型的上下文,而对应的那次运行已经取消了。这个 PR 之后,取消会终止正在运行的 hook,并丢弃它的结果。

Bug Reproduction Steps

  1. 配置一个运行几秒才返回 block 的 UserPromptSubmit hook(例如先等待几秒,再以退出码 2 退出)。
  2. 发一条消息,在 hook 运行期间取消本轮。
  3. 再发一条消息。

结果:hook 进程不受取消影响,跑完后客户端仍收到一条 blocked 的 hook.result;上下文里多出一条 <hook_result hook_event="UserPromptSubmit">…</hook_result> 的 assistant 消息。第 3 步提交时,被取消的第一条消息先重跑,这条过期的拦截结果随它一起发给了模型。新增的回归测试用桩 runner 稳定复现了这个顺序。

Root Cause

外部 UserPromptSubmit hook 拿到的是 new AbortController().signal,它永远不会触发。回合启动阶段(core 的 turn.starting → turnStarting → onBeforeSubmitPrompt)被整轮取消时,core 中止回合的 scope,把 prompt 放回队列并暂停调度,但 hook 收不到这次取消:

sequenceDiagram
    participant C as 客户端
    participant L as core loop
    participant H as 外部 hook 服务
    participant S as hook 进程
    C->>L: 提交 first
    L->>H: turn.starting(带回合 signal)
    H->>S: 启动 UserPromptSubmit
    C->>L: 整轮取消
    L->>L: 中止回合 scope,first 放回队列并暂停
    Note over H,S: 修复前:hook 用的 signal 不会触发,进程继续运行
    S-->>H: 退出码 2(block)
    H->>L: remind(hook_result blocked)
    H-->>C: hook.result(blocked)
    C->>L: 提交 second
    L->>L: 重跑 first,过期的提醒一起进入上下文
Loading

hook 返回后,原有的两处 throwIfAborted() 检查的也是这个假 signal,所以 block 结果照样被 remind 进 mailbox 并派发 HookResult。下一次回合启动时,这条提醒随重跑的 prompt 一起被取出,发给了模型。

这是根本修复:hook 改用回合真正的 abort signal 后,runner 现有的 abort 处理和原有的 throwIfAborted() 检查都随之生效,没有新增特殊分支。

Code Changes

改动在已有结构里,核心是 signal 的来源:

 turnStarting(event, signal)
-  ctx = { promptMessage, isSteer, hookParts, block }
+  ctx = { promptMessage, isSteer, hookParts, signal, block }
   run onBeforeSubmitPrompt(ctx)

 runPromptSubmitHook(ctx)
-  signal = new AbortController().signal
+  signal = ctx.signal
   signal.throwIfAborted()
   results = runner.trigger('UserPromptSubmit', { signal, ... })
   signal.throwIfAborted()
   block  → remind into context + HookResult
   others → hookParts + HookResult

取消之后的路径:runner 收到 abort,终止 hook 进程组(SIGTERM,100ms 后 SIGKILL;Windows 用 taskkill /T /F),立即返回,不报告 hook 失败;第二处 throwIfAborted() 抛出,跳过 remind 和 HookResult;turnStarting 的 catch 看到 signal 已中止,返回 blocked / aborted;core 发现这已经不是当前回合,忽略这个结果。

  • packages/agent-core-v2/src/agent/loop/loop.ts:PromptSubmitContext 新增 readonly signal: AbortSignal,与 BeforeStepContext.signal 同形。
  • packages/agent-core-v2/src/agent/loop/loopService.ts:turnStarting 把 core 传入的回合 signal 放进 ctx。仓库里只有这一处构造这个 ctx。
  • packages/agent-core-v2/src/features/externalHooks/agent/agentExternalHooksService.ts:UserPromptSubmit 改用 ctx.signal。
  • 测试:新增回归用例;两条手动构造 ctx 的现有用例补上 signal。

Behavior Changes and Affected Users

行为 之前 之后 谁依赖旧行为 逃生口
UserPromptSubmit hook 运行期间整轮取消(TUI Esc、桌面端与 Web 的停止、KAP POST /sessions/{id}:cancel、SDK 的取消) hook 进程跑到结束或超时(默认 30 秒) hook 进程组被终止(SIGTERM,100ms 后 SIGKILL;Windows 为 taskkill /T /F) 在 UserPromptSubmit 里执行必须跑完的副作用的 hook 脚本 无
同上,hook 随后返回 block block 被提醒进上下文,下一次回合随重跑的 prompt 发给模型;客户端收到 blocked 的 hook.result 丢弃,不进上下文,不发事件 无;旧行为就是本缺陷 不需要
同上,hook 随后返回非 block 的消息 客户端收到这些消息的 hook.result 不发事件 无 不需要
hook 运行期间 loop 关闭(会话关闭、引擎退出) hook 不会因关闭被终止 关闭会中止回合 scope,hook 同样被终止 同第一行 无
被取消后放回队列的 prompt 下次提交时重跑,hook 随之重跑 不变 — —
未被取消的 UserPromptSubmit(放行、追加文本、block) — 不变:signal 未中止时 throwIfAborted() 不抛出,代码路径与之前相同 — —

具名人群:配了 UserPromptSubmit hook 的用户(用户级 config.toml 或插件),涉及 TUI、桌面端与 Web、VS Code 扩展和 SDK 调用方;以及 hook 脚本作者。事件名、载荷和返回值语义都没变,只是取消时 hook 会被终止,处理方式与超时相同;PreToolUse 和 PreCompact 本来就把各自调用方的 signal 交给 runner。

契约目录 packages/agent-core-v2/src/features/externalHooks/ 的兼容性:

  • hook 脚本:stdin 载荷和返回值格式不变。
  • 客户端:hook.result 事件结构不变,只是不会再收到属于已取消运行的那一条。
  • 旧版本写的会话:已经写进 wire 的 hook_result 消息照常回放,wire 格式不变。
  • 类型:PromptSubmitContext 只在 agent-core-v2 内部构造;onBeforeSubmitPrompt 的处理函数(包括 kap-server 测试里注册的)只读取它,不受新增字段影响。
  • 文档:docs/*/customization/hooks.md 的事件说明仍然准确;文档没有描述任何 hook 在取消时的行为,本 PR 不改文档。

逃生口:没有提供。旧行为会把一次已取消运行的拦截结果交给模型和用户,属于缺陷;被终止的 hook 与超时被终止的处理方式相同。请维护者在这里确认不需要开关。

受影响模块与测试覆盖:

  • 第 1~3 行:packages/agent-core-v2/test/features/externalHooks/integration.test.ts 新增 UserPromptSubmit hook during a cancelled turn start(testkit 模型)。hook 运行中 loop.cancel(),随后返回 block;断言没有 hook.result、历史里没有 hook_result、所有模型请求里都没有 block 文本,且 hook 返回时 signal 已中止。修复前这 4 条断言逐条失败。runner 收到 abort 后立即返回、不等超时,由已有用例 externalHooksRunner.test.ts > aborts a running hook when the trigger signal aborts 覆盖。
  • 第 4 行:与第 1 行是同一个回合 signal,没有单独的用例。
  • 第 5 行:新用例里,被取消的 prompt 在下次提交时重跑并完成,hook 共被调用 3 次。
  • 第 6 行:放行路径经外部 hook 服务的覆盖来自 integration.test.ts 现有的两条 onBeforeSubmitPrompt 用例;block 与追加文本的渲染由 runner.test.ts 覆盖。未取消时服务层的 block 路径此前就没有引擎级用例,这条路径的代码本 PR 没有改动。
验证

macOS 本机实际运行:

  • pnpm lint:通过。
  • pnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmit:通过。
  • 受影响的测试 23 个文件、736 条通过:test/features/externalHooks、test/agent/loop、test/agent/prompt、test/agent/toolSelect/toolSelectService.test.ts、test/features/goal/goal.test.ts、test/agent/undo/undo.test.ts、test/agent/contextMemory/context.test.ts、test/agent/fullCompaction/fullCompaction.test.ts(以上在 packages/agent-core-v2 下),以及 packages/kap-server/test/prompts.test.ts。
  • 撤掉修复后新用例失败;恢复后整个文件连续 3 次 27/27 通过。
  • 平台:子进程的终止只在 macOS 上实测过。用真实 runner 和真实 hook 子进程临时跑过一次(未提交):cancel() 后 17ms 子进程退出,脚本没有执行到 block 分支,上下文、事件和模型请求里都没有它的结果。Linux 和 Windows 依赖 CI;Windows 的终止路径(taskkill /T /F)是 runner 现有的超时处理,本 PR 没有改。
  • pnpm run check:duplication:没有新增重复。

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.

…cancelled

The external UserPromptSubmit hook ran with an AbortController that never
fired, so cancelling the whole turn while the hook was still running let the
hook process run to completion. A block it returned afterwards was reminded
into the next turn's context and emitted as a hook result event, so the
model and clients saw a block for a run that had already been cancelled.

Prompt-submit hooks now receive the starting turn's abort signal and the
UserPromptSubmit hook passes it to the runner. Cancelling the turn
terminates the hook process and discards its result. The prompt keeps the
existing whole-turn cancel behavior: it stays queued and reruns, together
with its hook, on the next submission.
@changeset-bot

changeset-bot Bot commented Nov 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ed4df8c

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

This PR includes changesets to release 4 packages
Name Type
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
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 23, 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-23T03:38:42.537626Z ed4df8c PR opened
🔒 Security Review ✅ Completed 2026-11-23T03:41:31.674619Z ed4df8c 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 23, 2026

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

commit: ed4df8c

@sailist
sailist merged commit 63338e9 into main Nov 27, 2026
49 checks passed
@sailist
sailist deleted the fix/abort-cancelled-prompt-submit-hook branch November 27, 2026 16:08
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