Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(ask-user): add preview field for single-select question options, and improve ask_user_question UX

ldstyle89edd6ec914bd
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
index aefddbceb8..641895e8aa 100644
--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
@@ -69,6 +69,17 @@ _QUESTIONS_ITEM_SCHEMA: dict[str, Any] = {
"type": "string",
"description": "Explanation of what this option means.",
},
+ "preview": {
+ "type": "string",
+ "description": (
+ "Optional preview content rendered beside this option when "
+ "comparing concrete artifacts the user should visually compare "
+ "(e.g. ASCII mockups, code snippets). Markdown is supported; "
+ "use fenced code blocks for monospace mockups so alignment is "
+ "preserved. Only rendered for single-select questions; ignored "
+ "for multi-select."
+ ),
+ },
},
"required": ["label"],
},
@@ -129,7 +140,10 @@ _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'). Each question can have 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."
)
_EXTENDED_DESCRIPTION_CN: str = (
@@ -137,7 +151,9 @@ _EXTENDED_DESCRIPTION_CN: str = (
"1. 纯文本查询:只传 `query` —— 用户自由输入回答。\n"
"2. 结构化选项:传 `query` + `questions` —— 用户从预定义选项中选择。"
"当你希望用户在特定选项间做选择时(如「应用更新」vs「跳过」)使用 `questions`。"
- "每个问题可提供 2-4 个选项。"
+ "每个问题可提供 2-4 个选项。对于单选问题,选项可携带 `preview`(markdown,"
+ "如带围栏代码块的 ASCII mockup)展示在选项旁,用于对比具体产物;"
+ "仅在视觉对比有助于用户决策时使用。"
)
# ---------------------------------------------------------------------------
@@ -148,9 +164,12 @@ _EXTENDED_DESCRIPTION_CN: str = (
class StructuredAskUserPayload(BaseModel):
"""Payload for structured user answers."""
- answers: dict[str, str] = Field(
+ answers: dict[str, str | list[str]] = Field(
default_factory=dict,
- description="Mapping of question text to selected option label.",
+ description=(
+ "Mapping of question text to selected option label(s). "
+ "Value is a str for single-select, or list[str] for multi-select."
+ ),
)
@@ -302,9 +321,10 @@ class StructuredAskUserRail(AskUserRail):
answer_parts = []
for q_text, selected in payload.answers.items():
if q_text == "__free_text__":
- answer_parts.append(selected)
+ answer_parts.append(selected if isinstance(selected, str) else ", ".join(selected))
else:
- answer_parts.append(f"{q_text}: {selected}")
+ 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 ""
logger.info(
"[StructuredAskUserRail] Resolved structured answer: %s",
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
index 27588fe928..c45737181d 100644
--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
@@ -697,6 +697,9 @@ def _normalize_question_option(option: dict[str, Any]) -> dict[str, Any]:
value = option.get("value")
if isinstance(value, str) and value:
normalized["value"] = value
+ preview = option.get("preview")
+ if isinstance(preview, str) and preview.strip():
+ normalized["preview"] = preview
return normalized
diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
index cac43bd760..ff4f999754 100644
--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts
@@ -1701,6 +1701,11 @@ export class CliPiAppState {
this.localPendingQuestion = null;
this.pendingQuestion = null;
this.setStreamingStateInternal(StreamingState.Idle);
+ } else if (this.pendingQuestion) {
+ // Server-side pendingQuestion (ask_user_interrupt, permission_interrupt, etc.)
+ // chat.interrupt sent below will notify the server to cancel the agent work
+ this.pendingQuestion = null;
+ this.setStreamingStateInternal(StreamingState.Idle);
}
// Set local interrupt flag immediately for long-running command detection
this.interruptRequested = true;
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts
index 3ed333bf9b..df451a9117 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts
@@ -58,6 +58,7 @@ export interface PendingQuestionOption {
description?: string;
value?: string;
details?: string[];
+ preview?: string;
}
export interface UserAnswer {
@@ -438,6 +439,10 @@ function normalizePendingQuestion(payload: Record<string, unknown>): PendingQues
label: typeof option.label === "string" ? option.label : "",
description: typeof option.description === "string" ? option.description : undefined,
value: typeof option.value === "string" ? option.value : undefined,
+ preview:
+ typeof option.preview === "string" && option.preview.trim()
+ ? option.preview
+ : undefined,
}))
.filter((option) => option.label.length > 0)
: [],
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index d6e96712e3..886b84bdad 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -91,7 +91,7 @@ import {
orderedMemberIds,
teamWorkingStartedAtMs,
} from "./components/team-shared.js";
-import { padToWidth, prefixedLines, renderStyledMarkdownLines, renderWrappedText } from "./rendering/text.js";
+import { padToWidth, prefixedLines, renderMarkdownLines, renderStyledMarkdownLines, renderWrappedText } from "./rendering/text.js";
import { chalk, editorTheme, palette, selectListTheme, setCurrentThemeName } from "./theme.js";
import type { Hunk, GitDiffData, GitDiffStats, TurnDiff } from "../core/types.js";
@@ -1305,8 +1305,11 @@ export class AppScreen implements Component, Focusable {
private draftBeforeQuestion = "";
private syncingComposerInput = false;
private pendingQuestionAnswers = new Map<number, string>();
+ private pendingMultiSelectAnswers = new Map<number, string[]>();
private questionList: SelectList | null = null;
+ private questionCheckboxList: CheckboxList | null = null;
private questionDetailsMap: Map<string, string[]> | null = null;
+ private questionPreviewMap: Map<string, string> | null = null;
private questionOptionRows: QuestionOptionRowHit[] = [];
private otherInputMode = false;
private ctrlCPendingForQuestion = false;
@@ -2278,6 +2281,26 @@ export class AppScreen implements Component, Focusable {
return;
}
+ // Ctrl+D during pending question: same double-press mechanism as Ctrl+C
+ if (pendingQuestion && matchesKey(data, "ctrl+d")) {
+ if (this.ctrlCPendingForQuestion) {
+ this.clearCtrlCPendingForQuestion();
+ this.transientNotice = null;
+ this.interruptTask();
+ return;
+ }
+ this.ctrlCPendingForQuestion = true;
+ this.transientNotice = "Press Ctrl+D again to cancel";
+ this.ctrlCPendingForQuestionTimer = setTimeout(() => {
+ this.ctrlCPendingForQuestion = false;
+ this.ctrlCPendingForQuestionTimer = null;
+ this.transientNotice = null;
+ this.tui.requestRender();
+ }, 3000);
+ this.tui.requestRender();
+ return;
+ }
+
if (pendingQuestion && this.handlePendingQuestionInput(data, snapshot)) {
this.tui.requestRender();
return;
@@ -3238,6 +3261,7 @@ export class AppScreen implements Component, Focusable {
this.activeQuestionId = questionId;
this.activeQuestionIndex = 0;
this.pendingQuestionAnswers.clear();
+ this.pendingMultiSelectAnswers.clear();
this.draftBeforeQuestion = this.editor.getText();
this.editor.setText("");
const pendingQuestion = snapshot.pendingQuestion;
@@ -3255,8 +3279,11 @@ export class AppScreen implements Component, Focusable {
this.activeQuestionIndex = 0;
this.otherInputMode = false;
this.pendingQuestionAnswers.clear();
+ this.pendingMultiSelectAnswers.clear();
this.questionList = null;
+ this.questionCheckboxList = null;
this.questionDetailsMap = null;
+ this.questionPreviewMap = null;
this.setMouseTrackingEnabled(false);
if (!this.editor.getText() && this.draftBeforeQuestion) {
this.editor.setText(this.draftBeforeQuestion);
@@ -7071,26 +7098,46 @@ export class AppScreen implements Component, Focusable {
);
}
- if (this.questionList !== null) {
+ if (this.questionCheckboxList !== null) {
+ const checkboxLines = this.questionCheckboxList.render(width);
+ lines.push(...checkboxLines);
+ } else if (this.questionList !== null) {
const listLines = this.questionList.render(width);
- // Insert details sub-lines right after the currently selected item
+ // Insert preview / details sub-lines right after the currently selected item
// instead of appending them after the entire list.
const selectedItem = this.questionList.getSelectedItem();
- if (selectedItem && this.questionDetailsMap) {
- const details = this.questionDetailsMap.get(selectedItem.value);
- if (details && details.length > 0) {
- const indent = " ";
- const detailLines: string[] = [];
- for (const d of details) {
- // Wrap indented text to full terminal width, so long paths auto-break into multiple lines
- detailLines.push(
- ...renderWrappedText(Math.max(1, width), `${indent}${d}`, palette.text.dim),
+ if (selectedItem) {
+ const previewText = this.questionPreviewMap?.get(selectedItem.value);
+ const details = this.questionDetailsMap?.get(selectedItem.value);
+ const hasPreview = !!previewText;
+ const hasDetails = !!(details && details.length > 0);
+ if (hasPreview || hasDetails) {
+ const previewIndent = " ";
+ const detailIndent = " ";
+ const subLines: string[] = [];
+ // Markdown preview (ASCII mockups / code snippets) rendered with the
+ // same renderer as assistant messages so monospace alignment survives.
+ if (hasPreview) {
+ const mdLines = renderMarkdownLines(
+ Math.max(1, width - previewIndent.length),
+ previewText!,
);
+ for (const l of mdLines) {
+ subLines.push(previewIndent + l);
+ }
+ }
+ // Plain-text detail lines (e.g. rewind file-change summaries).
+ if (hasDetails) {
+ for (const d of details!) {
+ subLines.push(
+ ...renderWrappedText(Math.max(1, width), `${detailIndent}${d}`, palette.text.dim),
+ );
+ }
}
// SelectList.render() layout: [visible item 0..N-1, (scroll indicator?)]
// Replicate its scroll-window calculation to find where the selected
- // item sits, then splice detail lines right after it.
+ // item sits, then splice sub-lines right after it.
const filteredLen: number = this.questionList["filteredItems"]?.length ?? 0;
const selectedIdx: number = this.questionList["selectedIndex"] ?? 0;
const maxVis: number = this.questionList["maxVisible"] ?? 6;
@@ -7099,7 +7146,7 @@ export class AppScreen implements Component, Focusable {
Math.min(selectedIdx - Math.floor(maxVis / 2), filteredLen - maxVis),
);
const insertAt = Math.max(0, Math.min(selectedIdx - scrollStart + 1, listLines.length));
- listLines.splice(insertAt, 0, ...detailLines);
+ listLines.splice(insertAt, 0, ...subLines);
}
}
@@ -7131,6 +7178,12 @@ export class AppScreen implements Component, Focusable {
return false;
}
+ if (this.questionCheckboxList !== null) {
+ this.questionCheckboxList.handleInput(data);
+ this.tui.requestRender();
+ return true;
+ }
+
if (this.questionList !== null) {
const question =
snapshot.pendingQuestion.questions[this.activeQuestionIndex] ??
@@ -7230,7 +7283,7 @@ export class AppScreen implements Component, Focusable {
!!pendingQuestion &&
!this.otherInputMode &&
!this.isEditingInlinePlanReject(snapshot) &&
- (this.questionList !== null || (pendingQuestion.questions[0]?.options.length ?? 0) > 0);
+ (this.questionList !== null || this.questionCheckboxList !== null || (pendingQuestion.questions[0]?.options.length ?? 0) > 0);
}
private isEditingInlinePlanReject(snapshot: ReturnType<CliPiAppState["getSnapshot"]>): boolean {
@@ -7273,7 +7326,9 @@ export class AppScreen implements Component, Focusable {
const pendingQuestion = snapshot.pendingQuestion;
if (!pendingQuestion) {
this.questionList = null;
+ this.questionCheckboxList = null;
this.questionDetailsMap = null;
+ this.questionPreviewMap = null;
this.setMouseTrackingEnabled(false);
return;
}
@@ -7285,11 +7340,49 @@ export class AppScreen implements Component, Focusable {
);
if (!question || question.options.length === 0) {
this.questionList = null;
+ this.questionCheckboxList = null;
this.questionDetailsMap = null;
+ this.questionPreviewMap = null;
this.setMouseTrackingEnabled(false);
return;
}
+ // --- Multi-select: use CheckboxList ---
+ if (question.multiSelect) {
+ this.questionList = null;
+ this.questionDetailsMap = null;
+ this.questionPreviewMap = null;
+
+ const groups: CheckboxGroupType[] = [
+ {
+ name: question.header || question.question,
+ items: question.options.map((option) => ({
+ label: option.label,
+ value: option.label,
+ checked: false,
+ description: option.description,
+ })),
+ },
+ ];
+
+ const checkboxList = new CheckboxList(
+ groups,
+ Math.min(Math.max(question.options.length, 1), 20),
+ );
+ checkboxList.onSelect = (selectedValues: string[]) => {
+ this.handleMultiSelectConfirm(selectedValues);
+ };
+ checkboxList.onCancel = () => {
+ this.handleQuestionSelection("");
+ };
+ this.questionCheckboxList = checkboxList;
+ this.setMouseTrackingEnabled(true);
+ return;
+ }
+
+ // --- Single-select: use SelectList ---
+ this.questionCheckboxList = null;
+
const currentSelectedValue = this.questionList?.getSelectedItem()?.value;
const showRejectCursor =
planApprovalRequest &&
@@ -7326,6 +7419,16 @@ export class AppScreen implements Component, Focusable {
}
this.questionDetailsMap = detailsMap;
+ // Build preview map for options that carry markdown preview content
+ // (LLM-supplied ASCII mockups / code snippets). Rendered only for single-select.
+ const previewMap = new Map<string, string>();
+ for (const option of question.options) {
+ if (option.preview && option.preview.trim()) {
+ previewMap.set(option.label, option.preview);
+ }
+ }
+ this.questionPreviewMap = previewMap;
+
const maxVisible =
pendingQuestion.source === "permission_interrupt" ||
pendingQuestion.source === "confirm_interrupt"
@@ -7380,6 +7483,37 @@ export class AppScreen implements Component, Focusable {
this.setMouseTrackingEnabled(true);
}
+ private handleMultiSelectConfirm(selectedValues: string[]): void {
+ const snapshot = this.state.getSnapshot();
+ const pendingQuestion = snapshot.pendingQuestion;
+ if (!pendingQuestion) {
+ 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();
+ return;
+ }
+
+ const answers = pendingQuestion.questions.map((question, index) => {
+ // Current multi-select question uses the just-confirmed selectedValues;
+ // earlier multi-select questions use their stored arrays.
+ const multi =
+ index === this.activeQuestionIndex
+ ? selectedValues
+ : this.pendingMultiSelectAnswers.get(index);
+ return {
+ question: question.question,
+ selected_options: multi ?? [this.pendingQuestionAnswers.get(index) ?? ""],
+ };
+ });
+ this.state.submitQuestionAnswers(answers);
+ }
+
private handleQuestionSelection(label: string): void {
const snapshot = this.state.getSnapshot();
const pendingQuestion = snapshot.pendingQuestion;
@@ -7419,10 +7553,11 @@ export class AppScreen implements Component, Focusable {
}
const answers = pendingQuestion.questions.map((question, index) => {
+ const multi = this.pendingMultiSelectAnswers.get(index);
const answerValue = this.pendingQuestionAnswers.get(index) ?? question.options[0]?.label ?? "";
const answer = {
question: question.question,
- selected_options: [answerValue],
+ selected_options: multi ?? [answerValue],
};
if (
index === this.activeQuestionIndex &&
diff --git a/jiuwenswarm/common/ws_limits.py b/jiuwenswarm/common/ws_limits.py
new file mode 100644
index 0000000000..840433761e
--- /dev/null
+++ b/jiuwenswarm/common/ws_limits.py
@@ -0,0 +1,6 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Shared WebSocket payload limits for the Gateway-AgentServer link."""
+
+AGENT_WS_MAX_MESSAGE_BYTES = 8 * 2**20
+AGENT_WS_SEND_BUDGET_BYTES = 6 * 2**20
diff --git a/jiuwenswarm/gateway/routing/agent_client.py b/jiuwenswarm/gateway/routing/agent_client.py
index 2d9d84b17f..df48fa97fc 100644
--- a/jiuwenswarm/gateway/routing/agent_client.py
+++ b/jiuwenswarm/gateway/routing/agent_client.py
@@ -22,6 +22,7 @@ from jiuwenswarm.common.e2a.wire_codec import (
parse_agent_server_wire_unary,
)
from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
+from jiuwenswarm.common.ws_limits import AGENT_WS_MAX_MESSAGE_BYTES
from jiuwenswarm.common.ws_diagnostics import (
describe_ws_exception,
describe_ws_peer,
@@ -33,7 +34,6 @@ logger = logging.getLogger(__name__)
_STREAM_TRAILING_MESSAGE_GRACE_SECONDS = 0.7
AGENT_REQUEST_TIMEOUT_SECONDS: float = 600.0
_UNARY_REQUEST_TIMEOUT_SECONDS = AGENT_REQUEST_TIMEOUT_SECONDS
-_WS_MAX_SIZE = 8 * 2**20
class _ReceiverFailure:
@@ -190,7 +190,7 @@ class WebSocketAgentServerClient(AgentServerClient):
ping_interval=self._ping_interval,
ping_timeout=self._ping_timeout,
close_timeout=5.0,
- max_size=_WS_MAX_SIZE,
+ max_size=AGENT_WS_MAX_MESSAGE_BYTES,
)
logger.info("[WebSocketAgentServerClient] 已连接: %s", uri)
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 13722bc4e4..f8df08ceb3 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -19,6 +19,7 @@ from websockets.exceptions import ConnectionClosed as WebSocketConnectionClosed
from jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessService, reset_harness_packages_state
from jiuwenswarm.server.gateway_push.wire import build_server_push_wire
+from jiuwenswarm.server.ws_send import send_wire_payload
from jiuwenswarm.agents.harness.common.tools.acp_output_tools import get_acp_output_manager
from jiuwenswarm.common.utils import get_agent_sessions_dir, get_config_file
from jiuwenswarm.common.e2a.agent_compat import e2a_to_agent_request
@@ -46,6 +47,7 @@ from jiuwenswarm.common.ws_diagnostics import (
describe_ws_peer,
format_ws_diagnostics,
)
+from jiuwenswarm.common.ws_limits import AGENT_WS_MAX_MESSAGE_BYTES
from jiuwenswarm.extensions.hook_event import AgentServerHookEvents
from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manager
from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
@@ -1021,8 +1023,6 @@ class AgentWebSocketServer:
await ensure_persistent_checkpointer()
- ws_max_size = 8 * 2**20 # 8 MB — matches Gateway → AgentServer link
-
try:
from websockets.legacy.server import serve as legacy_serve
self._server = await legacy_serve(
@@ -1032,7 +1032,7 @@ class AgentWebSocketServer:
process_request=self._process_request,
ping_interval=self._ping_interval,
ping_timeout=self._ping_timeout,
- max_size=ws_max_size,
+ max_size=AGENT_WS_MAX_MESSAGE_BYTES,
)
except ImportError:
import websockets
@@ -1043,7 +1043,7 @@ class AgentWebSocketServer:
process_request=self._process_request,
ping_interval=self._ping_interval,
ping_timeout=self._ping_timeout,
- max_size=ws_max_size,
+ max_size=AGENT_WS_MAX_MESSAGE_BYTES,
)
logger.info(
"[AgentWebSocketServer] 已启动: ws://%s:%s", self._host, self._port
@@ -1276,7 +1276,7 @@ class AgentWebSocketServer:
"event": "connection.ack",
"payload": {"status": "ready"},
}
- await ws.send(json.dumps(ack_frame, ensure_ascii=False))
+ await send_wire_payload(ws, ack_frame)
logger.info("[AgentWebSocketServer] 已发送 connection.ack: %s", remote)
except Exception as e:
logger.warning("[AgentWebSocketServer] 发送 connection.ack 失败: %s", e)
@@ -1350,7 +1350,7 @@ class AgentWebSocketServer:
)
try:
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
except WebSocketConnectionClosed as send_exc:
logger.info(
"[AgentWebSocketServer] WebSocket 已关闭,JSON 解析错误未发送: %s",
@@ -1700,7 +1700,7 @@ class AgentWebSocketServer:
)
try:
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
except WebSocketConnectionClosed as send_exc:
logger.info(
"[AgentWebSocketServer] WebSocket 已关闭,错误响应未发送: %s",
@@ -1856,7 +1856,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
@staticmethod
def _resolve_code_language() -> str:
@@ -2153,7 +2153,7 @@ class AgentWebSocketServer:
resp.agent_ref = request.agent_ref
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
logger.info(
"[AgentWebSocketServer] 非流式响应已发送: request_id=%s",
request.request_id,
@@ -2182,7 +2182,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
logger.info(
"[AgentWebSocketServer] 非流式响应已发送: request_id=%s",
request.request_id,
@@ -2245,7 +2245,7 @@ class AgentWebSocketServer:
sequence=-1, # 心跳使用特殊序列号 -1
)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
logger.info(
"[AgentWebSocketServer] keepalive chunk 发送: request_id=%s",
request.request_id,
@@ -2288,7 +2288,15 @@ class AgentWebSocketServer:
)
try:
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ sent_original = await send_wire_payload(ws, wire)
+ if not sent_original:
+ logger.warning(
+ "[AgentWebSocketServer] 流式响应因单个 chunk 超限而停止: "
+ "request_id=%s seq=%s",
+ request.request_id,
+ chunk_count - 1,
+ )
+ return
except WebSocketConnectionClosed:
logger.info(
"[AgentWebSocketServer] 流式响应停止,WebSocket 已关闭: request_id=%s",
@@ -2355,7 +2363,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_session_rename(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 session.rename:与 CLI Gateway 本地回退共用 apply_session_rename。"""
@@ -2386,7 +2394,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_session_switch(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""Switch the active team runtime without deleting recoverable session state."""
@@ -2436,7 +2444,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _find_team_session_ids(self, team_name: str) -> list[str]:
from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata
@@ -2575,7 +2583,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_session_delete(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""Delete a single session and its recoverable runtime state."""
@@ -2659,7 +2667,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
def _resolve_rewind_agent(self, channel_id: str) -> tuple[Any, Any] | None:
"""Return (deep_agent, react_agent) for the given channel, or None."""
@@ -2679,8 +2687,8 @@ class AgentWebSocketServer:
@staticmethod
def _send_error_response(ws: Any, request: AgentRequest,
send_lock: asyncio.Lock, error: str,
- code: str | None = None) -> str:
- """Send an error AgentResponse and return the wire JSON string."""
+ code: str | None = None) -> dict[str, Any]:
+ """Build an error AgentResponse wire payload."""
payload: dict[str, Any] = {"error": error}
if code:
payload["code"] = code
@@ -2691,9 +2699,9 @@ class AgentWebSocketServer:
payload=payload,
metadata=request.metadata,
)
- return json.dumps(
- encode_agent_response_for_wire(resp, response_id=request.request_id),
- ensure_ascii=False,
+ return encode_agent_response_for_wire(
+ resp,
+ response_id=request.request_id,
)
async def _handle_session_rewind_full(
@@ -2720,7 +2728,7 @@ class AgentWebSocketServer:
"session_id and turn_index required", "BAD_REQUEST",
)
async with send_lock:
- await ws.send(wire)
+ await send_wire_payload(ws, wire)
return
try:
@@ -2731,7 +2739,7 @@ class AgentWebSocketServer:
"turn_index must be integer", "BAD_REQUEST",
)
async with send_lock:
- await ws.send(wire)
+ await send_wire_payload(ws, wire)
return
try:
@@ -2883,7 +2891,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_session_rewind_context(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -2904,7 +2912,7 @@ class AgentWebSocketServer:
"session_id and turn_index required", "BAD_REQUEST",
)
async with send_lock:
- await ws.send(wire)
+ await send_wire_payload(ws, wire)
return
try:
@@ -2915,7 +2923,7 @@ class AgentWebSocketServer:
"turn_index must be integer", "BAD_REQUEST",
)
async with send_lock:
- await ws.send(wire)
+ await send_wire_payload(ws, wire)
return
pair = self._resolve_rewind_agent(request.channel_id or "default")
@@ -2924,7 +2932,7 @@ class AgentWebSocketServer:
ws, request, send_lock, "no agent instance available",
)
async with send_lock:
- await ws.send(wire)
+ await send_wire_payload(ws, wire)
return
deep_agent, _react_agent = pair
@@ -2965,7 +2973,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_permissions_config(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 permissions.* E2A 请求(与 Web ``register_method`` 同名 method)。"""
@@ -2996,7 +3004,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_history_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
params = request.params if isinstance(request.params, dict) else {}
@@ -3019,7 +3027,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_proactive_tick(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
@@ -3065,7 +3073,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_team_snapshot(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from jiuwenswarm.agents.harness.team import get_team_manager
@@ -3085,7 +3093,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
try:
@@ -3107,7 +3115,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_team_members_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""Return the live team member list for /join seat validation.
@@ -3153,7 +3161,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
try:
@@ -3179,7 +3187,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_workflows(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""Handle command.workflows RPC request — return workflow_run_snapshot."""
@@ -3241,7 +3249,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
try:
@@ -3282,7 +3290,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_team_history_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""返回 team 模式历史记录的分页,避免与 history.get 并发竞争。
@@ -3304,7 +3312,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
session_id = session_id.strip()
@@ -3371,7 +3379,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_history_get_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
params = request.params if isinstance(request.params, dict) else {}
@@ -3394,7 +3402,7 @@ class AgentWebSocketServer:
sequence=0,
)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
messages = data.get("messages", [])
@@ -3419,8 +3427,17 @@ class AgentWebSocketServer:
response_id=request.request_id,
sequence=seq,
)
+ sent_original = False
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ sent_original = await send_wire_payload(ws, wire)
+ if not sent_original:
+ logger.warning(
+ "[AgentWebSocketServer] history 流式响应因单个 chunk 超限而停止: "
+ "request_id=%s seq=%s",
+ request.request_id,
+ seq,
+ )
+ return
done_chunk = AgentResponseChunk(
request_id=request.request_id,
@@ -3441,7 +3458,7 @@ class AgentWebSocketServer:
sequence=done_seq,
)
async with send_lock:
- await ws.send(json.dumps(wire_done, ensure_ascii=False))
+ await send_wire_payload(ws, wire_done)
async def _handle_command_add_dir(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -3475,7 +3492,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_chrome(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -3495,7 +3512,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_compact(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -3602,7 +3619,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_compact_partial(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -3651,7 +3668,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_context(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -3689,7 +3706,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_recap(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 /recap 命令:生成会话快速回顾(read-only,不修改历史)"""
@@ -3731,7 +3748,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_btw(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 /btw 命令:独立、无工具、单轮 LLM 侧问题查询。
@@ -3763,7 +3780,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
mode, sub_mode, _ = resolve_agent_request_mode(params.get("mode", "agent.plan"))
@@ -3808,7 +3825,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_diff(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from jiuwenswarm.server.utils.diff_service import get_diff_service
@@ -3853,7 +3870,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_simplify(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 /simplify 命令:组装代码精简审查 prompt 并返回(由前端作为消息发送给 Agent)。
@@ -3885,7 +3902,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_model(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -3981,7 +3998,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
@staticmethod
def _mask_sensitive_fields(payload: Any) -> Any:
@@ -4519,7 +4536,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_sandbox(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -4591,7 +4608,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_sandbox_enable(self, channel_id: str) -> dict[str, Any]:
# 1. 解析 sandbox endpoint: 优先 config.yaml::sandbox.url/type, 缺省走本地 jiuwenbox.
@@ -5264,7 +5281,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_session(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -5289,7 +5306,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_command_status(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -5436,7 +5453,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_browser_start(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""启动浏览器并返回执行结果(returncode)。"""
@@ -5462,7 +5479,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_browser_runtime_restart(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -5486,7 +5503,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agents_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from dataclasses import asdict as dataclass_asdict
@@ -5513,7 +5530,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agents_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from dataclasses import asdict as dataclass_asdict
@@ -5550,7 +5567,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _generate_agent_with_llm(
self, name: str, description: str
@@ -5671,7 +5688,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agents_update(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from dataclasses import asdict as dataclass_asdict
@@ -5729,7 +5746,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agents_delete(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService
@@ -5767,7 +5784,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agents_set_enabled(
self,
@@ -5824,7 +5841,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agents_tools_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService
@@ -5851,7 +5868,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_config_cache_clear(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -5875,7 +5892,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_agent_reload_config(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
try:
@@ -5937,7 +5954,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_extensions_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""获取所有 Rail 扩展列表."""
@@ -5962,7 +5979,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_extensions_import(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""导入新的 Rail 扩展(文件夹结构)."""
@@ -5997,7 +6014,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_extensions_delete(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""删除 Rail 扩展."""
@@ -6028,7 +6045,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_extensions_toggle(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""切换 Rail 扩展的启用状态,并触发热更新."""
@@ -6074,7 +6091,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_hooks_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""获取当前 hooks 配置(供 TUI /hooks 命令浏览)."""
@@ -6104,7 +6121,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def send_push(self, msg) -> None:
"""AgentServer 主动向 Gateway 推送消息。
@@ -6121,7 +6138,13 @@ class AgentWebSocketServer:
try:
wire = build_server_push_wire(msg)
async with self._current_send_lock:
- await self._current_ws.send(json.dumps(wire, ensure_ascii=False))
+ sent_original = await send_wire_payload(self._current_ws, wire)
+ if not sent_original:
+ logger.warning(
+ "[AgentWebSocketServer] send_push 内容过大已降级为错误帧: channel_id=%s",
+ msg.get("channel_id", ""),
+ )
+ return
response_kind = str(msg.get("response_kind") or "").strip()
if response_kind:
logger.info(
@@ -6240,7 +6263,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
logger.info("[AgentServer] initialize completed: capabilities=%s", capabilities)
@@ -6254,7 +6277,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_session_create(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -6304,7 +6327,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
logger.info("[AgentServer] session.create completed: session_id=%s", session_id)
@@ -6318,7 +6341,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_session_fork(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -6393,7 +6416,7 @@ class AgentWebSocketServer:
resp, response_id=request.request_id
)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
logger.info(
"[AgentServer] session.fork completed: source=%s target=%s title=%s",
@@ -6417,7 +6440,7 @@ class AgentWebSocketServer:
resp, response_id=request.request_id
)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
except Exception as e:
logger.exception("[AgentServer] session.fork failed: %s", e)
resp = AgentResponse(
@@ -6430,7 +6453,7 @@ class AgentWebSocketServer:
resp, response_id=request.request_id
)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_acp_tool_response(
self,
@@ -6471,7 +6494,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def handle_acp_tool_response_for_test(
self,
@@ -6506,7 +6529,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_harness_packages_scan(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -6533,7 +6556,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_harness_packages_activate(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -6551,7 +6574,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
try:
@@ -6605,7 +6628,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_harness_packages_deactivate(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -6623,7 +6646,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
try:
@@ -6672,7 +6695,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
async def _handle_harness_packages_delete(
self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock
@@ -6690,7 +6713,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
if package_id == "native":
@@ -6702,7 +6725,7 @@ class AgentWebSocketServer:
)
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
return
try:
@@ -6749,7 +6772,7 @@ class AgentWebSocketServer:
wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
def _resolve_model(self, model_name: Optional[str] = None) -> Optional[Any]:
"""Resolve model from jiuwenswarm config.
@@ -6952,4 +6975,4 @@ class AgentWebSocketServer:
action, request.request_id, list(wire.keys())[:10],
)
async with send_lock:
- await ws.send(json.dumps(wire, ensure_ascii=False))
+ await send_wire_payload(ws, wire)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index eaf3bc0c32..545c21208f 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -1164,15 +1164,36 @@ class JiuWenSwarm:
question_text = str(answer.get("question", "") or "").strip()
selected_options = answer.get("selected_options", [])
custom_input = str(answer.get("custom_input", "") or "").strip()
- answer_value = ""
- if selected_options:
- answer_value = str(selected_options[0] or "").strip()
+ if selected_options and isinstance(selected_options, list):
+ # Normalize each option to a stripped string, drop empties.
+ cleaned_options = [
+ str(raw_option or "").strip()
+ for raw_option in selected_options
+ if 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
+ elif len(cleaned_options) == 1:
+ answer_value = cleaned_options[0]
+ elif cleaned_options:
+ # Multi-select: preserve the full list of selections.
+ answer_value = cleaned_options
+ else:
+ answer_value = ""
elif custom_input:
answer_value = custom_input
+ else:
+ answer_value = ""
if question_text and answer_value:
answers_dict[question_text] = answer_value
elif answer_value:
- free_text_answer = answer_value
+ free_text_answer = (
+ answer_value
+ if isinstance(answer_value, str)
+ else ", ".join(answer_value)
+ )
if not answers_dict and free_text_answer:
answers_dict["__free_text__"] = free_text_answer
payload: dict[str, Any] = {"answers": answers_dict}
diff --git a/jiuwenswarm/server/ws_send.py b/jiuwenswarm/server/ws_send.py
new file mode 100644
index 0000000000..2e490edbbe
--- /dev/null
+++ b/jiuwenswarm/server/ws_send.py
@@ -0,0 +1,123 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Bounded WebSocket wire sending for AgentServer responses."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any
+
+from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
+from jiuwenswarm.common.e2a.wire_codec import (
+ encode_agent_chunk_for_wire,
+ encode_agent_response_for_wire,
+)
+from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
+from jiuwenswarm.common.ws_limits import AGENT_WS_SEND_BUDGET_BYTES
+
+logger = logging.getLogger(__name__)
+
+_ROUTING_KEYS = (
+ "session_id",
+ "task_id",
+ "context_id",
+ "correlation_id",
+)
+
+
+def _oversized_payload(actual_bytes: int) -> dict[str, Any]:
+ return {
+ "error": "AgentServer response exceeds WebSocket send budget",
+ "code": "response_too_large",
+ "actual_bytes": actual_bytes,
+ "max_bytes": AGENT_WS_SEND_BUDGET_BYTES,
+ }
+
+
+def _build_oversized_fallback(
+ wire: dict[str, Any], actual_bytes: int
+) -> dict[str, Any]:
+ request_id = str(wire.get("request_id") or "")
+ response_id = str(wire.get("response_id") or request_id)
+ channel_id = str(wire.get("channel") or "")
+ sequence = int(wire.get("sequence") or 0)
+ agent_ref = wire.get("agent_ref")
+ payload = _oversized_payload(actual_bytes)
+
+ if wire.get("is_stream"):
+ payload["event_type"] = "chat.error"
+ fallback = encode_agent_chunk_for_wire(
+ AgentResponseChunk(
+ request_id=request_id,
+ channel_id=channel_id,
+ payload=payload,
+ is_complete=True,
+ agent_ref=agent_ref,
+ ),
+ response_id=response_id,
+ sequence=sequence,
+ )
+ elif wire.get("type") == "event":
+ fallback = {
+ "type": "event",
+ "event": "response.error",
+ "payload": payload,
+ }
+ else:
+ fallback = encode_agent_response_for_wire(
+ AgentResponse(
+ request_id=request_id,
+ channel_id=channel_id,
+ ok=False,
+ payload=payload,
+ agent_ref=agent_ref,
+ ),
+ response_id=response_id,
+ sequence=sequence,
+ )
+
+ for key in _ROUTING_KEYS:
+ if wire.get(key) is not None:
+ fallback[key] = wire[key]
+
+ source_metadata = wire.get("metadata")
+ if (
+ isinstance(source_metadata, dict)
+ and source_metadata.get(E2A_WIRE_SERVER_PUSH_KEY) is True
+ ):
+ metadata = dict(fallback.get("metadata") or {})
+ metadata[E2A_WIRE_SERVER_PUSH_KEY] = True
+ fallback["metadata"] = metadata
+
+ return fallback
+
+
+async def send_wire_payload(ws: Any, wire: dict[str, Any]) -> bool:
+ """Send one bounded wire payload, replacing oversized data with an error."""
+ serialized = json.dumps(wire, ensure_ascii=False)
+ actual_bytes = len(serialized.encode("utf-8"))
+ if actual_bytes <= AGENT_WS_SEND_BUDGET_BYTES:
+ await ws.send(serialized)
+ return True
+
+ logger.error(
+ "AgentServer WebSocket response too large: request_id=%s "
+ "response_kind=%s is_stream=%s actual_bytes=%d max_bytes=%d",
+ wire.get("request_id"),
+ wire.get("response_kind"),
+ wire.get("is_stream"),
+ actual_bytes,
+ AGENT_WS_SEND_BUDGET_BYTES,
+ )
+ fallback = _build_oversized_fallback(wire, actual_bytes)
+ fallback_json = json.dumps(fallback, ensure_ascii=False)
+ fallback_bytes = len(fallback_json.encode("utf-8"))
+ if fallback_bytes > AGENT_WS_SEND_BUDGET_BYTES:
+ raise RuntimeError(
+ "oversized fallback exceeds WebSocket send budget: "
+ f"actual_bytes={fallback_bytes} "
+ f"max_bytes={AGENT_WS_SEND_BUDGET_BYTES}"
+ )
+ await ws.send(fallback_json)
+ return False
diff --git a/tests/unit_tests/agentserver/test_ws_send.py b/tests/unit_tests/agentserver/test_ws_send.py
new file mode 100644
index 0000000000..01c1580386
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_ws_send.py
@@ -0,0 +1,197 @@
+import ast
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
+from jiuwenswarm.common.e2a.wire_codec import (
+ encode_agent_chunk_for_wire,
+ encode_agent_response_for_wire,
+ parse_agent_server_wire_chunk,
+)
+from jiuwenswarm.common.schema.agent import (
+ AgentRequest,
+ AgentResponse,
+ AgentResponseChunk,
+)
+from jiuwenswarm.common.schema.message import ReqMethod
+from jiuwenswarm.server import agent_ws_server
+from jiuwenswarm.server import ws_send
+from jiuwenswarm.server.gateway_push.wire import build_server_push_wire
+
+
+class FakeWebSocket:
+ def __init__(self) -> None:
+ self.sent: list[str] = []
+
+ async def send(self, payload: str) -> None:
+ self.sent.append(payload)
+
+
+async def test_send_wire_payload_sends_small_wire_unchanged(monkeypatch):
+ monkeypatch.setattr(ws_send, "AGENT_WS_SEND_BUDGET_BYTES", 1024)
+ ws = FakeWebSocket()
+ wire = {"request_id": "r1", "body": {"result": "ok"}}
+
+ assert await ws_send.send_wire_payload(ws, wire) is True
+ assert json.loads(ws.sent[0]) == wire
+
+
+async def test_send_wire_payload_counts_utf8_bytes(monkeypatch):
+ wire = {"request_id": "r1", "body": {"result": "你" * 400}}
+ character_size = len(json.dumps(wire, ensure_ascii=False))
+ byte_size = len(json.dumps(wire, ensure_ascii=False).encode("utf-8"))
+ monkeypatch.setattr(ws_send, "AGENT_WS_SEND_BUDGET_BYTES", 1200)
+ ws = FakeWebSocket()
+
+ assert character_size < 1200 < byte_size
+ assert await ws_send.send_wire_payload(ws, wire) is False
+ assert len(ws.sent[0].encode("utf-8")) <= 1200
+
+
+async def test_oversized_unary_sends_e2a_error(monkeypatch):
+ monkeypatch.setattr(ws_send, "AGENT_WS_SEND_BUDGET_BYTES", 2048)
+ source = encode_agent_response_for_wire(
+ AgentResponse(
+ request_id="r-unary",
+ channel_id="web",
+ ok=True,
+ payload={"content": "x" * 4096},
+ agent_ref={"mode": "code", "id": "default"},
+ ),
+ response_id="r-unary",
+ )
+ source["session_id"] = "session-1"
+ ws = FakeWebSocket()
+
+ assert await ws_send.send_wire_payload(ws, source) is False
+
+ fallback = json.loads(ws.sent[0])
+ assert fallback["response_kind"] == "e2a.error"
+ assert fallback["request_id"] == "r-unary"
+ assert fallback["session_id"] == "session-1"
+ assert fallback["agent_ref"] == {"mode": "code", "id": "default"}
+ assert fallback["body"]["details"]["code"] == "response_too_large"
+ assert fallback["body"]["details"]["actual_bytes"] > 2048
+ assert fallback["body"]["details"]["max_bytes"] == 2048
+ assert len(ws.sent[0].encode("utf-8")) <= 2048
+
+
+async def test_oversized_stream_sends_final_error_chunk(monkeypatch):
+ monkeypatch.setattr(ws_send, "AGENT_WS_SEND_BUDGET_BYTES", 2048)
+ source = encode_agent_chunk_for_wire(
+ AgentResponseChunk(
+ request_id="r-stream",
+ channel_id="web",
+ payload={"event_type": "chat.tool_result", "result": "x" * 4096},
+ is_complete=False,
+ agent_ref={"mode": "team", "id": "team-1"},
+ ),
+ response_id="r-stream",
+ sequence=7,
+ )
+ ws = FakeWebSocket()
+
+ assert await ws_send.send_wire_payload(ws, source) is False
+
+ raw_fallback = json.loads(ws.sent[0])
+ fallback = parse_agent_server_wire_chunk(raw_fallback)
+ assert raw_fallback["sequence"] == 7
+ assert raw_fallback["agent_ref"] == {"mode": "team", "id": "team-1"}
+ assert fallback.is_complete is True
+ assert fallback.payload["event_type"] == "chat.error"
+ assert fallback.payload["code"] == "response_too_large"
+ assert len(ws.sent[0].encode("utf-8")) <= 2048
+
+
+async def test_oversized_server_push_preserves_push_marker(monkeypatch):
+ monkeypatch.setattr(ws_send, "AGENT_WS_SEND_BUDGET_BYTES", 2048)
+ source = build_server_push_wire(
+ {
+ "request_id": "push-1",
+ "channel_id": "web",
+ "session_id": "session-push",
+ "payload": {"result": "x" * 4096},
+ }
+ )
+ ws = FakeWebSocket()
+
+ assert await ws_send.send_wire_payload(ws, source) is False
+
+ fallback = json.loads(ws.sent[0])
+ assert fallback["metadata"][E2A_WIRE_SERVER_PUSH_KEY] is True
+ assert fallback["session_id"] == "session-push"
+ assert len(ws.sent[0].encode("utf-8")) <= 2048
+
+
+async def test_stream_stops_after_oversized_chunk_is_replaced(monkeypatch):
+ class FakeAgent:
+ async def process_message_stream(self, request):
+ for index in range(2):
+ yield AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={"content": str(index)},
+ is_complete=False,
+ )
+
+ server = agent_ws_server.AgentWebSocketServer.__new__(
+ agent_ws_server.AgentWebSocketServer
+ )
+ server._session_stream_tasks = {}
+ server._is_stateless_method_request = lambda request: True
+
+ async def get_agent(channel_id):
+ return FakeAgent()
+
+ async def no_plan_exit_check(request, agent):
+ return None
+
+ send_count = 0
+
+ async def replace_with_oversized_error(ws, wire):
+ nonlocal send_count
+ send_count += 1
+ return False
+
+ server._get_stateless_agent = get_agent
+ server._check_post_process_plan_exit = no_plan_exit_check
+ monkeypatch.setattr(
+ agent_ws_server,
+ "send_wire_payload",
+ replace_with_oversized_error,
+ )
+ request = AgentRequest(
+ request_id="stream-too-large",
+ channel_id="web",
+ session_id="session-1",
+ req_method=ReqMethod.CHAT_SEND,
+ params={},
+ is_stream=True,
+ )
+
+ await server._handle_stream(FakeWebSocket(), request, asyncio.Lock())
+
+ assert send_count == 1
+
+
+def test_agent_ws_server_has_no_direct_websocket_send_calls():
+ path = Path(agent_ws_server.__file__)
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ direct_sends = [
+ node.lineno
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "send"
+ ]
+
+ assert direct_sends == []
diff --git a/tests/unit_tests/gateway/test_agent_client.py b/tests/unit_tests/gateway/test_agent_client.py
index c05b814441..d71aafa1d9 100644
--- a/tests/unit_tests/gateway/test_agent_client.py
+++ b/tests/unit_tests/gateway/test_agent_client.py
@@ -4,11 +4,13 @@ import logging
import pytest
from websockets.exceptions import ConnectionClosedError
+from jiuwenswarm.common.ws_limits import AGENT_WS_MAX_MESSAGE_BYTES
from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields
from jiuwenswarm.common.e2a.wire_codec import (
encode_agent_chunk_for_wire,
encode_agent_response_for_wire,
)
+from jiuwenswarm.gateway.routing import agent_client
from jiuwenswarm.gateway.routing.agent_client import WebSocketAgentServerClient
from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
@@ -83,6 +85,11 @@ class ReconnectingAgentClientHarness(AgentClientHarness):
self._server_ready = True
+def test_agent_client_uses_shared_websocket_limit():
+ assert not hasattr(agent_client, "_WS_MAX_SIZE")
+ assert agent_client.AGENT_WS_MAX_MESSAGE_BYTES == AGENT_WS_MAX_MESSAGE_BYTES
+
+
@pytest.mark.asyncio
async def test_send_request_stream_keeps_tail_window_for_processing_status(monkeypatch):
client = AgentClientHarness()