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): validate structured question fields and allow free-text options
ldstyle87d27b49e27ba
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.pyindex 641895e8aa..9cc6fd33f8 100644--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py@@ -40,6 +40,8 @@ from openjiuwen.harness.rails.interrupt.interrupt_base import (logger = logging.getLogger(__name__)+MAX_STRUCTURED_QUESTIONS = 4+# ---------------------------------------------------------------------------# Extended input schema# ---------------------------------------------------------------------------@@ -49,6 +51,7 @@ _QUESTIONS_ITEM_SCHEMA: dict[str, Any] = {"properties": {"question": {"type": "string",+ "minLength": 1,"description": "The question to present to the user.",},"header": {@@ -58,11 +61,14 @@ _QUESTIONS_ITEM_SCHEMA: dict[str, Any] = {"options": {"type": "array","description": "Available choices for this question (2-4 items).",+ "maxItems": 4,+ "anyOf": [{"maxItems": 0}, {"minItems": 2}],"items": {"type": "object","properties": {"label": {"type": "string",+ "minLength": 1,"description": "Display text for this option (1-5 words).",},"description": {@@ -105,10 +111,12 @@ EXTENDED_INPUT_PARAMS_EN: dict[str, Any] = {"description": ("Structured questions with selectable options. ""Use this when you want the user to choose from predefined options "- "instead of typing free text. Each question must have 2-4 options. "+ "instead of typing free text. Ask at most 4 questions per call. "+ "Omit options for free-text input; otherwise provide 2-4 options. ""The user can always select 'Other' for custom input."),"items": _QUESTIONS_ITEM_SCHEMA,+ "maxItems": MAX_STRUCTURED_QUESTIONS,},},"required": ["query"],@@ -125,9 +133,12 @@ EXTENDED_INPUT_PARAMS_CN: dict[str, Any] = {"type": "array","description": ("带选项的结构化问题。当希望用户从预定义选项中选择而非自由输入时使用。"- "每个问题必须提供 2-4 个选项。用户始终可以选择「其他」进行自定义输入。"+ "每次调用最多询问 4 个问题。"+ "自由输入题不提供选项;否则必须提供 2-4 个选项。"+ "用户始终可以选择「其他」进行自定义输入。"),"items": _QUESTIONS_ITEM_SCHEMA,+ "maxItems": MAX_STRUCTURED_QUESTIONS,},},"required": ["query"],@@ -140,7 +151,8 @@ _EXTENDED_DESCRIPTION_EN: str = ("2. Structured questions (multi-choice): pass `query` + `questions` — ""the user selects from predefined options. ""Use `questions` when you want the user to choose between specific options "- "(e.g., 'Apply update' vs 'Skip'). Each question can have 2-4 options. "+ "(e.g., 'Apply update' vs 'Skip'). Ask at most 4 questions per call. "+ "Omit options for free-text input; otherwise provide 2-4 options. ""For single-select questions, an option may carry a `preview` (markdown, ""e.g. fenced code block ASCII mockup) shown beside it to compare concrete ""artifacts; use it only when a visual comparison helps the user decide."@@ -151,7 +163,8 @@ _EXTENDED_DESCRIPTION_CN: str = ("1. 纯文本查询:只传 `query` —— 用户自由输入回答。\n""2. 结构化选项:传 `query` + `questions` —— 用户从预定义选项中选择。""当你希望用户在特定选项间做选择时(如「应用更新」vs「跳过」)使用 `questions`。"- "每个问题可提供 2-4 个选项。对于单选问题,选项可携带 `preview`(markdown,"+ "每次调用最多询问 4 个问题。自由输入题不提供选项;否则必须提供 2-4 个选项。"+ "对于单选问题,选项可携带 `preview`(markdown,""如带围栏代码块的 ASCII mockup)展示在选项旁,用于对比具体产物;""仅在视觉对比有助于用户决策时使用。")@@ -280,11 +293,87 @@ class StructuredAskUserRail(AskUserRail):For plain query: delegate to parent class behavior (AskUserPayload)."""+ args = self._parse_tool_args(tool_call)+ raw_questions = args.get("questions")+ if "questions" in args and not isinstance(raw_questions, list):+ return self.reject(+ tool_result=(+ "[INVALID_ARGUMENT] questions must be an array when provided."+ )+ )+ questions_data = raw_questions if raw_questions else None+ if (+ questions_data is not None+ and len(questions_data) > MAX_STRUCTURED_QUESTIONS+ ):+ return self.reject(+ tool_result=(+ "[INVALID_ARGUMENT] ask_user accepts at most "+ f"{MAX_STRUCTURED_QUESTIONS} questions per call; "+ f"received {len(questions_data)}. "+ "Split them across multiple calls."+ )+ )++ for question_index, question in enumerate(questions_data or []):+ if not isinstance(question, Mapping):+ return self.reject(+ tool_result=(+ f"[INVALID_ARGUMENT] questions[{question_index}] "+ "must be an object."+ )+ )+ question_text = question.get("question")+ if not isinstance(question_text, str) or not question_text.strip():+ return self.reject(+ tool_result=(+ f"[INVALID_ARGUMENT] questions[{question_index}].question "+ "is required and must be a non-empty string."+ )+ )+ if "header" in question and not isinstance(question["header"], str):+ return self.reject(+ tool_result=(+ f"[INVALID_ARGUMENT] questions[{question_index}].header "+ "must be a string when provided."+ )+ )+ if "options" not in question:+ continue+ options = question["options"]+ if not isinstance(options, list):+ return self.reject(+ tool_result=(+ f"[INVALID_ARGUMENT] questions[{question_index}].options "+ "must be an array when provided."+ )+ )+ for option_index, option in enumerate(options):+ label = option.get("label") if isinstance(option, Mapping) else None+ if not isinstance(label, str) or not label.strip():+ path = (+ f"questions[{question_index}]."+ f"options[{option_index}].label"+ )+ return self.reject(+ tool_result=(+ f"[INVALID_ARGUMENT] {path} is required "+ "and must be a non-empty string."+ )+ )+ if options and not 2 <= len(options) <= 4:+ return self.reject(+ tool_result=(+ f"[INVALID_ARGUMENT] questions[{question_index}].options "+ "must contain either 0 or 2-4 items; "+ f"received {len(options)}."+ )+ )+if user_input is None:return self.interrupt(self._build_ask_request(tool_call))# Detect if this was a structured questions call by checking tool_args- questions_data = self.extract_questions(tool_call)is_structured = questions_data is not None and len(questions_data) > 0if is_structured:@@ -378,4 +467,4 @@ class StructuredAskUserRail(AskUserRail):if questions and isinstance(questions, list) and len(questions) > 0:return questions- return None\ No newline at end of file+ return Nonediff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex aae78de99a..3fefbd720b 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -674,7 +674,7 @@ def _build_multi_questions(questions_data: list) -> list:options = []question_payload = {"question": q["question"],- "header": q["header"],+ "header": q.get("header") or "Question","options": options,"multi_select": q.get("multi_select", False),}diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex 5291b5c326..9f18f90e82 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -12,6 +12,8 @@ import {matchesKey,decodeKittyPrintable,truncateToWidth,+ visibleWidth,+ wrapTextWithAnsi,} from "@mariozechner/pi-tui";import { spawnSync } from "node:child_process";import * as fs from "node:fs";@@ -1219,33 +1221,114 @@ const swarmWorkflowSelectListTheme = {description: (value: string) => palette.text.secondary(value),};-function wrapPlainText(text: string, width: number): string[] {- const maxWidth = Math.max(12, width - 1);+export function wrapPlainText(text: string, width: number): string[] {+ const maxWidth = Math.max(1, width - 1);const source = text.replace(/\r/g, "").split("\n");const lines: string[] = [];for (const rawLine of source) {- const words = rawLine.split(/\s+/).filter((word) => word.length > 0);- if (words.length === 0) {- lines.push("");- continue;- }- let current = "";- for (const word of words) {- const next = current ? `${current} ${word}` : word;- if (next.length <= maxWidth) {- current = next;- continue;+ const wrapped = wrapTextWithAnsi(rawLine, maxWidth);+ lines.push(...(wrapped.length > 0 ? wrapped : [""]));+ }+ return lines.length > 0 ? lines : [""];+}++export function renderWrappedQuestionOptions(+ items: SelectItem[],+ selectedIndex: number,+ maxVisible: number,+ width: number,+): { lines: string[]; selectedEndIndex: number } {+ const safeWidth = Math.max(1, width);+ if (items.length === 0) {+ return {+ lines: [padToWidth(selectListTheme.noMatch(" No matching commands"), safeWidth)],+ selectedEndIndex: 1,+ };+ }++ const visibleCount = Math.max(1, maxVisible);+ const startIndex = Math.max(+ 0,+ Math.min(selectedIndex - Math.floor(visibleCount / 2), items.length - visibleCount),+ );+ const endIndex = Math.min(startIndex + visibleCount, items.length);+ const lines: string[] = [];+ let selectedEndIndex = 0;+ const primaryColumnWidth = Math.max(+ 34,+ Math.min(+ 42,+ items.reduce(+ (widest, item) => Math.max(widest, visibleWidth(item.label || item.value) + 2),+ 0,+ ),+ ),+ );++ for (let index = startIndex; index < endIndex; index++) {+ const item = items[index];+ if (!item) continue;+ const selected = index === selectedIndex;+ const marker = selected ? "→ " : " ";+ const continuationMarker = " ".repeat(visibleWidth(marker));+ const bodyWidth = Math.max(1, safeWidth - visibleWidth(marker));+ const label = item.label || item.value;+ const description = item.description?.replace(/[\r\n]+/g, " ").trim() ?? "";+ const labelWidth = visibleWidth(label);+ const remainingDescriptionWidth =+ safeWidth - visibleWidth(marker) - primaryColumnWidth - 2;++ if (+ description &&+ safeWidth > 40 &&+ labelWidth <= primaryColumnWidth - 2 &&+ remainingDescriptionWidth > 10 &&+ visibleWidth(description) <= remainingDescriptionWidth+ ) {+ const spacing = " ".repeat(primaryColumnWidth - labelWidth);+ const content = `${label}${spacing}${description}`;+ const styled = selected+ ? selectListTheme.selectedText(`${marker}${content}`)+ : `${marker}${label}${selectListTheme.description(`${spacing}${description}`)}`;+ lines.push(padToWidth(styled, safeWidth));+ } else {+ const labelLines = wrapTextWithAnsi(label, bodyWidth);+ for (let lineIndex = 0; lineIndex < labelLines.length; lineIndex++) {+ const prefix = lineIndex === 0 ? marker : continuationMarker;+ const content = `${prefix}${labelLines[lineIndex]}`;+ lines.push(+ padToWidth(selected ? selectListTheme.selectedText(content) : content, safeWidth),+ );}- if (current) {- lines.push(current);++ if (description) {+ const descriptionPrefix = " ";+ const descriptionWidth = Math.max(1, safeWidth - visibleWidth(descriptionPrefix));+ for (const descriptionLine of wrapTextWithAnsi(description, descriptionWidth)) {+ lines.push(+ padToWidth(+ `${descriptionPrefix}${selectListTheme.description(descriptionLine)}`,+ safeWidth,+ ),+ );+ }}- current = word.length <= maxWidth ? word : word.slice(0, maxWidth);}- if (current) {- lines.push(current);++ if (selected) {+ selectedEndIndex = lines.length;}}- return lines.length > 0 ? lines : [text.slice(0, maxWidth)];++ if (startIndex > 0 || endIndex < items.length) {+ lines.push(+ padToWidth(+ selectListTheme.scrollInfo(` (${selectedIndex + 1}/${items.length})`),+ safeWidth,+ ),+ );+ }+ return { lines, selectedEndIndex };}/** Skip separator/blank lines when showing a compact human-question preview in lists. */@@ -1459,6 +1542,7 @@ export class AppScreen implements Component, Focusable {private syncingComposerInput = false;private pendingQuestionAnswers = new Map<number, string>();private pendingMultiSelectAnswers = new Map<number, string[]>();+ private pendingQuestionCustomInputs = new Map<number, string>();private questionList: SelectList | null = null;private questionCheckboxList: CheckboxList | null = null;private questionDetailsMap: Map<string, string[]> | null = null;@@ -3070,11 +3154,14 @@ export class AppScreen implements Component, Focusable {if (this.otherInputMode) {const pendingQuestion = snapshot.pendingQuestion;const pickedLabel = this.pendingQuestionAnswers.get(this.activeQuestionIndex) ?? "";+ this.pendingQuestionCustomInputs.set(this.activeQuestionIndex, text);this.otherInputMode = false;this.syncEditorSubmitState(this.state.getSnapshot());if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {- this.pendingQuestionAnswers.set(this.activeQuestionIndex, pickedLabel || text);+ if (!pickedLabel && !this.pendingMultiSelectAnswers.has(this.activeQuestionIndex)) {+ this.pendingQuestionAnswers.set(this.activeQuestionIndex, text);+ }this.activeQuestionIndex += 1;this.syncQuestionList(this.state.getSnapshot());this.editor.setText("");@@ -3084,24 +3171,23 @@ export class AppScreen implements Component, Focusable {const answers = pendingQuestion.questions.map((question, index) => {const label = this.pendingQuestionAnswers.get(index) ?? "";+ const multi = this.pendingMultiSelectAnswers.get(index);const isPlanRejectFeedback = shouldAppendPlanRejectFeedback(pendingQuestion.source,label,pendingQuestion.planApprovalKind,);- if (label === "Other" || isPlanRejectFeedback) {+ const customInput = this.pendingQuestionCustomInputs.get(index);+ if (customInput || label === "Other" || isPlanRejectFeedback) {return {question: question.question,- selected_options: [label],- custom_input:- index === this.activeQuestionIndex && (label === "Other" || text)- ? text- : undefined,+ selected_options: multi ?? [label],+ custom_input: customInput,};}return {question: question.question,- selected_options: [label || text],+ selected_options: multi ?? [label || text],};});this.state.submitQuestionAnswers(answers);@@ -3398,6 +3484,7 @@ export class AppScreen implements Component, Focusable {this.activeQuestionIndex = 0;this.pendingQuestionAnswers.clear();this.pendingMultiSelectAnswers.clear();+ this.pendingQuestionCustomInputs.clear();this.draftBeforeQuestion = this.editor.getText();this.editor.setText("");const pendingQuestion = snapshot.pendingQuestion;@@ -3416,6 +3503,7 @@ export class AppScreen implements Component, Focusable {this.otherInputMode = false;this.pendingQuestionAnswers.clear();this.pendingMultiSelectAnswers.clear();+ this.pendingQuestionCustomInputs.clear();this.questionList = null;this.questionCheckboxList = null;this.questionDetailsMap = null;@@ -8629,7 +8717,11 @@ export class AppScreen implements Component, Focusable {lines.push("");for (const opt of question.options) {const optLine = ` ${opt.label}${opt.description ? ` - ${opt.description}` : ""}`;- lines.push(padToWidth(palette.text.dim(optLine), width));+ lines.push(+ ...wrapPlainText(optLine, width).map((line) =>+ padToWidth(palette.text.dim(line), width),+ ),+ );}}lines.push("");@@ -8661,7 +8753,16 @@ export class AppScreen implements Component, Focusable {const checkboxLines = this.questionCheckboxList.render(width);lines.push(...checkboxLines);} else if (this.questionList !== null) {- const listLines = this.questionList.render(width);+ const wrappedOptions =+ pendingQuestion.source === "ask_user_interrupt"+ ? renderWrappedQuestionOptions(+ this.questionList["filteredItems"] ?? [],+ this.questionList["selectedIndex"] ?? 0,+ this.questionList["maxVisible"] ?? 20,+ width,+ )+ : null;+ const listLines = wrappedOptions?.lines ?? this.questionList.render(width);// Insert preview / details sub-lines right after the currently selected item// instead of appending them after the entire list.@@ -8704,7 +8805,9 @@ export class AppScreen implements Component, Focusable {0,Math.min(selectedIdx - Math.floor(maxVis / 2), filteredLen - maxVis),);- const insertAt = Math.max(0, Math.min(selectedIdx - scrollStart + 1, listLines.length));+ const insertAt = wrappedOptions+ ? wrappedOptions.selectedEndIndex+ : Math.max(0, Math.min(selectedIdx - scrollStart + 1, listLines.length));listLines.splice(insertAt, 0, ...subLines);}}@@ -9046,9 +9149,18 @@ export class AppScreen implements Component, Focusable {return;}+ this.pendingMultiSelectAnswers.set(this.activeQuestionIndex, selectedValues);+ if (selectedValues.includes("Other")) {+ this.otherInputMode = true;+ this.questionCheckboxList = null;+ this.setMouseTrackingEnabled(false);+ this.syncEditorSubmitState(snapshot);+ this.tui.requestRender();+ return;+ }+if (this.activeQuestionIndex < pendingQuestion.questions.length - 1) {// Multiple questions: advance to the next one- this.pendingMultiSelectAnswers.set(this.activeQuestionIndex, selectedValues);this.activeQuestionIndex += 1;this.syncQuestionList(this.state.getSnapshot());this.tui.requestRender();@@ -9062,10 +9174,12 @@ export class AppScreen implements Component, Focusable {index === this.activeQuestionIndex? selectedValues: this.pendingMultiSelectAnswers.get(index);- return {+ const answer = {question: question.question,selected_options: multi ?? [this.pendingQuestionAnswers.get(index) ?? ""],};+ const customInput = this.pendingQuestionCustomInputs.get(index);+ return customInput ? { ...answer, custom_input: customInput } : answer;});this.state.submitQuestionAnswers(answers);}@@ -9115,6 +9229,10 @@ export class AppScreen implements Component, Focusable {question: question.question,selected_options: multi ?? [answerValue],};+ const customInput = this.pendingQuestionCustomInputs.get(index);+ if (customInput) {+ return { ...answer, custom_input: customInput };+ }if (index === this.activeQuestionIndex &&collectPlanRejectFeedback &&diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.ts b/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.tsindex 7fbcd1c575..ad13d5eef4 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.ts@@ -1,5 +1,7 @@import chalk from "chalk";import { matchesKey } from "@mariozechner/pi-tui/dist/keys.js";+import { visibleWidth, wrapTextWithAnsi } from "@mariozechner/pi-tui";+import { padToWidth } from "../rendering/text.js";/*** CheckboxList — pi-tui Component for grouped multi-select with checkbox items.@@ -124,7 +126,10 @@ export class CheckboxList {const item = this.flatItems[i];if (item.type === "header") {- lines.push(this.theme.header(item.label));+ const headerWidth = Math.max(1, width - 6);+ for (const headerLine of wrapTextWithAnsi(item.label, headerWidth)) {+ lines.push(padToWidth(this.theme.header(headerLine), width));+ }continue;}@@ -134,32 +139,60 @@ export class CheckboxList {? this.theme.checkedMark: this.theme.uncheckedMark;- let line: string;- if (item.description) {- const labelWidth = 14;- const paddedLabel = item.label.padEnd(labelWidth);- line = ` ${marker}[${checkMark}] ${paddedLabel}${item.description}`;+ const prefix = ` ${marker}[${checkMark}] `;+ const continuationPrefix = " ".repeat(visibleWidth(prefix));+ const bodyWidth = Math.max(1, width - visibleWidth(prefix));+ const description = item.description?.replace(/[\r\n]+/g, " ").trim() ?? "";+ const itemLines: string[] = [];++ if (+ description &&+ visibleWidth(item.label) + 2 + visibleWidth(description) <= bodyWidth+ ) {+ itemLines.push(`${prefix}${item.label} ${description}`);} else {- line = ` ${marker}[${checkMark}] ${item.label}`;+ const labelLines = wrapTextWithAnsi(item.label, bodyWidth);+ for (let lineIndex = 0; lineIndex < labelLines.length; lineIndex++) {+ const linePrefix = lineIndex === 0 ? prefix : continuationPrefix;+ itemLines.push(`${linePrefix}${labelLines[lineIndex]}`);+ }+ if (description) {+ const descriptionPrefix = `${continuationPrefix} `;+ const descriptionWidth = Math.max(1, width - visibleWidth(descriptionPrefix));+ for (const descriptionLine of wrapTextWithAnsi(description, descriptionWidth)) {+ itemLines.push(`${descriptionPrefix}${descriptionLine}`);+ }+ }}- if (isFocused) {- line = this.theme.focus(line);- } else if (!item.checked) {- line = this.theme.dim(line);+ for (const itemLine of itemLines) {+ const styledLine = isFocused+ ? this.theme.focus(itemLine)+ : !item.checked+ ? this.theme.dim(itemLine)+ : itemLine;+ lines.push(padToWidth(styledLine, width));}-- lines.push(line);}// Scroll indicatorif (totalSelectable > this.maxVisible) {const currentSelectableIdx = selectableIndices.indexOf(this.selectedIndex);- lines.push(this.theme.hint(` (${currentSelectableIdx + 1}/${totalSelectable})`));+ lines.push(+ padToWidth(+ this.theme.hint(` (${currentSelectableIdx + 1}/${totalSelectable})`),+ width,+ ),+ );}// Hint line- lines.push(this.theme.hint("↑/↓ 导航 · 空格切换 · Enter 确认 · Esc 取消"));+ lines.push(+ padToWidth(+ this.theme.hint("↑/↓ 导航 · 空格切换 · Enter 确认 · Esc 取消"),+ width,+ ),+ );return lines;}@@ -234,4 +267,4 @@ export class CheckboxList {private _confirm(): void {this.onSelect(this.getCheckedValues());}-}\ No newline at end of file+}diff --git a/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs b/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjsindex 9831c7e611..12910f9468 100644--- a/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs+++ b/jiuwenswarm/channels/tui/frontend/tests/run-tests.mjs@@ -8,10 +8,14 @@ import {getPlanApprovalListLayout,getPlanRejectFeedbackHint,isPlanApprovalRequest,+ renderWrappedQuestionOptions,shouldCaptureTerminalMouse,shouldAppendPlanRejectFeedback,shouldCollectPlanRejectFeedback,+ wrapPlainText,} from "../dist/ui/app-screen.js";+import { CheckboxList } from "../dist/ui/components/checkbox-list.js";+import { visibleWidth } from "@mariozechner/pi-tui";import { planSwarmflowToggle } from "../dist/core/commands/builtins/swarmflow.js";import { buildAppScreenLines } from "../dist/ui/screen-layout.js";import {@@ -77,6 +81,70 @@ assert.equal();assert.deepEqual(getPlanApprovalListLayout(), { minPrimaryColumnWidth: 10, maxPrimaryColumnWidth: 10 });+const narrowQuestionTitle =+ "[Redis 方案] Redis 接入有三种方案,范围和依赖递增。请根据当前项目选择。";+const wrappedQuestionTitle = wrapPlainText(narrowQuestionTitle, 30);+assert.ok(wrappedQuestionTitle.length > 1);+assert.ok(wrappedQuestionTitle.every((line) => visibleWidth(line) <= 29));+assert.equal(+ wrappedQuestionTitle.join("").replace(/\s/g, ""),+ narrowQuestionTitle.replace(/\s/g, ""),+);++const wrappedQuestionOptions = renderWrappedQuestionOptions(+ [+ {+ value: "session",+ label: "方案 A:仅 session",+ description: "依赖 ioredis 与 express-session,保留完整说明不得截断",+ },+ {+ value: "global",+ label: "方案 B:全量",+ description: "增加限流缓存以及额外响应缓存",+ },+ ],+ 0,+ 2,+ 36,+);+assert.ok(wrappedQuestionOptions.lines.length > 2);+assert.ok(wrappedQuestionOptions.lines.every((line) => visibleWidth(line) <= 36));+assert.ok(+ wrappedQuestionOptions.lines+ .join("")+ .replace(/\u001b\[[0-9;]*m/g, "")+ .replace(/\s/g, "")+ .includes("保留完整说明不得截断"),+);+assert.ok(wrappedQuestionOptions.selectedEndIndex > 1);++const narrowCheckboxList = new CheckboxList(+ [+ {+ name: "启用哪些功能模块",+ items: [+ {+ label: "auth",+ value: "auth",+ checked: false,+ description: "认证模块,处理用户登录、权限验证以及完整审计记录",+ },+ ],+ },+ ],+ 1,+);+const narrowCheckboxLines = narrowCheckboxList.render(32);+assert.ok(narrowCheckboxLines.every((line) => visibleWidth(line) <= 32));+assert.ok(+ narrowCheckboxLines+ .join("")+ .replace(/\u001b\[[0-9;]*m/g, "")+ .replace(/\s/g, "")+ .includes("完整审计记录"),+);+// A long/scrollable transcript must not capture drag events: users should be// able to select and copy completed responses with the terminal's native UI.assert.equal(shouldCaptureTerminalMouse(false, false), false);@@ -249,6 +317,134 @@ assert.equal(pendingQuestionExitCount, 0);assert.ok(pendingQuestionInterruptCount === 2 && pendingQuestionExitCount === 0);console.log("ctrl+d render requests:", pendingQuestionRenderCount - renderCountBeforeCtrlD);+async function submitMultiSelectOther(selectedValues, customInput) {+ const submitted = [];+ const pendingQuestion = {+ requestId: "multi-select-other",+ source: "ask_user_interrupt",+ questions: [+ {+ header: "Modules",+ question: "Which modules?",+ multiSelect: true,+ options: [+ { label: "auth" },+ { label: "log" },+ { label: "Other" },+ ],+ },+ ],+ };+ const screen = Object.create(AppScreen.prototype);+ Object.assign(screen, {+ activeQuestionIndex: 0,+ pendingQuestionAnswers: new Map(),+ pendingMultiSelectAnswers: new Map(),+ pendingQuestionCustomInputs: new Map(),+ questionList: null,+ questionCheckboxList: { handleInput: () => undefined },+ otherInputMode: false,+ configEditorState: null,+ modelList: null,+ composerAttachments: [],+ expandPastedText: (text) => text,+ buildOutgoingMessage: (text) => ({ content: text, attachments: [] }),+ setMouseTrackingEnabled: () => undefined,+ syncEditorSubmitState: () => undefined,+ editor: { setText: () => undefined },+ state: {+ recordActivity: () => undefined,+ getSnapshot: () => ({ pendingQuestion }),+ submitQuestionAnswers: (answers) => submitted.push(answers),+ },+ tui: { requestRender: () => undefined },+ });++ screen.handleMultiSelectConfirm(selectedValues);+ assert.equal(screen.otherInputMode, true);+ assert.equal(screen.questionCheckboxList, null);+ assert.equal(submitted.length, 0);++ await screen.handleSubmit(customInput);+ return submitted[0];+}++assert.deepEqual(+ await submitMultiSelectOther(["Other"], "metrics"),+ [+ {+ question: "Which modules?",+ selected_options: ["Other"],+ custom_input: "metrics",+ },+ ],+);+assert.deepEqual(+ await submitMultiSelectOther(["auth", "Other"], "metrics"),+ [+ {+ question: "Which modules?",+ selected_options: ["auth", "Other"],+ custom_input: "metrics",+ },+ ],+);++// No "Other" selected: must not enter the free-text input mode, and must submit+// immediately without a custom_input field.+function submitMultiSelectNoOther(selectedValues) {+ const submitted = [];+ const pendingQuestion = {+ requestId: "multi-select-no-other",+ source: "ask_user_interrupt",+ questions: [+ {+ header: "Modules",+ question: "Which modules?",+ multiSelect: true,+ options: [{ label: "auth" }, { label: "log" }, { label: "Other" }],+ },+ ],+ };+ const screen = Object.create(AppScreen.prototype);+ Object.assign(screen, {+ activeQuestionIndex: 0,+ pendingQuestionAnswers: new Map(),+ pendingMultiSelectAnswers: new Map(),+ pendingQuestionCustomInputs: new Map(),+ questionList: null,+ questionCheckboxList: { handleInput: () => undefined },+ otherInputMode: false,+ configEditorState: null,+ modelList: null,+ composerAttachments: [],+ expandPastedText: (text) => text,+ buildOutgoingMessage: (text) => ({ content: text, attachments: [] }),+ setMouseTrackingEnabled: () => undefined,+ syncEditorSubmitState: () => undefined,+ syncQuestionList: () => undefined,+ editor: { setText: () => undefined },+ state: {+ recordActivity: () => undefined,+ getSnapshot: () => ({ pendingQuestion }),+ submitQuestionAnswers: (answers) => submitted.push(answers),+ },+ tui: { requestRender: () => undefined },+ });++ screen.handleMultiSelectConfirm(selectedValues);+ assert.equal(screen.otherInputMode, false);+ assert.equal(submitted.length, 1);+ return submitted[0];+}++assert.deepEqual(submitMultiSelectNoOther(["auth", "log"]), [+ {+ question: "Which modules?",+ selected_options: ["auth", "log"],+ },+]);+const agent = (name, node_type, correlation_id, id = `${name}-${node_type ?? "plain"}-${correlation_id ?? "none"}`) => ({id,name,diff --git a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsxindex d5f8fe4d89..a7798785db 100644--- a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx@@ -1,7 +1,7 @@/*** InteractionPrompt — Agent 主动提问(ask_user)吸附卡*- * 吸附在输入框正上方。支持单选 / 多选 / 自由输入 / 多轮(每题一页,最多 3 页)。+ * 吸附在输入框正上方。支持单选 / 多选 / 自由输入 / 多轮(每题一页,最多 4 页)。* 一次性收集所有页答案后提交;确认后前端合成「问题澄清」卡注入对话流。*/@@ -17,8 +17,8 @@ import { buildQaSummaryContent, type QaSummaryData, type QaSummaryItem } from './** 后端为「有选项的问题」追加的自定义输入占位项。 */const CUSTOM_OPTION_LABEL = 'Other';-/** 多轮上限(产品约定:多轮确认最多不超过 3 轮)。 */-const MAX_PAGES = 3;+/** 多轮上限(产品约定:多轮确认最多不超过 4 轮)。 */+const MAX_PAGES = 4;/*** 「跳过」/「取消」时回传给后端的标记文本。diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 0ebcea8c43..7b3a5089c8 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1237,10 +1237,16 @@ class JiuWenSwarm:for raw_option in selected_optionsif str(raw_option or "").strip()]- # When the only selection is "Other", prefer the free-text- # custom_input (single-select free-text path).- if len(cleaned_options) == 1 and cleaned_options[0] == "Other" and custom_input:- answer_value: Any = custom_input+ if custom_input:+ # "Other" is only a UI placeholder. Preserve normal+ # multi-select choices and append the user's text.+ normal_options = [+ option for option in cleaned_options if option != "Other"+ ]+ if normal_options:+ answer_value: Any = [*normal_options, custom_input]+ else:+ answer_value = custom_inputelif len(cleaned_options) == 1:answer_value = cleaned_options[0]elif cleaned_options:diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.pyindex 190c502cb7..7bd8b8ee67 100644--- a/tests/system_tests/test_structured_ask_user.py+++ b/tests/system_tests/test_structured_ask_user.py@@ -26,6 +26,7 @@ from openjiuwen.harness.rails.interrupt.ask_user_rail import AskUserPayloadfrom jiuwenswarm.agents.harness.common.rails.ask_user_rail import (EXTENDED_INPUT_PARAMS_CN,EXTENDED_INPUT_PARAMS_EN,+ MAX_STRUCTURED_QUESTIONS,StructuredAskUserRail,StructuredAskUserTool,)@@ -111,6 +112,19 @@ class TestStructuredAskUserToolSchema:assert EXTENDED_INPUT_PARAMS_EN["required"] == ["query"]assert EXTENDED_INPUT_PARAMS_CN["required"] == ["query"]+ @staticmethod+ def test_questions_schema_limits_each_call_to_four():+ """English and Chinese schemas must enforce the same question limit."""+ assert MAX_STRUCTURED_QUESTIONS == 4+ assert (+ EXTENDED_INPUT_PARAMS_EN["properties"]["questions"]["maxItems"]+ == MAX_STRUCTURED_QUESTIONS+ )+ assert (+ EXTENDED_INPUT_PARAMS_CN["properties"]["questions"]["maxItems"]+ == MAX_STRUCTURED_QUESTIONS+ )+@staticmethoddef test_questions_item_schema_structure():"""Each question item must have `question` (required) and optional@@ -126,6 +140,13 @@ class TestStructuredAskUserToolSchema:assert "options" in propsassert "multi_select" in propsassert _QUESTIONS_ITEM_SCHEMA["required"] == ["question"]+ assert props["question"]["minLength"] == 1+ options_schema = props["options"]+ assert options_schema["maxItems"] == 4+ assert options_schema["anyOf"] == [{"maxItems": 0}, {"minItems": 2}]+ option_schema = options_schema["items"]+ assert option_schema["required"] == ["label"]+ assert option_schema["properties"]["label"]["minLength"] == 1@staticmethoddef test_tool_card_name_is_ask_user():@@ -552,7 +573,7 @@ class TestStructuredAskUserRailResolveInterrupt:tc = _make_tool_call(arguments={"query": "Update?","questions": [{"question": "Apply?", "header": "Upd",- "options": [{"label": "Apply"}]}],+ "options": [{"label": "Apply"}, {"label": "Skip"}]}],})ctx = MagicMock()@@ -562,6 +583,261 @@ class TestStructuredAskUserRailResolveInterrupt:from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResultassert isinstance(decision, InterruptResult)+ @staticmethod+ @pytest.mark.asyncio+ async def test_four_questions_are_allowed():+ """The maximum supported batch should still produce an interrupt."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Setup info",+ "questions": [+ {"question": f"Question {index}?", "header": f"Q{index}"}+ for index in range(1, MAX_STRUCTURED_QUESTIONS + 1)+ ],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult+ assert isinstance(decision, InterruptResult)++ @staticmethod+ @pytest.mark.asyncio+ async def test_more_than_four_questions_are_rejected():+ """An oversized batch should return an argument error without prompting."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Setup info",+ "questions": [+ {"question": f"Question {index}?", "header": f"Q{index}"}+ for index in range(1, MAX_STRUCTURED_QUESTIONS + 2)+ ],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "at most 4 questions" in decision.tool_result++ @staticmethod+ @pytest.mark.parametrize(+ "option",+ [+ {"description": "missing label"},+ {"label": ""},+ {"label": " "},+ {"label": 123},+ {"value": "must not replace label"},+ ],+ )+ @pytest.mark.asyncio+ async def test_invalid_option_labels_are_rejected(option):+ """Every selectable option must provide a non-empty string label."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [{+ "question": "Which option?",+ "header": "Choice",+ "options": [option],+ }],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "questions[0].options[0].label" in decision.tool_result++ @staticmethod+ @pytest.mark.parametrize("question", [None, "not an object", 123, []])+ @pytest.mark.asyncio+ async def test_non_object_questions_are_rejected(question):+ """Every questions item must be an object."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [question],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "questions[0] must be an object" in decision.tool_result++ @staticmethod+ @pytest.mark.parametrize("questions", [None, {}, "not an array", 123])+ @pytest.mark.asyncio+ async def test_non_array_questions_are_rejected(questions):+ """An explicitly provided questions value must be an array."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": questions,+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "questions must be an array" in decision.tool_result++ @staticmethod+ @pytest.mark.parametrize(+ "question",+ [+ {"header": "Choice"},+ {"question": "", "header": "Choice"},+ {"question": " ", "header": "Choice"},+ {"question": 123, "header": "Choice"},+ ],+ )+ @pytest.mark.asyncio+ async def test_invalid_question_text_is_rejected(question):+ """Question text must be a non-empty string."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [question],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "questions[0].question" in decision.tool_result++ @staticmethod+ @pytest.mark.parametrize("header", [None, {}, 123])+ @pytest.mark.asyncio+ async def test_non_string_header_is_rejected(header):+ """An explicitly provided header must be a string."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [{+ "question": "Which option?",+ "header": header,+ }],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "questions[0].header must be a string" in decision.tool_result++ @staticmethod+ @pytest.mark.asyncio+ async def test_missing_header_uses_default():+ """An omitted header should be normalized to the frontend default."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [{"question": "Which option?"}],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult+ assert isinstance(decision, InterruptResult)++ interaction = MagicMock()+ interaction.id = "req_missing_header"+ interaction.value = decision.request+ payload = convert_interactions_to_ask_user_question([interaction])+ assert payload is not None+ assert payload["questions"][0]["header"] == "Question"++ @staticmethod+ @pytest.mark.parametrize("options", [None, {}, "not an array", 123])+ @pytest.mark.asyncio+ async def test_non_array_options_are_rejected(options):+ """An explicitly provided options value must be an array."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [{+ "question": "Which option?",+ "header": "Choice",+ "options": options,+ }],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "questions[0].options must be an array" in decision.tool_result++ @staticmethod+ @pytest.mark.asyncio+ async def test_empty_options_array_is_allowed():+ """An empty options array represents a free-input question."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Describe your preference",+ "questions": [{+ "question": "What do you prefer?",+ "header": "Preference",+ "options": [],+ }],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult+ assert isinstance(decision, InterruptResult)++ @staticmethod+ @pytest.mark.parametrize("option_count", [1, 5])+ @pytest.mark.asyncio+ async def test_invalid_option_counts_are_rejected(option_count):+ """Non-empty options arrays must contain between two and four items."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [{+ "question": "Which option?",+ "header": "Choice",+ "options": [+ {"label": f"Option {index}"}+ for index in range(option_count)+ ],+ }],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult+ assert isinstance(decision, RejectResult)+ assert "must contain either 0 or 2-4 items" in decision.tool_result++ @staticmethod+ @pytest.mark.parametrize("option_count", [2, 4])+ @pytest.mark.asyncio+ async def test_valid_option_counts_are_allowed(option_count):+ """Two and four options should both remain valid."""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(arguments={+ "query": "Choose",+ "questions": [{+ "question": "Which option?",+ "header": "Choice",+ "options": [+ {"label": f"Option {index}"}+ for index in range(option_count)+ ],+ }],+ })++ decision = await rail.resolve_interrupt(MagicMock(), tc, None)++ from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult+ assert isinstance(decision, InterruptResult)+@staticmethod@pytest.mark.asyncioasync def test_structured_answer_dict_returns_reject():diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex ee9ce05f78..66c79fe400 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -493,6 +493,50 @@ def test_build_inputs_preserves_original_request_on_ask_user_answers(monkeypatch}+def test_build_inputs_merges_multi_select_custom_input(monkeypatch):+ 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": ["auth", "Other"],+ "custom_input": "metrics",+ },+ {+ "question": "还有其他需求吗?",+ "selected_options": ["Other"],+ "custom_input": "tracing",+ },+ ],+ },+ )++ inputs, _, _ = interface_module.JiuWenSwarm().build_inputs(request)++ assert isinstance(inputs["query"], InteractiveInput)+ assert inputs["query"].user_inputs == {+ "tool-ask-1": {+ "answers": {+ "启用哪些模块?": ["auth", "metrics"],+ "还有其他需求吗?": "tracing",+ }+ }+ }++def test_chat_answer_routes_team_plan_confirm_interrupt_to_adapter(monkeypatch):from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module