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(ask_user): block empty Other and reject non-array options
NickFuryXXX1928ca5c488c
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.pyindex 1ef48518d2..c10f1cb444 100644--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py@@ -415,6 +415,14 @@ class StructuredAskUserRail(AskUserRail):value_text = selected if isinstance(selected, str) else ", ".join(selected)answer_parts.append(f"{q_text}: {value_text}")answer_text = "\n".join(answer_parts) if answer_parts else ""+ if not answer_text.strip():+ # Empty resume (e.g. bare Other) must not look like a valid answer (#2330).+ return self.reject(+ tool_result=(+ "[INVALID_ARGUMENT] answers must include at least "+ "one non-empty response."+ )+ )logger.info("[StructuredAskUserRail] Resolved structured answer: %s",answer_text,diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex 403371274c..2811bb369f 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -672,6 +672,9 @@ def _build_multi_questions(questions_data: list) -> list:questions = []for q in questions_data:raw_options = q.get("options", [])+ # Non-array options (e.g. "a,b") must not be iterated as characters (#2331).+ if not isinstance(raw_options, list):+ raw_options = []if raw_options:options = [_normalize_question_option(opt) for opt in raw_options if isinstance(opt, dict)]options.append({"label": "Other", "description": "Custom input"})diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex bd36bcb208..ddf6546c8e 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -3272,7 +3272,8 @@ export class AppScreen implements Component, Focusable {const { content, attachments } = this.buildOutgoingMessage(text);const snapshot = this.state.getSnapshot();- if (!content && !(snapshot.pendingQuestion && this.otherInputMode)) return;+ // Other 自定义输入模式下空内容不得提交(#2330),避免触发黄色 thinking。+ if (!content) return;if (snapshot.pendingQuestion) {if (this.questionList !== null) {diff --git a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsxindex a7798785db..12235e78ed 100644--- a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx@@ -121,6 +121,9 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)[patch],);+ /** 当前页是否选了 Other 却未填写自定义内容(禁止前进/提交,避免空答触发 thinking)。 */+ const incompleteCustom = st.customActive && !st.custom.trim();+/** 把某页状态转为一个 UserAnswer。 */const answerFor = useCallback((idx: number, overrides?: Record<number, PageState>): UserAnswer => {@@ -132,6 +135,10 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)if (s.skippedNoSelection && s.selected.length === 0 && !customText) {return { question: q?.question, selected_options: [], custom_input: SKIPPED_ANSWER_TEXT };}+ // Other 已激活但未输入:不得回落成第一个普通选项(#2330)。+ if (s.customActive && !customText) {+ return { question: q?.question, selected_options: [], custom_input: '' };+ }const answer: UserAnswer = { question: q?.question, selected_options: [...s.selected] };if (customText) answer.custom_input = customText;// 兜底:既无选择也无输入、且不是显式跳过时,默认第一个普通选项(避免后端拿到空答案)。@@ -209,9 +216,11 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)}, [total]);const handleNextOrConfirm = useCallback(() => {+ // Other 空输入:留在当前页提示用户填写,勿提交以免进入黄色 thinking(#2330)。+ if (incompleteCustom) return;if (isLast) submit(true);else goNextPage();- }, [isLast, submit, goNextPage]);+ }, [incompleteCustom, isLast, submit, goNextPage]);const handleSkip = useCallback(() => {// 跳过:无论当前页此前是否已经选中过某个选项/填过自定义输入,点击"跳过"@@ -353,7 +362,7 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)type="button"className="ix-btn ix-btn--primary"onClick={handleNextOrConfirm}- disabled={submitting}+ disabled={submitting || incompleteCustom}>{isLast ? t('interactionPrompt.confirm') : t('interactionPrompt.nextStep')}</button>diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex b712c8b23f..ac69125800 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1321,10 +1321,15 @@ class JiuWenSwarm:else:answer_value = custom_inputelif len(cleaned_options) == 1:- answer_value = cleaned_options[0]+ # Bare "Other" without custom text is incomplete (#2330).+ sole = cleaned_options[0]+ answer_value = "" if sole == "Other" else soleelif cleaned_options:- # Multi-select: preserve the full list of selections.- answer_value = cleaned_options+ # Multi-select: preserve real choices; drop placeholder-only Other.+ normal_options = [+ option for option in cleaned_options if option != "Other"+ ]+ answer_value = normal_options if normal_options else ""else:answer_value = ""elif custom_input:diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.pyindex 7bd8b8ee67..1f0f4984a8 100644--- a/tests/system_tests/test_structured_ask_user.py+++ b/tests/system_tests/test_structured_ask_user.py@@ -752,10 +752,10 @@ class TestStructuredAskUserRailResolveInterrupt:assert payload["questions"][0]["header"] == "Question"@staticmethod- @pytest.mark.parametrize("options", [None, {}, "not an array", 123])+ @pytest.mark.parametrize("options", [None, {}, "not an array", "a,b", 123])@pytest.mark.asyncioasync def test_non_array_options_are_rejected(options):- """An explicitly provided options value must be an array."""+ """An explicitly provided options value must be an array (#2331)."""rail = StructuredAskUserRail()tc = _make_tool_call(arguments={"query": "Choose",diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex ad3d7bd7d6..9a65ca4bd7 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -558,6 +558,48 @@ def test_build_inputs_merges_multi_select_custom_input(monkeypatch):}+def test_build_inputs_drops_bare_other_without_custom_input(monkeypatch):+ """Regression for #2330: empty Other must not become answer value \"Other\"."""+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _config: "disabled")++ request = AgentRequest(+ request_id="req-answer",+ channel_id="tui",+ session_id="team-session",+ params={+ "query": "",+ "mode": "team.plan",+ "request_id": "tool-ask-1",+ "source": "ask_user_interrupt",+ "answers": [+ {+ "question": "选择技术栈?",+ "selected_options": ["Other"],+ "custom_input": "",+ },+ {+ "question": "多选模块?",+ "selected_options": ["Other"],+ "custom_input": " ",+ },+ ],+ },+ )++ inputs, _, _ = interface_module.JiuWenSwarm().build_inputs(request)++ assert isinstance(inputs["query"], InteractiveInput)+ assert inputs["query"].user_inputs == {+ "tool-ask-1": {+ "answers": {},+ }+ }++def test_chat_answer_routes_team_plan_confirm_interrupt_to_adapter(monkeypatch):from jiuwenswarm.server.runtime.agent_adapter import interface as interface_modulediff --git a/tests/unit_tests/agentserver/test_ask_user_validation.py b/tests/unit_tests/agentserver/test_ask_user_validation.pynew file mode 100644index 0000000000..43ffcbe17d--- /dev/null+++ b/tests/unit_tests/agentserver/test_ask_user_validation.py@@ -0,0 +1,100 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for ask_user options/answers validation (#2330, #2331)."""++from __future__ import annotations++import json+from unittest.mock import MagicMock++import pytest+from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall+from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult, RejectResult++from jiuwenswarm.agents.harness.common.rails.ask_user_rail import StructuredAskUserRail+++def _make_tool_call(arguments: dict) -> ToolCall:+ return ToolCall(+ id="tc_ask",+ type="function",+ name="ask_user",+ arguments=json.dumps(arguments),+ )+++async def test_options_string_a_b_is_rejected():+ """Issue #2331: options='a,b' must reject instead of silent no-UI."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(+ {+ "query": "Choose",+ "questions": [+ {+ "question": "Which option?",+ "header": "Choice",+ "options": "a,b",+ }+ ],+ }+ )++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ assert isinstance(decision, RejectResult)+ assert "questions[0].options must be an array" in decision.tool_result+++async def test_valid_options_still_interrupt():+ rail = StructuredAskUserRail()+ tc = _make_tool_call(+ {+ "query": "Choose",+ "questions": [+ {+ "question": "Which option?",+ "header": "Choice",+ "options": [+ {"label": "A", "description": "a"},+ {"label": "B", "description": "b"},+ ],+ }+ ],+ }+ )++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ assert isinstance(decision, InterruptResult)+++async def test_empty_structured_answers_are_rejected():+ """Issue #2330: empty resume (bare Other) must not resolve as a blank answer."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(+ {+ "query": "Choose",+ "questions": [+ {+ "question": "Which option?",+ "header": "Choice",+ "options": [+ {"label": "A", "description": "a"},+ {"label": "B", "description": "b"},+ ],+ }+ ],+ }+ )++ decision = await rail.resolve_interrupt(+ MagicMock(),+ tc,+ {"answers": {}},+ )++ assert isinstance(decision, RejectResult)+ assert "answers must include at least one non-empty response" in decision.tool_resultdiff --git a/tests/unit_tests/agentserver/test_interrupt_helpers.py b/tests/unit_tests/agentserver/test_interrupt_helpers.pyindex 99e75b92be..fd5c78a6a3 100644--- a/tests/unit_tests/agentserver/test_interrupt_helpers.py+++ b/tests/unit_tests/agentserver/test_interrupt_helpers.py@@ -166,3 +166,44 @@ def test_scene_hook_leaves_other_tools_to_engine():outcome = asyncio.run(hook(_scene_hook_input("bash", None)))assert outcome is None+++def test_build_multi_questions_ignores_string_options():+ """Regression for #2331: options='a,b' must not become character options + Other."""+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ _build_multi_questions,+ )++ questions = _build_multi_questions(+ [+ {+ "question": "Which option?",+ "header": "Choice",+ "options": "a,b",+ }+ ]+ )++ assert len(questions) == 1+ assert questions[0]["options"] == []+++def test_build_multi_questions_appends_other_for_valid_options():+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ _build_multi_questions,+ )++ questions = _build_multi_questions(+ [+ {+ "question": "Which option?",+ "header": "Choice",+ "options": [+ {"label": "A", "description": "opt a"},+ {"label": "B", "description": "opt b"},+ ],+ }+ ]+ )++ assert [opt["label"] for opt in questions[0]["options"]] == ["A", "B", "Other"]