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: interrupt task when ctrl+c
ldstyle852a9673d7753
diff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex b8227e9cc0..c80b098bcc 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -510,7 +510,7 @@ export class CliPiAppState {this._getInputValueRef = ref;}- readonly sendEventOnly = (method: string, params: Record<string, unknown>): string => {+ readonly sendEventOnly = (method: string, params: Record<string, unknown>, isStream = false): string => {const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;const trustedDirs = getTrustedDirs();const workspaceDir = trustedDirs[0] || process.cwd();@@ -518,6 +518,7 @@ export class CliPiAppState {type: "req",id,method,+ ...(isStream ? { is_stream: true } : {}),params: {...params,session_id: (params.session_id as string | undefined) ?? this.sessionId,@@ -703,7 +704,7 @@ readonly request = async <T = Record<string, unknown>>(query: content,mode,...(attachments?.length ? { attachments } : {}),- });+ }, true);this.lastError = null;if (options?.logAsUser !== false) {this.entries = [@@ -763,7 +764,7 @@ readonly request = async <T = Record<string, unknown>>(const hadLocalWork = this.getSnapshot().cancellableWork;this.sendEventOnly("chat.interrupt", { intent: "cancel" });if (options?.showNotice !== false && hadLocalWork) {- this.addItem(addInfo(this.sessionId, "Interrupt requested", "i"));+ this.addItem(addInfo(this.sessionId, "Request Interrupted", "i"));}return true;}@@ -794,7 +795,7 @@ readonly request = async <T = Record<string, unknown>>(answers,source,mode: this.mode,- });+ }, true);} else {this.sendEventOnly("chat.user_answer", {request_id: this.pendingQuestion.requestId,diff --git a/jiuwenclaw/channels/tui/frontend/src/core/protocol.ts b/jiuwenclaw/channels/tui/frontend/src/core/protocol.tsindex a827595bc4..506d14b435 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/protocol.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/protocol.ts@@ -10,6 +10,7 @@ export interface ReqFrame {readonly type: "req";readonly id: string;readonly method: string;+ readonly is_stream?: boolean;readonly params: Record<string, unknown> & {content?: string;mode?: string;diff --git a/jiuwenclaw/channels/tui/frontend/src/core/ws-client.ts b/jiuwenclaw/channels/tui/frontend/src/core/ws-client.tsindex 079629a222..6ba9e4b6aa 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/ws-client.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/ws-client.ts@@ -1,5 +1,5 @@import WebSocket from "ws";-import type { Frame, ResFrame } from "./protocol.js";+import type { Frame, ReqFrame, ResFrame } from "./protocol.js";import { isResFrame } from "./protocol.js";export type FrameHandler = (frame: Frame) => void;@@ -87,13 +87,14 @@ export class WsClient {method: string,params: Record<string, unknown>,timeoutMs = 30000,+ isStream = false,): Promise<ResFrame> {return new Promise((resolve, reject) => {if (this.ws?.readyState !== WebSocket.OPEN) {reject(new Error(`socket not connected: ${method}`));return;}- const frame = { type: "req" as const, id, method, params };+ const frame: ReqFrame = { type: "req", id, method, params, ...(isStream ? { is_stream: true } : {}) };const timer = setTimeout(() => {this.pending.delete(id);reject(new Error(`request timeout: ${method}`));diff --git a/jiuwenclaw/gateway/app_gateway.py b/jiuwenclaw/gateway/app_gateway.pyindex c64b3b285d..cd596c4cb6 100644--- a/jiuwenclaw/gateway/app_gateway.py+++ b/jiuwenclaw/gateway/app_gateway.py@@ -612,6 +612,8 @@ class GatewayServer:if cwd and isinstance(cwd, str) and cwd.strip():metadata["cwd"] = cwd.strip()+ is_stream = bool(data.get("is_stream", False))+msg = Message(id=req_id,type="req",@@ -623,6 +625,7 @@ class GatewayServer:req_method=req_method,mode=mode,metadata=metadata,+ is_stream=is_stream,)if self._on_message_cb is not None:diff --git a/jiuwenclaw/server/agent_ws_server.py b/jiuwenclaw/server/agent_ws_server.pyindex bf803d4912..c64c797db2 100644--- a/jiuwenclaw/server/agent_ws_server.py+++ b/jiuwenclaw/server/agent_ws_server.py@@ -177,6 +177,8 @@ class AgentWebSocketServer:self._acp_client_capabilities_by_ws: dict[int, dict[str, Any]] = {}# AgentManager 实例self._agent_manager = AgentManager()+ # session_id → 正在运行的流式 asyncio.Task,用于 interrupt 时精确取消+ self._session_stream_tasks: dict[str, asyncio.Task] = {}# Scheduler service instance (for scheduled auto_harness tasks)self._scheduler_service: Optional[AutoHarnessService] = None# Model cache for scheduled task execution (same approach as interface_deep)@@ -368,6 +370,7 @@ class AgentWebSocketServer:self._current_ws = Noneself._current_send_lock = Noneself._clear_ws_acp_client_capabilities(ws)+ self._session_stream_tasks.clear()# Gateway 进程退出/端口关闭时,必须先取消各 session 内流式生产者(SessionManager)# 并中止 DeepAgent 内层循环;否则仅等待 _handle_message 任务结束会一直阻塞到任务自然完成。try:@@ -583,10 +586,28 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.SCHEDULE_DELETE:await self._handle_schedule_request(ws, request, send_lock, "delete")return+ if request.req_method == ReqMethod.CHAT_CANCEL:+ # 中断请求:先取消该 session 正在运行的流式任务,再继续正常处理+ sid = request.session_id or "default"+ stream_task = self._session_stream_tasks.get(sid)+ if stream_task is not None and not stream_task.done():+ logger.info(+ "[AgentWebSocketServer] cancel: 终止 session 流式任务: session_id=%s",+ sid,+ )+ stream_task.cancel()+ # 继续走 _handle_unary 让 agent 适配器处理 interrupt_resultif request.is_stream:await self._handle_stream(ws, request, send_lock)else:await self._handle_unary(ws, request, send_lock)+ except asyncio.CancelledError:+ # 流式任务被 interrupt 取消,正常退出无需报错+ logger.info(+ "[AgentWebSocketServer] 任务被取消: request_id=%s session_id=%s",+ request.request_id,+ request.session_id,+ )except Exception as e:logger.exception("[AgentWebSocketServer] 处理请求失败: request_id=%s: %s",@@ -692,6 +713,10 @@ class AgentWebSocketServer:async def _handle_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""流式处理:调用 process_message_stream,逐条发送 E2AResponse 线 JSON。"""channel_id = request.channel_id or "default"+ session_id = request.session_id or "default"+ current_task = asyncio.current_task()+ if current_task is not None:+ self._session_stream_tasks[session_id] = current_taskmode, sub_mode = _apply_resolved_mode_to_request(request)agent_mode = "agent" if mode == "auto_harness" else modetrusted_dirs = request.params.get("trusted_dirs", None)@@ -779,6 +804,9 @@ class AgentWebSocketServer:await heartbeat_taskexcept asyncio.CancelledError:pass+ # 清除 session 流式任务追踪(仅清除自身,避免误删后续新任务)+ if self._session_stream_tasks.get(session_id) is current_task:+ self._session_stream_tasks.pop(session_id, None)logger.info("[AgentWebSocketServer] 流式响应已发送: request_id=%s 共 %s 个 chunk",