Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(webui): bound history replay work
chengyongru7ba60c2ef051
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.pyindex de07d7ffc..954e5f240 100644--- a/nanobot/channels/websocket/tests/test_websocket_channel.py+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py@@ -5537,6 +5537,77 @@ def test_handle_webui_thread_get_returns_json(tmp_path, monkeypatch) -> None:assert body["has_pending_tool_calls"] is False+async def test_webui_thread_dispatch_runs_replay_off_event_loop(tmp_path, monkeypatch) -> None:+ from urllib.parse import quote++ from websockets.http11 import Request++ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ key = "websocket:threaded-history"+ append_transcript_object(+ key,+ {"event": "user", "chat_id": "threaded-history", "text": "hi"},+ )+ gateway = _basic_handler(MagicMock(), workspace_path=tmp_path)+ gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0+ encoded = quote(key, safe="")+ request = Request(+ f"/api/sessions/{encoded}/webui-thread",+ Headers([("Authorization", "Bearer tok")]),+ )+ original = gateway.http._handle_webui_thread_get++ def slow_replay(*args: Any, **kwargs: Any):+ time.sleep(0.15)+ return original(*args, **kwargs)++ monkeypatch.setattr(gateway.http, "_handle_webui_thread_get", slow_replay)+ request_task = asyncio.create_task(+ gateway.http._dispatch_session_routes(request, request.path)+ )++ await asyncio.sleep(0.03)++ assert request_task.done() is False+ response = await request_task+ assert response is not None+ assert response.status_code == 200+++async def test_webui_thread_diagnostics_hash_session_key(tmp_path, monkeypatch) -> None:+ from urllib.parse import quote++ from websockets.http11 import Request++ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_PAGE_RECORDS", 1)+ key = "websocket:private-session-name"+ for event in (+ {"event": "user", "chat_id": "private-session-name", "text": "hi"},+ {"event": "message", "chat_id": "private-session-name", "text": "hello"},+ {"event": "turn_end", "chat_id": "private-session-name"},+ ):+ append_transcript_object(key, event)+ gateway = _basic_handler(MagicMock(), workspace_path=tmp_path)+ gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0+ gateway.http._log = MagicMock()+ encoded = quote(key, safe="")+ request = Request(+ f"/api/sessions/{encoded}/webui-thread",+ Headers([("Authorization", "Bearer tok")]),+ )++ response = await gateway.http._dispatch_session_routes(request, request.path)++ assert response is not None+ assert response.status_code == 200+ call = gateway.http._log.warning.call_args+ assert call is not None+ assert key not in " ".join(str(value) for value in call.args)++@pytest.mark.asyncioasync def test_handle_session_context_get_reads_detached_session() -> None:from urllib.parse import quotediff --git a/nanobot/webui/http_utils.py b/nanobot/webui/http_utils.pyindex f2c9ecbd2..76d52312f 100644--- a/nanobot/webui/http_utils.py+++ b/nanobot/webui/http_utils.py@@ -9,6 +9,8 @@ import httpimport ipaddressimport jsonimport re+import time+from dataclasses import dataclassfrom typing import Any, castfrom urllib.parse import parse_qs, urlparse@@ -21,6 +23,17 @@ _JSON_GZIP_MIN_BYTES = 4 * 1024_JSON_GZIP_LEVEL = 5+@dataclass(slots=True)+class JSONResponseMetrics:+ """Serialization timings and sizes for an HTTP JSON response."""++ json_encode_ms: float = 0.0+ gzip_ms: float = 0.0+ uncompressed_bytes: int = 0+ response_bytes: int = 0+ gzip_enabled: bool = False++def strip_trailing_slash(path: str) -> str:if len(path) > 1 and path.endswith("/"):return path.rstrip("/")@@ -101,8 +114,13 @@ def http_json_response(status: int = 200,accept_encoding: str | None = None,extra_headers: list[tuple[str, str]] | None = None,+ metrics: JSONResponseMetrics | None = None,) -> Response:+ encode_started = time.perf_counter()body = json.dumps(data, ensure_ascii=False).encode("utf-8")+ if metrics is not None:+ metrics.json_encode_ms = (time.perf_counter() - encode_started) * 1000+ metrics.uncompressed_bytes = len(body)headers = [("Date", email.utils.formatdate(usegmt=True)),("Connection", "close"),@@ -111,11 +129,17 @@ def http_json_response(if accept_encoding is not None:headers.append(("Vary", "Accept-Encoding"))if len(body) >= _JSON_GZIP_MIN_BYTES and accepts_gzip(accept_encoding):+ gzip_started = time.perf_counter()body = gzip.compress(body, compresslevel=_JSON_GZIP_LEVEL, mtime=0)+ if metrics is not None:+ metrics.gzip_ms = (time.perf_counter() - gzip_started) * 1000+ metrics.gzip_enabled = Trueheaders.append(("Content-Encoding", "gzip"))if extra_headers:headers.extend(extra_headers)headers.append(("Content-Length", str(len(body))))+ if metrics is not None:+ metrics.response_bytes = len(body)reason = http.HTTPStatus(status).phrasereturn Response(status, reason, Headers(headers), body)diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.pyindex 82addef10..102a5d946 100644--- a/nanobot/webui/transcript.py+++ b/nanobot/webui/transcript.py@@ -9,8 +9,10 @@ import jsonimport osimport reimport shutil+import threadingimport timeimport uuid+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Callable, Mapping, NamedTuple, Sequence, castfrom urllib.parse import unquote, urlparse@@ -36,6 +38,10 @@ _TRANSCRIPT_ACTIVE_CHUNK_ID = "active"_TRANSCRIPT_SEGMENT_RE = re.compile(r"^\d{6}\.jsonl$")_DEFAULT_TRANSCRIPT_PAGE_LIMIT = 160_MAX_TRANSCRIPT_PAGE_LIMIT = 1000+_MAX_TRANSCRIPT_PAGE_RECORDS = 4_000+_MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024+_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"_MARKDOWN_LOCAL_IMAGE_RE = re.compile(@@ -179,6 +185,24 @@ class _SessionBackfillTurn(NamedTuple):assistant_records: tuple[dict[str, Any], ...]+@dataclass(slots=True)+class TranscriptReplayStats:+ """Bounded, non-sensitive diagnostics for one history replay."""++ effective_limit: int = 0+ source_bytes: int = 0+ parsed_records: int = 0+ selected_bytes: int = 0+ selected_records: int = 0+ compacted_delta_records: int = 0+ manifest_rebuilt: bool = False+ manifest_rebuild_ms: int = 0+ replay_ms: int = 0+ capped_by_bytes: bool = False+ capped_by_records: bool = False+ truncated_oversized_turn: bool = False++def _record_json_line(record: dict[str, Any]) -> str:return json.dumps(record, ensure_ascii=False, separators=(",", ":"))@@ -211,6 +235,116 @@ def _records_bytes(records: list[dict[str, Any]]) -> int:return total+def _stream_key(record: dict[str, Any], stream: str) -> tuple[str, str, str]:+ raw_turn_id = record.get("turn_id")+ turn_id = raw_turn_id if isinstance(raw_turn_id, str) else ""+ raw_phase = record.get("turn_phase")+ phase = raw_phase if isinstance(raw_phase, str) and raw_phase else stream+ raw_stream_id = record.get("stream_id")+ stream_id = raw_stream_id if isinstance(raw_stream_id, str) else ""+ return turn_id, phase, stream_id+++def _compact_completed_stream_deltas(+ turn: list[dict[str, Any]],+) -> tuple[list[dict[str, Any]], int]:+ """Fold transport deltas into canonical end records for a completed turn."""+ if not turn or turn[-1].get("event") != "turn_end":+ return turn, 0++ pending: dict[tuple[str, str, str], list[tuple[int, dict[str, Any]]]] = {}+ dropped_indexes: set[int] = set()+ replacements: dict[int, dict[str, Any]] = {}+ for index, record in enumerate(turn):+ event = record.get("event")+ if event in {"delta", "reasoning_delta"}:+ stream = "answer" if event == "delta" else "reasoning"+ pending.setdefault(_stream_key(record, stream), []).append((index, record))+ continue+ if event not in {"stream_end", "reasoning_end"}:+ continue+ stream = "answer" if event == "stream_end" else "reasoning"+ chunks = pending.pop(_stream_key(record, stream), [])+ if not chunks:+ continue+ completed = dict(record)+ text = completed.get("text")+ if not isinstance(text, str) or not text:+ completed["text"] = "".join(+ str(chunk.get("text") or "") for _, chunk in chunks+ )+ replacements[index] = completed+ dropped_indexes.update(chunk_index for chunk_index, _ in chunks)++ if not dropped_indexes:+ return turn, 0+ return [+ replacements.get(index, record)+ for index, record in enumerate(turn)+ if index not in dropped_indexes+ ], len(dropped_indexes)+++def _compact_completed_turns(+ turns: list[list[dict[str, Any]]],+) -> tuple[list[list[dict[str, Any]]], int]:+ compacted: list[list[dict[str, Any]]] = []+ dropped = 0+ for turn in turns:+ next_turn, turn_dropped = _compact_completed_stream_deltas(turn)+ compacted.append(next_turn)+ dropped += turn_dropped+ return compacted, dropped+++def _trim_oversized_turn(+ turn: list[dict[str, Any]],+ *,+ max_records: int,+ max_bytes: int,+) -> list[dict[str, Any]]:+ """Keep the useful tail of one pathological turn within a hard replay budget."""+ if not turn or max_records <= 0 or max_bytes <= 0:+ return []++ user_index = next(+ (index for index, record in enumerate(turn) if _is_user_transcript_row(record)),+ None,+ )+ end_index = next(+ (+ index+ for index in range(len(turn) - 1, -1, -1)+ if turn[index].get("event") == "turn_end"+ ),+ None,+ )+ answer_index = next(+ (+ index+ for index in range(len(turn) - 1, -1, -1)+ if turn[index].get("event") in {"delta", "stream_end", "message"}+ ),+ None,+ )+ priority = [user_index, end_index, answer_index]+ candidates = [+ *[index for index in priority if index is not None],+ *range(len(turn) - 1, -1, -1),+ ]+ selected: set[int] = set()+ selected_bytes = 0+ for index in candidates:+ if index in selected or len(selected) >= max_records:+ continue+ record_bytes = _records_bytes([turn[index]])+ if selected_bytes + record_bytes > max_bytes:+ continue+ selected.add(index)+ selected_bytes += record_bytes+ return [record for index, record in enumerate(turn) if index in selected]++def _flatten_turns(turns: list[list[dict[str, Any]]]) -> list[dict[str, Any]]:return [record for turn in turns for record in turn]@@ -262,12 +396,21 @@ def _segment_ids_on_disk(session_key: str) -> list[str]:)-def _segment_manifest_entry(session_key: str, segment_id: str) -> dict[str, Any]:+def _segment_manifest_entry(+ session_key: str,+ segment_id: str,+ *,+ stats: TranscriptReplayStats | None = None,+) -> dict[str, Any]:path = _segment_file_path(session_key, segment_id)lines = _read_transcript_file(path)+ size = path.stat().st_size if path.exists() else 0+ if stats is not None:+ stats.source_bytes += size+ stats.parsed_records += len(lines)return {"id": segment_id,- "bytes": path.stat().st_size if path.exists() else 0,+ "bytes": size,"turn_count": len(_split_transcript_turns(lines)),"user_count": sum(1 for line in lines if _is_user_transcript_row(line)),}@@ -311,7 +454,7 @@ def _write_segment_manifest(session_key: str, entries: list[dict[str, Any]]) ->"segments": entries,}path = _webui_transcript_manifest_path(session_key)- tmp_path = path.with_suffix(".json.tmp")+ tmp_path = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")try:tmp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")os.replace(tmp_path, path)@@ -320,23 +463,34 @@ def _write_segment_manifest(session_key: str, entries: list[dict[str, Any]]) ->raise-def _rebuild_segment_manifest(session_key: str) -> list[dict[str, Any]]:+def _rebuild_segment_manifest(+ session_key: str,+ *,+ stats: TranscriptReplayStats | None = None,+) -> list[dict[str, Any]]:+ started = time.perf_counter()segment_ids = _segment_ids_on_disk(session_key)- entries = [_segment_manifest_entry(session_key, segment_id) for segment_id in segment_ids]+ entries = [+ _segment_manifest_entry(session_key, segment_id, stats=stats)+ for segment_id in segment_ids+ ]if entries:_write_segment_manifest(session_key, entries)else:_webui_transcript_manifest_path(session_key).unlink(missing_ok=True)+ if stats is not None:+ stats.manifest_rebuilt = True+ stats.manifest_rebuild_ms += int((time.perf_counter() - started) * 1000)return entries-def _read_segment_manifest_entries(session_key: str) -> list[dict[str, Any]]:+def _load_segment_manifest_entries(session_key: str) -> list[dict[str, Any]] | None:directory = webui_transcript_segments_dir(session_key)if not directory.is_dir():return []path = _webui_transcript_manifest_path(session_key)if not path.is_file():- return _rebuild_segment_manifest(session_key)+ return Nonetry:data = json.loads(path.read_text(encoding="utf-8"))manifest = cast(dict[str, Any], data) if isinstance(data, dict) else None@@ -346,18 +500,56 @@ def _read_segment_manifest_entries(session_key: str) -> list[dict[str, Any]]:or manifest.get("version") != _TRANSCRIPT_SEGMENT_MANIFEST_VERSIONor not isinstance(raw_segments, list)):- return _rebuild_segment_manifest(session_key)+ return Noneentries: list[dict[str, Any]] = []for entry in cast(list[Any], raw_segments):normalized = _normalize_manifest_entry(session_key, entry)if normalized is None:- return _rebuild_segment_manifest(session_key)+ return Noneentries.append(normalized)if [entry["id"] for entry in entries] != _segment_ids_on_disk(session_key):- return _rebuild_segment_manifest(session_key)+ return Nonereturn entriesexcept (OSError, json.JSONDecodeError, TypeError, AttributeError):- return _rebuild_segment_manifest(session_key)+ return None+++def _manifest_rebuild_lock(session_key: str) -> threading.Lock:+ digest = hashlib.sha256(session_key.encode("utf-8")).digest()+ lock_index = int.from_bytes(digest[:2], "big") % len(_MANIFEST_REBUILD_LOCKS)+ return _MANIFEST_REBUILD_LOCKS[lock_index]+++def _read_segment_manifest_entries(+ session_key: str,+ *,+ stats: TranscriptReplayStats | None = None,+) -> list[dict[str, Any]]:+ entries = _load_segment_manifest_entries(session_key)+ if entries is not None:+ return entries+ with _manifest_rebuild_lock(session_key):+ entries = _load_segment_manifest_entries(session_key)+ if entries is not None:+ return entries+ return _rebuild_segment_manifest(session_key, stats=stats)+++def _repair_manifest_chunk_count(+ session_key: str,+ chunk_id: str,+ actual_turn_count: int,+ *,+ stats: TranscriptReplayStats | None = None,+) -> None:+ with _manifest_rebuild_lock(session_key):+ entries = _load_segment_manifest_entries(session_key)+ if entries is not None and any(+ entry["id"] == chunk_id and entry["turn_count"] == actual_turn_count+ for entry in entries+ ):+ return+ _rebuild_segment_manifest(session_key, stats=stats)def _read_segment_ids(session_key: str) -> list[str]:@@ -367,40 +559,43 @@ def _read_segment_ids(session_key: str) -> list[str]:def _append_segment_turns(session_key: str, turns: list[list[dict[str, Any]]]) -> None:if not turns:return- entries = _read_segment_manifest_entries(session_key)- next_id = int(entries[-1]["id"]) + 1 if entries else 1- batch: list[list[dict[str, Any]]] = []- batch_bytes = 0-- def write_batch() -> None:- nonlocal next_id- segment_id = f"{next_id:06d}"- path = _segment_file_path(session_key, segment_id)- _write_records_to_path(path, _flatten_turns(batch))- entries.append({- "id": segment_id,- "bytes": path.stat().st_size,- "turn_count": len(batch),- "user_count": sum(- 1- for turn in batch- for row in turn- if _is_user_transcript_row(row)- ),- })- next_id += 1-- for turn in turns:- turn_bytes = _records_bytes(turn)- if batch and batch_bytes + turn_bytes > _MAX_TRANSCRIPT_FILE_BYTES:+ with _manifest_rebuild_lock(session_key):+ entries = _load_segment_manifest_entries(session_key)+ if entries is None:+ entries = _rebuild_segment_manifest(session_key)+ next_id = int(entries[-1]["id"]) + 1 if entries else 1+ batch: list[list[dict[str, Any]]] = []+ batch_bytes = 0++ def write_batch() -> None:+ nonlocal next_id+ segment_id = f"{next_id:06d}"+ path = _segment_file_path(session_key, segment_id)+ _write_records_to_path(path, _flatten_turns(batch))+ entries.append({+ "id": segment_id,+ "bytes": path.stat().st_size,+ "turn_count": len(batch),+ "user_count": sum(+ 1+ for turn in batch+ for row in turn+ if _is_user_transcript_row(row)+ ),+ })+ next_id += 1++ for turn in turns:+ turn_bytes = _records_bytes(turn)+ if batch and batch_bytes + turn_bytes > _MAX_TRANSCRIPT_FILE_BYTES:+ write_batch()+ batch = []+ batch_bytes = 0+ batch.append(turn)+ batch_bytes += turn_bytes+ if batch:write_batch()- batch = []- batch_bytes = 0- batch.append(turn)- batch_bytes += turn_bytes- if batch:- write_batch()- _write_segment_manifest(session_key, entries)+ _write_segment_manifest(session_key, entries)def _rotate_active_transcript_if_needed(session_key: str) -> None:@@ -417,6 +612,14 @@ def _rotate_active_transcript_if_needed(session_key: str) -> None:if not lines:returnturns = _split_transcript_turns(lines)+ turns, compacted_delta_records = _compact_completed_turns(turns)+ if compacted_delta_records:+ _write_records_to_path(path, _flatten_turns(turns))+ try:+ if path.stat().st_size <= _ACTIVE_TRANSCRIPT_ROTATE_BYTES:+ return+ except OSError:+ returnif len(turns) <= 1:return@@ -439,7 +642,6 @@ def _rotate_active_transcript_if_needed(session_key: str) -> None:def _chunk_ids(session_key: str) -> list[str]:- _rotate_active_transcript_if_needed(session_key)ids = _read_segment_ids(session_key)if webui_transcript_path(session_key).is_file():ids.append(_TRANSCRIPT_ACTIVE_CHUNK_ID)@@ -456,13 +658,81 @@ def _read_chunk_turns(session_key: str, chunk_id: str) -> list[list[dict[str, Anreturn _split_transcript_turns(_read_transcript_file(path))+def _compact_segment_turns(+ session_key: str,+ chunk_id: str,+ *,+ stats: TranscriptReplayStats | None = None,+) -> list[list[dict[str, Any]]]:+ """Compact one immutable legacy segment and keep its manifest entry valid."""+ with _manifest_rebuild_lock(session_key):+ turns = _read_chunk_turns(session_key, chunk_id)+ if stats is not None:+ path = _segment_file_path(session_key, chunk_id)+ try:+ stats.source_bytes += path.stat().st_size+ except OSError:+ pass+ stats.parsed_records += sum(len(turn) for turn in turns)+ compacted, dropped = _compact_completed_turns(turns)+ if not dropped:+ return turns++ entries = _load_segment_manifest_entries(session_key)+ path = _segment_file_path(session_key, chunk_id)+ _write_records_to_path(path, _flatten_turns(compacted))+ if entries is None:+ _rebuild_segment_manifest(session_key, stats=stats)+ else:+ for entry in entries:+ if entry["id"] != chunk_id:+ continue+ entry["bytes"] = path.stat().st_size+ entry["turn_count"] = len(compacted)+ entry["user_count"] = sum(+ 1+ for turn in compacted+ for record in turn+ if _is_user_transcript_row(record)+ )+ break+ _write_segment_manifest(session_key, entries)+ if stats is not None:+ stats.compacted_delta_records += dropped+ return compacted++def _cached_chunk_turns(session_key: str,chunk_id: str,turn_cache: dict[str, list[list[dict[str, Any]]]],+ *,+ stats: TranscriptReplayStats | None = None,) -> list[list[dict[str, Any]]]:if chunk_id not in turn_cache:- turn_cache[chunk_id] = _read_chunk_turns(session_key, chunk_id)+ if chunk_id == _TRANSCRIPT_ACTIVE_CHUNK_ID:+ path = webui_transcript_path(session_key)+ else:+ path = _segment_file_path(session_key, chunk_id)+ turns = _read_chunk_turns(session_key, chunk_id)+ needs_compaction = chunk_id != _TRANSCRIPT_ACTIVE_CHUNK_ID and any(+ record.get("event") in {"delta", "reasoning_delta"}+ for turn in turns+ for record in turn+ )+ if needs_compaction:+ turns = _compact_segment_turns(+ session_key,+ chunk_id,+ stats=stats,+ )+ elif stats is not None:+ try:+ stats.source_bytes += path.stat().st_size+ except OSError:+ pass+ stats.parsed_records += sum(len(turn) for turn in turns)+ turn_cache[chunk_id] = turnsreturn turn_cache[chunk_id]@@ -505,11 +775,12 @@ def _coerce_page_limit(limit: int | None) -> int:def _chunk_turn_refs(session_key: str,turn_cache: dict[str, list[list[dict[str, Any]]]],+ *,+ stats: TranscriptReplayStats | None = None,) -> list[_TranscriptChunkRef]:- _rotate_active_transcript_if_needed(session_key)refs: list[_TranscriptChunkRef] = []ordinal = 0- for entry in _read_segment_manifest_entries(session_key):+ for entry in _read_segment_manifest_entries(session_key, stats=stats):chunk_id = str(entry["id"])turn_count = int(entry["turn_count"])if turn_count <= 0:@@ -521,6 +792,7 @@ def _chunk_turn_refs(session_key,_TRANSCRIPT_ACTIVE_CHUNK_ID,turn_cache,+ stats=stats,)active_turn_count = len(active_turns)if active_turn_count > 0:@@ -540,6 +812,8 @@ def _count_user_messages_before_ordinal(chunks: list[_TranscriptChunkRef],before_ordinal: int,turn_cache: dict[str, list[list[dict[str, Any]]]],+ *,+ stats: TranscriptReplayStats | None = None,) -> int:total = 0for chunk in chunks:@@ -551,7 +825,12 @@ def _count_user_messages_before_ordinal(if local_end >= chunk.turn_count:total += chunk.user_countcontinue- turns = _cached_chunk_turns(session_key, chunk.chunk_id, turn_cache)+ turns = _cached_chunk_turns(+ session_key,+ chunk.chunk_id,+ turn_cache,+ stats=stats,+ )total += sum(1for turn in turns[:local_end]@@ -566,16 +845,22 @@ def _select_transcript_page(*,limit: int | None,before: str | None,+ stats: TranscriptReplayStats | None = None,_manifest_rebuilt: bool = False,) -> tuple[list[dict[str, Any]], dict[str, Any]]:+ stats = stats or TranscriptReplayStats()page_limit = _coerce_page_limit(limit)+ stats.effective_limit = page_limitturn_cache: dict[str, list[list[dict[str, Any]]]] = {}- chunks = _chunk_turn_refs(session_key, turn_cache)+ chunks = _chunk_turn_refs(session_key, turn_cache, stats=stats)total_turns = sum(chunk.turn_count for chunk in chunks)before_ordinal = _decode_page_cursor(before)upper_ordinal = total_turns if before_ordinal is None else min(before_ordinal, total_turns)selected: list[_TranscriptTurnRef] = []selected_message_count = 0+ selected_record_count = 0+ selected_bytes = 0+ budget_reached = Falsefor chunk in reversed(chunks):if chunk.start_ordinal >= upper_ordinal:@@ -583,28 +868,68 @@ def _select_transcript_page(local_upper = min(chunk.turn_count, upper_ordinal - chunk.start_ordinal)if local_upper <= 0:continue- turns = _cached_chunk_turns(session_key, chunk.chunk_id, turn_cache)+ turns = _cached_chunk_turns(+ session_key,+ chunk.chunk_id,+ turn_cache,+ stats=stats,+ )if (chunk.chunk_id != _TRANSCRIPT_ACTIVE_CHUNK_IDand len(turns) != chunk.turn_countand not _manifest_rebuilt):- _rebuild_segment_manifest(session_key)+ _repair_manifest_chunk_count(+ session_key,+ chunk.chunk_id,+ len(turns),+ stats=stats,+ )return _select_transcript_page(session_key,limit=limit,before=before,+ stats=stats,_manifest_rebuilt=True,)local_upper = min(local_upper, len(turns))for turn_index in range(local_upper - 1, -1, -1):ordinal = chunk.start_ordinal + turn_index- turn = turns[turn_index]+ turn, compacted_delta_records = _compact_completed_stream_deltas(+ turns[turn_index]+ )+ stats.compacted_delta_records += compacted_delta_records+ turn_record_count = len(turn)+ turn_bytes = _records_bytes(turn)+ exceeds_records = (+ selected_record_count + turn_record_count > _MAX_TRANSCRIPT_PAGE_RECORDS+ )+ exceeds_bytes = selected_bytes + turn_bytes > _MAX_TRANSCRIPT_PAGE_BYTES+ if exceeds_records:+ stats.capped_by_records = True+ if exceeds_bytes:+ stats.capped_by_bytes = True+ if selected and (exceeds_records or exceeds_bytes):+ budget_reached = True+ break+ if exceeds_records or exceeds_bytes:+ turn = _trim_oversized_turn(+ turn,+ max_records=_MAX_TRANSCRIPT_PAGE_RECORDS,+ max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,+ )+ turn_record_count = len(turn)+ turn_bytes = _records_bytes(turn)+ stats.truncated_oversized_turn = Trueselected.append(_TranscriptTurnRef(ordinal, turn))+ selected_record_count += turn_record_count+ selected_bytes += turn_bytes+ replay_started = time.perf_counter()selected_message_count += len(replay_transcript_to_ui_messages(turn))+ stats.replay_ms += int((time.perf_counter() - replay_started) * 1000)if selected_message_count >= page_limit:break- if selected_message_count >= page_limit:+ if selected_message_count >= page_limit or budget_reached:breakselected_chronological = list(reversed(selected))@@ -616,6 +941,8 @@ def _select_transcript_page(turn_ordinal=ref.ordinal,)]+ stats.selected_records = len(lines)+ stats.selected_bytes = selected_bytesif not selected_chronological:return [], {"before_cursor": None,@@ -635,8 +962,11 @@ def _select_transcript_page(chunks,first_ref.ordinal,turn_cache,+ stats=stats,),}+ if stats.truncated_oversized_turn:+ page["truncated_oversized_turn"] = Truereturn lines, page@@ -691,10 +1021,24 @@ def _record_for_append(obj: dict[str, Any]) -> dict[str, Any]:return record+def _compact_active_completed_streams(session_key: str) -> None:+ path = webui_transcript_path(session_key)+ turns, compacted_delta_records = _compact_completed_turns(+ _split_transcript_turns(_read_transcript_file(path))+ )+ if compacted_delta_records:+ _write_records_to_path(path, _flatten_turns(turns))++def append_transcript_object(session_key: str, obj: dict[str, Any]) -> None:record = _record_for_append(obj)_append_to_active_transcript(session_key, record)+ if record.get("event") in {"delta", "reasoning_delta"}:+ _ACTIVE_TRANSCRIPTS_WITH_DELTAS.add(session_key)if record.get("event") == "turn_end":+ if session_key in _ACTIVE_TRANSCRIPTS_WITH_DELTAS:+ _compact_active_completed_streams(session_key)+ _ACTIVE_TRANSCRIPTS_WITH_DELTAS.discard(session_key)_rotate_active_transcript_if_needed(session_key)@@ -977,6 +1321,7 @@ def write_session_messages_as_transcript(def delete_webui_transcript(session_key: str) -> bool:+ _ACTIVE_TRANSCRIPTS_WITH_DELTAS.discard(session_key)removed = Falsefor path in (webui_transcript_path(session_key), _legacy_webui_thread_path(session_key)):if not path.is_file():@@ -1225,17 +1570,6 @@ def _split_transcript_turns(lines: list[dict[str, Any]]) -> list[list[dict[str,return turns-def _annotate_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:- return [- record- for turn_ordinal, turn in enumerate(_split_transcript_turns(lines))- for record in _records_with_replay_identity(- turn,- turn_ordinal=turn_ordinal,- )- ]--def _stable_record_digest(record: dict[str, Any]) -> str:persisted = {key: value@@ -2670,14 +3004,16 @@ def build_webui_thread_response(limit: int | None = None,direction: str | None = None,before: str | None = None,+ stats: TranscriptReplayStats | None = None,) -> dict[str, Any] | None:"""Return a payload compatible with ``WebuiThreadPersistedPayload``."""- paginated = limit is not None or direction is not None or before is not None- page: dict[str, Any] | None = None- if paginated:- lines, page = _select_transcript_page(session_key, limit=limit, before=before)- else:- lines = _annotate_replay_identities(read_transcript_lines(session_key))+ replay_stats = stats or TranscriptReplayStats()+ lines, page = _select_transcript_page(+ session_key,+ limit=limit,+ before=before,+ stats=replay_stats,+ )if not lines and active_turn_started_at is None:return Noneneeds_user_backfill = _needs_user_event_backfill(lines)@@ -2696,12 +3032,14 @@ def build_webui_thread_response(lines = _recover_incomplete_turns(lines, session_turns)lines = _ensure_replay_identities(lines)fork_boundary = fork_boundary_message_count(lines)+ replay_started = time.perf_counter()msgs = replay_transcript_to_ui_messages(lines,augment_user_media=augment_user_media,augment_assistant_media=augment_assistant_media,augment_assistant_text=augment_assistant_text,)+ replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000)payload: dict[str, Any] = {"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION,"sessionKey": session_key,@@ -2717,9 +3055,8 @@ def build_webui_thread_response(),"active_turn_id": active_turn_id,}- if page is not None:- page["loaded_message_count"] = len(msgs)- payload["page"] = page+ page["loaded_message_count"] = len(msgs)+ payload["page"] = pageif fork_boundary is not None:payload["fork_boundary_message_count"] = fork_boundaryreturn payloaddiff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex 9cef0f137..b2cf217d2 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -10,11 +10,13 @@ Also houses shared HTTP utility functions used by both this module andfrom __future__ import annotationsimport asyncio+import hashlibimport jsonimport mimetypesimport reimport timefrom collections.abc import Awaitable, Callable, Mapping+from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, castfrom urllib.parse import quote, unquote, urlsplit, urlunsplit@@ -40,9 +42,8 @@ from nanobot.webui.file_preview import (file_preview_payload,)from nanobot.webui.gateway_tokens import GatewayTokenStore, token_response_payload-from nanobot.webui.http_utils import (- accepts_gzip as _accepts_gzip,-)+from nanobot.webui.http_utils import JSONResponseMetrics+from nanobot.webui.http_utils import accepts_gzip as _accepts_gzipfrom nanobot.webui.http_utils import (case_insensitive_header as _case_insensitive_header,)@@ -128,7 +129,7 @@ from nanobot.webui.skills_marketplace import (trending_marketplace_skills,)from nanobot.webui.thread_disk import delete_webui_thread-from nanobot.webui.transcript import build_webui_thread_response+from nanobot.webui.transcript import TranscriptReplayStats, build_webui_thread_responsefrom nanobot.webui.workspaces import WebUIWorkspaceController_SLOW_WEBUI_HTTP_LOG_MS = 1_000@@ -136,6 +137,16 @@ _WEBUI_MUTATION_PAYLOAD_ATTR = "_nanobot_webui_mutation_payload"_WEBUI_MUTATION_REQUEST_ATTR = "_nanobot_webui_mutation_request"_NO_STORE_HEADERS = [("Cache-Control", "no-store")]++@dataclass(slots=True)+class _WebUIThreadDiagnostics:+ transcript: TranscriptReplayStats = field(default_factory=TranscriptReplayStats)+ response: JSONResponseMetrics = field(default_factory=JSONResponseMetrics)+ session_hash: str = ""+ build_ms: float = 0.0+ total_ms: float = 0.0+ event_loop_lag_ms: float = 0.0+_WEBUI_MUTATION_PATHS = {"automation.enable": "/api/webui/automations/enable","automation.disable": "/api/webui/automations/disable",@@ -566,6 +577,8 @@ class GatewayHTTPHandler:returnif not (path.startswith("/api/") or path == "/webui/bootstrap"):return+ if path.endswith("/webui-thread"):+ returnstatus = getattr(response, "status_code", None)self._log.warning("slow webui http route path={} status={} duration_ms={}",@@ -706,7 +719,7 @@ class GatewayHTTPHandler:async def _dispatch_session_routes(self, request: WsRequest, got: str) -> Response | None:m = re.match(r"^/api/sessions/([^/]+)/webui-thread$", got)if m:- return self._handle_webui_thread_get(request, m.group(1))+ return await self._handle_webui_thread_get_async(request, m.group(1))m = re.match(r"^/api/sessions/([^/]+)/context$", got)if m:@@ -816,7 +829,88 @@ class GatewayHTTPHandler:cleaned.append(row)return {"sessions": cleaned}- def _handle_webui_thread_get(self, request: WsRequest, key: str) -> Response:+ async def _handle_webui_thread_get_async(self, request: WsRequest, key: str) -> Response:+ diagnostics = _WebUIThreadDiagnostics()+ loop = asyncio.get_running_loop()+ expected_sample_at = loop.time() + 0.05+ max_lag_s = 0.0+ active = True+ timer: asyncio.TimerHandle++ def sample_event_loop_lag() -> None:+ nonlocal expected_sample_at, max_lag_s, timer+ now = loop.time()+ max_lag_s = max(max_lag_s, now - expected_sample_at)+ expected_sample_at = now + 0.05+ if active:+ timer = loop.call_later(0.05, sample_event_loop_lag)++ timer = loop.call_later(0.05, sample_event_loop_lag)+ started = time.perf_counter()+ try:+ response = await asyncio.to_thread(+ self._handle_webui_thread_get,+ request,+ key,+ diagnostics=diagnostics,+ )+ finally:+ active = False+ timer.cancel()+ diagnostics.total_ms = (time.perf_counter() - started) * 1000+ diagnostics.event_loop_lag_ms = max_lag_s * 1000+ self._log_webui_thread_diagnostics(response, diagnostics)+ return response++ def _log_webui_thread_diagnostics(+ self,+ response: Response,+ diagnostics: _WebUIThreadDiagnostics,+ ) -> None:+ stats = diagnostics.transcript+ if not (+ diagnostics.total_ms >= _SLOW_WEBUI_HTTP_LOG_MS+ or stats.manifest_rebuilt+ or stats.capped_by_bytes+ or stats.capped_by_records+ ):+ return+ self._log.warning(+ "webui thread replay session_hash={} status={} limit={} source_bytes={} "+ "parsed_records={} selected_bytes={} selected_records={} compacted_deltas={} "+ "manifest_rebuilt={} manifest_rebuild_ms={} capped_bytes={} capped_records={} "+ "truncated_turn={} replay_ms={} build_ms={} json_ms={} gzip_ms={} gzip={} "+ "response_bytes={} event_loop_lag_ms={} total_ms={}",+ diagnostics.session_hash or "unknown",+ response.status_code,+ stats.effective_limit,+ stats.source_bytes,+ stats.parsed_records,+ stats.selected_bytes,+ stats.selected_records,+ stats.compacted_delta_records,+ stats.manifest_rebuilt,+ stats.manifest_rebuild_ms,+ stats.capped_by_bytes,+ stats.capped_by_records,+ stats.truncated_oversized_turn,+ stats.replay_ms,+ round(diagnostics.build_ms, 1),+ round(diagnostics.response.json_encode_ms, 1),+ round(diagnostics.response.gzip_ms, 1),+ diagnostics.response.gzip_enabled,+ diagnostics.response.response_bytes,+ round(diagnostics.event_loop_lag_ms, 1),+ round(diagnostics.total_ms, 1),+ )++ def _handle_webui_thread_get(+ self,+ request: WsRequest,+ key: str,+ *,+ diagnostics: _WebUIThreadDiagnostics | None = None,+ ) -> Response:if not self.check_api_token(request):return _http_error(401, "Unauthorized")decoded_key = _decode_api_key(key)@@ -824,6 +918,8 @@ class GatewayHTTPHandler:return _http_error(400, "invalid session key")if not _is_websocket_channel_session_key(decoded_key):return _http_error(404, "session not found")+ if diagnostics is not None:+ diagnostics.session_hash = hashlib.sha256(decoded_key.encode("utf-8")).hexdigest()[:12]scope = self.workspaces.scope_for_session_key(decoded_key)def load_session_messages() -> list[dict[str, Any]] | None:@@ -864,6 +960,7 @@ class GatewayHTTPHandler:active_turn_transcript_persistence_failed = (websocket_turn_transcript_persistence_failed(chat_id))+ build_started = time.perf_counter()data = build_webui_thread_response(decoded_key,augment_user_media=self.media.augment_transcript_media,@@ -881,13 +978,17 @@ class GatewayHTTPHandler:limit=limit,direction=direction,before=before,+ stats=diagnostics.transcript if diagnostics is not None else None,)+ if diagnostics is not None:+ diagnostics.build_ms = (time.perf_counter() - build_started) * 1000if data is None:return _http_error(404, "webui thread not found")data["workspace_scope"] = scope.payload()return _http_json_response(data,accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),+ metrics=diagnostics.response if diagnostics is not None else None,)def _handle_file_preview(self, request: WsRequest, key: str) -> Response:diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.pyindex ac87b7759..04e2c5ebf 100644--- a/tests/utils/test_webui_transcript.py+++ b/tests/utils/test_webui_transcript.py@@ -2,7 +2,9 @@from __future__ import annotations+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Path+from threading import Event, Lockimport pytest@@ -10,6 +12,7 @@ import nanobot.webui.transcript as transcript_modulefrom nanobot.session.history_visibility import HIDDEN_HISTORY_METAfrom nanobot.webui.transcript import (WEBUI_TRANSCRIPT_SCHEMA_VERSION,+ TranscriptReplayStats,append_fork_marker,append_transcript_object,build_webui_thread_response,@@ -128,6 +131,60 @@ def test_segmented_transcript_paginates_latest_and_older_without_overlap(]+def test_missing_page_query_uses_bounded_default(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ monkeypatch.setattr("nanobot.webui.transcript._DEFAULT_TRANSCRIPT_PAGE_LIMIT", 4)+ key = "websocket:bounded-default"+ for idx in range(1, 5):+ _append_numbered_turn(key, "bounded-default", idx)++ latest = build_webui_thread_response(key)++ assert latest is not None+ assert _message_contents(latest) == _numbered_turn_texts(3, 4)+ assert latest["page"]["has_more_before"] is True+ assert latest["page"]["loaded_message_count"] == 4+++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)+ monkeypatch.setattr("nanobot.webui.transcript._MAX_TRANSCRIPT_PAGE_BYTES", 1_200)+ key = "websocket:oversized-turn"+ append_transcript_object(+ key,+ {"event": "user", "chat_id": "oversized-turn", "text": "question"},+ )+ for idx in range(20):+ append_transcript_object(+ key,+ {+ "event": "message",+ "chat_id": "oversized-turn",+ "kind": "progress",+ "text": f"progress {idx} " + ("x" * 160),+ },+ )+ append_transcript_object(+ key,+ {"event": "message", "chat_id": "oversized-turn", "text": "final answer"},+ )+ append_transcript_object(key, {"event": "turn_end", "chat_id": "oversized-turn"})+ stats = TranscriptReplayStats()++ latest = build_webui_thread_response(key, stats=stats)++ assert latest is not None+ assert stats.selected_records <= 5+ assert stats.selected_bytes <= 1_200+ assert stats.capped_by_records is True+ assert stats.capped_by_bytes is True+ assert stats.truncated_oversized_turn is True+ assert latest["page"]["truncated_oversized_turn"] is True+ assert latest["messages"][0]["content"] == "question"+ assert latest["messages"][-1]["content"] == "final answer"++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"@@ -202,6 +259,83 @@ def test_segment_manifest_can_be_rebuilt_when_missing_or_corrupt(tmp_path, monkeassert manifest.read_text(encoding="utf-8").lstrip().startswith("{")+def test_manifest_repair_is_single_flight(tmp_path, monkeypatch) -> None:+ key = "websocket:manifest-single-flight"+ _write_segmented_turns(tmp_path, monkeypatch, key, "manifest-single-flight", 4)+ manifest = webui_transcript_segments_dir(key) / "manifest.json"+ manifest.write_text("{not json", encoding="utf-8")+ original = transcript_module._rebuild_segment_manifest+ rebuild_started = Event()+ release_rebuild = Event()+ calls = 0+ calls_lock = Lock()++ def slow_rebuild(*args, **kwargs):+ nonlocal calls+ with calls_lock:+ calls += 1+ rebuild_started.set()+ assert release_rebuild.wait(2)+ return original(*args, **kwargs)++ monkeypatch.setattr(transcript_module, "_rebuild_segment_manifest", slow_rebuild)+ with ThreadPoolExecutor(max_workers=2) as executor:+ first = executor.submit(transcript_module._read_segment_manifest_entries, key)+ assert rebuild_started.wait(2)+ second = executor.submit(transcript_module._read_segment_manifest_entries, key)+ release_rebuild.set()+ assert first.result(timeout=2) == second.result(timeout=2)++ assert calls == 1+++def test_page_read_compacts_legacy_immutable_segment(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ key = "websocket:compact-segment"+ segment_id = "000001"+ rows = [+ {"event": "user", "chat_id": "compact-segment", "text": "q"},+ {+ "event": "delta",+ "chat_id": "compact-segment",+ "stream_id": "answer-1",+ "text": "answer ",+ },+ {+ "event": "delta",+ "chat_id": "compact-segment",+ "stream_id": "answer-1",+ "text": "done",+ },+ {+ "event": "stream_end",+ "chat_id": "compact-segment",+ "stream_id": "answer-1",+ },+ {"event": "turn_end", "chat_id": "compact-segment"},+ ]+ segment_path = transcript_module._segment_file_path(key, segment_id)+ transcript_module._write_records_to_path(segment_path, rows)+ transcript_module._write_segment_manifest(+ key,+ [transcript_module._segment_manifest_entry(key, segment_id)],+ )+ stats = TranscriptReplayStats()++ latest = build_webui_thread_response(key, stats=stats)+ persisted = transcript_module._read_transcript_file(segment_path)++ assert latest is not None+ assert _message_contents(latest) == ["q", "answer done"]+ assert [record["event"] for record in persisted] == [+ "user",+ "stream_end",+ "turn_end",+ ]+ assert stats.compacted_delta_records == 2+ assert transcript_module._load_segment_manifest_entries(key) is not None++def test_rotation_does_not_reread_existing_segments(tmp_path, monkeypatch) -> None:key = "websocket:manifest-append"_write_segmented_turns(tmp_path, monkeypatch, key, "manifest-append", 4)@@ -397,6 +531,33 @@ def test_replay_delta_and_turn_end(tmp_path, monkeypatch) -> None:assert msgs[1]["latencyMs"] == 42+def test_completed_turn_persists_canonical_stream_end_text(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ key = "websocket:compact-deltas"+ for event in (+ {"event": "user", "chat_id": "compact-deltas", "text": "q"},+ {"event": "reasoning_delta", "chat_id": "compact-deltas", "text": "think "},+ {"event": "reasoning_delta", "chat_id": "compact-deltas", "text": "more"},+ {"event": "reasoning_end", "chat_id": "compact-deltas"},+ {"event": "delta", "chat_id": "compact-deltas", "text": "answer "},+ {"event": "delta", "chat_id": "compact-deltas", "text": "done"},+ {"event": "stream_end", "chat_id": "compact-deltas"},+ {"event": "turn_end", "chat_id": "compact-deltas"},+ ):+ append_transcript_object(key, event)++ lines = read_transcript_lines(key)++ assert [record["event"] for record in lines] == [+ "user",+ "reasoning_end",+ "stream_end",+ "turn_end",+ ]+ assert lines[1]["text"] == "think more"+ assert lines[2]["text"] == "answer done"++def test_replay_canonical_completed_stream_records() -> None:msgs = replay_transcript_to_ui_messages([{"event": "user", "chat_id": "canonical", "text": "q"},diff --git a/tests/webui/test_http_utils.py b/tests/webui/test_http_utils.pyindex e23710332..9eefb67e2 100644--- a/tests/webui/test_http_utils.py+++ b/tests/webui/test_http_utils.py@@ -3,18 +3,28 @@import gzipimport json-from nanobot.webui.http_utils import http_json_response+from nanobot.webui.http_utils import JSONResponseMetrics, http_json_responsedef test_http_json_response_compresses_large_payload_when_gzip_is_accepted() -> None:payload = {"message": "响应内容" * 2_000}+ metrics = JSONResponseMetrics()- response = http_json_response(payload, accept_encoding="br, gzip; q=0.5")+ response = http_json_response(+ payload,+ accept_encoding="br, gzip; q=0.5",+ metrics=metrics,+ )assert response.headers["Content-Encoding"] == "gzip"assert response.headers["Vary"] == "Accept-Encoding"assert int(response.headers["Content-Length"]) == len(response.body)assert json.loads(gzip.decompress(response.body)) == payload+ assert metrics.gzip_enabled is True+ assert metrics.gzip_ms >= 0+ assert metrics.json_encode_ms >= 0+ assert metrics.uncompressed_bytes == len(gzip.decompress(response.body))+ assert metrics.response_bytes == len(response.body)def test_http_json_response_preserves_identity_when_gzip_is_rejected() -> None: