JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(tui): Support interruption via Ctrl+C during manual execution of /recap
openJiuwen-bota11e75e79ee5
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 74658220dd..859575ea7b 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -235,6 +235,8 @@ export class CliPiAppState {private suppressInterruptResult = false;/** 本地中断请求标志,cancel() 调用时立即置 true,用于 long-running 命令的中断检测。 */private interruptRequested = false;+ /** 当前正在执行的斜杠命令 WS 请求 ID,用于 Ctrl+C 时立即取消。 */+ private activeCommandRequestId: string | null = null;private lastVisibleUserRequest: VisibleUserRequest | null = null;/** 保存 askQuestions 之前的 streamingState,用于在对话框关闭后恢复。 */private streamingStateBeforeQuestion: StreamingState | null = null;@@ -627,9 +629,21 @@ export class CliPiAppState {return this.interruptRequested;}- /** Set local interrupt flag (for long-running local commands like log streaming) */- requestLocalInterrupt(): void {+ /**+ * Set local interrupt flag (for long-running local commands like log streaming).+ * Returns true if an active command WS request was cancelled — this signals+ * to the Ctrl+C handler that the interrupt consumed the keystroke and the+ * "double-press-to-exit" timer should be reset.+ */+ requestLocalInterrupt(): boolean {this.interruptRequested = true;+ // 立即取消正在执行的命令 WS 请求(如 /recap),避免等待 60 秒超时+ if (this.activeCommandRequestId) {+ this.wsClient.cancelRequest(this.activeCommandRequestId, "cancelled");+ this.activeCommandRequestId = null;+ return true; // 命令请求被取消 → Ctrl+C 被消费,不应触发"连按两次退出"+ }+ return false;}/** Clear local interrupt flag (called after handling interrupt) */@@ -764,22 +778,31 @@ export class CliPiAppState {timeoutMs?: number,): Promise<T> => {const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;+ // 记录当前命令请求 ID,以便 Ctrl+C 时能立即取消 WS 请求+ this.activeCommandRequestId = id;const trustedDirs = getTrustedDirs();const projectDir = getCurrentProjectDir() || process.cwd();const cwd = getCurrentCwd() || projectDir;- const response = await this.wsClient.request(- id,- method,- {- ...params,- session_id: params.session_id ?? this.sessionId,- ...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),- ...(projectDir ? { project_dir: projectDir } : {}),- ...(cwd ? { cwd } : {}),- },- timeoutMs ?? 30000,- );- return response.payload as T;+ try {+ const response = await this.wsClient.request(+ id,+ method,+ {+ ...params,+ session_id: params.session_id ?? this.sessionId,+ ...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),+ ...(projectDir ? { project_dir: projectDir } : {}),+ ...(cwd ? { cwd } : {}),+ },+ timeoutMs ?? 30000,+ );+ return response.payload as T;+ } finally {+ // 请求完成后清理追踪(无论成功/失败/取消)+ if (this.activeCommandRequestId === id) {+ this.activeCommandRequestId = null;+ }+ }};readonly updateSession = (newId: string): void => {@@ -1040,6 +1063,11 @@ export class CliPiAppState {}// Set local interrupt flag immediately for long-running command detectionthis.interruptRequested = true;+ // 同时取消正在执行的命令 WS 请求(与 requestLocalInterrupt 保持一致)+ if (this.activeCommandRequestId) {+ this.wsClient.cancelRequest(this.activeCommandRequestId, "cancelled");+ this.activeCommandRequestId = null;+ }const hadLocalWork = this.getSnapshot().cancellableWork;this.sendEventOnly("chat.interrupt", { intent: "cancel", mode: this.mode });if (options?.showNotice !== false && hadLocalWork) {diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/recap.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/recap.tsindex 465a657012..d2785a0b02 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/recap.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/recap.ts@@ -1,5 +1,5 @@import { addError, addInfo } from "../helpers.js";-import { CommandKind, type SlashCommand } from "../types.js";+import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";interface RecapResponse {status: "ok" | "no_turn" | "failed";@@ -9,6 +9,24 @@ interface RecapResponse {const NO_TURN_MSG = "Nothing to recap yet — send a message first.";const FAILED_MSG = "Couldn't generate a recap. Please try again later.";+const CANCELLED_MSG = "Recap cancelled.";++/**+ * 创建一个在 Ctrl+C 中断时 reject 的 Promise,用于 Promise.race 中。+ * 每 100ms 检查一次 ctx.isInterruptRequested(),检测到中断立即 reject。+ */+function waitForInterrupt(ctx: CommandContext): Promise<never> {+ return new Promise((_, reject) => {+ const check = () => {+ if (ctx.isInterruptRequested()) {+ reject(new Error("cancelled"));+ return;+ }+ setTimeout(check, 100);+ };+ setTimeout(check, 100);+ });+}export function createRecapCommand(): SlashCommand {return {@@ -20,14 +38,23 @@ export function createRecapCommand(): SlashCommand {hidden: true,takesArgs: false,action: async (ctx) => {+ // 如果在开始前就已经被中断(比如上一轮残留的中断标志),立即退出+ if (ctx.isInterruptRequested()) {+ ctx.addItem(addInfo(ctx.sessionId, CANCELLED_MSG, "i"));+ ctx.clearInterruptRequested();+ return;+ }+ctx.addItem(addInfo(ctx.sessionId, "Recaping...", "⏳"));try {- const payload = await ctx.request<RecapResponse>(- "command.recap",- { mode: ctx.mode },- 60000,- );+ // 将 WS 请求与中断检测赛跑:+ // - WS 请求正常返回 → 走正常结果处理+ // - 用户按 Ctrl+C → waitForInterrupt reject → 跳到 catch 块处理取消+ const payload = await Promise.race([+ ctx.request<RecapResponse>("command.recap", { mode: ctx.mode }, 60000),+ waitForInterrupt(ctx),+ ]);switch (payload.status) {case "ok":@@ -41,6 +68,13 @@ export function createRecapCommand(): SlashCommand {break;}} catch (error) {+ // 用户按 Ctrl+C 取消+ if (error instanceof Error && error.message === "cancelled") {+ ctx.addItem(addInfo(ctx.sessionId, CANCELLED_MSG, "i"));+ ctx.clearInterruptRequested();+ return;+ }+ // 其他错误(超时、网络断开等)const message = error instanceof Error ? error.message : String(error);ctx.addItem(addError(ctx.sessionId, `recap failed: ${message}`));}diff --git a/jiuwenswarm/channels/tui/frontend/src/core/ws-client.ts b/jiuwenswarm/channels/tui/frontend/src/core/ws-client.tsindex 6c51dc3b98..5263330e90 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/ws-client.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/ws-client.ts@@ -207,6 +207,21 @@ export class WsClient {}}+ /**+ * Cancel a specific pending request by ID.+ * Clears the timeout timer, removes the entry, and rejects the Promise.+ * Used when a command is interrupted (Ctrl+C) to clean up the WS request+ * immediately instead of waiting for timeout.+ */+ cancelRequest(id: string, reason = "cancelled"): void {+ const pending = this.pending.get(id);+ if (pending) {+ clearTimeout(pending.timer);+ this.pending.delete(id);+ pending.reject(new Error(reason));+ }+ }+private rejectAllPending(error: Error): void {for (const pending of this.pending.values()) {clearTimeout(pending.timer);diff --git a/jiuwenswarm/channels/tui/frontend/src/index.ts b/jiuwenswarm/channels/tui/frontend/src/index.tsindex 55ba98cf8c..2509265ca0 100644--- a/jiuwenswarm/channels/tui/frontend/src/index.ts+++ b/jiuwenswarm/channels/tui/frontend/src/index.ts@@ -104,7 +104,9 @@ tui.setFocus(screen);process.on("SIGTERM", () => {void closeUi(0);});-// 双击 Ctrl+C 退出:第一次中断当前任务,1 秒内再按一次退出进程。+// 双击 Ctrl+C 退出:第一次中断当前任务,3 秒内再按一次退出进程。+// 当 Ctrl+C 消费在取消命令(如 /recap)上时,重置计时器,+// 需要再连按两次才能退出,而非只需一次。let lastInterruptTime = 0;process.on("SIGINT", () => {const now = Date.now();diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex b6f1fb13fa..26332851cc 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -976,7 +976,7 @@ export class AppScreen implements Component, Focusable {},hasServerTask: () => this.state.hasServerTask(),requestLocalInterrupt: () => {- this.state.requestLocalInterrupt();+ return this.state.requestLocalInterrupt();},showCtrlCExitHint: () => {if (this.transientNoticeTimer) {diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/keymap.ts b/jiuwenswarm/channels/tui/frontend/src/ui/keymap.tsindex bfa4af6116..f67c2a3883 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/keymap.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/keymap.ts@@ -13,8 +13,13 @@ let lastInterruptTime = 0;export interface AppScreenKeymapDelegate {/** Interrupt server-side task (send chat.interrupt) */interruptTask(): void;- /** Set local interrupt flag only (for long-running local commands like log streaming) */- requestLocalInterrupt(): void;+ /**+ * Set local interrupt flag only (for long-running local commands like log streaming).+ * Returns true if an active command WS request was cancelled — this means the+ * Ctrl+C keystroke was consumed by the command cancellation and the "double-press-+ * to-exit" timer should be reset.+ */+ requestLocalInterrupt(): boolean;/** Show a brief hint that pressing Ctrl+C again will exit */showCtrlCExitHint(): void;exitApp(): void;@@ -48,19 +53,30 @@ export const APP_SCREEN_KEY_BINDINGS: readonly KeyBinding[] = [}// Always set local interrupt flag (for long-running local commands)- delegate.requestLocalInterrupt();+ // Returns true if an active command request was cancelled — this means+ // Ctrl+C was consumed by command cancellation, not a generic interrupt.+ const commandCancelled = delegate.requestLocalInterrupt();// Only send chat.interrupt if there's a server task runningif (delegate.hasServerTask()) {delegate.interruptTask();}+ // When a command (e.g. /recap) was cancelled, reset the double-press timer+ // so the user needs TWO fresh Ctrl+C presses to exit, not just one more.+ if (commandCancelled && !delegate.hasServerTask()) {+ lastInterruptTime = 0;+ // Don't show the "Press Ctrl+C again to exit" hint — the user just+ // cancelled a command, they don't intend to exit the TUI.+ return;+ }+// If idle (no server task and no local command running), clear inputif (delegate.isIdle()) {delegate.clearInput();}- // Show hint that pressing Ctrl+C again within 1s will exit+ // Show hint that pressing Ctrl+C again will exitdelegate.showCtrlCExitHint();lastInterruptTime = now;