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(todo): restore todo snapshot with session history
guozirui1bf636b94b586
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex 54219493e0..3b34be85b2 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -31,7 +31,6 @@ from openjiuwen.core.single_agent.rail.base import ()from openjiuwen.harness.rails.base import DeepAgentRailfrom openjiuwen.harness.rails.skills.skill_use_rail import get_current_skill_name-from openjiuwen.harness.schema.task import TodoStatusfrom openjiuwen.harness.tools import TodoListToolfrom openjiuwen.harness.workspace.workspace import WorkspaceNode@@ -63,6 +62,7 @@ from jiuwenswarm.common.tool_display import (extract_call_goal,inject_call_goal_schema,)+from jiuwenswarm.common.todo_snapshot import format_todos_for_frontendfrom jiuwenswarm.common.utils import fix_json_arguments, logger# "todo":flash 统一工具(单卡 action 分发,覆盖同一组引擎操作)@@ -1631,34 +1631,8 @@ class JiuSwarmStreamEventRail(DeepAgentRail):def _format_todos_for_frontend(todos_data: List[Any],) -> List[dict[str, Any]]:- """Format todo items for frontend compatibility.-- Maps internal TodoStatus values to frontend-compatible status strings.- Cancelled items are omitted because the frontend todo panel tracks- actionable or completed tasks only.-- Args:- todos_data: List of TodoItem objects from TodoListTool.-- Returns:- List of formatted todo dictionaries.- """- status_mapping = {- TodoStatus.PENDING: "pending",- TodoStatus.IN_PROGRESS: "in_progress",- TodoStatus.COMPLETED: "completed",- }-- return [- {- "id": item.id,- "content": item.content,- "activeForm": item.activeForm,- "status": status_mapping.get(item.status, item.status.value),- }- for item in todos_data- if item.status != TodoStatus.CANCELLED- ]+ """Use the same mapping for live events and history restoration."""+ return format_todos_for_frontend(todos_data)@staticmethodasync def _emit_context_usage(diff --git a/jiuwenswarm/common/todo_snapshot.py b/jiuwenswarm/common/todo_snapshot.pynew file mode 100644index 0000000000..85647f3167--- /dev/null+++ b/jiuwenswarm/common/todo_snapshot.py@@ -0,0 +1,82 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Load and format persisted Todo snapshots for frontend restoration."""++from __future__ import annotations++import json+import re+from typing import Any++from openjiuwen.harness.schema.task import TodoStatus++from jiuwenswarm.common.utils import get_deepagent_todo_dir++_SAFE_SESSION_ID = re.compile(+ r"^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,78}[A-Za-z0-9])?$"+)++_STATUS_TO_FRONTEND = {+ TodoStatus.PENDING: "pending",+ TodoStatus.IN_PROGRESS: "in_progress",+ TodoStatus.COMPLETED: "completed",+ "pending": "pending",+ "waiting": "pending",+ "in_progress": "in_progress",+ "running": "in_progress",+ "completed": "completed",+}+_CANCELLED_STATUSES = frozenset({+ TodoStatus.CANCELLED,+ "cancelled",+ "canceled",+ "deleted",+})+++def format_todos_for_frontend(todos_data: list[Any]) -> list[dict[str, Any]]:+ """Convert Todo objects or persisted dictionaries to frontend fields."""+ formatted: list[dict[str, Any]] = []+ for item in todos_data:+ if item is None:+ continue+ if isinstance(item, dict):+ status = item.get("status", "pending")+ todo_id = item.get("id")+ content = item.get("content")+ active_form = item.get("activeForm")+ else:+ status = getattr(item, "status", None)+ todo_id = getattr(item, "id", None)+ content = getattr(item, "content", "")+ active_form = getattr(item, "activeForm", None)++ status_value = getattr(status, "value", status)+ status_key = str(status_value or "pending").lower()+ if status in _CANCELLED_STATUSES or status_key in _CANCELLED_STATUSES:+ continue+ if todo_id is None or todo_id == "":+ continue+ content_text = content if isinstance(content, str) else ""+ formatted.append({+ "id": str(todo_id),+ "content": content_text,+ "activeForm": active_form if isinstance(active_form, str) else content_text,+ "status": _STATUS_TO_FRONTEND.get(status, _STATUS_TO_FRONTEND.get(status_key, "pending")),+ })+ return formatted+++def load_todo_snapshot_for_frontend(session_id: str) -> list[dict[str, Any]]:+ """Read one session's Todo snapshot; invalid or unreadable input is empty."""+ normalized = (session_id or "").strip()+ if not normalized or _SAFE_SESSION_ID.fullmatch(normalized) is None:+ return []+ path = get_deepagent_todo_dir() / normalized / "todo.json"+ if not path.is_file():+ return []+ try:+ raw = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError):+ return []+ return format_todos_for_frontend(raw) if isinstance(raw, list) else []diff --git a/jiuwenswarm/server/handlers/session.py b/jiuwenswarm/server/handlers/session.pyindex 529ed0e9a4..381107cc98 100644--- a/jiuwenswarm/server/handlers/session.py+++ b/jiuwenswarm/server/handlers/session.py@@ -16,6 +16,7 @@ from jiuwenswarm.common.e2a.wire_codec import (encode_agent_response_for_wire,)from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk+from jiuwenswarm.common.todo_snapshot import load_todo_snapshot_for_frontendfrom jiuwenswarm.common.utils import get_agent_sessions_dirfrom jiuwenswarm.server.context import RequestContextfrom jiuwenswarm.server.handlers._shared import (@@ -888,6 +889,34 @@ async def handle_history_get_stream(ctx: RequestContext) -> None:)return+ next_sequence = len(messages) if isinstance(messages, list) else 0+ if page_idx == 1 and isinstance(session_id, str) and session_id.strip():+ todos = load_todo_snapshot_for_frontend(session_id)+ todo_chunk = AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={+ "event_type": "todo.updated",+ "todos": todos,+ "session_id": session_id.strip(),+ },+ is_complete=False,+ )+ wire_todo = encode_agent_chunk_for_wire(+ todo_chunk,+ response_id=request.request_id,+ sequence=next_sequence,+ )+ if not await ctx.sink.send_wire(wire_todo):+ logger.warning(+ "[history.get] todo snapshot send failed: request_id=%s "+ "session_id=%s todo_count=%s",+ request.request_id,+ session_id.strip(),+ len(todos),+ )+ next_sequence += 1+done_chunk = AgentResponseChunk(request_id=request.request_id,channel_id=request.channel_id,@@ -900,10 +929,9 @@ async def handle_history_get_stream(ctx: RequestContext) -> None:},is_complete=True,)- done_seq = len(messages) if isinstance(messages, list) else 0wire_done = encode_agent_chunk_for_wire(done_chunk,response_id=request.request_id,- sequence=done_seq,+ sequence=next_sequence,)await ctx.sink.send_wire(wire_done)diff --git a/tests/unit_tests/server/test_history_todo_restore.py b/tests/unit_tests/server/test_history_todo_restore.pynew file mode 100644index 0000000000..867c277427--- /dev/null+++ b/tests/unit_tests/server/test_history_todo_restore.py@@ -0,0 +1,88 @@+from __future__ import annotations++from types import SimpleNamespace++import pytest++from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.server.context import RequestContext+from jiuwenswarm.server.handlers import session as session_handlers+++class _Sink:+ def __init__(self) -> None:+ self.sent: list[dict] = []++ async def send_wire(self, wire: dict) -> bool:+ self.sent.append(wire)+ return True+++def _context(page_idx: int) -> tuple[RequestContext, _Sink]:+ sink = _Sink()+ request = AgentRequest(+ request_id=f"history-{page_idx}",+ channel_id="web",+ req_method="history.get",+ params={"session_id": "web_todo_1", "page_idx": page_idx},+ is_stream=True,+ )+ return RequestContext(request, sink, "test", SimpleNamespace()), sink+++def _history(monkeypatch):+ monkeypatch.setattr(+ session_handlers,+ "get_conversation_history",+ lambda session_id, page_idx, sessions_root=None: {+ "messages": [{"role": "user", "content": "hello"}],+ "total_pages": 2,+ "page_idx": page_idx,+ },+ )+ monkeypatch.setattr(+ session_handlers,+ "encode_agent_chunk_for_wire",+ lambda chunk, response_id, sequence: {+ "response_id": response_id,+ "sequence": sequence,+ "payload": chunk.payload,+ "is_complete": chunk.is_complete,+ },+ )+++async def test_history_first_page_emits_todo_snapshot_before_done(monkeypatch, _history):+ monkeypatch.setattr(+ session_handlers,+ "load_todo_snapshot_for_frontend",+ lambda _session_id: [{"id": "t1", "status": "pending"}],+ )+ ctx, sink = _context(1)++ await session_handlers.handle_history_get_stream(ctx)++ event_types = [item["payload"]["event_type"] for item in sink.sent]+ assert event_types == ["history.message", "todo.updated", "history.message"]+ assert sink.sent[1]["sequence"] == 1+ assert sink.sent[2]["sequence"] == 2+++async def test_history_later_page_does_not_load_todo(monkeypatch, _history):+ called = False++ def _load(_session_id):+ nonlocal called+ called = True+ return []++ monkeypatch.setattr(session_handlers, "load_todo_snapshot_for_frontend", _load)+ ctx, sink = _context(2)++ await session_handlers.handle_history_get_stream(ctx)++ assert called is False+ assert all(item["payload"]["event_type"] != "todo.updated" for item in sink.sent)diff --git a/tests/unit_tests/server/test_todo_snapshot.py b/tests/unit_tests/server/test_todo_snapshot.pynew file mode 100644index 0000000000..143ed63088--- /dev/null+++ b/tests/unit_tests/server/test_todo_snapshot.py@@ -0,0 +1,42 @@+from __future__ import annotations++import json+from types import SimpleNamespace++from openjiuwen.harness.schema.task import TodoStatus++from jiuwenswarm.common.todo_snapshot import (+ format_todos_for_frontend,+ load_todo_snapshot_for_frontend,+)+++def test_format_todos_keeps_completed_and_drops_cancelled():+ items = [+ SimpleNamespace(id="a", content="pending", activeForm="doing", status=TodoStatus.PENDING),+ SimpleNamespace(id="b", content="done", activeForm="done", status=TodoStatus.COMPLETED),+ SimpleNamespace(id="c", content="cancel", activeForm="cancel", status=TodoStatus.CANCELLED),+ ]++ assert [item["id"] for item in format_todos_for_frontend(items)] == ["a", "b"]+++def test_load_snapshot_accepts_json_and_rejects_unsafe_session(tmp_path, monkeypatch):+ root = tmp_path / "todo"+ snapshot = root / "web_session_1" / "todo.json"+ snapshot.parent.mkdir(parents=True)+ snapshot.write_text(+ json.dumps([{"id": "t1", "content": "restore", "status": "in_progress"}]),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenswarm.common.todo_snapshot.get_deepagent_todo_dir", lambda: root+ )++ assert load_todo_snapshot_for_frontend("web_session_1") == [{+ "id": "t1",+ "content": "restore",+ "activeForm": "restore",+ "status": "in_progress",+ }]+ assert load_todo_snapshot_for_frontend("../web_session_1") == []