perf(subagent): read saved task history by loaded turns (#6634)
This commit is contained in:
1 parent
1196698ecb
commit
eb8546c321
20 files changed
+893
-97
No files matched your search
+1
-1
@@ -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.
|
||||
|
||||
|
||||
+58
-15
@@ -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:
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 "<expr>=? AND <expr>=?" 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]}
|
||||
@@ -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):
|
||||
|
||||
@@ -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 <main className="bg-background text-foreground" style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
|
||||
<div className="flex h-10 shrink-0 items-center gap-4 px-4 text-sm">
|
||||
<button onClick={() => setKey((current) => current.endsWith("-a") ? "websocket:boundary-b" : "websocket:boundary-a")}>Switch conversation</button>
|
||||
@@ -24,10 +30,13 @@ export function HistoryBoundaryFixture({ local = false, navigate = false, tasks
|
||||
<Profiler id="history-boundary" onRender={(_, phase, actualDuration) => {
|
||||
window.dispatchEvent(new CustomEvent("history-boundary-render", { detail: { phase, actualDuration } }));
|
||||
}}>
|
||||
<SubagentTasksProvider client={client} token={token} sessionKey={key} enabled={tasks} liveEvents={false}>
|
||||
<SubagentTasksProvider client={client} token={token} sessionKey={key} enabled={tasks} liveEvents={false}
|
||||
turnIds={taskWindow?.key === key ? taskWindow.turnIds : []}
|
||||
windowReady={taskWindow?.key === key && (!history.loading || messages.length > 0)}>
|
||||
<ThreadViewport messages={messages} isStreaming={false} conversationKey={key}
|
||||
messagesKey={local ? key : history.messagesKey}
|
||||
conversationReady={local || history.messagesReady} hasMoreBefore={history.hasMoreBefore}
|
||||
onVisibleMessagesChange={tasks ? reportVisibleMessages : undefined}
|
||||
initialLoading={history.loading} initialError={history.error} onRetryInitial={history.refresh}
|
||||
loadingOlder={history.loadingOlder} olderError={history.olderError} onLoadOlder={history.loadOlder}
|
||||
navigation={navigate ? navigation : undefined} userMessageOffset={history.userMessageOffset}
|
||||
|
||||
@@ -8,7 +8,7 @@ function historyPage(start: number, count = 12, more = start > 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 }) => {
|
||||
|
||||
@@ -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<HTMLButtonElement | null>(null);
|
||||
const buttons = useRef(new Map<string, HTMLButtonElement>());
|
||||
const detailPanel = useRef<HTMLDivElement | null>(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<string>(), 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 {
|
||||
|
||||
@@ -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")}>
|
||||
<section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
@@ -1573,6 +1586,7 @@ export function ThreadShell({
|
||||
activeTurnStartedHere={activeTurnStartedHere}
|
||||
conversationKey={historyKey}
|
||||
conversationReady={messagesReady}
|
||||
onVisibleMessagesChange={reportVisibleMessages}
|
||||
showScrollToBottomButton={!!session}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
|
||||
@@ -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<ThreadViewportHandle, ThreadViewportPro
|
||||
conversationKey = null,
|
||||
messagesKey = conversationKey,
|
||||
conversationReady = true,
|
||||
onVisibleMessagesChange,
|
||||
showScrollToBottomButton = true,
|
||||
cliApps = [],
|
||||
mcpPresets = [],
|
||||
@@ -471,6 +473,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
() => 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;
|
||||
|
||||
+46
-8
@@ -696,15 +696,53 @@ export async function updateAutomation(
|
||||
return mutation<AutomationsPayload>(transport, "automation.update", { id, values });
|
||||
}
|
||||
|
||||
export async function fetchSubagentTasks(token: string, sessionKey: string): Promise<SubagentTasksPayload> {
|
||||
const payload = await request<unknown>(
|
||||
`/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<SubagentTasksPayload> {
|
||||
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<string, SubagentTasksPayload["tasks"][number]>();
|
||||
for (const query of queries) {
|
||||
const payload = await request<unknown>(
|
||||
`${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(
|
||||
|
||||
@@ -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");
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ function mockFetchRoutes(routes: Record<string, unknown>): 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<unknown>)()
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -67,7 +67,7 @@ describe("transcript replay with real task and stream subscriptions", () => {
|
||||
const tree = (showThread: boolean) => (
|
||||
<ClientProvider client={client} token="test">
|
||||
<SubagentTasksProvider client={client} sessionKey={`websocket:${CHAT_ID}`}
|
||||
token="test" enabled liveEvents>{showThread && <Thread />}</SubagentTasksProvider>
|
||||
token="test" enabled liveEvents turnIds={[TURN_ID]}>{showThread && <Thread />}</SubagentTasksProvider>
|
||||
</ClientProvider>
|
||||
);
|
||||
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) => (
|
||||
<SubagentTasksProvider client={client} sessionKey={`websocket:${CHAT_ID}`}
|
||||
token="test" enabled liveEvents>{children}</SubagentTasksProvider>
|
||||
token="test" enabled liveEvents turnIds={[TURN_ID]}>{children}</SubagentTasksProvider>
|
||||
);
|
||||
const view = render(
|
||||
<ClientProvider client={client} token="test">
|
||||
|
||||
@@ -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 <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
|
||||
return <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}
|
||||
turnIds={[...new Set(threadMessages.filter((message) => message.role === "user" && message.turnId)
|
||||
.map((message) => message.turnId as string))]}>
|
||||
<div data-testid="messages"><SubagentThreadMessages messages={threadMessages} onActivityToggle={onActivityToggle} /></div>
|
||||
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
|
||||
</SubagentTasksProvider>;
|
||||
@@ -74,6 +83,7 @@ describe("subagent result archives", () => {
|
||||
client.onChat.mockClear();
|
||||
client.onStatus.mockClear();
|
||||
chatHandlers.clear();
|
||||
statusHandlers.clear();
|
||||
vi.stubGlobal("fetch", vi.fn(async () => response([task()])));
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -231,6 +241,172 @@ describe("subagent result archives", () => {
|
||||
expect(screen.getByTestId("messages").querySelectorAll("[data-subagent-id]")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "loaded", threadMessages: [messages[0]], turnIds: ["turn-a"] },
|
||||
{ name: "empty", threadMessages: [], turnIds: [] },
|
||||
])("reads the $name history window while keeping active tasks available", async ({ threadMessages, turnIds }) => {
|
||||
const old: UIMessage = { id: "old", role: "user", content: "Earlier prompt", turnId: "old", createdAt: 99_000 };
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
return response([
|
||||
task({ task_id: "live", label: "Live", state: "running", completed_at: null, origin_message_id: "elsewhere", origin_turn_id: "elsewhere" }),
|
||||
...(url.searchParams.getAll("turn_id").includes("old")
|
||||
? [task({ task_id: "old", label: "Earlier check", origin_message_id: "old", origin_turn_id: "old" })] : []),
|
||||
]);
|
||||
});
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout({ threadMessages }));
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||
expect(seen[0].searchParams.get("scope")).toBe("window");
|
||||
expect(seen[0].searchParams.getAll("turn_id")).toEqual(turnIds);
|
||||
view.rerender(layout({ threadMessages: [old, messages[0]] }));
|
||||
const archive = await screen.findByRole("region", { name: "Subtasks" });
|
||||
await user.click(summary(archive));
|
||||
expect(within(archive).getByRole("button", { name: /Earlier check/ })).toBeVisible();
|
||||
expect(seen.some((url) => url.searchParams.getAll("turn_id").includes("old"))).toBe(true);
|
||||
expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
});
|
||||
|
||||
it("coalesces window changes and refreshes while reads are in flight, retaining the newest task revision", async () => {
|
||||
const first = messages[0];
|
||||
const second: UIMessage = { id: "second", role: "user", content: "Second prompt", turnId: "turn-second", createdAt: 1 };
|
||||
const seen: URL[] = [];
|
||||
let resolveFirst!: (response: Response) => void;
|
||||
let resolveSecond!: (response: Response) => void;
|
||||
const running = task({ state: "running", completed_at: null, origin_message_id: "elsewhere", origin_turn_id: "elsewhere" });
|
||||
vi.mocked(fetch).mockImplementation((input) => {
|
||||
seen.push(new URL(String(input), "http://localhost"));
|
||||
if (seen.length === 1) return new Promise<Response>((resolve) => { resolveFirst = resolve; });
|
||||
if (seen.length === 2) return new Promise<Response>((resolve) => { resolveSecond = resolve; });
|
||||
return Promise.resolve(response([task({ revision: 3, label: "Live revision 3", origin_message_id: "elsewhere", origin_turn_id: "elsewhere" })]));
|
||||
});
|
||||
const tree = (threadMessages: UIMessage[], active = true) => <StrictMode>{layout({ threadMessages, active })}</StrictMode>;
|
||||
const view = render(tree([first]));
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
view.rerender(tree([second]));
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(seen).toHaveLength(1);
|
||||
emitTask({ ...running, revision: 2, label: "Live revision 2" });
|
||||
await act(async () => resolveFirst(response([running])));
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
expect(seen[1].searchParams.getAll("turn_id")).toEqual(["turn-second"]);
|
||||
expect(seen[1].searchParams.getAll("track")).toEqual(["task-1"]);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByTestId("subagent-task-dock-trigger"));
|
||||
expect(screen.getByRole("button", { name: /Live revision 2 Running/ })).toBeVisible();
|
||||
view.rerender(tree([first]));
|
||||
await act(async () => resolveSecond(response([running])));
|
||||
// Focus invalidated the first page while its original read was in flight;
|
||||
// revisiting it must not treat that old response as fresh.
|
||||
await waitFor(() => expect(seen).toHaveLength(3));
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
expect(seen[2].searchParams.getAll("track")).toEqual(["task-1"]);
|
||||
expect(await screen.findByRole("button", { name: /Live revision 3 Completed/ })).toBeVisible();
|
||||
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||
await waitFor(() => expect(seen).toHaveLength(4));
|
||||
expect(seen[3].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
expect(seen[3].searchParams.getAll("track")).toEqual([]);
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(seen).toHaveLength(5));
|
||||
expect(seen[4].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
view.rerender(tree([first], false));
|
||||
view.rerender(tree([first]));
|
||||
await waitFor(() => expect(seen).toHaveLength(6));
|
||||
expect(seen[5].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
});
|
||||
|
||||
it("retries a failed history page when revisited without rereading a cached page", async () => {
|
||||
const first = messages[0];
|
||||
const second: UIMessage = { id: "second", role: "user", content: "Second prompt", turnId: "turn-second", createdAt: 1 };
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
if (seen.length === 2) return new Response("unavailable", { status: 503 });
|
||||
return response(url.searchParams.getAll("turn_id").includes("turn-second")
|
||||
? [task({ origin_message_id: "second", origin_turn_id: "turn-second", label: "Recovered result" })] : []);
|
||||
});
|
||||
const view = render(layout({ threadMessages: [first] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
view.rerender(layout({ threadMessages: [second] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
view.rerender(layout({ threadMessages: [first] }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(seen).toHaveLength(2);
|
||||
view.rerender(layout({ threadMessages: [second] }));
|
||||
const archive = await screen.findByRole("region", { name: "Subtasks" });
|
||||
await userEvent.setup().click(summary(archive));
|
||||
expect(within(archive).getByRole("button", { name: /Recovered result/ })).toBeVisible();
|
||||
expect(seen).toHaveLength(3);
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(["turn-second"]);
|
||||
});
|
||||
|
||||
it("revalidates a cached off-window page after reconnect misses a completed task", async () => {
|
||||
const first = messages[0];
|
||||
const second: UIMessage = { id: "second", role: "user", content: "Second prompt", turnId: "turn-second", createdAt: 1 };
|
||||
const seen: URL[] = [];
|
||||
let completedWhileOffline = false;
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
return response(completedWhileOffline && url.searchParams.getAll("turn_id").includes("turn-a")
|
||||
? [task({ origin_message_id: "prompt-a", label: "Completed while offline" })] : []);
|
||||
});
|
||||
const view = render(layout({ threadMessages: [first] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
view.rerender(layout({ threadMessages: [second] }));
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
completedWhileOffline = true;
|
||||
act(() => statusHandlers.forEach((handler) => handler("open")));
|
||||
await waitFor(() => expect(seen).toHaveLength(3));
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(["turn-second"]);
|
||||
view.rerender(layout({ threadMessages: [first] }));
|
||||
const archive = await screen.findByRole("region", { name: "Subtasks" });
|
||||
await userEvent.setup().click(summary(archive));
|
||||
expect(within(archive).getByRole("button", { name: /Completed while offline/ })).toBeVisible();
|
||||
expect(seen[3].searchParams.getAll("turn_id")).toEqual(["turn-a"]);
|
||||
});
|
||||
|
||||
it("does not let an old session's delayed scoped read contaminate the new session", async () => {
|
||||
let resolveOld!: (response: Response) => void;
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation((input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
if (url.pathname.includes("websocket%3Aa")) return new Promise<Response>((resolve) => { resolveOld = resolve; });
|
||||
return Promise.resolve(response([task({ task_id: "new", label: "New session", state: "running", completed_at: null })]));
|
||||
});
|
||||
const view = render(layout());
|
||||
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
|
||||
view.rerender(layout({ sessionKey: "websocket:b" }));
|
||||
const user = userEvent.setup();
|
||||
await user.click(await screen.findByTestId("subagent-task-dock-trigger"));
|
||||
expect(await screen.findByRole("button", { name: /New session Running/ })).toBeVisible();
|
||||
await act(async () => resolveOld(response([task({ label: "Old session", state: "running", completed_at: null })])));
|
||||
expect(screen.queryByRole("button", { name: /Old session/ })).not.toBeInTheDocument();
|
||||
expect(seen).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("reconciles a previously active off-window task after focus", async () => {
|
||||
const seen: URL[] = [];
|
||||
vi.mocked(fetch).mockImplementation(async (input) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
seen.push(url);
|
||||
return response(url.searchParams.getAll("track").includes("task-1")
|
||||
? [task({ revision: 2, origin_message_id: "other", origin_turn_id: "other" })]
|
||||
: [task({ state: "running", completed_at: null, origin_message_id: "other", origin_turn_id: "other" })]);
|
||||
});
|
||||
render(layout({ threadMessages: [messages[0]] }));
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
act(() => { window.dispatchEvent(new Event("focus")); });
|
||||
await waitFor(() => expect(seen.some((url) => url.searchParams.getAll("track").includes("task-1"))).toBe(true));
|
||||
await waitFor(() => expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1"));
|
||||
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows older results only with their loaded prompt and preserves details through history navigation", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt",
|
||||
|
||||
@@ -72,7 +72,8 @@ interface LayoutOptions {
|
||||
}
|
||||
function layout({ enabled = true, liveEvents = true, historyEnabled = false, sessionKey = "websocket:a", visible = true, active = true, inputKey = null, threadMessages = messages }: LayoutOptions = {}) {
|
||||
return <ThreadVisibilityContext.Provider value={visible}>
|
||||
<SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}>
|
||||
<SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}
|
||||
turnIds={[...new Set(threadMessages.flatMap(message => message.role === "user" && message.turnId ? [message.turnId] : []))]}>
|
||||
<div data-testid="messages"><SubagentThreadMessages messages={threadMessages} /></div>
|
||||
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock inputKey={inputKey ?? latestSubagentInputKey(threadMessages)} /><textarea aria-label="Message" /></div>
|
||||
</SubagentTasksProvider>
|
||||
@@ -117,7 +118,7 @@ describe("session-owned task UI", () => {
|
||||
const user = userEvent.setup();
|
||||
render(layout());
|
||||
const trigger = await screen.findByTestId("subagent-task-dock-trigger");
|
||||
expect(fetch).toHaveBeenCalledWith("/api/sessions/websocket%3Aa/subagents", expect.any(Object));
|
||||
expect(fetch).toHaveBeenCalledWith("/api/sessions/websocket%3Aa/subagents?scope=window&turn_id=turn-a", expect.any(Object));
|
||||
expect(screen.getAllByTestId("subagent-task-dock-trigger")).toEqual([trigger]);
|
||||
expect(screen.getByTestId("composer")).toContainElement(trigger);
|
||||
expect(trigger).toHaveTextContent("Running: 1");
|
||||
@@ -824,6 +825,7 @@ describe("session-owned task UI", () => {
|
||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
|
||||
vi.mocked(fetch).mockResolvedValue(response([task({ task_id: "task-b", label: "Other work" })]));
|
||||
view.rerender(layout({ sessionKey: "websocket:b" }));
|
||||
const list = await openTaskList(user);
|
||||
@@ -980,6 +982,7 @@ describe("session-owned task UI", () => {
|
||||
const list = await openTaskList(user);
|
||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(resolveOld).toBeTypeOf("function"));
|
||||
emitTask(task({ revision: 3, state: "cancelled", completed_at: 102 }));
|
||||
vi.mocked(fetch).mockImplementationOnce(async () => response([
|
||||
task({ revision: 2 }), task({ task_id: "task-2", label: "Recovered check", created_at: 101 }),
|
||||
|
||||
@@ -544,6 +544,81 @@ describe("ThreadShell", () => {
|
||||
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("queries only rendered task history as loaded pages and navigation windows change", async () => {
|
||||
const client = makeClient();
|
||||
const chatId = "task-window-pages";
|
||||
const rows = (prefix: string, count: number) => Array.from({ length: count }, (_, index) => ({
|
||||
id: `${prefix}${index}`, role: "user" as const, content: `${prefix} prompt ${index}`, turnId: `${prefix}t${index}`,
|
||||
}));
|
||||
let resolveInitial!: (response: Response) => void;
|
||||
const seen: URL[] = [];
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
if (url.pathname.endsWith("/subagents")) {
|
||||
seen.push(url);
|
||||
return Promise.resolve(httpJson({ tasks: [] }));
|
||||
}
|
||||
if (url.pathname.endsWith("/prompts")) return Promise.resolve(httpJson({ prompts: [{
|
||||
id: "nav2", preview: "nav prompt 2", answerPreview: "", createdAt: 1,
|
||||
cursor: "nav", turnId: "navt2",
|
||||
}] }));
|
||||
if (url.pathname.endsWith("/webui-thread")) {
|
||||
if (url.searchParams.get("before") === "older") return Promise.resolve(httpJson({
|
||||
...transcriptFromSimpleMessages(rows("old", 5)),
|
||||
page: { has_more_before: false, user_message_offset: 0 },
|
||||
}));
|
||||
if (url.searchParams.get("after") === "nav") return Promise.resolve(httpJson({
|
||||
...transcriptFromSimpleMessages(rows("nav", 3)),
|
||||
page: { has_more_before: false, has_more_after: true },
|
||||
}));
|
||||
return new Promise<Response>((resolve) => { resolveInitial = resolve; });
|
||||
}
|
||||
return Promise.resolve(new Response(null, { status: 404 }));
|
||||
}));
|
||||
const { container } = render(<StrictMode>{wrap(client, <ThreadShell session={session(chatId)} title="Task pages"
|
||||
onToggleSidebar={() => {}} />, null, "tok", ["webui.prompt-navigation.v1", "webui.subagents.v1", "webui.subagents.events.v1"])}</StrictMode>);
|
||||
await waitFor(() => expect(resolveInitial).toBeTypeOf("function"));
|
||||
expect(seen).toHaveLength(0);
|
||||
act(() => client._emitChat(chatId, { event: "subagent_task", chat_id: chatId, task: {
|
||||
task_id: "live-during-load", revision: 1, label: "Live during load", task_description: "Background work",
|
||||
origin_turn_id: "elsewhere", origin_message_id: null, created_at: 100, completed_at: null,
|
||||
state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1, tool_events: [],
|
||||
usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
|
||||
} }));
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
await act(async () => resolveInitial(httpJson({ ...transcriptFromSimpleMessages(rows("new", 5)),
|
||||
page: { before_cursor: "older", has_more_before: true, user_message_offset: 5 },
|
||||
})));
|
||||
await screen.findByText("new prompt 4");
|
||||
await waitFor(() => expect(seen).toHaveLength(1));
|
||||
expect(seen[0].searchParams.getAll("turn_id")).toEqual(rows("new", 5).map(row => row.turnId));
|
||||
expect(seen[0].searchParams.getAll("track")).toEqual(["live-during-load"]);
|
||||
|
||||
const scroller = container.querySelector(".thread-message-viewport") as HTMLElement;
|
||||
Object.defineProperties(scroller, {
|
||||
scrollHeight: { configurable: true, value: 2400 }, clientHeight: { configurable: true, value: 600 },
|
||||
scrollTop: { configurable: true, writable: true, value: 0 },
|
||||
});
|
||||
fireEvent.keyDown(scroller, { key: "Home" });
|
||||
await screen.findByText("old prompt 0");
|
||||
await waitFor(() => expect(seen).toHaveLength(2));
|
||||
expect(seen[1].searchParams.getAll("turn_id")).toEqual(rows("old", 5).map(row => row.turnId));
|
||||
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Message navigation" }));
|
||||
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Jump to message: nav prompt 2" }));
|
||||
await screen.findByText("nav prompt 2");
|
||||
await waitFor(() => expect(seen).toHaveLength(3));
|
||||
expect(seen[2].searchParams.getAll("turn_id")).toEqual(rows("nav", 3).map(row => row.turnId));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Scroll to bottom" }));
|
||||
await screen.findByText("new prompt 4");
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(seen).toHaveLength(3);
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(seen).toHaveLength(4));
|
||||
const latest = [...rows("old", 5), ...rows("new", 5)];
|
||||
expect(seen[3].searchParams.getAll("turn_id")).toEqual(latest.map(row => row.turnId));
|
||||
});
|
||||
|
||||
it("keeps the dock and task events alive after the parent response finishes", async () => {
|
||||
const client = makeClient();
|
||||
const snapshot: SubagentTaskSnapshot = {
|
||||
@@ -553,7 +628,7 @@ describe("ThreadShell", () => {
|
||||
usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
|
||||
};
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).endsWith("/subagents")) return httpJson({ tasks: [snapshot] });
|
||||
if (new URL(String(input), "http://localhost").pathname.endsWith("/subagents")) return httpJson({ tasks: [snapshot] });
|
||||
if (String(input).includes("/webui-thread")) return httpJson(transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "Delegate inspection", turnId: "parent-turn" },
|
||||
]));
|
||||
@@ -583,7 +658,7 @@ describe("ThreadShell", () => {
|
||||
it("renders one persisted task entry at the initiating prompt through the full shell", async () => {
|
||||
const client = makeClient();
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input).endsWith("/subagents")) return httpJson({ tasks: [{
|
||||
if (new URL(String(input), "http://localhost").pathname.endsWith("/subagents")) return httpJson({ tasks: [{
|
||||
task_id: "completed-task", label: "Inspect settings", task_description: "Inspect settings",
|
||||
origin_turn_id: "delegation-turn", origin_message_id: null, created_at: 100, completed_at: 102,
|
||||
state: "done", phase: "done", elapsed_seconds: 2, iteration: 1, tool_events: [],
|
||||
|
||||
Reference in new issue
Block a user