Skip to content

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(cli): cancel current task when received ctrl+c

ldstyle8bab608de5056
diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
index ad820bd2f7..5963ca07a5 100644
--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py
+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py
@@ -2055,7 +2055,7 @@ class JiuWenClawDeepAdapter:
根据 intent 分流:
- pause: 暂停循环(不取消任务)
- resume: 恢复已暂停的循环
- - cancel: 取消所有运行中的任务
+ - cancel: 为当前 session 生成取消结果与清理信息;真正停任务由 SessionManager 完成
- supplement: 取消当前任务但保留 todo
Args:
@@ -2108,14 +2108,9 @@ class JiuWenClawDeepAdapter:
message = "任务已切换"
else:
- # cancel(默认):停止所有执行 + 清理 todo
- # 1. 通过 rail abort 在 checkpoint 抛 CancelledError,打断当前内层执行
- if self._stream_event_rail is not None:
- self._stream_event_rail.abort()
- # 2. 终止 DeepAgent 外层 task loop
- if self._instance is not None:
- await self._instance.abort()
- # 3. 将未完成的 todo 项标记为 cancelled,并获取更新后的 todo 列表
+ # cancel(默认):仅做当前 session 的清理与回执。
+ # 真正停止运行中的任务由 facade 层的 SessionManager.cancel_session_task(session_id) 完成,
+ # 避免共享 DeepAgent 实例上的全局 abort 误伤其它并发 session。
updated_todos = None
if request.session_id:
try:
diff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.py
index a64b764702..7434e37710 100644
--- a/jiuwenclaw/agentserver/interface.py
+++ b/jiuwenclaw/agentserver/interface.py
@@ -357,7 +357,7 @@ class JiuWenClaw:
根据 intent 分流:
- pause: 暂停 ReAct 循环(不取消任务)
- resume: 恢复已暂停的 ReAct 循环
- - cancel: 取消所有运行中的任务
+ - cancel: 取消当前 session 正在运行的任务
- supplement: 取消当前任务但保留 todo
Args:
@@ -368,28 +368,45 @@ class JiuWenClaw:
Returns:
AgentResponse 包含 interrupt_result 事件数据
"""
- adapter = self._ensure_adapter()
- # 调用 adapter 的 process_interrupt 处理 SDK 特定逻辑(如 pause/resume、todo 标记等)
- response = await adapter.process_interrupt(request)
intent = request.params.get("intent", "cancel")
+ session_id = self._session_manager.get_session_id(request.session_id)
+ adapter = self._ensure_adapter()
if intent == "pause":
# 暂停:不取消任务,只暂停 ReAct 循环
- return response
+ return await adapter.process_interrupt(request)
if intent == "resume":
# 恢复:恢复 ReAct 循环
- return response
+ return await adapter.process_interrupt(request)
if intent == "supplement":
# 取消当前 session 的任务
- session_id = self._session_manager.get_session_id(request.session_id)
+ response = await adapter.process_interrupt(request)
await self._session_manager.cancel_session_task(session_id, "interrupt(supplement): ")
return response
- # cancel: 取消所有 session 的任务
- await self._session_manager.cancel_all_session_tasks(f"interrupt(intent={intent}): ")
- return response
+ # cancel: 仅取消当前 session 的任务,避免误伤其它并发会话
+ await self._session_manager.cancel_session_task(session_id, f"interrupt(intent={intent}): ")
+ await self._cancel_team_work_for_session(
+ session_id,
+ log_prefix=f"interrupt(intent={intent}): ",
+ )
+ return await adapter.process_interrupt(request)
+
+ async def _cancel_team_work_for_session(self, session_id: str, log_prefix: str = "") -> bool:
+ """终止当前 session 的 Team runtime(若存在)。"""
+ from jiuwenclaw.agentserver.team import get_team_manager
+
+ try:
+ team_manager = get_team_manager()
+ return await team_manager.terminate_session_runtime(session_id, reason=log_prefix)
+ except Exception:
+ logger.exception(
+ "[JiuWenClaw] failed to terminate team runtime: session_id=%s",
+ session_id,
+ )
+ return False
async def process_message(self, request: AgentRequest) -> AgentResponse:
"""处理非流式请求.
diff --git a/jiuwenclaw/agentserver/session_manager.py b/jiuwenclaw/agentserver/session_manager.py
index ffbc539481..64532a11e2 100644
--- a/jiuwenclaw/agentserver/session_manager.py
+++ b/jiuwenclaw/agentserver/session_manager.py
@@ -47,6 +47,11 @@ class SessionManager:
except (asyncio.CancelledError, Exception):
pass
self._session_tasks[session_id] = None
+ logger.info(
+ "[SessionManager] %ssession task terminated: session_id=%s",
+ log_msg_prefix,
+ session_id,
+ )
async def cancel_all_session_tasks(self, log_msg_prefix: str = "") -> None:
"""取消所有 session 的非流式任务."""
diff --git a/jiuwenclaw/agentserver/team/team_manager.py b/jiuwenclaw/agentserver/team/team_manager.py
index 9f00b43394..2084236546 100644
--- a/jiuwenclaw/agentserver/team/team_manager.py
+++ b/jiuwenclaw/agentserver/team/team_manager.py
@@ -594,6 +594,31 @@ class TeamManager:
def register_stream_task(self, session_id: str, task: asyncio.Task) -> None:
self._stream_tasks[session_id] = task
+ async def terminate_session_runtime(self, session_id: str, reason: str = "") -> bool:
+ """终止指定 session 的 Team 运行时(stream/monitor/team agent/runtime cleanup)。"""
+ async with self._lock:
+ has_stream_task = session_id in self._stream_tasks
+ has_team_runtime = session_id in self._team_agents or session_id in self._team_monitors
+ if not has_stream_task and not has_team_runtime:
+ return False
+ logger.info(
+ "[TeamManager] %sterminate team session runtime: session_id=%s",
+ reason,
+ session_id,
+ )
+ cleaned = await self._destroy_team(session_id)
+ logger.info(
+ "[TeamManager] %steam session terminated: session_id=%s cleaned=%s",
+ reason,
+ session_id,
+ cleaned,
+ )
+ return True
+
+ async def cancel_session_stream_task(self, session_id: str, reason: str = "") -> bool:
+ """兼容旧命名;实际语义为终止该 session 的 Team runtime。"""
+ return await self.terminate_session_runtime(session_id, reason=reason)
+
async def cancel_all_stream_tasks(self, reason: str = "") -> None:
"""Gateway 与 AgentServer 断开时取消 Team 后台 stream 协程(含 create_task 绕开 SessionManager 的任务)。"""
async with self._lock:
diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.ts
index 7af9c188dd..354902795f 100644
--- a/jiuwenclaw/cli/src/app-state.ts
+++ b/jiuwenclaw/cli/src/app-state.ts
@@ -1,4 +1,4 @@
-import { addInfo } from "./core/commands/helpers.js";
+import { addError, addInfo } from "./core/commands/helpers.js";
import type { CommandContext } from "./core/commands/types.js";
import {
computeTimeoutAt,
@@ -62,9 +62,13 @@ export interface AppSnapshot {
pendingQuestion: PendingQuestion | null;
lastError: string | null;
isProcessing: boolean;
- /** 主会话流式进行中、等待确认,或 Team 模式下有成员处于工作中(Ctrl+C 应发 interrupt 而非预退出) */
+ /**
+ * 当前 UI 观测到是否存在运行中的工作。
+ * 用于渲染与本地交互(如 Esc);Ctrl+C 的中断请求仍以服务端为准,不依赖此值放行。
+ */
cancellableWork: boolean;
isPaused: boolean;
+ isInterrupted: boolean;
activeSubtasks: SubtaskState[];
todos: TodoItem[];
teamMemberEvents: TeamMemberEvent[];
@@ -302,8 +306,10 @@ export class CliPiAppState {
const hasActiveSubtasks = [...this.activeSubtasks.values()].some(
(s) => s.status !== "completed" && s.status !== "error",
);
+ // 与「Ctrl+C 强制结束当前任务」对齐:有任一进行中工作则为 true。
const cancellableWork =
isProcessing ||
+ this.streamingState === StreamingState.Paused ||
hasRunningTools ||
hasActiveSubtasks ||
this.evolutionStatus === "running" ||
@@ -335,6 +341,7 @@ export class CliPiAppState {
isProcessing,
cancellableWork,
isPaused: this.streamingState === StreamingState.Paused,
+ isInterrupted: this.streamingState === StreamingState.Interrupted,
activeSubtasks: [...this.activeSubtasks.values()].sort((a, b) => a.index - b.index),
todos: [...this.todos],
teamMemberEvents: [...this.teamMemberEvents],
@@ -621,12 +628,20 @@ readonly request = async <T = Record<string, unknown>>(
return requestId;
}
- cancel(options?: { showNotice?: boolean }): void {
+ /** 向服务端请求中断当前 session 的任务;成功发送前不宣称“已中断”。 */
+ cancel(options?: { showNotice?: boolean }): boolean {
+ if (this.connectionStatus !== "connected") {
+ if (options?.showNotice !== false) {
+ this.addItem(addError(this.sessionId, "Unable to interrupt task while disconnected"));
+ }
+ return false;
+ }
+ const hadLocalWork = this.getSnapshot().cancellableWork;
this.sendEventOnly("chat.interrupt", { intent: "cancel" });
- if (options?.showNotice === false) {
- return;
+ if (options?.showNotice !== false && hadLocalWork) {
+ this.addItem(addInfo(this.sessionId, "Interrupt requested", "i"));
}
- this.addItem(addInfo(this.sessionId, "Task interrupted", "i"));
+ return true;
}
resume(): void {
diff --git a/jiuwenclaw/cli/src/core/event-handlers.ts b/jiuwenclaw/cli/src/core/event-handlers.ts
index e35c3ce3c7..a38c043a70 100644
--- a/jiuwenclaw/cli/src/core/event-handlers.ts
+++ b/jiuwenclaw/cli/src/core/event-handlers.ts
@@ -616,10 +616,36 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram
case "chat.interrupt_result": {
const intent = typeof payload.intent === "string" ? payload.intent : "cancel";
if (intent === "cancel") {
- delegate.setStreamingState(StreamingState.Idle);
- delegate.getActiveSubtasks().clear();
- delegate.setEvolutionStatus("idle");
- delegate.markRunningToolsInterrupted();
+ const success = payload.success !== false;
+ const message =
+ typeof payload.message === "string" && payload.message.trim()
+ ? payload.message
+ : success
+ ? "当前会话任务已终止"
+ : "当前会话任务终止失败";
+ if (success) {
+ delegate.setStreamingState(StreamingState.Interrupted);
+ delegate.getActiveSubtasks().clear();
+ delegate.setEvolutionStatus("idle");
+ delegate.markRunningToolsInterrupted();
+ appendEntry(delegate, {
+ kind: "info",
+ id: createId("info"),
+ sessionId: activeSessionId,
+ content: message,
+ icon: "i",
+ at: new Date().toISOString(),
+ });
+ } else {
+ appendEntry(delegate, {
+ kind: "error",
+ id: createId("error"),
+ sessionId: activeSessionId,
+ content: message,
+ at: new Date().toISOString(),
+ });
+ delegate.setLastError(message);
+ }
} else if (intent === "pause") {
delegate.setStreamingState(StreamingState.Paused);
} else {
diff --git a/jiuwenclaw/cli/src/core/types.ts b/jiuwenclaw/cli/src/core/types.ts
index 0db5de3efb..803d240d58 100644
--- a/jiuwenclaw/cli/src/core/types.ts
+++ b/jiuwenclaw/cli/src/core/types.ts
@@ -2,6 +2,7 @@ export enum StreamingState {
Idle = "idle",
Responding = "responding",
Paused = "paused",
+ Interrupted = "interrupted",
WaitingForConfirmation = "waiting_for_confirmation",
}
diff --git a/jiuwenclaw/cli/src/index.ts b/jiuwenclaw/cli/src/index.ts
index 1e9d750565..4d284bdbfe 100644
--- a/jiuwenclaw/cli/src/index.ts
+++ b/jiuwenclaw/cli/src/index.ts
@@ -47,11 +47,11 @@ tui.setClearOnShrink(true);
let closed = false;
let screen: AppScreen | null = null;
+/** 退出 CLI 前先向服务端发 `chat.interrupt`,结束当前会话中正在运行的 agent 任务(已连接时;idle 时多为 no-op)。 */
async function cancelBeforeExit(): Promise<void> {
if (appState.getSnapshot().connectionStatus !== "connected") {
return;
}
- // 关 TUI 即请求服务端终止当前会话工作;idle 时一般为 no-op。
appState.cancel({ showNotice: false });
await new Promise((resolve) => setTimeout(resolve, 200));
}
@@ -104,6 +104,10 @@ tui.setFocus(screen);
process.on("SIGTERM", () => {
void closeUi(0);
});
+// 与 TUI 内 Ctrl+C 一致:SIGINT 始终尝试中断当前 session 的任务,不退出进程(退出用 /exit、SIGTERM 等)。
+process.on("SIGINT", () => {
+ screen?.interruptTask();
+});
process.on("uncaughtException", (error) => {
void crash(error);
});
diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.ts
index c8624c85be..7b2a7d4230 100644
--- a/jiuwenclaw/cli/src/ui/app-screen.ts
+++ b/jiuwenclaw/cli/src/ui/app-screen.ts
@@ -342,7 +342,6 @@ export class AppScreen implements Component, Focusable {
private showTeamPanel = false;
private selectedTeamMemberId: string | null = null;
private viewedTeamMemberId: string | null = null;
- private exitArmedUntil = 0;
private transientNotice: string | null = null;
private transientNoticeTimer: ReturnType<typeof setTimeout> | null = null;
private animationTimer: ReturnType<typeof setInterval> | null = null;
@@ -403,6 +402,15 @@ export class AppScreen implements Component, Focusable {
this.editor.invalidate();
}
+ /**
+ * Ctrl+C / SIGINT 始终尝试向服务端发送当前 session 的中断请求。
+ * 是否真的存在运行任务由服务端判断;CLI/TUI 本身不退出。
+ */
+ interruptTask(): void {
+ this.state.cancel();
+ this.tui.requestRender();
+ }
+
handleInput(data: string): void {
const snapshot = this.state.getSnapshot();
const pendingQuestion = snapshot.pendingQuestion;
@@ -418,26 +426,7 @@ export class AppScreen implements Component, Focusable {
}
const handled = handleAppScreenKeyInput(data, {
- getSnapshot: () => snapshot,
- cancel: () => this.state.cancel(),
- requestExit: () => {
- const now = Date.now();
- if (now <= this.exitArmedUntil) {
- this.exit();
- return;
- }
- this.exitArmedUntil = now + 1500;
- this.transientNotice = "Press Ctrl+C again to exit";
- if (this.transientNoticeTimer) {
- clearTimeout(this.transientNoticeTimer);
- }
- this.transientNoticeTimer = setTimeout(() => {
- this.transientNotice = null;
- this.transientNoticeTimer = null;
- this.tui.requestRender();
- }, 1500);
- this.tui.requestRender();
- },
+ interruptTask: () => this.interruptTask(),
toggleTodos: () => {
this.showTodos = !this.showTodos;
this.tui.requestRender();
@@ -611,7 +600,9 @@ export class AppScreen implements Component, Focusable {
transientNotice: this.transientNotice,
animationPhase: this.animationPhase,
runningElapsedMs:
- (snapshot.isProcessing || teamWorking) && this.runningStartedAtMs !== null
+ !snapshot.isInterrupted &&
+ (snapshot.isProcessing || teamWorking) &&
+ this.runningStartedAtMs !== null
? Date.now() - this.runningStartedAtMs
: undefined,
});
@@ -1347,7 +1338,8 @@ export class AppScreen implements Component, Focusable {
snapshot.teamMemberEvents,
snapshot.teamMessageEvents,
);
- const shouldAnimate = snapshot.isProcessing || hasRunningTools || teamWorking;
+ const shouldAnimate =
+ !snapshot.isInterrupted && (snapshot.isProcessing || hasRunningTools || teamWorking);
if (!shouldAnimate) {
if (this.animationTimer) {
clearInterval(this.animationTimer);
diff --git a/jiuwenclaw/cli/src/ui/keymap.ts b/jiuwenclaw/cli/src/ui/keymap.ts
index 8f09d464d9..88482d5db9 100644
--- a/jiuwenclaw/cli/src/ui/keymap.ts
+++ b/jiuwenclaw/cli/src/ui/keymap.ts
@@ -1,10 +1,13 @@
import { matchesKey } from "@mariozechner/pi-tui";
-import type { AppSnapshot } from "../app-state.js";
+
+/**
+ * 快捷键约定(Ctrl+C):
+ * 用户在 CLI/TUI 按下 Ctrl+C 时,始终尝试向服务端发送 `chat.interrupt`,
+ * 强制结束当前 session 正在运行的任务;不退出 CLI/TUI。
+ */
export interface AppScreenKeymapDelegate {
- getSnapshot(): AppSnapshot;
- cancel(): void;
- requestExit(): void;
+ interruptTask(): void;
toggleTodos(): void;
toggleTeamPanel(): void;
toggleTranscript(): void;
@@ -22,14 +25,9 @@ export const APP_SCREEN_KEY_BINDINGS: readonly KeyBinding[] = [
{
key: "ctrl+c",
label: "ctrl+c",
- description: "cancel active run or arm exit",
+ description: "请求强制结束当前任务(不退出 CLI)",
run: (delegate) => {
- const snapshot = delegate.getSnapshot();
- if (snapshot.cancellableWork) {
- delegate.cancel();
- } else {
- delegate.requestExit();
- }
+ delegate.interruptTask();
},
},
{
diff --git a/jiuwenclaw/cli/src/ui/screen-layout.ts b/jiuwenclaw/cli/src/ui/screen-layout.ts
index f63ef2a294..e6db10289a 100644
--- a/jiuwenclaw/cli/src/ui/screen-layout.ts
+++ b/jiuwenclaw/cli/src/ui/screen-layout.ts
@@ -70,6 +70,10 @@ function renderRunningStatus(animationPhase: number, elapsedMs: number | undefin
return `• ${animatedLabel} (${formatElapsed(elapsedMs)} • esc to interrupt)`;
}
+function renderInterruptedStatus(): string {
+ return "• Interrupted";
+}
+
function connectionStatusLabel(status: AppSnapshot["connectionStatus"]): string | null {
switch (status) {
case "connecting":
@@ -110,6 +114,8 @@ function buildStatusLines(
const right = snapshot.lastError
? `error:${snapshot.lastError}`
+ : snapshot.isInterrupted
+ ? renderInterruptedStatus()
: snapshot.isPaused
? "paused"
: snapshot.isProcessing || teamWorking
diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.py
index 1d3de32845..0e3de7d55f 100644
--- a/jiuwenclaw/gateway/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler.py
@@ -333,8 +333,8 @@ class MessageHandler(ABC):
async def _cancel_agent_work_for_session(self, msg: "Message", old_sid: str | None) -> None:
"""取消指定 session 的网关流式任务,并向 AgentServer 发送 CHAT_CANCEL(与 Web chat.interrupt intent=cancel 对齐)。
- 网关侧仅取消 ``_stream_sessions[rid] == old_sid`` 的流式任务。AgentServer 对 ``intent=cancel`` 仍可能
- ``cancel_all_session_tasks``(与现网 unary 中断一致);若需仅撤销单 session 需在 interface 层扩展协议。
+ 网关侧仅取消 ``_stream_sessions[rid] == old_sid`` 的流式任务,并向 AgentServer 发送同 session 的
+ ``intent=cancel``,由 AgentServer 继续取消该 session 上的实际执行任务。
"""
from jiuwenclaw.schema.message import Message, ReqMethod
@@ -358,10 +358,10 @@ class MessageHandler(ABC):
if tasks_to_cancel:
await asyncio.gather(*tasks_to_cancel, return_exceptions=True)
-
- for rid in rids_cancelled:
- await self._send_interrupt_result_notification(
- rid, msg.channel_id, old_sid, "cancel",
+ logger.info(
+ "[MessageHandler] 当前 session 流式任务已终止: session_id=%s request_ids=%s",
+ old_sid,
+ rids_cancelled,
)
if old_sid is None and not rids_cancelled:
@@ -394,7 +394,51 @@ class MessageHandler(ABC):
)
agent_msg = await self._prepare_agent_dispatch_message(cancel_req)
env_interrupt = self.message_to_e2a(agent_msg)
- await self._send_interrupt_to_agent(env_interrupt)
+ try:
+ resp = await self._agent_client.send_request(env_interrupt)
+ except Exception as exc:
+ logger.warning("[MessageHandler] AgentServer 中断请求失败: %s", exc)
+ await self._send_interrupt_result_notification(
+ msg.id,
+ msg.channel_id,
+ sid_for_agent,
+ "cancel",
+ message=f"任务终止失败: {exc}",
+ success=False,
+ )
+ return
+
+ payload = resp.payload if isinstance(resp.payload, dict) else {}
+ if payload.get("event_type") == "chat.interrupt_result":
+ out = self._response_to_message(
+ resp,
+ sid_for_agent,
+ request_metadata=msg.metadata,
+ )
+ await self.publish_robot_messages(out)
+ logger.info(
+ "[MessageHandler] 已转发 AgentServer 中断结果: request_id=%s ok=%s",
+ resp.request_id,
+ resp.ok,
+ )
+ return
+
+ error_message = "任务终止失败"
+ if isinstance(payload, dict):
+ raw_error = payload.get("error") or payload.get("message")
+ if isinstance(raw_error, str) and raw_error.strip():
+ error_message = raw_error.strip()
+ elif not resp.ok:
+ error_message = "任务终止失败"
+
+ await self._send_interrupt_result_notification(
+ msg.id,
+ msg.channel_id,
+ sid_for_agent,
+ "cancel",
+ message=error_message,
+ success=False,
+ )
async def cancel_agent_sessions_on_disconnect(
self,
@@ -1959,16 +2003,23 @@ class MessageHandler(ABC):
session_id: str | None,
intent: str,
message: str | None = None,
+ success: bool = True,
) -> None:
"""发送 interrupt_result 事件到前端(pause / resume 等)."""
from jiuwenclaw.schema.message import Message, EventType
- messages_map = {
+ success_messages_map = {
"pause": "任务已暂停",
"resume": "任务已恢复",
"cancel": "任务已取消",
"supplement": "任务已切换",
}
+ failure_messages_map = {
+ "pause": "任务暂停失败",
+ "resume": "任务恢复失败",
+ "cancel": "任务终止失败",
+ "supplement": "任务切换失败",
+ }
notify_msg = Message(
id=request_id,
type="event",
@@ -1980,8 +2031,13 @@ class MessageHandler(ABC):
payload={
"event_type": "chat.interrupt_result",
"intent": intent,
- "success": True,
- "message": message or messages_map.get(intent, "任务已中断"),
+ "success": success,
+ "message": message
+ or (
+ success_messages_map.get(intent, "任务已中断")
+ if success
+ else failure_messages_map.get(intent, "任务中断失败")
+ ),
},
event_type=EventType.CHAT_INTERRUPT_RESULT,
metadata=None,