fix(webui): preserve oversized turn history with record pagination (#6586)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-11 17:32:47 +08:00
1 parent 5c1083df7f
commit 3c61bcfdf0
34 files changed
+3466 -380

No files matched your search

+25 -4
View File
@@ -40,7 +40,7 @@ _CONTENT_FIELDS = frozenset({
"session_message", "input_id", "response_input_ids", INBOUND_META_LOCAL_MEDIA, "tool_events", "edits", "source", "response_sources", "resuming",
"merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state",
"outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message",
"transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as",
"transcript_incomplete", "stream_id", "text_from_seq", "compaction_id", "phase", "reason", "render_as",
"request_usage", "request_id", "run_id", "sequence", "context_graph", "context_snapshot",
})
@@ -66,6 +66,10 @@ def fact_from_record(record: Mapping[str, Any]) -> HistoryFact:
sequence = record.get("turn_seq")
if sequence is not None and (isinstance(sequence, bool) or not isinstance(sequence, int) or sequence < 0):
raise ValueError("invalid history sequence")
start = record.get("text_from_seq")
if start is not None and (isinstance(start, bool) or not isinstance(start, int)
or sequence is None or not 0 <= start <= sequence):
raise ValueError("invalid history text coverage")
turn_id, phase = record.get("turn_id"), record.get("turn_phase")
if turn_id is not None and (not isinstance(turn_id, str) or len(turn_id) > 128):
raise ValueError("invalid history turn identity")
@@ -96,12 +100,29 @@ def record_from_fact(fact: HistoryFact, key: str, *, expand_graphs: bool = True)
return record
def turn_records(
history: HistoryReader, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None,
def _records_from_entries(
history: HistoryReader, ordinal: int, entries: Sequence[tuple[int, HistoryFact]],
) -> list[dict[str, Any]]:
return [{**record_from_fact(fact, history.key, expand_graphs=False),
"_webui_replay_identity": f"turn:{ordinal}:record:{position}"}
for position, fact in history.read_entries(ordinal, max_records=max_records, max_bytes=max_bytes)]
for position, fact in entries]
def turn_records(history: HistoryReader, ordinal: int) -> list[dict[str, Any]]:
return _records_from_entries(history, ordinal, history.read_entries(ordinal))
def turn_record_page(
history: HistoryReader, ordinal: int, *, start: int, end: int, reverse: bool,
max_records: int, max_bytes: int, allow_oversized: bool = False,
) -> tuple[list[dict[str, Any]], int, int, int]:
page = history.read_entry_page(ordinal, start=start, end=end, reverse=reverse,
max_records=max_records, max_bytes=max_bytes,
allow_oversized=allow_oversized)
if not page.entries:
return [], start, start, 0
return (_records_from_entries(history, ordinal, page.entries), page.entries[0][0],
page.entries[-1][0] + 1, page.source_bytes)
def _read_legacy_file(path: Path) -> list[dict[str, Any]]:
+32 -12
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
import asyncio
import json
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, replace
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias
@@ -94,6 +94,21 @@ class WebUIOutboundTransport(Protocol):
) -> None: ...
@dataclass
class _StreamBuffer:
"""Text and its first wire sequence share the same continuation/reset lifetime."""
chunks: list[str] = field(default_factory=list)
from_seq: int | None = None
def observe(self, event: Mapping[str, Any]) -> None:
if self.from_seq is None:
self.from_seq = event.get("turn_seq")
def snapshot(self) -> dict[str, Any]:
return {"text_from_seq": self.from_seq} if self.from_seq is not None else {}
class WebUIOutboundDelivery:
"""Keep presentation, history and delivery-turn policy out of socket writers."""
@@ -112,8 +127,8 @@ class WebUIOutboundDelivery:
self._temporary_chats = temporary_chats
self._session_projection = session_projection
self._context_graph = ContextGraphObserver(transcripts.sessions)
self._stream_text_buffers: dict[tuple[str, str], list[str]] = {}
self._reasoning_text_buffers: dict[tuple[str, str], list[str]] = {}
self._stream_text_buffers: dict[tuple[str, str], _StreamBuffer] = {}
self._reasoning_text_buffers: dict[tuple[str, str], _StreamBuffer] = {}
async def _project_notification(self, msg: OutboundMessage) -> NotificationProjection | None:
event = msg.event
@@ -486,11 +501,13 @@ class WebUIOutboundDelivery:
payload: StreamWirePayload = {"event": "reasoning_delta", "chat_id": chat_id, "text": delta}
if stream_id is not None:
payload["stream_id"] = stream_id
self._reasoning_text_buffers.setdefault((chat_id, str(stream_id or "")), []).append(delta)
buffered = self._reasoning_text_buffers.setdefault((chat_id, str(stream_id or "")), _StreamBuffer())
buffered.chunks.append(delta)
body: dict[str, Any] = dict(payload)
await self._persist_turn_stream_event(
chat_id, body, completed_text=None, metadata=metadata or {}, phase="reasoning",
)
buffered.observe(body)
await self._fanout(recipients, body, label=" reasoning ")
async def send_reasoning_end(
@@ -501,8 +518,9 @@ class WebUIOutboundDelivery:
payload: StreamWirePayload = {"event": "reasoning_end", "chat_id": chat_id}
if stream_id is not None:
payload["stream_id"] = stream_id
text = "".join(self._reasoning_text_buffers.pop((chat_id, str(stream_id or "")), []))
body: dict[str, Any] = dict(payload)
buffered = self._reasoning_text_buffers.pop((chat_id, str(stream_id or "")), _StreamBuffer())
text = "".join(buffered.chunks)
body: dict[str, Any] = {**payload, **buffered.snapshot()}
await self._persist_turn_stream_event(
chat_id, body, completed_text=text or None, metadata=metadata or {}, phase="reasoning",
)
@@ -535,30 +553,32 @@ class WebUIOutboundDelivery:
if stream_end:
payload = {"event": "stream_end", "chat_id": chat_id}
buffered = (
self._stream_text_buffers.setdefault(stream_key, [])
if merge_next else self._stream_text_buffers.pop(stream_key, [])
self._stream_text_buffers.setdefault(stream_key, _StreamBuffer())
if merge_next else self._stream_text_buffers.pop(stream_key, _StreamBuffer())
)
if delta:
buffered.append(delta)
full_text = "".join(buffered)
buffered.chunks.append(delta)
full_text = "".join(buffered.chunks)
rewritten = self._media.rewrite_local_markdown_images(full_text)
completed_text = rewritten
if delta or rewritten != full_text:
payload["text"] = rewritten
else:
payload = {"event": "delta", "chat_id": chat_id, "text": delta}
self._stream_text_buffers.setdefault(stream_key, []).append(delta)
buffered = self._stream_text_buffers.setdefault(stream_key, _StreamBuffer())
buffered.chunks.append(delta)
if stream_id is not None:
payload["stream_id"] = stream_id
if stream_end and resuming:
payload["resuming"] = True
if stream_end and merge_next:
payload["merge_next"] = True
body: dict[str, Any] = dict(payload)
body: dict[str, Any] = {**payload, **(buffered.snapshot() if stream_end else {})}
await self._persist_turn_stream_event(
chat_id, body, completed_text=completed_text, metadata=metadata or {},
phase="answer", include_source=True,
)
buffered.observe(body)
await self._fanout(recipients, body, label=" stream ")
async def _send_payload(
+203 -125
View File
@@ -46,6 +46,7 @@ from nanobot.webui.history import (
fact_from_record,
initialize_history,
record_from_fact,
turn_record_page,
turn_records,
)
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
@@ -62,8 +63,6 @@ _MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024
_MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024
_WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
_WEBUI_REPLAY_IDENTITY_KEY = "_webui_replay_identity"
_WEBUI_PROJECTION_RECEIPTS_KEY = "_webui_projection_receipts"
_WEBUI_TRACE_DETAIL_UNSAFE_KEY = "_webui_trace_detail_unsafe"
_WEBUI_TRACE_DETAIL_REF_RE = re.compile(
r"^(?P<turn>\d{1,12})\.(?P<message>history-[0-9a-f]{20})$"
)
@@ -200,7 +199,9 @@ def webui_transcript_revision(
class _TranscriptTurnRef(NamedTuple):
ordinal: int
records: list[dict[str, Any]]
trace_details_safe: bool = True
start: int
end: int
total: int
class _SessionBackfillTurn(NamedTuple):
@@ -223,7 +224,7 @@ class _DeferredTraceGroup(NamedTuple):
@dataclass(slots=True)
class TranscriptReplayStats:
"""Bounded, non-sensitive diagnostics for one history replay."""
"""Selected-source page diagnostics; canonical recovery reads are separate."""
effective_limit: int = 0
source_bytes: int = 0
@@ -281,8 +282,6 @@ def _projection_receipts(records: Sequence[Mapping[str, Any]]) -> list[_Projecti
def _compact_completed_stream_deltas(
turn: list[dict[str, Any]],
*,
include_projection_receipts: bool = False,
) -> tuple[list[dict[str, Any]], int]:
if not turn or turn[-1].get("event") != "turn_end":
return turn, 0
@@ -303,15 +302,10 @@ def _compact_completed_stream_deltas(
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
)
if include_projection_receipts:
receipts = _projection_receipts([*(chunk for _, chunk in chunks), record])
if receipts:
completed[_WEBUI_PROJECTION_RECEIPTS_KEY] = receipts
# The sealed snapshot is authoritative even when media rewriting changes
# its text. Only old ends without text need their preceding fragments.
if not isinstance(completed.get("text"), str):
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)
@@ -347,28 +341,34 @@ 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: record.get(_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)
]
def _encode_page_cursor(before_turn_ordinal: int) -> str:
class _PageCursor(NamedTuple):
turn: int
position: int = 0
def _encode_page_cursor(before_turn_ordinal: int, position: int = 0) -> str:
data = {"before_turn": before_turn_ordinal}
if position:
data["position"] = position
raw = json.dumps(
{"before_turn": before_turn_ordinal},
data,
separators=(",", ":"),
ensure_ascii=False,
).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def decode_transcript_cursor(value: str | None) -> int | None:
def decode_transcript_cursor(value: str | None) -> _PageCursor | None:
if not value:
return None
try:
@@ -380,13 +380,13 @@ def decode_transcript_cursor(value: str | None) -> int | None:
return None
cursor_data = cast(dict[str, Any], data)
before_turn = cursor_data.get("before_turn")
position = cursor_data.get("position", 0)
if (
isinstance(before_turn, bool)
or not isinstance(before_turn, int)
or before_turn < 0
isinstance(before_turn, bool) or not isinstance(before_turn, int) or before_turn < 0
or isinstance(position, bool) or not isinstance(position, int) or position < 0
):
return None
return before_turn
return _PageCursor(before_turn, position)
def _coerce_page_limit(limit: int | None) -> int:
@@ -398,7 +398,14 @@ def _coerce_page_limit(limit: int | None) -> int:
def _transcript_turn_at_ordinal(
ordinal: int, *, history: HistoryReader,
) -> list[dict[str, Any]] | None:
return turn_records(history, ordinal) or None
ref = next(history.turns(before=ordinal + 1, after=ordinal), None)
if ref is None or ref.record_count > _MAX_TRANSCRIPT_PAGE_RECORDS or ref.byte_count > _MAX_TRANSCRIPT_PAGE_BYTES:
return None
records, start, end, _ = turn_record_page(
history, ordinal, start=0, end=ref.record_count, reverse=False,
max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
)
return records if start == 0 and end == ref.record_count else None
def _select_transcript_page(
@@ -409,54 +416,86 @@ def _select_transcript_page(
page_limit = _coerce_page_limit(limit)
stats.effective_limit = page_limit
total_turns = history.turn_count
before_ordinal = decode_transcript_cursor(before)
upper = total_turns if before_ordinal is None else min(before_ordinal, total_turns)
after_ordinal = decode_transcript_cursor(after)
before_cursor = decode_transcript_cursor(before)
after_cursor = decode_transcript_cursor(after)
forward = after_cursor is not None
upper = total_turns
if before_cursor is not None:
upper = min(before_cursor.turn + int(before_cursor.position > 0), total_turns)
lower = min(after_cursor.turn, total_turns) if after_cursor is not None else 0
selected: list[_TranscriptTurnRef] = []
event_count = record_count = byte_count = 0
for ref in history.turns(before=upper, after=after_ordinal or 0, reverse=after_ordinal is None):
exceeds_records = record_count + ref.record_count > _MAX_TRANSCRIPT_PAGE_RECORDS
for ref in history.turns(before=upper, after=lower, reverse=not forward):
start, end = 0, ref.record_count
if after_cursor is not None and ref.ordinal == after_cursor.turn:
start = min(after_cursor.position, end)
if before_cursor is not None and ref.ordinal == before_cursor.turn:
end = min(before_cursor.position, end)
if start >= end:
continue
requested_partial = start > 0 or end < ref.record_count
exceeds_records = record_count + end - start > _MAX_TRANSCRIPT_PAGE_RECORDS
exceeds_bytes = byte_count + ref.byte_count > _MAX_TRANSCRIPT_PAGE_BYTES
stats.capped_by_records |= exceeds_records
stats.capped_by_bytes |= exceeds_bytes
if selected and (exceeds_records or exceeds_bytes):
if selected and (requested_partial or exceeds_records or exceeds_bytes):
break
safe = not (exceeds_records or exceeds_bytes)
turn = turn_records(
history, ref.ordinal,
max_records=None if safe else _MAX_TRANSCRIPT_PAGE_RECORDS,
max_bytes=None if safe else _MAX_TRANSCRIPT_PAGE_BYTES,
remaining_records = _MAX_TRANSCRIPT_PAGE_RECORDS - record_count
remaining_bytes = _MAX_TRANSCRIPT_PAGE_BYTES - byte_count
turn, first_position, end_position, source_bytes = turn_record_page(
history, ref.ordinal, start=start, end=end, reverse=not forward,
max_records=remaining_records, max_bytes=remaining_bytes,
allow_oversized=not selected,
)
stats.parsed_records += len(turn)
stats.source_bytes += ref.byte_count if safe else _records_bytes(turn)
turn, dropped = _compact_completed_stream_deltas(turn, include_projection_receipts=True)
stats.compacted_delta_records += dropped
if not safe:
stats.truncated_oversized_turn = True
selected.append(_TranscriptTurnRef(ref.ordinal, turn, safe))
record_count += len(turn)
byte_count += _records_bytes(turn)
event_count += _client_projection_page_event_count(turn)
if event_count >= page_limit:
stats.source_bytes += source_bytes
if source_bytes > remaining_bytes or (len(turn) < end - start and len(turn) < remaining_records):
stats.capped_by_bytes = True
if not turn:
break
chronological = selected if after_ordinal is not None else list(reversed(selected))
partial = first_position > 0 or end_position < ref.record_count
# A partial turn is always a page of its own, even when a size estimate
# from older stored metadata understated the actual encoded bytes.
if selected and partial:
break
raw_count = len(turn)
if partial:
stats.truncated_oversized_turn = True
else:
turn, dropped = _compact_completed_stream_deltas(turn)
stats.compacted_delta_records += dropped
selected.append(_TranscriptTurnRef(ref.ordinal, turn, first_position, end_position, ref.record_count))
record_count += raw_count
byte_count += source_bytes
event_count += _client_projection_page_event_count(turn)
if partial or event_count >= page_limit:
break
chronological = selected if forward else list(reversed(selected))
records = [record for ref in chronological for record in _records_with_replay_identity(
ref.records, turn_ordinal=ref.ordinal, trace_details_safe=ref.trace_details_safe,
ref.records, turn_ordinal=ref.ordinal,
)]
stats.selected_records, stats.selected_bytes = len(records), byte_count
stats.selected_records, stats.selected_bytes = len(records), _records_bytes(records)
if not chronological:
return [], {"before_cursor": None, "has_more_before": False, "after_cursor": None,
"has_more_after": False, "loaded_event_count": 0, "user_message_offset": 0}
first, last = chronological[0].ordinal, chronological[-1].ordinal
first, last = chronological[0], chronological[-1]
has_more_before = first.start > 0 or first.ordinal > 0
has_more_after = last.end < last.total or last.ordinal + 1 < total_turns
revision = history.revision
page: dict[str, Any] = {
"before_cursor": _encode_page_cursor(first) if first else None,
"has_more_before": first > 0,
"after_cursor": _encode_page_cursor(last + 1) if last + 1 < total_turns else None,
"has_more_after": last + 1 < total_turns, "loaded_event_count": 0,
"user_message_offset": history.user_count_before(first),
"history_generation": revision[0] if revision is not None else None,
"before_cursor": _encode_page_cursor(first.ordinal, first.start) if has_more_before else None,
"has_more_before": has_more_before,
"after_cursor": (
_encode_page_cursor(last.ordinal, last.end) if last.end < last.total
else _encode_page_cursor(last.ordinal + 1) if has_more_after else None
),
"has_more_after": has_more_after, "loaded_event_count": 0,
"user_message_offset": history.user_count_before(first.ordinal, first.start),
}
if stats.truncated_oversized_turn:
if first.start > 0 or first.end < first.total:
page["truncated_oversized_turn"] = True
page["record_range"] = {"turn": first.ordinal, "start": first.start, "end": first.end}
return records, page
@@ -1034,17 +1073,19 @@ def _user_recovery_signature(event: dict[str, Any]) -> str:
return json.dumps(fields, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def _find_unique_session_turn_by_user(
def _find_recoverable_session_turn(
session_turns: list[_SessionBackfillTurn],
user_event: dict[str, Any],
user_events: list[dict[str, Any]],
) -> _SessionBackfillTurn | None:
signature = _user_recovery_signature(user_event)
if len(user_events) != 1:
return None
signature = _user_recovery_signature(user_events[0])
matches = [
turn
for turn in session_turns
if _user_recovery_signature(turn.user_event) == signature
]
return matches[0] if len(matches) == 1 else None
return matches[0] if len(matches) == 1 and matches[0].assistant_records else None
def _is_recoverable_answer_record(record: dict[str, Any]) -> bool:
@@ -1066,6 +1107,29 @@ def _needs_incomplete_turn_recovery(lines: list[dict[str, Any]]) -> bool:
)
def _recover_incomplete_fragment(
lines: list[dict[str, Any]], session_turn: _SessionBackfillTurn, *, terminal: bool,
) -> list[dict[str, Any]]:
retained = [record for record in lines if not _is_recoverable_answer_record(record)]
if not terminal:
return retained
turn_end = retained.pop()
stable_end_ms = _valid_created_at_ms(turn_end.get("created_at_ms"))
turn_id = turn_end.get("turn_id")
for index, source in enumerate(session_turn.assistant_records):
answer = dict(source)
if isinstance(turn_id, str) and turn_id:
answer["turn_id"] = turn_id
answer["turn_phase"] = "answer"
if stable_end_ms is not None:
answer["created_at_ms"] = max(0, stable_end_ms - len(session_turn.assistant_records) + index)
retained.append(answer)
completed_end = dict(turn_end)
completed_end.pop(WEBUI_TRANSCRIPT_INCOMPLETE_KEY, None)
retained.append(completed_end)
return retained
def _recover_incomplete_turns(
lines: list[dict[str, Any]],
session_turns: list[_SessionBackfillTurn],
@@ -1082,44 +1146,18 @@ def _recover_incomplete_turns(
continue
user_events = [record for record in turn if record.get("event") == "user"]
if len(user_events) != 1:
recovered.extend(turn)
continue
session_turn = _find_unique_session_turn_by_user(session_turns, user_events[0])
if session_turn is None or not session_turn.assistant_records:
session_turn = _find_recoverable_session_turn(session_turns, user_events)
if session_turn is None:
recovered.extend(turn)
continue
stable_end_ms = _valid_created_at_ms(turn_end.get("created_at_ms"))
turn_id = turn_end.get("turn_id")
answer_records: list[dict[str, Any]] = []
for index, source in enumerate(session_turn.assistant_records):
answer = dict(source)
if isinstance(turn_id, str) and turn_id:
answer["turn_id"] = turn_id
answer["turn_phase"] = "answer"
if stable_end_ms is not None:
answer["created_at_ms"] = max(
0,
stable_end_ms - len(session_turn.assistant_records) + index,
)
answer_records.append(answer)
# Session history is the durable source of the completed answer. Keep
# traces/reasoning/file edits, but replace any partial answer fragments.
recovered.extend(
record
for record in turn[:-1]
if not _is_recoverable_answer_record(record)
)
recovered.extend(answer_records)
completed_end = dict(turn_end)
completed_end.pop(WEBUI_TRANSCRIPT_INCOMPLETE_KEY, None)
recovered.append(completed_end)
recovered.extend(_recover_incomplete_fragment(turn, session_turn, terminal=True))
return recovered
def _needs_user_event_backfill(lines: list[dict[str, Any]], history: HistoryReader) -> bool:
def _needs_user_event_backfill(
lines: list[dict[str, Any]], history: HistoryReader, *, legacy: bool = True,
) -> bool:
referenced_inputs = {
input_id
for record in lines
@@ -1127,7 +1165,7 @@ def _needs_user_event_backfill(lines: list[dict[str, Any]], history: HistoryRead
for input_id in cast(list[object], references)
if isinstance(input_id, str) and input_id
}
return any(not history.has_input(input_id) for input_id in referenced_inputs) or any(
return any(not history.has_input(input_id) for input_id in referenced_inputs) or legacy and any(
not any(record.get("event") == "user" or isinstance(record.get("response_input_ids"), list) for record in turn)
and _transcript_turn_signature(turn)
for turn in _split_transcript_turns(lines)
@@ -1242,8 +1280,6 @@ def _media_from_signed_urls(value: Any) -> list[dict[str, Any]]:
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
@@ -1353,7 +1389,7 @@ def build_webui_trace_detail_response(
turn = _transcript_turn_at_ordinal(ordinal, history=history)
if turn is None:
return None
turn, _ = _compact_completed_stream_deltas(turn, include_projection_receipts=True)
turn, _ = _compact_completed_stream_deltas(turn)
lines = _records_with_replay_identity(turn, turn_ordinal=ordinal)
for group in _client_projection_deferred_trace_groups(lines).values():
first = lines[group.start]
@@ -1412,9 +1448,6 @@ def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]:
fields["created_at_ms"] = created_at_ms
if isinstance(input_id := record.get("input_id"), str):
fields["input_id"] = input_id
receipts = record.get(_WEBUI_PROJECTION_RECEIPTS_KEY)
if receipts:
fields["projection_receipts"] = receipts
return fields
@@ -1487,6 +1520,8 @@ def _client_projection_event(
if event in {"delta", "stream_end", "reasoning_delta", "reasoning_end"}:
projected = {"event": event, **common}
if record.get("text_from_seq") is not None:
projected["text_from_seq"] = record["text_from_seq"]
stream_id = record.get("stream_id")
if isinstance(stream_id, str) and stream_id:
projected["stream_id"] = stream_id
@@ -1703,10 +1738,11 @@ def _client_projection_events(
augment_user_media: Callable[[list[str], list[str]], list[dict[str, Any]]] | None,
augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None,
augment_assistant_text: Callable[[str], str] | None,
defer_traces: bool = True,
) -> tuple[list[dict[str, Any]], int | None]:
events: list[dict[str, Any]] = []
fork_boundary_event_index: int | None = None
deferred_groups = _client_projection_deferred_trace_groups(lines)
deferred_groups = _client_projection_deferred_trace_groups(lines) if defer_traces else {}
deferred_until = 0
for index, record in enumerate(lines):
if index < deferred_until and record.get("event") != "model_request":
@@ -1865,28 +1901,59 @@ def build_webui_thread_response(
session_turns = _session_backfill_turns(session_key, session_messages or [])
return session_turns
# Truncation can discard every reference that proves an input is missing.
# Complete pages keep the ordinary missing-input fast-path decision.
if replay_stats.truncated_oversized_turn or _needs_user_event_backfill(lines, history):
record_range = page.get("record_range")
fragment = record_range is not None
ref = next(history.turns(after=record_range["turn"], before=record_range["turn"] + 1), None) if record_range else None
needs_backfill = (
history.has_missing_input_references(ref.ordinal)
or (ref.user_count == 0 and record_range["start"] == 0 and history.has_navigation_answer(ref.ordinal))
) if ref is not None and record_range is not None else _needs_user_event_backfill(lines, history, legacy=not fragment)
backfill_plan: dict[int, list[tuple[int, dict[str, Any]]]] = {}
if needs_backfill:
view, _ = _prompt_view_snapshot(
session_key, history=history, session_turns_loader=load_session_turns,
session_version_loader=session_version_loader,
)
backfill_plan = view.backfill_plan
recovered_lines: list[dict[str, Any]] = []
selected_turns = _split_transcript_turns(lines)
for turn in selected_turns:
# Page selection assigns this absolute identity before any recovery.
for turn in _split_transcript_turns(lines):
ordinal = int(turn[0][_WEBUI_REPLAY_IDENTITY_KEY].split(":")[1])
for anchor, user in view.backfill_plan.get(ordinal, []):
# Positions are stable even when the record at the anchor was
# removed by oversized-turn selection or delta compaction.
for anchor, user in backfill_plan.get(ordinal, []):
if record_range is not None and not record_range["start"] <= anchor < record_range["end"]:
continue
index = next((i for i, record in enumerate(turn)
if (identity := record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")).startswith(f"turn:{ordinal}:record:")
and int(identity.rsplit(":", 1)[1]) >= anchor), len(turn))
turn.insert(index, dict(user))
recovered_lines.extend(turn)
lines = recovered_lines
if _needs_incomplete_turn_recovery(lines):
if record_range is not None:
if ref is not None and ref.user_count == 1:
ordinal = ref.ordinal
terminal = record_range["end"] == ref.record_count
if terminal:
incomplete = bool(lines and lines[-1].get("event") == "turn_end"
and lines[-1].get(WEBUI_TRANSCRIPT_INCOMPLETE_KEY) is True)
else:
incomplete = history.incomplete_completion_marker(ordinal, ref.record_count - 1)
if incomplete and (position := history.unique_user_position(ordinal)) is not None:
identity = f"turn:{ordinal}:record:{position}"
user = next((record for record in lines if record.get(_WEBUI_REPLAY_IDENTITY_KEY) == identity), None)
if user is None:
records, _, _, _ = turn_record_page(
history, ordinal, start=position, end=position + 1, reverse=False,
max_records=1, max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES, allow_oversized=True,
)
if records:
user = records[0]
if user is not None:
users = [user, *(item for _, item in backfill_plan.get(ordinal, []))]
session_turn = _find_recoverable_session_turn(load_session_turns(), users)
if session_turn is not None:
lines = _recover_incomplete_fragment(lines, session_turn, terminal=terminal)
if terminal:
page["recovered_answers"] = True
elif _needs_incomplete_turn_recovery(lines):
lines = _recover_incomplete_turns(lines, load_session_turns())
bang_inputs = {
record.get("turn_id") for record in lines
@@ -1899,7 +1966,7 @@ def build_webui_thread_response(
and record.get("render_as") != "text" and record.get("turn_id") in bang_inputs
and isinstance(record.get("turn_id"), str)
}
if legacy_shell_candidates:
if legacy_shell_candidates and not fragment:
if session_messages is None and session_messages_loader is not None:
session_messages = session_messages_loader()
shell_turns = {
@@ -1934,10 +2001,10 @@ def build_webui_thread_response(
augment_user_media=augment_user_media,
augment_assistant_media=augment_assistant_media,
augment_assistant_text=augment_assistant_text,
defer_traces=not fragment,
)
if not include_model_requests:
# Select pages and stable identities before capability filtering, so an
# older client's cursors still navigate the same durable transcript.
# Select pages and stable identities before filtering request telemetry.
if fork_boundary_event_index is not None:
fork_boundary_event_index = sum(
event["event"] != "model_request" for event in events[:fork_boundary_event_index]
@@ -1996,14 +2063,16 @@ def prompt_index_revision(session_key: str, session_version: tuple[str, int] | N
return webui_transcript_revision(session_key, history=history, variant={"session_version": session_version})
def _prompt_summary(record: dict[str, Any], ordinal: int, answer: str) -> PromptSummary:
def _prompt_summary(
record: dict[str, Any], ordinal: int, answer: str, position: int = 0,
) -> PromptSummary:
return {
"id": _client_projection_event_id(record),
"inputId": str(record.get("input_id") or ""),
"preview": str(record.get("text") or "").strip()[:320],
"answerPreview": answer,
"createdAt": _valid_created_at_ms(record.get("created_at_ms")) or 0,
"cursor": _encode_page_cursor(ordinal),
"cursor": _encode_page_cursor(ordinal, position),
"turnId": str(record.get("turn_id") or ""),
}
@@ -2035,20 +2104,22 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
signature[0][:240] if signature else "", has_user,
tuple(dict.fromkeys(response_inputs[ordinal])) if ordinal in response_inputs else None,
))
seen_turns: set[str] = set()
seen_messages: set[str] = set()
for index, record in enumerate(records):
if record.get("event") != "user":
continue
turn_id = str(record.get("turn_id") or "")
position = int(record[_WEBUI_REPLAY_IDENTITY_KEY].rsplit(":", 1)[1])
input_id = record.get("input_id")
if isinstance(input_id, str) and input_id:
input_ids.add(input_id)
result.append(_prompt_summary(record, ordinal, answers.get(input_id, "")))
result.append(_prompt_summary(record, ordinal, answers.get(input_id, ""), position))
continue
if turn_id and turn_id in seen_turns:
continue
if turn_id:
seen_turns.add(turn_id)
provenance = normalize_session_message_ui_metadata(record.get("session_message"))
if provenance:
message_id = str(provenance["message_id"])
if message_id in seen_messages:
continue
seen_messages.add(message_id)
answer = ""
for following in records[index + 1:]:
if following.get("event") == "user":
@@ -2057,7 +2128,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
answer = str(following.get("text") or "").strip()[:240]
if answer:
break
result.append(_prompt_summary(record, ordinal, answer))
result.append(_prompt_summary(record, ordinal, answer, position))
return _ChunkPromptView(tuple(result), tuple(candidates), frozenset(input_ids), answers, turns)
@@ -2078,7 +2149,8 @@ def _build_prompt_view(
if needs_canonical and session_turns_loader is not None:
session_turns = session_turns_loader()
entries: list[tuple[int, PromptSummary, dict[str, Any] | None]] = [
(decode_transcript_cursor(prompt["cursor"]) or 0, prompt, None) for prompt in raw_prompts
(cursor.turn if (cursor := decode_transcript_cursor(prompt["cursor"])) else 0, prompt, None)
for prompt in raw_prompts
]
session_cursor = 0
signature_positions: dict[str, list[int]] = {}
@@ -2150,9 +2222,15 @@ def _build_prompt_view(
event_id = _client_projection_event_id(record)
order[(ordinal, event_id)] = position
if event_id in recovered_ids:
reverse_plan.append((next_anchor, record))
anchor = next_anchor if any("response_input_ids" in item for item in records) else 0
reverse_plan.append((anchor, record))
if reverse_plan:
plan[ordinal] = list(reversed(reverse_plan))
for ordinal, prompt, user in entries:
if user is not None:
anchor = next(anchor for anchor, record in plan[ordinal]
if _client_projection_event_id(record) == prompt["id"])
prompt["cursor"] = _encode_page_cursor(ordinal, anchor)
entries.sort(key=lambda entry: (entry[0], order.get((entry[0], entry[1]["id"]), 0)))
return _PromptView(tuple(prompt for _, prompt, _ in entries), plan, needs_canonical)