diff --git a/docs/webui.md b/docs/webui.md index ebd8601cf..7a79a07e7 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -149,7 +149,7 @@ When nanobot delegates work to subagents, **Subtasks** appears above the message Finished tasks leave the live list when it is closed. If you are already reading the list, they remain until you close it. When all tasks finish with the list closed, a brief completion or failure summary appears and then disappears; focusing or hovering over it keeps it available. -Saved results appear as compact, expandable records beside the requests that started the work, and scroll with the conversation. Tasks without a matching request in the displayed history remain under **Other tasks**. Refreshing or reopening the WebUI restores active work in the fixed entry and finished work in the conversation, without restarting tasks or bringing all old tasks back into the live list. +Saved results appear as compact, expandable records beside their associated requests, and scroll with the conversation. Results for earlier requests appear when their turns are loaded; tasks without a matching request in the displayed history are not shown there. Refreshing or reopening the WebUI restores active work in the fixed entry and finished work in the conversation, without restarting tasks or bringing all old tasks back into the live list. The WebUI retrieves finished tasks only for the loaded turns. Select a task for its read-only conversation and tool activity. Closing the details leaves it running; its stop button cancels only that task. Give follow-up instructions to nanobot in the main conversation. diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 3927c2d26..26d81f7c4 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -5,7 +5,7 @@ import json import time import uuid import warnings -from collections.abc import Awaitable, Callable, Mapping +from collections.abc import Awaitable, Callable, Collection, Mapping from copy import deepcopy from dataclasses import dataclass, field, replace from functools import partial @@ -441,35 +441,78 @@ class SubagentManager: if status.owner == session_key}, } + def _turn_statuses_for_session( + self, session_key: str, *, turns: Collection[str], tracked: Collection[str], + ) -> dict[str, SubagentStatus]: + """Keep live work plus the tasks the caller still tracks outside the loaded turns.""" + return { + **{tid: record.snapshot() for tid, record in self._tasks.items() + if record.status.owner == session_key and record.status.finished_at is None}, + **{tid: deepcopy(status) for tid, status in self._terminal_statuses.items() + if status.owner == session_key + and (tid in tracked or status.origin_turn_id in turns)}, + } + + def _runtime_for_request( + self, session_key: str, turns: Collection[str] | None, tracked: Collection[str], + ) -> dict[str, SubagentStatus]: + if turns is None: + return self._runtime_statuses_for_session(session_key) + return self._turn_statuses_for_session(session_key, turns=set(turns), tracked=set(tracked)) + def _merge_session_statuses( self, session_key: str, runtime: Mapping[str, SubagentStatus], *, include_history: bool, + turns: Collection[str] | None = None, tracked: Collection[str] = (), ) -> Mapping[str, SubagentStatus]: - if self.sessions is not None and not self.sessions.exists(session_key): - return {} - statuses = self.sessions.load(session_key) if include_history and self.sessions is not None else {} - for task_id, status in runtime.items(): - if self.sessions is not None and not self.sessions.contains(task_id, session_key): - continue - persisted = statuses.get(task_id) - if persisted is None or status.revision >= persisted.revision: - statuses[task_id] = status - return statuses + sessions = self.sessions + if sessions is None: + return dict(runtime) + + def read() -> Mapping[str, SubagentStatus]: + if not sessions.exists(session_key): + return {} + if not include_history: + statuses: dict[str, SubagentStatus] = {} + elif turns is None: + statuses = sessions.load(session_key) + else: + statuses = sessions.load_turns(session_key, turn_ids=list(turns)) + outside = [task_id for task_id in tracked if task_id not in statuses] + if outside: + statuses.update(sessions.load_tracked(session_key, outside)) + for task_id, status in runtime.items(): + if not sessions.contains(task_id, session_key): + continue + persisted = statuses.get(task_id) + if persisted is None or status.revision >= persisted.revision: + statuses[task_id] = status + return statuses + + # One connection per request: existence, the turn read, tracked fallbacks and + # ownership checks are separate transactions on the same worker. + return sessions.read_batch(read) def statuses_for_session( self, session_key: str | None, *, include_history: bool = True, + turns: Collection[str] | None = None, tracked: Collection[str] = (), ) -> Mapping[str, SubagentStatus]: """Return only tasks owned by the given session, never a global fallback.""" if not session_key: return {} return self._merge_session_statuses( - session_key, self._runtime_statuses_for_session(session_key), include_history=include_history, + session_key, self._runtime_for_request(session_key, turns, tracked), + include_history=include_history, turns=turns, tracked=tracked, ) - async def read_statuses_for_session(self, session_key: str) -> Mapping[str, SubagentStatus]: + async def read_statuses_for_session( + self, session_key: str, *, turns: Collection[str] | None = None, + tracked: Collection[str] = (), + ) -> Mapping[str, SubagentStatus]: """Capture runtime observations on the owner loop; read stored metadata on a worker.""" - runtime = self._runtime_statuses_for_session(session_key) return await asyncio.to_thread( - self._merge_session_statuses, session_key, runtime, include_history=True, + self._merge_session_statuses, session_key, + self._runtime_for_request(session_key, turns, tracked), + include_history=True, turns=turns, tracked=tracked, ) def set_provider(self, provider: LLMProvider, model: str) -> None: diff --git a/nanobot/agent/subagent_sessions.py b/nanobot/agent/subagent_sessions.py index 1c777f908..a43342e52 100644 --- a/nanobot/agent/subagent_sessions.py +++ b/nanobot/agent/subagent_sessions.py @@ -2,14 +2,20 @@ from __future__ import annotations import math import time -from typing import Any, cast +from collections.abc import Callable, Sequence +from typing import Any, TypeVar, cast from loguru import logger from pydantic import TypeAdapter, ValidationError from nanobot.agent.subagent_status import SubagentSessionError as SubagentSessionError from nanobot.agent.subagent_status import SubagentStatus -from nanobot.session.manager import Session, SessionManager, SessionPolicy +from nanobot.session.manager import ( + Session, + SessionManager, + SessionMetadataPayload, + SessionPolicy, +) from nanobot.session.sqlite_store import SessionConflictError from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY, SessionType @@ -17,6 +23,7 @@ SUBAGENT = SessionType("subagent", needs_handle=False, public_history=False) TASK_METADATA_KEY = "subagent_task" _STATUS = TypeAdapter(SubagentStatus) _ACTIVE_STATES = {"queued", "running", "stopping"} +_T = TypeVar("_T") class SubagentSessions: @@ -109,8 +116,27 @@ class SubagentSessions: return status def load(self, owner: str) -> dict[str, SubagentStatus]: + return self._statuses(owner, self.sessions.list_child_session_metadata(owner)) + + def load_turns(self, owner: str, *, turn_ids: Sequence[str]) -> dict[str, SubagentStatus]: + """Read subagent headers attributed to the requested parent turns.""" + return self._statuses( + owner, self.sessions.list_subagent_session_metadata(owner, turn_ids=turn_ids), + ) + + def load_tracked(self, owner: str, task_ids: Sequence[str]) -> dict[str, SubagentStatus]: + """Read already observed tasks in one query when they fall outside the loaded turns.""" + return self._statuses( + owner, self.sessions.read_child_session_metadata( + owner, [self.key(task_id) for task_id in task_ids], + ), + ) + + def _statuses( + self, owner: str, rows: Sequence[SessionMetadataPayload], + ) -> dict[str, SubagentStatus]: result: dict[str, SubagentStatus] = {} - for row in self.sessions.list_child_session_metadata(owner): + for row in rows: key = row["key"] task_id = key.removeprefix("subagent:") if key != self.key(task_id): @@ -120,6 +146,10 @@ class SubagentSessions: result[task_id] = status return result + def read_batch(self, operation: Callable[[], _T]) -> _T: + """Share one store connection across the reads of a single request.""" + return self.sessions.read_batch(operation) + async def interrupt_pending(self) -> None: """Seal abandoned work after the gateway acquires execution ownership.""" for row in self.sessions.list_sessions(): diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index bc8a3fcca..0cf7357a9 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio import re import threading -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from copy import deepcopy from dataclasses import dataclass, field from datetime import datetime @@ -516,6 +516,18 @@ class SessionManager: """Read persisted child headers without transcripts, checkpoints, or pending inputs.""" return self._store.list_child_session_metadata(parent_key) + def list_subagent_session_metadata( + self, parent_key: str, *, turn_ids: Sequence[str], + ) -> list[SessionMetadataPayload]: + """Read persisted subagent headers attributed to the requested parent turns.""" + return self._store.list_subagent_session_metadata(parent_key, turn_ids=turn_ids) + + def read_child_session_metadata( + self, parent_key: str, child_keys: Sequence[str], + ) -> list[SessionMetadataPayload]: + """Read named persisted child headers without transcripts or pending inputs.""" + return self._store.read_child_session_metadata(parent_key, child_keys) + def save(self, session: Session) -> None: """Commit an offline administrative snapshot, rejecting obsolete history.""" self._require_offline_mutation() diff --git a/nanobot/session/sqlite_store.py b/nanobot/session/sqlite_store.py index d2fbc1f84..0df9a6fcb 100644 --- a/nanobot/session/sqlite_store.py +++ b/nanobot/session/sqlite_store.py @@ -4,7 +4,7 @@ import json import os import sqlite3 import threading -from collections.abc import Callable, Generator, Iterator +from collections.abc import Callable, Generator, Iterator, Sequence from concurrent.futures import CancelledError from contextlib import contextmanager, suppress from datetime import datetime @@ -25,12 +25,27 @@ from nanobot.session.manager import ( metadata_title, ) from nanobot.session.summary import is_summary_checkpoint -from nanobot.session.types import PARENT_SESSION_KEY +from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY _CHECKPOINT = "runtime_checkpoint" _INPUTS = ("pending_user_followups",) _T = TypeVar("_T") +# The expression below defines the v6 partial index and must stay stable for upgrades. +_SUBAGENT_ORIGIN = "origin_turn_id" +_SUBAGENT_PARENT = f"json_extract(metadata, '$.{PARENT_SESSION_KEY}')" +_SUBAGENT_ORIGIN_FILTER = ( + f"json_extract(metadata, '$.{SESSION_TYPE_KEY}')='subagent' " + f"AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text' " + f"AND json_type(metadata, '$.subagent_task.{_SUBAGENT_ORIGIN}')='text'" +) + +# Field names above are fixed by the schema; all caller-supplied values are bound. +_SUBAGENT_METADATA_QUERY = f"""SELECT key, created_at, updated_at, metadata FROM sessions + WHERE {_SUBAGENT_ORIGIN_FILTER} + AND {_SUBAGENT_PARENT}=? + AND json_extract(metadata, '$.subagent_task.{_SUBAGENT_ORIGIN}') IN (SELECT value FROM json_each(?))""" + def _encode(value: object) -> str: return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) @@ -123,9 +138,16 @@ def _create_schema_v5(db: sqlite3.Connection) -> None: ) WHERE kind='input'""") +def _create_schema_v6(db: sqlite3.Connection) -> None: + db.execute(f"""CREATE INDEX sessions_subagent_{_SUBAGENT_ORIGIN} ON sessions ( + {_SUBAGENT_PARENT}, json_extract(metadata, '$.subagent_task.{_SUBAGENT_ORIGIN}') + ) WHERE {_SUBAGENT_ORIGIN_FILTER}""") + + # Entries upgrade version N to N+1. Preserve released entries and append upgrades. _SCHEMA_MIGRATIONS: tuple[Callable[[sqlite3.Connection], None], ...] = ( _create_schema_v1, _create_schema_v2, _create_schema_v3, _create_schema_v4, _create_schema_v5, + _create_schema_v6, ) @@ -728,6 +750,36 @@ class SqliteSessionStore: (parent_key,), )] + def list_subagent_session_metadata( + self, parent_key: str, *, turn_ids: Sequence[str], + ) -> list[SessionMetadataPayload]: + """Read only subagent headers attributed to the requested parent turns.""" + turns = [value for value in turn_ids if value] + if not turns: + return [] + with self.transaction(write=False) as db: + return [{"key": row[0], "created_at": row[1], "updated_at": row[2], + "metadata": _object(row[3])} + for row in db.execute(_SUBAGENT_METADATA_QUERY, (parent_key, _encode(turns)))] + + def read_child_session_metadata( + self, parent_key: str, child_keys: Sequence[str], + ) -> list[SessionMetadataPayload]: + """Read named child headers in one query, excluding checkpoints and pending inputs.""" + keys = [key for key in child_keys if key] + if not keys: + return [] + with self.transaction(write=False) as db: + return [{"key": row[0], "created_at": row[1], "updated_at": row[2], + "metadata": _object(row[3])} + for row in db.execute( + f"""SELECT key, created_at, updated_at, metadata FROM sessions + WHERE key IN (SELECT value FROM json_each(?)) + AND json_extract(metadata, '$.{PARENT_SESSION_KEY}')=? + AND json_type(metadata, '$.{PARENT_SESSION_KEY}')='text'""", + (_encode(keys), parent_key), + )] + def list_metadata(self) -> list[dict[str, Any]]: with self.transaction(write=False) as db: # Fetch one value so a large list does not cross the Python/SQLite diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index ec76eb58e..9c52fb0a7 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -920,8 +920,22 @@ class GatewayHTTPHandler: return _http_error(404, "session not found") if self.subagent_manager is None: return _http_error(503, "subagent manager unavailable") + query = _parse_query(request.path) + scope = query.get("scope") + if scope is not None and scope != ["window"]: + return _http_error(400, "invalid task scope") + turns = query.get("turn_id", []) + tracked = query.get("track", []) + if scope == ["window"] and (len(turns) + len(tracked) > 512 + or any(not value or len(value) > 512 for value in (*turns, *tracked))): + return _http_error(400, "invalid task window") try: - statuses = await self.subagent_manager.read_statuses_for_session(session_key) + if scope == ["window"]: + statuses = await self.subagent_manager.read_statuses_for_session( + session_key, turns=turns, tracked=tracked, + ) + else: + statuses = await self.subagent_manager.read_statuses_for_session(session_key) except (OSError, SubagentSessionError): return _http_error(503, "task history unavailable") return _http_json_response({ diff --git a/tests/session/test_subagent_metadata_query.py b/tests/session/test_subagent_metadata_query.py new file mode 100644 index 000000000..747a23550 --- /dev/null +++ b/tests/session/test_subagent_metadata_query.py @@ -0,0 +1,136 @@ +import json +import sqlite3 +from datetime import datetime + +import nanobot.session.sqlite_store as sqlite_store +from nanobot.session.manager import Session, SessionManager +from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY + + +def test_subagent_metadata_matches_only_requested_turns(tmp_path, monkeypatch): + manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "storage") + parent = "chat:项目'\"\\root" + turn_id = "turn-雪'\"\\" + + def save(key, task, *, owner=parent, kind="subagent", second=0): + manager.save(Session( + key=key, updated_at=datetime(2026, 1, 1, 0, 0, second), + messages=[{"role": "user", "content": "private transcript"}], + metadata={ + PARENT_SESSION_KEY: owner, SESSION_TYPE_KEY: kind, "subagent_task": task, + "runtime_checkpoint": {"step": 1}, "pending_user_followups": [{"id": "queued"}], + }, + )) + + save("subagent:turn", {"origin_turn_id": turn_id, "state": "running"}, second=1) + save("subagent:unmatched", {"origin_turn_id": "unmatched"}, second=2) + save("subagent:other-parent", {"origin_turn_id": turn_id}, owner="chat:other", second=3) + save("extension:child", {"origin_turn_id": turn_id}, kind="extension", second=4) + save("subagent:grandchild", {"origin_turn_id": turn_id}, owner="subagent:turn", second=5) + save("subagent:blank", {"origin_turn_id": ""}, second=6) + save("subagent:no-origin", {"state": "running"}, second=7) + # Message-only attribution is not a turn and must not match the turn read. + save("subagent:message-only", {"origin_message_id": turn_id}, second=8) + + def prohibit_listing(*_args, **_kwargs): + raise AssertionError("filtered metadata must not load all child or session headers") + + monkeypatch.setattr(manager._store, "list_metadata", prohibit_listing) + monkeypatch.setattr(manager._store, "list_child_session_metadata", prohibit_listing) + decode = sqlite_store._object + decoded = [] + + def track_decode(raw): + metadata = decode(raw) + decoded.append(metadata) + return metadata + + monkeypatch.setattr(sqlite_store, "_object", track_decode) + rows = manager.list_subagent_session_metadata(parent, turn_ids=[turn_id, turn_id]) + assert {row["key"] for row in rows} == {"subagent:turn"} + assert len(decoded) == len(rows) + only = rows[0] + assert only["updated_at"] == "2026-01-01T00:00:01" + assert only["metadata"]["subagent_task"]["state"] == "running" + assert "runtime_checkpoint" not in only["metadata"] + assert "pending_user_followups" not in only["metadata"] + only["metadata"]["subagent_task"]["state"] = "changed" + assert manager.list_subagent_session_metadata(parent, turn_ids=[turn_id])[0]["metadata"][ + "subagent_task" + ]["state"] == "running" + + assert manager.list_subagent_session_metadata(parent, turn_ids=[]) == [] + assert manager.list_subagent_session_metadata(parent, turn_ids=[""]) == [] + assert manager.list_subagent_session_metadata( + "chat:missing' OR 1=1 --", turn_ids=[turn_id], + ) == [] + + +def test_subagent_origin_index_follows_metadata_updates(tmp_path): + manager = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "storage") + key, parent, other = "subagent:task", "chat:parent", "chat:other" + manager.save(Session(key=key, metadata={ + SESSION_TYPE_KEY: "subagent", PARENT_SESSION_KEY: parent, + "subagent_task": {"origin_turn_id": "turn"}, + })) + + def keys(owner): + return [row["key"] for row in manager.list_subagent_session_metadata( + owner, turn_ids=["turn"], + )] + + assert keys(parent) == [key] + assert manager.update_session_metadata(key, {"subagent_task": {"state": "running"}}) + assert keys(parent) == [] + assert manager.update_session_metadata(key, { + "subagent_task": {"origin_turn_id": "turn"}, PARENT_SESSION_KEY: other, + }) + assert keys(parent) == [] + assert keys(other) == [key] + + +def test_subagent_origin_index_upgrades_and_supports_large_batches(tmp_path, monkeypatch): + workspace, root = tmp_path / "workspace", tmp_path / "storage" + parent = "chat:upgrade" + turn_ids = [f"turn-{i}" for i in range(4000)] + with monkeypatch.context() as patch: + patch.setattr(sqlite_store, "_SCHEMA_MIGRATIONS", sqlite_store._SCHEMA_MIGRATIONS[:5]) + manager = SessionManager(workspace, sessions_root=root) + + def seed(): + for key, owner, task in ( + ("subagent:turn", parent, {"origin_turn_id": turn_ids[-1]}), + ("subagent:no-origin", parent, {"state": "done"}), + *( + (f"subagent:unrelated-{i}", parent, {"origin_turn_id": f"not-in-page-{i}"}) + for i in range(150) + ), + ): + manager.save(Session(key=key, metadata={ + SESSION_TYPE_KEY: "subagent", PARENT_SESSION_KEY: owner, "subagent_task": task, + })) + + manager._store.run_write(seed) + with manager._store.transaction(write=False) as db: + assert db.execute("PRAGMA user_version").fetchone()[0] == 5 + + upgraded = SessionManager(workspace, sessions_root=root) + # Reopening upgrades only once and retains already persisted metadata. + upgraded = SessionManager(workspace, sessions_root=root) + with upgraded._store.transaction(write=False) as db: + assert db.execute("PRAGMA user_version").fetchone()[0] == len(sqlite_store._SCHEMA_MIGRATIONS) + plan = [row[3] for row in db.execute( + "EXPLAIN QUERY PLAN " + sqlite_store._SUBAGENT_METADATA_QUERY, + (parent, json.dumps(turn_ids)), + )] + assert any( + "SEARCH sessions USING INDEX sessions_subagent_origin_turn_id" in detail + and "=? AND =?" in detail + for detail in plan + ), plan + # The API must not consume one SQLite variable per requested ID. + db.setlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, 10) + rows = upgraded.list_subagent_session_metadata(parent, turn_ids=turn_ids) + + assert {row["key"] for row in rows} == {"subagent:turn"} + assert rows[0]["metadata"]["subagent_task"] == {"origin_turn_id": turn_ids[-1]} diff --git a/tests/webui/test_subagent_persistence.py b/tests/webui/test_subagent_persistence.py index bd00812aa..55425f4ce 100644 --- a/tests/webui/test_subagent_persistence.py +++ b/tests/webui/test_subagent_persistence.py @@ -17,6 +17,7 @@ from nanobot.agent.memory import Consolidator from nanobot.agent.runner import AgentRunResult from nanobot.agent.subagent import SubagentControlError, SubagentManager from nanobot.agent.subagent_sessions import SUBAGENT, TASK_METADATA_KEY, SubagentSessions +from nanobot.agent.subagent_status import SubagentStatus from nanobot.agent.tools.context import RequestContext, current_request_context, request_context from nanobot.agent.tools.session_messages import SendSessionMessageTool from nanobot.agent.tools.sessions import ReadSessionTool, SearchSessionsTool @@ -33,8 +34,9 @@ from nanobot.providers.base import ( ) from nanobot.session.jsonl_migration import WORKSPACE_BACKUP_DIR from nanobot.session.location import SessionLocation -from nanobot.session.manager import SessionManager +from nanobot.session.manager import SessionManager, SessionPolicy from nanobot.session.session_handles import SessionHandleResolver +from nanobot.session.sqlite_store import SqliteSessionStore from nanobot.session.summary import SessionSummaryCheckpoint, is_summary_checkpoint from nanobot.session.types import PARENT_SESSION_KEY, SESSION_TYPE_KEY from nanobot.session.webui_turns import WebuiTurnCoordinator @@ -65,6 +67,106 @@ def gateway_for(manager, sessions, workspace): return gateway, SimpleNamespace(remote_address=("127.0.0.1", 12345)), Headers({"Authorization": f"Bearer {token}"}) +@pytest.mark.asyncio +async def test_windowed_task_reads_limit_history_and_reconcile_active_work(tmp_path): + manager, sessions, runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions") + await sessions.state.get("websocket:parent") + await sessions.state.get("websocket:other") + + async def saved(task_id, owner, *, turn_id="turn-a"): + status = SubagentStatus( + task_id=task_id, label=task_id, task_description=task_id, owner=owner, + started_at=0, finished_at=1, state="done", completed_at=1, + origin_turn_id=turn_id, + ) + await sessions.state.create_child( + owner, SubagentSessions.key(task_id), + metadata={SESSION_TYPE_KEY: SUBAGENT.name, TASK_METADATA_KEY: SubagentSessions._payload(status)}, + content=task_id, policy=SessionPolicy(), + ) + + await saved("a", "websocket:parent") + await saved("b", "websocket:parent", turn_id="turn-b") + # A task with no origin is only reachable while the caller still tracks it. + await saved("unknown", "websocket:parent", turn_id=None) + await saved("foreign", "websocket:other") + entered = asyncio.Event() + + async def blocked(spec): + entered.set() + await asyncio.Event().wait() + + manager.runner.run = blocked + await manager.spawn("active", session_key="websocket:parent", runtime=runtime) + await asyncio.wait_for(entered.wait(), timeout=2) + active_id, = manager._tasks + gateway, connection, headers = gateway_for(manager, sessions, tmp_path / "agent") + path = "/api/sessions/websocket%3Aparent/subagents" + try: + response = await gateway.http.dispatch( + connection, Request(path + "?scope=window&turn_id=turn-a", headers), + ) + assert response.status_code == 200 + assert {task["task_id"] for task in json.loads(response.body)["tasks"]} == {"a", active_id} + tracked = await gateway.http.dispatch( + connection, Request(path + "?scope=window&track=b&track=foreign", headers), + ) + # Live work is always included; tracked tasks outside the loaded turns come along. + assert {task["task_id"] for task in json.loads(tracked.body)["tasks"]} == {active_id, "b"} + legacy_read = await gateway.http.dispatch(connection, Request(path, headers)) + assert {task["task_id"] for task in json.loads(legacy_read.body)["tasks"]} == { + "a", "b", "unknown", active_id, + } + for invalid in ("?scope=window&turn_id=", "?scope=everything"): + malformed = await gateway.http.dispatch(connection, Request(path + invalid, headers)) + assert malformed.status_code == 400, invalid + finally: + await manager.close() + + +@pytest.mark.asyncio +async def test_windowed_task_read_opens_one_store_connection(tmp_path, monkeypatch): + manager, sessions, _runtime = manager_with_storage(tmp_path / "agent", tmp_path / "sessions") + await sessions.state.get("websocket:parent") + for task_id, turn_id in ( + ("in-window", "turn-window"), + ("tracked-1", "turn-old"), + ("tracked-2", "turn-old"), + ("tracked-3", "turn-old"), + ): + status = SubagentStatus( + task_id=task_id, label=task_id, task_description=task_id, owner="websocket:parent", + started_at=0, finished_at=1, state="done", completed_at=1, + origin_turn_id=turn_id, + ) + await sessions.state.create_child( + "websocket:parent", SubagentSessions.key(task_id), + metadata={SESSION_TYPE_KEY: SUBAGENT.name, TASK_METADATA_KEY: SubagentSessions._payload(status)}, + content=task_id, policy=SessionPolicy(), + ) + + opened = 0 + original = SqliteSessionStore._open_connection + + def counting(self, *, worker: bool = False): + nonlocal opened + opened += 1 + return original(self, worker=worker) + + monkeypatch.setattr(SqliteSessionStore, "_open_connection", counting) + try: + statuses = await manager.read_statuses_for_session( + "websocket:parent", turns=["turn-window"], + tracked=["tracked-1", "tracked-2", "tracked-3"], + ) + # Tracked work outside the window stays visible, and the whole read shares + # one connection instead of one per tracked task. + assert set(statuses) == {"in-window", "tracked-1", "tracked-2", "tracked-3"} + assert opened == 1 + finally: + await manager.close() + + async def wait_for_model_requests(manager, task_id, requests, count): task = manager._running_tasks[task_id] for _ in range(count): diff --git a/webui/browser/history-boundary-fixture.tsx b/webui/browser/history-boundary-fixture.tsx index 2b3ccff15..9dc343911 100644 --- a/webui/browser/history-boundary-fixture.tsx +++ b/webui/browser/history-boundary-fixture.tsx @@ -1,4 +1,4 @@ -import { Profiler, useState } from "react"; +import { Profiler, useCallback, useState } from "react"; import { ThreadViewport } from "@/components/thread/ThreadViewport"; import { SubagentTasksProvider } from "@/components/thread/SubagentTasks"; import { useClient } from "@/providers/ClientProvider"; @@ -17,6 +17,12 @@ export function HistoryBoundaryFixture({ local = false, navigate = false, tasks const history = useSessionHistory(local ? null : key); const messages = local ? localMessages : history.messages; const navigation = usePromptHistory(local ? null : key, history.version, messages); + const [taskWindow, setTaskWindow] = useState<{ key: string; turnIds: string[] } | null>(null); + const reportVisibleMessages = useCallback((visible: UIMessage[]) => { + const turnIds = [...new Set(visible.flatMap(message => message.role === "user" && message.turnId ? [message.turnId] : []))]; + setTaskWindow(current => current?.key === key && current.turnIds.length === turnIds.length + && current.turnIds.every((turnId, index) => turnId === turnIds[index]) ? current : { key, turnIds }); + }, [key]); return
@@ -24,10 +30,13 @@ export function HistoryBoundaryFixture({ local = false, navigate = false, tasks { window.dispatchEvent(new CustomEvent("history-boundary-render", { detail: { phase, actualDuration } })); }}> - + 0)}> 0) { has_more_before: more, has_more_after: start + count < 52 } }; } -async function installHistory(page: Page, initialStart = 40, initialCount = 12) { +async function installHistory(page: Page, initialStart = 40, initialCount = 12, pageContent = historyPage) { const reads: string[] = []; const pending: Array<(value: "success" | "error") => void> = []; let fastResponse = false; @@ -19,9 +19,9 @@ async function installHistory(page: Page, initialStart = 40, initialCount = 12) prompts: Array.from({ length: 52 }, (_, i) => ({ id: `u${i}`, preview: `Question ${i}`, answerPreview: "Historical answer", turnId: `turn${i}`, cursor: String(i), createdAt: i + 1 })), } }); if (!url.pathname.endsWith("/webui-thread")) return route.fulfill({ json: {} }); - if (url.pathname.includes("boundary-b")) return route.fulfill({ json: historyPage(0, 2, false) }); + if (url.pathname.includes("boundary-b")) return route.fulfill({ json: pageContent(0, 2, false) }); const cursor = url.searchParams.get("before") ?? url.searchParams.get("after"); - if (cursor === null) return route.fulfill({ json: historyPage(initialStart, initialCount) }); + if (cursor === null) return route.fulfill({ json: pageContent(initialStart, initialCount) }); reads.push(url.search); const outcome = fastResponse ? await new Promise<"success">((resolve) => { releaseFastResponse = () => resolve("success"); }) @@ -29,7 +29,7 @@ async function installHistory(page: Page, initialStart = 40, initialCount = 12) if (outcome === "error") return route.fulfill({ status: 503, body: "History unavailable" }); const start = url.searchParams.has("after") ? Number(cursor) : Math.max(0, Number(cursor) - 12); const count = url.searchParams.has("after") ? 12 : Number(cursor) - start; - await route.fulfill({ json: historyPage(start, count, start > 0) }); + await route.fulfill({ json: pageContent(start, count, start > 0) }); }); return { reads, @@ -305,16 +305,28 @@ test("wheel loading hands off to a retained 48px slot; prepend and delayed layou }); test("task results stay with their prompts and retain the reading boundary when earlier messages load", async ({ page }) => { - const history = await installHistory(page); - await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [ - { task_id: "current", label: "Current check", origin_message_id: "u40" }, - { task_id: "earlier", label: "Earlier check", origin_message_id: "u28" }, - ].map((task) => ({ - ...task, revision: 1, task_description: "Check work", - state: "done", phase: "completed", elapsed_seconds: 2, iteration: 1, - tool_events: [], usage: null, receipts: {}, result: "Verified", partial: false, - stop_reason: null, error: null, origin_turn_id: null, created_at: 100, completed_at: 102, - })) } })); + const history = await installHistory(page, 40, 12, (start, count, more) => { + const payload = historyPage(start, count, more); + return { ...payload, events: payload.events.map(event => ({ + ...event, turn_id: `turn${event.projection_id.slice(1)}`, + })) }; + }); + const taskReads: string[][] = []; + await page.route("**/api/sessions/**/subagents?*", (route) => { + const query = new URL(route.request().url()).searchParams; + expect(query.get("scope")).toBe("window"); + const turns = query.getAll("turn_id"); + taskReads.push(turns); + return route.fulfill({ json: { tasks: [ + { task_id: "current", label: "Current check", origin_turn_id: "turn40" }, + { task_id: "earlier", label: "Earlier check", origin_turn_id: "turn28" }, + ].filter(task => turns.includes(task.origin_turn_id)).map((task) => ({ + ...task, revision: 1, task_description: "Check work", + state: "done", phase: "completed", elapsed_seconds: 2, iteration: 1, + tool_events: [], usage: null, receipts: {}, result: "Verified", partial: false, + stop_reason: null, error: null, origin_message_id: null, created_at: 100, completed_at: 102, + })) } }); + }); await page.goto("/browser/fixture.html?case=history-boundary&tasks"); const body = page.getByTestId("thread-message-region"); const currentResults = body.locator('[data-user-prompt-id="u40"] + [data-subagent-results]'); @@ -347,6 +359,10 @@ test("task results stay with their prompts and retain the reading boundary when expect(history.reads).toHaveLength(1); await earlierResults.locator("[data-subagent-results-summary]").click(); await expect(earlierResults.getByRole("button", { name: /Earlier check Completed/ })).toBeVisible(); + expect(taskReads).toEqual([ + Array.from({ length: 12 }, (_, index) => `turn${40 + index}`), + Array.from({ length: 12 }, (_, index) => `turn${28 + index}`), + ]); }); test("touch reveals a static partial ready header, arms only on release, and retains a stable full loading header", async ({ browser, baseURL }) => { diff --git a/webui/src/components/thread/SubagentTasks.tsx b/webui/src/components/thread/SubagentTasks.tsx index 5392c5961..318f1f202 100644 --- a/webui/src/components/thread/SubagentTasks.tsx +++ b/webui/src/components/thread/SubagentTasks.tsx @@ -7,7 +7,7 @@ import { InterruptedTaskIcon, ErrorTaskIcon, } from "@/components/icons/product-icons"; -import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"; +import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; @@ -47,11 +47,13 @@ interface SubagentTasksProviderProps { enabled: boolean; liveEvents: boolean; historyEnabled?: boolean; + turnIds: string[]; + windowReady?: boolean; active?: boolean; children: ReactNode; } -export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, active = true, children }: SubagentTasksProviderProps) { +export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, turnIds, windowReady = true, active = true, children }: SubagentTasksProviderProps) { const { t } = useTranslation("common"); const pageVisible = usePageVisibility(); const paneVisible = useThreadVisibility(); @@ -64,9 +66,29 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live const trigger = useRef(null); const buttons = useRef(new Map()); const detailPanel = useRef(null); + const taskRef = useRef(tasks); + taskRef.current = tasks; + const windowScope = { turnIds }; + const windowKey = JSON.stringify(windowScope); + const windowRef = useRef(windowScope); + windowRef.current = windowScope; + const windowKeyRef = useRef(windowKey); + windowKeyRef.current = windowKey; + const readState = useMemo(() => ({ + turnIds: new Set(), inFlight: false, force: false, epoch: 0, + }), [client, sessionKey]); + const readStateRef = useRef(readState); + readStateRef.current = readState; + const refreshRef = useRef<((force: boolean, invalidate?: boolean) => void) | null>(null); + const mergeTasks = (incoming: SubagentTaskSnapshot[]) => { + const next = mergeSubagentTasks(taskRef.current, incoming); + taskRef.current = next; + setTasks(next); + }; useLayoutEffect(() => { scopeGeneration.current += 1; + taskRef.current = []; setTasks([]); setSelectedId(null); setStoppingId(null); @@ -84,46 +106,80 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live }, [active, paneVisible]); useEffect(() => { - if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token) return; + if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token || !liveEvents) return; + let subscribing = true; + const unsubscribeChat = client.onChat(sessionKey.slice("websocket:".length), (event) => { + if (readStateRef.current === readState && event.event === "subagent_task" && isSubagentTask(event.task)) mergeTasks([event.task]); + }); + const unsubscribeStatus = client.onStatus((status) => { + if (!subscribing && status === "open") refreshRef.current?.(true, true); + }); + subscribing = false; + return () => { unsubscribeChat(); unsubscribeStatus(); }; + }, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible, readState]); + + useEffect(() => { + if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token || !windowReady) return; let cancelled = false; - let refreshing = false; - let refreshPending = false; - const refresh = async () => { - if (refreshing) { refreshPending = true; return; } - refreshing = true; - try { - const payload = await fetchSubagentTasks(token, sessionKey); - if (!cancelled) { - setTasks((current) => mergeSubagentTasks(current, payload.tasks)); + let scheduled = false; + const read = () => { + if (readState.inFlight) return; + const full = readState.force; + const current = windowRef.current; + const requested = { + turnIds: current.turnIds.filter((id) => full || !readState.turnIds.has(id)), + }; + if (!full && requested.turnIds.length === 0) return; + readState.force = false; + readState.inFlight = true; + const requestedKey = windowKeyRef.current; + const requestedEpoch = readState.epoch; + const window = { + ...requested, + trackedIds: taskRef.current.filter(isActiveSubagentTask).map((task) => task.task_id), + }; + let succeeded = false; + void fetchSubagentTasks(token, sessionKey, window).then((payload) => { + if (!mounted.current || readStateRef.current !== readState) return; + succeeded = true; + if (requestedEpoch === readState.epoch) { + for (const id of requested.turnIds) readState.turnIds.add(id); } - } catch { - // Background read failures retain the last task snapshot. - } finally { - refreshing = false; - if (refreshPending && !cancelled) { - refreshPending = false; - void refresh(); - } - } + mergeTasks(payload.tasks); + }).catch(() => { + // Background read failures retain the last task snapshot and remain retryable. + }).finally(() => { + readState.inFlight = false; + if (readStateRef.current === readState + && (succeeded || readState.force || requestedKey !== windowKeyRef.current)) refreshRef.current?.(false); + }); }; - const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => { - if (cancelled || event.event !== "subagent_task") return; - if (!isSubagentTask(event.task)) return; - setTasks((current) => mergeSubagentTasks(current, [event.task])); - }) : undefined; - const unsubscribeStatus = liveEvents ? client.onStatus((status) => { - if (status === "open") void refresh(); - }) : undefined; - if (!refreshing) void refresh(); - const focus = () => void refresh(); + const refresh = (force: boolean, invalidate = false) => { + if (cancelled) return; + if (invalidate) { + // Events may have been missed on any previously viewed page. Mark all + // pages stale, then refresh only the current one and revisit others lazily. + readState.epoch += 1; + readState.turnIds.clear(); + } + if (force) readState.force = true; + if (scheduled) return; + scheduled = true; + // Coalesce layout-driven window changes and Strict Mode effect replays. + queueMicrotask(() => { scheduled = false; if (!cancelled) read(); }); + }; + refreshRef.current = refresh; + refresh(true, true); + const focus = () => refresh(true, true); window.addEventListener("focus", focus); return () => { cancelled = true; - unsubscribeChat?.(); - unsubscribeStatus?.(); + refreshRef.current = null; window.removeEventListener("focus", focus); }; - }, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible]); + }, [client, enabled, active, sessionKey, token, pageVisible, paneVisible, windowReady, readState]); + + useEffect(() => { refreshRef.current?.(false); }, [windowKey]); const stop = async (task: SubagentTaskSnapshot) => { if (!sessionKey) return; @@ -133,7 +189,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live try { const next = await cancelSubagentTask(client, sessionKey, task.task_id); if (!mounted.current || generation !== scopeGeneration.current) return; - setTasks((current) => mergeSubagentTasks(current, [next])); + mergeTasks([next]); } catch (reason) { if (mounted.current && generation === scopeGeneration.current) setStopError(reason instanceof Error ? reason.message : t("thread.subagents.stopFailed")); } finally { diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 067d5d3ae..65b1d88e9 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -485,6 +485,17 @@ export function ThreadShell({ const { t } = useTranslation(); const chatId = session?.chatId ?? null; const historyKey = temporary ? null : session?.key ?? null; + const [visibleWindow, setVisibleWindow] = useState<{ key: string | null; turnIds: string[]; hasMessages: boolean } | null>(null); + const reportVisibleMessages = useCallback((messages: UIMessage[]) => { + // Saved results attach to turns, so only the rendered user turns matter here. + const turnIds = [...new Set(messages.flatMap((message) => ( + message.role === "user" && message.turnId ? [message.turnId] : [] + )))]; + setVisibleWindow((current) => current?.key === historyKey && current.hasMessages === (messages.length > 0) + && current.turnIds.length === turnIds.length + && current.turnIds.every((turnId, index) => turnId === turnIds[index]) + ? current : { key: historyKey, turnIds, hasMessages: messages.length > 0 }); + }, [historyKey]); const previewSessionKey = session?.key ?? null; const mentionSessions = useMemo( () => sessions.filter((candidate) => candidate.key !== historyKey).map((candidate) => { @@ -1527,6 +1538,8 @@ export function ThreadShell({ sessionKey={session?.key ?? null} liveEvents={webuiCapabilities.includes("webui.subagents.events.v1")} historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")} + turnIds={visibleWindow?.key === historyKey ? visibleWindow.turnIds : []} + windowReady={messagesReady && visibleWindow?.key === historyKey && (!initialHistoryLoading || visibleWindow.hasMessages)} active={composerActive} enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
@@ -1573,6 +1586,7 @@ export function ThreadShell({ activeTurnStartedHere={activeTurnStartedHere} conversationKey={historyKey} conversationReady={messagesReady} + onVisibleMessagesChange={reportVisibleMessages} showScrollToBottomButton={!!session} cliApps={cliApps} mcpPresets={mcpPresets} diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index 38a56446e..94415caa4 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -60,6 +60,7 @@ interface ThreadViewportProps { /** Override when message ownership changes after the selected conversation. */ messagesKey?: string | null; conversationReady?: boolean; + onVisibleMessagesChange?: (messages: UIMessage[]) => void; showScrollToBottomButton?: boolean; cliApps?: CliAppInfo[]; mcpPresets?: McpPresetInfo[]; @@ -287,6 +288,7 @@ export const ThreadViewport = forwardRef windowMessages(messages, visibleMessageCount), [messages, visibleMessageCount], ); + useLayoutEffect(() => { + if (conversationReady) onVisibleMessagesChange?.(visibleMessages); + }, [conversationReady, onVisibleMessagesChange, visibleMessages]); const hiddenMessageCount = messages.length - visibleMessages.length; const historyUnknown = hasMoreBefore === null; const historyExhausted = hasMoreBefore === false && hiddenMessageCount === 0; diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index a12356a60..bb3d089f9 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -696,15 +696,53 @@ export async function updateAutomation( return mutation(transport, "automation.update", { id, values }); } -export async function fetchSubagentTasks(token: string, sessionKey: string): Promise { - const payload = await request( - `/api/sessions/${encodeURIComponent(sessionKey)}/subagents`, token, undefined, API_READ_TIMEOUT_MS, - ); - if (!isRecord(payload) || !Array.isArray(payload.tasks) || !payload.tasks.every(isSubagentTask) - || new Set(payload.tasks.map((task) => task.task_id)).size !== payload.tasks.length) { - throw new Error("Invalid subagent tasks response"); +export interface SubagentTaskWindow { + turnIds: string[]; + trackedIds: string[]; +} + +export async function fetchSubagentTasks( + token: string, sessionKey: string, window: SubagentTaskWindow, +): Promise { + const path = `/api/sessions/${encodeURIComponent(sessionKey)}/subagents`; + const queries: URLSearchParams[] = []; + let query = new URLSearchParams({ scope: "window" }); + // Track the encoded length as it grows; re-serializing the whole target per id would be quadratic. + let length = query.toString().length; + let count = 0; + for (const [key, values] of [ + ["turn_id", window.turnIds], ["track", window.trackedIds], + ] as const) { + for (const value of values) { + const pair = new URLSearchParams({ [key]: value }).toString(); + // Keep request targets bounded, including percent-encoded identifiers. + if (count && (length + 1 + pair.length > 5000 || count >= 400)) { + queries.push(query); + query = new URLSearchParams({ scope: "window" }); + length = query.toString().length; + count = 0; + } + query.append(key, value); + length += 1 + pair.length; + count += 1; + } } - return { tasks: payload.tasks }; + queries.push(query); + const tasks = new Map(); + for (const query of queries) { + const payload = await request( + `${path}?${query}`, token, undefined, API_READ_TIMEOUT_MS, + ); + if (!isRecord(payload) || !Array.isArray(payload.tasks) || !payload.tasks.every(isSubagentTask) + || new Set(payload.tasks.map((task) => task.task_id)).size !== payload.tasks.length) { + throw new Error("Invalid subagent tasks response"); + } + for (const task of payload.tasks) { + const previous = tasks.get(task.task_id); + if (!previous || (task.revision ?? 0) > (previous.revision ?? 0)) tasks.set(task.task_id, task); + } + } + return { tasks: [...tasks.values()] }; } export async function fetchSubagentThread( diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index c8e39dc18..c8f3333a5 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -34,6 +34,7 @@ import { fetchTrendingMarketplaceSkills, fetchWebuiThread, fetchSubagentThread, + fetchSubagentTasks, fetchWebuiThreadTraceDetail, fetchWorkspaces, importMcpConfig, @@ -105,6 +106,20 @@ describe("webui API helpers", () => { ); }); + it("splits a large subagent window into bounded reads", async () => { + vi.mocked(fetch).mockResolvedValue({ ok: true, json: async () => ({ tasks: [] }) } as Response); + const turnIds = Array.from({ length: 400 }, (_, index) => `turn-${index}-${"x".repeat(32)}`); + await expect(fetchSubagentTasks("tok", "websocket:chat-1", { + turnIds, trackedIds: ["task-1"], + })).resolves.toEqual({ tasks: [] }); + const urls = vi.mocked(fetch).mock.calls.map(([url]) => new URL(String(url), "http://localhost")); + expect(urls.length).toBeGreaterThan(1); + expect(urls.every((url) => url.search.length <= 5001)).toBe(true); + expect(urls.every((url) => url.searchParams.get("scope") === "window")).toBe(true); + expect(urls.flatMap((url) => url.searchParams.getAll("turn_id"))).toEqual(turnIds); + expect(urls.flatMap((url) => url.searchParams.getAll("track"))).toEqual(["task-1"]); + }); + it("percent-encodes websocket keys when fetching webui-thread snapshot", async () => { await fetchWebuiThread("tok", "websocket:chat-1"); diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx index 061b13428..ceb4dc060 100644 --- a/webui/src/tests/app-layout.test.tsx +++ b/webui/src/tests/app-layout.test.tsx @@ -72,7 +72,7 @@ function mockFetchRoutes(routes: Record): void { vi.fn(async (input: RequestInfo | URL) => { const route = routes[String(input)] ?? (String(input) === "/api/webui/sidebar-state" ? {} : undefined) - ?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined); + ?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(new URL(String(input), "http://localhost").pathname) ? { tasks: [] } : undefined); const body = typeof route === "function" ? await (route as () => unknown | Promise)() @@ -415,7 +415,7 @@ describe("App layout", () => { terminal: { webui: { capabilities: supported ? ["webui.core.v1", "webui.subagents.v1"] : ["webui.core.v1"] } }, }); mockFetchRoutes({ - "/api/sessions/websocket%3Achat-a/subagents": { tasks: [{ + "/api/sessions/websocket%3Achat-a/subagents?scope=window": { tasks: [{ task_id: "task-1", label: "Config check", task_description: "Inspect configuration", state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1, tool_events: [], usage: null, receipts: {}, result: null, partial: false, @@ -434,7 +434,7 @@ describe("App layout", () => { await userEvent.setup().click(trigger); expect(await screen.findByRole("button", { name: /Config check Running/ })).toBeVisible(); } else expect(screen.queryByRole("button", { name: /Subtasks/ })).not.toBeInTheDocument(); - const reads = vi.mocked(fetch).mock.calls.filter(([url]) => String(url).endsWith("/subagents")); + const reads = vi.mocked(fetch).mock.calls.filter(([url]) => new URL(String(url), "http://localhost").pathname.endsWith("/subagents")); expect(reads).toHaveLength(supported ? 1 : 0); expect(requestMutationSpy).not.toHaveBeenCalled(); }); diff --git a/webui/src/tests/chat-replay-ownership.test.tsx b/webui/src/tests/chat-replay-ownership.test.tsx index b9e7924cf..687f846bc 100644 --- a/webui/src/tests/chat-replay-ownership.test.tsx +++ b/webui/src/tests/chat-replay-ownership.test.tsx @@ -67,7 +67,7 @@ describe("transcript replay with real task and stream subscriptions", () => { const tree = (showThread: boolean) => ( {showThread && } + token="test" enabled liveEvents turnIds={[TURN_ID]}>{showThread && } ); const view = render(tree(false)); @@ -103,7 +103,7 @@ describe("transcript replay with real task and stream subscriptions", () => { socket.receive(toolMessage("while-away-c")); const tasks = (children?: ReactNode) => ( {children} + token="test" enabled liveEvents turnIds={[TURN_ID]}>{children} ); const view = render( diff --git a/webui/src/tests/subagent-results.test.tsx b/webui/src/tests/subagent-results.test.tsx index dc9296cfc..e4fb6d6ed 100644 --- a/webui/src/tests/subagent-results.test.tsx +++ b/webui/src/tests/subagent-results.test.tsx @@ -1,4 +1,5 @@ -import { act, cleanup, render, screen, waitFor, within } from "@testing-library/react"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { StrictMode } from "react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -7,17 +8,22 @@ import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults" import { SubagentTasksProvider } from "@/components/thread/SubagentTasks"; import { setAppLanguage } from "@/i18n"; import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences"; -import type { InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types"; +import type { ConnectionStatus, InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types"; const requestMutation = vi.fn(); const chatHandlers = new Set<(event: InboundEvent) => void>(); +const statusHandlers = new Set<(status: ConnectionStatus) => void>(); const client = { requestMutation, onChat: vi.fn((_chatId: string, handler: (event: InboundEvent) => void) => { chatHandlers.add(handler); return () => { chatHandlers.delete(handler); }; }), - onStatus: vi.fn(() => () => {}), + onStatus: vi.fn((handler: (status: ConnectionStatus) => void) => { + statusHandlers.add(handler); + handler("open"); + return () => { statusHandlers.delete(handler); }; + }), }; const messages: UIMessage[] = [ { id: "prompt-a", role: "user", content: "Inspect config", turnId: "turn-a", createdAt: 100_000 }, @@ -47,14 +53,17 @@ function emitTask(snapshot: SubagentTaskSnapshot) { chatHandlers.forEach((handler) => handler({ event: "subagent_task", chat_id: "a", task: snapshot })); }); } -function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, onActivityToggle }: { +function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, active = true, onActivityToggle }: { threadMessages?: UIMessage[]; sessionKey?: string; liveEvents?: boolean; historyEnabled?: boolean; + active?: boolean; onActivityToggle?: () => void; } = {}) { - return + return message.role === "user" && message.turnId) + .map((message) => message.turnId as string))]}>