fix(webui): cache and defer thread history

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-12 17:09:51 +08:00
1 parent 7ba60c2ef0
commit a490cd629b
30 files changed
+1306 -145

No files matched your search

@@ -3136,6 +3136,116 @@ async def test_webui_thread_negotiates_gzip_for_large_payloads(
await server_task
@pytest.mark.asyncio
async def test_webui_thread_revalidates_and_loads_large_trace_details(
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:revalidated-thread"
sm = _seed_session(tmp_path, key=key)
trace = f'exec({json.dumps({"command": "x" * 40_000})})'
for event in (
{"event": "user", "chat_id": "revalidated-thread", "text": "run it"},
{
"event": "message",
"chat_id": "revalidated-thread",
"kind": "progress",
"text": trace,
},
{"event": "message", "chat_id": "revalidated-thread", "text": "done"},
{"event": "turn_end", "chat_id": "revalidated-thread"},
):
append_transcript_object(key, event)
port = _free_port()
channel = _ch(bus, session_manager=sm, workspace_path=tmp_path, port=port)
server_task = asyncio.create_task(channel.start())
try:
token = channel.gateway.tokens.issue_api_token(300)
url = (
f"http://127.0.0.1:{port}/api/sessions/"
"websocket%3Arevalidated-thread/webui-thread?limit=40&direction=latest"
)
auth = {"Authorization": f"Bearer {token}"}
first = await _http_get(url, headers=auth)
assert first.status_code == 200
assert first.headers["Cache-Control"] == "no-store"
assert first.headers["ETag"] == f'"{first.json()["revision"]}"'
trace_message = next(
message for message in first.json()["messages"] if message.get("kind") == "trace"
)
assert trace_message["content"] == "exec(…)"
unchanged = await _http_get(
url,
headers={**auth, "If-None-Match": first.headers["ETag"]},
)
assert unchanged.status_code == 304
assert unchanged.content == b""
detail = await _http_get(
f"http://127.0.0.1:{port}/api/sessions/"
"websocket%3Arevalidated-thread/webui-thread/trace-detail"
f"?ref={trace_message['traceDetail']['ref']}",
headers=auth,
)
assert detail.status_code == 200
assert detail.json()["content"] == trace
append_transcript_object(
key,
{"event": "user", "chat_id": "revalidated-thread", "text": "again"},
)
changed = await _http_get(
url,
headers={**auth, "If-None-Match": first.headers["ETag"]},
)
assert changed.status_code == 200
assert changed.headers["ETag"] != first.headers["ETag"]
finally:
await channel.stop()
await server_task
@pytest.mark.asyncio
async def test_webui_thread_omits_validator_when_transcript_changes_during_replay(
bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from nanobot.webui.transcript import append_transcript_object
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:changing-thread"
sm = _seed_session(tmp_path, key=key)
append_transcript_object(
key,
{"event": "user", "chat_id": "changing-thread", "text": "hello"},
)
revisions = iter(("before-replay", "after-replay"))
monkeypatch.setattr(
"nanobot.webui.ws_http.webui_transcript_revision",
lambda *_args, **_kwargs: next(revisions),
)
port = _free_port()
channel = _ch(bus, session_manager=sm, workspace_path=tmp_path, port=port)
server_task = asyncio.create_task(channel.start())
try:
token = channel.gateway.tokens.issue_api_token(300)
response = await _http_get(
f"http://127.0.0.1:{port}/api/sessions/"
"websocket%3Achanging-thread/webui-thread?limit=40&direction=latest",
headers={"Authorization": f"Bearer {token}"},
)
assert response.status_code == 200
assert "ETag" not in response.headers
assert "revision" not in response.json()
finally:
await channel.stop()
await server_task
@pytest.mark.asyncio
async def test_session_delete_rejects_non_websocket_keys(
bus: MagicMock, tmp_path: Path
+189 -3
View File
@@ -40,10 +40,18 @@ _DEFAULT_TRANSCRIPT_PAGE_LIMIT = 160
_MAX_TRANSCRIPT_PAGE_LIMIT = 1000
_MAX_TRANSCRIPT_PAGE_RECORDS = 4_000
_MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024
_MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024
_MAX_DEFERRED_TRACE_SUMMARY_ROWS = 16
_MAX_DEFERRED_TOOL_EVENT_SUMMARY_ROWS = 8
_MANIFEST_REBUILD_LOCKS = tuple(threading.Lock() for _ in range(32))
_ACTIVE_TRANSCRIPTS_WITH_DELTAS: set[str] = set()
_WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
_WEBUI_REPLAY_IDENTITY_KEY = "_webui_replay_identity"
_WEBUI_TRACE_DETAIL_REF_KEY = "_webui_trace_detail_ref"
_WEBUI_TRACE_DETAIL_UNSAFE_KEY = "_webui_trace_detail_unsafe"
_WEBUI_TRACE_DETAIL_REF_RE = re.compile(
r"^(?P<turn>\d{1,12})\.(?P<message>tr-[0-9a-f]{16}(?:-\d+)?)$"
)
_MARKDOWN_LOCAL_IMAGE_RE = re.compile(
r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)"
)
@@ -167,9 +175,58 @@ def _legacy_webui_thread_path(session_key: str) -> Path:
return get_webui_dir() / f"{stem}.json"
def webui_transcript_revision(
session_key: str,
*,
variant: Mapping[str, Any] | None = None,
) -> str | None:
"""Return a cheap revision from transcript artifact metadata and response inputs."""
active_path = webui_transcript_path(session_key)
segment_dir = webui_transcript_segments_dir(session_key)
snapshots: list[tuple[str, int, int]] = []
artifacts = (
("active", active_path),
("legacy", _legacy_webui_thread_path(session_key)),
("manifest", segment_dir / "manifest.json"),
("segments", segment_dir),
)
for label, path in artifacts:
try:
stat = path.stat()
except OSError:
continue
if label != "segments" and not path.is_file():
continue
snapshots.append((label, stat.st_size, stat.st_mtime_ns))
if not snapshots:
return None
digest = hashlib.sha256()
digest.update(
json.dumps(
snapshots,
ensure_ascii=False,
separators=(",", ":"),
).encode("utf-8")
)
if variant:
digest.update(b"\0")
digest.update(
json.dumps(
variant,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
default=str,
).encode("utf-8")
)
return digest.hexdigest()[:32]
class _TranscriptTurnRef(NamedTuple):
ordinal: int
records: list[dict[str, Any]]
trace_details_safe: bool = True
class _TranscriptChunkRef(NamedTuple):
@@ -353,11 +410,13 @@ def _records_with_replay_identity(
records: list[dict[str, Any]],
*,
turn_ordinal: int,
trace_details_safe: bool = True,
) -> list[dict[str, Any]]:
return [
{
**record,
_WEBUI_REPLAY_IDENTITY_KEY: f"turn:{turn_ordinal}:record:{record_index}",
**({_WEBUI_TRACE_DETAIL_UNSAFE_KEY: True} if not trace_details_safe else {}),
}
for record_index, record in enumerate(records)
]
@@ -807,6 +866,20 @@ def _chunk_turn_refs(
return refs
def _transcript_turn_at_ordinal(
session_key: str,
ordinal: int,
) -> list[dict[str, Any]] | None:
turn_cache: dict[str, list[list[dict[str, Any]]]] = {}
for chunk in _chunk_turn_refs(session_key, turn_cache):
local_index = ordinal - chunk.start_ordinal
if local_index < 0 or local_index >= chunk.turn_count:
continue
turns = _cached_chunk_turns(session_key, chunk.chunk_id, turn_cache)
return turns[local_index] if local_index < len(turns) else None
return None
def _count_user_messages_before_ordinal(
session_key: str,
chunks: list[_TranscriptChunkRef],
@@ -895,6 +968,7 @@ def _select_transcript_page(
local_upper = min(local_upper, len(turns))
for turn_index in range(local_upper - 1, -1, -1):
ordinal = chunk.start_ordinal + turn_index
trace_details_safe = True
turn, compacted_delta_records = _compact_completed_stream_deltas(
turns[turn_index]
)
@@ -921,7 +995,8 @@ def _select_transcript_page(
turn_record_count = len(turn)
turn_bytes = _records_bytes(turn)
stats.truncated_oversized_turn = True
selected.append(_TranscriptTurnRef(ordinal, turn))
trace_details_safe = False
selected.append(_TranscriptTurnRef(ordinal, turn, trace_details_safe))
selected_record_count += turn_record_count
selected_bytes += turn_bytes
replay_started = time.perf_counter()
@@ -939,6 +1014,7 @@ def _select_transcript_page(
for record in _records_with_replay_identity(
ref.records,
turn_ordinal=ref.ordinal,
trace_details_safe=ref.trace_details_safe,
)
]
stats.selected_records = len(lines)
@@ -2036,12 +2112,85 @@ def _media_from_signed_urls(value: Any) -> list[dict[str, Any]]:
return media
def _trace_detail_ref(message_id: str, record: Mapping[str, Any]) -> str | None:
if record.get(_WEBUI_TRACE_DETAIL_UNSAFE_KEY) is True:
return None
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY)
if not isinstance(identity, str):
return None
match = re.match(r"^turn:(\d+):record:", identity)
return f"{match.group(1)}.{message_id}" if match else None
def _truncate_utf8(value: str, max_bytes: int) -> str:
encoded = value.encode("utf-8")
if len(encoded) <= max_bytes:
return value
return encoded[: max_bytes - 3].decode("utf-8", errors="ignore") + "…"
def _trace_summary(line: str) -> str:
if len(line.encode("utf-8")) <= 512:
return line
match = re.match(r"^([A-Za-z0-9_.-]+)\(", line.strip())
return f"{_truncate_utf8(match.group(1), 240)}(…)" if match else _truncate_utf8(line, 240)
def _defer_large_trace_details(messages: list[dict[str, Any]]) -> None:
for message in messages:
if message.get("kind") != "trace":
continue
detail = {
key: message[key]
for key in ("content", "traces", "toolEvents")
if key in message
}
detail_bytes = len(_record_json_line(detail).encode("utf-8"))
detail_ref = message.get(_WEBUI_TRACE_DETAIL_REF_KEY)
if detail_bytes <= _MAX_INLINE_TRACE_DETAIL_BYTES:
continue
content = message.get("content")
traces = message.get("traces")
if isinstance(content, str):
message["content"] = _trace_summary(content)
if isinstance(traces, list):
message["traces"] = [
_trace_summary(trace)
for trace in cast(list[Any], traces)[-_MAX_DEFERRED_TRACE_SUMMARY_ROWS:]
if isinstance(trace, str)
]
events = message.get("toolEvents")
if isinstance(events, list):
summarized_events: list[dict[str, Any]] = []
for item in cast(list[Any], events)[-_MAX_DEFERRED_TOOL_EVENT_SUMMARY_ROWS:]:
if not isinstance(item, dict):
continue
event = cast(dict[str, Any], item)
summarized_events.append(
{
key: _truncate_utf8(value, 512)
for key in ("call_id", "name", "phase", "error")
if isinstance((value := event.get(key)), str)
}
)
message["toolEvents"] = summarized_events
trace_count = len(cast(list[Any], traces)) if isinstance(traces, list) else int(bool(content))
if isinstance(detail_ref, str):
message["traceDetail"] = {
"ref": detail_ref,
"bytes": detail_bytes,
"traceCount": trace_count,
}
def replay_transcript_to_ui_messages(
lines: list[dict[str, Any]],
*,
augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
augment_assistant_text: Callable[[str], str] | None = None,
defer_trace_details: bool = False,
) -> list[dict[str, Any]]:
"""Fold JSONL records into ``UIMessage``-shaped dicts for the WebUI.
@@ -2445,14 +2594,16 @@ def replay_transcript_to_ui_messages(
if not segment:
segment = _new_activity_segment(activate=False)
active_file_edit_segment_id = segment
message_id = _new_id("tr", idx)
messages.append(
{
"id": _new_id("tr", idx),
"id": message_id,
"role": "tool",
"kind": "trace",
"content": "",
"traces": [],
"fileEdits": [],
_WEBUI_TRACE_DETAIL_REF_KEY: _trace_detail_ref(message_id, lines[idx]),
"activitySegmentId": segment,
**turn_fields,
"createdAt": created_at_ms if created_at_ms is not None else _ts_base + idx,
@@ -2804,14 +2955,16 @@ def replay_transcript_to_ui_messages(
}
messages[-1] = merged
else:
message_id = _new_id("tr", idx)
messages.append(
{
"id": _new_id("tr", idx),
"id": message_id,
"role": "tool",
"kind": "trace",
"content": trace_lines[-1],
"traces": trace_lines,
**({"toolEvents": visible_structured_events} if visible_structured_events else {}),
_WEBUI_TRACE_DETAIL_REF_KEY: _trace_detail_ref(message_id, rec),
"activitySegmentId": segment,
**_turn_fields(rec, "activity"),
"createdAt": _created_at_ms(rec, idx),
@@ -2886,6 +3039,8 @@ def replay_transcript_to_ui_messages(
buffer_parts = []
continue
if defer_trace_details:
_defer_large_trace_details(messages)
for i, m in enumerate(messages):
if (
augment_assistant_text is not None
@@ -2894,8 +3049,10 @@ def replay_transcript_to_ui_messages(
and isinstance(m.get("content"), str)
):
messages[i] = {**m, "content": augment_assistant_text(m["content"])}
m = messages[i]
m.pop("isStreaming", None)
m.pop("reasoningStreaming", None)
m.pop(_WEBUI_TRACE_DETAIL_REF_KEY, None)
return messages
@@ -2990,6 +3147,34 @@ def completed_turn_ids(lines: list[dict[str, Any]]) -> list[str]:
return completed
def build_webui_trace_detail_response(
session_key: str,
detail_ref: str,
) -> dict[str, Any] | None:
"""Resolve one deferred trace from its stable turn ordinal and replay id."""
match = _WEBUI_TRACE_DETAIL_REF_RE.fullmatch(detail_ref)
if match is None:
return None
ordinal = int(match.group("turn"))
message_id = match.group("message")
turn = _transcript_turn_at_ordinal(session_key, ordinal)
if turn is None:
return None
lines = _records_with_replay_identity(turn, turn_ordinal=ordinal)
for message in replay_transcript_to_ui_messages(lines):
if message.get("id") != message_id or message.get("kind") != "trace":
continue
return {
"message_id": message_id,
**{
key: message[key]
for key in ("content", "traces", "toolEvents")
if key in message
},
}
return None
def build_webui_thread_response(
session_key: str,
*,
@@ -3038,6 +3223,7 @@ def build_webui_thread_response(
augment_user_media=augment_user_media,
augment_assistant_media=augment_assistant_media,
augment_assistant_text=augment_assistant_text,
defer_trace_details=True,
)
replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000)
payload: dict[str, Any] = {
+92 -1
View File
@@ -129,7 +129,12 @@ from nanobot.webui.skills_marketplace import (
trending_marketplace_skills,
)
from nanobot.webui.thread_disk import delete_webui_thread
from nanobot.webui.transcript import TranscriptReplayStats, build_webui_thread_response
from nanobot.webui.transcript import (
TranscriptReplayStats,
build_webui_thread_response,
build_webui_trace_detail_response,
webui_transcript_revision,
)
from nanobot.webui.workspaces import WebUIWorkspaceController
_SLOW_WEBUI_HTTP_LOG_MS = 1_000
@@ -138,6 +143,17 @@ _WEBUI_MUTATION_REQUEST_ATTR = "_nanobot_webui_mutation_request"
_NO_STORE_HEADERS = [("Cache-Control", "no-store")]
def _quoted_etag(revision: str) -> str:
return f'"{revision}"'
def _etag_matches(value: str, etag: str) -> bool:
return any(
candidate.strip().removeprefix("W/") in {"*", etag}
for candidate in value.split(",")
)
@dataclass(slots=True)
class _WebUIThreadDiagnostics:
transcript: TranscriptReplayStats = field(default_factory=TranscriptReplayStats)
@@ -717,6 +733,14 @@ class GatewayHTTPHandler:
# -- Session routes -----------------------------------------------------
async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None:
m = re.match(r"^/api/sessions/([^/]+)/webui-thread/trace-detail$", got)
if m:
return await asyncio.to_thread(
self._handle_webui_trace_detail_get,
request,
m.group(1),
)
m = re.match(r"^/api/sessions/([^/]+)/webui-thread$", got)
if m:
return await self._handle_webui_thread_get_async(request, m.group(1))
@@ -960,6 +984,37 @@ class GatewayHTTPHandler:
active_turn_transcript_persistence_failed = (
websocket_turn_transcript_persistence_failed(chat_id)
)
session_metadata = (
self.session_manager.read_session_metadata(decoded_key)
if self.session_manager is not None
else None
)
revision_variant = {
"active_turn_id": active_turn_id,
"active_turn_started_at": active_turn_started_at,
"active_turn_transcript_persistence_failed": (
active_turn_transcript_persistence_failed
),
"before": before,
"direction": direction,
"gateway_instance": self.tokens.instance_id,
"limit": limit,
"session_updated_at": (
session_metadata.get("updated_at") if session_metadata is not None else None
),
"workspace_scope": scope.payload(),
}
initial_revision = webui_transcript_revision(decoded_key, variant=revision_variant)
etag = _quoted_etag(initial_revision) if initial_revision is not None else None
if etag is not None and _etag_matches(
_case_insensitive_header(request.headers, "If-None-Match"),
etag,
):
return _http_response(
b"",
status=304,
extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)],
)
build_started = time.perf_counter()
data = build_webui_thread_response(
decoded_key,
@@ -985,12 +1040,48 @@ class GatewayHTTPHandler:
if data is None:
return _http_error(404, "webui thread not found")
data["workspace_scope"] = scope.payload()
latest_session_metadata = (
self.session_manager.read_session_metadata(decoded_key)
if self.session_manager is not None
else None
)
revision_variant["session_updated_at"] = (
latest_session_metadata.get("updated_at")
if latest_session_metadata is not None
else None
)
final_revision = webui_transcript_revision(decoded_key, variant=revision_variant)
response_headers = list(_NO_STORE_HEADERS)
if final_revision is not None and final_revision == initial_revision:
data["revision"] = final_revision
response_headers.append(("ETag", _quoted_etag(final_revision)))
return _http_json_response(
data,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=response_headers,
metrics=diagnostics.response if diagnostics is not None else None,
)
def _handle_webui_trace_detail_get(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
decoded_key = _decode_api_key(key)
if decoded_key is None:
return _http_error(400, "invalid session key")
if not _is_websocket_channel_session_key(decoded_key):
return _http_error(404, "session not found")
detail_ref = _query_first(_parse_query(request.path), "ref")
if not detail_ref:
return _http_error(400, "missing trace detail ref")
data = build_webui_trace_detail_response(decoded_key, detail_ref)
if data is None:
return _http_error(404, "trace detail not found")
return _http_json_response(
data,
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=_NO_STORE_HEADERS,
)
def _handle_file_preview(self, request: WsRequest, key: str) -> Response:
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
+185
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Event, Lock
@@ -16,9 +17,11 @@ from nanobot.webui.transcript import (
append_fork_marker,
append_transcript_object,
build_webui_thread_response,
build_webui_trace_detail_response,
fork_transcript_before_user_index,
read_transcript_lines,
replay_transcript_to_ui_messages,
webui_transcript_revision,
webui_transcript_segments_dir,
write_session_messages_as_transcript,
)
@@ -146,6 +149,136 @@ def test_missing_page_query_uses_bounded_default(tmp_path, monkeypatch) -> None:
assert latest["page"]["loaded_message_count"] == 4
def test_large_trace_details_are_deferred_and_resolved(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:deferred-trace"
trace = f'exec({json.dumps({"command": "x" * 40_000})})'
for event in (
{"event": "user", "chat_id": "deferred-trace", "text": "run it"},
{
"event": "message",
"chat_id": "deferred-trace",
"kind": "progress",
"text": trace,
},
{"event": "message", "chat_id": "deferred-trace", "text": "done"},
{"event": "turn_end", "chat_id": "deferred-trace"},
):
append_transcript_object(key, event)
payload = build_webui_thread_response(key, limit=40, direction="latest")
assert payload is not None
trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")
assert trace_message["content"] == "exec(…)"
assert trace_message["traces"] == ["exec(…)"]
assert trace_message["traceDetail"]["bytes"] > 32 * 1024
assert len(json.dumps(payload)) < len(trace)
detail = build_webui_trace_detail_response(key, trace_message["traceDetail"]["ref"])
assert detail == {
"message_id": trace_message["id"],
"content": trace,
"traces": [trace],
}
def test_large_structured_trace_error_is_bounded_and_resolved(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:deferred-trace-error"
full_error = "failure: " + "界" * 40_000
for event in (
{"event": "user", "chat_id": "deferred-trace-error", "text": "run it"},
{
"event": "message",
"chat_id": "deferred-trace-error",
"kind": "progress",
"text": 'exec({"command":"false"})',
"tool_events": [
{
"phase": "error",
"call_id": "call-exec",
"name": "exec",
"error": full_error,
}
],
},
{"event": "message", "chat_id": "deferred-trace-error", "text": "done"},
{"event": "turn_end", "chat_id": "deferred-trace-error"},
):
append_transcript_object(key, event)
payload = build_webui_thread_response(key, limit=40, direction="latest")
assert payload is not None
trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")
assert len(json.dumps(trace_message).encode("utf-8")) < 4_096
assert len(trace_message["toolEvents"][0]["error"].encode("utf-8")) <= 512
detail = build_webui_trace_detail_response(key, trace_message["traceDetail"]["ref"])
assert detail is not None
assert detail["toolEvents"][0]["error"] == full_error
def test_many_short_trace_rows_are_bounded_and_resolved(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:deferred-many-traces"
trace_count = 2_000
append_transcript_object(
key,
{"event": "user", "chat_id": "deferred-many-traces", "text": "run many tools"},
)
for index in range(trace_count):
append_transcript_object(
key,
{
"event": "message",
"chat_id": "deferred-many-traces",
"kind": "progress",
"text": f"tool_{index}(value)",
},
)
append_transcript_object(
key,
{"event": "message", "chat_id": "deferred-many-traces", "text": "done"},
)
append_transcript_object(key, {"event": "turn_end", "chat_id": "deferred-many-traces"})
payload = build_webui_thread_response(key, limit=40, direction="latest")
assert payload is not None
trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")
assert trace_message["traceDetail"]["traceCount"] == trace_count
assert len(trace_message["traces"]) <= 16
assert len(json.dumps(trace_message).encode("utf-8")) < 4_096
detail = build_webui_trace_detail_response(key, trace_message["traceDetail"]["ref"])
assert detail is not None
assert len(detail["traces"]) == trace_count
assert detail["traces"][0] == "tool_0(value)"
assert detail["traces"][-1] == f"tool_{trace_count - 1}(value)"
def test_transcript_revision_tracks_artifacts_and_variants(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:revision"
append_transcript_object(key, {"event": "user", "chat_id": "revision", "text": "one"})
first = webui_transcript_revision(key, variant={"limit": 40})
same = webui_transcript_revision(key, variant={"limit": 40})
other_variant = webui_transcript_revision(key, variant={"limit": 80})
append_transcript_object(key, {"event": "message", "chat_id": "revision", "text": "two"})
changed = webui_transcript_revision(key, variant={"limit": 40})
assert first is not None
assert same == first
assert other_variant != first
assert changed != first
def test_single_oversized_turn_is_bounded_and_marked(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_PAGE_RECORDS", 5)
@@ -185,6 +318,58 @@ def test_single_oversized_turn_is_bounded_and_marked(tmp_path, monkeypatch) -> N
assert latest["messages"][-1]["content"] == "final answer"
def test_truncated_turn_does_not_advertise_ambiguous_trace_detail(
tmp_path,
monkeypatch,
) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_PAGE_RECORDS", 6)
monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_PAGE_BYTES", 1_000_000)
key = "websocket:truncated-trace-detail"
append_transcript_object(
key,
{"event": "user", "chat_id": "truncated-trace-detail", "text": "question"},
)
for prefix in ("first", "second"):
for idx in range(4):
append_transcript_object(
key,
{
"event": "message",
"chat_id": "truncated-trace-detail",
"kind": "progress",
"text": f"{prefix}_{idx}({('x' * 12_000)})",
},
)
if prefix == "first":
append_transcript_object(
key,
{
"event": "message",
"chat_id": "truncated-trace-detail",
"text": "intermediate",
},
)
append_transcript_object(
key,
{"event": "message", "chat_id": "truncated-trace-detail", "text": "done"},
)
append_transcript_object(
key,
{"event": "turn_end", "chat_id": "truncated-trace-detail"},
)
payload = build_webui_thread_response(key, limit=40, direction="latest")
assert payload is not None
assert payload["page"]["truncated_oversized_turn"] is True
trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")
assert trace_message["content"] == "second_3(…)"
assert all(trace.startswith("second_") for trace in trace_message["traces"])
assert "traceDetail" not in trace_message
assert len(json.dumps(trace_message).encode("utf-8")) < 4_096
def test_latest_page_reads_active_chunk_once(tmp_path, monkeypatch) -> None:
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:single-active-read"
@@ -127,6 +127,10 @@ function countActivity(
continue;
}
if (m.kind === "trace") {
if (m.traceDetail) {
toolCalls += m.traceDetail.traceCount;
continue;
}
const lines = traceLines(m);
for (const line of lines) {
if (!isCliRunTraceLine(line) && !isMcpRunTraceLine(line)) {
@@ -157,6 +161,8 @@ interface AgentActivityClusterProps {
retryStatus?: RetryStatus | null;
cliApps?: CliAppInfo[];
mcpPresets?: McpPresetInfo[];
traceDetailScope?: string | null;
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
onOpenFilePreview?: (path: string) => void;
}
@@ -228,6 +234,8 @@ function FoldedAgentActivity({
retryStatus = null,
cliApps = EMPTY_CLI_APPS,
mcpPresets = EMPTY_MCP_PRESETS,
traceDetailScope = null,
onLoadTraceDetails,
onOpenFilePreview,
}: AgentActivityClusterProps) {
const { t } = useTranslation();
@@ -265,6 +273,7 @@ function FoldedAgentActivity({
const [userToggledOuter, setUserToggledOuter] = useState(false);
const [outerOpenLocal, setOuterOpenLocal] = useState(false);
const [completionHoldOpen, setCompletionHoldOpen] = useState(false);
const [failedTraceDetailKey, setFailedTraceDetailKey] = useState<string | null>(null);
const [now, setNow] = useState(() => Date.now());
const [activityScrollFade, setActivityScrollFade] = useState({ top: false, bottom: false });
const activityScrollRef = useRef<HTMLDivElement>(null);
@@ -277,6 +286,28 @@ function FoldedAgentActivity({
const outerExpanded = userToggledOuter
? outerOpenLocal
: isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming);
const deferredTraceRefs = useMemo(
() => Array.from(new Set(
messages
.map((message) => message.traceDetail?.ref)
.filter((ref): ref is string => typeof ref === "string" && ref.length > 0),
)),
[messages],
);
const traceDetailKey = useMemo(
() => `${traceDetailScope ?? ""}\u0000${deferredTraceRefs.join("\u0000")}`,
[deferredTraceRefs, traceDetailScope],
);
const traceDetailLoadFailed = failedTraceDetailKey === traceDetailKey;
const requestTraceDetails = useCallback(async (refs: string[]) => {
if (!onLoadTraceDetails) return;
setFailedTraceDetailKey(null);
try {
await onLoadTraceDetails(refs);
} catch {
setFailedTraceDetailKey(`${traceDetailScope ?? ""}\u0000${refs.join("\u0000")}`);
}
}, [onLoadTraceDetails, traceDetailScope]);
const hasVisibleActivity = reasoningSteps > 0 || toolCalls > 0 || modelSegments > 0 || cliCount > 0 || mcpCount > 0 || fileCount > 0;
const hasOnlyFileActivity = fileCount > 0 && activityMessages.every(messageHasOnlyFileActivity);
@@ -397,6 +428,12 @@ function FoldedAgentActivity({
useEffect(() => cancelActivityScrollFrame, [cancelActivityScrollFrame]);
useEffect(() => {
if (outerExpanded && deferredTraceRefs.length > 0) {
void requestTraceDetails(deferredTraceRefs);
}
}, [deferredTraceRefs, outerExpanded, requestTraceDetails]);
useEffect(() => {
if (!isTurnStreaming || !pageVisible || !threadVisible) return undefined;
setNow(Date.now());
@@ -453,6 +490,18 @@ function FoldedAgentActivity({
onToggle={toggleOuter}
onScroll={onActivityScroll}
>
{traceDetailLoadFailed ? (
<div role="alert" className="flex items-center gap-2 py-1 text-[12px] text-destructive">
<span>{t("message.traceDetailsLoadFailed", { defaultValue: "Full activity details could not be loaded." })}</span>
<button
type="button"
className="shrink-0 rounded-sm font-medium underline underline-offset-2 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => void requestTraceDetails(deferredTraceRefs)}
>
{t("message.retryTraceDetails", { defaultValue: "Retry" })}
</button>
</div>
) : null}
<ActivityMessageTimeline
messages={activityMessages}
active={isTurnStreaming}
@@ -20,6 +20,8 @@ interface ThreadMessagesProps {
mcpPresets?: McpPresetInfo[];
slashCommands?: SlashCommand[];
forkBoundaryMessageCount?: number | null;
traceDetailScope?: string | null;
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
onOpenFilePreview?: (path: string) => void;
onForkFromMessage?: (beforeUserIndex: number) => void;
onQuoteSelection?: (text: string) => void;
@@ -70,6 +72,8 @@ export function ThreadMessages({
mcpPresets = [],
slashCommands = [],
forkBoundaryMessageCount = null,
traceDetailScope = null,
onLoadTraceDetails,
onOpenFilePreview,
onForkFromMessage,
onQuoteSelection,
@@ -175,6 +179,8 @@ export function ThreadMessages({
cliApps={cliApps}
mcpPresets={mcpPresets}
slashCommands={slashCommands}
traceDetailScope={traceDetailScope}
onLoadTraceDetails={onLoadTraceDetails}
onOpenFilePreview={onOpenFilePreview}
onForkFromMessage={onForkFromMessage}
/>
@@ -258,6 +264,8 @@ interface ThreadDisplayUnitProps {
cliApps: CliAppInfo[];
mcpPresets: McpPresetInfo[];
slashCommands: SlashCommand[];
traceDetailScope: string | null;
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
onOpenFilePreview?: (path: string) => void;
onForkFromMessage?: (beforeUserIndex: number) => void;
}
@@ -278,6 +286,8 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
cliApps,
mcpPresets,
slashCommands,
traceDetailScope,
onLoadTraceDetails,
onOpenFilePreview,
onForkFromMessage,
}: ThreadDisplayUnitProps) {
@@ -325,6 +335,8 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
startedAtMs={unit.startedAtMs}
cliApps={cliApps}
mcpPresets={mcpPresets}
traceDetailScope={traceDetailScope}
onLoadTraceDetails={onLoadTraceDetails}
onOpenFilePreview={onOpenFilePreview}
/>
) : (
@@ -364,6 +376,8 @@ function threadDisplayUnitPropsEqual(
&& previous.cliApps === next.cliApps
&& previous.mcpPresets === next.mcpPresets
&& previous.slashCommands === next.slashCommands
&& previous.traceDetailScope === next.traceDetailScope
&& previous.onLoadTraceDetails === next.onLoadTraceDetails
&& previous.onOpenFilePreview === next.onOpenFilePreview
&& previous.onForkFromMessage === next.onForkFromMessage
);
@@ -26,6 +26,7 @@ import {
fetchInstalledCliApps,
fetchMcpPresets,
fetchSettings,
fetchWebuiThreadTraceDetail,
listSlashCommands,
} from "@/lib/api";
import {
@@ -806,6 +807,9 @@ export function ThreadShell({
const completedCanonicalHydrateVersionRef = useRef<Map<string, number>>(new Map());
const committedHistoryLineageRef = useRef<Map<string, number>>(new Map());
const sessionKeyByChatIdRef = useRef<Map<string, string>>(new Map());
const traceDetailRequestsRef = useRef<Map<string, Promise<void>>>(new Map());
const activeHistoryKeyRef = useRef(historyKey);
activeHistoryKeyRef.current = historyKey;
const currentUiMessagesRef = useRef<UIMessage[] | null>(null);
const uiRevisionRef = useRef(0);
const showTemporaryChatControl =
@@ -840,6 +844,49 @@ export function ThreadShell({
dismissStreamError,
} = useNanobotStream(chatId, initial, hasPendingToolCalls, handleTurnEnd);
const loadTraceDetails = useCallback(async (refs: string[]) => {
const requestKey = historyKey;
if (!requestKey) return;
const requests: Promise<void>[] = [];
for (const ref of refs) {
const requestId = `${requestKey}:${ref}`;
const existing = traceDetailRequestsRef.current.get(requestId);
if (existing) {
requests.push(existing);
continue;
}
const request = fetchWebuiThreadTraceDetail(getToken(), requestKey, ref)
.then((detail) => {
if (activeHistoryKeyRef.current !== requestKey) return;
setMessages((current) => current.map((message) => (
message.traceDetail?.ref === ref
? {
...message,
content: detail.content,
traces: detail.traces,
toolEvents: detail.toolEvents,
traceDetail: undefined,
}
: message
)));
})
.catch((error: unknown) => {
if (activeHistoryKeyRef.current !== requestKey) return;
throw error;
})
.finally(() => {
traceDetailRequestsRef.current.delete(requestId);
});
traceDetailRequestsRef.current.set(requestId, request);
requests.push(request);
}
await Promise.all(requests);
}, [getToken, historyKey, setMessages]);
useEffect(() => () => {
activeHistoryKeyRef.current = null;
}, []);
useLayoutEffect(() => {
if (currentUiMessagesRef.current === messages) return;
currentUiMessagesRef.current = messages;
@@ -1748,6 +1795,8 @@ export function ThreadShell({
loadingOlder={loadingOlder}
userMessageOffset={userMessageOffset}
onLoadOlder={loadOlder}
traceDetailScope={historyKey}
onLoadTraceDetails={messagesReady ? loadTraceDetails : undefined}
onOpenFilePreview={historyKey ? handleOpenFilePreview : undefined}
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
onQuoteSelection={session ? handleQuoteSelection : undefined}
@@ -56,6 +56,8 @@ interface ThreadViewportProps {
loadingOlder?: boolean;
userMessageOffset?: number;
onLoadOlder?: () => Promise<void> | void;
traceDetailScope?: string | null;
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
onOpenFilePreview?: (path: string) => void;
onForkFromMessage?: (beforeUserIndex: number) => void;
onQuoteSelection?: (text: string) => void;
@@ -71,7 +73,7 @@ const SOFT_KEYBOARD_MIN_INSET_PX = 80;
const SESSION_HANDOFF_EXIT_DURATION_MS = 80;
const SESSION_HANDOFF_ENTER_DURATION_MS = 140;
const SESSION_HANDOFF_OPACITY = 0.82;
export const INITIAL_HISTORY_WINDOW = 160;
export const INITIAL_HISTORY_WINDOW = 120;
export const HISTORY_WINDOW_INCREMENT = 120;
interface HistoryScrollAnchor {
@@ -239,6 +241,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
loadingOlder = false,
userMessageOffset = 0,
onLoadOlder,
traceDetailScope = null,
onLoadTraceDetails,
onOpenFilePreview,
onForkFromMessage,
onQuoteSelection,
@@ -886,6 +890,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
mcpPresets={mcpPresets}
slashCommands={slashCommands}
forkBoundaryMessageCount={visibleForkBoundaryMessageCount}
traceDetailScope={traceDetailScope}
onLoadTraceDetails={onLoadTraceDetails}
onOpenFilePreview={onOpenFilePreview}
onForkFromMessage={onForkFromMessage}
onQuoteSelection={onQuoteSelection}
+100 -85
View File
@@ -11,16 +11,18 @@ import {
} from "@/lib/api";
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
import { deriveTitle } from "@/lib/format";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import type {
ChatSummary,
SessionAutomationJob,
SessionDeleteResult,
UIMessage,
WebuiThreadPersistedPayload,
WorkspaceScopePayload,
} from "@/lib/types";
const EMPTY_MESSAGES: UIMessage[] = [];
const INITIAL_HISTORY_PAGE_LIMIT = 80;
const INITIAL_HISTORY_PAGE_LIMIT = 40;
const OLDER_HISTORY_PAGE_LIMIT = 120;
const CHAT_CREATE_TIMEOUT_MS = 60_000;
@@ -121,6 +123,71 @@ function completedTurnIdsFromThread(
));
}
interface SessionHistoryState {
key: string | null;
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
forkBoundaryMessageCount: number | null;
beforeCursor: string | null;
hasMoreBefore: boolean;
userMessageOffset: number;
version: number;
continuity: SessionHistoryContinuity;
lineage: number;
activeTurnId: string | null;
}
function emptyHistoryState(key: string | null, loading = false): SessionHistoryState {
return {
key,
messages: [],
loading,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
};
}
function cachedHistoryState(
key: string,
body: WebuiThreadPersistedPayload,
version: number,
): SessionHistoryState {
const messages = persistedMessagesToUi(body.messages ?? []);
return {
key,
messages,
loading: false,
loadingOlder: false,
error: null,
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
completedTurnIds: completedTurnIdsFromThread(body),
forkBoundaryMessageCount: typeof body.fork_boundary_message_count === "number"
? Math.max(0, Math.min(body.fork_boundary_message_count, messages.length))
: null,
beforeCursor: body.page?.before_cursor ?? null,
hasMoreBefore: body.page?.has_more_before === true,
userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0),
version,
continuity: "initial",
lineage: version,
activeTurnId: typeof body.active_turn_id === "string" ? body.active_turn_id : null,
};
}
/** Sidebar state: fetches the full session list and exposes create / delete actions. */
export function useSessions(): {
sessions: ChatSummary[];
@@ -273,6 +340,7 @@ export function useSessions(): {
const result = await apiDeleteSession(client, key, options);
if (result.blocked_by_automations || (!result.deleted && !optimistic)) return result;
optimisticKeysRef.current.delete(key);
webuiThreadCache.delete(key);
setSessions((prev) => prev.filter((s) => s.key !== key));
// The gateway may have restarted and forgotten an unpersisted chat's
// draft scope, but removing that optimistic session is still a deletion.
@@ -329,38 +397,12 @@ export function useSessionHistory(key: string | null): {
const refresh = useCallback(() => {
setRefreshSeq((value) => value + 1);
}, []);
const [state, setState] = useState<{
key: string | null;
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
forkBoundaryMessageCount: number | null;
beforeCursor: string | null;
hasMoreBefore: boolean;
userMessageOffset: number;
version: number;
continuity: SessionHistoryContinuity;
lineage: number;
activeTurnId: string | null;
}>({
key: null,
messages: [],
loading: false,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
const [state, setState] = useState<SessionHistoryState>(() => {
if (!key) return emptyHistoryState(null);
const cached = webuiThreadCache.get(key);
if (!cached) return emptyHistoryState(key, true);
historyVersionRef.current = 1;
return cachedHistoryState(key, cached, historyVersionRef.current);
});
useEffect(() => () => {
@@ -374,23 +416,7 @@ export function useSessionHistory(key: string | null): {
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
setState({
key: null,
messages: [],
loading: false,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
});
setState(emptyHistoryState(null));
return;
}
let cancelled = false;
@@ -398,35 +424,37 @@ export function useSessionHistory(key: string | null): {
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
// Mark the new key as loading immediately so callers never see stale
// messages from the previous session during the render right after a switch.
const cachedBody = webuiThreadCache.get(key);
const cachedVersion = cachedBody ? historyVersionRef.current + 1 : 0;
if (cachedBody) historyVersionRef.current = cachedVersion;
setState((prev) => prev.key === key
? { ...prev, loading: true, loadingOlder: false, error: null }
: {
key,
messages: [],
loading: true,
? {
...prev,
loading: cachedBody ? false : prev.messages.length === 0 && prev.lineage === 0,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
});
}
: cachedBody
? cachedHistoryState(key, cachedBody, cachedVersion)
: emptyHistoryState(key, true));
(async () => {
try {
const body = await fetchWebuiThread(getToken(), key, {
limit: INITIAL_HISTORY_PAGE_LIMIT,
direction: "latest",
signal: controller.signal,
revision: cachedBody?.revision,
cached: cachedBody,
});
if (cancelled) return;
if (body === cachedBody && cachedBody !== undefined) {
setState((prev) => prev.key === key
? { ...prev, loading: false, error: null }
: prev);
return;
}
if (body) webuiThreadCache.set(key, body);
else webuiThreadCache.delete(key);
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
const completedTurnIds = completedTurnIdsFromThread(body);
@@ -480,6 +508,7 @@ export function useSessionHistory(key: string | null): {
} catch (e) {
if (cancelled || isAbortError(e)) return;
if (e instanceof ApiError && e.status === 404) {
webuiThreadCache.delete(key);
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
setState((prev) => {
@@ -505,23 +534,9 @@ export function useSessionHistory(key: string | null): {
};
});
} else {
setState((prev) => ({
key,
messages: [],
loading: false,
loadingOlder: false,
error: (e as Error).message,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: prev.key === key ? prev.version : 0,
continuity: prev.key === key ? prev.continuity : "initial",
lineage: prev.key === key ? prev.lineage : 0,
activeTurnId: prev.key === key ? prev.activeTurnId : null,
}));
setState((prev) => prev.key === key && prev.messages.length > 0
? { ...prev, loading: false, error: (e as Error).message }
: { ...emptyHistoryState(key), error: (e as Error).message });
}
}
})();
+2
View File
@@ -1750,6 +1750,8 @@
"activityWorkingFor": "Working for {{duration}}",
"activityWorked": "Worked",
"activityWorkedFor": "Worked for {{duration}}",
"traceDetailsLoadFailed": "Full activity details could not be loaded.",
"retryTraceDetails": "Retry",
"retryConnection": "Connection failed",
"retryTimeout": "Model timed out",
"retryRateLimit": "Rate limited",
+2
View File
@@ -1578,6 +1578,8 @@
"activityWorkingFor": "Trabajando durante {{duration}}",
"activityWorked": "Trabajo completado",
"activityWorkedFor": "Trabajó durante {{duration}}",
"traceDetailsLoadFailed": "No se pudieron cargar los detalles completos de la actividad.",
"retryTraceDetails": "Reintentar",
"retryConnection": "Error de conexión",
"retryTimeout": "Se agotó el tiempo de espera del modelo",
"retryRateLimit": "Límite de solicitudes alcanzado",
+2
View File
@@ -1577,6 +1577,8 @@
"activityWorkingFor": "Travail en cours depuis {{duration}}",
"activityWorked": "Travail terminé",
"activityWorkedFor": "Travail terminé en {{duration}}",
"traceDetailsLoadFailed": "Impossible de charger les détails complets de l’activité.",
"retryTraceDetails": "Réessayer",
"retryConnection": "Échec de la connexion",
"retryTimeout": "Délai d’attente du modèle dépassé",
"retryRateLimit": "Limite de requêtes atteinte",
+2
View File
@@ -1577,6 +1577,8 @@
"activityWorkingFor": "Memproses selama {{duration}}",
"activityWorked": "Selesai memproses",
"activityWorkedFor": "Diproses selama {{duration}}",
"traceDetailsLoadFailed": "Detail aktivitas lengkap tidak dapat dimuat.",
"retryTraceDetails": "Coba lagi",
"retryConnection": "Koneksi gagal",
"retryTimeout": "Waktu respons model habis",
"retryRateLimit": "Batas permintaan tercapai",
+2
View File
@@ -1577,6 +1577,8 @@
"activityWorkingFor": "{{duration}}作業中",
"activityWorked": "作業しました",
"activityWorkedFor": "{{duration}}作業しました",
"traceDetailsLoadFailed": "アクティビティの詳細を読み込めませんでした。",
"retryTraceDetails": "再試行",
"retryConnection": "接続に失敗しました",
"retryTimeout": "モデルがタイムアウトしました",
"retryRateLimit": "リクエスト制限に達しました",
+2
View File
@@ -1577,6 +1577,8 @@
"activityWorkingFor": "{{duration}} 동안 작업 중",
"activityWorked": "작업함",
"activityWorkedFor": "{{duration}} 동안 작업함",
"traceDetailsLoadFailed": "전체 활동 세부 정보를 불러올 수 없습니다.",
"retryTraceDetails": "다시 시도",
"retryConnection": "연결 실패",
"retryTimeout": "모델 응답 시간 초과",
"retryRateLimit": "요청 한도 초과",
+2
View File
@@ -1564,6 +1564,8 @@
"activityWorkingFor": "Trabalhando por {{duration}}",
"activityWorked": "Trabalhou",
"activityWorkedFor": "Trabalhou por {{duration}}",
"traceDetailsLoadFailed": "Não foi possível carregar os detalhes completos da atividade.",
"retryTraceDetails": "Tentar novamente",
"retryConnection": "Falha na conexão",
"retryTimeout": "O modelo excedeu o tempo limite",
"retryRateLimit": "Limite de solicitações atingido",
+2
View File
@@ -1577,6 +1577,8 @@
"activityWorkingFor": "Đang xử lý trong {{duration}}",
"activityWorked": "Đã xử lý",
"activityWorkedFor": "Đã xử lý trong {{duration}}",
"traceDetailsLoadFailed": "Không thể tải đầy đủ chi tiết hoạt động.",
"retryTraceDetails": "Thử lại",
"retryConnection": "Kết nối thất bại",
"retryTimeout": "Mô hình đã hết thời gian chờ",
"retryRateLimit": "Đã đạt giới hạn yêu cầu",
+2
View File
@@ -1750,6 +1750,8 @@
"activityWorkingFor": "处理中 {{duration}}",
"activityWorked": "已处理",
"activityWorkedFor": "处理了 {{duration}}",
"traceDetailsLoadFailed": "无法加载完整活动详情。",
"retryTraceDetails": "重试",
"retryConnection": "连接失败",
"retryTimeout": "模型响应超时",
"retryRateLimit": "请求频率受限",
+2
View File
@@ -1576,6 +1576,8 @@
"activityWorkingFor": "處理中,已 {{duration}}",
"activityWorked": "已處理",
"activityWorkedFor": "已處理 {{duration}}",
"traceDetailsLoadFailed": "無法載入完整活動詳情。",
"retryTraceDetails": "重試",
"retryConnection": "連線失敗",
"retryTimeout": "模型回應逾時",
"retryRateLimit": "請求頻率受限",
+24 -1
View File
@@ -41,6 +41,7 @@ import type {
WebSearchSettingsUpdate,
WorkspacesPayload,
WebuiThreadPersistedPayload,
WebuiThreadTraceDetailPayload,
WorkspaceScopePayload,
} from "./types";
import { fetchWithTimeout } from "./http";
@@ -226,6 +227,8 @@ export interface FetchWebuiThreadOptions {
direction?: "latest";
before?: string | null;
signal?: AbortSignal;
revision?: string;
cached?: WebuiThreadPersistedPayload;
}
export async function fetchWebuiThread(
@@ -243,17 +246,37 @@ export async function fetchWebuiThread(
const query = params.toString();
const suffix = query ? `?${query}` : "";
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
if (options?.revision) headers["If-None-Match"] = `"${options.revision}"`;
const res = await fetchWithTimeout(url, {
headers: { Authorization: `Bearer ${token}` },
headers,
credentials: "same-origin",
cache: "no-store",
signal: options?.signal,
});
if (res.status === 304 && options?.cached) return options.cached;
if (res.status === 404) return null;
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
return (await res.json()) as WebuiThreadPersistedPayload;
}
export async function fetchWebuiThreadTraceDetail(
token: string,
key: string,
ref: string,
base: string = "",
): Promise<WebuiThreadTraceDetailPayload> {
const query = new URLSearchParams({ ref });
const url = `${base}/api/sessions/${encodeURIComponent(key)}/webui-thread/trace-detail?${query}`;
const res = await fetchWithTimeout(url, {
headers: { Authorization: `Bearer ${token}` },
credentials: "same-origin",
cache: "no-store",
});
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
return (await res.json()) as WebuiThreadTraceDetailPayload;
}
export async function fetchFilePreview(
token: string,
key: string,
+56
View File
@@ -0,0 +1,56 @@
/** Byte- and entry-bounded in-memory LRU for JSON-shaped WebUI state. */
export class MemoryLruCache<T> {
private entries = new Map<string, { value: T; bytes: number }>();
private sizes = new WeakMap<object, number>();
private bytes = 0;
constructor(
private maxBytes: number,
private maxEntries: number,
private canEvict: (key: string) => boolean = () => true,
) {}
get(key: string): T | undefined {
const entry = this.entries.get(key);
if (!entry) return undefined;
this.entries.delete(key);
this.entries.set(key, entry);
return entry.value;
}
set(key: string, value: T): void {
this.delete(key);
const bytes = this.estimate(value);
this.entries.set(key, { value, bytes });
this.bytes += bytes;
for (const candidate of this.entries.keys()) {
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
if (this.canEvict(candidate)) this.delete(candidate);
}
}
delete(key: string): void {
const entry = this.entries.get(key);
if (entry) this.bytes -= entry.bytes;
this.entries.delete(key);
}
clear(): void {
this.entries.clear();
this.sizes = new WeakMap<object, number>();
this.bytes = 0;
}
private estimate(value: unknown): number {
if (typeof value === "string") return value.length * 2;
if (!value || typeof value !== "object") return 8;
const cached = this.sizes.get(value);
if (cached !== undefined) return cached;
const size = 32 + Object.values(value).reduce<number>(
(total, item) => total + this.estimate(item),
0,
);
this.sizes.set(value, size);
return size;
}
}
+7 -42
View File
@@ -1,49 +1,14 @@
import type { UIMessage } from "./types";
import { MemoryLruCache } from "./memory-lru-cache";
/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */
export class ThreadMessageCache {
private entries = new Map<string, { messages: UIMessage[]; bytes: number }>();
private sizes = new WeakMap<object, number>();
private bytes = 0;
export class ThreadMessageCache extends MemoryLruCache<UIMessage[]> {
constructor(
private isPinned: (key: string) => boolean,
private maxBytes = 16 * 1024 * 1024,
private maxEntries = 12,
) {}
get(key: string): UIMessage[] | undefined {
const entry = this.entries.get(key);
if (!entry) return undefined;
this.entries.delete(key);
this.entries.set(key, entry);
return entry.messages;
}
set(key: string, messages: UIMessage[]): void {
this.delete(key);
const bytes = this.estimate(messages);
this.entries.set(key, { messages, bytes });
this.bytes += bytes;
for (const candidate of this.entries.keys()) {
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
if (!this.isPinned(candidate)) this.delete(candidate);
}
}
delete(key: string): void {
const entry = this.entries.get(key);
if (entry) this.bytes -= entry.bytes;
this.entries.delete(key);
}
private estimate(value: unknown): number {
if (typeof value === "string") return value.length * 2;
if (!value || typeof value !== "object") return 8;
const cached = this.sizes.get(value);
if (cached !== undefined) return cached;
const size = 32 + Object.values(value).reduce<number>((total, item) => total + this.estimate(item), 0);
this.sizes.set(value, size);
return size;
isPinned: (key: string) => boolean,
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
) {
super(maxBytes, maxEntries, (key) => !isPinned(key));
}
}
+15
View File
@@ -81,6 +81,12 @@ export interface UIMessage {
/** Structured tool events behind trace rows. Kept so activity cards can
* distinguish running, completed, and failed tool phases. */
toolEvents?: ToolProgressEvent[];
/** Oversized persisted trace content that can be fetched when activity is expanded. */
traceDetail?: {
ref: string;
bytes: number;
traceCount: number;
};
/** Activity rows: explicit file edits emitted by edit tools. */
fileEdits?: UIFileEdit[];
/** Activity rows created during the same agent phase share one collapsible block. */
@@ -1542,6 +1548,8 @@ export interface WebuiThreadPersistedPayload {
schemaVersion: number;
sessionKey?: string;
savedAt?: string;
/** Cheap server revision used for application-managed conditional revalidation. */
revision?: string;
messages: UIMessage[];
fork_boundary_message_count?: number;
/** Turn ids backed by an explicit persisted ``turn_end`` event. */
@@ -1553,6 +1561,13 @@ export interface WebuiThreadPersistedPayload {
workspace_scope?: WorkspaceScopePayload;
}
export interface WebuiThreadTraceDetailPayload {
message_id: string;
content: string;
traces?: string[];
toolEvents?: ToolProgressEvent[];
}
export interface FilePreviewPayload {
path: string;
display_path: string;
+14
View File
@@ -0,0 +1,14 @@
import { MemoryLruCache } from "./memory-lru-cache";
import type { WebuiThreadPersistedPayload } from "./types";
/** Process-local canonical replay cache used for stale-while-revalidate session entry. */
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
constructor(
maxBytes = 16 * 1024 * 1024,
maxEntries = 12,
) {
super(maxBytes, maxEntries);
}
}
export const webuiThreadCache = new WebuiThreadCache();
@@ -140,6 +140,36 @@ function installReducedMotion() {
}
describe("AgentActivityCluster", () => {
it("loads deferred trace details only after completed activity is expanded", async () => {
const onLoadTraceDetails = vi.fn();
render(
<AgentActivityCluster
messages={[{
id: "t-deferred",
role: "tool",
kind: "trace",
content: "exec(…)",
traces: ["exec(…)"],
traceDetail: {
ref: "9.tr-deadbeefdeadbeef",
bytes: 40_000,
traceCount: 1,
},
createdAt: 1,
}]}
isTurnStreaming={false}
hasBodyBelow={false}
onLoadTraceDetails={onLoadTraceDetails}
/>,
);
expect(onLoadTraceDetails).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: /Worked/ }));
await waitFor(() => {
expect(onLoadTraceDetails).toHaveBeenCalledWith(["9.tr-deadbeefdeadbeef"]);
});
});
it("shows model retries in the existing live activity header", () => {
render(
<AgentActivityCluster
+42
View File
@@ -28,6 +28,7 @@ import {
fetchSkills,
fetchTrendingMarketplaceSkills,
fetchWebuiThread,
fetchWebuiThreadTraceDetail,
fetchWorkspaces,
importMcpConfig,
installMarketplaceSkill,
@@ -117,6 +118,47 @@ describe("webui API helpers", () => {
);
});
it("revalidates a cached WebUI thread and reuses it on 304", async () => {
const cached = {
schemaVersion: 3,
revision: "rev-1",
messages: [],
};
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
status: 304,
} as Response);
await expect(fetchWebuiThread("tok", "websocket:chat-1", {
revision: cached.revision,
cached,
})).resolves.toBe(cached);
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread",
expect.objectContaining({
headers: {
Authorization: "Bearer tok",
"If-None-Match": '"rev-1"',
},
cache: "no-store",
}),
);
});
it("fetches deferred trace details with encoded session and ref", async () => {
await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.tr-deadbeefdeadbeef",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
cache: "no-store",
}),
);
});
it("aborts a WebUI thread request when its caller signal is aborted", async () => {
let requestSignal: AbortSignal | null = null;
vi.mocked(fetch).mockImplementation((_input, init) => new Promise((_resolve, reject) => {
+186 -1
View File
@@ -8,8 +8,15 @@ import { ThreadShell } from "@/components/thread/ThreadShell";
import i18n from "@/i18n";
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import type { CliAppsPayload, ConnectionStatus, SettingsPayload, UIMessage } from "@/lib/types";
import type {
CliAppsPayload,
ConnectionStatus,
SettingsPayload,
UIMessage,
WebuiThreadPersistedPayload,
} from "@/lib/types";
const HERO_GREETING_PATTERN =
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
@@ -262,6 +269,36 @@ function httpJson(body: unknown) {
};
}
function traceDetailThread(
deferred: boolean,
answer: string,
revision?: string,
): WebuiThreadPersistedPayload {
return {
schemaVersion: 3,
...(revision ? { revision } : {}),
messages: [
{
id: "trace-shared",
role: "tool",
kind: "trace",
content: deferred ? "exec(…)" : 'exec({"command":"echo full"})',
traces: [deferred ? "exec(…)" : 'exec({"command":"echo full"})'],
...(deferred
? { traceDetail: { ref: "1.trace-shared", bytes: 40_000, traceCount: 1 } }
: {}),
createdAt: 1_000,
},
{
id: "answer-shared",
role: "assistant",
content: answer,
createdAt: 2_000,
},
],
};
}
function setDocumentVisibility(value: DocumentVisibilityState): void {
Object.defineProperty(document, "visibilityState", {
configurable: true,
@@ -417,6 +454,7 @@ function settingsWithFastPreset(): SettingsPayload {
describe("ThreadShell", () => {
beforeEach(() => {
webuiThreadCache.clear();
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
@@ -427,6 +465,153 @@ describe("ThreadShell", () => {
);
});
it("surfaces and retries a deferred trace-detail request failure", async () => {
const client = makeClient();
let detailCalls = 0;
const fetchMock = vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/webui-thread/trace-detail?")) {
detailCalls += 1;
if (detailCalls === 1) {
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
}
return Promise.resolve(httpJson({
message_id: "trace-deferred",
content: 'exec({"command":"echo full"})',
traces: ['exec({"command":"echo full"})'],
}));
}
if (url.includes("websocket%3Atrace-detail-retry/webui-thread")) {
return Promise.resolve(httpJson({
schemaVersion: 3,
messages: [
{
id: "trace-deferred",
role: "tool",
kind: "trace",
content: "exec(…)",
traces: ["exec(…)"],
traceDetail: { ref: "1.trace-deferred", bytes: 40_000, traceCount: 1 },
createdAt: 1_000,
},
{ id: "answer", role: "assistant", content: "done", createdAt: 2_000 },
],
}));
}
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
});
vi.stubGlobal("fetch", fetchMock);
render(wrap(
client,
<ThreadShell
session={session("trace-detail-retry")}
title="Trace detail retry"
onToggleSidebar={() => {}}
/>,
));
const activity = await screen.findByRole("button", { name: /Worked/ });
fireEvent.click(activity);
expect(await screen.findByRole("alert")).toHaveTextContent(
"Full activity details could not be loaded.",
);
expect(detailCalls).toBe(1);
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(detailCalls).toBe(2));
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
fireEvent.click(activity);
fireEvent.click(activity);
await act(async () => Promise.resolve());
expect(detailCalls).toBe(2);
});
it("ignores a deferred trace-detail failure after switching sessions", async () => {
const client = makeClient();
const detailUrls: string[] = [];
let rejectDetail!: (reason: Error) => void;
const pendingDetail = new Promise<Response>((_resolve, reject) => {
rejectDetail = reject;
});
const cachedB = traceDetailThread(false, "done-b", "rev-b");
webuiThreadCache.set("websocket:trace-failure-b", cachedB);
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/webui-thread/trace-detail?")) {
detailUrls.push(url);
return pendingDetail;
}
if (url.includes("websocket%3Atrace-failure-a/webui-thread")) {
return Promise.resolve(httpJson(traceDetailThread(true, "done-a")));
}
if (url.includes("websocket%3Atrace-failure-b/webui-thread")) {
return Promise.resolve(httpJson(cachedB));
}
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
}));
const view = (chatId: string) => wrap(
client,
<ThreadShell
session={session(chatId)}
title={`Trace ${chatId}`}
onToggleSidebar={() => {}}
/>,
);
const { rerender } = render(view("trace-failure-a"));
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
rerender(view("trace-failure-b"));
await screen.findByText("done-b");
await act(async () => rejectDetail(new Error("late failure")));
expect(detailUrls).toHaveLength(1);
expect(detailUrls[0]).toContain("websocket%3Atrace-failure-a");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("does not carry a visible trace-detail failure into a cached session", async () => {
const client = makeClient();
const detailUrls: string[] = [];
const cachedB = traceDetailThread(false, "cached-b", "rev-visible-b");
webuiThreadCache.set("websocket:visible-failure-b", cachedB);
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/webui-thread/trace-detail?")) {
detailUrls.push(url);
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
}
if (url.includes("websocket%3Avisible-failure-a/webui-thread")) {
return Promise.resolve(httpJson(traceDetailThread(true, "failed-a")));
}
if (url.includes("websocket%3Avisible-failure-b/webui-thread")) {
return Promise.resolve(httpJson(cachedB));
}
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
}));
const view = (chatId: string) => wrap(
client,
<ThreadShell
session={session(chatId)}
title={`Trace ${chatId}`}
onToggleSidebar={() => {}}
/>,
);
const { rerender } = render(view("visible-failure-a"));
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
expect(await screen.findByRole("alert")).toBeInTheDocument();
rerender(view("visible-failure-b"));
await screen.findByText("cached-b");
expect(detailUrls).toHaveLength(1);
expect(detailUrls[0]).toContain("websocket%3Avisible-failure-a");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("renders each logical round in a completed turn as its own usage bar", async () => {
const client = makeClient();
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
+16 -10
View File
@@ -1461,6 +1461,7 @@ describe("ThreadViewport", () => {
it("renders only the tail window for long history by default", () => {
const longMessages = makeLongMessages(300);
const firstVisible = longMessages.length - INITIAL_HISTORY_WINDOW;
render(
<ThreadViewport
@@ -1470,8 +1471,8 @@ describe("ThreadViewport", () => {
/>,
);
expect(screen.queryByText("message 139")).not.toBeInTheDocument();
expect(screen.getByText("message 140")).toBeInTheDocument();
expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();
expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();
expect(screen.getByText("message 299")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Load earlier messages" })).not.toBeInTheDocument();
});
@@ -1509,6 +1510,7 @@ describe("ThreadViewport", () => {
});
it("prefetches earlier history within half a viewport of the top", () => {
const expandedFirstVisible = 300 - INITIAL_HISTORY_WINDOW - HISTORY_WINDOW_INCREMENT;
const { container } = render(
<ThreadViewport
messages={makeLongMessages(300)}
@@ -1527,14 +1529,16 @@ describe("ThreadViewport", () => {
act(() => {
dispatchUserScroll(scroller);
});
expect(screen.queryByText("message 139")).not.toBeInTheDocument();
expect(
screen.queryByText(`message ${300 - INITIAL_HISTORY_WINDOW - 1}`),
).not.toBeInTheDocument();
scroller.scrollTop = 250;
act(() => {
dispatchUserScroll(scroller);
});
expect(screen.getByText("message 20")).toBeInTheDocument();
expect(screen.queryByText("message 19")).not.toBeInTheDocument();
expect(screen.getByText(`message ${expandedFirstVisible}`)).toBeInTheDocument();
expect(screen.queryByText(`message ${expandedFirstVisible - 1}`)).not.toBeInTheDocument();
});
it("keeps the first visible history item fixed while deferred rows materialize", () => {
@@ -1562,7 +1566,8 @@ describe("ThreadViewport", () => {
},
});
const anchor = screen.getByText("message 140")
const firstVisible = 300 - INITIAL_HISTORY_WINDOW;
const anchor = screen.getByText(`message ${firstVisible}`)
.closest<HTMLElement>("[data-thread-display-unit]");
expect(anchor).not.toBeNull();
hitTarget = anchor;
@@ -1913,15 +1918,16 @@ describe("ThreadViewport", () => {
it("expands the window start to avoid cutting an agent activity cluster", () => {
const clustered = makeLongMessages(200);
const boundary = clustered.length - INITIAL_HISTORY_WINDOW;
clustered.splice(
38,
boundary - 2,
3,
{
id: "r0",
role: "assistant",
content: "",
reasoning: "first reasoning",
createdAt: 38,
createdAt: boundary - 2,
},
{
id: "t0",
@@ -1929,14 +1935,14 @@ describe("ThreadViewport", () => {
kind: "trace",
content: "tool()",
traces: ["tool()"],
createdAt: 39,
createdAt: boundary - 1,
},
{
id: "r1",
role: "assistant",
content: "",
reasoning: "second reasoning",
createdAt: 40,
createdAt: boundary,
},
);
+67 -1
View File
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessions";
import * as api from "@/lib/api";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ClientProvider } from "@/providers/ClientProvider";
vi.mock("@/lib/api", async (importOriginal) => {
@@ -93,6 +94,7 @@ describe("useSessions", () => {
vi.mocked(api.listSessions).mockReset();
vi.mocked(api.deleteSession).mockReset();
vi.mocked(api.fetchWebuiThread).mockReset();
webuiThreadCache.clear();
});
it("does not use low-information greetings as fallback session titles", () => {
@@ -566,6 +568,70 @@ describe("useSessions", () => {
expect(result.current.messages[2]!.content).toBe("summary");
});
it("shows a cached transcript immediately while revalidating it", async () => {
const cached = {
schemaVersion: 3,
revision: "rev-cached",
messages: [
{ id: "a1", role: "assistant" as const, content: "cached answer", createdAt: 1 },
],
};
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(cached);
const first = renderHook(() => useSessionHistory("websocket:cached"), {
wrapper: wrap(fakeClient()),
});
await waitFor(() => expect(first.result.current.loading).toBe(false));
first.unmount();
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise(() => {}));
const second = renderHook(() => useSessionHistory("websocket:cached"), {
wrapper: wrap(fakeClient()),
});
expect(second.result.current.loading).toBe(false);
expect(second.result.current.messages[0]?.content).toBe("cached answer");
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith(
"tok",
"websocket:cached",
expect.objectContaining({
limit: 40,
direction: "latest",
revision: "rev-cached",
cached,
}),
);
second.unmount();
});
it("keeps rendered history visible when its LRU entry was evicted before refresh", async () => {
const loaded = {
schemaVersion: 3,
revision: "rev-loaded",
messages: [
{ id: "a1", role: "assistant" as const, content: "still visible", createdAt: 1 },
],
};
vi.mocked(api.fetchWebuiThread)
.mockResolvedValueOnce(loaded)
.mockImplementationOnce(() => new Promise(() => {}));
const { result, unmount } = renderHook(
() => useSessionHistory("websocket:evicted"),
{ wrapper: wrap(fakeClient()) },
);
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.messages[0]?.content).toBe("still visible");
webuiThreadCache.delete("websocket:evicted");
act(() => result.current.refresh());
await waitFor(() => expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2));
expect(result.current.loading).toBe(false);
expect(result.current.messages[0]?.content).toBe("still visible");
unmount();
});
it("flags transcript ending with a trace row as pending", async () => {
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
schemaVersion: 3,
@@ -785,7 +851,7 @@ describe("useSessions", () => {
"tok",
"websocket:paged",
expect.objectContaining({
limit: 80,
limit: 40,
direction: "latest",
signal: expect.any(AbortSignal),
}),
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
import type { WebuiThreadPersistedPayload } from "@/lib/types";
function payload(id: string): WebuiThreadPersistedPayload {
return {
schemaVersion: 3,
revision: `rev-${id}`,
messages: [{ id, role: "assistant", content: id, createdAt: 1 }],
};
}
describe("WebuiThreadCache", () => {
it("evicts the least recently used session", () => {
const cache = new WebuiThreadCache(10_000, 2);
cache.set("a", payload("a"));
cache.set("b", payload("b"));
expect(cache.get("a")).toBeDefined();
cache.set("c", payload("c"));
expect(cache.get("a")?.revision).toBe("rev-a");
expect(cache.get("b")).toBeUndefined();
expect(cache.get("c")?.revision).toBe("rev-c");
});
it("does not retain a payload larger than the byte budget", () => {
const cache = new WebuiThreadCache(64, 2);
cache.set("large", payload("x".repeat(100)));
expect(cache.get("large")).toBeUndefined();
});
});