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(tui): stabilize plan approval reject flow
ldstyle865a7d9df170d
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 476defc4f6..f32b83fe70 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -195,6 +195,10 @@ const DEFERRED_TRANSCRIPT_EVENTS = new Set(["harness.activate_interaction",]);+function isPlanClientMode(mode: ClientMode): boolean {+ return mode === "agent.plan" || mode === "code.plan" || mode === "team.plan";+}+// ── Auto-recap (自动回顾) 常量 ──/** 用户空闲多久后自动触发回顾(5分钟)。 */const AUTO_RECAP_IDLE_THRESHOLD_MS = 5 * 60_000;@@ -235,6 +239,43 @@ function isLocalFileSearchTool(name: string): boolean {return LOCAL_FILE_SEARCH_TOOL_NAMES.has(name.trim().toLowerCase());}+function isRejectOption(label: string): boolean {+ const normalized = label.trim();+ return (+ normalized.includes("拒绝") || /^reject\b/i.test(normalized) || /^deny\b/i.test(normalized)+ );+}++function isPlanApprovalRejectWithoutFeedback(+ pendingQuestion: PendingQuestion,+ answers: UserAnswer[],+): boolean {+ if (+ pendingQuestion.source !== "confirm_interrupt" ||+ pendingQuestion.planApprovalKind !== "plan_approval"+ ) {+ return false;+ }++ const rejected = answers.some((answer) =>+ answer.selected_options.some((option) => isRejectOption(option)),+ );+ if (!rejected) {+ return false;+ }++ return answers.every((answer) => !answer.custom_input?.trim());+}++function withPlanApprovalCancelFeedback(answers: UserAnswer[]): UserAnswer[] {+ return answers.map((answer) => ({+ ...answer,+ custom_input:+ answer.custom_input?.trim() ||+ "用户取消了本次计划审批。请保持 plan 模式并等待用户下一条指令,不要继续调用 exit_plan_mode。",+ }));+}+function detectRipgrep(): boolean {try {const result = spawnSync("rg", ["--version"], { stdio: "ignore" });@@ -334,6 +375,7 @@ export class CliPiAppState {private activeCommandRequestId: string | null = null;/** 当前正在执行的命令名称,用于追踪不可中断命令。 */private runningCommand: string | null = null;+ private pendingPlanEntrySource: "slash_command" | null = null;private lastVisibleUserRequest: VisibleUserRequest | null = null;/** 保存 askQuestions 之前的 streamingState,用于在对话框关闭后恢复。 */private streamingStateBeforeQuestion: StreamingState | null = null;@@ -1019,6 +1061,7 @@ export class CliPiAppState {connectionStatus: snapshot.connectionStatus,mode: snapshot.mode,setMode: this.setMode,+ markPlanEntryFromSlashCommand: this.markPlanEntryFromSlashCommand,setModel: this.setModel,setPreferredLanguage: this.setPreferredLanguage,setThemeName: this.setThemeName,@@ -1237,6 +1280,7 @@ export class CliPiAppState {this.workflowRuns = [];this.btwOverlay = null;this._btwActive = false;+ this.pendingPlanEntrySource = null;if (this.accentColor !== "default") {this.accentColor = "default";setCurrentAccentColor("default");@@ -1373,12 +1417,19 @@ export class CliPiAppState {};readonly setMode = (mode: ClientMode): void => {+ if (!isPlanClientMode(mode)) {+ this.pendingPlanEntrySource = null;+ }if (this.mode !== mode) {this.mode = mode;this.emitChange();}};+ readonly markPlanEntryFromSlashCommand = (): void => {+ this.pendingPlanEntrySource = "slash_command";+ };+readonly setModel = (name: string): void => {const trimmed = name.trim();if (trimmed && this.modelInfo.model !== trimmed) {@@ -1475,9 +1526,17 @@ export class CliPiAppState {): string | null => {if (this.connectionStatus !== "connected") return null;const mode = modeOverride ?? this.mode;+ const planEntrySource = isPlanClientMode(mode) ? this.pendingPlanEntrySource : null;+ const params = {+ content,+ query: content,+ mode,+ ...(attachments?.length ? { attachments } : {}),+ ...(planEntrySource ? { plan_entry_source: planEntrySource } : {}),+ };// Pre-check: reject messages whose serialized frame exceeds 7 MB (gateway// server max_size is 8 MB; leave 1 MB margin for JSON overhead).- const estimatedSize = JSON.stringify({ type: "req", method: "chat.send", params: { content, query: content, mode, ...(attachments?.length ? { attachments } : {}) } }).length;+ const estimatedSize = JSON.stringify({ type: "req", method: "chat.send", params }).length;if (estimatedSize > 7 * 1024 * 1024) {this.addItem(addError(this.sessionId, `消息过大(约 ${Math.round(estimatedSize / 1024 / 1024)} MB),请缩短输入内容。`));this.emitChange();@@ -1490,14 +1549,12 @@ export class CliPiAppState {}const requestId = this.sendEventOnly("chat.send",- {- content,- query: content,- mode,- ...(attachments?.length ? { attachments } : {}),- },+ params,true,);+ if (planEntrySource) {+ this.pendingPlanEntrySource = null;+ }this.lastError = null;this.resetCurrentUsageTokens();if (options?.logAsUser !== false) {@@ -1622,6 +1679,24 @@ export class CliPiAppState {this.emitChange();return;}+ if (isPlanApprovalRejectWithoutFeedback(this.pendingQuestion, answers)) {+ const resumeMode = this.pendingQuestion.resumeMode ?? this.mode;+ this.sendEventOnly("chat.send", {+ query: "",+ request_id: this.pendingQuestion.requestId,+ answers: withPlanApprovalCancelFeedback(answers),+ source: this.pendingQuestion.source,+ mode: resumeMode,+ plan_approval_kind: this.pendingQuestion.planApprovalKind,+ plan_content: this.pendingQuestion.planContent ?? "",+ plan_language: this.pendingQuestion.planLanguage ?? "cn",+ });+ this.pendingQuestion = null;+ this.setStreamingStateInternal(StreamingState.Idle);+ this.streamingStateBeforeQuestion = null;+ this.emitChange();+ return;+ }const source = this.pendingQuestion.source;const approvalTransport =this.pendingQuestion.evolutionMeta &&diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.tsindex 07916b663e..84ed3c2bba 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/plan.ts@@ -29,6 +29,7 @@ export function createPlanCommand(): SlashCommand {if (ctx.mode !== target) {ctx.setMode(target);}+ ctx.markPlanEntryFromSlashCommand?.();if (!value) {ctx.addItem(addInfo(ctx.sessionId, "Plan mode enabled", "p"));diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.tsindex 54ac8bbbe1..b9d0815175 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/types.ts@@ -71,6 +71,7 @@ export interface CommandContext {connectionStatus: ConnectionStatus;mode: ClientMode;setMode: (mode: ClientMode) => void;+ markPlanEntryFromSlashCommand?: () => void;setModel: (name: string) => void;setPreferredLanguage: (language: PreferredLanguage) => void;setThemeName: (theme: ThemeName) => void;diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts b/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.tsindex 183fbaff26..e150f998f6 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/screen-layout.ts@@ -124,6 +124,10 @@ function connectionStatusLabel(status: AppSnapshot["connectionStatus"]): string}}+function isPlanMode(mode: AppSnapshot["mode"]): boolean {+ return mode === "agent.plan" || mode === "code.plan" || mode === "team.plan";+}+function buildStatusLines(snapshot: AppSnapshot,width: number,@@ -142,6 +146,7 @@ function buildStatusLines(left.push(displayTitle);}left.push(`mode:${snapshot.mode}`);+ if (isPlanMode(snapshot.mode)) left.push("使用 /mode 退出plan模式");if (snapshot.transcriptFoldMode !== "none") left.push(`fold:${snapshot.transcriptFoldMode}`);const teamWorking =isTeamMode(snapshot.mode) &&diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 3f6a80e4b4..3628eeb31c 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -1356,6 +1356,12 @@ class AgentWebSocketServer:return Truereturn method in _CODE_MODE_SYNC_METHODS+ @staticmethod+ 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"+@staticmethoddef _session_mode_sync_lock(session_id: str) -> asyncio.Lock:lock = _session_mode_sync_locks.get(session_id)@@ -1454,8 +1460,8 @@ class AgentWebSocketServer:) -> bool:"""code 模式:确保 agent 的 plan_mode 状态正确,必要时执行 switch_mode 并持久化.- 当 plan 已完成(plan_slug 存在且 mode 不为 "plan")时跳过 switch_mode,- 避免 exit_plan_mode 已恢复的模式被覆盖.+ 当 plan 刚完成时跳过陈旧的 normal→plan switch_mode,+ 避免 exit_plan_mode 已恢复的模式被覆盖;显式用户 /plan 进入除外.switch_mode 内部已通过 save_state 写入正确的 "deepagent" key,此处只需 post_run 持久化到 checkpointer.@@ -1495,12 +1501,16 @@ class AgentWebSocketServer:mode_changed_to_plan = Falseif state.plan_mode.mode != sub_mode:# Guard: block stale normal→plan switches when plan was already exited.+ # Explicit user /plan requests bypass this guard and start a fresh plan.# 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:+ explicit_plan_entry = self._is_explicit_plan_entry_request(request)+ if explicit_plan_entry:+ _plan_exited_sessions.discard(session_id)+ elif session_id in _plan_exited_sessions:_plan_exited_sessions.discard(session_id)blocked = Truelogger.info(diff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pyindex 682887a61c..6ccb237945 100644--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -19,6 +19,7 @@ import pytestfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server import agent_ws_server as agent_ws_server_modulefrom jiuwenswarm.server.agent_ws_server import AgentWebSocketServer@@ -134,6 +135,50 @@ async def test_ensure_code_mode_state_skips_if_mode_already_matches() -> None:plan_instance.switch_mode.assert_not_called()+async def test_ensure_code_mode_state_allows_explicit_plan_reentry_after_exit() -> None:+ """A user-triggered /plan re-entry must not be blocked by stale exit guards."""+ session_id = "sess_explicit_reentry"++ plan_agent = MagicMock()+ plan_instance = MagicMock()+ plan_agent.get_instance.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)+ server._push_plan_mode_exited = AsyncMock()+ request = _chat_request(+ session_id,+ "implement this in plan mode",+ mode="code.plan",+ extra_params={"plan_entry_source": "slash_command"},+ )++ 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 server._ensure_code_mode_state(+ 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")+ server._push_plan_mode_exited.assert_not_awaited()+ assert request.params["mode"] == "code.plan"++@pytest.mark.asyncioasync def test_ensure_skips_for_team_sub_mode() -> None:"""_ensure_code_mode_state returns False for team sub_mode."""