refactor(webui): separate gateway mutations and UI state (#6727)
This commit is contained in:
1 parent
ce12bfdd0d
commit
5537bdabd3
70 files changed
+4058
-3650
No files matched your search
+115
-611
@@ -1,7 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
@@ -11,7 +9,6 @@ import time
|
||||
import uuid
|
||||
from bisect import bisect_left
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Mapping, NamedTuple, NotRequired, Sequence, TypedDict, cast
|
||||
@@ -32,7 +29,6 @@ from nanobot.session.history_graph import (
|
||||
decode_graph,
|
||||
decode_snapshot,
|
||||
graph_decoding,
|
||||
graph_size_adjustment,
|
||||
)
|
||||
from nanobot.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
@@ -53,6 +49,34 @@ from nanobot.webui.history import (
|
||||
from nanobot.webui.metadata import WEBUI_MESSAGE_SOURCE_METADATA_KEY, WEBUI_TURN_METADATA_KEY
|
||||
from nanobot.webui.outbound_wire import project_tool_events
|
||||
from nanobot.webui.session_identity import webui_session_key
|
||||
from nanobot.webui.transcript_replay import (
|
||||
WEBUI_REPLAY_IDENTITY_KEY,
|
||||
compact_completed_stream_deltas,
|
||||
encode_page_cursor,
|
||||
ensure_replay_identities,
|
||||
parse_replay_identity,
|
||||
projection_event_id,
|
||||
read_trace_turn,
|
||||
select_transcript_page,
|
||||
split_transcript_turns,
|
||||
)
|
||||
from nanobot.webui.transcript_replay import (
|
||||
TranscriptReplayStats as TranscriptReplayStats,
|
||||
)
|
||||
from nanobot.webui.transcript_replay import (
|
||||
compact_legacy_records as compact_legacy_records,
|
||||
)
|
||||
from nanobot.webui.transcript_replay import (
|
||||
decode_transcript_cursor as decode_transcript_cursor,
|
||||
)
|
||||
from nanobot.webui.transcript_trace import (
|
||||
TraceProjection,
|
||||
index_trace_projection,
|
||||
parse_trace_detail_ref,
|
||||
)
|
||||
from nanobot.webui.transcript_trace import (
|
||||
tool_trace_lines_from_events as tool_trace_lines_from_events,
|
||||
)
|
||||
|
||||
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
|
||||
WEBUI_FORK_MARKER_EVENT = "fork_marker"
|
||||
@@ -63,10 +87,6 @@ _MAX_TRANSCRIPT_PAGE_RECORDS = 4_000
|
||||
_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_TRACE_DETAIL_REF_RE = re.compile(
|
||||
r"^(?P<turn>\d{1,12})\.(?P<message>history-[0-9a-f]{20})$"
|
||||
)
|
||||
_MARKDOWN_LOCAL_IMAGE_RE = re.compile(
|
||||
r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)"
|
||||
)
|
||||
@@ -197,309 +217,18 @@ def webui_transcript_revision(
|
||||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()[:32]
|
||||
|
||||
|
||||
class _TranscriptTurnRef(NamedTuple):
|
||||
ordinal: int
|
||||
records: list[dict[str, Any]]
|
||||
start: int
|
||||
end: int
|
||||
total: int
|
||||
|
||||
|
||||
class _SessionBackfillTurn(NamedTuple):
|
||||
user_event: dict[str, Any]
|
||||
assistant_signature: tuple[str, ...]
|
||||
assistant_records: tuple[dict[str, Any], ...]
|
||||
|
||||
|
||||
class _ProjectionReceipt(TypedDict):
|
||||
turn_id: str
|
||||
ranges: list[list[int]]
|
||||
|
||||
|
||||
class _DeferredTraceGroup(NamedTuple):
|
||||
start: int
|
||||
stop: int
|
||||
detail_bytes: int
|
||||
trace_count: int
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TranscriptReplayStats:
|
||||
"""Selected-source page diagnostics; canonical recovery reads are separate."""
|
||||
|
||||
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
|
||||
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=(",", ":"))
|
||||
|
||||
|
||||
def _records_bytes(records: list[dict[str, Any]]) -> int:
|
||||
total = 0
|
||||
for record in records:
|
||||
total += len(_record_json_line(record).encode("utf-8")) + graph_size_adjustment(record) + 1
|
||||
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 _projection_receipts(records: Sequence[Mapping[str, Any]]) -> list[_ProjectionReceipt]:
|
||||
members: dict[str, set[int]] = {}
|
||||
for record in records:
|
||||
turn_id, sequence = record.get("turn_id"), record.get("turn_seq")
|
||||
if (
|
||||
isinstance(turn_id, str) and turn_id
|
||||
and isinstance(sequence, int) and not isinstance(sequence, bool) and sequence >= 0
|
||||
):
|
||||
members.setdefault(turn_id, set()).add(sequence)
|
||||
receipts: list[_ProjectionReceipt] = []
|
||||
for turn_id, sequences in members.items():
|
||||
ranges: list[list[int]] = []
|
||||
for sequence in sorted(sequences):
|
||||
if ranges and ranges[-1][1] + 1 == sequence:
|
||||
ranges[-1][1] = sequence
|
||||
else:
|
||||
ranges.append([sequence, sequence])
|
||||
receipts.append({"turn_id": turn_id, "ranges": ranges})
|
||||
return receipts
|
||||
|
||||
|
||||
def _compact_completed_stream_deltas(
|
||||
turn: list[dict[str, Any]],
|
||||
) -> tuple[list[dict[str, Any]], int]:
|
||||
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)
|
||||
# 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)
|
||||
|
||||
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 compact_legacy_records(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
turns, _ = _compact_completed_turns(_split_transcript_turns(records))
|
||||
return [record for turn in turns for record in turn]
|
||||
|
||||
|
||||
def _records_with_replay_identity(
|
||||
records: list[dict[str, Any]],
|
||||
*,
|
||||
turn_ordinal: int,
|
||||
) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
**record,
|
||||
_WEBUI_REPLAY_IDENTITY_KEY: record.get(_WEBUI_REPLAY_IDENTITY_KEY, f"turn:{turn_ordinal}:record:{record_index}"),
|
||||
}
|
||||
for record_index, record in enumerate(records)
|
||||
]
|
||||
|
||||
|
||||
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(
|
||||
data,
|
||||
separators=(",", ":"),
|
||||
ensure_ascii=False,
|
||||
).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_transcript_cursor(value: str | None) -> _PageCursor | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
padded = value + "=" * (-len(value) % 4)
|
||||
data = json.loads(base64.urlsafe_b64decode(padded.encode("ascii")).decode("utf-8"))
|
||||
except (binascii.Error, json.JSONDecodeError, UnicodeDecodeError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
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
|
||||
or isinstance(position, bool) or not isinstance(position, int) or position < 0
|
||||
):
|
||||
return None
|
||||
return _PageCursor(before_turn, position)
|
||||
|
||||
|
||||
def _coerce_page_limit(limit: int | None) -> int:
|
||||
if limit is None:
|
||||
return _DEFAULT_TRANSCRIPT_PAGE_LIMIT
|
||||
return max(1, min(_MAX_TRANSCRIPT_PAGE_LIMIT, int(limit)))
|
||||
|
||||
|
||||
def _transcript_turn_at_ordinal(
|
||||
ordinal: int, *, history: HistoryReader,
|
||||
) -> list[dict[str, Any]] | 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(
|
||||
*, history: HistoryReader, limit: int | None,
|
||||
before: str | None, after: str | None = None, stats: TranscriptReplayStats | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
stats = stats or TranscriptReplayStats()
|
||||
page_limit = _coerce_page_limit(limit)
|
||||
stats.effective_limit = page_limit
|
||||
total_turns = history.turn_count
|
||||
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=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 (requested_partial or exceeds_records or exceeds_bytes):
|
||||
break
|
||||
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 += 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
|
||||
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,
|
||||
)]
|
||||
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], 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] = {
|
||||
"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 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
|
||||
|
||||
|
||||
def read_transcript_lines(session_key: str, *, history: HistoryReader) -> list[dict[str, Any]]:
|
||||
return [record_from_fact(fact, session_key) for fact in history.all_facts()]
|
||||
|
||||
@@ -872,9 +601,9 @@ def _session_user_event(
|
||||
if isinstance(input_id, str) and _WEBUI_TURN_ID_RE.fullmatch(input_id):
|
||||
event["turn_id"] = input_id
|
||||
event["turn_phase"] = "user"
|
||||
event[_WEBUI_REPLAY_IDENTITY_KEY] = f"input:{session_key}:{input_id}"
|
||||
event[WEBUI_REPLAY_IDENTITY_KEY] = f"input:{session_key}:{input_id}"
|
||||
elif canonical_position is not None:
|
||||
event[_WEBUI_REPLAY_IDENTITY_KEY] = f"canonical:{session_key}:message:{canonical_position}"
|
||||
event[WEBUI_REPLAY_IDENTITY_KEY] = f"canonical:{session_key}:message:{canonical_position}"
|
||||
return event
|
||||
|
||||
|
||||
@@ -958,75 +687,6 @@ def _session_backfill_turns(
|
||||
return turns
|
||||
|
||||
|
||||
def _split_transcript_turns(lines: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
turns: list[list[dict[str, Any]]] = []
|
||||
current: list[dict[str, Any]] = []
|
||||
for rec in lines:
|
||||
current.append(rec)
|
||||
if rec.get("event") == "turn_end":
|
||||
turns.append(current)
|
||||
current = []
|
||||
if current:
|
||||
turns.append(current)
|
||||
return turns
|
||||
|
||||
|
||||
def _stable_record_digest(record: dict[str, Any]) -> str:
|
||||
persisted = {
|
||||
key: value
|
||||
for key, value in record.items()
|
||||
if key != _WEBUI_REPLAY_IDENTITY_KEY
|
||||
}
|
||||
raw = json.dumps(
|
||||
persisted,
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
default=str,
|
||||
)
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _ensure_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
annotated: list[dict[str, Any]] = []
|
||||
for fallback_turn_index, turn in enumerate(_split_transcript_turns(lines)):
|
||||
anchor = next(
|
||||
(
|
||||
value
|
||||
for record in turn
|
||||
if isinstance(
|
||||
value := record.get(_WEBUI_REPLAY_IDENTITY_KEY),
|
||||
str,
|
||||
)
|
||||
and value
|
||||
),
|
||||
None,
|
||||
)
|
||||
if anchor and ":record:" in anchor:
|
||||
turn_identity = anchor.rsplit(":record:", 1)[0]
|
||||
else:
|
||||
turn_digest = hashlib.sha256(
|
||||
"\n".join(_stable_record_digest(record) for record in turn).encode("ascii")
|
||||
).hexdigest()[:16]
|
||||
turn_identity = f"legacy:{fallback_turn_index}:{turn_digest}"
|
||||
synthetic_occurrences: dict[str, int] = {}
|
||||
for record in turn:
|
||||
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY)
|
||||
if isinstance(identity, str) and identity:
|
||||
annotated.append(record)
|
||||
continue
|
||||
digest = _stable_record_digest(record)
|
||||
occurrence = synthetic_occurrences.get(digest, 0)
|
||||
synthetic_occurrences[digest] = occurrence + 1
|
||||
annotated.append({
|
||||
**record,
|
||||
_WEBUI_REPLAY_IDENTITY_KEY: (
|
||||
f"{turn_identity}:synthetic:{digest}:{occurrence}"
|
||||
),
|
||||
})
|
||||
return annotated
|
||||
|
||||
|
||||
def _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]:
|
||||
texts: list[str] = []
|
||||
stream_parts: list[str] = []
|
||||
@@ -1135,7 +795,7 @@ def _recover_incomplete_turns(
|
||||
session_turns: list[_SessionBackfillTurn],
|
||||
) -> list[dict[str, Any]]:
|
||||
recovered: list[dict[str, Any]] = []
|
||||
for turn in _split_transcript_turns(lines):
|
||||
for turn in split_transcript_turns(lines):
|
||||
turn_end = turn[-1] if turn else None
|
||||
if (
|
||||
not isinstance(turn_end, dict)
|
||||
@@ -1170,7 +830,7 @@ def _needs_user_event_backfill(
|
||||
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(display_lines)
|
||||
for turn in split_transcript_turns(display_lines)
|
||||
)
|
||||
|
||||
|
||||
@@ -1197,50 +857,6 @@ def _with_backfilled_user(
|
||||
return records
|
||||
|
||||
|
||||
def _format_tool_call_trace(call: Any) -> str | None:
|
||||
if not call or not isinstance(call, dict):
|
||||
return None
|
||||
call_data = cast(dict[str, Any], call)
|
||||
fn = call_data.get("function")
|
||||
function_data = cast(dict[str, Any], fn) if isinstance(fn, dict) else None
|
||||
name = function_data.get("name") if function_data is not None else None
|
||||
if not isinstance(name, str) or not name:
|
||||
raw_name = call_data.get("name")
|
||||
name = raw_name if isinstance(raw_name, str) else ""
|
||||
if not name:
|
||||
return None
|
||||
args = (
|
||||
function_data.get("arguments") if function_data is not None else None
|
||||
) or call_data.get("arguments")
|
||||
if isinstance(args, str) and args.strip():
|
||||
return f"{name}({args})"
|
||||
if args and isinstance(args, dict):
|
||||
return f"{name}({json.dumps(args, ensure_ascii=False)})"
|
||||
return f"{name}()"
|
||||
|
||||
|
||||
def tool_trace_lines_from_events(events: Any) -> list[str]:
|
||||
if not isinstance(events, list):
|
||||
return []
|
||||
lines: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for event in cast(list[Any], events):
|
||||
if not event or not isinstance(event, dict):
|
||||
continue
|
||||
tool_event = cast(dict[str, Any], event)
|
||||
if tool_event.get("phase") not in {"start", "end", "error"}:
|
||||
continue
|
||||
call_id = tool_event.get("call_id")
|
||||
if isinstance(call_id, str) and call_id:
|
||||
if call_id in seen:
|
||||
continue
|
||||
seen.add(call_id)
|
||||
t = _format_tool_call_trace(tool_event)
|
||||
if t:
|
||||
lines.append(t)
|
||||
return lines
|
||||
|
||||
|
||||
def _normalize_tool_events(events: Any) -> list[dict[str, Any]]:
|
||||
if not isinstance(events, list):
|
||||
return []
|
||||
@@ -1281,28 +897,6 @@ 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:
|
||||
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 has_pending_tool_calls(
|
||||
lines: list[dict[str, Any]],
|
||||
*,
|
||||
@@ -1383,44 +977,18 @@ def build_webui_trace_detail_response(
|
||||
*, history: HistoryReader,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Resolve one deferred activity group as canonical projection events."""
|
||||
match = _WEBUI_TRACE_DETAIL_REF_RE.fullmatch(detail_ref)
|
||||
if match is None:
|
||||
identity = parse_trace_detail_ref(detail_ref)
|
||||
if identity is None:
|
||||
return None
|
||||
ordinal = int(match.group("turn"))
|
||||
message_id = match.group("message")
|
||||
turn = _transcript_turn_at_ordinal(ordinal, history=history)
|
||||
ordinal, message_id = identity
|
||||
turn = read_trace_turn(
|
||||
ordinal, history=history,
|
||||
max_records=_MAX_TRANSCRIPT_PAGE_RECORDS, max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
|
||||
)
|
||||
if turn is None:
|
||||
return None
|
||||
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]
|
||||
if _client_projection_event_id(first) != message_id:
|
||||
continue
|
||||
events = [
|
||||
event
|
||||
for record in lines[group.start:group.stop]
|
||||
if record.get("event") != "model_request" and (
|
||||
event := _client_projection_event(
|
||||
record,
|
||||
augment_user_media=None,
|
||||
augment_assistant_media=None,
|
||||
augment_assistant_text=None,
|
||||
)
|
||||
) is not None
|
||||
]
|
||||
return {"message_id": message_id, "events": events}
|
||||
return None
|
||||
|
||||
|
||||
def _client_projection_event_id(record: Mapping[str, Any]) -> str:
|
||||
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY)
|
||||
if record.get("event") == "user" and isinstance(input_id := record.get("input_id"), str) and input_id:
|
||||
identity = f"input:{record.get('chat_id')}:{input_id}"
|
||||
if not isinstance(identity, str) or not identity:
|
||||
identity = _stable_record_digest(dict(record))
|
||||
digest = hashlib.sha256(f"event\0{identity}".encode("utf-8")).hexdigest()[:20]
|
||||
return f"history-{digest}"
|
||||
lines, _ = compact_completed_stream_deltas(turn)
|
||||
return _index_trace_projection(lines).detail(message_id)
|
||||
|
||||
|
||||
def _client_projection_turn_fields(record: Mapping[str, Any]) -> dict[str, Any]:
|
||||
@@ -1442,7 +1010,7 @@ def _client_projection_turn_fields(record: Mapping[str, Any]) -> dict[str, Any]:
|
||||
def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]:
|
||||
fields: dict[str, Any] = {
|
||||
"chat_id": str(record.get("chat_id") or ""),
|
||||
"projection_id": _client_projection_event_id(record),
|
||||
"projection_id": projection_event_id(record),
|
||||
**_client_projection_turn_fields(record),
|
||||
}
|
||||
created_at_ms = _valid_created_at_ms(record.get("created_at_ms"))
|
||||
@@ -1468,6 +1036,28 @@ def _client_projection_source(record: dict[str, Any]) -> dict[str, Any] | None:
|
||||
return projected
|
||||
|
||||
|
||||
def _augment_projected_message(
|
||||
record: dict[str, Any], projected: dict[str, Any], *,
|
||||
augment_media: Callable[[list[str]], list[dict[str, Any]]] | None,
|
||||
augment_text: Callable[[str], str] | None,
|
||||
cached: bool = False,
|
||||
) -> None:
|
||||
if augment_text is not None and projected.get("render_as") != "text":
|
||||
projected["text"] = augment_text(projected["text"])
|
||||
if augment_media is not None and isinstance(raw_media := record.get("media"), list):
|
||||
paths = [path for path in cast(list[object], raw_media) if isinstance(path, str) and path]
|
||||
if paths:
|
||||
# When re-signing local paths, do not fall back to stale signed URLs.
|
||||
media = augment_media(paths)
|
||||
if media:
|
||||
projected["media_urls"] = media
|
||||
else:
|
||||
projected.pop("media_urls", None)
|
||||
return
|
||||
if not cached and (media := _media_from_signed_urls(record.get("media_urls"))):
|
||||
projected["media_urls"] = media
|
||||
|
||||
|
||||
def _client_projection_event(
|
||||
record: dict[str, Any],
|
||||
*,
|
||||
@@ -1546,8 +1136,6 @@ def _client_projection_event(
|
||||
text = record.get("text")
|
||||
content = text if isinstance(text, str) else ""
|
||||
render_as_text = record.get("render_as") == "text"
|
||||
if not render_as_text and augment_assistant_text is not None:
|
||||
content = augment_assistant_text(content)
|
||||
projected = {"event": "message", **common, "text": content}
|
||||
if render_as_text:
|
||||
projected["render_as"] = "text"
|
||||
@@ -1557,21 +1145,9 @@ def _client_projection_event(
|
||||
tool_events = _normalize_tool_events(record.get("tool_events"))
|
||||
if tool_events:
|
||||
projected["tool_events"] = tool_events
|
||||
raw_media = record.get("media")
|
||||
media_paths = [
|
||||
path
|
||||
for path in cast(list[Any], raw_media)
|
||||
if isinstance(path, str) and path
|
||||
] if isinstance(raw_media, list) else []
|
||||
media = (
|
||||
augment_assistant_media(media_paths)
|
||||
if media_paths and augment_assistant_media is not None
|
||||
else []
|
||||
_augment_projected_message(
|
||||
record, projected, augment_media=augment_assistant_media, augment_text=augment_assistant_text,
|
||||
)
|
||||
if not media and (not media_paths or augment_assistant_media is None):
|
||||
media = _media_from_signed_urls(record.get("media_urls"))
|
||||
if media:
|
||||
projected["media_urls"] = media
|
||||
latency_ms = record.get("latency_ms")
|
||||
if isinstance(latency_ms, int | float) and latency_ms >= 0:
|
||||
projected["latency_ms"] = int(latency_ms)
|
||||
@@ -1664,78 +1240,14 @@ def _client_projection_event(
|
||||
return None
|
||||
|
||||
|
||||
def _client_projection_deferred_trace_groups(
|
||||
lines: list[dict[str, Any]],
|
||||
) -> dict[int, _DeferredTraceGroup]:
|
||||
groups: dict[int, _DeferredTraceGroup] = {}
|
||||
start: int | None = None
|
||||
detail_bytes = 0
|
||||
trace_count = 0
|
||||
|
||||
def flush(stop: int) -> None:
|
||||
nonlocal start, detail_bytes, trace_count
|
||||
if (
|
||||
start is not None
|
||||
and detail_bytes > _MAX_INLINE_TRACE_DETAIL_BYTES
|
||||
):
|
||||
groups[start] = _DeferredTraceGroup(
|
||||
start=start,
|
||||
stop=stop,
|
||||
detail_bytes=detail_bytes,
|
||||
trace_count=max(1, trace_count),
|
||||
)
|
||||
start = None
|
||||
detail_bytes = 0
|
||||
trace_count = 0
|
||||
|
||||
for index, record in enumerate(lines):
|
||||
# Usage belongs to the turn, not the activity body. It must not split
|
||||
# one deferred tool group into many eagerly loaded fragments.
|
||||
if record.get("event") == "model_request":
|
||||
continue
|
||||
is_activity = (
|
||||
record.get("event") == "message"
|
||||
and record.get("kind") in {"tool_hint", "progress"}
|
||||
)
|
||||
if not is_activity:
|
||||
flush(index)
|
||||
continue
|
||||
event = _client_projection_event(
|
||||
record,
|
||||
augment_user_media=None,
|
||||
augment_assistant_media=None,
|
||||
augment_assistant_text=None,
|
||||
)
|
||||
if event is None:
|
||||
flush(index)
|
||||
continue
|
||||
if start is None:
|
||||
start = index
|
||||
detail_bytes += len(_record_json_line(event).encode("utf-8"))
|
||||
tool_events = _normalize_tool_events(record.get("tool_events"))
|
||||
traces = tool_trace_lines_from_events(tool_events)
|
||||
if traces:
|
||||
trace_count += len(traces)
|
||||
elif not tool_events and isinstance(record.get("text"), str) and record["text"]:
|
||||
trace_count += 1
|
||||
flush(len(lines))
|
||||
return groups
|
||||
def _project_trace_event(record: dict[str, Any]) -> dict[str, Any] | None:
|
||||
return _client_projection_event(
|
||||
record, augment_user_media=None, augment_assistant_media=None, augment_assistant_text=None,
|
||||
)
|
||||
|
||||
|
||||
def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int:
|
||||
supported = {
|
||||
"user",
|
||||
"delta",
|
||||
"stream_end",
|
||||
"reasoning_delta",
|
||||
"reasoning_end",
|
||||
"message",
|
||||
"file_edit",
|
||||
"context_compaction",
|
||||
"model_request",
|
||||
"turn_end",
|
||||
}
|
||||
return max(1, sum(record.get("event") in supported for record in turn))
|
||||
def _index_trace_projection(lines: list[dict[str, Any]]) -> TraceProjection:
|
||||
return index_trace_projection(lines, _project_trace_event, max_inline_bytes=_MAX_INLINE_TRACE_DETAIL_BYTES)
|
||||
|
||||
|
||||
def _client_projection_events(
|
||||
@@ -1748,7 +1260,7 @@ def _client_projection_events(
|
||||
) -> 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) if defer_traces else {}
|
||||
traces = _index_trace_projection(lines) if defer_traces else None
|
||||
deferred_until = 0
|
||||
for index, record in enumerate(lines):
|
||||
if index < deferred_until and record.get("event") != "model_request":
|
||||
@@ -1757,39 +1269,24 @@ def _client_projection_events(
|
||||
if fork_boundary_event_index is None:
|
||||
fork_boundary_event_index = len(events)
|
||||
continue
|
||||
event = _client_projection_event(
|
||||
record,
|
||||
augment_user_media=augment_user_media,
|
||||
augment_assistant_media=augment_assistant_media,
|
||||
augment_assistant_text=augment_assistant_text,
|
||||
)
|
||||
cached = traces.events.get(index) if traces is not None else None
|
||||
if cached is not None:
|
||||
event = cached
|
||||
_augment_projected_message(
|
||||
record, event, augment_media=augment_assistant_media,
|
||||
augment_text=augment_assistant_text, cached=True,
|
||||
)
|
||||
else:
|
||||
event = _client_projection_event(
|
||||
record,
|
||||
augment_user_media=augment_user_media,
|
||||
augment_assistant_media=augment_assistant_media,
|
||||
augment_assistant_text=augment_assistant_text,
|
||||
)
|
||||
if event is None:
|
||||
continue
|
||||
group = deferred_groups.get(index)
|
||||
if group is not None:
|
||||
detail_ref = _trace_detail_ref(_client_projection_event_id(record), record)
|
||||
last_text = next(
|
||||
(
|
||||
text
|
||||
for grouped in reversed(lines[group.start:group.stop])
|
||||
if isinstance((text := grouped.get("text")), str) and text
|
||||
),
|
||||
"",
|
||||
)
|
||||
event["text"] = _trace_summary(last_text)
|
||||
event.pop("tool_events", None)
|
||||
receipts = _projection_receipts([
|
||||
grouped for grouped in lines[group.start:group.stop]
|
||||
if grouped.get("event") != "model_request"
|
||||
])
|
||||
if receipts:
|
||||
event["projection_receipts"] = receipts
|
||||
if detail_ref is not None:
|
||||
event["trace_detail"] = {
|
||||
"ref": detail_ref,
|
||||
"bytes": group.detail_bytes,
|
||||
"traceCount": group.trace_count,
|
||||
}
|
||||
if traces is not None and (group := traces.groups.get(index)) is not None:
|
||||
traces.summarize(lines, group, event)
|
||||
deferred_until = group.stop
|
||||
events.append(event)
|
||||
return events, fork_boundary_event_index
|
||||
@@ -1849,13 +1346,13 @@ def build_session_thread_response(
|
||||
"activity" if record["event"] == "file_edit" or record.get("kind") in {"progress", "tool_hint"}
|
||||
else "answer",
|
||||
"created_at_ms": created_at_ms,
|
||||
_WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:{index}:{offset}",
|
||||
WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:{index}:{offset}",
|
||||
})
|
||||
rows.append(record)
|
||||
if not active and rows:
|
||||
rows.append({"event": "turn_end", "chat_id": chat_id,
|
||||
"turn_id": turn_id, "latency_ms": latency_ms,
|
||||
_WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:end"})
|
||||
WEBUI_REPLAY_IDENTITY_KEY: f"session:{session.key}:end"})
|
||||
events = [event for record in rows if (event := _client_projection_event(
|
||||
record, augment_user_media=augment_user_media, augment_assistant_media=augment_assistant_media,
|
||||
augment_assistant_text=augment_assistant_text,
|
||||
@@ -1888,9 +1385,11 @@ def build_webui_thread_response(
|
||||
) -> dict[str, Any] | None:
|
||||
"""Return canonical events, hiding additive request events from old clients."""
|
||||
replay_stats = stats or TranscriptReplayStats()
|
||||
lines, page = _select_transcript_page(
|
||||
lines, page = select_transcript_page(
|
||||
history=history,
|
||||
limit=limit,
|
||||
page_limit=_coerce_page_limit(limit),
|
||||
max_records=_MAX_TRANSCRIPT_PAGE_RECORDS,
|
||||
max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
|
||||
before=before,
|
||||
after=after,
|
||||
stats=replay_stats,
|
||||
@@ -1922,14 +1421,19 @@ def build_webui_thread_response(
|
||||
)
|
||||
backfill_plan = view.backfill_plan
|
||||
recovered_lines: list[dict[str, Any]] = []
|
||||
for turn in _split_transcript_turns(lines):
|
||||
ordinal = int(turn[0][_WEBUI_REPLAY_IDENTITY_KEY].split(":")[1])
|
||||
for turn in split_transcript_turns(lines):
|
||||
first_identity = parse_replay_identity(turn[0].get(WEBUI_REPLAY_IDENTITY_KEY))
|
||||
if first_identity is None:
|
||||
recovered_lines.extend(turn)
|
||||
continue
|
||||
ordinal = first_identity[0]
|
||||
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))
|
||||
if (parsed := parse_replay_identity(record.get(WEBUI_REPLAY_IDENTITY_KEY))) is not None
|
||||
and parsed[0] == ordinal
|
||||
and parsed[1] >= anchor), len(turn))
|
||||
turn.insert(index, dict(user))
|
||||
recovered_lines.extend(turn)
|
||||
lines = recovered_lines
|
||||
@@ -1944,7 +1448,7 @@ def build_webui_thread_response(
|
||||
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)
|
||||
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,
|
||||
@@ -1986,7 +1490,7 @@ def build_webui_thread_response(
|
||||
and record.get("turn_id") in shell_turns else record
|
||||
for record in lines
|
||||
]
|
||||
lines = _ensure_replay_identities(lines)
|
||||
lines = ensure_replay_identities(lines)
|
||||
payload: dict[str, Any] = {
|
||||
"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION,
|
||||
"sessionKey": session_key,
|
||||
@@ -2073,12 +1577,12 @@ def _prompt_summary(
|
||||
record: dict[str, Any], ordinal: int, answer: str, position: int = 0,
|
||||
) -> PromptSummary:
|
||||
return {
|
||||
"id": _client_projection_event_id(record),
|
||||
"id": 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, position),
|
||||
"cursor": encode_page_cursor(ordinal, position),
|
||||
"turnId": str(record.get("turn_id") or ""),
|
||||
}
|
||||
|
||||
@@ -2092,7 +1596,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
|
||||
turns: dict[int, list[dict[str, Any]]] = {}
|
||||
for ordinal, position, fact in history.navigation():
|
||||
record = record_from_fact(fact, history.key)
|
||||
record[_WEBUI_REPLAY_IDENTITY_KEY] = f"turn:{ordinal}:record:{position}"
|
||||
record[WEBUI_REPLAY_IDENTITY_KEY] = f"turn:{ordinal}:record:{position}"
|
||||
turns.setdefault(ordinal, []).append(record)
|
||||
if record.get("event") in {"message", "stream_end"} and not record.get("kind"):
|
||||
if isinstance(references := record.get("response_input_ids"), list):
|
||||
@@ -2114,7 +1618,7 @@ def _history_prompt_summaries(history: HistoryReader) -> _ChunkPromptView:
|
||||
for index, record in enumerate(records):
|
||||
if record.get("event") != "user":
|
||||
continue
|
||||
position = int(record[_WEBUI_REPLAY_IDENTITY_KEY].rsplit(":", 1)[1])
|
||||
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)
|
||||
@@ -2214,18 +1718,18 @@ def _build_prompt_view(
|
||||
plan: dict[int, list[tuple[int, dict[str, Any]]]] = {}
|
||||
for ordinal, records in chunk.turns.items():
|
||||
users = backfilled_users.get(ordinal, [])
|
||||
recovered_ids = {_client_projection_event_id(user) for user in users}
|
||||
recovered_ids = {projection_event_id(user) for user in users}
|
||||
for user in users:
|
||||
records = _with_backfilled_user(records, user)
|
||||
next_anchor = 2**63 - 1
|
||||
reverse_plan: list[tuple[int, dict[str, Any]]] = []
|
||||
for position in range(len(records) - 1, -1, -1):
|
||||
record = records[position]
|
||||
identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY, "")
|
||||
identity = record.get(WEBUI_REPLAY_IDENTITY_KEY, "")
|
||||
if identity.startswith(f"turn:{ordinal}:record:"):
|
||||
next_anchor = int(identity.rsplit(":", 1)[1])
|
||||
if record.get("event") == "user":
|
||||
event_id = _client_projection_event_id(record)
|
||||
event_id = projection_event_id(record)
|
||||
order[(ordinal, event_id)] = position
|
||||
if event_id in recovered_ids:
|
||||
anchor = next_anchor if any("response_input_ids" in item for item in records) else 0
|
||||
@@ -2235,8 +1739,8 @@ def _build_prompt_view(
|
||||
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)
|
||||
if 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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user