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: 1. interrupt task when receiving Ctrl+C command, and support /clear next; 2. forcibly terminate tasks when tui closed
ldstyle8cf64b02937ee
diff --git a/jiuwenclaw/agentserver/agent_manager.py b/jiuwenclaw/agentserver/agent_manager.pyindex 7e7a562097..5d7ae68820 100644--- a/jiuwenclaw/agentserver/agent_manager.py+++ b/jiuwenclaw/agentserver/agent_manager.py@@ -117,6 +117,15 @@ class AgentManager:return ACP_DEFAULT_CAPABILITIES.copy()return None+ async def cancel_all_inflight_work(self, reason: str = "[gateway ws disconnect] ") -> None:+ """Gateway 与 AgentServer 的 WebSocket 断开时:取消所有已创建 Agent 实例上的在途任务。"""+ for modes in list(self.agents.values()):+ for agent in list(modes.values()):+ try:+ await agent.cancel_inflight_work(reason)+ except Exception:+ logger.exception("[AgentManager] cancel_inflight_work failed")+def get_client_capabilities(self, channel_id: str = "") -> dict[str, Any]:channel_key = str(channel_id or "").strip()caps = self._client_capabilities_by_channel.get(channel_key)diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex 5ca6388cdf..bd2cf649df 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -234,7 +234,26 @@ class AgentWebSocketServer:self._current_ws = Noneself._current_send_lock = Noneself._clear_ws_acp_client_capabilities(ws)+ # Gateway 进程退出/端口关闭时,必须先取消各 session 内流式生产者(SessionManager)+ # 并中止 DeepAgent 内层循环;否则仅等待 _handle_message 任务结束会一直阻塞到任务自然完成。+ try:+ await self._agent_manager.cancel_all_inflight_work(+ reason=f"[gateway ws closed {remote}] ",+ )+ except Exception:+ logger.exception("[AgentWebSocketServer] cancel_all_inflight_work failed")+ try:+ from jiuwenclaw.agentserver.team import get_team_manager++ await get_team_manager().cancel_all_stream_tasks(+ reason=f"[gateway ws closed {remote}] ",+ )+ except Exception:+ logger.exception("[AgentWebSocketServer] team stream cancel failed")if tasks:+ for t in list(tasks):+ if not t.done():+ t.cancel()await asyncio.gather(*tasks, return_exceptions=True)async def _handle_message(self, ws: Any, raw: str | bytes, send_lock: asyncio.Lock) -> None:diff --git a/jiuwenclaw/agentserver/deep_agent/interface_deep.py b/jiuwenclaw/agentserver/deep_agent/interface_deep.pyindex 65c0783d7e..a5c39de9b7 100644--- a/jiuwenclaw/agentserver/deep_agent/interface_deep.py+++ b/jiuwenclaw/agentserver/deep_agent/interface_deep.py@@ -2077,6 +2077,19 @@ class JiuWenClawDeepAdapter:metadata=request.metadata,)+ async def abort_on_gateway_disconnect(self) -> None:+ """Gateway 与 AgentServer 的 WebSocket 断开时:与 interrupt(cancel) 同样中止 rail 与 DeepAgent 实例。"""+ if self._stream_event_rail is not None:+ self._stream_event_rail.abort()+ if self._instance is not None:+ try:+ await self._instance.abort()+ except Exception as exc:+ logger.warning(+ "[JiuWenClawDeepAdapter] abort_on_gateway_disconnect instance.abort failed: %s",+ exc,+ )+def _has_valid_model_config(self) -> bool:"""检查是否有有效的模型配置."""# 检查环境变量中是否有 API_KEYdiff --git a/jiuwenclaw/agentserver/interface.py b/jiuwenclaw/agentserver/interface.pyindex 12be6e01d6..ad0bc4eec3 100644--- a/jiuwenclaw/agentserver/interface.py+++ b/jiuwenclaw/agentserver/interface.py@@ -722,6 +722,20 @@ class JiuWenClaw:# ---------- 资源清理 ----------+ async def cancel_inflight_work(self, log_prefix: str = "[gateway disconnect] ") -> None:+ """Gateway 与 AgentServer 的 WebSocket 断开时调用:取消 session 流式任务并中止 adapter 内层循环。"""+ await self._session_manager.cancel_all_session_tasks(log_prefix)+ adapter = self._adapter+ if adapter is None:+ return+ abort_fn = getattr(adapter, "abort_on_gateway_disconnect", None)+ if not callable(abort_fn):+ return+ try:+ await abort_fn()+ except Exception:+ logger.exception("[JiuWenClaw] adapter.abort_on_gateway_disconnect failed")+async def cleanup(self) -> None:"""清理资源,准备销毁实例.diff --git a/jiuwenclaw/agentserver/team/team_manager.py b/jiuwenclaw/agentserver/team/team_manager.pyindex f3a03f4452..9f00b43394 100644--- a/jiuwenclaw/agentserver/team/team_manager.py+++ b/jiuwenclaw/agentserver/team/team_manager.py@@ -594,6 +594,35 @@ class TeamManager:def register_stream_task(self, session_id: str, task: asyncio.Task) -> None:self._stream_tasks[session_id] = task+ async def cancel_all_stream_tasks(self, reason: str = "") -> None:+ """Gateway 与 AgentServer 断开时取消 Team 后台 stream 协程(含 create_task 绕开 SessionManager 的任务)。"""+ async with self._lock:+ pending = list(self._stream_tasks.items())+ for session_id, task in pending:+ if task.done():+ continue+ logger.info(+ "[TeamManager] %scancel stream task session_id=%s",+ reason,+ session_id,+ )+ task.cancel()+ for session_id, task in pending:+ if task.done():+ continue+ try:+ await task+ except asyncio.CancelledError:+ pass+ except Exception as exc:+ logger.warning(+ "[TeamManager] stream task await after cancel failed session_id=%s: %s",+ session_id,+ exc,+ )+ async with self._lock:+ self._stream_tasks.clear()+_team_manager: TeamManager | None = Nonediff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex 02e4bff301..92b8f861ef 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -185,6 +185,7 @@ class RouteConfig:inbound_interceptor: Callable[..., Awaitable[bool]] | None = Noneoutbound_interceptor: Callable[..., Awaitable[bool]] | None = Nonecleanup_handler: Callable[..., Any] | None = None+ disconnect_handler: Callable[..., Any] | None = None@dataclass@@ -469,10 +470,21 @@ class GatewayServer:stale_request_ids = [request_id for request_id, client in self._request_to_client.items() if client is ws]for request_id in stale_request_ids:self._request_to_client.pop(request_id, None)- stale_session_ids = [session_id for session_id, client in self._session_to_client.items() if client is ws]- for session_id in stale_session_ids:- self._session_to_client.pop(session_id, None)- if route.cleanup_handler is not None:+ stale_session_keys = [key for key, client in self._session_to_client.items() if client is ws]+ for session_key in stale_session_keys:+ self._session_to_client.pop(session_key, None)+ if route.disconnect_handler is not None:+ try:+ result = route.disconnect_handler(ws, stale_session_keys)+ if asyncio.iscoroutine(result):+ await result+ except Exception:+ logger.warning(+ "GatewayServer disconnect handler failed: path=%s",+ request_path,+ exc_info=True,+ )+ elif route.cleanup_handler is not None:try:route.cleanup_handler(ws)except Exception:@@ -657,6 +669,7 @@ def _build_route_config_map(bindings: list[GatewayRouteBinding]) -> dict[str, Roinbound_interceptor=binding.inbound_interceptor,outbound_interceptor=binding.outbound_interceptor,cleanup_handler=binding.cleanup_handler,+ disconnect_handler=binding.disconnect_handler,)for binding in bindings}diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.pyindex d41a1c3e41..e805dcfcd6 100644--- a/jiuwenclaw/channel/cli_channel.py+++ b/jiuwenclaw/channel/cli_channel.py@@ -1149,10 +1149,17 @@ def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:))+ async def _tui_disconnect(_ws: Any, stale_session_keys: list[tuple[str, str]]) -> None:+ mh = bind.message_handler+ if mh is None or not stale_session_keys:+ return+ await mh.cancel_agent_sessions_on_disconnect(stale_session_keys)+return GatewayRouteBinding(path=bind.path,channel_id=bind.channel_id,forward_methods=CLI_FORWARD_REQ_METHODS,forward_no_local_handler_methods=CLI_FORWARD_NO_LOCAL_HANDLER_METHODS,install=_install,+ disconnect_handler=_tui_disconnect,)diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.tsindex 34289c37ce..c88da1429f 100644--- a/jiuwenclaw/cli/src/app-state.ts+++ b/jiuwenclaw/cli/src/app-state.ts@@ -1,3 +1,4 @@+import { addInfo } from "./core/commands/helpers.js";import type { CommandContext } from "./core/commands/types.js";import {computeTimeoutAt,@@ -32,6 +33,7 @@ import {type ToolCallDisplay,type ToolExecution,} from "./core/types.js";+import { isTeamWorking } from "./ui/components/team-shared.js";import {getCurrentAccentColor,getCurrentThemeName,@@ -58,6 +60,8 @@ export interface AppSnapshot {pendingQuestion: PendingQuestion | null;lastError: string | null;isProcessing: boolean;+ /** 主会话流式进行中、等待确认,或 Team 模式下有成员处于工作中(Ctrl+C 应发 interrupt 而非预退出) */+ cancellableWork: boolean;isPaused: boolean;activeSubtasks: SubtaskState[];todos: TodoItem[];@@ -171,6 +175,9 @@ export class CliPiAppState {clearToolExecutionState: () => {this.clearToolExecutionState();},+ markRunningToolsInterrupted: () => {+ this.markRunningToolsInterrupted();+ },pushHistoryEntry: (entry) => {this.historyEntries.push(entry);},@@ -259,6 +266,19 @@ export class CliPiAppState {const isProcessing =this.streamingState === StreamingState.Responding ||this.streamingState === StreamingState.WaitingForConfirmation;+ const hasRunningTools = this.toolExecutionOrder.some((id) => {+ const ex = this.toolExecutions.get(id);+ return ex?.tool.status === "running";+ });+ const hasActiveSubtasks = [...this.activeSubtasks.values()].some(+ (s) => s.status !== "completed" && s.status !== "error",+ );+ const cancellableWork =+ isProcessing ||+ hasRunningTools ||+ hasActiveSubtasks ||+ this.evolutionStatus === "running" ||+ (this.mode === "team" && isTeamWorking(this.teamMemberEvents, this.teamMessageEvents));return {connectionStatus: this.connectionStatus,sessionId: this.sessionId,@@ -284,6 +304,7 @@ export class CliPiAppState {: null,lastError: this.lastError,isProcessing,+ cancellableWork,isPaused: this.streamingState === StreamingState.Paused,activeSubtasks: [...this.activeSubtasks.values()].sort((a, b) => a.index - b.index),todos: [...this.todos],@@ -556,8 +577,12 @@ readonly request = async <T = Record<string, unknown>>(return requestId;}- cancel(): void {+ cancel(options?: { showNotice?: boolean }): void {this.sendEventOnly("chat.interrupt", { intent: "cancel" });+ if (options?.showNotice === false) {+ return;+ }+ this.addItem(addInfo(this.sessionId, "Task interrupted", "i"));}resume(): void {@@ -707,6 +732,37 @@ readonly request = async <T = Record<string, unknown>>(}, delay + 10);}+ private markRunningToolsInterrupted(): void {+ const nowIso = new Date().toISOString();+ let changed = false;+ for (const [toolCallId, execution] of this.toolExecutions) {+ if (execution.tool.status !== "running") {+ continue;+ }+ const nextTool: ToolCallDisplay = {+ ...execution.tool,+ status: "completed",+ summary: execution.tool.summary?.trim() ? execution.tool.summary : "Interrupted",+ };+ this.toolExecutions.set(toolCallId, {+ ...execution,+ tool: nextTool,+ updatedAt: nowIso,+ });+ this.entries = upsertToolGroupDisplay(+ this.entries,+ execution.sessionId,+ execution.requestId,+ nextTool,+ );+ changed = true;+ }+ if (changed) {+ this.scheduleToolTimeoutCheck();+ this.emitChange();+ }+ }+private markTimedOutExecutions(): boolean {const nowIso = new Date().toISOString();const nowMs = Date.parse(nowIso);diff --git a/jiuwenclaw/cli/src/core/commands/builtins/cancel.ts b/jiuwenclaw/cli/src/core/commands/builtins/cancel.tsindex 816f4d355b..a615fdad11 100644--- a/jiuwenclaw/cli/src/core/commands/builtins/cancel.ts+++ b/jiuwenclaw/cli/src/core/commands/builtins/cancel.ts@@ -1,3 +1,4 @@+import { addInfo } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";export function createCancelCommand(): SlashCommand {@@ -10,6 +11,7 @@ export function createCancelCommand(): SlashCommand {kind: CommandKind.BUILT_IN,action: (ctx) => {ctx.sendEventOnly("chat.interrupt", { intent: "cancel" });+ ctx.addItem(addInfo(ctx.sessionId, "Task interrupted", "i"));},};}diff --git a/jiuwenclaw/cli/src/core/event-handlers.ts b/jiuwenclaw/cli/src/core/event-handlers.tsindex fb3dcb0578..7ad2dda9cd 100644--- a/jiuwenclaw/cli/src/core/event-handlers.ts+++ b/jiuwenclaw/cli/src/core/event-handlers.ts@@ -82,6 +82,8 @@ export interface AppEventDelegate {at?: string,): void;clearToolExecutionState(): void;+ /** 用户中断:将 running 的工具标为已结束,避免 TUI 继续转圈 */+ markRunningToolsInterrupted(): void;pushHistoryEntry(entry: HistoryItem): void;scheduleHistoryFlush(): void;safeRestoreHistory(sessionId: string): void;@@ -612,6 +614,7 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFramdelegate.setStreamingState(StreamingState.Idle);delegate.getActiveSubtasks().clear();delegate.setEvolutionStatus("idle");+ delegate.markRunningToolsInterrupted();} else if (intent === "pause") {delegate.setStreamingState(StreamingState.Paused);} else {diff --git a/jiuwenclaw/cli/src/index.ts b/jiuwenclaw/cli/src/index.tsindex f5aba8b8b6..1e9d750565 100644--- a/jiuwenclaw/cli/src/index.ts+++ b/jiuwenclaw/cli/src/index.ts@@ -48,15 +48,12 @@ let closed = false;let screen: AppScreen | null = null;async function cancelBeforeExit(): Promise<void> {- const snapshot = appState.getSnapshot();- if (!snapshot.isProcessing && !snapshot.isPaused) {+ if (appState.getSnapshot().connectionStatus !== "connected") {return;}- if (snapshot.connectionStatus !== "connected") {- return;- }- appState.cancel();- await new Promise((resolve) => setTimeout(resolve, 120));+ // 关 TUI 即请求服务端终止当前会话工作;idle 时一般为 no-op。+ appState.cancel({ showNotice: false });+ await new Promise((resolve) => setTimeout(resolve, 200));}async function closeUi(exitCode = 0): Promise<void> {diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.tsindex 41ba465821..12dccfc91f 100644--- a/jiuwenclaw/cli/src/ui/app-screen.ts+++ b/jiuwenclaw/cli/src/ui/app-screen.ts@@ -409,7 +409,7 @@ export class AppScreen implements Component, Focusable {? isPermissionRequest(pendingQuestion?.source, activeQuestion.question): false;- if (!pendingQuestion && snapshot.isProcessing && matchesKey(data, "escape")) {+ if (!pendingQuestion && snapshot.cancellableWork && matchesKey(data, "escape")) {this.state.cancel();return;}diff --git a/jiuwenclaw/cli/src/ui/keymap.ts b/jiuwenclaw/cli/src/ui/keymap.tsindex 714dfc50e7..8f09d464d9 100644--- a/jiuwenclaw/cli/src/ui/keymap.ts+++ b/jiuwenclaw/cli/src/ui/keymap.ts@@ -25,7 +25,7 @@ export const APP_SCREEN_KEY_BINDINGS: readonly KeyBinding[] = [description: "cancel active run or arm exit",run: (delegate) => {const snapshot = delegate.getSnapshot();- if (snapshot.isProcessing) {+ if (snapshot.cancellableWork) {delegate.cancel();} else {delegate.requestExit();diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.pyindex a927ffd827..0a394d894e 100644--- a/jiuwenclaw/gateway/message_handler.py+++ b/jiuwenclaw/gateway/message_handler.py@@ -366,23 +366,21 @@ class MessageHandler(ABC):if old_sid is None and not rids_cancelled:return- # 非流式场景不向 AgentServer 下发 cancel,避免无在途流式任务时触发不必要的中断逻辑。- if not bool(getattr(msg, "is_stream", False)):- logger.info(- "[MessageHandler] 跳过 AgentServer cancel(非流式): channel_id=%s session_id=%s",- msg.channel_id,- old_sid,- )+ sid_for_agent = (old_sid or "").strip()+ if not sid_for_agent:return+ # 即使网关侧已无活跃流式拉取任务(例如 Agent 正在执行 shell/工具),也必须通知 AgentServer,+ # 否则仅断开 CLI WebSocket 无法停止已派发的工作。+cancel_req = Message(id=f"interrupt_{int(time.time() * 1000):x}_{secrets.token_hex(3)}",type="req",channel_id=msg.channel_id,- session_id=old_sid,+ session_id=sid_for_agent,params={"intent": "cancel",- "session_id": old_sid,+ "session_id": sid_for_agent,},timestamp=time.time(),ok=True,@@ -397,6 +395,40 @@ class MessageHandler(ABC):env_interrupt = self.message_to_e2a(agent_msg)await self._send_interrupt_to_agent(env_interrupt)+ async def cancel_agent_sessions_on_disconnect(+ self,+ session_keys: list[tuple[str, str]],+ ) -> None:+ """TUI/WebSocket 异常断开时,取消仍绑定在该连接上的会话(与显式 chat.interrupt 对齐)。"""+ from jiuwenclaw.schema.message import Message, ReqMethod++ seen: set[str] = set()+ for _channel_id, session_id in session_keys:+ sid = (session_id or "").strip()+ if not sid or sid in seen:+ continue+ seen.add(sid)+ stub = Message(+ id=f"ws_drop_{int(time.time() * 1000):x}_{secrets.token_hex(4)}",+ type="req",+ channel_id=_channel_id,+ session_id=sid,+ params={"intent": "cancel", "session_id": sid},+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.CHAT_CANCEL,+ is_stream=False,+ )+ try:+ await self._cancel_agent_work_for_session(stub, sid)+ except Exception:+ logger.warning(+ "[MessageHandler] disconnect cancel failed: channel_id=%s session_id=%s",+ _channel_id,+ sid,+ exc_info=True,+ )+async def _new_session_cancel_and_notice(self,params: NewSessionCancelParams,diff --git a/jiuwenclaw/gateway/route_binding.py b/jiuwenclaw/gateway/route_binding.pyindex ccb8cc825c..302dece2c3 100644--- a/jiuwenclaw/gateway/route_binding.py+++ b/jiuwenclaw/gateway/route_binding.py@@ -15,4 +15,5 @@ class GatewayRouteBinding:inbound_interceptor: Callable[..., Awaitable[bool]] | None = Noneoutbound_interceptor: Callable[..., Awaitable[bool]] | None = Nonecleanup_handler: Callable[..., Any] | None = None+ disconnect_handler: Callable[..., Any] | None = Noneinstall: Callable[[Any], None] | None = None