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(goal): goal task exception handling
wncbdjd6b9daac694e
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 1e77a3b521..7fc97b9a22 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -200,6 +200,10 @@ class MessageHandler(ABC):self._stream_metadata: dict[str, dict[str, Any] | None] = {} # request_id -> request metadataself._stream_modes: dict[str, str] = {} # request_id -> modeself._stream_emits_processing_status: dict[str, bool] = {} # request_id -> emits chat.processing_status+ # request_id -> req_method value(如 chat.send / command.goal / history.get)。+ # 用于 processing_status=false 守卫:仅 chat.send(emit=True) 与 command.goal+ # 长流可挡住补发;history.get 等短只读流不得挡住。+ self._stream_methods: dict[str, str] = {}# 非流式 chat.send(如飞书 enable_streaming=False)任务追踪:rid -> mode。# 流式任务走 _stream_emits_processing_status;非流式 chat 不产生 processing_status,# 但同样是“用户发起的对话任务在跑”,配置保存锁须覆盖,故单列此集合。@@ -695,6 +699,7 @@ class MessageHandler(ABC):self._stream_sessions.pop(rid, None)self._stream_metadata.pop(rid, None)self._stream_emits_processing_status.pop(rid, None)+ self._stream_methods.pop(rid, None)self._stream_app_ids.pop(rid, None)self._stream_modes.pop(rid, None)@@ -2930,6 +2935,37 @@ class MessageHandler(ABC):return msg.req_method == ReqMethod.CHAT_SEND+ def _session_has_streams_blocking_processing_false(+ self, session_id: str | None+ ) -> bool:+ """同 session 是否还有应挡住 ``is_processing=false`` 补发的流.++ - ``chat.send``(emit=True):正常对话仍在跑+ - ``command.goal``(emit=False 长流):权限同意短流结束时不得误清前端,+ 否则会出现「前端已结束、后端 Goal 还在跑、后续 delta 收不到」++ ``history.get`` 等短只读流不计入,否则 chat 结束时若并发拉历史,会永远+ 等不到 false(这些流自身 emit=False,退出时也不会补发)。+ """+ from jiuwenswarm.common.schema.message import ReqMethod++ for active_rid, sid in self._stream_sessions.items():+ if sid != session_id:+ continue+ if self._stream_emits_processing_status.get(active_rid, True):+ return True+ if self._stream_methods.get(active_rid) == ReqMethod.COMMAND_GOAL.value:+ return True+ return False++ @staticmethod+ def _stream_method_value(msg: "Message") -> str:+ """Normalize ``msg.req_method`` to its wire value string."""+ req_method = getattr(msg, "req_method", None)+ if req_method is None:+ return ""+ return str(getattr(req_method, "value", req_method) or "")+async def _trigger_before_chat_request_hook(self, msg: "Message") -> None:if not self._should_trigger_before_chat_request_hook(msg):return@@ -3858,14 +3894,17 @@ class MessageHandler(ABC):# 若以下分支均不进入 _send_processing_status(其内部会广播),# 则前端保存锁可能卡在最后一次广播值,仅靠重连自愈。# cancelled 也会补发 is_processing=false(见下方),故不再排除 cancelled。+ # Block false only while chat.send or command.goal remains — not+ # arbitrary emit=False streams (e.g. history.get). Otherwise a short+ # permission-resume chat.send would clear is_processing while Goal+ # is still running; but history.get must not strand the spinner.+ session_blocks_processing_false = (+ self._session_has_streams_blocking_processing_false(session_id)+ )_will_broadcast = (emit_processing_statusand not has_processing_status_false- and not any(- sid == session_id- and self._stream_emits_processing_status.get(active_rid, True)- for active_rid, sid in self._stream_sessions.items()- )+ and not session_blocks_processing_false)logger.info("[task.global_running] stream 退出: rid=%s cancelled=%s emit=%s "@@ -3885,15 +3924,10 @@ class MessageHandler(ABC):# AgentServer 的 interrupt_result 可能要等很久(如命中 agent 首次初始化的同步阻塞窗口,# 事件循环读不出 cancel 消息),此时前端会一直转圈。主动补发一次 is_processing=false,# 让 TUI 立刻停转圈,不等 AgentServer 回 interrupt_result。- # session_has_active_tasks 守卫仍保证:同 session 还有其它活跃流时不误发 false。+ # 守卫:同 session 还有 chat.send 或 command.goal 时不误发 false+ # (避免权限同意短流在 Goal 仍跑时清前端;history.get 不挡)。if emit_processing_status and not has_processing_status_false:- # 检查该 session_id 是否还有活跃任务- session_has_active_tasks = any(- sid == session_id- and self._stream_emits_processing_status.get(active_rid, True)- for active_rid, sid in self._stream_sessions.items()- )- if not session_has_active_tasks:+ if not session_blocks_processing_false:await self._send_processing_status(rid, session_id, channel_id,is_processing=False, app_id=stream_app_id,@@ -3945,6 +3979,7 @@ class MessageHandler(ABC):"""Start a Gateway stream consumer and register stream bookkeeping."""emit_processing_status = self._should_emit_processing_status_for_stream(msg)self._stream_emits_processing_status[stream_rid] = emit_processing_status+ self._stream_methods[stream_rid] = self._stream_method_value(msg)self._stream_modes[stream_rid] = (msg.params.get("mode", "plan") if isinstance(msg.params, dict) else "plan")@@ -4180,6 +4215,7 @@ class MessageHandler(ABC):self._stream_sessions.clear()self._stream_metadata.clear()self._stream_emits_processing_status.clear()+ self._stream_methods.clear()self._stream_modes.clear()pending_disconnect_cancels = list(self._disconnect_cancel_tasks.values())for task in pending_disconnect_cancels:diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 3f999f4341..6f61da8e3b 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -1815,6 +1815,21 @@ class AgentWebSocketServer:))+ @staticmethod+ def _is_readonly_goal_get_request(request: AgentRequest) -> bool:+ """``command.goal`` + ``action=get``:只读查询,不得兜底新建 session metadata.++ 与 skills.list 同类问题:走 ``_prepare_code_mode_chat_turn`` 会触发+ ``sync_session_request_metadata`` 在无 metadata 时写出+ ``metadata.json``。get 仍需要真实 agent(可能从 checkpointer 读已有+ Goal),故不能整段塞进 ``_is_stateless_method_request``。+ """+ if request.req_method != ReqMethod.COMMAND_GOAL:+ return False+ params = request.params if isinstance(request.params, dict) else {}+ action = str(params.get("action") or "get").strip().lower()+ return action == "get"+async def _get_stateless_agent(self, channel_id: str) -> Any:"""为无状态请求取 agent,**不触发任何 mode 的 adapter 重建**.@@ -1840,6 +1855,8 @@ class AgentWebSocketServer:self,request: AgentRequest,channel_id: str,+ *,+ sync_metadata: bool = True,) -> tuple[str, str | None, Any]:"""Mode resolution and correct agent instance selection."""# [新增] 在 _apply_resolved_mode_to_request 把 canonical mode 写回 params 之前,@@ -1860,12 +1877,30 @@ class AgentWebSocketServer:canonical_mode = (request.params.get("mode") if isinstance(request.params, dict) else None)- project_dir = _sync_chat_request_metadata(- request,- requested_project_dir,- canonical_mode if canonical_mode else mode,- explicit_mode_provided=explicit_mode_provided,- )+ if sync_metadata:+ project_dir = _sync_chat_request_metadata(+ request,+ requested_project_dir,+ canonical_mode if canonical_mode else mode,+ explicit_mode_provided=explicit_mode_provided,+ )+ else:+ # Read-only path (e.g. command.goal get): never create/update+ # metadata.json. Prefer request project_dir, else locked disk value.+ project_dir = requested_project_dir+ if not (isinstance(project_dir, str) and project_dir.strip()):+ sid = str(request.session_id or "").strip()+ if sid:+ from jiuwenswarm.server.runtime.session.session_metadata import (+ get_session_metadata,+ )++ meta = get_session_metadata(+ sid, cache_bust=True, enable_writeback=False+ )+ locked = meta.get("project_dir") if isinstance(meta, dict) else None+ if isinstance(locked, str) and locked.strip():+ project_dir = locked.strip()if isinstance(project_dir, str) and project_dir.strip():project_dir = project_dir.strip()request.params["project_dir"] = project_dir@@ -2031,20 +2066,27 @@ class AgentWebSocketServer:)return+ readonly_goal_get = self._is_readonly_goal_get_request(request)mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(- request, channel_id+ request,+ channel_id,+ sync_metadata=not readonly_goal_get,)- restored_plan = await self._ensure_code_mode_state(request, mode, sub_mode, agent)- if restored_plan:- await self._push_plan_mode_exited(request)+ if not readonly_goal_get:+ restored_plan = await self._ensure_code_mode_state(+ request, mode, sub_mode, agent+ )+ if restored_plan:+ await self._push_plan_mode_exited(request)resp = Nonetry:resp = await agent.process_message(request)finally:# Push plan.mode_exited if exit_plan_mode restored mode during processing- await self._check_post_process_plan_exit(request, agent)+ if not readonly_goal_get:+ await self._check_post_process_plan_exit(request, agent)# V2: 非流式响应回带请求侧 agent_ref,供 gateway 3 元组路由(设计 §6.3)。# is None 守卫:保留 agent 层显式设置的 agent_ref(如 team 模式由事件派生)。@@ -2072,16 +2114,22 @@ class AgentWebSocketServer:# 无状态流式请求(skills / skilldev / plugins / symphony)不需要 mode 解析和# code mode 状态管理,直接走 process_message_stream 即可。用轻量 agent 获取,# 不触发 adapter 重建(恢复 8f54b26a7 误删的短路,并修正 5084467df 触发重建的缺陷)。+ readonly_goal_get = self._is_readonly_goal_get_request(request)if self._is_stateless_method_request(request):agent = await self._get_stateless_agent(channel_id)else:mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(- request, channel_id+ request,+ channel_id,+ sync_metadata=not readonly_goal_get,)- restored_plan = await self._ensure_code_mode_state(request, mode, sub_mode, agent)- if restored_plan:- await self._push_plan_mode_exited(request)+ if not readonly_goal_get:+ restored_plan = await self._ensure_code_mode_state(+ request, mode, sub_mode, agent+ )+ if restored_plan:+ await self._push_plan_mode_exited(request)chunk_count = 0# 心跳控制:当有真实 chunk 发送时重置,空闲时发送心跳@@ -2195,7 +2243,8 @@ class AgentWebSocketServer:if not entries:self._session_stream_tasks.pop(session_id, None)# Push plan.mode_exited if exit_plan_mode restored mode during processing- await self._check_post_process_plan_exit(request, agent)+ if not readonly_goal_get:+ await self._check_post_process_plan_exit(request, agent)logger.info("[AgentWebSocketServer] 流式响应已发送: request_id=%s 共 %s 个 chunk",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 6094328aa2..0ebcea8c43 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -2105,25 +2105,13 @@ class JiuWenSwarm:# proactive_recommendation 是系统触发的推荐指令(不是用户说的话),不写 user# history——否则刷新页面会显示"[主动推荐指令] xxx"这种用户没说过的消息。- # command.goal: only set records the objective as a user turn; resume/- # pause/clear/get remain control traffic.+ # command.goal set history is written only after a successful set inside+ # the DeepAdapter stream path (same success gate as unary process_message).params_for_history = request.params if isinstance(request.params, dict) else {}- if request.req_method == ReqMethod.COMMAND_GOAL:- goal_action = str(params_for_history.get("action", "") or "").strip().lower()- if goal_action == "set":- objective = str(params_for_history.get("objective") or "").strip()- if objective:- append_history_record(- session_id=session_id,- request_id=request.request_id,- channel_id=request.channel_id,- role="user",- content=objective,- timestamp=time.time(),- channel_metadata=request.metadata,- mode=params_for_history.get("mode", "unknown"),- )- elif _should_record_user_history(params_for_history):+ if (+ request.req_method != ReqMethod.COMMAND_GOAL+ and _should_record_user_history(params_for_history)+ ):append_history_record(session_id=session_id,request_id=request.request_id,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 163b74652b..bb9f0aee6b 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -5645,10 +5645,14 @@ class JiuWenSwarmDeepAdapter:return startedreturn bool(getattr(self._instance, "_interaction_started", False))- def _has_active_goal_interaction(self) -> bool:- """Whether the shared DeepAgent still owns an active goal interaction."""- if self._has_active_goal_round():- return True+ def _goal_record_is_active(self) -> bool:+ """Whether GoalRecord is ACTIVE (persistent objective still running).++ Unlike ``_has_active_goal_interaction``, this ignores an in-flight goal+ round. Used when deciding whether to demote ``chat.final``: after user+ cancel/pause the record is no longer ACTIVE, so a terminal final must+ reach the frontend even while the aborted round is still unwinding.+ """if self._instance is None:return Falsemanager = getattr(self._instance, "goal_manager", None)@@ -5658,18 +5662,28 @@ class JiuWenSwarmDeepAdapter:peek = getattr(manager, "peek", None)record = peek() if callable(peek) else manager.get_store().load()except Exception:- logger.debug("[Goal] failed to inspect active goal status", exc_info=True)+ logger.debug("[Goal] failed to inspect goal record status", exc_info=True)return Falsestatus = getattr(record, "status", None)status_value = getattr(status, "value", status)return status_value == "active"+ def _has_active_goal_interaction(self) -> bool:+ """Whether the shared DeepAgent still owns an active goal interaction."""+ if self._has_active_goal_round():+ return True+ return self._goal_record_is_active()+def _adapt_goal_intermediate_final(self, parsed: dict | None) -> dict | None:if not isinstance(parsed, dict):return parsedif parsed.get("event_type") != "chat.final":return parsed- if not self._has_active_goal_interaction():+ # Demote only while the GoalRecord remains ACTIVE. Do not key off an+ # in-flight goal round: user cancel pauses the record first, then+ # aborts the round — finals during unwind must stay terminal so the+ # frontend can close the dialog.+ if not self._goal_record_is_active():return parsedadapted = dict(parsed)adapted["event_type"] = "chat.delta"@@ -5736,6 +5750,44 @@ class JiuWenSwarmDeepAdapter:mode = self._resolve_input_dispatch_mode(params)return mode in (InputDispatchMode.STEER, InputDispatchMode.FOLLOW_UP)+ @staticmethod+ def _is_interrupt_resume_dispatch(params: Any) -> bool:+ """HITL answers must inject into the existing interaction when possible.++ Permission / confirm / ask-user resumes arrive as ``chat.send`` with+ ``answers``. When a Goal (or other) consumer already holds the output+ lease, ``attach_output`` returns ``None`` — we must still ``send_input``+ so InteractiveInput reaches DeepAgent; otherwise the tool stays blocked+ while Goal keeps running.+ """+ if not isinstance(params, dict):+ return False+ source = str(params.get("source") or "").strip()+ answers = params.get("answers")+ request_id = str(params.get("request_id") or "").strip()+ if (+ bool(request_id)+ and isinstance(answers, list)+ and source in {+ "ask_user_interrupt",+ "confirm_interrupt",+ "permission_interrupt",+ "evolution_interrupt",+ }+ ):+ return True+ from jiuwenswarm.gateway.message_handler.evolution_approval import (+ is_interrupt_evolution_approval_answer_payload,+ )++ return is_interrupt_evolution_approval_answer_payload(params)++ def _should_inject_into_existing_interaction(self, params: Any) -> bool:+ """Whether input must be sent even when this request cannot take the lease."""+ return self._is_ack_only_dispatch(params) or self._is_interrupt_resume_dispatch(+ params+ )+@staticmethoddef _structured_goal_op_from_request(request: AgentRequest,@@ -6045,8 +6097,31 @@ class JiuWenSwarmDeepAdapter:Closing the owning interaction output stream is the primary shutdownpath for streaming hosts. This unary handler is the idempotentfallback: ``cancel_round`` aborts the current user or goal attempt- without clearing GoalRecord.+ without clearing GoalRecord. For user cancel, pause an ACTIVE goal+ first so the GoalBar stops continuing after the round is aborted."""+ paused_goal_payload: dict[str, Any] | None = None+ if intent == "cancel":+ try:+ goal_manager = self._get_goal_manager()+ if goal_manager is not None:+ record = await goal_manager.get()+ status = getattr(record, "status", None) if record is not None else None+ if status is GoalStatus.ACTIVE:+ paused = await goal_manager.pause()+ paused_goal_payload = self._goal_record_payload(paused)+ logger.info(+ "[JiuWenSwarmDeepAdapter] interrupt(cancel): paused ACTIVE goal "+ "session=%s",+ request.session_id,+ )+ except Exception:+ logger.exception(+ "[JiuWenSwarmDeepAdapter] interrupt(cancel): goal pause failed "+ "session=%s",+ request.session_id,+ )+cancelled = Falsetry:cancelled = await self._instance.cancel_round(@@ -6074,6 +6149,11 @@ class JiuWenSwarmDeepAdapter:}if new_input:payload["new_input"] = new_input+ if paused_goal_payload is not None:+ # Always return the paused snapshot on the interrupt response so+ # Web/TUI can refresh GoalBar even when no output lease remains+ # to receive goal.updated.+ payload["goal"] = paused_goal_payload# Best-effort todo cancellation for user cancel (does not touch runtime).if cancelled and intent == "cancel" and request.session_id:@@ -6817,6 +6897,36 @@ class JiuWenSwarmDeepAdapter:return "Goal resumed." if goal is not None else "No goal in this session."return "Goal set." if goal is not None else "Goal was not set."+ @staticmethod+ def _record_goal_set_history_if_needed(+ request: AgentRequest,+ *,+ action: str | None,+ result_type: str | None,+ goal_payload: dict[str, Any] | None,+ ) -> None:+ """Write objective as a user history turn only after a successful set."""+ if str(action or "").strip().lower() != "set":+ return+ if result_type in {"goal_error", "goal_confirm_required", None}:+ return+ if not isinstance(goal_payload, dict):+ return+ objective = str(goal_payload.get("objective") or "").strip()+ if not objective:+ return+ params = request.params if isinstance(request.params, dict) else {}+ append_history_record(+ session_id=request.session_id or "default",+ request_id=request.request_id,+ channel_id=request.channel_id,+ role="user",+ content=objective,+ timestamp=time.time(),+ channel_metadata=request.metadata,+ mode=params.get("mode", "unknown"),+ )+@staticmethoddef _interaction_goal_updated_payload(payload: Any) -> dict[str, Any]:"""Normalize goal updates to the public Web/TUI payload shape."""@@ -6895,7 +7005,13 @@ class JiuWenSwarmDeepAdapter:}try:if normalized_action == "get":- goal = await goal_manager.get()+ # Read-only status query: use the lock-free ``peek`` snapshot so a+ # long-running / stuck goal round (which holds the shared+ # interaction control lock across ``set``/``clear`` -> abort) can+ # never block a plain ``command.goal get`` up to the unary timeout.+ # ``await get()`` would serialize on that same control lock.+ peek = getattr(goal_manager, "peek", None)+ goal = peek() if callable(peek) else await goal_manager.get()elif normalized_action == "set":goal = await goal_manager.set(objective or "",@@ -6904,17 +7020,84 @@ class JiuWenSwarmDeepAdapter:max_attempts=max_attempts,)elif normalized_action == "pause":+ before = await goal_manager.get()+ if before is None:+ return {+ "result_type": "goal_error",+ "action": normalized_action,+ "error_code": "no_goal",+ "error": "No goal in this session; cannot pause.",+ "goal": None,+ }+ before_status = before.statusgoal = await goal_manager.pause()+ goal_payload = self._goal_record_payload(goal)+ if before_status is not GoalStatus.ACTIVE:+ status_value = getattr(before_status, "value", str(before_status))+ return {+ "result_type": "goal_error",+ "action": normalized_action,+ "error_code": "invalid_state",+ "error": (+ f"Goal is {status_value}; only active goals can be paused."+ ),+ "goal": goal_payload,+ }+ return {+ "result_type": "goal_control",+ "action": normalized_action,+ "goal": goal_payload,+ "output": "Goal paused.",+ }elif normalized_action == "resume":+ before = await goal_manager.get()+ if before is None:+ return {+ "result_type": "goal_error",+ "action": normalized_action,+ "error_code": "no_goal",+ "error": "No goal in this session; cannot resume.",+ "goal": None,+ }+ before_status = before.status+ if before_status is GoalStatus.ACTIVE:+ goal_payload = self._goal_record_payload(before)+ return {+ "result_type": "goal_control",+ "action": normalized_action,+ "goal": goal_payload,+ "output": "Goal already active.",+ }+ if before_status not in (GoalStatus.PAUSED, GoalStatus.BLOCKED):+ status_value = getattr(before_status, "value", str(before_status))+ return {+ "result_type": "goal_error",+ "action": normalized_action,+ "error_code": "invalid_state",+ "error": (+ f"Goal is {status_value}; only paused/blocked goals "+ "can be resumed."+ ),+ "goal": self._goal_record_payload(before),+ }goal = await goal_manager.resume()elif normalized_action == "clear":removed = await goal_manager.clear()+ if removed is None:+ return {+ "result_type": "goal_error",+ "action": normalized_action,+ "error_code": "no_goal",+ "error": "No goal in this session; nothing to clear.",+ "goal": None,+ "cleared_goal": None,+ }return {"result_type": "goal_control","action": normalized_action,"goal": None,"cleared_goal": self._goal_record_payload(removed),- "output": self._format_goal_control_message(normalized_action, None),+ "output": "Goal cleared.",}else:return {@@ -7256,8 +7439,8 @@ class JiuWenSwarmDeepAdapter:metadata=request.metadata,)interaction_stream = await self._instance.attach_output()- elif self._is_ack_only_dispatch(request.params):- # Steal the reader if idle; otherwise inject into the existing stream.+ elif self._should_inject_into_existing_interaction(request.params):+ # Idle → become the reader; busy → inject into the existing stream.interaction_stream = await self._instance.attach_output()await self._instance.send_input(SendInputRequest(@@ -7805,6 +7988,12 @@ class JiuWenSwarmDeepAdapter:},is_complete=False,)+ self._record_goal_set_history_if_needed(+ request,+ action=goal_action if isinstance(goal_action, str) else None,+ result_type=result_type if isinstance(result_type, str) else None,+ goal_payload=goal_snapshot if isinstance(goal_snapshot, dict) else None,+ )# Only keep the lease when set/resume left an ACTIVE goal to run.if result_type != "goal_stream" or interaction_stream is None:if interaction_stream is not None:@@ -7826,6 +8015,12 @@ class JiuWenSwarmDeepAdapter:},is_complete=False,)+ self._record_goal_set_history_if_needed(+ request,+ action=goal_action if isinstance(goal_action, str) else None,+ result_type="goal_stream" if goal_stream_request else "goal_control",+ goal_payload=goal_snapshot if isinstance(goal_snapshot, dict) else None,+ )if attach_goal_request:gm = self._get_goal_manager()peek = getattr(gm, "peek", None) if gm is not None else None@@ -7842,8 +8037,10 @@ class JiuWenSwarmDeepAdapter:yield chunkinteraction_stream_abort = Falsereturn- elif self._is_ack_only_dispatch(request.params):+ elif self._should_inject_into_existing_interaction(request.params):# Idle → become the reader; busy → inject and accept.+ # Interrupt resumes (permission/confirm/ask-user) must send_input+ # even when Goal already holds the output lease.interaction_stream = await self._instance.attach_output()await self._instance.send_input(SendInputRequest(@@ -8052,9 +8249,11 @@ class JiuWenSwarmDeepAdapter:)if accumulated_text:+ # Same rule as _adapt_goal_intermediate_final: only keep the+ # host flush as delta while GoalRecord is still ACTIVE.final_event_type = ("chat.delta"- if self._has_active_goal_interaction()+ if self._goal_record_is_active()else "chat.final")yield AgentResponseChunk(@@ -8090,6 +8289,9 @@ class JiuWenSwarmDeepAdapter:# InteractionOutputStream.close() in ``finally`` owns the targeted# round abort. Do not issue a second adapter-level abort here:# it can race with a newly attached output consumer.+ # Do not yield chat.final here: CancelledError often means the+ # consumer is already tearing down, so the frame may never reach+ # the frontend; user Stop already closes UI via interrupt_result.if _debug_logger is not None:_debug_logger.end_run(status="cancelled")raisediff --git a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.pyindex a55cf94e43..cc8e2f7d11 100644--- a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py+++ b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py@@ -80,6 +80,74 @@ async def test_cancel_runs_teardown_when_session_not_in_active_counter(assert response.payload["success"] is True+async def test_interaction_cancel_pauses_active_goal_before_cancel_round() -> None:+ """User stop should pause ACTIVE Goal then cancel_round; payload carries goal."""+ from openjiuwen.harness.goal.schema import GoalRecord, GoalStatus++ paused_record = GoalRecord.create(session_id="sess-goal", objective="keep going")+ paused_record.status = GoalStatus.PAUSED+ active_record = GoalRecord.create(session_id="sess-goal", objective="keep going")+ active_record.status = GoalStatus.ACTIVE++ goal_manager = MagicMock()+ goal_manager.get = AsyncMock(return_value=active_record)+ goal_manager.pause = AsyncMock(return_value=paused_record)++ instance = MagicMock()+ instance._interaction_started = True+ instance.goal_manager = goal_manager+ instance.cancel_round = AsyncMock(return_value=True)++ adapter = _make_adapter(+ _active_session_ids={"sess-goal": 1},+ _stream_event_rail=MagicMock(),+ _instance=instance,+ )+ adapter._cancel_pending_todos = AsyncMock(return_value=None)++ response = await adapter.process_interrupt(+ AgentRequest(+ request_id="req-stop",+ channel_id="web",+ session_id="sess-goal",+ req_method=ReqMethod.CHAT_CANCEL,+ params={"intent": "cancel", "mode": "agent"},+ )+ )++ goal_manager.pause.assert_awaited_once()+ instance.cancel_round.assert_awaited_once_with(reason="user_cancel")+ assert response.payload["event_type"] == "chat.interrupt_result"+ assert response.payload["goal"]["status"] == "paused"+ assert response.payload["goal"]["objective"] == "keep going"+++async def test_interaction_cancel_skips_pause_when_no_goal() -> None:+ goal_manager = MagicMock()+ goal_manager.get = AsyncMock(return_value=None)+ goal_manager.pause = AsyncMock()++ instance = MagicMock()+ instance._interaction_started = True+ instance.goal_manager = goal_manager+ instance.cancel_round = AsyncMock(return_value=True)++ adapter = _make_adapter(+ _active_session_ids={"sess-x": 1},+ _stream_event_rail=MagicMock(),+ _instance=instance,+ )+ adapter._cancel_pending_todos = AsyncMock(return_value=None)++ response = await adapter.process_interrupt(_build_cancel_request("sess-x"))++ goal_manager.pause.assert_not_awaited()+ instance.cancel_round.assert_awaited_once()+ assert "goal" not in response.payload++@pytest.mark.asyncioasync def test_unmark_skips_rail_cleanup_when_stream_consumer_cancelled() -> None:rail = MagicMock()diff --git a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py b/tests/unit_tests/agentserver/test_goal_runtime_adapter.pyindex 6bf2a31dd3..24d24375c3 100644--- a/tests/unit_tests/agentserver/test_goal_runtime_adapter.py+++ b/tests/unit_tests/agentserver/test_goal_runtime_adapter.py@@ -65,13 +65,17 @@ class _FakeGoals:async def pause(self) -> GoalRecord | None:self.calls.append(("pause", None))- if self.record is not None:+ if self.record is None:+ return None+ if self.record.status is GoalStatus.ACTIVE:self.record.status = GoalStatus.PAUSEDreturn self.recordasync def resume(self) -> GoalRecord | None:self.calls.append(("resume", None))- if self.record is not None and self.record.status is GoalStatus.PAUSED:+ if self.record is None:+ return None+ if self.record.status in (GoalStatus.PAUSED, GoalStatus.BLOCKED):self.record.status = GoalStatus.ACTIVEreturn self.record@@ -130,9 +134,61 @@ async def test_resume_without_goal_is_a_normal_control_response() -> None:)assert result is not None- assert result["result_type"] == "goal_control"+ assert result["result_type"] == "goal_error"+ assert result["error_code"] == "no_goal"assert result["goal"] is None- assert result["output"] == "No goal in this session."+ assert "cannot resume" in str(result["error"])+++async def test_pause_without_goal_returns_no_goal_error() -> None:+ result = await _adapter(_FakeGoals()).handle_goal_command_structured(+ {"action": "pause"},+ session_id="session-1",+ )+ assert result is not None+ assert result["result_type"] == "goal_error"+ assert result["error_code"] == "no_goal"+++async def test_clear_without_goal_returns_no_goal_error() -> None:+ result = await _adapter(_FakeGoals()).handle_goal_command_structured(+ {"action": "clear"},+ session_id="session-1",+ )+ assert result is not None+ assert result["result_type"] == "goal_error"+ assert result["error_code"] == "no_goal"+++async def test_resume_completed_goal_returns_invalid_state() -> None:+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="done")+ goals.record.status = GoalStatus.COMPLETED+ result = await _adapter(goals).handle_goal_command_structured(+ {"action": "resume"},+ session_id="session-1",+ )+ assert result is not None+ assert result["result_type"] == "goal_error"+ assert result["error_code"] == "invalid_state"+ assert result["goal"]["status"] == "completed"+++async def test_pause_non_active_goal_returns_invalid_state() -> None:+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="paused")+ goals.record.status = GoalStatus.PAUSED+ result = await _adapter(goals).handle_goal_command_structured(+ {"action": "pause"},+ session_id="session-1",+ )+ assert result is not None+ assert result["result_type"] == "goal_error"+ assert result["error_code"] == "invalid_state"@pytest.mark.asyncio@@ -195,6 +251,29 @@ def test_runtime_events_are_adapted_without_leaking_runtime_objects() -> None:}+def test_empty_answer_chunk_is_dropped_not_emitted_as_chat_final() -> None:+ """Empty answer is not a UI closer — discard for both Goal and normal chat."""+ assert (+ JiuWenSwarmDeepAdapter._parse_stream_chunk(+ {+ "type": "answer",+ "payload": {"output": {"output": "", "chunked": False}},+ }+ )+ is None+ )+ assert (+ JiuWenSwarmDeepAdapter._parse_stream_chunk(+ {+ "type": "answer",+ "payload": {"output": {"output": " ", "chunked": False}},+ },+ _has_streamed_content=True,+ )+ is None+ )++def test_runtime_goal_update_payload_is_always_nested_under_goal() -> None:goal = GoalRecord.create(session_id="session-1", objective="ship the feature").to_dict()updated = JiuWenSwarmDeepAdapter._parse_stream_chunk(@@ -253,6 +332,50 @@ def test_active_goal_demotes_intermediate_chat_final_to_delta() -> None:}+def test_interrupt_resume_dispatch_injects_even_without_output_lease() -> None:+ """Permission answers must send_input when Goal already holds the lease."""+ assert JiuWenSwarmDeepAdapter._is_interrupt_resume_dispatch(+ {+ "source": "permission_interrupt",+ "request_id": "call_1",+ "answers": [{"selected_options": ["allow_once"]}],+ }+ )+ adapter = _adapter(_FakeGoals())+ assert adapter._should_inject_into_existing_interaction(+ {+ "source": "permission_interrupt",+ "request_id": "call_1",+ "answers": [{"selected_options": ["allow_once"]}],+ }+ )+ assert not adapter._should_inject_into_existing_interaction(+ {"query": "hello", "mode": "agent"}+ )+++def test_paused_goal_keeps_chat_final_terminal_even_if_round_still_unwinding() -> None:+ """User cancel pauses GoalRecord first; finals during abort must stay final."""+ goals = _FakeGoals()+ goals.record = GoalRecord.create(session_id="session-1", objective="ship the feature")+ goals.record.status = GoalStatus.PAUSED+ adapter = _adapter(goals)+ # Simulate an in-flight goal round still unwinding after pause+cancel.+ adapter._instance.active_round = SimpleNamespace(run_kind="goal")+ adapter._instance.interaction_started = True++ payload = adapter._adapt_goal_intermediate_final(+ {"event_type": "chat.final", "content": "cancelled output"}+ )++ assert payload == {+ "event_type": "chat.final",+ "content": "cancelled output",+ }+ assert adapter._has_active_goal_interaction() is True+ assert adapter._goal_record_is_active() is False++def test_internal_goal_resume_is_not_recorded_as_user_history() -> None:assert _should_record_user_history({@@ -308,6 +431,40 @@ def test_chat_send_does_not_map_to_structured_goal_op() -> None:assert JiuWenSwarmDeepAdapter._structured_goal_op_from_request(req) is None+def test_readonly_goal_get_skips_metadata_sync_flag() -> None:+ """command.goal get is read-only; set/resume/pause/clear are not."""+ from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer++ get_req = AgentRequest(+ request_id="g1",+ channel_id="web",+ session_id="ghost_goal_get",+ req_method=ReqMethod.COMMAND_GOAL,+ params={"action": "get", "mode": "agent"},+ )+ assert AgentWebSocketServer._is_readonly_goal_get_request(get_req) is True+ # Default action is get when omitted.+ assert AgentWebSocketServer._is_readonly_goal_get_request(+ AgentRequest(+ request_id="g2",+ channel_id="web",+ session_id="ghost_goal_get",+ req_method=ReqMethod.COMMAND_GOAL,+ params={},+ )+ ) is True+ for action in ("set", "resume", "pause", "clear"):+ assert AgentWebSocketServer._is_readonly_goal_get_request(+ AgentRequest(+ request_id=f"a-{action}",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.COMMAND_GOAL,+ params={"action": action},+ )+ ) is False++def test_web_channel_does_not_treat_goal_slash_as_intent() -> None:assert (JiuWenSwarmDeepAdapter._parse_goal_slash_intent("/goal set write a report")diff --git a/tests/unit_tests/gateway/test_message_handler_evolution.py b/tests/unit_tests/gateway/test_message_handler_evolution.pyindex 446d5d56d8..0fbf4ef740 100644--- a/tests/unit_tests/gateway/test_message_handler_evolution.py+++ b/tests/unit_tests/gateway/test_message_handler_evolution.py@@ -460,6 +460,92 @@ def test_processing_status_is_only_emitted_for_chat_streams() -> None:) is False++async def test_permission_resume_stream_keeps_processing_while_goal_stream_active() -> None:+ """command.goal (emit=False) still blocks processing_status=false on permission ack."""+ handler = _TestMessageHandler.create()+ _FakeAgentClient.stream_payloads = [+ {"event_type": "runtime.accepted", "request_id": "perm-1"},+ ]+ # Seed an in-flight Goal stream on the same session (emit=False).+ getattr(handler, "_stream_emits_processing_status")["goal-1"] = False+ getattr(handler, "_stream_methods")["goal-1"] = ReqMethod.COMMAND_GOAL.value+ getattr(handler, "_stream_sessions")["goal-1"] = "sess-goal"+ getattr(handler, "_stream_modes")["goal-1"] = "agent"+ getattr(handler, "_stream_channels")["goal-1"] = "web"++ await handler.process_stream(+ SimpleNamespace(+ request_id="perm-1",+ channel="web",+ method=ReqMethod.CHAT_SEND.value,+ params={+ "source": "permission_interrupt",+ "request_id": "call_perm_1",+ "answers": [{"selected_options": ["allow_once"]}],+ },+ ),+ "sess-goal",+ None,+ emit_processing_status=True,+ )++ payloads = await _drain_robot_payloads_for_permission_resume(handler)+ assert not any(+ p.get("event_type") == "chat.processing_status"+ and p.get("is_processing") is False+ for p in payloads+ )+ # Goal tracking must still be present after the short resume stream exits.+ assert "goal-1" in getattr(handler, "_stream_sessions")+++async def test_chat_send_clears_processing_while_history_get_stream_active() -> None:+ """history.get must not block processing_status=false (unlike command.goal)."""+ handler = _TestMessageHandler.create()+ _FakeAgentClient.stream_payloads = [+ {"event_type": "chat.final", "content": "done"},+ ]+ getattr(handler, "_stream_emits_processing_status")["hist-1"] = False+ getattr(handler, "_stream_methods")["hist-1"] = ReqMethod.HISTORY_GET.value+ getattr(handler, "_stream_sessions")["hist-1"] = "sess-chat"+ getattr(handler, "_stream_modes")["hist-1"] = "agent"+ getattr(handler, "_stream_channels")["hist-1"] = "web"++ await handler.process_stream(+ SimpleNamespace(+ request_id="chat-1",+ channel="web",+ method=ReqMethod.CHAT_SEND.value,+ params={"query": "hello"},+ ),+ "sess-chat",+ None,+ emit_processing_status=True,+ )++ payloads = await _drain_robot_payloads_for_permission_resume(handler)+ assert any(+ p.get("event_type") == "chat.processing_status"+ and p.get("is_processing") is False+ for p in payloads+ )+ assert "hist-1" in getattr(handler, "_stream_sessions")+++async def _drain_robot_payloads_for_permission_resume(handler: _TestMessageHandler) -> list[dict]:+ payloads: list[dict] = []+ while True:+ out = await handler.consume_robot_messages(timeout=0)+ if out is None:+ break+ if isinstance(out.payload, dict):+ payloads.append(out.payload)+ return payloads++def test_queued_supplement_message_instructs_todo_continuation():handler = _TestMessageHandler.create()msg = _message(ReqMethod.CHAT_CANCEL)