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: change the review info when exit plam mode
ldstyle8204887fb3213
diff --git a/jiuwenswarm/agents/harness/code/rails/__init__.py b/jiuwenswarm/agents/harness/code/rails/__init__.pyindex c549246103..233b8da6d0 100644--- a/jiuwenswarm/agents/harness/code/rails/__init__.py+++ b/jiuwenswarm/agents/harness/code/rails/__init__.py@@ -3,11 +3,11 @@from jiuwenswarm.agents.harness.code.rails.code_task_planning_rail import (CodeTaskPlanningRail,)-from jiuwenswarm.agents.harness.code.rails.code_plan_approval_rail import (- PlanApprovalRail,+from jiuwenswarm.agents.harness.code.rails.code_plan_approval_interrupt_rail import (+ PlanApprovalInterruptRail,)__all__ = ["CodeTaskPlanningRail",- "PlanApprovalRail",+ "PlanApprovalInterruptRail",]diff --git a/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py b/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.pyindex 096ab2048c..9a2fc2eeea 100644--- a/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py+++ b/jiuwenswarm/agents/harness/code/rails/code_agent_mode_rail.py@@ -1,6 +1,12 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""CodeAgentModeRail — defer plan-mode exit until the user approves in chat."""+"""CodeAgentModeRail — plan-mode write enforcement for code mode.++Plan approval is handled by ``PlanApprovalInterruptRail`` with an+immediate dialog (aligned with Claude Code). This rail handles:+- Blocking ``switch_mode`` from exiting plan mode+- Blocking non-git write operations via bash in plan mode+"""from __future__ import annotations@@ -8,34 +14,13 @@ import jsonimport refrom typing import TYPE_CHECKING, Any+from openjiuwen.core.common.logging import loggerfrom openjiuwen.core.single_agent.rail.base import AgentCallbackContextfrom openjiuwen.harness.rails.agent_mode_rail import AgentModeRail-from jiuwenswarm.agents.harness.code.rails.code_plan_approval_rail import (- PENDING_EXIT_RESULT_PREFIX,-)-if TYPE_CHECKING:from openjiuwen.harness.deep_agent import DeepAgent-_EMPTY_EXIT_MSG = {- "cn": "规划模式已结束。你现在可以结束本轮。\n计划文件:{plan_path}",- "en": "Plan mode ended. You can now exit the turn.\nPlan file: {plan_path}",-}--_SWITCH_MODE_EXIT_PLAN_MSG = {- "cn": (- "[AgentModeRail] plan 模式下不能用 switch_mode 退出。"- "请先调用 exit_plan_mode 提交计划,再在对话中回复「按计划实现」等批准执行;"- "或使用 /mode code.normal 切换模式。"- ),- "en": (- "[AgentModeRail] switch_mode cannot exit plan mode. "- "Call exit_plan_mode, then approve in chat (e.g. implement the plan), "- "or use /mode code.normal."- ),-}-_NON_GIT_WRITE_RE = re.compile(r"\b(mkdir|touch|mv|cp|chmod|chown|dd|tee|wget|curl\s+.*\s*-[a-zA-Z]*O)\b"r"|\brm\s+(-[a-zA-Z]*[rf]|/|[~.])"@@ -45,22 +30,19 @@ _NON_GIT_WRITE_RE = re.compile()-def _plan_tool_language(language: str | None) -> str:- return "cn" if language == "cn" else "en"--class CodeAgentModeRail(AgentModeRail):"""AgentModeRail variant for jiuwenswarm code mode.- ``exit_plan_mode`` presents the plan for review but does **not** restore- normal mode until the user approves via chat (handled by the server-side- pending-approval gate).+ Plan approval is handled by ``PlanApprovalInterruptRail`` which intercepts+ ``exit_plan_mode`` with an immediate approval dialog (aligned with Claude Code).+ Mode restoration happens inside ``ExitPlanModeTool.invoke()`` on approval."""def init(self, agent: "DeepAgent") -> None:- """Register tools and patch ``exit_plan_mode`` to defer mode restore."""+ """Register tools. No exit_plan_mode patching needed —+ ``PlanApprovalInterruptRail`` handles the approval gate.+ """super().init(agent)- self._patch_exit_plan_mode_tool()async def before_tool_call(self, ctx: AgentCallbackContext) -> None:"""Enforce plan-mode write blocks beyond the parent git-only guard."""@@ -72,8 +54,17 @@ class CodeAgentModeRail(AgentModeRail):if plan_state.mode == "plan" and tool_name == "switch_mode":target = self._parse_switch_mode_target(ctx)if target in {"normal", "auto"}:- lang = "cn" if self._language_is_cn() else "en"- self._reject_tool(ctx, _SWITCH_MODE_EXIT_PLAN_MSG[lang])+ if self._language_is_cn():+ msg = (+ "[AgentModeRail] plan 模式下不能用 switch_mode 退出。"+ "请先调用 exit_plan_mode 提交计划等待审批。"+ )+ else:+ msg = (+ "[AgentModeRail] switch_mode cannot exit plan mode. "+ "Call exit_plan_mode to submit your plan for approval."+ )+ self._reject_tool(ctx, msg)returnawait super().before_tool_call(ctx)@@ -95,43 +86,54 @@ class CodeAgentModeRail(AgentModeRail):self._reject_tool(ctx, msg)async def after_tool_call(self, ctx: AgentCallbackContext) -> None:- """Skip default exit handling while the plan awaits user approval."""- if (- ctx.inputs.tool_name == "exit_plan_mode"- and not ctx.extra.get("_skip_tool")- and ctx.inputs.tool_result is not None- ):- return- await super().after_tool_call(ctx)-- def _patch_exit_plan_mode_tool(self) -> None:- """Read plan for review without calling ``restore_mode_after_plan_exit``."""- for tool in self._tools:- if getattr(tool.card, "name", "") != "exit_plan_mode":- continue-- language = _plan_tool_language(getattr(tool, "_language", "cn"))-- async def patched_invoke(inputs, _tool=tool, _lang=language, **kwargs):- agent = _tool._agent_ref # pylint: disable=protected-access- session = kwargs.get("session")- plan_path = agent.get_plan_file_path(session)- plan_text = ""- if plan_path and plan_path.exists():- plan_text = plan_path.read_text(encoding="utf-8")- plan_path_str = str(plan_path) if plan_path else ""- if not plan_text.strip():- return _EMPTY_EXIT_MSG[_lang].format(plan_path=plan_path_str)- prefix = PENDING_EXIT_RESULT_PREFIX[_lang].format(- plan_path=plan_path_str,- )- return prefix + plan_text-- tool.invoke = patched_invoke- break+ """Override parent to fix mode restoration on user rejection.++ The parent ``AgentModeRail.after_tool_call()`` has a supplement+ mode-restoration block that calls ``restore_mode_after_plan_exit()``+ when ``tool_result is not None``. However, when+ ``PlanApprovalInterruptRail`` rejects the call (user clicks Reject),+ ``_skip_tool()`` sets ``tool_result`` to the feedback string — so the+ ``is not None`` check passes and the mode is erroneously restored.++ **Important**: we check ``_plan_rejected`` instead of ``_skip_tool``+ because ``ability_manager._railed_execute_single_tool_call`` **pops**+ ``_skip_tool`` from ``ctx.extra`` before ``after_tool_call`` runs.+ ``PlanApprovalInterruptRail`` sets ``_plan_rejected`` which persists+ through the pop.+ """+ tool_name = ctx.inputs.tool_name+ agent = self._agent+ rejected = ctx.extra.get("_plan_rejected", False)++ # Segment 1: register / unregister task_tool (same as parent)+ if tool_name == "enter_plan_mode" and not rejected:+ self._register_task_tool(agent)+ elif tool_name == "exit_plan_mode" and not rejected:+ self._unregister_task_tool(agent)++ # Segment 2: supplement mode restoration (PARENT BUG FIXED)+ # Only restore when the tool was NOT rejected — i.e. it actually+ # executed but the plan was empty (ExitPlanModeTool.invoke() returns+ # early without calling restore_mode_after_plan_exit).+ if tool_name == "exit_plan_mode" and not rejected:+ session = ctx.session+ state = agent.load_state(session)+ if (state.plan_mode.mode == "plan"+ and ctx.inputs.tool_result is not None):+ try:+ agent.restore_mode_after_plan_exit(session)+ logger.info(+ "[CodeAgentModeRail] Restored mode after plan exit "+ "(plan was empty, tool did not restore)"+ )+ except Exception as exc:+ logger.warning(+ "[CodeAgentModeRail] Failed to restore mode: %s", exc+ )@staticmethoddef _parse_switch_mode_target(ctx: AgentCallbackContext) -> str:+ """Parse the target mode from a switch_mode tool-call context."""raw: Any = Nonetool_call = getattr(ctx.inputs, "tool_call", None)if tool_call is not None:diff --git a/jiuwenswarm/agents/harness/code/rails/code_plan_approval_interrupt_rail.py b/jiuwenswarm/agents/harness/code/rails/code_plan_approval_interrupt_rail.pynew file mode 100644index 0000000000..89aaccc9b3--- /dev/null+++ b/jiuwenswarm/agents/harness/code/rails/code_plan_approval_interrupt_rail.py@@ -0,0 +1,240 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""PlanApprovalInterruptRail — instant plan approval dialog for exit_plan_mode.++Aligns with Claude Code: ``exit_plan_mode`` triggers an **immediate** user+interaction showing the plan content, and mode restoration happens inside+the tool call itself (not deferred to the next user turn).++How it works:+1. LLM calls ``exit_plan_mode``.+2. This rail intercepts BEFORE the tool executes.+3. Plan file is read and presented in the interrupt message.+4. User sees the plan and chooses [Approve] or [Reject].+5. **Approve**: tool executes → ``ExitPlanModeTool.invoke()`` calls+ ``restore_mode_after_plan_exit()`` immediately → mode restored.+6. **Reject**: tool skipped → LLM gets error → stays in plan mode → can revise.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any, Optional++from openjiuwen.core.common.logging import logger+from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall+from openjiuwen.core.single_agent.interrupt.response import InterruptRequest+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.rails.interrupt.confirm_rail import (+ ConfirmInterruptRail,+)+from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult++if TYPE_CHECKING:+ from openjiuwen.harness.deep_agent import DeepAgent++# ── Plan approval interrupt message templates ──────────────────────────++_PLAN_APPROVAL_MESSAGE_CN = """\+**计划审批**++Agent 已完成计划制定,等待你审批:++{plan_preview}++---+请选择:+- **批准**:退出 plan 模式,开始执行计划+- **拒绝**:留在 plan 模式,Agent 将根据你的反馈修改计划"""++_PLAN_APPROVAL_MESSAGE_EN = """\+**Plan Approval**++The agent has completed a plan and is requesting your approval:++{plan_preview}++---+Choose:+- **Approve**: Exit plan mode and begin implementation+- **Reject**: Stay in plan mode, the agent will revise the plan based on your feedback"""++_PLAN_EMPTY_MESSAGE_CN = """\+**计划审批**++Agent 请求退出 plan 模式,但计划文件为空。++---+请选择:+- **批准**:退出 plan 模式(无计划内容)+- **拒绝**:留在 plan 模式,让 Agent 先写好计划"""++_PLAN_EMPTY_MESSAGE_EN = """\+**Plan Approval**++The agent is requesting to exit plan mode, but the plan file is empty.++---+Choose:+- **Approve**: Exit plan mode (no plan content)+- **Reject**: Stay in plan mode, let the agent write a plan first"""++# Truncate plan preview to this many characters to keep the dialog readable+_MAX_PLAN_PREVIEW_CHARS = 3000+++class PlanApprovalInterruptRail(ConfirmInterruptRail):+ """Interrupt ``exit_plan_mode`` to show the plan for user approval.++ Extends ``ConfirmInterruptRail`` with a plan-aware interrupt message+ that reads the plan file and presents it inline. Mode restoration+ happens inside ``ExitPlanModeTool.invoke()`` when the user approves.++ Priority 78 — runs BEFORE the generic ``CodeConfirmInterruptRail`` (80)+ but AFTER ``AgentModeRail`` (85) so plan mode enforcement is active.+ """++ priority = 78++ def __init__(self) -> None:+ super().__init__(tool_names=["exit_plan_mode"])+ self._agent: "DeepAgent | None" = None++ # ── Lifecycle ───────────────────────────────────────────────────++ def init(self, agent: "DeepAgent") -> None:+ """Capture the agent reference for plan file reading.++ Args:+ agent: The parent DeepAgent.+ """+ self._agent = agent++ def uninit(self, agent: "DeepAgent") -> None: # noqa: ARG002+ """Release the agent reference."""+ self._agent = None++ # ── Interrupt logic ──────────────────────────────────────────────++ async def resolve_interrupt(+ self,+ ctx: AgentCallbackContext,+ tool_call: Optional[ToolCall],+ user_input: Optional[Any],+ auto_confirm_config: Optional[dict] = None,+ ):+ """Override to inject plan content into the interrupt message.++ On first call (user_input is None): reads the plan file and builds+ a rich approval message showing the plan content.++ On resume: delegates to ``ConfirmInterruptRail.resolve_interrupt()``+ which handles ``ConfirmPayload`` deserialization and approve/reject.++ Args:+ ctx: Agent callback context.+ tool_call: The tool call being intercepted.+ user_input: User response from resume (None on first call).+ auto_confirm_config: Current auto-confirm settings.+ """+ # First call — show plan content in the interrupt message+ if user_input is None and tool_call is not None:+ plan_content = self._read_plan_content(ctx)+ language = self._detect_language()+ message = self._build_approval_message(plan_content, language)+ return self.interrupt(+ InterruptRequest(+ message=message,+ payload_schema=self.request.payload_schema,+ auto_confirm_key="exit_plan_mode",+ )+ )++ # Resume — delegate to parent (handles ConfirmPayload.approved)+ decision = await super().resolve_interrupt(+ ctx, tool_call, user_input, auto_confirm_config+ )+ # When the user rejects, _skip_tool() sets ctx.extra["_skip_tool"]=True,+ # but _railed_execute_single_tool_call pops it before after_tool_call+ # runs. Set a persistent marker so CodeAgentModeRail.after_tool_call()+ # can still detect the rejection and skip mode restoration.+ if isinstance(decision, RejectResult):+ ctx.extra["_plan_rejected"] = True+ return decision++ # ── Helpers ──────────────────────────────────────────────────────++ def _detect_language(self) -> str:+ """Return ``"cn"`` or ``"en"`` based on the agent's configured language.++ Reads from ``system_prompt_builder.language`` on the agent. Falls back+ to ``"cn"`` if the agent reference is unavailable.+ """+ agent = self._agent+ if agent is not None:+ builder = getattr(agent, "system_prompt_builder", None)+ if builder is not None:+ lang = getattr(builder, "language", "cn")+ if lang in ("cn", "en"):+ return lang+ return "cn"++ def _read_plan_content(self, ctx: AgentCallbackContext) -> str:+ """Read the plan file content for display in the approval dialog.++ Args:+ ctx: Agent callback context with session reference.++ Returns:+ Plan file text, or empty string if no plan file exists.+ """+ agent = self._agent+ if agent is None:+ return ""++ session = ctx.session+ if session is None:+ return ""+ plan_path = agent.get_plan_file_path(session)+ if not plan_path or not plan_path.exists():+ return ""++ try:+ return plan_path.read_text(encoding="utf-8").strip()+ except OSError as exc:+ logger.warning(+ "[PlanApprovalInterruptRail] Failed to read plan file %s: %s",+ plan_path, exc,+ )+ return ""++ def _build_approval_message(self, plan_content: str, language: str) -> str:+ """Build the interrupt message with plan preview.++ Args:+ plan_content: The full plan file text (may be empty).+ language: ``"cn"`` or ``"en"``.++ Returns:+ Formatted markdown message for the approval dialog.+ """+ if language == "en":+ template = (+ _PLAN_APPROVAL_MESSAGE_EN+ if plan_content+ else _PLAN_EMPTY_MESSAGE_EN+ )+ else:+ template = (+ _PLAN_APPROVAL_MESSAGE_CN+ if plan_content+ else _PLAN_EMPTY_MESSAGE_CN+ )++ preview = plan_content+ if len(preview) > _MAX_PLAN_PREVIEW_CHARS:+ preview = preview[:_MAX_PLAN_PREVIEW_CHARS] + "\n\n… (truncated)"++ return template.format(plan_preview=preview)+++__all__ = ["PlanApprovalInterruptRail"]diff --git a/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.py b/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.pydeleted file mode 100644index 8e1b86123f..0000000000--- a/jiuwenswarm/agents/harness/code/rails/code_plan_approval_rail.py+++ /dev/null@@ -1,226 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.--"""PlanApprovalRail — pending-approval lifecycle for plan mode exit.--Aligns with Claude Code: ``exit_plan_mode`` presents the plan for review-but the agent **stays in plan mode** until the user approves via chat.-Mode restoration (``restore_mode_after_plan_exit``) happens only after-approval, when the server injects the approved notification on the next-user turn and ``_ensure_code_mode_state`` runs.--The rail:--1. Detects successful ``exit_plan_mode`` calls in ``after_tool_call``.-2. Re-enters plan mode if the tool already restored it prematurely.-3. Rewrites tool_result copy from "plan ended" to "awaiting your review".-4. Stores ``_plan_approval_state`` for the server pending gate.-"""--from __future__ import annotations--from dataclasses import dataclass-from pathlib import Path-from typing import TYPE_CHECKING, Any--from openjiuwen.core.common.logging import logger-from openjiuwen.core.single_agent.rail.base import AgentCallbackContext-from openjiuwen.harness.rails.base import DeepAgentRail--from jiuwenswarm.agents.harness.code.prompt.plan_approval import PENDING_APPROVAL_MARKER--if TYPE_CHECKING:- from openjiuwen.harness.deep_agent import DeepAgent---@dataclass-class PlanApprovalState:- """Pending-approval state for one session.-- Stored on the agent instance after exit_plan_mode and consumed by the- server layer on the next user request.- """-- pending: bool = False- plan_slug: str = ""- plan_content: str = ""- plan_path: str = ""-- def to_dict(self) -> dict[str, Any]:- """Serialize to a JSON-friendly dict."""- return {- "pending": self.pending,- "plan_slug": self.plan_slug,- "plan_content": self.plan_content,- "plan_path": self.plan_path,- }---PENDING_EXIT_RESULT_PREFIX = {- "cn": "计划已提交,等待用户确认。\n计划文件:{plan_path}\n\n## 计划:\n",- "en": "Plan submitted for your review.\nPlan file: {plan_path}\n\n## Plan:\n",-}---def _detect_language(agent: DeepAgent | None) -> str:- """Return ``"cn"`` or ``"en"`` based on the agent's prompt builder."""- if agent is None:- return "cn"- builder = getattr(agent, "system_prompt_builder", None)- if builder is None:- return "cn"- return getattr(builder, "language", "cn")---class PlanApprovalRail(DeepAgentRail):- """Rail that manages the plan-approval lifecycle.-- Priority ``76`` — runs after AgentModeRail (85) and ConfirmInterruptRail- so that the tool has already executed and its result is available.- """-- priority = 76-- def init(self, agent: DeepAgent) -> None:- """Capture the agent reference.-- Args:- agent: The parent DeepAgent.- """- self._agent = agent-- def uninit(self, agent: DeepAgent) -> None:- """Clean up the stored agent reference."""- self._agent = None-- async def before_model_call(self, ctx: AgentCallbackContext) -> None:- """No-op — this rail only observes tool calls."""- return-- async def before_tool_call(self, ctx: AgentCallbackContext) -> None:- """No-op — this rail only observes tool calls."""- return-- async def after_tool_call(self, ctx: AgentCallbackContext) -> None:- """Detect exit_plan_mode and store pending-approval state.-- Also appends a pending-approval text marker as a **fallback** so- text-only channels (e.g. IM bridges) still see guidance on how to- approve/reject the plan.-- Args:- ctx: Callback context containing tool-name, result, and session.- """- if ctx.inputs.tool_name != "exit_plan_mode":- return- if ctx.extra.get("_skip_tool"):- return- # ConfirmInterrupt 等 hook 中断时工具未真正执行,不应进入待审批状态。- if ctx.inputs.tool_result is None:- return-- agent = self._agent- if agent is None:- logger.warning("[PlanApprovalRail] agent is None, skipping")- return-- language = _detect_language(agent)-- # ── 1. Extract plan content from tool result ──- tool_msg = ctx.inputs.tool_msg- result_text = ""- if tool_msg and hasattr(tool_msg, "content") and tool_msg.content:- raw = tool_msg.content- if isinstance(raw, str):- result_text = raw- elif isinstance(raw, list):- # Extract text from structured content blocks- for block in raw:- if isinstance(block, dict) and block.get("type") == "text":- result_text = block.get("text", "")- if result_text:- break- if not result_text:- result_text = str(ctx.inputs.tool_result or "")-- # ── 2. Extract plan body (strip prefix metadata) ──- plan_content = self._extract_plan_body(result_text)-- # ── 3. Load plan metadata via agent ──- plan_path = agent.get_plan_file_path(ctx.session)- plan_path_str = str(plan_path) if plan_path else ""- state = agent.load_state(ctx.session)-- # Safety net: patched exit_plan_mode must stay in plan until approval.- if state.plan_mode.mode != "plan":- agent.switch_mode(session=ctx.session, mode="plan")- state = agent.load_state(ctx.session)- logger.warning(- "[PlanApprovalRail] Re-entered plan mode after premature exit restore"- )-- if not plan_content and plan_path_str:- try:- plan_file = Path(plan_path_str)- if plan_file.is_file():- plan_content = plan_file.read_text(encoding="utf-8").strip()- except OSError:- plan_content = ""- if not plan_content:- logger.warning("[PlanApprovalRail] no plan content extracted from exit_plan_mode result")- plan_content = "(plan content unavailable)"-- # ── 4. Build and store approval state ──- approval_state = PlanApprovalState(- pending=True,- plan_slug=state.plan_mode.plan_slug or "",- plan_content=plan_content,- plan_path=plan_path_str,- )- agent._plan_approval_state = approval_state # pylint: disable=protected-access- logger.info(- "[PlanApprovalRail] exit_plan_mode detected, pending approval set "- "for plan %s",- approval_state.plan_slug,- )-- # ── 5. Rewrite tool_result + append chat guidance marker ──- marker = PENDING_APPROVAL_MARKER.get(language, PENDING_APPROVAL_MARKER["cn"])- if tool_msg and hasattr(tool_msg, "content"):- tool_msg.content = str(tool_msg.content) + marker-- @staticmethod- def _extract_plan_body(result_text: str) -> str:- """Strip the prefix metadata from the ExitPlanModeTool result.-- ExitPlanModeTool returns::-- 规划模式已结束。- 计划文件:xxx-- ## 计划:- <plan_body>-- We only keep the part after the ``## 计划:`` / ``## Plan:`` marker.-- Args:- result_text: Full tool result text.- language: ``"cn"`` or ``"en"``.-- Returns:- The plan body text, or the full text if no marker is found.- """- for marker in ("## 计划:\n", "## Plan:\n"):- if marker in result_text:- return result_text.split(marker, 1)[1].strip()- # Fallback: try to strip common prefixes- lines = result_text.strip().split("\n", 10)- if len(lines) > 5:- return "\n".join(lines[5:]).strip()- return result_text.strip()---__all__ = [- "PENDING_EXIT_RESULT_PREFIX",- "PlanApprovalRail",- "PlanApprovalState",-]diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex cf807b7890..42b4703047 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -352,7 +352,8 @@ _PERMISSION_INTERRUPT_MARKERS = ("Permission denied","安全风险评估",)-_CONFIRM_INTERRUPT_TOOLS = frozenset({"switch_mode", "exit_plan_mode"})+# exit_plan_mode uses PlanApprovalInterruptRail (extends ConfirmInterruptRail)+_CONFIRM_INTERRUPT_TOOLS = frozenset({"switch_mode", "exit_plan_mode"})def _read_interrupt_fields(value_obj: Any) -> tuple[str, str, dict | None]:diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex ad23166522..ec6809abf6 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -19,6 +19,7 @@ from openjiuwen.harness.prompts import PromptSectionfrom openjiuwen.harness.prompts.prompt_attachment_manager import (PromptAttachmentKind,)+from openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_promptfrom jiuwenswarm.common.utils import get_config_dir, logger@@ -27,6 +28,8 @@ from jiuwenswarm.common.utils import get_agent_workspace_dir_LANGUAGE_NAMES = {"cn": "Chinese", "zh": "Chinese", "en": "English"}+_LANGUAGE_NAMES = {"cn": "Chinese", "zh": "Chinese", "en": "English"}+class RuntimePromptRail(DeepAgentRail):"""在 before_model_call 中注入时间及运行时状态文件路径。"""@@ -220,7 +223,7 @@ class RuntimePromptRail(DeepAgentRail):priority=95,)- # ── Language output constraint (injected near end, like Claude Code) ──+ # ── Language output constraint (injected near end) ──language_name = _LANGUAGE_NAMES.get(language_val, language_val)language_output_content = ("# Language\n\n"@@ -450,10 +453,10 @@ class RuntimePromptRail(DeepAgentRail):try:writer = self.attachment_manager.bind_context(ctx)await writer.add_section(- section=section,- content=content,- kind=kind,- source="jiuwenswarm.runtime_prompt_rail",+ section,+ content,+ kind,+ "jiuwenswarm.runtime_prompt_rail",priority=priority,content_kind="text/markdown",)diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex 928782a237..4e346dd2c0 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -75,7 +75,7 @@ import {teamWorkingStartedAtMs,} from "./components/team-shared.js";import { padToWidth, renderWrappedText } from "./rendering/text.js";-import { editorTheme, palette, selectListTheme, setCurrentThemeName } from "./theme.js";+import { chalk, editorTheme, palette, selectListTheme, setCurrentThemeName } from "./theme.js";const END_CURSOR = "\x1b[7m \x1b[0m";const ENABLE_MOUSE_TRACKING = "\x1b[?1000h\x1b[?1006h";@@ -89,6 +89,8 @@ const SWARM_WORKFLOW_AGENT_TEXT_PREVIEW_ROWS = 6;const PERMISSION_TOOL_RE = /工具\s+`([^`]+)`\s+需要授权/;const CONFIRM_TOOL_RE = /(?:Tool|工具)\s*:\s*`([^`]+)`/i;const CONFIRM_ACTION_RE = /\*\*(?:Agent wants to|Tool `[^`]+` requires your approval)([^*]*)\*\*/i;+const PLAN_APPROVAL_RE = /\*\*(?:Plan Approval|计划审批)\*\*/i;+const PLAN_REJECT_INPUT_RE = /(\s+\[ .+ \])$/;const PERMISSION_RISK_RE = /安全风险评估:\**\s*([^\s*]+)?\s*\**([^*\n]+?风险)\**/m;const PERMISSION_QUOTE_RE = /^>\s*(.+)$/gm;const PERMISSION_JSON_BLOCK_RE = /```json\s*([\s\S]*?)\s*```/i;@@ -356,6 +358,10 @@ function resolveFdBinary(): string | null {return null;}+export function isPlanApprovalRequest(source: string | undefined, questionText: string): boolean {+ return source === "confirm_interrupt" && PLAN_APPROVAL_RE.test(questionText);+}+function isPermissionRequest(source: string | undefined, questionText: string): boolean {return (source === "permission_interrupt" ||@@ -367,6 +373,24 @@ function isPermissionRequest(source: string | undefined, questionText: string):);}+export function getPendingQuestionTitle(+ source: string | undefined,+ questionText: string,+ progress: string,+ activeQuestionIndex: number,+ total: number,+): string {+ if (isPlanApprovalRequest(source, questionText)) {+ return progress+ ? `Exit Plan and Execute: ${activeQuestionIndex + 1}/${total}`+ : "Exit Plan and Execute:";+ }+ if (source === "confirm_interrupt") {+ return progress ? `Confirm ${activeQuestionIndex + 1}/${total}` : "Confirm action";+ }+ return progress ? `Permission ${activeQuestionIndex + 1}/${total}` : "Permission";+}+function parsePermissionSummary(questionText: string): PermissionSummary {const tool =PERMISSION_TOOL_RE.exec(questionText)?.[1]?.trim() ||@@ -536,6 +560,18 @@ function normalizePermissionOptionLabel(label: string): string {return trimmed;}+export function formatQuestionOptionLabelForDisplay(label: string, planApproval: boolean): string {+ if (!planApproval) {+ return normalizePermissionOptionLabel(label);+ }+ return isRejectOption(label) ? "Reject" : "Approve";+}++function isAlwaysAllowOption(label: string): boolean {+ const normalized = label.trim();+ return normalized.includes("总是允许") || /^always allow\b/i.test(normalized);+}+function isAllowOption(label: string): boolean {const normalized = label.trim();return normalized.includes("允许") || /^allow\b/i.test(normalized);@@ -548,6 +584,76 @@ function isRejectOption(label: string): boolean {);}+export function shouldCollectPlanRejectFeedback(+ source: string | undefined,+ questionText: string,+ label: string,+): boolean {+ return isPlanApprovalRequest(source, questionText) && isRejectOption(label);+}++export function shouldAppendPlanRejectFeedback(+ source: string | undefined,+ questionText: string,+ label: string,+): boolean {+ return shouldCollectPlanRejectFeedback(source, questionText, label);+}++export function getPlanRejectFeedbackHint(+ feedback: string,+ showCursor = false,+ cursorIndex?: number,+): string {+ const trimmed = feedback.trim();+ if (!showCursor) {+ return `[ ${trimmed || "tell jiuwenswarm what to change"} ]`;+ }+ const cursor = Math.max(0, Math.min(cursorIndex ?? feedback.length, feedback.length));+ return trimmed+ ? `[ ${feedback.slice(0, cursor)}${END_CURSOR}${feedback.slice(cursor)} ]`+ : `[ ${END_CURSOR}tell jiuwenswarm what to change ]`;+}++export function buildPlanApprovalQuestionItems(+ options: Array<{ label: string; description?: string }>,+ feedback: string,+ showRejectCursor = false,+ cursorIndex?: number,+): SelectItem[] {+ return options+ .filter((option) => !isAlwaysAllowOption(option.label))+ .map((option) => ({+ value: option.label,+ label: formatQuestionOptionLabelForDisplay(option.label, true),+ description: isRejectOption(option.label)+ ? getPlanRejectFeedbackHint(feedback, showRejectCursor, cursorIndex)+ : undefined,+ }));+}++export function getPlanApprovalListLayout(): {+ minPrimaryColumnWidth: number;+ maxPrimaryColumnWidth: number;+} {+ return { minPrimaryColumnWidth: 10, maxPrimaryColumnWidth: 10 };+}++const planApprovalSelectListTheme = {+ ...selectListTheme,+ selectedText: (value: string) => {+ const match = PLAN_REJECT_INPUT_RE.exec(value);+ if (!match?.index) {+ return selectListTheme.selectedText(value);+ }+ return (+ selectListTheme.selectedText(value.slice(0, match.index)) ++ chalk.dim(match[1])+ );+ },+ description: (value: string) => chalk.dim(value),+};+function wrapPlainText(text: string, width: number): string[] {const maxWidth = Math.max(12, width - 1);const source = text.replace(/\r/g, "").split("\n");@@ -1503,7 +1609,8 @@ export class AppScreen implements Component, Focusable {// input_value phase: editor is rendered inside buildConfigEditorLines.// search_list/select_value phase: no text input needed in the main editor.const isConfigEditorActive = this.configEditorState !== null;- const editorLines = isConfigEditorActive+ const hideEditorForInlinePlanReject = this.isEditingInlinePlanReject(snapshot);+ const editorLines = isConfigEditorActive || hideEditorForInlinePlanReject? []: this.applySlashCommandHint(this.editor.render(width), width);const composerPreviewLines: string[] = [];@@ -1603,9 +1710,9 @@ export class AppScreen implements Component, Focusable {const { content, attachments } = this.buildOutgoingMessage(text);- if (!content) return;-const snapshot = this.state.getSnapshot();+ if (!content && !(snapshot.pendingQuestion && this.otherInputMode)) return;+if (snapshot.pendingQuestion) {if (this.questionList !== null) {const selected = this.questionList.getSelectedItem();@@ -1632,11 +1739,19 @@ export class AppScreen implements Component, Focusable {const answers = pendingQuestion.questions.map((question, index) => {const label = this.pendingQuestionAnswers.get(index) ?? "";- if (label === "Other") {+ const isPlanRejectFeedback = shouldAppendPlanRejectFeedback(+ pendingQuestion.source,+ question.question,+ label,+ );+ if (label === "Other" || isPlanRejectFeedback) {return {question: question.question,selected_options: [label],- custom_input: index === this.activeQuestionIndex ? text : undefined,+ custom_input:+ index === this.activeQuestionIndex && (label === "Other" || text)+ ? text+ : undefined,};}return {@@ -4703,18 +4818,18 @@ export class AppScreen implements Component, Focusable {const total = pendingQuestion.questions.length;const progress = total > 1 ? ` (${this.activeQuestionIndex + 1}/${total})` : "";const permissionRequest = isPermissionRequest(pendingQuestion.source, question.question);+ const planApprovalRequest = isPlanApprovalRequest(pendingQuestion.source, question.question);const lines: string[] = [];- if (permissionRequest) {+ if (permissionRequest && !this.otherInputMode) {const summary = parsePermissionSummary(question.question);- const title =- pendingQuestion.source === "confirm_interrupt"- ? progress- ? `Confirm ${this.activeQuestionIndex + 1}/${total}`- : "Confirm action"- : progress- ? `Permission ${this.activeQuestionIndex + 1}/${total}`- : "Permission";+ const title = getPendingQuestionTitle(+ pendingQuestion.source,+ question.question,+ progress,+ this.activeQuestionIndex,+ total,+ );lines.push(...renderPermissionBlock(width, summary, title));} else if (this.otherInputMode) {lines.push(@@ -4732,12 +4847,20 @@ export class AppScreen implements Component, Focusable {}lines.push("");lines.push(- ...wrapPlainText(- `[Answer] Please enter your answer:`,+ ...wrapPlainText(`[Answer] Please enter your answer:`, width).map((line) =>+ padToWidth(palette.status.info(line), width),+ ),+ );+ lines.push(+ padToWidth(+ palette.text.dim(+ planApprovalRequest+ ? "tell jiuwenswarm what to change · Enter submit · Esc back to options"+ : "Type your answer · Enter submit · Esc back to options",+ ),width,- ).map((line) => padToWidth(palette.status.info(line), width)),+ ),);- lines.push(padToWidth(palette.text.dim("Type your answer · Enter submit · Esc back to options"), width));} else {lines.push(...wrapPlainText(@@ -4784,7 +4907,9 @@ export class AppScreen implements Component, Focusable {padToWidth(palette.text.dim(permissionRequest- ? "↑/↓ review · Enter/click confirm · Esc reject"+ ? planApprovalRequest+ ? "↑/↓ review · Type feedback on Reject · Enter/click confirm"+ : "↑/↓ review · Enter/click confirm · Esc reject": "↑/↓ choose · Enter/click confirm · Esc reject",),width,@@ -4815,6 +4940,32 @@ export class AppScreen implements Component, Focusable {}if (this.questionList !== null) {+ const question =+ snapshot.pendingQuestion.questions[this.activeQuestionIndex] ??+ snapshot.pendingQuestion.questions[0];+ const selected = this.questionList.getSelectedItem();+ const editingPlanReject = !!question &&+ !!selected &&+ shouldAppendPlanRejectFeedback(+ snapshot.pendingQuestion.source,+ question.question,+ selected.value,+ );+ const printableChar = this.getPrintableChar(data);+ if (+ editingPlanReject &&+ (printableChar !== undefined ||+ matchesKey(data, "backspace") ||+ matchesKey(data, "delete") ||+ this.isInlinePlanRejectCursorInput(data))+ ) {+ this.pendingQuestionAnswers.set(this.activeQuestionIndex, selected.value);+ this.editor.handleInput(data);+ this.syncQuestionList(this.state.getSnapshot());+ this.syncEditorSubmitState(this.state.getSnapshot());+ this.tui.requestRender();+ return true;+ }this.questionList.handleInput(data);return true;}@@ -4850,15 +5001,31 @@ export class AppScreen implements Component, Focusable {return;}- for (const option of question.options) {- const displayLabel = normalizePermissionOptionLabel(option.label);+ const planApprovalRequest = isPlanApprovalRequest(+ snapshot.pendingQuestion.source,+ question.question,+ );+ const rowItems = planApprovalRequest+ ? buildPlanApprovalQuestionItems(+ question.options,+ this.editor.getText(),+ this.isEditingInlinePlanReject(snapshot),+ this.editor.getCursor().col,+ )+ : question.options.map((option) => ({+ value: option.label,+ label: formatQuestionOptionLabelForDisplay(option.label, false),+ }));++ for (const option of rowItems) {+ const displayLabel = option.label ?? option.value;for (let i = 0; i < screenLines.length; i++) {const plain = stripAnsi(screenLines[i]);if ((plain.startsWith("→ ") || plain.startsWith(" ")) &&plain.includes(displayLabel)) {- this.questionOptionRows.push({ row: i + 1, value: option.label });+ this.questionOptionRows.push({ row: i + 1, value: option.value });break;}}@@ -4870,9 +5037,42 @@ export class AppScreen implements Component, Focusable {this.editor.disableSubmit =!!pendingQuestion &&!this.otherInputMode &&+ !this.isEditingInlinePlanReject(snapshot) &&(this.questionList !== null || (pendingQuestion.questions[0]?.options.length ?? 0) > 0);}+ private isEditingInlinePlanReject(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): boolean {+ const pendingQuestion = snapshot.pendingQuestion;+ if (!pendingQuestion || this.questionList === null) {+ return false;+ }+ const question =+ pendingQuestion.questions[this.activeQuestionIndex] ?? pendingQuestion.questions[0];+ const selected = this.questionList.getSelectedItem();+ return !!question &&+ !!selected &&+ shouldAppendPlanRejectFeedback(pendingQuestion.source, question.question, selected.value);+ }++ private isInlinePlanRejectCursorInput(data: string): boolean {+ return (+ matchesKey(data, "left") ||+ matchesKey(data, "right") ||+ matchesKey(data, "home") ||+ matchesKey(data, "end") ||+ matchesKey(data, "ctrl+b") ||+ matchesKey(data, "ctrl+f") ||+ matchesKey(data, "ctrl+a") ||+ matchesKey(data, "ctrl+e") ||+ matchesKey(data, "alt+left") ||+ matchesKey(data, "alt+right") ||+ matchesKey(data, "ctrl+left") ||+ matchesKey(data, "ctrl+right") ||+ matchesKey(data, "alt+b") ||+ matchesKey(data, "alt+f")+ );+ }+private syncQuestionList(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): void {const pendingQuestion = snapshot.pendingQuestion;if (!pendingQuestion) {@@ -4883,6 +5083,7 @@ export class AppScreen implements Component, Focusable {}const question = pendingQuestion.questions[this.activeQuestionIndex];+ const planApprovalRequest = isPlanApprovalRequest(pendingQuestion.source, question?.question ?? "");if (!question || question.options.length === 0) {this.questionList = null;this.questionDetailsMap = null;@@ -4890,15 +5091,32 @@ export class AppScreen implements Component, Focusable {return;}- const items: SelectItem[] = question.options.map((option) => ({- value: option.label,- label:- pendingQuestion.source === "permission_interrupt" ||- pendingQuestion.source === "confirm_interrupt"- ? normalizePermissionOptionLabel(option.label)- : option.label,- description: option.description,- }));+ const currentSelectedValue = this.questionList?.getSelectedItem()?.value;+ const showRejectCursor =+ planApprovalRequest &&+ !!currentSelectedValue &&+ shouldAppendPlanRejectFeedback(+ pendingQuestion.source,+ question.question,+ currentSelectedValue,+ );++ const items: SelectItem[] = planApprovalRequest+ ? buildPlanApprovalQuestionItems(+ question.options,+ this.editor.getText(),+ showRejectCursor,+ this.editor.getCursor().col,+ )+ : question.options.map((option) => ({+ value: option.label,+ label:+ pendingQuestion.source === "permission_interrupt" ||+ pendingQuestion.source === "confirm_interrupt"+ ? formatQuestionOptionLabelForDisplay(option.label, false)+ : option.label,+ description: option.description,+ }));// Build details map for options that have sub-lines (e.g. rewind file changes)const detailsMap = new Map<string, string[]>();@@ -4917,15 +5135,17 @@ export class AppScreen implements Component, Focusable {// For memory edit, use a layout that shows short labels with full-path details sub-lines.// For rewind and other questions with details sub-lines, use a narrower label column// so the description starts sooner and details can align beneath it.- const layout = pendingQuestion.source === "local_command_memory_edit"- ? { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 30 }- : detailsMap.size > 0- ? { minPrimaryColumnWidth: 10, maxPrimaryColumnWidth: 10 }- : { minPrimaryColumnWidth: 34, maxPrimaryColumnWidth: 42 };+ const layout = planApprovalRequest+ ? getPlanApprovalListLayout()+ : pendingQuestion.source === "local_command_memory_edit"+ ? { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 30 }+ : detailsMap.size > 0+ ? { minPrimaryColumnWidth: 10, maxPrimaryColumnWidth: 10 }+ : { minPrimaryColumnWidth: 34, maxPrimaryColumnWidth: 42 };const list = new SelectList(items,Math.min(Math.max(items.length, 1), maxVisible),- selectListTheme,+ planApprovalRequest ? planApprovalSelectListTheme : selectListTheme,layout,);list.onSelect = (item) => {@@ -4942,7 +5162,8 @@ export class AppScreen implements Component, Focusable {list.onSelectionChange = () => {this.invalidate();};- let selectedValue = this.pendingQuestionAnswers.get(this.activeQuestionIndex);+ let selectedValue =+ currentSelectedValue ?? this.pendingQuestionAnswers.get(this.activeQuestionIndex);// For memory edit, restore cursor to the last selected file within this sessionif (!selectedValue && pendingQuestion.source === "local_command_memory_edit" && lastMemorySelection) {selectedValue = lastMemorySelection;@@ -4964,6 +5185,14 @@ export class AppScreen implements Component, Focusable {return;}+ const question =+ pendingQuestion.questions[this.activeQuestionIndex] ?? pendingQuestion.questions[0];+ const collectPlanRejectFeedback = shouldCollectPlanRejectFeedback(+ pendingQuestion.source,+ question?.question ?? "",+ label,+ );+if (label === "Other") {this.otherInputMode = true;this.pendingQuestionAnswers.set(this.activeQuestionIndex, label);@@ -4989,11 +5218,25 @@ export class AppScreen implements Component, Focusable {const answers = pendingQuestion.questions.map((question, index) => {const answerValue = this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "";- return {+ const answer = {question: question.question,selected_options: [answerValue],};+ if (+ index === this.activeQuestionIndex &&+ collectPlanRejectFeedback &&+ shouldAppendPlanRejectFeedback(pendingQuestion.source, question.question, answerValue)+ ) {+ const feedback = this.editor.getText().trim();+ if (feedback) {+ return { ...answer, custom_input: feedback };+ }+ }+ return answer;});this.state.submitQuestionAnswers(answers);+ if (collectPlanRejectFeedback) {+ this.editor.setText("");+ }}}diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 550cc23533..1e31991480 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -81,33 +81,20 @@ from jiuwenswarm.common.security.ws_origin import (is_allowed_browser_origin,)from jiuwenswarm.agents.harness.code.prompt.plan_approval import (- APPROVE_CMD_PREFIX,- APPROVED_NOTIFICATION,- FEEDBACK_INJECTION,PLAN_MODE_EXITED_EVENT_TYPE,- PLAN_USER_APPROVED_FLAG,- REJECT_CMD_PREFIX,- classify_plan_user_intent,- extract_feedback_from_reject,- is_direct_plan_implement_request,)from jiuwenswarm.common.schema.message import ReqMethodlogger = logging.getLogger(__name__)-# ── Plan approval state store (session_id → PlanApprovalState) ────────────-# Populated by PlanApprovalRail.after_tool_call after exit_plan_mode,-# consumed by _handle_pending_plan_approval before the next user turn.-_pending_plan_approvals: dict[str, dict] = {}--# Sessions where the user approved the plan on the latest chat turn.-# Consumed by _ensure_code_mode_state (session-scoped, not request.params) so-# concurrent skills.list RPCs cannot steal the approval flag.-_plan_approved_sessions: set[str] = set()-# Serialize plan-mode restore per session to avoid checkpoint races._session_mode_sync_locks: dict[str, asyncio.Lock] = {}+# Sessions that have successfully exited plan mode via exit_plan_mode tool.+# Set by _check_post_process_plan_exit, consumed by _ensure_code_mode_state+# to prevent TUI-race re-entrance to plan mode.+_plan_exited_sessions: set[str] = set()+_CODE_MODE_SYNC_METHODS = frozenset({ReqMethod.CHAT_SEND,ReqMethod.CHAT_RESUME,@@ -432,46 +419,6 @@ def _inject_plan_mode_activation_reminder(request: AgentRequest) -> None:# ── Plan approval helpers ──────────────────────────────────────────────-def _store_pending_approval_from_agent(- session_id: str,- agent_instance: Any,-) -> None:- """Pick up ``_plan_approval_state`` from the agent instance and store it.-- Called after ``agent.process_message`` / ``process_message_stream``- completes. The rail sets ``agent_instance._plan_approval_state`` during- ``after_tool_call``; we read it and store it in the session-level dict so- the next request can inspect it.-- Args:- session_id: The session identifier.- agent_instance: The DeepAgent instance that just processed a request.- """- approval_state = getattr(agent_instance, "_plan_approval_state", None)- if approval_state is None:- return- # Convert dataclass to dict if needed- if hasattr(approval_state, "to_dict"):- _pending_plan_approvals[session_id] = approval_state.to_dict()- elif isinstance(approval_state, dict):- _pending_plan_approvals[session_id] = approval_state- else:- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_slug": getattr(approval_state, "plan_slug", ""),- "plan_content": getattr(approval_state, "plan_content", ""),- "plan_path": getattr(approval_state, "plan_path", ""),- }- try:- delattr(agent_instance, "_plan_approval_state")- except (AttributeError, TypeError):- pass- logger.info(- "[_store_pending_approval] Session %s has pending plan approval",- session_id,- )--def _is_resuming_tool_interrupt(request: AgentRequest) -> bool:"""Return True when the request resumes a paused tool-call interrupt."""params = request.params if isinstance(request.params, dict) else {}@@ -487,142 +434,6 @@ def _is_resuming_tool_interrupt(request: AgentRequest) -> bool:}-def _check_and_handle_pending_approval(- request: AgentRequest,- language: str = "cn",-) -> bool:- """Check for pending plan approval and handle user's response.-- Must be called BEFORE agent processing (before _ensure_code_mode_state).- If there is a pending approval and the user's message is a response to it,- this function will:-- - **On approval**: Return ``True``, having already modified ``request``- to inject the approval notification into the query (which will be- visible to the model in normal mode).- - **On feedback**: Return ``True``, having injected the feedback as a- ``<system-reminder>`` and kept plan mode active.- - **No pending approval**: Return ``False`` (no changes).-- Args:- request: The incoming request (will be mutated if approval is handled).- language: ``"cn"`` or ``"en"``.-- Returns:- ``True`` if a pending approval was found and handled; ``False`` otherwise.- """- if _is_resuming_tool_interrupt(request):- return False-- session_id = request.session_id- if not session_id:- return False-- pending = _pending_plan_approvals.pop(session_id, None)- if not pending or not pending.get("pending"):- return False-- # Read the user's response- user_msg = _request_query_text(request)- if not user_msg:- # Empty user message — keep pending state- _pending_plan_approvals[session_id] = pending- return False-- plan_content = pending.get("plan_content", "")- lang = "cn" if language == "cn" else "en"-- # Classify: approve → exit plan and implement; revise → stay in plan.- is_reject_cmd = user_msg.startswith(REJECT_CMD_PREFIX)- intent = classify_plan_user_intent(user_msg)-- if intent == "approve":- # ── User approves the plan ──- _plan_approved_sessions.add(session_id)- if isinstance(request.params, dict):- request.params["mode"] = "code.normal"- request.params[PLAN_USER_APPROVED_FLAG] = True- approval_text = APPROVED_NOTIFICATION[lang].format(plan_content=plan_content)- if isinstance(request.params, dict):- request.params["query"] = approval_text- logger.info(- "[_check_and_handle_pending_approval] User APPROVED plan for session %s",- session_id,- )- else:- # ── User wants plan revisions only ──- feedback_msg = user_msg- if is_reject_cmd:- feedback_msg = extract_feedback_from_reject(user_msg)- feedback_text = FEEDBACK_INJECTION[lang].format(user_message=feedback_msg)- _plan_approved_sessions.discard(session_id)- if isinstance(request.params, dict):- request.params["mode"] = "code.plan"- request.params.pop(PLAN_USER_APPROVED_FLAG, None)- request.params["query"] = feedback_text- logger.info(- "[_check_and_handle_pending_approval] User REVISE plan for session %s",- session_id,- )-- return True---async def _try_handle_direct_plan_implement(- request: AgentRequest,- agent: Any,- language: str = "cn",-) -> bool:- """Approve plan via chat when ``exit_plan_mode`` left no pending gate.-- Covers cases where the user says e.g. 「按计划实现」 after rejecting a- misleading ``switch_mode`` confirm, without re-calling ``exit_plan_mode``.- """- if _is_resuming_tool_interrupt(request):- return False-- session_id = request.session_id- if not session_id or not isinstance(request.params, dict):- return False- if request.params.get(PLAN_USER_APPROVED_FLAG):- return False- user_msg = _request_query_text(request)- if not is_direct_plan_implement_request(user_msg):- return False-- from openjiuwen.core.single_agent import create_agent_session-- session = create_agent_session(- session_id=request.session_id,- card=agent.get_instance().card,- )- await session.pre_run(inputs=None)- state = agent.get_instance().load_state(session)- if state.plan_mode.mode != "plan":- return False-- plan_path = agent.get_instance().get_plan_file_path(session)- plan_content = ""- if plan_path and plan_path.exists():- plan_content = plan_path.read_text(encoding="utf-8")- if not plan_content.strip():- return False-- lang = "cn" if language == "cn" else "en"- _plan_approved_sessions.add(session_id)- request.params["mode"] = "code.normal"- request.params[PLAN_USER_APPROVED_FLAG] = True- request.params["query"] = APPROVED_NOTIFICATION[lang].format(- plan_content=plan_content,- )- logger.info(- "[_try_handle_direct_plan_implement] User APPROVED plan via chat "- "for session %s",- session_id,- )- return True--class AgentWebSocketServer:"""Gateway 与 AgentServer 之间的 WebSocket 服务端(单例).@@ -1457,6 +1268,52 @@ class AgentWebSocketServer:},})+ async def _check_post_process_plan_exit(+ self,+ request: AgentRequest,+ agent: Any,+ ) -> None:+ """Detect plan→normal transition that happened inside tool execution.++ When ``exit_plan_mode`` is approved, ``ExitPlanModeTool.invoke()``+ calls ``restore_mode_after_plan_exit()`` to persist the mode change+ to the session checkpointer. This runs AFTER ``_ensure_code_mode_state``+ has already completed (which only syncs the mode BEFORE processing).++ We check the persisted state here and push a ``plan.mode_exited``+ event so the TUI status bar updates immediately, rather than waiting+ for the next user request.++ Only checks requests whose sub_mode is ``"plan"`` — the transition+ from plan→normal can only happen during a plan-mode request (the LLM+ calls ``exit_plan_mode``). Checking ``sub_mode == "normal"`` requests+ would produce false positives for every background RPC (e.g.+ ``skills.list``) that uses ``code.normal`` but never had an active+ plan session.+ """+ session_id = request.session_id+ if not session_id:+ return+ mode, sub_mode = _apply_resolved_mode_to_request(request)+ if mode != "code" or sub_mode != "plan":+ return++ from openjiuwen.core.single_agent import create_agent_session+ session = create_agent_session(+ session_id=session_id,+ card=agent.get_instance().card,+ )+ await session.pre_run(inputs=None)+ state = agent.get_instance().load_state(session)+ if state.plan_mode.mode == "normal":+ _plan_exited_sessions.add(session_id)+ await self._push_plan_mode_exited(request)+ logger.info(+ "[_check_post_process_plan_exit] Detected plan→normal after "+ "tool execution for session=%s",+ session_id,+ )+@staticmethoddef _is_resuming_tool_interrupt(request: AgentRequest) -> bool:"""Return True when the request resumes a paused tool-call interrupt."""@@ -1467,12 +1324,7 @@ class AgentWebSocketServer:request: AgentRequest,channel_id: str,) -> tuple[str, str | None, Any]:- """Plan approval gates, mode resolution, and correct agent instance selection."""- language = self._resolve_code_language()-- if not _is_resuming_tool_interrupt(request):- _check_and_handle_pending_approval(request, language=language)-+ """Mode resolution and correct agent instance selection."""mode, sub_mode = _apply_resolved_mode_to_request(request)agent_mode = "agent" if mode == "auto_harness" else modeproject_dir = resolve_request_project_dir(request)@@ -1486,24 +1338,6 @@ class AgentWebSocketServer:if agent is None:raise ValueError("Failed to get agent")- if (- not _is_resuming_tool_interrupt(request)- and await _try_handle_direct_plan_implement(- request, agent, language=language- )- ):- prev_sub_mode = sub_mode- mode, sub_mode = _apply_resolved_mode_to_request(request)- if sub_mode != prev_sub_mode:- agent = await self._agent_manager.get_agent(- channel_id=channel_id,- mode=agent_mode,- project_dir=project_dir,- sub_mode=sub_mode,- )- if agent is None:- raise ValueError("Failed to get agent")-return mode, sub_mode, agentasync def _ensure_code_mode_state(@@ -1523,8 +1357,12 @@ class AgentWebSocketServer:切换到 plan 模式且尚未调用 enter_plan_mode 时,注入 <system-reminder>告知 LLM 调用 enter_plan_mode(对齐 Claude Code:plan 指令不进 system prompt)。+ ``exit_plan_mode`` now restores mode immediately inside the tool+ (via ``restore_mode_after_plan_exit``), so this method no longer needs+ to gate plan→normal transitions with an approval flag.+Returns:- ``True`` if plan mode was restored to normal after user approval.+ ``True`` if plan mode was restored to normal (mode sync occurred)."""if mode != "code" or sub_mode == "team":return False@@ -1548,43 +1386,63 @@ class AgentWebSocketServer:)await session.pre_run(inputs=None) # 从 checkpointer 加载历史 statestate = agent.get_instance().load_state(session)- # 仅在目标模式与当前模式不同时执行模式切换,避免:- # 1. exit_plan_mode 已恢复的模式被覆盖(plan 完成 → mode=normal, sub_mode=normal → 跳过)- # 2. 已在 plan 模式时冗余调用 switch_mode(pre_plan_mode 被污染)- # 3. 强制退出后无法重新进入 plan 模式(plan_slug 残留 + mode=normal → sub_mode=plan → 执行)+ # 仅在目标模式与当前模式不同时执行模式切换+ mode_changed_to_plan = Falseif state.plan_mode.mode != sub_mode:- approved_this_turn = session_id in _plan_approved_sessions- if isinstance(request.params, dict):- request.params.pop(PLAN_USER_APPROVED_FLAG, None)- # 仅当用户明确批准计划时才允许 plan → normal。- if state.plan_mode.mode == "plan" and sub_mode == "normal":- if approved_this_turn:- _plan_approved_sessions.discard(session_id)- agent.get_instance().restore_mode_after_plan_exit(session)- restored_after_approval = True+ # Guard: block stale normal→plan switches when plan was already exited.+ # Two mechanisms:+ # 1. _plan_exited_sessions flag (precise — set by _check_post_process_plan_exit)+ # 2. plan_slug fallback (defense-in-depth — plan exists but mode is normal)+ if state.plan_mode.mode == "normal" and sub_mode == "plan":+ blocked = False+ if session_id in _plan_exited_sessions:+ _plan_exited_sessions.discard(session_id)+ blocked = Truelogger.info(- "[_ensure_code_mode_state] Restored plan→normal after user "- "approval for session=%s",+ "[_ensure_code_mode_state] Blocked stale plan re-entry via "+ "flag for session=%s",session_id,)- else:- if isinstance(request.params, dict):- request.params["mode"] = "code.plan"+ elif state.plan_mode.plan_slug is not None:+ # Fallback: plan was completed, checkpoint is authoritative.+ # Clear slug so this guard is one-shot.+ state.plan_mode.plan_slug = None+ agent.get_instance().save_state(session, state)+ await session.post_run()+ blocked = Truelogger.info(- "[_ensure_code_mode_state] Blocked plan→normal without approval "- "for session=%s request_id=%s",+ "[_ensure_code_mode_state] Blocked stale plan re-entry via "+ "plan_slug for session=%s",session_id,- request.request_id,)- else:- agent.get_instance().switch_mode(session=session, mode=sub_mode)- # switch_mode/restore 内部已通过 save_state 写入 "deepagent" key,+ if blocked:+ if isinstance(request.params, dict):+ request.params["mode"] = "code.normal"+ await self._push_plan_mode_exited(request)+ return False+ agent.get_instance().switch_mode(session=session, mode=sub_mode)+ if state.plan_mode.mode == "plan" and sub_mode == "normal":+ restored_after_approval = True+ logger.info(+ "[_ensure_code_mode_state] Synced plan→normal for session=%s",+ session_id,+ )+ if sub_mode == "plan":+ mode_changed_to_plan = True+ # Clear stale plan_slug from previous plan session so+ # enter_plan_mode creates a fresh plan file.+ state = agent.get_instance().load_state(session)+ if state.plan_mode.plan_slug:+ state.plan_mode.plan_slug = None+ agent.get_instance().save_state(session, state)+ # switch_mode 内部已通过 save_state 写入 "deepagent" key,# 只需 post_run 持久化到 checkpointerawait session.post_run()- # 切换到 plan 模式且尚未调用 enter_plan_mode 时,- # 注入 <system-reminder> 告知 LLM 调用 enter_plan_mode。- if sub_mode == "plan" and not state.plan_mode.plan_slug:+ # 切换到 plan 模式时注入 <system-reminder> 告知 LLM 调用 enter_plan_mode。+ # 使用 mode_changed_to_plan 而非 plan_slug 判断,因为 restore_mode_after_plan_exit+ # 不清除 plan_slug,导致后续 /plan 时提醒被错误跳过。+ if sub_mode == "plan" and mode_changed_to_plan:_inject_plan_mode_activation_reminder(request)return restored_after_approval@@ -1617,13 +1475,12 @@ class AgentWebSocketServer:if restored_plan:await self._push_plan_mode_exited(request)- resp = await agent.process_message(request)-- # ── Pick up pending approval state from agent ──- _store_pending_approval_from_agent(- request.session_id or "default",- agent.get_instance(),- )+ resp = None+ try:+ 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)wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:@@ -1717,11 +1574,8 @@ class AgentWebSocketServer:if self._session_stream_tasks.get(session_id) is current_task:self._session_stream_tasks.pop(session_id, None)- # ── Pick up pending approval state from agent ──- _store_pending_approval_from_agent(- session_id,- agent.get_instance(),- )+ # Push plan.mode_exited if exit_plan_mode restored mode during processing+ await self._check_post_process_plan_exit(request, agent)logger.info("[AgentWebSocketServer] 流式响应已发送: request_id=%s 共 %s 个 chunk",@@ -2056,6 +1910,7 @@ class AgentWebSocketServer:)else:shutil.rmtree(session_dir)+ _plan_exited_sessions.discard(target)remove_session_metadata_cache(target)resp = AgentResponse(request_id=request.request_id,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 8dd18ed461..6aa910900a 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -55,7 +55,7 @@ from jiuwenswarm.agents.harness.code.prompt.code_prompt_builder import ()from jiuwenswarm.agents.harness.code.rails import (CodeTaskPlanningRail,- PlanApprovalRail,+ PlanApprovalInterruptRail,)from jiuwenswarm.agents.harness.common.rails import (ProjectMemoryRail,@@ -195,7 +195,7 @@ _RAIL_BUILD_NAMES: dict[str, str] = {"CodingMemoryRail": "_build_coding_memory_rail","WorktreeRail": "_build_worktree_rail_via_config","CodeAgentRail": "_build_code_agent_rail",- "PlanApprovalRail": "_build_plan_approval_rail",+ "PlanApprovalInterruptRail": "_build_plan_approval_rail",}_TOOL_BUILD_NAMES: dict[str, str] = {@@ -402,6 +402,21 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):raw = "cn"return resolve_language(raw)+ def _resolve_output_language(self) -> str:+ """Resolve user's preferred output language for runtime_state display.++ Distinct from prompt/runtime language (always "en" in code mode).+ Returns the normalized language code ("cn"/"en") based on+ config.yaml preferred_language, so the Language section injected+ by RuntimePromptRail can instruct the LLM to respond in the+ user's chosen language.+ """+ config_base = get_config()+ raw = str(config_base.get("preferred_language", "zh")).strip().lower()+ if raw == "zh":+ raw = "cn"+ return resolve_language(raw)+# ─── 初始化 ──────────────────────────────async def create_instance(self, config: dict[str, Any] | None = None, *,@@ -653,7 +668,16 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):return Nonedef _build_agent_mode_rail(self) -> AgentModeRail | None:- """构建 CodeAgentModeRail(plan 退出需用户批准后生效)."""+ """构建 CodeAgentModeRail。++ 与 Claude Code 对齐:+ - ``plan_mode_system_note``: 静态注入 system prompt(KV-cache 友好),+ 告知 LLM 必须先调 ``enter_plan_mode``。+ - ``enter_plan_instructions``: 追加到 ``enter_plan_mode`` 的 tool_result,+ 包含完整的 5-phase 工作流说明(指令在对话中,不在 system prompt)。+ - ``exit_plan_notification``: 追加到 ``exit_plan_mode`` 的 tool_result,+ 显式告知 LLM 已退出 plan 模式,可以开始编辑文件。+ """try:from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import (CodeAgentModeRail,@@ -661,6 +685,9 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):return CodeAgentModeRail(allowed_tools=_CODE_PLAN_ALLOWED_TOOLS,+ plan_mode_system_note=_PLAN_MODE_SYSTEM_NOTE,+ enter_plan_instructions=_ENTER_PLAN_MODE_INSTRUCTIONS_EN,+ exit_plan_notification=_EXIT_PLAN_MODE_NOTIFICATION,)except Exception as exc:logger.warning("[JiuwenSwarmCodeAdapter] CodeAgentModeRail create failed: %s", exc)@@ -690,7 +717,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):CodeConfirmInterruptRail,)- # exit_plan_mode 由 PlanApprovalRail 负责计划审批,不再走 ConfirmInterrupt。+ # exit_plan_mode 由 PlanApprovalInterruptRail 负责计划审批,不再走 ConfirmInterrupt。filtered = [name for name in (tool_names or []) if name != "exit_plan_mode"]return CodeConfirmInterruptRail(tool_names=filtered or ["switch_mode"])except Exception as exc:@@ -1041,14 +1068,18 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):logger.warning("[JiuwenSwarmCodeAdapter] CodeAgentRail create failed: %s", exc)return None- def _build_plan_approval_rail(self) -> PlanApprovalRail | None:- """构建 PlanApprovalRail,管理 plan 审批生命周期。"""+ def _build_plan_approval_rail(self) -> PlanApprovalInterruptRail | None:+ """构建 PlanApprovalInterruptRail,管理 plan 审批生命周期。++ ``exit_plan_mode`` 触发即时审批弹窗(对齐 Claude Code),+ 用户批准后立即恢复 normal 模式。+ """try:- rail = PlanApprovalRail()- logger.info("[JiuwenSwarmCodeAdapter] PlanApprovalRail created")+ rail = PlanApprovalInterruptRail()+ logger.info("[JiuwenSwarmCodeAdapter] PlanApprovalInterruptRail created")return railexcept Exception as exc:- logger.warning("[JiuwenSwarmCodeAdapter] PlanApprovalRail create failed: %s", exc)+ logger.warning("[JiuwenSwarmCodeAdapter] PlanApprovalInterruptRail create failed: %s", exc)return Nonedef _get_current_agent_rails(@@ -1057,7 +1088,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):"""扩展父类方法,将 Code/Plan 专属 Rail 纳入热重载范围。父类 _get_current_agent_rails 只返回 skill/context/memory 等 rail,- CodeAgentRail 和 PlanApprovalRail 不在其中。覆盖此方法确保 config reload+ CodeAgentRail 和 PlanApprovalInterruptRail 不在其中。覆盖此方法确保 config reload时这些 rail 被正确重新初始化。"""rails_list = super()._get_current_agent_rails(config, config_base)diff --git a/tests/unit_tests/agentserver/test_code_agent_mode_rail.py b/tests/unit_tests/agentserver/test_code_agent_mode_rail.pyindex 8ee4252ec8..87ac0706d5 100644--- a/tests/unit_tests/agentserver/test_code_agent_mode_rail.py+++ b/tests/unit_tests/agentserver/test_code_agent_mode_rail.py@@ -65,16 +65,21 @@ async def test_before_tool_call_blocks_non_git_write_in_plan_mode() -> None:assert ctx.extra.get("_skip_tool") is True-def test_init_patches_exit_plan_mode_invoke() -> None:+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+ ExitPlanModeTool handles mode restoration directly inside invoke().+ """rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])tool = MagicMock()+ original_invoke = object()+ tool.invoke = original_invoketool.card.name = "exit_plan_mode"tool._language = "cn"- tool._agent_ref = MagicMock()- tool._agent_ref.get_plan_file_path.return_value = Nonerail._tools = [tool]agent = MagicMock()rail.init(agent)- assert tool.invoke is not rail._patch_exit_plan_mode_tool+ # Verify the tool's invoke was NOT replaced+ assert tool.invoke is original_invokediff --git a/tests/unit_tests/agentserver/test_plan_approval.py b/tests/unit_tests/agentserver/test_plan_approval.pyindex d2673ab17e..d9a7825bd5 100644--- a/tests/unit_tests/agentserver/test_plan_approval.py+++ b/tests/unit_tests/agentserver/test_plan_approval.py@@ -1,36 +1,20 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Unit tests for text-only plan approval gate."""+"""Unit tests for plan approval utilities.++These NLP-based intent classifiers are kept as a fallback for text-based+approval in channels without TUI interrupt support.+"""# pylint: disable=protected-accessfrom jiuwenswarm.agents.harness.code.prompt.plan_approval import (- PLAN_USER_APPROVED_FLAG,classify_plan_user_intent,is_direct_plan_implement_request,)from jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethod-from jiuwenswarm.server.agent_ws_server import (- _check_and_handle_pending_approval,- _pending_plan_approvals,- _plan_approved_sessions,- AgentWebSocketServer,-)---def _make_request(session_id: str, query: str, mode: str = "code.normal") -> AgentRequest:- return AgentRequest(- request_id="req_test",- channel_id="tui",- session_id=session_id,- params={"query": query, "mode": mode},- )---def setup_function() -> None:- _pending_plan_approvals.clear()- _plan_approved_sessions.clear()+from jiuwenswarm.server.agent_ws_server import AgentWebSocketServerdef test_direct_plan_implement_requires_strong_signal() -> None:@@ -56,39 +40,6 @@ def test_classify_mixed_revision_overrides_short_approval() -> None:assert classify_plan_user_intent("可以,但是要把第二步改成异步") == "revise"-def test_pending_approval_accepts_free_text_approve() -> None:- session_id = "sess_approve"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan\n\nDo the thing",- "plan_slug": "test-plan",- "plan_path": "/tmp/plan.md",- }- request = _make_request(session_id, "可以,开始吧")-- assert _check_and_handle_pending_approval(request, language="cn") is True- assert session_id not in _pending_plan_approvals- assert request.params["mode"] == "code.normal"- assert request.params[PLAN_USER_APPROVED_FLAG] is True- assert session_id in _plan_approved_sessions- assert "用户已批准" in request.params["query"]- assert "Do the thing" in request.params["query"]---def test_approve_registers_session_level_flag() -> None:- session_id = "sess_flag"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan",- "plan_slug": "test-plan",- "plan_path": "/tmp/plan.md",- }- request = _make_request(session_id, "按计划实现")-- assert _check_and_handle_pending_approval(request, language="cn") is True- assert session_id in _plan_approved_sessions--def test_skills_list_does_not_sync_code_mode() -> None:request = AgentRequest(request_id="req_skills",@@ -98,64 +49,3 @@ def test_skills_list_does_not_sync_code_mode() -> None:params={"mode": "code.normal"},)assert AgentWebSocketServer._should_sync_code_mode_state(request) is False---def test_pending_approval_accepts_implement_phrase() -> None:- session_id = "sess_implement"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan",- "plan_slug": "test-plan",- "plan_path": "/tmp/plan.md",- }- request = _make_request(session_id, "按计划实现")-- assert _check_and_handle_pending_approval(request, language="cn") is True- assert request.params["mode"] == "code.normal"- assert request.params[PLAN_USER_APPROVED_FLAG] is True---def test_pending_approval_accepts_feedback_text() -> None:- session_id = "sess_feedback"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan",- "plan_slug": "test-plan",- "plan_path": "/tmp/plan.md",- }- request = _make_request(session_id, "多添加几个边界测试用例")-- assert _check_and_handle_pending_approval(request, language="cn") is True- assert request.params["mode"] == "code.plan"- assert PLAN_USER_APPROVED_FLAG not in request.params- assert "用户要求修订计划" in request.params["query"]- assert "多添加几个边界测试用例" in request.params["query"]---def test_pending_approval_ignores_structured_a2ui_event() -> None:- session_id = "sess_a2ui_event"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan",- "plan_slug": "test-plan",- "plan_path": "/tmp/plan.md",- }- event = {- "type": "a2ui.client_event",- "event": {- "userAction": {- "name": "submitForm",- "context": {"dietary": ["vegetarian"]},- }- },- }- request = AgentRequest(- request_id="req_a2ui_event",- channel_id="web",- session_id=session_id,- params={"query": event, "content": event, "mode": "agent.fast"},- )-- assert _check_and_handle_pending_approval(request, language="cn") is False- assert _pending_plan_approvals[session_id]["pending"] is True- assert request.params["query"] is eventdiff --git a/tests/unit_tests/agentserver/test_plan_approval_rail.py b/tests/unit_tests/agentserver/test_plan_approval_rail.pydeleted file mode 100644index f56470e4a1..0000000000--- a/tests/unit_tests/agentserver/test_plan_approval_rail.py+++ /dev/null@@ -1,60 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.--"""Unit tests for PlanApprovalRail deferred plan-mode exit."""--# pylint: disable=protected-access--from types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock--import pytest--from jiuwenswarm.agents.harness.code.rails.code_agent_mode_rail import CodeAgentModeRail-from jiuwenswarm.agents.harness.code.rails.code_plan_approval_rail import PlanApprovalRail---async def test_exit_plan_mode_appends_pending_marker_without_switching_mode() -> None:- rail = PlanApprovalRail()- agent = MagicMock()- plan_state = SimpleNamespace(mode="plan", plan_slug="test-plan")- agent.load_state.return_value = SimpleNamespace(plan_mode=plan_state)- agent.get_plan_file_path.return_value = None-- ctx = SimpleNamespace(- session=SimpleNamespace(),- inputs=SimpleNamespace(- tool_name="exit_plan_mode",- tool_result={"ok": True},- tool_msg=SimpleNamespace(- content="Plan submitted for your review.\n\n## Plan:\nstep 1",- ),- ),- extra={},- )-- rail._agent = agent- await rail.after_tool_call(ctx)-- agent.switch_mode.assert_not_called()- assert getattr(agent, "_plan_approval_state").pending is True- assert "仍在规划模式" in ctx.inputs.tool_msg.content---async def test_code_agent_mode_rail_skips_exit_after_tool_call() -> None:- rail = CodeAgentModeRail(allowed_tools=["exit_plan_mode"])- rail._agent = MagicMock()- parent = AsyncMock()- rail.__class__.__bases__[0].after_tool_call = parent-- ctx = SimpleNamespace(- inputs=SimpleNamespace(- tool_name="exit_plan_mode",- tool_result={"ok": True},- ),- extra={},- )-- await rail.after_tool_call(ctx)- parent.assert_not_called()diff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pyindex cd0f03ba4d..682887a61c 100644--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -1,33 +1,32 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""End-to-end orchestration tests for plan mode approval and exit flows."""+"""End-to-end orchestration tests for plan mode — aligned with Claude Code.++Plan approval is now handled by ``PlanApprovalInterruptRail`` which intercepts+``exit_plan_mode`` with an immediate approval dialog. Mode restoration happens+inside ``ExitPlanModeTool.invoke()`` via ``restore_mode_after_plan_exit()``.+The server-side pending-approval gate has been removed.+"""++# pylint: disable=protected-accessfrom __future__ import annotations-from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest-from jiuwenswarm.agents.harness.code.prompt.plan_approval import PLAN_USER_APPROVED_FLAGfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethod-from jiuwenswarm.server.agent_ws_server import (- AgentWebSocketServer,- _check_and_handle_pending_approval,- _pending_plan_approvals,- _plan_approved_sessions,- _try_handle_direct_plan_implement,-)+from jiuwenswarm.server.agent_ws_server import AgentWebSocketServerdef _chat_request(session_id: str,- query: str,+ query: str = "hello",*,mode: str = "code.plan",- req_method: ReqMethod = ReqMethod.CHAT_SEND,extra_params: dict | None = None,) -> AgentRequest:params: dict = {"query": query, "mode": mode}@@ -37,134 +36,43 @@ def _chat_request(request_id="req_flow",channel_id="tui",session_id=session_id,- req_method=req_method,+ req_method=ReqMethod.CHAT_SEND,params=params,)-def setup_function() -> None:- _pending_plan_approvals.clear()- _plan_approved_sessions.clear()--@pytest.mark.asyncio-async def test_direct_implement_refetches_normal_agent_instance(tmp_path: Path) -> None:- """TUI still sends code.plan; server must switch to code:normal agent after approval."""- session_id = "sess_refetch"- plan_file = tmp_path / "sliding-window.md"- plan_file.write_text("# Plan\n\nImplement sliding window.", encoding="utf-8")-- plan_agent = MagicMock()- plan_instance = MagicMock()- normal_agent = MagicMock()- normal_instance = MagicMock()- plan_agent.get_instance.return_value = plan_instance- normal_agent.get_instance.return_value = normal_instance-- plan_state = SimpleNamespace(mode="plan", plan_slug="sliding-window")- plan_instance.card = SimpleNamespace(id="code-agent")- normal_instance.card = SimpleNamespace(id="code-agent")- plan_instance.load_state.return_value = SimpleNamespace(plan_mode=plan_state)- plan_instance.get_plan_file_path.return_value = plan_file- plan_instance.restore_mode_after_plan_exit = MagicMock()-- manager = MagicMock()- manager.get_agent = AsyncMock(side_effect=[plan_agent, normal_agent])-- server = AgentWebSocketServer.__new__(AgentWebSocketServer)- server._agent_manager = manager- server._resolve_code_language = MagicMock(return_value="cn")-- request = _chat_request(session_id, "好,那按计划实现吧", mode="code.plan")-- mock_session = MagicMock()- mock_session.pre_run = AsyncMock()- with (- patch(- "openjiuwen.core.single_agent.create_agent_session",- MagicMock(return_value=mock_session),- ),- patch.object(- AgentWebSocketServer,- "_ensure_code_mode_state",- new_callable=AsyncMock,- return_value=True,- ) as ensure_mock,- ):- mode, sub_mode, agent = await server._prepare_code_mode_chat_turn(- request, "tui"- )-- assert manager.get_agent.await_count == 2- second_call = manager.get_agent.await_args_list[1].kwargs- assert second_call["sub_mode"] == "normal"- assert agent is normal_agent- assert sub_mode == "normal"- assert request.params["mode"] == "code.normal"- assert session_id in _plan_approved_sessions- assert "用户已批准" in request.params["query"]- ensure_mock.assert_not_called()+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+ without plan-approval side effects.+ """+ session_id = "sess_basic"--async def test_pending_approval_uses_normal_agent_without_extra_refetch() -> None:- session_id = "sess_pending"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan\nstep 1",- "plan_slug": "test",- "plan_path": "/tmp/plan.md",- }-- normal_agent = MagicMock()+ agent = MagicMock()manager = MagicMock()- manager.get_agent = AsyncMock(return_value=normal_agent)+ manager.get_agent = AsyncMock(return_value=agent)server = AgentWebSocketServer.__new__(AgentWebSocketServer)server._agent_manager = managerserver._resolve_code_language = MagicMock(return_value="cn")- request = _chat_request(session_id, "按计划实现", mode="code.plan")+ request = _chat_request(session_id, "hello", mode="code.plan")- mode, sub_mode, agent = await server._prepare_code_mode_chat_turn(request, "tui")+ mode, sub_mode, resolved_agent = await server._prepare_code_mode_chat_turn(+ request, "tui"+ )- assert manager.get_agent.await_count == 1- assert sub_mode == "normal"- assert agent is normal_agent- assert session_id not in _pending_plan_approvals+ assert mode == "code"+ assert sub_mode == "plan"+ assert resolved_agent is agent+ manager.get_agent.assert_awaited_once()@pytest.mark.asyncio-async def test_confirm_interrupt_resume_does_not_consume_pending_approval() -> None:- session_id = "sess_interrupt"- _pending_plan_approvals[session_id] = {- "pending": True,- "plan_content": "# Plan",- "plan_slug": "test",- "plan_path": "/tmp/plan.md",- }-- assert (- _check_and_handle_pending_approval(- _chat_request(- session_id,- "",- extra_params={- "request_id": "tool_req_1",- "answers": {"approved": False},- "source": "confirm_interrupt",- },- ),- language="cn",- )- is False- )- assert session_id in _pending_plan_approvals-+async def test_ensure_code_mode_state_syncs_plan_to_normal() -> None:+ """_ensure_code_mode_state syncs plan→normal when modes differ."""+ session_id = "sess_sync"-async def test_blocked_plan_to_normal_without_approval(tmp_path: Path) -> None:- session_id = "sess_block"plan_agent = MagicMock()plan_instance = MagicMock()plan_agent.get_instance.return_value = plan_instance@@ -178,7 +86,6 @@ async def test_blocked_plan_to_normal_without_approval(tmp_path: Path) -> None:post_run = AsyncMock()server = AgentWebSocketServer.__new__(AgentWebSocketServer)-request = _chat_request(session_id, "hello", mode="code.normal")with patch(@@ -191,15 +98,14 @@ async def test_blocked_plan_to_normal_without_approval(tmp_path: Path) -> None:request, "code", "normal", plan_agent)- assert restored is False- assert request.params["mode"] == "code.plan"- plan_instance.restore_mode_after_plan_exit.assert_not_called()+ assert restored is True+ plan_instance.switch_mode.assert_called_once_with(session=session, mode="normal")@pytest.mark.asyncio-async def test_ensure_restores_plan_to_normal_after_approval(tmp_path: Path) -> None:- session_id = "sess_restore"- _plan_approved_sessions.add(session_id)+async def test_ensure_code_mode_state_skips_if_mode_already_matches() -> None:+ """_ensure_code_mode_state does nothing when plan_mode already matches."""+ session_id = "sess_skip"plan_agent = MagicMock()plan_instance = MagicMock()@@ -210,169 +116,72 @@ async def test_ensure_restores_plan_to_normal_after_approval(tmp_path: Path) ->session = MagicMock()create_session = MagicMock(return_value=session)- pre_run = AsyncMock()- post_run = AsyncMock()server = AgentWebSocketServer.__new__(AgentWebSocketServer)- request = _chat_request(session_id, "injected approval", mode="code.normal")- request.params[PLAN_USER_APPROVED_FLAG] = True+ request = _chat_request(session_id, "hello", mode="code.plan")with patch("openjiuwen.core.single_agent.create_agent_session",create_session,):- session.pre_run = pre_run- session.post_run = post_run+ session.pre_run = AsyncMock()+ session.post_run = AsyncMock()restored = await server._ensure_code_mode_state(- request, "code", "normal", plan_agent+ request, "code", "plan", plan_agent)- assert restored is True- plan_instance.restore_mode_after_plan_exit.assert_called_once_with(session)- assert session_id not in _plan_approved_sessions+ assert restored is False+ plan_instance.switch_mode.assert_not_called()@pytest.mark.asyncio-async def test_direct_implement_reads_plan_file(tmp_path: Path) -> None:- session_id = "sess_direct"- plan_file = tmp_path / "plan.md"- plan_file.write_text("# Direct plan body", encoding="utf-8")-+async def test_ensure_skips_for_team_sub_mode() -> None:+ """_ensure_code_mode_state returns False for team sub_mode."""agent = MagicMock()- instance = MagicMock()- agent.get_instance.return_value = instance- instance.card = SimpleNamespace(id="code-agent")- instance.load_state.return_value = SimpleNamespace(- plan_mode=SimpleNamespace(mode="plan", plan_slug="plan")- )- instance.get_plan_file_path.return_value = plan_file-- request = _chat_request(session_id, "按计划实现")- session = MagicMock()- with patch(- "openjiuwen.core.single_agent.create_agent_session",- MagicMock(return_value=session),- ):- session.pre_run = AsyncMock()- handled = await _try_handle_direct_plan_implement(- request,- agent,- language="cn",- )-- assert handled is True- assert "Direct plan body" in request.params["query"]---async def test_direct_implement_ignores_structured_a2ui_event() -> None:- event = {- "type": "a2ui.client_event",- "event": {- "userAction": {- "name": "submitForm",- "context": {"dietary": ["vegetarian"]},- }- },- }- request = AgentRequest(- request_id="req_a2ui_event",- channel_id="web",- session_id="sess_a2ui_event",- params={"query": event, "content": event, "mode": "agent.fast"},- )-- handled = await _try_handle_direct_plan_implement(- request,- MagicMock(),- language="cn",- )+ server = AgentWebSocketServer.__new__(AgentWebSocketServer)+ request = _chat_request("sess_team", mode="code.team")- assert handled is False- assert request.params["query"] is event+ restored = await server._ensure_code_mode_state(request, "code", "team", agent)+ assert restored is False@pytest.mark.asyncio-async def test_reject_switch_mode_then_direct_implement_exits_plan(- tmp_path: Path,-) -> None:- """Reproduce stuck scenario: reject switch_mode confirm, then chat approve."""- session_id = "sess_stuck"- plan_file = tmp_path / "plan.md"- plan_file.write_text("# Sliding window plan\nstep 1", encoding="utf-8")-- plan_agent = MagicMock()- normal_agent = MagicMock()- plan_instance = MagicMock()- normal_instance = MagicMock()- plan_agent.get_instance.return_value = plan_instance- normal_agent.get_instance.return_value = normal_instance- plan_instance.card = SimpleNamespace(id="code-agent")- normal_instance.card = SimpleNamespace(id="code-agent")- plan_instance.load_state.return_value = SimpleNamespace(- plan_mode=SimpleNamespace(mode="plan", plan_slug="plan")- )- plan_instance.get_plan_file_path.return_value = plan_file+async def test_prepare_chat_turn_skips_approval_for_interrupt_resume() -> None:+ """_prepare_code_mode_chat_turn works correctly for interrupt resume requests."""+ session_id = "sess_interrupt"+ agent = MagicMock()manager = MagicMock()- manager.get_agent = AsyncMock(side_effect=[plan_agent, normal_agent])+ manager.get_agent = AsyncMock(return_value=agent)server = AgentWebSocketServer.__new__(AgentWebSocketServer)server._agent_manager = managerserver._resolve_code_language = MagicMock(return_value="cn")- # Step 1: user rejects switch_mode — pending must survive (none here).- reject_req = _chat_request(+ request = _chat_request(session_id,"",+ mode="code.plan",extra_params={- "request_id": "sw_1",- "answers": {"approved": False},+ "request_id": "tool_req_1",+ "answers": {"approved": True},"source": "confirm_interrupt",},)- assert _check_and_handle_pending_approval(reject_req, language="cn") is False- # Step 2: user approves implementation in chat while TUI still shows plan.- mock_session = MagicMock()- mock_session.pre_run = AsyncMock()- implement_req = _chat_request(session_id, "好,那按计划实现吧", mode="code.plan")+ mode, sub_mode, _agent = await server._prepare_code_mode_chat_turn(request, "tui")- with patch(- "openjiuwen.core.single_agent.create_agent_session",- MagicMock(return_value=mock_session),- ):- mode, sub_mode, agent = await server._prepare_code_mode_chat_turn(- implement_req, "tui"- )-- assert sub_mode == "normal"- assert agent is normal_agent- assert implement_req.params["mode"] == "code.normal"- assert session_id in _plan_approved_sessions+ assert mode == "code"+ assert sub_mode == "plan"+ manager.get_agent.assert_awaited_once()@pytest.mark.asyncio-async def test_skills_list_does_not_restore_plan_mode() -> None:- session_id = "sess_skills"- _plan_approved_sessions.add(session_id)-- plan_agent = MagicMock()- plan_instance = MagicMock()- plan_agent.get_instance.return_value = plan_instance-+async def test_ensure_skips_for_agent_mode() -> None:+ """_ensure_code_mode_state returns False for non-code modes."""+ agent = MagicMock()server = AgentWebSocketServer.__new__(AgentWebSocketServer)- request = AgentRequest(- request_id="req_skills",- channel_id="tui",- session_id=session_id,- req_method=ReqMethod.SKILLS_LIST,- params={"mode": "code.normal"},- )-- restored = await server._ensure_code_mode_state(- request, "code", "normal", plan_agent- )+ request = _chat_request("sess_agent", mode="agent.fast")+ restored = await server._ensure_code_mode_state(request, "agent", "fast", agent)assert restored is False- plan_instance.restore_mode_after_plan_exit.assert_not_called()diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 94af17cd9a..54ce5501e5 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -222,7 +222,7 @@ async def test_runtime_prompt_uses_runtime_cwd_over_stale_trusted_dir(tmp_path):prompt = builder.build()assert "Current project directory" not in promptrendered = agent.prompt_attachment_manager.render(- await agent.prompt_attachment_manager.collect_for_session("sess1")+ await agent.prompt_attachment_manager.list_by_filter(session_id="sess1"))assert "Current project directory" in renderedassert str(current_dir) in rendered@@ -259,7 +259,7 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtimeprompt = builder.build()assert "Always respond in Chinese." in promptrendered = agent.prompt_attachment_manager.render(- await agent.prompt_attachment_manager.collect_for_session("sess1")+ await agent.prompt_attachment_manager.list_by_filter(session_id="sess1"))assert "Always respond in Chinese." not in renderedassert "Always respond in English." not in rendered