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:Preserve interrupted supplement output
chensheng123452ace43bc0ddd
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex 0db6a1752c..fa06e9ebeb 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -34,7 +34,7 @@ from openjiuwen.harness.workspace.workspace import WorkspaceNodefrom jiuwenswarm.common.utils import logger-_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_list", "todo_modify"])+_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify"])def _structured_tool_result_payload(result: Any) -> Any | None:@@ -293,10 +293,10 @@ class JiuClawStreamEventRail(DeepAgentRail):if not self._conversation_id:returnif tool_name in _TODO_TOOL_NAMES:- # Subagent tool calls have a different session object than _main_session.- # Only emit todo.updated for the main agent's calls.- if self._main_session is None or session is not self._main_session:- return+ # Emit the main-agent todo snapshot after every todo tool call. The+ # todo tool itself is loaded from the main workspace below, so this+ # stays authoritative even when a resumed/supplement turn uses a+ # different stream session object.await self._emit_todo_updated(session, self._conversation_id)# ------------------------------------------------------------------@@ -395,9 +395,6 @@ class JiuClawStreamEventRail(DeepAgentRail):)return- if not todos_data:- return-todos = self._format_todos_for_frontend(todos_data)try:diff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 0ed36c0b66..3f9d4ccd0f 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -109,7 +109,13 @@ export interface AppSnapshot {modelInfo: { provider: string; model: string; version: string };sessionTitle: string;statusLineText: string | null;- memoryWarnings: { path: string; kind: string; char_count: number; threshold: number; message: string }[];+ memoryWarnings: {+ path: string;+ kind: string;+ char_count: number;+ threshold: number;+ message: string;+ }[];}function formatElapsed(ms: number): string {@@ -140,13 +146,11 @@ export class CliPiAppState {private collapsedToolGroupIds = new Set<string>();private streamingState: StreamingState = StreamingState.Idle;private pendingQuestion: PendingQuestion | null = null;- private localPendingQuestion:- | {- requestId: string;- resolve: (answers: UserAnswer[]) => void;- reject: (error: Error) => void;- }- | null = null;+ private localPendingQuestion: {+ requestId: string;+ resolve: (answers: UserAnswer[]) => void;+ reject: (error: Error) => void;+ } | null = null;private lastError: string | null = null;private activeSubtasks = new Map<string, SubtaskState>();private todos: TodoItem[] = [];@@ -179,7 +183,13 @@ export class CliPiAppState {model: "",version: "",};- private memoryWarnings: { path: string; kind: string; char_count: number; threshold: number; message: string }[] = [];+ private memoryWarnings: {+ path: string;+ kind: string;+ char_count: number;+ threshold: number;+ message: string;+ }[] = [];private memoryRefreshTimer: ReturnType<typeof setInterval> | null = null;/** 当 closeUi 中 cancelBeforeExit 调 cancel({showNotice:false}) 时置 true,抑制 chat.interrupt_result 的 UI 通知。 */private suppressInterruptResult = false;@@ -283,9 +293,13 @@ export class CliPiAppState {const u = usage as Record<string, unknown>;const entry: ModelUsageEntry = {model: key,- input_tokens: (existing?.input_tokens ?? 0) + (typeof u.input_tokens === "number" ? u.input_tokens : 0),- output_tokens: (existing?.output_tokens ?? 0) + (typeof u.output_tokens === "number" ? u.output_tokens : 0),- total_tokens: (existing?.total_tokens ?? 0) + (typeof u.total_tokens === "number" ? u.total_tokens : 0),+ input_tokens:+ (existing?.input_tokens ?? 0) + (typeof u.input_tokens === "number" ? u.input_tokens : 0),+ output_tokens:+ (existing?.output_tokens ?? 0) ++ (typeof u.output_tokens === "number" ? u.output_tokens : 0),+ total_tokens:+ (existing?.total_tokens ?? 0) + (typeof u.total_tokens === "number" ? u.total_tokens : 0),};this.usageByModel.set(key, entry);},@@ -362,16 +376,24 @@ export class CliPiAppState {this.request<Record<string, unknown>>("memory.status", { detailed: true }),]);const config =- configPayload.status === "fulfilled" && configPayload.value && typeof configPayload.value === "object"+ configPayload.status === "fulfilled" &&+ configPayload.value &&+ typeof configPayload.value === "object"? (configPayload.value as Record<string, unknown>): {};const modelsResult =- modelsPayload.status === "fulfilled" && modelsPayload.value && typeof modelsPayload.value === "object"+ modelsPayload.status === "fulfilled" &&+ modelsPayload.value &&+ typeof modelsPayload.value === "object"? (modelsPayload.value as Record<string, unknown>): {};const activeModelName = String(modelsResult.active_model ?? "").trim();- const models = Array.isArray(modelsResult.models) ? (modelsResult.models as Record<string, unknown>[]) : [];- const activeModel = activeModelName ? models.find((m) => m.model_name === activeModelName) : models[0];+ const models = Array.isArray(modelsResult.models)+ ? (modelsResult.models as Record<string, unknown>[])+ : [];+ const activeModel = activeModelName+ ? models.find((m) => m.model_name === activeModelName)+ : models[0];this.modelInfo = {provider: String(activeModel?.model_provider ?? config.model_provider ?? ""),model: activeModelName || String(config.model ?? ""),@@ -379,11 +401,19 @@ export class CliPiAppState {};const memoryResult =- memoryPayload.status === "fulfilled" && memoryPayload.value && typeof memoryPayload.value === "object"+ memoryPayload.status === "fulfilled" &&+ memoryPayload.value &&+ typeof memoryPayload.value === "object"? (memoryPayload.value as Record<string, unknown>): {};const largeFiles = Array.isArray(memoryResult.large_files)- ? (memoryResult.large_files as { path: string; kind: string; char_count: number; threshold: number; message: string }[])+ ? (memoryResult.large_files as {+ path: string;+ kind: string;+ char_count: number;+ threshold: number;+ message: string;+ }[]): [];this.memoryWarnings = largeFiles;@@ -399,10 +429,18 @@ export class CliPiAppState {this.memoryRefreshTimer = setInterval(async () => {try {const memoryResult = await this.request<Record<string, unknown>>(- "memory.status", { detailed: true }, 10_000,+ "memory.status",+ { detailed: true },+ 10_000,);const largeFiles = Array.isArray(memoryResult.large_files)- ? (memoryResult.large_files as { path: string; kind: string; char_count: number; threshold: number; message: string }[])+ ? (memoryResult.large_files as {+ path: string;+ kind: string;+ char_count: number;+ threshold: number;+ message: string;+ }[]): [];this.memoryWarnings = largeFiles;this.emitChange();@@ -444,8 +482,7 @@ export class CliPiAppState {hasRunningTools ||hasActiveSubtasks ||this.evolutionStatus === "running" ||- (isTeamMode(this.mode) &&- isTeamWorking(this.teamMemberEvents, this.teamMessageEvents));+ (isTeamMode(this.mode) && isTeamWorking(this.teamMemberEvents, this.teamMessageEvents));return {connectionStatus: this.connectionStatus,sessionId: this.sessionId,@@ -588,7 +625,11 @@ export class CliPiAppState {this._getInputValueRef = ref;}- readonly sendEventOnly = (method: string, params: Record<string, unknown>, isStream = false): string => {+ readonly sendEventOnly = (+ method: string,+ params: Record<string, unknown>,+ isStream = false,+ ): string => {const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;const trustedDirs = getTrustedDirs();const workspaceDir = trustedDirs[0] || process.cwd();@@ -607,7 +648,7 @@ export class CliPiAppState {return id;};-readonly request = async <T = Record<string, unknown>>(+ readonly request = async <T = Record<string, unknown>>(method: string,params: Record<string, unknown>,timeoutMs?: number,@@ -615,12 +656,17 @@ readonly request = async <T = Record<string, unknown>>(const id = `tui_${Date.now().toString(16)}_${Math.random().toString(36).slice(2, 6)}`;const trustedDirs = getTrustedDirs();const workspaceDir = trustedDirs[0] || process.cwd();- const response = await this.wsClient.request(id, method, {- ...params,- session_id: params.session_id ?? this.sessionId,- ...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),- ...(workspaceDir ? { cwd: workspaceDir } : {}),- }, timeoutMs ?? 30000);+ const response = await this.wsClient.request(+ id,+ method,+ {+ ...params,+ session_id: params.session_id ?? this.sessionId,+ ...(trustedDirs.length > 0 ? { trusted_dirs: trustedDirs } : {}),+ ...(workspaceDir ? { cwd: workspaceDir } : {}),+ },+ timeoutMs ?? 30000,+ );return response.payload as T;};@@ -638,10 +684,9 @@ readonly request = async <T = Record<string, unknown>>(readonly safeFetchSessionTitle = (sessionId: string): void => {void (async () => {try {- const meta = await this.request<{ session_id: string; title: string }>(- "session.rename",- { session_id: sessionId },- );+ const meta = await this.request<{ session_id: string; title: string }>("session.rename", {+ session_id: sessionId,+ });this.setSessionTitle(meta.title || "");} catch {// 标题获取失败不影响核心功能@@ -777,12 +822,16 @@ readonly request = async <T = Record<string, unknown>>(if (this.streamingState !== StreamingState.Idle) {this.sendEventOnly("chat.interrupt", { intent: "cancel" });}- const requestId = this.sendEventOnly("chat.send", {- content,- query: content,- mode,- ...(attachments?.length ? { attachments } : {}),- }, true);+ const requestId = this.sendEventOnly(+ "chat.send",+ {+ content,+ query: content,+ mode,+ ...(attachments?.length ? { attachments } : {}),+ },+ true,+ );this.lastError = null;if (options?.logAsUser !== false) {this.entries = [@@ -868,13 +917,17 @@ readonly request = async <T = Record<string, unknown>>(}const source = this.pendingQuestion.source;if (source === "permission_interrupt" || source === "ask_user_interrupt") {- this.sendEventOnly("chat.send", {- query: "",- request_id: this.pendingQuestion.requestId,- answers,- source,- mode: this.mode,- }, true);+ this.sendEventOnly(+ "chat.send",+ {+ query: "",+ request_id: this.pendingQuestion.requestId,+ answers,+ source,+ mode: this.mode,+ },+ true,+ );} else {this.sendEventOnly("chat.user_answer", {request_id: this.pendingQuestion.requestId,@@ -1045,11 +1098,7 @@ readonly request = async <T = Record<string, unknown>>(if (!entries || entries.length === 0) return;// 找最后一个实质 user message- const nonSyntheticTags = [- "<local-command-stdout>",- "<bash-stdout>",- "<task-notification>",- ];+ const nonSyntheticTags = ["<local-command-stdout>", "<bash-stdout>", "<task-notification>"];let lastUserIdx = -1;for (let i = entries.length - 1; i >= 0; i--) {const e = entries[i];@@ -1384,9 +1433,122 @@ readonly request = async <T = Record<string, unknown>>(existing.requestId ?? requestId,nextTool,);+ this.applyTodoToolResult(nextTool);this.scheduleToolTimeoutCheck();}+ private applyTodoToolResult(tool: ToolCallDisplay): void {+ if (tool.status !== "completed" || tool.isError) {+ return;+ }+ const args = tool.arguments;+ if (!args || typeof args !== "object" || Array.isArray(args)) {+ return;+ }+ const record = args as Record<string, unknown>;+ if (tool.name === "todo_create") {+ this.applyTodoCreateArgs(record);+ return;+ }+ if (tool.name === "todo_modify") {+ this.applyTodoModifyArgs(record);+ }+ }++ private applyTodoCreateArgs(args: Record<string, unknown>): void {+ const tasks = Array.isArray(args.tasks) ? args.tasks : [];+ const nowIso = new Date().toISOString();+ const nextTodos = tasks+ .filter((task): task is Record<string, unknown> => {+ return Boolean(task && typeof task === "object" && !Array.isArray(task));+ })+ .map((task, index): TodoItem | null => {+ const id = typeof task.id === "string" ? task.id : "";+ if (!id) {+ return null;+ }+ const status = this.normalizeTodoStatus(task.status) ?? "pending";+ return {+ id,+ content: typeof task.content === "string" ? task.content : id,+ activeForm: typeof task.activeForm === "string" ? task.activeForm : "",+ status: task.status === undefined && index === 0 ? "in_progress" : status,+ createdAt: nowIso,+ updatedAt: nowIso,+ };+ })+ .filter((todo): todo is TodoItem => todo !== null);+ if (nextTodos.length > 0) {+ this.todos = nextTodos;+ }+ }++ private applyTodoModifyArgs(args: Record<string, unknown>): void {+ const action = typeof args.action === "string" ? args.action : "update";+ if (action === "delete") {+ const ids = new Set(+ (Array.isArray(args.ids) ? args.ids : []).filter(+ (id): id is string => typeof id === "string",+ ),+ );+ if (ids.size > 0) {+ this.todos = this.todos.filter((todo) => !ids.has(todo.id));+ }+ return;+ }+ if (action !== "update") {+ return;+ }+ const updates = Array.isArray(args.todos) ? args.todos : [];+ const byId = new Map(this.todos.map((todo) => [todo.id, todo]));+ const nowIso = new Date().toISOString();+ for (const update of updates) {+ if (!update || typeof update !== "object" || Array.isArray(update)) {+ continue;+ }+ const item = update as Record<string, unknown>;+ const id = typeof item.id === "string" ? item.id : "";+ if (!id) {+ continue;+ }+ const status = this.normalizeTodoStatus(item.status);+ if (status === null) {+ byId.delete(id);+ continue;+ }+ const current = byId.get(id);+ if (!current) {+ continue;+ }+ byId.set(id, {+ ...current,+ content: typeof item.content === "string" ? item.content : current.content,+ activeForm: typeof item.activeForm === "string" ? item.activeForm : current.activeForm,+ status: status ?? current.status,+ updatedAt: nowIso,+ });+ }+ this.todos = [...byId.values()];+ }++ private normalizeTodoStatus(status: unknown): TodoItem["status"] | null | undefined {+ if (status === undefined) {+ return undefined;+ }+ if (+ status === "deleted" ||+ status === "delete" ||+ status === "cancelled" ||+ status === "canceled"+ ) {+ return null;+ }+ if (status === "in_progress" || status === "completed" || status === "pending") {+ return status;+ }+ return undefined;+ }+private addSyntheticToolExecution(tool: ToolCallDisplay,sessionId: string,@@ -1439,7 +1601,6 @@ readonly request = async <T = Record<string, unknown>>(this.startStatusLinePoll();}-private buildStatusLineJsonInput(): Record<string, unknown> {const snapshot = this.getSnapshot();const usage = this.getUsageSummary();@@ -1498,28 +1659,41 @@ readonly request = async <T = Record<string, unknown>>(// input=$(cat "$JIUWENSWARM_SL_FILE")const tmpFile = join(tmpdir(), "jiuwenswarm-sl.json");writeFileSync(tmpFile, jsonInput, "utf8");- const msysPath = tmpFile.split(sep).join("/").replace(/^([A-Za-z]):/, (_, d) => "/" + d.toLowerCase());+ const msysPath = tmpFile+ .split(sep)+ .join("/")+ .replace(/^([A-Za-z]):/, (_, d) => "/" + d.toLowerCase());const patchedCmd = cmd.replace(/\$\(cat\)/g, `$(cat "${msysPath}")`);const fullCmd = `export JIUWENSWARM_SL_FILE="${msysPath}"; ${patchedCmd}`;- const child = execFile("sh", ["-c", fullCmd], { timeout: 3_000, maxBuffer: 10_240, cwd: process.cwd() }, (err, stdout) => {- if (err) return;- const text = stdout.trim();- if (text !== this.statusLineText) {- this.statusLineText = text || null;- this.emitChange();- }- });+ const child = execFile(+ "sh",+ ["-c", fullCmd],+ { timeout: 3_000, maxBuffer: 10_240, cwd: process.cwd() },+ (err, stdout) => {+ if (err) return;+ const text = stdout.trim();+ if (text !== this.statusLineText) {+ this.statusLineText = text || null;+ this.emitChange();+ }+ },+ );} else {// On POSIX, stdin piping works correctly in sh -c.- const child = execFile("sh", ["-c", cmd], { timeout: 3_000, maxBuffer: 10_240 }, (err, stdout) => {- if (err) return;- const text = stdout.trim();- if (text !== this.statusLineText) {- this.statusLineText = text || null;- this.emitChange();- }- });+ const child = execFile(+ "sh",+ ["-c", cmd],+ { timeout: 3_000, maxBuffer: 10_240 },+ (err, stdout) => {+ if (err) return;+ const text = stdout.trim();+ if (text !== this.statusLineText) {+ this.statusLineText = text || null;+ this.emitChange();+ }+ },+ );child.stdin?.end(jsonInput);}} catch {diff --git a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.tsindex 1056a3d135..3318cd9647 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/event-handlers.ts@@ -797,6 +797,7 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram);if (payload.is_processing !== true) {delegate.getActiveSubtasks().clear();+ delegate.setTodos([]);delegate.setEvolutionStatus("idle");delegate.clearInterruptRequested();}diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/components/todo-list.ts b/jiuwenswarm/channels/tui/frontend/src/ui/components/todo-list.tsindex 1d444f83d2..ada12e3ccc 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/components/todo-list.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/components/todo-list.ts@@ -35,12 +35,16 @@ export function renderTodoList(todos: TodoItem[],width: number,collapsed: boolean = false,- animationPhase: number = 0+ animationPhase: number = 0,): string[] {if (todos.length === 0) {return [];}+ if (todos.every((todo) => todo.status === "completed")) {+ return [];+ }+const pendingCount = todos.filter((t) => t.status === "pending").length;const inProgressCount = todos.filter((t) => t.status === "in_progress").length;const completedCount = todos.filter((t) => t.status === "completed").length;@@ -61,10 +65,6 @@ export function renderTodoList(return [padToWidth(headerLine, width), " ".repeat(width)];}- if (todos.every((todo) => todo.status === "completed")) {- return [padToWidth(palette.text.secondary("Todo"), width), " ".repeat(width)];- }-const ordered = [...todos.filter((todo) => todo.status === "in_progress"),...todos.filter((todo) => todo.status === "pending"),@@ -80,9 +80,5 @@ export function renderTodoList(selectListTheme,);- return [- padToWidth(headerLine, width),- ...list.render(width),- " ".repeat(width),- ];+ return [padToWidth(headerLine, width), ...list.render(width), " ".repeat(width)];}diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 9f0b662e21..e645f844fd 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -130,6 +130,7 @@ class MessageHandler(ABC):self._stream_emits_processing_status: dict[str, bool] = {} # request_id -> emits chat.processing_statusself._pending_evolution_approval: dict[str, str] = {} # session_id -> approval_request_idself._queued_supplement_input: dict[str, dict[str, Any]] = {} # session_id -> queued supplement payload+ self._session_last_user_query: dict[str, str] = {}self._session_evolution_in_progress: set[str] = set()self._acp_session_aliases: dict[str, str] = {} # external_session_id -> internal_session_idself._acp_session_alias_lock = asyncio.Lock()@@ -191,6 +192,7 @@ class MessageHandler(ABC):def handle_message(self, msg: "Message") -> None:"""Channel 同步回调:将消息放入 user_messages 队列,由转发循环发给 AgentServer."""+ self._remember_user_query_context(msg)self._user_messages.put_nowait(msg)logger.info("[MessageHandler] _user_messages 入队: id=%s channel_id=%s session_id=%s",@@ -199,6 +201,30 @@ class MessageHandler(ABC):# ---------- Channel 控制状态:\new_session / \mode ----------+ def _remember_user_query_context(self, msg: "Message") -> None:+ if not self._is_chat_send_message(msg):+ return+ if not isinstance(msg.params, dict) or msg.params.get("is_supplement") is True:+ return+ session_id = str(msg.session_id or "").strip()+ if not session_id:+ return+ query = str(msg.params.get("query") or msg.params.get("content") or "").strip()+ if not query:+ return+ self._session_last_user_query[session_id] = query[:8000]++ def _get_session_last_user_query(self, session_id: str | None) -> str:+ if not session_id:+ return ""+ return self._session_last_user_query.get(str(session_id), "")++ @staticmethod+ def _is_chat_send_message(msg: "Message") -> bool:+ method = getattr(msg, "req_method", None)+ value = getattr(method, "value", method)+ return value == "chat.send" or str(value) == "ReqMethod.CHAT_SEND"+def _get_channel_default_state(self, channel_id: str) -> ChannelControlState:"""从 config.yaml 读取 Channel 的默认 session_id / mode."""try:@@ -1986,17 +2012,48 @@ class MessageHandler(ABC):self._clear_pending_evolution_approval(session_id)self._pop_queued_supplement_input(session_id)+ @staticmethod+ def _build_supplement_continuation_query(+ new_input: str,+ original_request: str = "",+ ) -> str:+ trimmed = str(new_input or "").strip()+ original = str(original_request or "").strip()+ original_section = (+ f"\n\n原始任务请求如下,请以它作为继续执行 todo 时的上下文,尤其要保留其中的文件路径、目录、约束和目标:\n{original[:8000]}"+ if original+ else ""+ )+ return (+ "用户在当前任务执行中追加了补充/调整请求:\n"+ f"{trimmed}\n\n"+ "请先处理这个补充/调整请求,然后检查并继续执行当前会话 todo 列表中仍未完成的 "+ "in_progress 或 pending 任务。不要因为补充请求本身处理完成就询问用户下一步;"+ "只有在确认 todo 列表没有未完成任务时,才可以总结或询问后续方向。\n\n"+ "注意:追加补充请求会中断上一轮流式输出,用户界面上上一轮正在输出的任务结果可能只展示了一部分。"+ "如果补充请求发生时某个 todo 正在输出结果,或者 todo 状态已经前进但该任务结果可能没有完整展示,"+ "继续执行时请先补全或简要重述这个被中断任务的完整结果,再推进后续 todo;"+ "不要仅因为 todo 状态已经变为 completed 就跳过用户尚未完整看到的任务结果。"+ f"{original_section}"+ )+@staticmethoddef _build_queued_chat_send_message(msg: "Message",new_input: str,attachments: list[dict[str, Any]] | None = None,+ original_request: str = "",) -> "Message":from jiuwenswarm.common.schema.message import Message, ReqMethodnew_req_id = f"req_{int(time.time() * 1000):x}_{msg.id}"params: dict[str, Any] = {- "query": new_input,+ "query": MessageHandler._build_supplement_continuation_query(+ new_input,+ original_request,+ ),+ "supplement_input": new_input,+ "original_request": original_request,"session_id": msg.session_id,"is_supplement": True,}@@ -2090,6 +2147,7 @@ class MessageHandler(ABC):msg,queued_input,queued_attachments if isinstance(queued_attachments, list) else None,+ self._get_session_last_user_query(msg.session_id),)self._user_messages.put_nowait(queued_msg)logger.info(@@ -2214,13 +2272,19 @@ class MessageHandler(ABC):new_req_id = f"req_{int(time.time() * 1000):x}_{msg.id}"sup_meta = dict(msg.metadata) if msg.metadata else None+ original_request = self._get_session_last_user_query(msg.session_id)new_msg = Message(id=new_req_id,type="req",channel_id=msg.channel_id,session_id=msg.session_id,params={- "query": new_input.strip(),+ "query": self._build_supplement_continuation_query(+ new_input,+ original_request,+ ),+ "supplement_input": new_input.strip(),+ "original_request": original_request,"session_id": msg.session_id,"is_supplement": True,**(@@ -2695,6 +2759,7 @@ class MessageHandler(ABC):self._session_evolution_in_progress.clear()self._pending_evolution_approval.clear()self._queued_supplement_input.clear()+ self._session_last_user_query.clear()# 取消转发循环if self._forward_task is not None:diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_todo.py b/tests/unit_tests/agentserver/test_stream_event_rail_todo.pynew file mode 100644index 0000000000..1d81198a37--- /dev/null+++ b/tests/unit_tests/agentserver/test_stream_event_rail_todo.py@@ -0,0 +1,40 @@+import pytest+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (+ JiuClawStreamEventRail,+)+++class _FakeTodoTool:+ async def load_todos(self, session_id: str):+ assert session_id == "sess-1"+ return []+++class _FakeSession:+ def __init__(self):+ self.outputs = []++ async def write_stream(self, output):+ self.outputs.append(output)+++class _TestRail(JiuClawStreamEventRail):+ def install_todo_tool(self, tool):+ self._main_todo_tool = tool++ async def emit_todo_updated(self, session, session_id: str):+ await self._emit_todo_updated(session, session_id)+++async def test_empty_todo_list_is_emitted_to_clear_frontend():+ rail = _TestRail()+ rail.install_todo_tool(_FakeTodoTool())+ session = _FakeSession()++ await rail.emit_todo_updated(session, "sess-1")++ assert len(session.outputs) == 1+ output = session.outputs[0]+ assert output.type == "todo.updated"+ assert output.payload == {"todos": []}diff --git a/tests/unit_tests/gateway/test_message_handler_evolution.py b/tests/unit_tests/gateway/test_message_handler_evolution.pyindex 061566697d..5c17d0f6d5 100644--- a/tests/unit_tests/gateway/test_message_handler_evolution.py+++ b/tests/unit_tests/gateway/test_message_handler_evolution.py@@ -112,6 +112,24 @@ class _TestMessageHandler(MessageHandler):publish_interrupt_result=publish_interrupt_result,)+ def build_queued_chat_send_message(+ self,+ msg: Message,+ new_input: str,+ original_request: str = "",+ ) -> Message:+ return self._build_queued_chat_send_message(+ msg,+ new_input,+ original_request=original_request,+ )++ def remember_user_query_context(self, msg: Message) -> None:+ self._remember_user_query_context(msg)++ def get_session_last_user_query(self, session_id: str) -> str:+ return self._get_session_last_user_query(session_id)+def _message(req_method: ReqMethod) -> Message:return Message(@@ -152,6 +170,40 @@ def test_processing_status_is_only_emitted_for_chat_streams() -> None:) is False+def test_queued_supplement_message_instructs_todo_continuation():+ handler = _TestMessageHandler.create()+ msg = _message(ReqMethod.CHAT_CANCEL)++ queued = handler.build_queued_chat_send_message(+ msg,+ "删除 todo 列表里的提出改善意见",+ original_request=r"Analyze C:\repo\src\ui\screen-layout.ts",+ )++ assert queued.params["supplement_input"] == "删除 todo 列表里的提出改善意见"+ assert queued.params["original_request"] == r"Analyze C:\repo\src\ui\screen-layout.ts"+ assert r"C:\repo\src\ui\screen-layout.ts" in queued.params["query"]+ assert "继续执行当前会话 todo 列表中仍未完成" in queued.params["query"]+ assert "不要因为补充请求本身处理完成就询问用户下一步" in queued.params["query"]+ assert "上一轮正在输出的任务结果可能只展示了一部分" in queued.params["query"]+ assert "不要仅因为 todo 状态已经变为 completed 就跳过" in queued.params["query"]+++def test_chat_send_query_context_is_remembered_for_supplement():+ handler = _TestMessageHandler.create()+ msg = _message(ReqMethod.CHAT_SEND)+ msg.params = {+ "query": r"Read C:\repo\src\ui\screen-layout.ts and summarize it",+ }++ handler.remember_user_query_context(msg)++ assert (+ handler.get_session_last_user_query("sess-1")+ == r"Read C:\repo\src\ui\screen-layout.ts and summarize it"+ )++@pytest.mark.asyncioasync def test_handle_evolution_chunk_auto_accepts_previous_pending_approval() -> None:handler = _TestMessageHandler.create()