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

agentserver: 修复审批中断时 plan 模式误退出与工具结果假失败

NickFuryXXX14f8ebec5189
diff --git a/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py b/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py
index 9a2fc2eeea..f3444ff7e6 100644
--- a/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py
+++ b/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py
@@ -18,6 +18,10 @@ from openjiuwen.core.common.logging import logger
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.rails.agent_mode_rail import AgentModeRail
+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
+ extract_tool_interrupt,
+)
+
if TYPE_CHECKING:
from openjiuwen.harness.deep_agent import DeepAgent
@@ -100,11 +104,25 @@ class CodeAgentModeRail(AgentModeRail):
``_skip_tool`` from ``ctx.extra`` before ``after_tool_call`` runs.
``PlanApprovalInterruptRail`` sets ``_plan_rejected`` which persists
through the pop.
+
+ The ``@rail`` decorator fires ``AFTER_TOOL_CALL`` from a ``finally``
+ block, so this hook also runs when ``PlanApprovalInterruptRail``
+ suspends the call for approval. In that case the tool has not
+ executed yet and the user has answered nothing, so plan mode must
+ stay untouched until the resumed call runs.
"""
tool_name = ctx.inputs.tool_name
agent = self._agent
rejected = ctx.extra.get("_plan_rejected", False)
+ if self._is_pending_user_interrupt(ctx):
+ logger.info(
+ "[CodeAgentModeRail] '%s' suspended for user approval; "
+ "keeping plan mode until the resumed call executes",
+ tool_name,
+ )
+ return
+
# Segment 1: register / unregister task_tool (same as parent)
if tool_name == "enter_plan_mode" and not rejected:
self._register_task_tool(agent)
@@ -131,6 +149,17 @@ class CodeAgentModeRail(AgentModeRail):
"[CodeAgentModeRail] Failed to restore mode: %s", exc
)
+ @staticmethod
+ def _is_pending_user_interrupt(ctx: AgentCallbackContext) -> bool:
+ """Whether this tool call ended by suspending for user input.
+
+ ``ToolCallResilienceRail.on_tool_exception`` fills ``tool_result``
+ with a failure placeholder before ``AFTER_TOOL_CALL`` runs, so a
+ ``tool_result is not None`` check cannot tell a suspended call apart
+ from an executed one — the pending interrupt on ``ctx.exception`` can.
+ """
+ return extract_tool_interrupt(getattr(ctx, "exception", None)) is not None
+
@staticmethod
def _parse_switch_mode_target(ctx: AgentCallbackContext) -> str:
"""Parse the target mode from a switch_mode tool-call context."""
diff --git a/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.py b/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.py
index 0ae3010bc3..addd4f9629 100644
--- a/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.py
+++ b/jiuwenswarm/agents/harness/code/rails/code_confirm_interrupt_rail.py
@@ -70,6 +70,21 @@ def build_confirm_interrupt_message(tool_name: str, tool_args: dict[str, Any] |
class CodeConfirmInterruptRail(ConfirmInterruptRail):
"""ConfirmInterruptRail with tool-specific confirmation copy for code mode."""
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._agent: Any | None = None
+
+ def init(self, agent: Any) -> None:
+ """Capture the stateful Code/DeepAgent rather than callback ReActAgent."""
+ super().init(agent)
+ self._agent = agent
+
+ def uninit(self, agent: Any) -> None: # noqa: ARG002
+ try:
+ super().uninit(agent)
+ finally:
+ self._agent = None
+
async def resolve_interrupt(
self,
ctx: AgentCallbackContext,
@@ -103,16 +118,18 @@ class CodeConfirmInterruptRail(ConfirmInterruptRail):
):
if tool_call is None or (tool_call.name or "") != "switch_mode":
return None
- agent = ctx.agent
+ args = self._parse_tool_args(tool_call)
+ target = str(args.get("mode") or args.get("target_mode") or "").strip()
+ # Entering plan mode is valid regardless of current plan state and must
+ # not touch state APIs on the callback's outer ReActAgent.
+ if target not in {"normal", "auto"}:
+ return None
+ agent = self._agent
if agent is None:
return None
plan_state = agent.load_state(ctx.session).plan_mode
if plan_state.mode != "plan":
return None
- args = self._parse_tool_args(tool_call)
- target = str(args.get("mode") or args.get("target_mode") or "").strip()
- if target not in {"normal", "auto"}:
- return None
language = "cn"
builder = getattr(agent, "system_prompt_builder", None)
if builder is not None and getattr(builder, "language", "cn") == "en":
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index cc32967d5a..b3e28f30c4 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -123,21 +123,36 @@ def _parse_tool_call_arguments(tool_call: Any) -> dict[str, Any]:
return {}
-def _extract_tool_interrupt(value: Any) -> Any | None:
- if value is None:
- return None
- if value.__class__.__name__ == "ToolInterruptException" and hasattr(value, "request"):
- return value
-
- for attr_name in ("cause", "__cause__"):
- cause = getattr(value, attr_name, None)
- if cause is not None and cause is not value:
- interrupt = _extract_tool_interrupt(cause)
- if interrupt is not None:
- return interrupt
+def extract_tool_interrupt(value: Any) -> Any | None:
+ """Find a tool interrupt in wrapped exception chains without looping.
+
+ Class-name matching intentionally supports exceptions crossing duplicated
+ SDK import boundaries, where ``isinstance`` can be false for equivalent
+ ToolInterruptException classes.
+ """
+ pending = [value]
+ seen: set[int] = set()
+ while pending:
+ current = pending.pop()
+ if current is None or id(current) in seen:
+ continue
+ seen.add(id(current))
+ if (
+ current.__class__.__name__ == "ToolInterruptException"
+ and hasattr(current, "request")
+ ):
+ return current
+ for attr_name in ("cause", "__cause__"):
+ cause = getattr(current, attr_name, None)
+ if cause is not None and cause is not current:
+ pending.append(cause)
return None
+# Backward-compatible private alias for existing tests/imports.
+_extract_tool_interrupt = extract_tool_interrupt
+
+
def _normalize_ask_user_interrupt_value(value_obj: Any, tool_args: dict[str, Any]) -> Any:
"""Attach ask_user tool metadata so plain-query interrupts are not misclassified."""
if isinstance(value_obj, dict):
@@ -1278,12 +1293,18 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
return
normalize_read_file_tool_outcome(ctx)
- await self._emit_tool_result(session, tc, ctx.inputs.tool_result)
- self._symphony_stream_handler.request_force_finish(
- ctx,
- tc,
- ctx.inputs.tool_result,
- )
+ # A call suspended for user input (approval card, ask_user) has no
+ # result yet: ToolCallResilienceRail only left a failure placeholder
+ # on ctx.inputs.tool_result. Emitting it would show the tool as
+ # failed before the user has answered; the resumed call emits the
+ # real result.
+ if _extract_tool_interrupt(ctx.exception) is None:
+ await self._emit_tool_result(session, tc, ctx.inputs.tool_result)
+ self._symphony_stream_handler.request_force_finish(
+ ctx,
+ tc,
+ ctx.inputs.tool_result,
+ )
await self._emit_ask_user_question_if_interrupted(
session,
tc,
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 3cc25cf5e3..d5fd6bcfd3 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -102,6 +102,7 @@ from jiuwenswarm.server.handlers._default import ( # noqa: F401 — re-exporte
_is_explicit_plan_entry_request,
_is_readonly_goal_get_request,
_is_stateless_method_request,
+ _prepare_tenant_code_mode_chat_turn,
_session_mode_sync_lock,
_should_sync_code_mode_state,
_uses_tenant_pool,
diff --git a/jiuwenswarm/server/handlers/_default.py b/jiuwenswarm/server/handlers/_default.py
index 5efdc7835d..3bfe9a7634 100644
--- a/jiuwenswarm/server/handlers/_default.py
+++ b/jiuwenswarm/server/handlers/_default.py
@@ -38,6 +38,7 @@ from jiuwenswarm.server.handlers._shared import (
_sync_chat_request_metadata,
resolve_request_project_dir,
)
+from jiuwenswarm.server.runtime.tenant_agent_pool import TenantAgentPool
logger = logging.getLogger(__name__)
@@ -78,7 +79,8 @@ def _is_readonly_goal_get_request(request: AgentRequest) -> bool:
def _is_explicit_plan_entry_request(request: AgentRequest) -> bool:
if not isinstance(request.params, dict):
return False
- return request.params.get("plan_entry_source") == "slash_command"
+ source = str(request.params.get("plan_entry_source") or "").strip().lower()
+ return source in {"slash_command", "e2a"}
def _should_sync_code_mode_state(request: AgentRequest) -> bool:
@@ -312,6 +314,7 @@ async def _prepare_code_mode_chat_turn(
channel_id: str,
*,
sync_metadata: bool = True,
+ agent_manager: Any | None = None,
) -> tuple[str, str | None, Any]:
"""Mode resolution and correct agent instance selection."""
# [新增] 在 _apply_resolved_mode_to_request 把 canonical mode 写回 params 之前,
@@ -324,19 +327,46 @@ async def _prepare_code_mode_chat_turn(
params = request.params if isinstance(request.params, dict) else {}
_raw_mode = params.get("mode")
explicit_mode_provided = isinstance(_raw_mode, str) and bool(_raw_mode.strip())
+ source = str(params.get("source") or "").strip()
+ is_interrupt_continuation = (
+ source
+ in {"permission_interrupt", "confirm_interrupt", "ask_user_interrupt"}
+ and isinstance(params.get("answers"), list)
+ and bool(str(params.get("request_id") or "").strip())
+ )
runtime_work_mode = None
sid = str(request.session_id or "").strip()
sessions_root = _sessions_dir_for_request(request)
+ session_metadata: dict[str, Any] = {}
if sid:
from jiuwenswarm.server.runtime.session.session_metadata import (
get_session_metadata,
)
- session_metadata = get_session_metadata(
+ loaded_metadata = get_session_metadata(
sid,
cache_bust=True,
enable_writeback=False,
sessions_root=sessions_root,
)
+ if isinstance(loaded_metadata, dict):
+ session_metadata = loaded_metadata
+
+ # Control continuations normally contain only answers + the interrupted
+ # tool_call id. Restore the original canonical mode before applying
+ # defaults; otherwise the request is irreversibly rewritten to
+ # ``agent`` and the tenant pool creates a different adapter instance.
+ if is_interrupt_continuation and not explicit_mode_provided:
+ stored_mode = str(session_metadata.get("mode") or "").strip()
+ if stored_mode and stored_mode.lower() != "unknown":
+ params["mode"] = stored_mode
+ _raw_mode = stored_mode
+ logger.info(
+ "[AgentWebSocketServer] interrupt continuation routing "
+ "restored: session_id=%s mode=%s source=%s",
+ sid,
+ stored_mode,
+ source,
+ )
stored_work_mode = (
session_metadata.get("work_mode")
if isinstance(session_metadata, dict)
@@ -356,9 +386,16 @@ async def _prepare_code_mode_chat_turn(
runtime_work_mode = request_work_mode.strip().lower()
if runtime_work_mode is not None:
params["work_mode"] = runtime_work_mode
+ # An explicit/hydrated concrete mode is the stronger routing identity.
+ # A stale session work_mode (OfficeClaw historically initialized it as
+ # ``work``) must not turn an explicit ``code.normal`` request into agent.
+ mode_work_mode = runtime_work_mode
+ concrete_mode = str(_raw_mode or "").strip().lower()
+ if concrete_mode.startswith(("code.", "team")) or concrete_mode == "code":
+ mode_work_mode = None
mode, sub_mode = _apply_resolved_mode_to_request(
request,
- work_mode=runtime_work_mode,
+ work_mode=mode_work_mode,
)
agent_mode = "agent" if mode == "auto_harness" else mode
requested_project_dir = resolve_request_project_dir(request)
@@ -398,8 +435,9 @@ async def _prepare_code_mode_chat_turn(
request.params["project_dir"] = project_dir
request.metadata = dict(request.metadata or {})
request.metadata["project_dir"] = project_dir
- await ctx.services.agent_manager.wait_for_session_prewarm(request.session_id)
- agent = await ctx.services.agent_manager.get_agent(
+ manager = agent_manager or ctx.services.agent_manager
+ await manager.wait_for_session_prewarm(request.session_id)
+ agent = await manager.get_agent(
channel_id=channel_id,
mode=agent_mode,
project_dir=project_dir,
@@ -410,6 +448,45 @@ async def _prepare_code_mode_chat_turn(
return mode, sub_mode, agent
+async def _get_tenant_agent_manager(ctx, request: AgentRequest) -> Any:
+ """Resolve the tenant-pool AgentManager for an officeclaw/E2A request."""
+ pool = ctx.services.tenant_pool()
+ agent_id, service_id, workspace_key = TenantAgentPool.extract_ids(request)
+ agent_id, service_id = pool.resolve_control_rpc_tenant(
+ request, agent_id, service_id
+ )
+ return await pool.get_agent_manager(agent_id, service_id, workspace_key)
+
+
+async def _prepare_tenant_code_mode_chat_turn(
+ ctx,
+ request: AgentRequest,
+ channel_id: str,
+) -> tuple[str, str | None, Any] | None:
+ """Run the same code.plan sync as the default WS path on tenant-pool chats.
+
+ officeclaw previously skipped ``_ensure_code_mode_state``, so
+ ``mode=code.plan`` never switched durable plan_mode.
+ """
+ if request.req_method not in _CODE_MODE_SYNC_METHODS:
+ return None
+ if _is_readonly_goal_get_request(request):
+ return None
+ manager = await _get_tenant_agent_manager(ctx, request)
+ mode, sub_mode, agent = await _prepare_code_mode_chat_turn(
+ ctx,
+ request,
+ channel_id,
+ agent_manager=manager,
+ )
+ restored_plan = await _ensure_code_mode_state(
+ ctx, request, mode, sub_mode, agent
+ )
+ if restored_plan:
+ await _push_plan_mode_exited(ctx, request)
+ return mode, sub_mode, agent
+
+
# ── 入口:表未命中时由 pipeline 调用 ──────────────────────────────────────
async def _handle_unary(
@@ -453,31 +530,15 @@ async def _handle_unary_impl(
channel_id = request.channel_id or "default"
if _uses_tenant_pool(request):
- if request.req_method in _CODE_MODE_SYNC_METHODS:
- params = request.params if isinstance(request.params, dict) else {}
- _raw_mode = params.get("mode")
- explicit_mode_provided = (
- isinstance(_raw_mode, str) and bool(_raw_mode.strip())
- )
- mode_for_sync = (
- _raw_mode.strip()
- if explicit_mode_provided
- else str(_raw_mode or "agent")
- )
- locked = _sync_chat_request_metadata(
- request,
- resolve_request_project_dir(request),
- mode_for_sync,
- explicit_mode_provided=explicit_mode_provided,
- )
- if isinstance(locked, str) and locked.strip():
- request.params["project_dir"] = locked.strip()
- request.metadata = dict(request.metadata or {})
- request.metadata["project_dir"] = locked.strip()
- resp = await ctx.services.tenant_pool().process_message(request)
- if getattr(resp, "agent_ref", None) is None:
- resp.agent_ref = request.agent_ref
- await ctx.sink.send_unary(resp, response_id=request.request_id)
+ prepared = await _prepare_tenant_code_mode_chat_turn(ctx, request, channel_id)
+ try:
+ resp = await ctx.services.tenant_pool().process_message(request)
+ if getattr(resp, "agent_ref", None) is None:
+ resp.agent_ref = request.agent_ref
+ await ctx.sink.send_unary(resp, response_id=request.request_id)
+ finally:
+ if prepared is not None:
+ await _check_post_process_plan_exit(ctx, request, prepared[2])
logger.info(
"[AgentWebSocketServer] 非流式响应已发送 (tenant pool): request_id=%s",
request.request_id,
@@ -594,39 +655,23 @@ async def _handle_stream_impl(
ctx.services.session_stream_tasks.setdefault(session_id, {})[current_task] = stream_stop_event
if _uses_tenant_pool(request):
- if request.req_method in _CODE_MODE_SYNC_METHODS:
- params = request.params if isinstance(request.params, dict) else {}
- _raw_mode = params.get("mode")
- explicit_mode_provided = (
- isinstance(_raw_mode, str) and bool(_raw_mode.strip())
- )
- mode_for_sync = (
- _raw_mode.strip()
- if explicit_mode_provided
- else str(_raw_mode or "agent")
- )
- locked = _sync_chat_request_metadata(
- request,
- resolve_request_project_dir(request),
- mode_for_sync,
- explicit_mode_provided=explicit_mode_provided,
- )
- if isinstance(locked, str) and locked.strip():
- request.params["project_dir"] = locked.strip()
- request.metadata = dict(request.metadata or {})
- request.metadata["project_dir"] = locked.strip()
+ prepared = await _prepare_tenant_code_mode_chat_turn(ctx, request, channel_id)
chunk_count = 0
- async for chunk in ctx.services.tenant_pool().process_message_stream(request):
- chunk_count += 1
- if chunk.agent_ref is None:
- chunk.agent_ref = request.agent_ref
- sent_original = await ctx.sink.send_chunk(
- chunk,
- sequence=chunk_count - 1,
- response_id=request.request_id,
- )
- if not sent_original:
- return
+ try:
+ async for chunk in ctx.services.tenant_pool().process_message_stream(request):
+ chunk_count += 1
+ if chunk.agent_ref is None:
+ chunk.agent_ref = request.agent_ref
+ sent_original = await ctx.sink.send_chunk(
+ chunk,
+ sequence=chunk_count - 1,
+ response_id=request.request_id,
+ )
+ if not sent_original:
+ return
+ finally:
+ if prepared is not None:
+ await _check_post_process_plan_exit(ctx, request, prepared[2])
logger.info(
"[AgentWebSocketServer] 流式响应完成 (tenant pool): request_id=%s chunks=%s",
request.request_id,
diff --git a/jiuwenswarm/server/handlers/_shared.py b/jiuwenswarm/server/handlers/_shared.py
index bbfca41b35..a5e2620cf0 100644
--- a/jiuwenswarm/server/handlers/_shared.py
+++ b/jiuwenswarm/server/handlers/_shared.py
@@ -102,6 +102,9 @@ def resolve_request_project_dir(request: AgentRequest) -> str | None:
metadata_project_dir = metadata.get("project_dir") if isinstance(metadata, dict) else None
if isinstance(metadata_project_dir, str) and metadata_project_dir.strip():
return metadata_project_dir.strip()
+ workspace_dir = params.get("workspace_dir")
+ if isinstance(workspace_dir, str) and workspace_dir.strip():
+ return workspace_dir.strip()
cwd = params.get("cwd")
if isinstance(cwd, str) and cwd.strip():
return cwd.strip()
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 5a9cd0c35e..931957503c 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -136,6 +136,8 @@ ERROR_EVENT_TYPE = _ERROR_EVENT.value
# 与 skill_turbo/executor.STREAM_SOURCE_ID_FIELD 一致:并发节点用它标识 source,
# 前端据其路由到 subagent 行。adapter 转发 llm_reasoning / llm_output 时须原样透传。
STREAM_SOURCE_ID_FIELD = "stream_source_id"
+_INTERRUPT_OUTPUT_ATTACH_RETRY_COUNT = 20
+_INTERRUPT_OUTPUT_ATTACH_RETRY_INTERVAL_SECONDS = 0.05
def _propagate_stream_source_id(
@@ -10074,6 +10076,61 @@ class JiuWenSwarmDeepAdapter:
return False
return not self._goal_record_is_active()
+ @staticmethod
+ def _approved_plan_exit_resume_tool_call_id(params: Any) -> str:
+ """返回已批准 plan-exit resume 对应的工具调用 ID。
+
+ Confirm interrupt 恢复后,运行时可能在模型已经给出结论的情况下只向
+ 输出流暴露工具事件。这一标记让流末尾能为该极窄路径补一个用户可见的
+ 完成消息;其他 confirm / permission resume 不受影响。
+ """
+ if not isinstance(params, dict):
+ return ""
+ if str(params.get("source") or "").strip() != "confirm_interrupt":
+ return ""
+ tool_call_id = str(params.get("request_id") or "").strip()
+ answers = params.get("answers")
+ if not tool_call_id or not isinstance(answers, list) or not answers:
+ return ""
+ answer = answers[0]
+ if not isinstance(answer, dict):
+ return ""
+ options = answer.get("selected_options")
+ if not isinstance(options, list) or not options:
+ return ""
+ approved_values = {"approve", "本次允许", "批准", "proceed", "开始执行"}
+ selected = str(options[0] or "").strip().lower()
+ return tool_call_id if selected in approved_values else ""
+
+ def _plan_exit_fallback_content(self) -> str:
+ if self._resolve_runtime_language() == "en":
+ return "Plan approved. Exited plan mode and switched to code.normal mode."
+ return "计划已获批准,已退出 plan 模式,当前处于 code.normal 模式。"
+
+ async def _reattach_interrupt_output(self, session_id: str) -> Any | None:
+ """Briefly wait for the interrupted consumer to release its output lease."""
+ started = time.monotonic()
+ for attempt in range(1, _INTERRUPT_OUTPUT_ATTACH_RETRY_COUNT + 1):
+ await asyncio.sleep(_INTERRUPT_OUTPUT_ATTACH_RETRY_INTERVAL_SECONDS)
+ interaction_stream = await self._instance.attach_output()
+ if interaction_stream is not None:
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] interrupt output reattached: "
+ "session_id=%s attempts=%s elapsed_ms=%.1f",
+ session_id,
+ attempt,
+ (time.monotonic() - started) * 1000,
+ )
+ return interaction_stream
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] interrupt output still leased; returning ACK: "
+ "session_id=%s attempts=%s elapsed_ms=%.1f",
+ session_id,
+ _INTERRUPT_OUTPUT_ATTACH_RETRY_COUNT,
+ (time.monotonic() - started) * 1000,
+ )
+ return None
+
@staticmethod
def _resolve_input_dispatch_mode(params: Any) -> InputDispatchMode | None:
"""Map host ``input_mode`` / ``runtime_mode`` onto OpenJiuwen dispatch mode.
@@ -14009,6 +14066,10 @@ class JiuWenSwarmDeepAdapter:
"total_cost": 0.0,
}
emitted_ask_user_request_ids: set[str] = set()
+ approved_plan_exit_tool_call_id = self._approved_plan_exit_resume_tool_call_id(
+ request.params
+ )
+ saw_approved_plan_exit_result = False
def should_skip_duplicate_ask_user(parsed: dict | None) -> bool:
if not isinstance(parsed, dict):
@@ -14042,7 +14103,19 @@ class JiuWenSwarmDeepAdapter:
def note_chat_payload(payload: dict[str, Any]) -> dict[str, Any]:
nonlocal had_assistant_output, emitted_terminal_chat_final
+ nonlocal saw_approved_plan_exit_result
event_type = payload.get("event_type")
+ is_plan_exit_result = (
+ event_type == "chat.tool_result"
+ and str(payload.get("tool_name") or "") == "exit_plan_mode"
+ )
+ if (
+ approved_plan_exit_tool_call_id
+ and is_plan_exit_result
+ and str(payload.get("tool_call_id") or "")
+ == approved_plan_exit_tool_call_id
+ ):
+ saw_approved_plan_exit_result = True
# first_byte: first history-visible assistant event (matches history.jsonl).
if event_type in (
"chat.delta",
@@ -14466,6 +14539,18 @@ class JiuWenSwarmDeepAdapter:
mode=self._resolve_input_dispatch_mode(request.params),
)
)
+ if interaction_stream is None:
+ # The interrupted chat.send consumer releases its output
+ # lease asynchronously. A resume arriving in that tiny
+ # window used to receive only runtime.accepted, while the
+ # original consumer had already emitted its complete frame;
+ # no client then remained to relay the resumed final reply.
+ # Give that predecessor a bounded chance to unwind before
+ # falling back to the ACK-only path for genuinely busy
+ # sessions owned by another consumer.
+ interaction_stream = await self._reattach_interrupt_output(
+ request.session_id or "default"
+ )
if interaction_stream is None:
async for chunk in _yield_runtime_accepted():
yield chunk
@@ -14838,12 +14923,15 @@ class JiuWenSwarmDeepAdapter:
emitted_terminal_chat_final=emitted_terminal_chat_final,
):
self._stream_content_run_kind = None
+ fallback_content = ""
+ if saw_approved_plan_exit_result and not had_assistant_output:
+ fallback_content = self._plan_exit_fallback_content()
yield AgentResponseChunk(
request_id=rid,
channel_id=cid,
payload=note_chat_payload({
"event_type": "chat.final",
- "content": "",
+ "content": fallback_content,
}),
is_complete=False,
)
diff --git a/jiuwenswarm/server/runtime/agent_manager.py b/jiuwenswarm/server/runtime/agent_manager.py
index 58a1283786..391b2bc838 100644
--- a/jiuwenswarm/server/runtime/agent_manager.py
+++ b/jiuwenswarm/server/runtime/agent_manager.py
@@ -1504,6 +1504,65 @@ class AgentManager:
)
return "agent"
+ def _agent_lookup_from_request(self, request: Any) -> tuple[str, str | None, str | None]:
+ """Resolve get_agent keys from a chat request.
+
+ Must match ``AgentWebSocketServer._prepare_code_mode_chat_turn`` so the
+ tenant-pool path reuses the same cached instance after plan-mode sync.
+ """
+ from jiuwenswarm.server.handlers._shared import resolve_agent_request_mode
+
+ params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}
+ mode_full = self._resolve_request_mode(request, params)
+ mode, sub_mode, _canonical = resolve_agent_request_mode(mode_full)
+ agent_mode = "agent" if mode == "auto_harness" else mode
+ project_dir = (
+ params.get("project_dir")
+ or params.get("workspace_dir")
+ or params.get("cwd")
+ )
+ if isinstance(project_dir, str):
+ project_dir = project_dir.strip() or None
+ else:
+ project_dir = None
+ source = str(params.get("source") or "").strip()
+ is_interrupt_continuation = (
+ source
+ in {"permission_interrupt", "confirm_interrupt", "ask_user_interrupt"}
+ and isinstance(params.get("answers"), list)
+ and bool(str(params.get("request_id") or "").strip())
+ )
+ if project_dir is None and is_interrupt_continuation:
+ sid = str(getattr(request, "session_id", "") or "").strip()
+ if sid:
+ try:
+ from jiuwenswarm.common.utils import resolve_tenant_sessions_dir
+ from jiuwenswarm.server.runtime.session.session_metadata import (
+ get_session_metadata,
+ )
+
+ sessions_root = resolve_tenant_sessions_dir(
+ self.service_id, self.agent_id,
+ )
+ meta = get_session_metadata(
+ sid,
+ cache_bust=True,
+ enable_writeback=False,
+ sessions_root=sessions_root,
+ )
+ stored_project_dir = (
+ meta.get("project_dir") if isinstance(meta, dict) else None
+ )
+ if isinstance(stored_project_dir, str) and stored_project_dir.strip():
+ project_dir = stored_project_dir.strip()
+ params["project_dir"] = project_dir
+ except Exception:
+ logger.debug(
+ "[AgentManager] resolve project_dir from session metadata failed",
+ exc_info=True,
+ )
+ return agent_mode, sub_mode, project_dir
+
async def process_message(self, request: Any) -> Any:
"""处理非流式请求.
@@ -1521,15 +1580,13 @@ class AgentManager:
return await self._process_disk_only_evolution(request)
channel_id = getattr(request, "channel_id", "")
- params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}
- mode_full = self._resolve_request_mode(request, params)
- mode = str(mode_full).split(".")[0] if mode_full else "agent"
- workspace_dir = params.get("workspace_dir")
+ mode, sub_mode, project_dir = self._agent_lookup_from_request(request)
agent = await self.get_agent(
channel_id=channel_id,
mode=mode,
- project_dir=workspace_dir,
+ project_dir=project_dir,
+ sub_mode=sub_mode,
)
if agent is None:
raise RuntimeError(f"[AgentManager] No agent available for channel {channel_id}")
@@ -1551,15 +1608,13 @@ class AgentManager:
try:
await self.wait_for_session_prewarm(getattr(request, "session_id", None))
channel_id = getattr(request, "channel_id", "")
- params = getattr(request, "params", {}) if isinstance(getattr(request, "params", {}), dict) else {}
- mode_full = self._resolve_request_mode(request, params)
- mode = str(mode_full).split(".")[0] if mode_full else "agent"
- workspace_dir = params.get("workspace_dir")
+ mode, sub_mode, project_dir = self._agent_lookup_from_request(request)
agent = await self.get_agent(
channel_id=channel_id,
mode=mode,
- project_dir=workspace_dir,
+ project_dir=project_dir,
+ sub_mode=sub_mode,
)
if agent is None:
raise RuntimeError(f"[AgentManager] No agent available for channel {channel_id}")
diff --git a/tests/transport/test_default_path.py b/tests/transport/test_default_path.py
index 06ac6b444b..3217624df3 100644
--- a/tests/transport/test_default_path.py
+++ b/tests/transport/test_default_path.py
@@ -354,7 +354,7 @@ def test_unary_tenant_pool_branch_short_circuits(dp, server, monkeypatch):
resp = AgentResponse(request_id=req.request_id, channel_id="web", ok=True,
payload={"content": "tenant"})
- used = {"pool": False, "prepare": False}
+ used = {"pool": False, "prepare": False, "tenant_prepare": False}
class _Pool:
async def process_message(self, request): # noqa: ANN001
@@ -365,14 +365,20 @@ def test_unary_tenant_pool_branch_short_circuits(dp, server, monkeypatch):
used["prepare"] = True
return ("agent", None, StubAgent(unary=resp))
+ async def _tenant_prepare(*_a, **_k): # noqa: ANN002
+ used["tenant_prepare"] = True
+ return None
+
monkeypatch.setattr(dp, "_uses_tenant_pool", lambda _r: True)
monkeypatch.setattr(server, "_tenant_pool", lambda: _Pool())
monkeypatch.setattr(dp, "_prepare_code_mode_chat_turn", _prepare)
+ monkeypatch.setattr(dp, "_prepare_tenant_code_mode_chat_turn", _tenant_prepare)
ws = _run_unary(dp, server, req)
assert used["pool"], "应走租户池分支"
- assert not used["prepare"], "租户池分支不应触发 code-mode 准备"
+ assert used["tenant_prepare"], "chat.send 租户池应先做 code.plan 同步"
+ assert not used["prepare"], "不应再走默认 agent_manager 的 code-mode 准备"
assert len(ws.sent) == 1
diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.py
index fa374f1452..97ad694942 100644
--- a/tests/unit_tests/agentserver/test_agentserver_modes.py
+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py
@@ -68,7 +68,7 @@ def test_progressive_defaults_expose_registered_ask_user_tool():
def test_progressive_runtime_config_exposes_registered_ask_user_tool():
config_path = Path(__file__).parents[3] / "jiuwenswarm/resources/config.yaml"
- config = yaml.safe_load(config_path.read_text())
+ config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
eager_tools = config["react"]["tool_lazy_load"]["eager_tools"]
assert "ask_user" in eager_tools
@@ -267,7 +267,19 @@ def test_resolve_request_project_dir_prefers_params_project_dir():
assert agent_ws_server_module.resolve_request_project_dir(request) == "/tmp/project"
-def test_resolve_request_project_dir_falls_back_to_cwd_for_legacy_clients():
+def test_resolve_request_project_dir_falls_back_to_workspace_dir() -> None:
+ request = AgentRequest(
+ request_id="req-e2a",
+ channel_id="officeclaw",
+ params={"workspace_dir": "E:/workspace/demo-project"},
+ )
+
+ assert agent_ws_server_module.resolve_request_project_dir(request) == (
+ "E:/workspace/demo-project"
+ )
+
+
+def test_resolve_request_project_dir_falls_back_to_cwd_for_legacy_clients() -> None:
request = AgentRequest(
request_id="req-chat",
channel_id="tui",
diff --git a/tests/unit_tests/agentserver/test_code_agent_mode_rail.py b/tests/unit_tests/agentserver/test_code_agent_mode_rail.py
index 87ac0706d5..551add423a 100644
--- a/tests/unit_tests/agentserver/test_code_agent_mode_rail.py
+++ b/tests/unit_tests/agentserver/test_code_agent_mode_rail.py
@@ -8,10 +8,36 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from openjiuwen.core.runner.callback import AbortError
+from openjiuwen.core.single_agent.interrupt.exception import ToolInterruptException
+from openjiuwen.core.single_agent.interrupt.response import InterruptRequest
from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import CodeAgentModeRail
+def _exit_plan_mode_ctx(*, exception: object = None, tool_result: object = "done"):
+ """Build an after_tool_call context for an ``exit_plan_mode`` call."""
+ return SimpleNamespace(
+ session=SimpleNamespace(),
+ inputs=SimpleNamespace(
+ tool_name="exit_plan_mode",
+ tool_call=SimpleNamespace(id="call_1"),
+ tool_args={},
+ tool_result=tool_result,
+ ),
+ extra={},
+ exception=exception,
+ )
+
+
+def _plan_mode_agent() -> MagicMock:
+ agent = MagicMock()
+ agent.load_state.return_value = SimpleNamespace(
+ plan_mode=SimpleNamespace(mode="plan", plan_slug="test-plan")
+ )
+ return agent
+
+
@pytest.mark.asyncio
async def test_before_tool_call_blocks_switch_mode_exit_in_plan_mode() -> None:
rail = CodeAgentModeRail(allowed_tools=["switch_mode"])
@@ -65,6 +91,60 @@ async def test_before_tool_call_blocks_non_git_write_in_plan_mode() -> None:
assert ctx.extra.get("_skip_tool") is True
+async def test_after_tool_call_keeps_plan_mode_while_approval_is_pending() -> None:
+ """A suspended ``exit_plan_mode`` must not exit plan mode.
+
+ ``ToolCallResilienceRail`` writes a failure placeholder into
+ ``tool_result`` when the approval interrupt is raised, so the rail has to
+ recognise the pending interrupt on ``ctx.exception`` instead.
+ """
+ rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])
+ agent = _plan_mode_agent()
+ rail._agent = agent
+ rail._unregister_task_tool = MagicMock()
+
+ interrupt = ToolInterruptException(request=InterruptRequest(message="计划审批"))
+ ctx = _exit_plan_mode_ctx(
+ exception=AbortError("Tool execution interrupted", cause=interrupt),
+ tool_result=SimpleNamespace(success=False, data=None, error=""),
+ )
+ await rail.after_tool_call(ctx)
+
+ agent.restore_mode_after_plan_exit.assert_not_called()
+ rail._unregister_task_tool.assert_not_called()
+
+
+async def test_after_tool_call_restores_mode_when_tool_executed() -> None:
+ """An executed ``exit_plan_mode`` that left plan mode on still restores."""
+ rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])
+ agent = _plan_mode_agent()
+ rail._agent = agent
+ rail._unregister_task_tool = MagicMock()
+
+ ctx = _exit_plan_mode_ctx()
+ await rail.after_tool_call(ctx)
+
+ agent.restore_mode_after_plan_exit.assert_called_once_with(ctx.session)
+ rail._unregister_task_tool.assert_called_once()
+
+
+async def test_after_tool_call_keeps_plan_mode_when_user_rejected() -> None:
+ rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])
+ agent = _plan_mode_agent()
+ rail._agent = agent
+ rail._unregister_task_tool = MagicMock()
+
+ ctx = _exit_plan_mode_ctx()
+ ctx.extra["_plan_rejected"] = True
+ await rail.after_tool_call(ctx)
+
+ agent.restore_mode_after_plan_exit.assert_not_called()
+ rail._unregister_task_tool.assert_not_called()
+
+
def test_init_no_longer_patches_exit_plan_mode_invoke() -> None:
"""After removing the pending-approval pattern, CodeAgentModeRail.init()
should NOT patch exit_plan_mode.invoke. The parent AgentModeRail's
diff --git a/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.py b/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.py
index d985d2a755..ffd28e9824 100644
--- a/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.py
+++ b/tests/unit_tests/agentserver/test_code_confirm_interrupt_rail.py
@@ -3,7 +3,7 @@
"""Unit tests for CodeConfirmInterruptRail plan-mode switch_mode guard."""
from types import SimpleNamespace
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
import pytest
@@ -21,12 +21,13 @@ async def test_switch_mode_exit_rejected_in_plan_without_confirm_ui() -> None:
plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")
agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)
agent.system_prompt_builder = SimpleNamespace(language="cn")
+ rail.init(agent)
tool_call = SimpleNamespace(
name="switch_mode",
arguments='{"mode": "normal"}',
)
- ctx = SimpleNamespace(agent=agent, session=SimpleNamespace())
+ ctx = SimpleNamespace(agent=SimpleNamespace(), session=SimpleNamespace())
decision = await rail.resolve_interrupt(ctx, tool_call, user_input=None)
@@ -41,15 +42,56 @@ async def test_switch_mode_exit_rejected_even_after_user_approves_confirm() -> N
plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")
agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)
agent.system_prompt_builder = SimpleNamespace(language="cn")
+ rail.init(agent)
tool_call = SimpleNamespace(
name="switch_mode",
arguments='{"mode": "normal"}',
)
- ctx = SimpleNamespace(agent=agent, session=SimpleNamespace())
+ ctx = SimpleNamespace(agent=SimpleNamespace(), session=SimpleNamespace())
decision = await rail.resolve_interrupt(
ctx, tool_call, user_input={"approved": True}
)
assert isinstance(decision, RejectResult)
+
+
+async def test_switch_mode_enter_plan_does_not_load_state_from_react_agent() -> None:
+ rail = CodeConfirmInterruptRail(tool_names=["switch_mode"])
+ stateful_agent = MagicMock()
+ rail.init(stateful_agent)
+ ctx = SimpleNamespace(agent=SimpleNamespace(), session=SimpleNamespace())
+ tool_call = SimpleNamespace(name="switch_mode", arguments='{"mode": "plan"}')
+
+ decision = await rail.resolve_interrupt(ctx, tool_call, user_input=None)
+
+ stateful_agent.load_state.assert_not_called()
+ assert decision is not None
+
+
+def test_uninit_releases_stateful_agent() -> None:
+ rail = CodeConfirmInterruptRail(tool_names=["switch_mode"])
+ agent = MagicMock()
+ rail.init(agent)
+
+ rail.uninit(agent)
+
+ assert rail._agent is None
+
+
+def test_init_and_uninit_preserve_parent_lifecycle() -> None:
+ rail = CodeConfirmInterruptRail(tool_names=["switch_mode"])
+ agent = MagicMock()
+ parent = CodeConfirmInterruptRail.__bases__[0]
+
+ with patch.object(parent, "init") as parent_init, patch.object(
+ parent, "uninit"
+ ) as parent_uninit:
+ rail.init(agent)
+ rail.uninit(agent)
+
+ parent_init.assert_called_once_with(agent)
+ parent_uninit.assert_called_once_with(agent)
+ assert rail._agent is None
diff --git a/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py b/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py
index b03769677e..f7c21029d7 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_rewrite_fast_path_adapter.py
@@ -1770,6 +1770,8 @@ async def test_nonstream_structured_goal_never_enters_html_direct_path(monkeypat
async def test_stream_html_text_in_hitl_resume_goes_to_core_attach_and_send(monkeypatch):
adapter, instance = _entry_adapter(monkeypatch)
instance.attach_output.return_value = None
+ reattach = AsyncMock(return_value=None)
+ monkeypatch.setattr(adapter, "_reattach_interrupt_output", reattach)
html_followup = AsyncMock(
return_value=RewriteHtmlFollowupResult(
status="completed",
@@ -1801,6 +1803,7 @@ async def test_stream_html_text_in_hitl_resume_goes_to_core_attach_and_send(monk
assert chunks[-1].is_complete is True
html_followup.assert_not_awaited()
instance.attach_output.assert_awaited_once_with()
+ reattach.assert_awaited_once_with("session-1")
instance.send_input.assert_awaited_once()
diff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py
index f19c0a1e9a..52580c6c4f 100644
--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py
+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py
@@ -12,6 +12,7 @@ The server-side pending-approval gate has been removed.
from __future__ import annotations
+import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -44,6 +45,9 @@ from jiuwenswarm.common.schema.agent import AgentRequest
from jiuwenswarm.common.schema.message import ReqMethod
from jiuwenswarm.server import agent_ws_server as agent_ws_server_module
from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
+ JiuWenSwarmDeepAdapter,
+)
def _chat_request(
@@ -65,6 +69,25 @@ def _chat_request(
)
+def test_approved_plan_exit_resume_is_detected() -> None:
+ params = {
+ "source": "confirm_interrupt",
+ "request_id": "exit_plan_call_1",
+ "answers": [{"selected_options": ["approve"]}],
+ }
+
+ assert (
+ JiuWenSwarmDeepAdapter._approved_plan_exit_resume_tool_call_id(params)
+ == "exit_plan_call_1"
+ )
+ assert (
+ JiuWenSwarmDeepAdapter._approved_plan_exit_resume_tool_call_id(
+ {**params, "answers": [{"selected_options": ["reject"]}]}
+ )
+ == ""
+ )
+
+
@pytest.mark.asyncio
async def test_prepare_code_mode_chat_turn_resolves_mode_and_agent() -> None:
"""_prepare_code_mode_chat_turn resolves mode/sub_mode and gets the agent
@@ -301,6 +324,290 @@ async def test_ensure_code_mode_state_allows_explicit_plan_reentry_after_exit(mo
assert request.params["mode"] == "code.plan"
+async def test_ensure_code_mode_state_allows_e2a_plan_reentry_after_exit(
+ monkeypatch,
+) -> None:
+ """E2A/officeclaw clients mark explicit plan entry with plan_entry_source=e2a."""
+ session_id = "sess_e2a_reentry"
+
+ plan_agent = MagicMock()
+ plan_instance = MagicMock()
+ plan_agent.get_instance.return_value = plan_instance
+ plan_agent.ensure_instance = AsyncMock(return_value=plan_instance)
+ plan_instance.card = SimpleNamespace(id="code-agent")
+ plan_state = SimpleNamespace(mode="normal", plan_slug="old-plan")
+ plan_instance.load_state.return_value = SimpleNamespace(plan_mode=plan_state)
+
+ session = MagicMock()
+ create_session = MagicMock(return_value=session)
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ _push_mock = AsyncMock()
+ monkeypatch.setattr(_default, "_push_plan_mode_exited", _push_mock)
+ request = _chat_request(
+ session_id,
+ "continue in plan mode",
+ mode="code.plan",
+ extra_params={"plan_entry_source": "e2a"},
+ )
+
+ agent_ws_server_module._plan_exited_sessions.add(session_id)
+ try:
+ with patch(
+ "openjiuwen.core.single_agent.create_agent_session",
+ create_session,
+ ):
+ session.pre_run = AsyncMock()
+ session.post_run = AsyncMock()
+ restored = await _default._ensure_code_mode_state(
+ _default_ctx(server, request),
+ request, "code", "plan", plan_agent
+ )
+ finally:
+ agent_ws_server_module._plan_exited_sessions.discard(session_id)
+
+ assert restored is False
+ plan_instance.switch_mode.assert_called_once_with(session=session, mode="plan")
+ _push_mock.assert_not_awaited()
+ assert request.params["mode"] == "code.plan"
+
+
+def test_explicit_plan_entry_accepts_only_known_sources() -> None:
+ e2a_request = _chat_request("sess", extra_params={"plan_entry_source": "e2a"})
+ slash_request = _chat_request(
+ "sess", extra_params={"plan_entry_source": "slash_command"}
+ )
+ stale_request = _chat_request("sess")
+ unknown_request = _chat_request(
+ "sess", extra_params={"plan_entry_source": "always-present-client-marker"}
+ )
+
+ assert _default._is_explicit_plan_entry_request(e2a_request) is True
+ assert _default._is_explicit_plan_entry_request(slash_request) is True
+ assert _default._is_explicit_plan_entry_request(stale_request) is False
+ assert _default._is_explicit_plan_entry_request(unknown_request) is False
+
+
+async def test_tenant_unary_plan_exit_cleanup_runs_when_processing_fails() -> None:
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ agent = MagicMock()
+ pool = MagicMock()
+ pool.process_message = AsyncMock(side_effect=RuntimeError("send failed"))
+ server._tenant_pool = MagicMock(return_value=pool)
+ request = _chat_request("sess_unary_failure")
+ ctx = _default_ctx(server, request)
+ check_exit = AsyncMock()
+
+ with patch.object(_default, "_uses_tenant_pool", return_value=True), patch.object(
+ _default,
+ "_prepare_tenant_code_mode_chat_turn",
+ new=AsyncMock(return_value=("code", "plan", agent)),
+ ), patch.object(
+ _default, "_check_post_process_plan_exit", new=check_exit
+ ), patch(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.ensure_persistent_checkpointer",
+ new=AsyncMock(),
+ ):
+ with pytest.raises(RuntimeError, match="send failed"):
+ await _default._handle_unary_impl(ctx, request)
+
+ check_exit.assert_awaited_once_with(ctx, request, agent)
+
+
+async def test_interrupt_output_reattach_retries_until_lease_is_released(
+ monkeypatch,
+) -> None:
+ adapter = JiuWenSwarmDeepAdapter.__new__(JiuWenSwarmDeepAdapter)
+ stream = object()
+ adapter._instance = SimpleNamespace(
+ attach_output=AsyncMock(side_effect=[None, None, stream])
+ )
+ sleep = AsyncMock()
+ monkeypatch.setattr(asyncio, "sleep", sleep)
+
+ result = await adapter._reattach_interrupt_output("sess-reattach")
+
+ assert result is stream
+ assert adapter._instance.attach_output.await_count == 3
+ assert sleep.await_count == 3
+
+
+def test_plan_exit_fallback_content_follows_runtime_language() -> None:
+ adapter = JiuWenSwarmDeepAdapter.__new__(JiuWenSwarmDeepAdapter)
+ adapter._resolve_runtime_language = MagicMock(return_value="en")
+ assert adapter._plan_exit_fallback_content().startswith("Plan approved.")
+ adapter._resolve_runtime_language.return_value = "zh"
+ assert adapter._plan_exit_fallback_content().startswith("计划已获批准")
+
+
+async def test_prepare_code_mode_chat_turn_uses_injected_agent_manager() -> None:
+ injected = MagicMock()
+ injected.get_agent = AsyncMock(return_value=MagicMock())
+ injected.wait_for_session_prewarm = AsyncMock()
+ default_manager = MagicMock()
+ default_manager.get_agent = AsyncMock()
+ default_manager.wait_for_session_prewarm = AsyncMock()
+
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ server._agent_manager = default_manager
+ request = _chat_request("sess_injected", mode="code.plan")
+
+ mode, sub_mode, _agent = await _default._prepare_code_mode_chat_turn(
+ _default_ctx(server, request),
+ request,
+ "officeclaw",
+ agent_manager=injected,
+ )
+
+ assert mode == "code"
+ assert sub_mode == "plan"
+ injected.get_agent.assert_awaited_once()
+ default_manager.get_agent.assert_not_called()
+
+
+def test_agent_lookup_uses_plan_sub_mode_and_workspace_dir() -> None:
+ from jiuwenswarm.server.runtime.agent_manager import AgentManager
+
+ manager = AgentManager.__new__(AgentManager)
+ manager.service_id = "default"
+ manager.agent_id = "office"
+ request = SimpleNamespace(
+ params={"mode": "code.plan", "workspace_dir": "E:/workspace/demo-project"}
+ )
+ mode, sub_mode, project_dir = manager._agent_lookup_from_request(request)
+ assert mode == "code"
+ assert sub_mode == "plan"
+ assert project_dir == "E:/workspace/demo-project"
+
+
+ "interrupt_source",
+ ["permission_interrupt", "confirm_interrupt", "ask_user_interrupt"],
+)
+async def test_tenant_interrupt_continuation_restores_code_route_before_defaults(
+ interrupt_source: str,
+) -> None:
+ """OfficeClaw approval replies omit mode/project_dir; restore both before lookup."""
+ agent = MagicMock()
+ manager = MagicMock()
+ manager.get_agent = AsyncMock(return_value=agent)
+ manager.wait_for_session_prewarm = AsyncMock()
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ server._agent_manager = manager
+ request = AgentRequest(
+ request_id="resume-wire-request",
+ channel_id="officeclaw",
+ session_id="sess_resume_code",
+ req_method=ReqMethod.CHAT_SEND,
+ params={
+ "query": "",
+ "source": interrupt_source,
+ "request_id": "bash_call_1",
+ "answers": [{"selected_options": ["本次允许"]}],
+ },
+ )
+ metadata = {
+ "mode": "code.normal",
+ # Historical OfficeClaw sessions may contain this stale value.
+ "work_mode": "work",
+ "project_dir": "E:/workspace/original-project",
+ }
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",
+ return_value=metadata,
+ ), patch.object(
+ _default,
+ "_sync_chat_request_metadata",
+ return_value=metadata["project_dir"],
+ ):
+ mode, sub_mode, selected = await _default._prepare_code_mode_chat_turn(
+ _default_ctx(server, request),
+ request,
+ "officeclaw",
+ agent_manager=manager,
+ )
+
+ assert (mode, sub_mode, selected) == ("code", "normal", agent)
+ assert request.params["mode"] == "code.normal"
+ assert request.params["project_dir"] == metadata["project_dir"]
+ manager.get_agent.assert_awaited_once_with(
+ channel_id="officeclaw",
+ mode="code",
+ project_dir=metadata["project_dir"],
+ sub_mode="normal",
+ )
+
+
+async def test_explicit_code_mode_wins_over_stale_stored_work_mode() -> None:
+ agent = MagicMock()
+ manager = MagicMock()
+ manager.get_agent = AsyncMock(return_value=agent)
+ manager.wait_for_session_prewarm = AsyncMock()
+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)
+ server._agent_manager = manager
+ request = _chat_request(
+ "sess_explicit_code",
+ mode="code.normal",
+ )
+ request.channel_id = "officeclaw"
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",
+ return_value={"mode": "unknown", "work_mode": "work"},
+ ), patch.object(
+ _default,
+ "_sync_chat_request_metadata",
+ return_value=None,
+ ):
+ mode, sub_mode, _ = await _default._prepare_code_mode_chat_turn(
+ _default_ctx(server, request),
+ request,
+ "officeclaw",
+ agent_manager=manager,
+ )
+
+ assert (mode, sub_mode) == ("code", "normal")
+ assert request.params["mode"] == "code.normal"
+
+
+def test_agent_lookup_restores_project_dir_for_interrupt_continuation() -> None:
+ from jiuwenswarm.server.runtime.agent_manager import AgentManager
+
+ manager = AgentManager.__new__(AgentManager)
+ manager.service_id = "default"
+ manager.agent_id = "office"
+ request = SimpleNamespace(
+ session_id="sess_project_resume",
+ params={
+ "source": "ask_user_interrupt",
+ "request_id": "ask_call_1",
+ "answers": [{"selected_options": ["继续"]}],
+ },
+ )
+ metadata = {
+ "mode": "team",
+ "project_dir": "E:/workspace/team-project",
+ }
+
+ with patch(
+ "jiuwenswarm.server.runtime.session.session_metadata.get_session_metadata",
+ return_value=metadata,
+ ):
+ mode, sub_mode, project_dir = manager._agent_lookup_from_request(request)
+
+ assert (mode, sub_mode) == ("team", None)
+ assert project_dir == metadata["project_dir"]
+ assert request.params["mode"] == "team"
+ assert request.params["project_dir"] == metadata["project_dir"]
+
+
@pytest.mark.asyncio
async def test_disconnect_cleanup_then_stale_plan_reentry_blocked_by_slug(monkeypatch) -> None:
"""After disconnect cleanup discards the plan-exited flag, a stale (non-explicit)
diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_tool_result.py b/tests/unit_tests/agentserver/test_stream_event_rail_tool_result.py
new file mode 100644
index 0000000000..078f8ead81
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_stream_event_rail_tool_result.py
@@ -0,0 +1,90 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tool-result streaming behaviour of JiuSwarmStreamEventRail."""
+
+# pylint: disable=protected-access
+
+from types import SimpleNamespace
+
+import pytest
+from openjiuwen.core.runner.callback import AbortError
+from openjiuwen.core.single_agent.interrupt.exception import ToolInterruptException
+from openjiuwen.core.single_agent.interrupt.response import InterruptRequest
+from openjiuwen.core.single_agent.rail.base import ToolCallInputs
+
+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
+ JiuSwarmStreamEventRail,
+ extract_tool_interrupt,
+)
+
+
+class _FakeSession:
+ def __init__(self):
+ self.outputs = []
+
+ async def write_stream(self, output):
+ self.outputs.append(output)
+
+ @staticmethod
+ def get_session_id() -> str:
+ return "sess-1"
+
+
+def _pending_approval_exception() -> AbortError:
+ """Mirror what the approval rail raises out of ``before_tool_call``."""
+ return AbortError(
+ "Tool execution interrupted: exit_plan_mode",
+ cause=ToolInterruptException(request=InterruptRequest(message="计划审批")),
+ )
+
+
+def _ctx(session: _FakeSession, *, exception: object = None):
+ tool_call = SimpleNamespace(id="call_1", name="exit_plan_mode", arguments={})
+ return SimpleNamespace(
+ session=session,
+ agent=None,
+ context=None,
+ extra={},
+ exception=exception,
+ inputs=ToolCallInputs(
+ tool_call=tool_call,
+ tool_name="exit_plan_mode",
+ tool_args={},
+ tool_result=SimpleNamespace(success=False, data=None, error=""),
+ ),
+ )
+
+
+async def test_no_tool_result_emitted_while_waiting_for_approval() -> None:
+ """A call suspended for approval has no result to report yet."""
+ session = _FakeSession()
+ ctx = _ctx(session, exception=_pending_approval_exception())
+
+ await JiuSwarmStreamEventRail().after_tool_call(ctx)
+
+ assert [output.type for output in session.outputs] == []
+
+
+async def test_tool_result_emitted_for_executed_tool_call() -> None:
+ session = _FakeSession()
+ ctx = _ctx(session)
+
+ await JiuSwarmStreamEventRail().after_tool_call(ctx)
+
+ assert [output.type for output in session.outputs] == ["tool_result"]
+
+
+def test_shared_interrupt_unwrap_handles_deep_and_cyclic_chains() -> None:
+ interrupt = ToolInterruptException(request=InterruptRequest(message="approve"))
+ wrapped = interrupt
+ for index in range(10):
+ wrapped = SimpleNamespace(cause=wrapped, marker=index)
+
+ assert extract_tool_interrupt(wrapped) is interrupt
+
+ first = SimpleNamespace(cause=None)
+ second = SimpleNamespace(cause=first)
+ first.cause = second
+ assert extract_tool_interrupt(first) is None