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

Fix history restore processing status & todo error

chensheng12345d6486cc458ea
diff --git a/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py b/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py
index bab8e41852..71b2ecefcc 100644
--- a/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenclaw/agents/harness/common/rails/stream_event_rail.py
@@ -452,7 +452,8 @@ class JiuClawStreamEventRail(DeepAgentRail):
"""Format todo items for frontend compatibility.
Maps internal TodoStatus values to frontend-compatible status strings.
- Cancelled status is mapped to 'pending' for frontend compatibility.
+ Cancelled items are omitted because the frontend todo panel tracks
+ actionable or completed tasks only.
Args:
todos_data: List of TodoItem objects from TodoListTool.
@@ -464,7 +465,6 @@ class JiuClawStreamEventRail(DeepAgentRail):
TodoStatus.PENDING: "pending",
TodoStatus.IN_PROGRESS: "in_progress",
TodoStatus.COMPLETED: "completed",
- TodoStatus.CANCELLED: "pending",
}
return [
@@ -475,6 +475,7 @@ class JiuClawStreamEventRail(DeepAgentRail):
"status": status_mapping.get(item.status, item.status.value),
}
for item in todos_data
+ if item.status != TodoStatus.CANCELLED
]
@staticmethod
diff --git a/jiuwenclaw/agents/harness/common/tools/todo_compat.py b/jiuwenclaw/agents/harness/common/tools/todo_compat.py
new file mode 100644
index 0000000000..092a9db4bb
--- /dev/null
+++ b/jiuwenclaw/agents/harness/common/tools/todo_compat.py
@@ -0,0 +1,94 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Compatibility shims for OpenJiuWen todo tools."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from openjiuwen.core.common.exception.codes import StatusCode
+from openjiuwen.core.common.exception.errors import build_error
+from openjiuwen.harness.schema.task import TodoItem, TodoStatus
+from openjiuwen.harness.tools.todo import TodoModifyTool as _OpenJiuWenTodoModifyTool
+
+
+class CompatibleTodoModifyTool(_OpenJiuWenTodoModifyTool):
+ """Accept deleted/canceled status updates from clients as todo mutations.
+
+ Some clients send task deletion as an update payload with
+ ``{"status": "deleted"}`` rather than the canonical
+ ``{"action": "delete", "ids": [...]}``. The upstream tool rejects that
+ status, leaving the task pending. This shim preserves the canonical behavior
+ while treating those update statuses as delete/cancel operations.
+ """
+
+ async def _update_todos(
+ self,
+ session_id: str,
+ todos_data: list[dict[str, Any]],
+ current_todos: list[TodoItem],
+ ) -> str:
+ if not isinstance(todos_data, list):
+ raise build_error(
+ StatusCode.TOOL_TODOS_VALIDATION_INVALID,
+ reason="Batch update failed: 'todos' must be a list",
+ )
+
+ todo_map = {todo.id: todo for todo in current_todos}
+ deleted_ids: set[str] = set()
+ updated_count = 0
+
+ for todo_data in todos_data:
+ todo_id = todo_data.get("id")
+ if not todo_id:
+ raise build_error(
+ StatusCode.TOOL_TODOS_VALIDATION_INVALID,
+ reason="Batch update failed: Missing required field: 'id'",
+ )
+ if todo_id not in todo_map:
+ raise build_error(
+ StatusCode.TOOL_TODOS_VALIDATION_INVALID,
+ reason=f"Batch update failed: Task with ID '{todo_id}' not found",
+ )
+
+ status_value = todo_data.get("status")
+ if status_value in ("deleted", "delete"):
+ deleted_ids.add(todo_id)
+ continue
+
+ current_todo = todo_map[todo_id]
+ if "content" in todo_data:
+ current_todo.content = todo_data["content"]
+ if "activeForm" in todo_data:
+ current_todo.activeForm = todo_data["activeForm"]
+ if "description" in todo_data:
+ current_todo.description = todo_data["description"]
+ if "status" in todo_data:
+ if status_value == "canceled":
+ status_value = "cancelled"
+ current_todo.status = TodoStatus(status_value)
+ if "selected_model_id" in todo_data:
+ current_todo.selected_model_id = todo_data["selected_model_id"]
+ updated_count += 1
+
+ updated_todos = [todo for todo in current_todos if todo.id not in deleted_ids]
+ self._validate_single_in_progress(updated_todos)
+ await self.save_todos(session_id, updated_todos)
+
+ parts: list[str] = []
+ if updated_count:
+ parts.append(f"Successfully updated {updated_count} task(s)")
+ if deleted_ids:
+ parts.append(
+ f"Successfully deleted {len(deleted_ids)} task(s) (IDs: {', '.join(sorted(deleted_ids))})"
+ )
+ return "; ".join(parts) or "No task changes applied"
+
+
+def install_todo_modify_compat_patch() -> None:
+ """Patch OpenJiuWen exports so TaskPlanningRail uses the compatible tool."""
+ import openjiuwen.harness.tools as tools_module
+ import openjiuwen.harness.tools.todo as todo_module
+
+ tools_module.TodoModifyTool = CompatibleTodoModifyTool
+ todo_module.TodoModifyTool = CompatibleTodoModifyTool
diff --git a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts
index a3a79d8683..f420b4e512 100644
--- a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts
+++ b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts
@@ -145,12 +145,7 @@ function _handleSwitchModeToolResult(
const existingMode = delegate.getMode();
let newMode: ClientMode | null = null;
if (existingMode.startsWith("code.")) {
- newMode =
- subMode === "plan"
- ? "code.plan"
- : subMode === "team"
- ? "code.team"
- : "code.normal";
+ newMode = subMode === "plan" ? "code.plan" : subMode === "team" ? "code.team" : "code.normal";
} else if (existingMode.startsWith("agent.")) {
newMode = subMode === "plan" ? "agent.plan" : "agent.fast";
}
@@ -608,22 +603,40 @@ function handleSubtaskUpdate(
return true;
}
+function normalizeTodoStatus(status: unknown): TodoItem["status"] | null {
+ if (status === "deleted" || status === "cancelled" || status === "canceled") {
+ return null;
+ }
+ if (status === "in_progress" || status === "completed") {
+ return status;
+ }
+ return "pending";
+}
+
+function isTodoPayloadItem(item: unknown): item is Record<string, unknown> {
+ return Boolean(item && typeof item === "object" && !Array.isArray(item));
+}
+
function handleTodoUpdated(delegate: AppEventDelegate, payload: Record<string, unknown>): boolean {
const todos = Array.isArray(payload.todos) ? payload.todos : [];
delegate.setTodos(
todos
- .filter((item): item is TodoItem => Boolean(item && typeof item === "object"))
- .map((item) => ({
- id: typeof item.id === "string" ? item.id : "",
- content: typeof item.content === "string" ? item.content : "",
- activeForm: typeof item.activeForm === "string" ? item.activeForm : "",
- status: (item.status === "in_progress" || item.status === "completed"
- ? item.status
- : "pending") as TodoItem["status"],
- createdAt: typeof item.createdAt === "string" ? item.createdAt : new Date().toISOString(),
- updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : new Date().toISOString(),
- }))
- .filter((item) => item.id.length > 0),
+ .filter(isTodoPayloadItem)
+ .map((item): TodoItem | null => {
+ const status = normalizeTodoStatus(item.status);
+ if (status === null) {
+ return null;
+ }
+ return {
+ id: typeof item.id === "string" ? item.id : "",
+ content: typeof item.content === "string" ? item.content : "",
+ activeForm: typeof item.activeForm === "string" ? item.activeForm : "",
+ status,
+ createdAt: typeof item.createdAt === "string" ? item.createdAt : new Date().toISOString(),
+ updatedAt: typeof item.updatedAt === "string" ? item.updatedAt : new Date().toISOString(),
+ };
+ })
+ .filter((item): item is TodoItem => item !== null && item.id.length > 0),
);
return true;
}
diff --git a/jiuwenclaw/gateway/message_handler/message_handler.py b/jiuwenclaw/gateway/message_handler/message_handler.py
index f37fa3d2a6..8029bbe418 100644
--- a/jiuwenclaw/gateway/message_handler/message_handler.py
+++ b/jiuwenclaw/gateway/message_handler/message_handler.py
@@ -127,6 +127,7 @@ class MessageHandler(ABC):
self._stream_sessions: dict[str, str | None] = {} # request_id -> session_id
self._stream_metadata: dict[str, dict[str, Any] | None] = {} # request_id -> request metadata
self._stream_modes: dict[str, str] = {} # request_id -> mode
+ self._stream_emits_processing_status: dict[str, bool] = {} # request_id -> emits chat.processing_status
self._pending_evolution_approval: dict[str, str] = {} # session_id -> approval_request_id
self._queued_supplement_input: dict[str, dict[str, Any]] = {} # session_id -> queued supplement payload
self._session_evolution_in_progress: set[str] = set()
@@ -1704,6 +1705,12 @@ class MessageHandler(ABC):
ReqMethod.CHAT_ANSWER,
)
+ @staticmethod
+ def _should_emit_processing_status_for_stream(msg: "Message") -> bool:
+ from jiuwenclaw.common.schema.message import ReqMethod
+
+ return msg.req_method == ReqMethod.CHAT_SEND
+
async def _trigger_before_chat_request_hook(self, msg: "Message") -> None:
if not self._should_trigger_before_chat_request_hook(msg):
return
@@ -2254,15 +2261,23 @@ class MessageHandler(ABC):
if env.is_stream:
# 流式处理:启动后台任务,支持多任务并发
# 通知前端新任务开始处理
- await self._send_processing_status(
- stream_rid, msg.session_id, msg.channel_id, is_processing=True,
- )
+ emit_processing_status = self._should_emit_processing_status_for_stream(msg)
+ if emit_processing_status:
+ await self._send_processing_status(
+ stream_rid, msg.session_id, msg.channel_id, is_processing=True,
+ )
task = asyncio.create_task(
- self.process_stream(env, msg.session_id, msg.metadata)
+ self.process_stream(
+ env,
+ msg.session_id,
+ msg.metadata,
+ emit_processing_status=emit_processing_status,
+ )
)
self._stream_tasks[stream_rid] = task
self._stream_sessions[stream_rid] = msg.session_id
self._stream_metadata[stream_rid] = msg.metadata
+ self._stream_emits_processing_status[stream_rid] = emit_processing_status
self._stream_modes[stream_rid] = (
msg.params.get("mode", "plan") if isinstance(msg.params, dict) else "plan"
)
@@ -2301,6 +2316,8 @@ class MessageHandler(ABC):
env: "E2AEnvelope",
session_id: str | None,
request_metadata: dict[str, Any] | None,
+ *,
+ emit_processing_status: bool = True,
) -> None:
"""处理流式请求,逐个 chunk 写入 robot_messages.
@@ -2358,6 +2375,7 @@ class MessageHandler(ABC):
self._stream_tasks.pop(rid, None)
self._stream_sessions.pop(rid, None)
self._stream_metadata.pop(rid, None)
+ self._stream_emits_processing_status.pop(rid, None)
self._stream_modes.pop(rid, None)
if session_id is not None and session_id not in self._stream_sessions.values():
# Fallback cleanup when stream exits unexpectedly without evolution end signal.
@@ -2368,10 +2386,12 @@ class MessageHandler(ABC):
)
# 该 session 流式任务正常结束后,通知前端处理完成
# 只有当 AgentServer 没有发送过 processing_status=false 时才发送
- if not cancelled and not has_processing_status_false:
+ if emit_processing_status and not cancelled and not has_processing_status_false:
# 检查该 session_id 是否还有活跃任务
session_has_active_tasks = any(
- sid == session_id for sid in self._stream_sessions.values()
+ sid == session_id
+ and self._stream_emits_processing_status.get(active_rid, True)
+ for active_rid, sid in self._stream_sessions.items()
)
if not session_has_active_tasks:
await self._send_processing_status(
@@ -2599,6 +2619,7 @@ class MessageHandler(ABC):
self._stream_tasks.clear()
self._stream_sessions.clear()
self._stream_metadata.clear()
+ self._stream_emits_processing_status.clear()
self._stream_modes.clear()
self._session_evolution_in_progress.clear()
self._pending_evolution_approval.clear()
diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py
index 0f18f6e73d..de101baa92 100644
--- a/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenclaw/server/runtime/agent_adapter/interface_deep.py
@@ -111,6 +111,10 @@ from jiuwenclaw.agents.harness.common.rails.interrupt.interrupt_helpers import (
build_permission_rail,
convert_interactions_to_ask_user_question,
)
+from jiuwenclaw.agents.harness.common.tools.todo_compat import (
+ CompatibleTodoModifyTool,
+ install_todo_modify_compat_patch,
+)
from jiuwenclaw.agents.harness.common.prompt.prompt_builder import build_identity_prompt
from jiuwenclaw.agents.harness.common.rails import (
JiuClawStreamEventRail,
@@ -211,6 +215,8 @@ from jiuwenclaw.common.utils import (
load_dotenv(dotenv_path=get_env_file(), override=True)
reset_free_search_runtime_flags()
+TodoModifyTool = CompatibleTodoModifyTool
+install_todo_modify_compat_patch()
_react_config = get_config().get("react", {})
_sandbox_config = get_config().get("sandbox", {})
diff --git a/tests/unit_tests/gateway/test_message_handler_evolution.py b/tests/unit_tests/gateway/test_message_handler_evolution.py
index 2d5a2f9ff4..f2a4183131 100644
--- a/tests/unit_tests/gateway/test_message_handler_evolution.py
+++ b/tests/unit_tests/gateway/test_message_handler_evolution.py
@@ -2,6 +2,7 @@ from types import SimpleNamespace
import pytest
+from jiuwenclaw.common.schema.message import Message, ReqMethod
from jiuwenclaw.gateway.message_handler.message_handler import MessageHandler
@@ -76,6 +77,34 @@ class _TestMessageHandler(MessageHandler):
user_messages = getattr(self, "_user_messages")
return user_messages.get_nowait()
+ def should_emit_processing_status_for_stream(self, msg: Message) -> bool:
+ return self._should_emit_processing_status_for_stream(msg)
+
+
+def _message(req_method: ReqMethod) -> Message:
+ return Message(
+ id="req-1",
+ type="req",
+ channel_id="web",
+ session_id="sess-1",
+ params={},
+ timestamp=0,
+ ok=True,
+ req_method=req_method,
+ is_stream=True,
+ )
+
+
+def test_processing_status_is_only_emitted_for_chat_streams():
+ handler = _TestMessageHandler.create()
+
+ assert handler.should_emit_processing_status_for_stream(
+ _message(ReqMethod.CHAT_SEND)
+ ) is True
+ assert handler.should_emit_processing_status_for_stream(
+ _message(ReqMethod.HISTORY_GET)
+ ) is False
+
@pytest.mark.asyncio
async def test_handle_evolution_chunk_auto_accepts_previous_pending_approval():