Skip to content

fix: show shutdown progress and force exit on Ctrl+C during shutdown hooks - #4164

Merged
Grapedge merged 3 commits into
MoonshotAI:mainfrom
huangzheng2016:fix/shutdown-hook-hint
Oct 10, 2026
Merged

Grapedge merged 3 commits into
MoonshotAI:mainfrom
huangzheng2016:fix/shutdown-hook-hint

Conversation

@huangzheng2016

Copy link
Copy Markdown
Contributor

Requirement or Bug

退出 Kimi Code 时,如果配置了耗时较长的 SessionEnd hook(hook timeout 最长 30 秒),界面会冻结在最后一帧且无任何提示,看起来像卡死;期间再按 Ctrl+C 也没有反应。

Bug Reproduction Steps

  1. 在 config.toml 配置一个耗时的 SessionEnd hook(例如 command = "sleep 15", timeout = 30)。
  2. 启动 kimi,发送任意消息(如 ! echo hi)创建会话。
  3. 空闲时连按两次 Ctrl-C 退出:第二次按下后界面冻结、无任何提示,15 秒后(hook 结束)才退出;冻结期间再按 Ctrl-C 无任何反应。

Root Cause

  • KimiTUI.stop() 中 closeSession('shutting down') 会同步执行 SessionEnd hooks,时长由用户 hook 配置决定(最长 30 秒),期间 TUI 停在最后一帧,用户无法区分"正在关闭"和"程序卡死"。
  • shutdown 期间键盘处理器仍存活:再按 Ctrl-C 会走正常的取消/退出确认逻辑,把关闭提示覆盖掉(clearPendingExit/armPendingExit),或者干脆被忽略,没有任何"立即退出"的通道。

这是根本修复:关闭期间给出可见反馈,并把该窗口内的 Ctrl-C 定义为"跳过等待、立即强制退出"。

Code Changes

 stop()
   isShuttingDown = true
+  editor.onCtrlC = () => emergencyTerminalExit(130)   // shutdown 窗口内再按 = 立即强制退出
   …existing teardown…
+  footer.setTransientHint('Shutting down… (running shutdown hooks)')
+  ui.requestRender()
   await closeSession('shutting down')                  // SessionEnd hooks 在这里运行
   …

 EditorKeyboardController
+  disposed 标志;dispose() 后置位
   onSubmit / onPreInput / onChange / onCtrlC / onCtrlD / onEscape
-  …原逻辑…
+  if (this.disposed) return …                          // shutdown 后不再覆盖提示/武装退出确认

说明:Ctrl-C 在 raw 模式下以字节 \x03 到达,stop() 内直接替换 editor.onCtrlC 即可接管;emergencyTerminalExit 会恢复终端模式(raw mode / 光标)后以 130(128+SIGINT)退出。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
退出执行 SessionEnd hooks 期间的状态栏 冻结在最后一帧,无提示 显示 Shutting down… (running shutdown hooks) 无(仅新增提示,不改变关闭顺序与时长) —
shutdown hooks 运行期间按 Ctrl-C 按键被忽略或覆盖关闭提示,只能等 hook 跑完 立即强制退出(恢复终端后以 130 退出),不等 hook timeout 依赖 shutdown 期间 Ctrl-C 无效果的 TUI 用户 不按即可维持原有的优雅关闭
shutdown 期间按 Esc / 输入 / 其他快捷键 可能清除状态栏提示(clearPendingExit) 不再影响关闭提示与确认状态 无 —
空闲双击 Ctrl-C / Ctrl-D 退出、任务运行中 Ctrl-C 取消 — 完全不变 所有 TUI 用户 —

受影响模块与测试覆盖:

  • editor-keyboard.ts(dispose 后失效)→ test/tui/controllers/editor-keyboard.test.ts 新增 1 个用例:dispose 后 Ctrl-C/Esc/submit 不触碰 footer 提示、不触发 stop。
  • kimi-tui.ts(stop() 提示 + 强制退出接管)→ test/tui/kimi-tui-message-flow.test.ts 新增 1 个用例:stop() 挂起在 closeSession 时按 Ctrl-C 会调用 emergencyTerminalExit(130)。
  • 已在 tmux 中端到端验证:慢 hook(15s)场景下,关闭期间状态栏显示提示,再按一次 Ctrl-C 进程在 2 秒内退出(不等待 hook)。

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.

@changeset-bot

changeset-bot Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 8c5acad

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

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code 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 Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T08:12:11.652610Z 8c5acad New commits
ℹ️ 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 Oct 10, 2026 •

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

commit: 8c5acad

Grapedge
Grapedge previously approved these changes Oct 10, 2026

@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: 264cb6cd25

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
// A Ctrl+C during shutdown means "don't wait for slow hooks": skip the
// remaining graceful close and get out immediately.
this.state.editor.onCtrlC = () => {
this.emergencyTerminalExit(130);

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 Leave fullscreen before forcing the process to exit

When tui_mode = "fullscreen" and the user invokes the new Ctrl+C escape while closeSession() is waiting, this call goes directly to process.exit() through emergencyTerminalExit() and bypasses stopUiForExit(). restoreTerminalModes() does not emit the alternate-screen/mouse/autowrap teardown; those sequences (ESC[?1049l, mouse disable, and autowrap enable) are only sent by TuiAltScreen.stop() in packages/pi-tui/src/tui-alt-screen.ts:392-418, so the user's shell remains in Kimi's alternate screen with mouse reporting active. On POSIX the same bypass also skips run-shell.ts's saved-stty restoration. Perform complete UI/terminal cleanup before the forced exit.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
this.aborted = true;
// A Ctrl+C during shutdown means "don't wait for slow hooks": skip the
// remaining graceful close and get out immediately.
this.state.editor.onCtrlC = () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Capture shutdown Ctrl+C outside the editor

When shutdown starts while an editor replacement is focused—for example, SIGTERM arrives with /help or a settings picker open and a SessionEnd hook then blocks—pi-tui routes Ctrl+C only to the focused component (packages/pi-tui/src/tui.ts:1080-1090). stop() neither restores editor focus nor adds a global input listener, so changing state.editor.onCtrlC is unreachable; HelpPanel and ChoicePicker ignore Ctrl+C and the promised immediate exit still waits for the hook timeout. Capture the shutdown key at the UI level or otherwise independently of focus.

AGENTS.md reference: apps/kimi-code/AGENTS.md:L25-L26

Useful? React with 👍 / 👎.

};

editor.onPreInput = (data: string) => {
if (this.disposed) return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Quiesce every editor shortcut after disposal

After editorKeyboard.dispose() during a slow closeSession(), returning false here tells CustomEditor.handleInput() to continue dispatching the key. Several installed handlers still lack a disposed check—notably Ctrl+G's onOpenExternalEditor, plus Shift-Tab, Ctrl+S/B/O, paste, and history—so Ctrl+G can call state.ui.stop(), spawn $EDITOR, and later restart the UI concurrently with shutdown instead of leaving only emergency Ctrl+C active. Consume non-Ctrl+C input after disposal or clear/guard every remaining handler.

Useful? React with 👍 / 👎.

@huangzheng2016

Copy link
Copy Markdown
Contributor Author

Review feedback addressed in 8c5acad:

  • P1 (fullscreen teardown): the shutdown Ctrl+C no longer goes through the bare emergencyTerminalExit() path. It now runs the full stopUiForExit() (alternate screen / mouse reporting / autowrap teardown) plus the CLI's restoreStty() via onExit, then exits with 130.
  • P2 (focus-independent capture): Ctrl+C during shutdown is captured via pi-tui's addInputListener (runs before focus routing) instead of overriding editor.onCtrlC, so it works when a dialog/editor replacement holds focus. The listener is removed when stop() finishes.
  • P2 (post-dispose shortcuts): consolidated the per-handler guards into a single consume-all in onPreInput after dispose(), so no editor shortcut (Ctrl+G external editor, Ctrl+S, etc.) can fire while the UI is being torn down.

Tests updated accordingly; full suite and e2e (15s slow-hook scenario, force exit within seconds) verified.

@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: 8c5acadd2c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// input-listener level so it works no matter which component holds focus
// (a dialog may have replaced the editor).
const removeForceExitListener = this.state.ui.addInputListener((data) => {
if (!matchesKey(data, Key.ctrl('c'))) return undefined;

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 Accept only Ctrl+C press events in the shutdown listener

When a normal double-Ctrl+C exit is waiting in closeSession() on a terminal that supports Kitty event reporting, releasing the second Ctrl+C also matches this condition and immediately forces the exit without a third key press. ProcessTerminal requests Kitty flag 2 (packages/pi-tui/src/terminal.ts:251-255), matchesKey() matches the resulting \x1b[99;5:3u release sequence, and the generic release filter in packages/pi-tui/src/tui.ts:1024-1087 runs only after global input listeners, so slow SessionEnd hooks and harness cleanup are silently skipped. Reject release/repeat events here and act only on a new press.

AGENTS.md reference: AGENTS.md:L118-L120

Useful? React with 👍 / 👎.

Comment on lines +1102 to +1103
if (this.onExit) {
void this.onExit(130);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Bypass foreground handoffs during a forced exit

When shutdown was initiated by /web or /remote-control, those commands register exitForegroundTask before calling stop() (apps/kimi-code/src/tui/commands/web.ts:41-42,55-110); routing forced Ctrl+C through the normal onExit therefore reaches apps/kimi-code/src/cli/run-shell.ts:258-263, which awaits that foreground task instead of calling process.exit. In this context the advertised forced exit starts and remains in the web/remote-control server (and the still-running original shutdown can later invoke the handoff again), so the force path must clear or bypass the takeover.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

// stty restore via onExit, instead of the bare emergency sequences.
private forceExitDuringShutdown(): void {
try {
this.stopUiForExit();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drain pending input before the forced terminal teardown

When /exit, Ctrl+D, or SIGTERM has already started shutdown and the user force-exits with Ctrl+C on a Kitty terminal over slow SSH, the release sequence can still be in flight when this call removes and pauses stdin. The normal path explicitly awaits state.terminal.drainInput() at kimi-tui.ts:1076-1082, and ProcessTerminal.drainInput() is documented and implemented specifically to consume late Kitty releases before returning control to the parent shell (packages/pi-tui/src/terminal.ts:78-84,384-419). The new stopUiForExit() call fixes screen teardown but still bypasses that drain, so the release escape sequence can leak into the user's shell; perform the short drain before stopping the UI.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

@Grapedge
Grapedge merged commit 3395f5b into MoonshotAI:main Oct 10, 2026
15 checks passed
@github-actions github-actions Bot mentioned this pull request Oct 10, 2026
@github-actions github-actions Bot mentioned this pull request Oct 14, 2026
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