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(todo): align restored snapshots with live state

guozirui12834777a80f2
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index 3b34be85b2..4688489a57 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -55,14 +55,16 @@ from jiuwenswarm.agents.harness.common.rails.read_file_validation import (
)
from jiuwenswarm.agents.harness.common.rails.task_execution_rail import (
SKILL_TURBO_OUTER_TODO_ACTIVE_EXTRA_KEY,
- overlay_serial_todo_statuses,
)
from jiuwenswarm.common.tool_display import (
build_tool_display_name,
extract_call_goal,
inject_call_goal_schema,
)
-from jiuwenswarm.common.todo_snapshot import format_todos_for_frontend
+from jiuwenswarm.common.todo_snapshot import (
+ format_todos_for_frontend,
+ overlay_serial_todo_statuses,
+)
from jiuwenswarm.common.utils import fix_json_arguments, logger
# "todo":flash 统一工具(单卡 action 分发,覆盖同一组引擎操作)
diff --git a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
index 7cb2de35fb..88c47de73a 100644
--- a/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/task_execution_rail.py
@@ -33,6 +33,7 @@ from openjiuwen.harness.rails.base import DeepAgentRail
from openjiuwen.harness.workspace.workspace import WorkspaceNode
from jiuwenswarm.common.tool_display import build_tool_display_name
+from jiuwenswarm.common.todo_snapshot import overlay_serial_todo_statuses
from jiuwenswarm.common.utils import logger
from jiuwenswarm.agents.harness.common.tools.todo_resume import (
filter_todos_by_generation,
@@ -52,38 +53,6 @@ def get_current_task_id() -> str | None:
return _ACTIVE_TASK_ID.get()
-_SERIAL_TODO_DONE_STATUSES = frozenset({"completed", "cancelled"})
-
-
-def overlay_serial_todo_statuses(
- items: list[dict[str, Any]],
- *,
- done_statuses: frozenset[str] | None = None,
-) -> list[dict[str, Any]]:
- """Hide out-of-order completed/in_progress rows from a UI snapshot.
-
- RelayClaw treats only the last visible row as live and hides pending.
- Showing a later completed item while an earlier one is still open
- looks like the list is out of order. Shared by TaskExecutionRail
- (task.update) and StreamEventRail (todo.updated).
- """
- done = done_statuses if done_statuses is not None else _SERIAL_TODO_DONE_STATUSES
- overlay: list[dict[str, Any]] = []
- found_open = False
- for item in items:
- copied = dict(item)
- status = str(copied.get("status", "pending")).lower()
- if status in done:
- if found_open and status == "completed":
- copied["status"] = "pending"
- elif found_open:
- copied["status"] = "pending"
- else:
- found_open = True
- overlay.append(copied)
- return overlay
-
-
# 图像产物扩展名白名单
_IMAGE_ARTIFACT_EXTENSIONS = frozenset({
".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg",
diff --git a/jiuwenswarm/agents/harness/common/tools/todo_resume.py b/jiuwenswarm/agents/harness/common/tools/todo_resume.py
index 9968f336d0..061405347e 100644
--- a/jiuwenswarm/agents/harness/common/tools/todo_resume.py
+++ b/jiuwenswarm/agents/harness/common/tools/todo_resume.py
@@ -17,6 +17,11 @@ from typing import Any, List, Sequence
from openjiuwen.harness.tools.todo import TODO_GENERATION_TOKEN_SESSION_KEY
+from jiuwenswarm.common.todo_generation import (
+ filter_todos_by_generation as filter_todos_by_generation,
+ todo_item_generation_token as todo_item_generation_token,
+)
+
_ACTIVE_TODO_STATUS_VALUES = frozenset({"pending", "in_progress"})
_RESUME_QUERY_PATTERNS = (
@@ -127,31 +132,6 @@ def get_todo_generation_token(session: Any) -> str | None:
return value if isinstance(value, str) and value else None
-def todo_item_generation_token(item: Any) -> str | None:
- """Extract the generation token from a TodoItem or its persisted dict."""
- if isinstance(item, dict):
- value = item.get("generation_token")
- else:
- value = getattr(item, "generation_token", None)
- return value if isinstance(value, str) and value else None
-
-
-def filter_todos_by_generation(items: Sequence[Any], token: str | None) -> List[Any]:
- """Drop entries from superseded generations; unstamped entries pass.
-
- ``token`` 为 None(未启用隔离 / 会话无该标志)时原样放行,退化到
- 旧版行为(fail-open),不新增故障点。
- """
- if not token:
- return list(items)
- kept: List[Any] = []
- for item in items:
- item_token = todo_item_generation_token(item)
- if not item_token or item_token == token:
- kept.append(item)
- return kept
-
-
def _todo_status_value(item: Any) -> str:
status = getattr(item, "status", "")
if hasattr(status, "value"):
diff --git a/jiuwenswarm/common/todo_generation.py b/jiuwenswarm/common/todo_generation.py
new file mode 100644
index 0000000000..ced994edb8
--- /dev/null
+++ b/jiuwenswarm/common/todo_generation.py
@@ -0,0 +1,30 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Pure helpers for filtering persisted todos by generation."""
+
+from __future__ import annotations
+
+from typing import Any, Sequence
+
+
+def todo_item_generation_token(item: Any) -> str | None:
+ """Extract the generation token from a TodoItem or its persisted dict."""
+ if isinstance(item, dict):
+ value = item.get("generation_token")
+ else:
+ value = getattr(item, "generation_token", None)
+ return value if isinstance(value, str) and value else None
+
+
+def filter_todos_by_generation(
+ items: Sequence[Any],
+ token: str | None,
+) -> list[Any]:
+ """Drop superseded generations; unstamped legacy entries pass."""
+ if not token:
+ return list(items)
+ return [
+ item
+ for item in items
+ if todo_item_generation_token(item) in (None, token)
+ ]
diff --git a/jiuwenswarm/common/todo_snapshot.py b/jiuwenswarm/common/todo_snapshot.py
index 201d6d64d0..c63a462811 100644
--- a/jiuwenswarm/common/todo_snapshot.py
+++ b/jiuwenswarm/common/todo_snapshot.py
@@ -6,11 +6,15 @@ from __future__ import annotations
import json
import re
+from pathlib import Path
from typing import Any
from openjiuwen.harness.schema.task import TodoStatus
from jiuwenswarm.common.utils import get_deepagent_todo_dir
+from jiuwenswarm.common.todo_generation import (
+ filter_todos_by_generation,
+)
_SAFE_SESSION_ID = re.compile(
r"^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,78}[A-Za-z0-9])?$"
@@ -32,6 +36,30 @@ _CANCELLED_STATUSES = frozenset({
"canceled",
"deleted",
})
+_SERIAL_TODO_DONE_STATUSES = frozenset({"completed", "cancelled"})
+
+
+def overlay_serial_todo_statuses(
+ items: list[dict[str, Any]],
+ *,
+ done_statuses: frozenset[str] | None = None,
+) -> list[dict[str, Any]]:
+ """Hide out-of-order completed/in-progress rows from a UI snapshot."""
+ done = done_statuses if done_statuses is not None else _SERIAL_TODO_DONE_STATUSES
+ overlay: list[dict[str, Any]] = []
+ found_open = False
+ for item in items:
+ copied = dict(item)
+ status = str(copied.get("status", "pending")).lower()
+ if status in done:
+ if found_open and status == "completed":
+ copied["status"] = "pending"
+ elif found_open:
+ copied["status"] = "pending"
+ else:
+ found_open = True
+ overlay.append(copied)
+ return overlay
def format_todos_for_frontend(todos_data: list[Any]) -> list[dict[str, Any]]:
@@ -71,16 +99,25 @@ def format_todos_for_frontend(todos_data: list[Any]) -> list[dict[str, Any]]:
return formatted
-def load_todo_snapshot_for_frontend(session_id: str) -> list[dict[str, Any]]:
+def load_todo_snapshot_for_frontend(
+ session_id: str,
+ *,
+ todo_root: Path | None = None,
+ generation_token: str | None = None,
+) -> 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"
+ root = todo_root if todo_root is not None else get_deepagent_todo_dir()
+ path = root / 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 []
+ if not isinstance(raw, list):
+ return []
+ current_items = filter_todos_by_generation(raw, generation_token)
+ return overlay_serial_todo_statuses(format_todos_for_frontend(current_items))
diff --git a/jiuwenswarm/server/handlers/session.py b/jiuwenswarm/server/handlers/session.py
index 381107cc98..76b061cba0 100644
--- a/jiuwenswarm/server/handlers/session.py
+++ b/jiuwenswarm/server/handlers/session.py
@@ -11,15 +11,20 @@ import shutil
from typing import Any
from weakref import WeakValueDictionary
+from openjiuwen.core.single_agent import create_agent_session
+
+from jiuwenswarm.agents.harness.common.tools.todo_resume import (
+ get_todo_generation_token,
+)
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.todo_snapshot import load_todo_snapshot_for_frontend
-from jiuwenswarm.common.utils import get_agent_sessions_dir
from jiuwenswarm.server.context import RequestContext
from jiuwenswarm.server.handlers._shared import (
+ _agent_workspace_dir_for_request,
_background_session_kvc_tasks,
_sessions_dir_for_request,
_is_team_metadata_mode,
@@ -53,6 +58,46 @@ _session_switch_locks: WeakValueDictionary[str, asyncio.Lock] = (
)
+async def _todo_generation_token_for_history(
+ ctx: RequestContext,
+ session_id: str,
+) -> str | None:
+ """Restore the current todo generation from the session checkpoint."""
+ try:
+ resolved = await _resolve_rewind_agent(
+ ctx,
+ ctx.request.channel_id or "default",
+ session_id,
+ )
+ if resolved is None:
+ return None
+ deep_agent, _ = resolved
+ live_session = getattr(deep_agent, "_interaction_session", None)
+ if live_session is not None:
+ try:
+ live_session_id = str(live_session.get_session_id() or "").strip()
+ except Exception: # noqa: BLE001 - tolerate session implementations
+ live_session_id = ""
+ if live_session_id == session_id:
+ token = get_todo_generation_token(live_session)
+ if token:
+ return token
+
+ checkpoint_session = create_agent_session(
+ session_id=session_id,
+ card=deep_agent.card,
+ )
+ await checkpoint_session.pre_run(inputs=None)
+ return get_todo_generation_token(checkpoint_session)
+ except Exception: # noqa: BLE001 - history restore must remain fail-open
+ logger.warning(
+ "[history.get] todo generation restore failed: session_id=%s",
+ session_id,
+ exc_info=True,
+ )
+ return None
+
+
def _coerce_int(value: object, default: int) -> int:
"""宽松解析整数:兼容 int / 整数值 float / 数字字符串。
@@ -891,7 +936,17 @@ async def handle_history_get_stream(ctx: RequestContext) -> None:
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)
+ normalized_session_id = session_id.strip()
+ generation_token = await _todo_generation_token_for_history(
+ ctx,
+ normalized_session_id,
+ )
+ todo_root = _agent_workspace_dir_for_request(request) / "todo"
+ todos = load_todo_snapshot_for_frontend(
+ normalized_session_id,
+ todo_root=todo_root,
+ generation_token=generation_token,
+ )
todo_chunk = AgentResponseChunk(
request_id=request.request_id,
channel_id=request.channel_id,
diff --git a/tests/unit_tests/server/test_history_todo_restore.py b/tests/unit_tests/server/test_history_todo_restore.py
index 867c277427..558787f5e2 100644
--- a/tests/unit_tests/server/test_history_todo_restore.py
+++ b/tests/unit_tests/server/test_history_todo_restore.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -55,10 +56,30 @@ def _history(monkeypatch):
@pytest.mark.asyncio
async def test_history_first_page_emits_todo_snapshot_before_done(monkeypatch, _history):
+ captured = {}
+
+ async def _token(_ctx, _session_id):
+ return "current-token"
+
+ def _load(_session_id, *, todo_root, generation_token):
+ captured["todo_root"] = todo_root
+ captured["generation_token"] = generation_token
+ return [{"id": "t1", "status": "pending"}]
+
+ monkeypatch.setattr(
+ session_handlers,
+ "_todo_generation_token_for_history",
+ _token,
+ )
+ monkeypatch.setattr(
+ session_handlers,
+ "_agent_workspace_dir_for_request",
+ lambda _request: Path("tenant-agent-workspace"),
+ )
monkeypatch.setattr(
session_handlers,
"load_todo_snapshot_for_frontend",
- lambda _session_id: [{"id": "t1", "status": "pending"}],
+ _load,
)
ctx, sink = _context(1)
@@ -68,6 +89,10 @@ async def test_history_first_page_emits_todo_snapshot_before_done(monkeypatch, _
assert event_types == ["history.message", "todo.updated", "history.message"]
assert sink.sent[1]["sequence"] == 1
assert sink.sent[2]["sequence"] == 2
+ assert captured == {
+ "todo_root": Path("tenant-agent-workspace") / "todo",
+ "generation_token": "current-token",
+ }
@pytest.mark.asyncio
diff --git a/tests/unit_tests/server/test_todo_snapshot.py b/tests/unit_tests/server/test_todo_snapshot.py
index 2451f0dc34..378d35709e 100644
--- a/tests/unit_tests/server/test_todo_snapshot.py
+++ b/tests/unit_tests/server/test_todo_snapshot.py
@@ -54,3 +54,41 @@ def test_load_snapshot_accepts_json_and_rejects_unsafe_session(tmp_path, monkeyp
"status": "in_progress",
}]
assert load_todo_snapshot_for_frontend("../web_session_1") == []
+
+
+def test_load_snapshot_filters_old_generation_and_overlays_serial_statuses(tmp_path):
+ root = tmp_path / "tenant" / "agent" / "jiuwenclaw_workspace" / "todo"
+ snapshot = root / "web_session_2" / "todo.json"
+ snapshot.parent.mkdir(parents=True)
+ snapshot.write_text(
+ json.dumps([
+ {
+ "id": "old",
+ "content": "old generation",
+ "status": "completed",
+ "generation_token": "old-token",
+ },
+ {
+ "id": "current-open",
+ "content": "current open",
+ "status": "in_progress",
+ "generation_token": "current-token",
+ },
+ {
+ "id": "current-late",
+ "content": "completed out of order",
+ "status": "completed",
+ "generation_token": "current-token",
+ },
+ ]),
+ encoding="utf-8",
+ )
+
+ restored = load_todo_snapshot_for_frontend(
+ "web_session_2",
+ todo_root=root,
+ generation_token="current-token",
+ )
+
+ assert [item["id"] for item in restored] == ["current-open", "current-late"]
+ assert [item["status"] for item in restored] == ["in_progress", "pending"]