diff --git a/nanobot/session/display_history.py b/nanobot/session/display_history.py index 5a88a57da..b5d8e0c4c 100644 --- a/nanobot/session/display_history.py +++ b/nanobot/session/display_history.py @@ -86,6 +86,12 @@ class HistoryTurn: user_count: int +@dataclass(frozen=True) +class HistoryEntryPage: + entries: list[tuple[int, HistoryFact]] + source_bytes: int + + class HistoryReader: """A single-session view valid only inside its owner's read transaction.""" @@ -122,50 +128,60 @@ class HistoryReader: ): yield HistoryTurn(*row) - def read_entries( - self, ordinal: int, *, max_records: int | None = None, max_bytes: int | None = None, - ) -> list[tuple[int, HistoryFact]]: - clause = "session_key=? AND turn_ordinal=?" - params = (self.key, ordinal) - selected: list[int] | None = None - if max_records is not None and max_bytes is not None: - # Inspect sizes/positions, not unbounded JSON bodies, before decoding - # a pathological single turn. Preserve the first input and useful tail. - priorities: list[tuple[int, int]] = [] - for kinds, order in (((HistoryKind.INPUT,), "ASC"), - ((HistoryKind.COMPLETION,), "DESC"), - ((HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, HistoryKind.ANSWER_FRAGMENT), "DESC")): - row = self._db.execute( - f"SELECT position, coalesce(json_extract(record, '$.uncompressed_bytes'), length(CAST(record AS BLOB))) FROM history_entries WHERE {clause} " - f"AND kind IN ({','.join('?' for _ in kinds)}) ORDER BY position {order} LIMIT 1", - (*params, *kinds), - ).fetchone() - if row is not None: - priorities.append((row[0], row[1])) - candidates = self._db.execute( - f"SELECT position, coalesce(json_extract(record, '$.uncompressed_bytes'), length(CAST(record AS BLOB))) FROM history_entries WHERE {clause} ORDER BY position DESC LIMIT ?", - (*params, max_records), - ) - positions: set[int] = set() - used = 0 - for position, size in (*priorities, *candidates): - if position not in positions and len(positions) < max_records and used + size <= max_bytes: - positions.add(position) - used += size - selected = sorted(positions) - if not selected: - return [] - clause += f" AND position IN ({','.join('?' for _ in selected)})" + def read_entries(self, ordinal: int) -> list[tuple[int, HistoryFact]]: return [(row[0], HistoryFact.decode(row[1])) for row in self._db.execute( - f"SELECT position, record FROM history_entries WHERE {clause} ORDER BY position", - (*params, *(selected or [])), + """SELECT position, record FROM history_entries + WHERE session_key=? AND turn_ordinal=? ORDER BY position""", + (self.key, ordinal), )] - def user_count_before(self, ordinal: int) -> int: - return int(self._db.execute( + def read_entry_page( + self, ordinal: int, *, start: int, end: int, reverse: bool, + max_records: int, max_bytes: int, allow_oversized: bool = False, + ) -> HistoryEntryPage: + """Read a contiguous range, budgeting encoded and expanded source bytes.""" + order = "DESC" if reverse else "ASC" + sizes = self._db.execute( + f"""SELECT position, max(length(CAST(record AS BLOB)), + coalesce(json_extract(record, '$.uncompressed_bytes'), 0)) + FROM history_entries WHERE session_key=? AND turn_ordinal=? + AND position>=? AND position max_bytes and (positions or not allow_oversized): + break + positions.append(position) + used += size + if used >= max_bytes: + break + if not positions: + return HistoryEntryPage([], 0) + first, last = min(positions), max(positions) + 1 + entries = [(row[0], HistoryFact.decode(row[1])) for row in self._db.execute( + """SELECT position, record FROM history_entries WHERE session_key=? AND turn_ordinal=? + AND position>=? AND position int: + earlier = int(self._db.execute( "SELECT coalesce(sum(user_count), 0) FROM history_turns WHERE session_key=? AND ordinal bool: return self._db.execute( @@ -174,6 +190,45 @@ class HistoryReader: (self.key, input_id), ).fetchone() is not None + def has_missing_input_references(self, ordinal: int) -> bool: + """Detect backfill across page boundaries without loading answer bodies.""" + return self._db.execute( + """SELECT 1 FROM history_entries AS answer, + json_each(answer.record, '$.content.response_input_ids') AS reference + WHERE answer.session_key=? AND answer.turn_ordinal=? AND answer.kind IN (?, ?, ?) + AND reference.type='text' AND reference.value!='' + AND NOT EXISTS ( + SELECT 1 FROM history_entries AS input WHERE input.session_key=answer.session_key + AND input.kind=? AND json_extract(input.record, '$.content.input_id')=reference.value + ) LIMIT 1""", + (self.key, ordinal, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, + HistoryKind.ANSWER_FRAGMENT, HistoryKind.INPUT), + ).fetchone() is not None + + def unique_user_position(self, ordinal: int) -> int | None: + positions = self._db.execute( + """SELECT position FROM history_entries WHERE session_key=? AND turn_ordinal=? + AND kind=? ORDER BY position LIMIT 2""", + (self.key, ordinal, HistoryKind.INPUT), + ).fetchall() + return int(positions[0][0]) if len(positions) == 1 else None + + def incomplete_completion_marker(self, ordinal: int, position: int) -> bool: + """Inspect the terminal marker without decoding the full fact.""" + row = self._db.execute( + """SELECT json_type(record, '$.content.transcript_incomplete') + FROM history_entries WHERE session_key=? AND turn_ordinal=? AND position=? AND kind=?""", + (self.key, ordinal, position, HistoryKind.COMPLETION), + ).fetchone() + return bool(row and row[0] == "true") + + def has_navigation_answer(self, ordinal: int) -> bool: + return self._db.execute( + """SELECT 1 FROM history_entries WHERE session_key=? AND turn_ordinal=? + AND kind IN (?, ?, ?) LIMIT 1""", + (self.key, ordinal, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, HistoryKind.ANSWER_FRAGMENT), + ).fetchone() is not None + def navigation(self) -> Iterator[tuple[int, int, HistoryFact]]: """Read input/answer records only, never file diffs or tool result bodies.""" kinds = (HistoryKind.INPUT, HistoryKind.ANSWER, HistoryKind.ANSWER_SEGMENT, diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py index 5367cd8c2..288831a26 100644 --- a/nanobot/webui/history.py +++ b/nanobot/webui/history.py @@ -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]]: diff --git a/nanobot/webui/outbound_delivery.py b/nanobot/webui/outbound_delivery.py index 28107f76d..1a9b64158 100644 --- a/nanobot/webui/outbound_delivery.py +++ b/nanobot/webui/outbound_delivery.py @@ -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( diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 0ff6daec6..afe35647b 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -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\d{1,12})\.(?Phistory-[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) diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index b0ae803ae..8561cc833 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -271,7 +271,6 @@ def test_thread_response_preserves_optional_stream_ids(history, delta_event, end "wire-first", "wire-first", "wire-second", "wire-second", None, None, ] assert all("stream_id" not in event for event in stream_events[-2:]) - assert all("projection_receipts" not in event for event in stream_events) assert history.read(key) == original_rows @@ -280,7 +279,7 @@ def test_thread_response_preserves_optional_stream_ids(history, delta_event, end [("delta", "stream_end", "answer"), ("reasoning_delta", "reasoning_end", "reasoning")], ) @pytest.mark.parametrize("completed_text", [None, "canonical text"]) -def test_thread_response_receipts_for_folded_legacy_deltas( +def test_complete_turn_folds_legacy_deltas_into_authoritative_stream_snapshots( history, delta_event, end_event, phase, completed_text, ) -> None: key = "websocket:folded-receipts" @@ -310,9 +309,8 @@ def test_thread_response_receipts_for_folded_legacy_deltas( assert [(event["stream_id"], event["turn_seq"], event["text"]) for event in ends] == [ ("primary", 9, primary_text), ("secondary", 10, "other"), ] - assert [event["projection_receipts"] for event in ends] == [ - [{"turn_id": "turn-folded", "ranges": [[3, 4], [8, 9]]}], - [{"turn_id": "turn-folded", "ranges": [[6, 6], [10, 10]]}], + assert [event["event"] for event in payload["events"]] == [ + "user_message", "message", end_event, end_event, "turn_end", ] assert history.read(key) == original_rows # Migration compaction retains its existing record format, without HTTP metadata. @@ -570,15 +568,16 @@ def test_single_oversized_turn_is_bounded_and_marked(history, tmp_path, monkeypa assert latest is not None assert stats.selected_records <= 5 - assert stats.selected_bytes <= 1_200 + assert stats.source_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 _message_contents(latest) == ["question", "final answer"] + assert latest["page"]["record_range"] == {"turn": 0, "start": 18, "end": 23} + assert _message_contents(latest) == ["final answer"] -def test_truncated_turn_does_not_advertise_ambiguous_trace_detail(history, +def test_sliced_turn_keeps_full_trace_details_inline(history, tmp_path, monkeypatch, ) -> None: @@ -623,10 +622,11 @@ def test_truncated_turn_does_not_advertise_ambiguous_trace_detail(history, assert payload is not None assert payload["page"]["truncated_oversized_turn"] is True - trace_event = next(event for event in payload["events"] if event.get("kind") == "progress") - assert trace_event["text"] == "second_3(…)" - assert "trace_detail" not in trace_event - assert len(json.dumps(trace_event).encode("utf-8")) < 4_096 + traces = [event for event in payload["events"] if event.get("kind") == "progress"] + assert [event["text"] for event in traces] == [ + f"second_{idx}({('x' * 12_000)})" for idx in range(4) + ] + assert all("trace_detail" not in event for event in traces) def test_page_cursor_survives_appends_after_latest_page(history, diff --git a/tests/webui/test_backfill_order_regression.py b/tests/webui/test_backfill_order_regression.py index f8ce14895..fc520ccdb 100644 --- a/tests/webui/test_backfill_order_regression.py +++ b/tests/webui/test_backfill_order_regression.py @@ -1,6 +1,20 @@ +import pytest + from nanobot.webui.transcript import TranscriptReplayStats +def _paged_events(history, key, messages): + pages = [history.build(key, limit=10, session_messages_loader=lambda: messages)] + assert pages[0]["page"]["truncated_oversized_turn"] + while pages[-1]["page"]["has_more_before"]: + pages.append(history.build(key, limit=10, before=pages[-1]["page"]["before_cursor"], + session_messages_loader=lambda: messages)) + assert len(pages) < 30 + events = [event for page in reversed(pages) for event in page["events"]] + assert len({event["projection_id"] for event in events}) == len(events) + return events + + def test_grouped_backfill_keeps_response_input_order_in_page_and_index(history, tmp_path, monkeypatch): monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) key = "websocket:backfill-order" @@ -75,10 +89,11 @@ def test_empty_response_inputs_do_not_use_legacy_answer_matching(history, tmp_pa assert [event["projection_id"] for event in latest["events"] if event["event"] == "user_message"] == [index[0]["id"]] -def test_truncated_turn_applies_plan_when_reference_anchor_is_dropped(history, tmp_path, monkeypatch): +@pytest.mark.parametrize("budget", [1, 5]) +def test_fragmented_turn_preserves_backfill_order_across_reference_anchors(history, tmp_path, monkeypatch, budget): from nanobot.webui import transcript monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) - monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 5) + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", budget) key = "websocket:truncated-backfill" ids = ["input:a", "input:b", "input:c"] messages = [{"role": "user", "content": text, "input_id": ident} @@ -90,15 +105,16 @@ def test_truncated_turn_applies_plan_when_reference_anchor_is_dropped(history, t history.append(key, {"event": "message", "text": "last", "response_input_ids": ids[2:]}) history.append(key, {"event": "turn_end"}) index = history.prompts(key, session_messages_loader=lambda: messages) - page = history.build(key, limit=10, session_messages_loader=lambda: messages) - users = [event for event in page["events"] if event["event"] == "user_message"] - assert page["page"]["truncated_oversized_turn"] - assert not page["page"]["has_more_before"] + events = _paged_events(history, key, messages) + users = [event for event in events if event["event"] == "user_message"] assert [event["text"] for event in users] == ["A", "B", "C"] assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index] + for prompt in index: + page = history.build(key, after=prompt["cursor"], session_messages_loader=lambda: messages) + assert prompt["id"] in [event["projection_id"] for event in page["events"]] -def test_truncated_turn_recovers_even_if_all_missing_references_were_dropped(history, tmp_path, monkeypatch): +def test_older_pages_recover_inputs_whose_references_are_outside_latest_page(history, tmp_path, monkeypatch): from nanobot.webui import transcript monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4) @@ -111,14 +127,13 @@ def test_truncated_turn_recovers_even_if_all_missing_references_were_dropped(his history.append(key, {"event": "message", "text": "new"}) history.append(key, {"event": "turn_end"}) index = history.prompts(key, session_messages_loader=lambda: messages) - page = history.build(key, limit=10, session_messages_loader=lambda: messages) - users = [event for event in page["events"] if event["event"] == "user_message"] - assert page["page"]["truncated_oversized_turn"] + events = _paged_events(history, key, messages) + users = [event for event in events if event["event"] == "user_message"] assert [event["text"] for event in users] == ["A", "B"] assert [event["projection_id"] for event in users] == [prompt["id"] for prompt in index] -def test_completed_stream_compaction_and_truncation_keep_shared_backfill_anchor(history, tmp_path, monkeypatch): +def test_completed_stream_compaction_and_record_pages_keep_shared_backfill_anchor(history, tmp_path, monkeypatch): from nanobot.webui import transcript monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) @@ -142,13 +157,12 @@ def test_completed_stream_compaction_and_truncation_keep_shared_backfill_anchor( full = history.build(key, limit=10, session_messages_loader=loader, stats=stats) assert stats.compacted_delta_records == 3 monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 8) - truncated_stats = TranscriptReplayStats() - truncated = history.build(key, limit=10, session_messages_loader=loader, stats=truncated_stats) - assert truncated["page"]["truncated_oversized_turn"] - assert truncated_stats.compacted_delta_records == 3 + events = _paged_events(history, key, messages) + assert [event["text"] for event in events if event["event"] == "delta"] == ["one", "two", "three"] + assert [event["text"] for event in events if event["event"] == "stream_end"] == ["onetwothree"] expected_ids = [prompt["id"] for prompt in index] assert [prompt["inputId"] for prompt in index] == ids - for page in (full, truncated): - users = [event for event in page["events"] if event["event"] == "user_message"] + for replay in (full["events"], events): + users = [event for event in replay if event["event"] == "user_message"] assert [event["text"] for event in users] == ["A", "B", "C"] assert [event["projection_id"] for event in users] == expected_ids diff --git a/tests/webui/test_record_pages.py b/tests/webui/test_record_pages.py new file mode 100644 index 000000000..907819934 --- /dev/null +++ b/tests/webui/test_record_pages.py @@ -0,0 +1,596 @@ +import base64 +import json +import time + +import pytest +from websockets.datastructures import Headers +from websockets.http11 import Request + +from nanobot.bus.queue import MessageBus +from nanobot.channels.websocket.runtime import WebSocketConfig +from nanobot.session.display_history import HistoryFact +from nanobot.session.history_graph import history_record_size +from nanobot.webui import transcript +from nanobot.webui.gateway_services import build_gateway_services +from nanobot.webui.history import fact_from_record + + +def _legacy_cursor(turn): + raw = json.dumps({"before_turn": turn}, separators=(",", ":")).encode() + return base64.urlsafe_b64encode(raw).decode().rstrip("=") + + +@pytest.mark.parametrize("budget", ["records", "bytes"]) +def test_oversized_turn_pages_are_contiguous_and_replay_raw_events(history, monkeypatch, budget): + key = "websocket:record-pages" + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4 if budget == "records" else 100) + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_BYTES", 500 if budget == "bytes" else 100_000) + monkeypatch.setattr(transcript, "_MAX_INLINE_TRACE_DETAIL_BYTES", 10) + rows = [ + {"event": "user", "text": "previous", "turn_id": "previous"}, + {"event": "turn_end", "turn_id": "previous"}, + {"event": "user", "text": "first", "turn_id": "execution", "turn_seq": 1}, + {"event": "delta", "text": "![plot](diagram", "turn_id": "execution", "turn_seq": 2}, + {"event": "delta", "text": ".png)", "turn_id": "execution", "turn_seq": 3}, + {"event": "stream_end", "text": "![plot](/api/media/signed)", "turn_id": "execution", "turn_seq": 4}, + {"event": "message", "kind": "progress", "text": "trace one with full detail", "turn_id": "execution", "turn_seq": 5}, + {"event": "user", "text": "second", "turn_id": "execution", "turn_seq": 6}, + {"event": "message", "kind": "progress", "text": "trace two with full detail", "turn_id": "execution", "turn_seq": 7}, + {"event": "message", "text": "answer", "turn_id": "execution", "turn_seq": 8}, + {"event": "turn_end", "turn_id": "execution", "turn_seq": 9, "transcript_incomplete": True}, + {"event": "user", "text": "next", "turn_id": "next"}, + {"event": "turn_end", "turn_id": "next"}, + ] + for row in rows: + history.append(key, row) + + decoded = [] + original_decode = HistoryFact.decode + + def track_decode(record): + decoded.append(record) + return original_decode(record) + + monkeypatch.setattr(HistoryFact, "decode", track_decode) + + def no_canonical_load(): + pytest.fail("a sliced turn must not trigger canonical recovery") + + def read(**kwargs): + decoded.clear() + stats = transcript.TranscriptReplayStats() + page = history.build(key, limit=100, stats=stats, + session_messages_loader=no_canonical_load, **kwargs) + assert page is not None + assert stats.parsed_records == len(decoded) <= transcript._MAX_TRANSCRIPT_PAGE_RECORDS + assert stats.source_bytes == sum(max(len(record.encode("utf-8")), history_record_size(record)) for record in decoded) + assert stats.source_bytes <= transcript._MAX_TRANSCRIPT_PAGE_BYTES + return page + + latest = read() + backwards = [latest] + while backwards[-1]["page"]["has_more_before"]: + backwards.append(read(before=backwards[-1]["page"]["before_cursor"])) + assert len(backwards) < 20 + chronological = list(reversed(backwards)) + fragments = [page for page in chronological if "record_range" in page["page"]] + ranges = [page["page"]["record_range"] for page in fragments] + assert len(ranges) > 1 + assert all(r["turn"] == 1 for r in ranges) + assert ranges[0]["start"] == 0 and ranges[-1]["end"] == 9 + assert all(a["end"] == b["start"] for a, b in zip(ranges, ranges[1:])) + assert all(page["page"]["truncated_oversized_turn"] for page in fragments) + events = [event for page in chronological for event in page["events"]] + target = [event for event in events if event.get("turn_id") == "execution"] + assert [event["turn_seq"] for event in target] == list(range(1, 10)) + assert [event["event"] for event in target[1:4]] == ["delta", "delta", "stream_end"] + assert [event["text"] for event in target[1:4]] == ["![plot](diagram", ".png)", "![plot](/api/media/signed)"] + progress = [event for event in target if event.get("kind") == "progress"] + assert [event["text"] for event in progress] == ["trace one with full detail", "trace two with full detail"] + assert all("trace_detail" not in event for event in progress) + assert len({event["projection_id"] for event in events}) == len(events) + + forwards = [read(after=_legacy_cursor(0))] + while forwards[-1]["page"]["has_more_after"]: + forwards.append(read(after=forwards[-1]["page"]["after_cursor"])) + assert len(forwards) < 20 + forward_events = [event for page in forwards for event in page["events"]] + assert forward_events == events + + prompts = history.prompts(key) + assert [p["preview"] for p in prompts] == ["previous", "first", "second", "next"] + for offset, prompt in enumerate(prompts): + page = read(after=prompt["cursor"]) + assert page["events"][0]["projection_id"] == prompt["id"] + assert page["page"]["user_message_offset"] == offset + + old = read(after=_legacy_cursor(1)) + assert old["events"][0]["text"] == "first" + + +def test_page_generation_is_stable_across_appends_and_changes_after_recreation(history): + key = "websocket:page-generation" + history.append(key, {"event": "user", "text": "first"}) + first = history.build(key)["page"]["history_generation"] + history.append(key, {"event": "message", "text": "answer"}) + assert history.build(key)["page"]["history_generation"] == first + history.sessions.delete_session(key) + history.append(key, {"event": "user", "text": "replacement"}) + assert history.build(key)["page"]["history_generation"] != first + + +def test_single_record_larger_than_page_budget_still_makes_progress(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_BYTES", 200) + key = "websocket:large-record" + for record in ( + {"event": "user", "text": "x" * 400}, + {"event": "message", "text": "answer"}, + {"event": "turn_end"}, + ): + history.append(key, record) + stats = transcript.TranscriptReplayStats() + first = history.build(key, after=_legacy_cursor(0), stats=stats) + assert first["page"]["record_range"] == {"turn": 0, "start": 0, "end": 1} + assert first["events"][0]["text"] == "x" * 400 + assert 200 < stats.source_bytes < 1_000 + second = history.build(key, after=first["page"]["after_cursor"]) + assert second["page"]["record_range"]["start"] == 1 + assert history.build(key, before=second["page"]["before_cursor"])["events"] == first["events"] + + +def test_sliced_projection_retains_model_requests_and_stable_event_ids(history, monkeypatch): + key = "websocket:model-request-pages" + for record in ( + {"event": "user", "text": "question"}, + {"event": "model_request", "request_id": "r", "run_id": "run", "sequence": 1, "phase": "started"}, + {"event": "message", "text": "answer"}, + {"event": "turn_end"}, + ): + history.append(key, record) + complete = history.build(key, include_model_requests=True) + assert "record_range" not in complete["page"] + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 2) + first = history.build(key, after=_legacy_cursor(0), include_model_requests=True) + second = history.build(key, after=first["page"]["after_cursor"], include_model_requests=True) + assert [event["event"] for event in first["events"]] == ["user_message", "model_request"] + assert first["events"] + second["events"] == complete["events"] + without_requests = history.build(key, after=_legacy_cursor(0)) + assert [event["event"] for event in without_requests["events"]] == ["user_message"] + assert without_requests["page"]["after_cursor"] == first["page"]["after_cursor"] + + +def test_stale_trace_reference_does_not_read_an_oversized_turn(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + monkeypatch.setattr(transcript, "_MAX_INLINE_TRACE_DETAIL_BYTES", 10) + key = "websocket:trace-grows" + history.append(key, {"event": "user", "text": "question"}) + history.append(key, {"event": "message", "kind": "progress", "text": "full trace text"}) + page = history.build(key) + reference = next(event["trace_detail"]["ref"] for event in page["events"] if event.get("trace_detail")) + assert history.trace(key, reference) is not None + history.append(key, {"event": "message", "kind": "progress", "text": "another trace"}) + history.append(key, {"event": "message", "kind": "progress", "text": "yet another trace"}) + assert history.trace(key, reference) is None + + +@pytest.mark.asyncio +async def test_http_defaults_to_record_pages_and_accepts_legacy_turn_cursor(history, tmp_path, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 2) + key = "websocket:http-pages" + for record in ( + {"event": "user", "text": "first"}, + {"event": "message", "text": "one"}, + {"event": "user", "text": "second"}, + {"event": "message", "text": "two"}, + {"event": "turn_end"}, + ): + history.append(key, record) + gateway = build_gateway_services( + config=WebSocketConfig(), bus=MessageBus(), session_manager=history.sessions, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + headers = Headers([("Authorization", "Bearer test-token")]) + path = "/api/sessions/websocket%3Ahttp-pages/webui-thread" + + async def get(query): + response = await gateway.http._dispatch_session_routes(Request(path + query, headers), path) + assert response.status_code == 200 + return json.loads(response.body) + + latest = await get("") + assert latest["page"]["record_range"] == {"turn": 0, "start": 3, "end": 5} + earlier = await get("?before=" + latest["page"]["before_cursor"]) + assert earlier["page"]["record_range"] == {"turn": 0, "start": 1, "end": 3} + from_legacy = await get("?after=" + _legacy_cursor(0)) + assert from_legacy["page"]["record_range"] == {"turn": 0, "start": 0, "end": 2} + response = await gateway.http._dispatch_session_routes(Request(path + "/prompts", headers), path + "/prompts") + assert response.status_code == 200 + prompts = json.loads(response.body) + second = await get("?after=" + prompts["prompts"][1]["cursor"]) + assert second["events"][0]["projection_id"] == prompts["prompts"][1]["id"] + assert second["page"]["user_message_offset"] == 1 + + +def test_compaction_does_not_reuse_the_source_record_budget(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 10) + key = "websocket:compacted-source-budget" + for i in range(3): + for row in [ + {"event": "user", "text": f"question {i}"}, + *({"event": "delta", "text": "x"} for _ in range(4)), + {"event": "stream_end", "text": "xxxx"}, + {"event": "turn_end"}, + ]: + history.append(key, row) + stats = transcript.TranscriptReplayStats() + latest = history.build(key, limit=100, stats=stats) + assert stats.parsed_records == 7 + assert stats.compacted_delta_records == 4 + assert len(latest["events"]) == 3 + assert "record_range" not in latest["page"] + assert latest["page"]["has_more_before"] + + +def test_source_budget_accounts_for_graphs_larger_in_storage(history, monkeypatch): + key = "websocket:graph-byte-budget" + graph = {"nodes": [{"path": "/a", "name": "a", "tokens": 1, "state": "loaded"}], "edges": []} + rows = [ + {"event": "user", "text": "question", "created_at_ms": 1}, + *({"event": "model_request", "request_id": str(i), "run_id": "run", "sequence": 1, + "phase": "started", "context_graph": graph, "created_at_ms": 1} for i in range(2)), + {"event": "turn_end", "created_at_ms": 1}, + ] + encoded = [fact_from_record(row).encode() for row in rows] + logical = sum(history_record_size(record) for record in encoded) + actual = sum(max(history_record_size(record), len(record.encode("utf-8"))) for record in encoded) + assert logical < actual + for row in rows: + history.append(key, row) + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_BYTES", logical) + stats = transcript.TranscriptReplayStats() + first = history.build(key, after=_legacy_cursor(0), include_model_requests=True, stats=stats) + assert first["page"]["record_range"]["start"] == 0 + assert stats.source_bytes <= logical + assert stats.capped_by_bytes + second = history.build(key, after=first["page"]["after_cursor"], include_model_requests=True) + assert second["page"]["record_range"]["start"] == first["page"]["record_range"]["end"] + events = first["events"] + second["events"] + assert [event["event"] for event in events] == ["user_message", "model_request", "model_request", "turn_end"] + assert all(event["context_graph"] == graph for event in events if event["event"] == "model_request") + + # Stored turn aggregates can understate bytes when a small compressed graph + # expands. If an earlier turn already occupies the page, do not mix a + # partially read next turn into it or lose the next turn's boundary. + other = "websocket:graph-after-normal-turn" + previous = [{"event": "user", "text": "previous", "created_at_ms": 1}, + {"event": "turn_end", "created_at_ms": 1}] + for row in [*previous, *rows]: + history.append(other, row) + previous_bytes = sum(history_record_size(fact_from_record(row).encode()) for row in previous) + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_BYTES", logical + previous_bytes) + stats = transcript.TranscriptReplayStats() + initial = history.build(other, after=_legacy_cursor(0), include_model_requests=True, stats=stats) + assert [event["event"] for event in initial["events"]] == ["user_message", "turn_end"] + assert "record_range" not in initial["page"] + assert stats.capped_by_bytes and stats.source_bytes <= logical + previous_bytes + following = history.build(other, after=initial["page"]["after_cursor"], include_model_requests=True) + assert [event["event"] for event in following["events"]] == ["user_message", "model_request", "model_request", "turn_end"] + + +@pytest.mark.parametrize("user_position", [0, 13]) +def test_oversized_incomplete_turn_recovers_once_across_all_fragments(history, monkeypatch, user_position): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4) + key = "websocket:incomplete-record-pages" + turn_id = "incomplete-turn" + rows = [ + {"event": "user", "text": "unique question", "turn_id": turn_id}, + {"event": "delta", "text": "partial", "turn_id": turn_id}, + *({"event": "message", "kind": "progress", "text": f"step {i}", "turn_id": turn_id} + for i in range(20)), + {"event": "turn_end", "turn_id": turn_id, "transcript_incomplete": True}, + ] + user = rows.pop(0) + rows.insert(user_position, user) + for row in rows: + history.append(key, row) + original_history = history.read(key) + messages = [ + {"role": "user", "content": "unique question"}, + {"role": "assistant", "content": "complete canonical answer"}, + ] + def read(**kwargs): + stats = transcript.TranscriptReplayStats() + page = history.build(key, session_messages=messages, stats=stats, **kwargs) + assert stats.parsed_records <= 4 + assert stats.source_bytes <= transcript._MAX_TRANSCRIPT_PAGE_BYTES + return page + + pages = [read(after=_legacy_cursor(0))] + while pages[-1]["page"]["has_more_after"]: + pages.append(read(after=pages[-1]["page"]["after_cursor"])) + assert len(pages) < len(rows) + events = [event for page in pages for event in page["events"]] + assert [event["text"] for event in events if event["event"] == "message" and not event.get("kind")] == [ + "complete canonical answer", + ] + assert not any(event["event"] == "delta" for event in events) + assert pages[-1]["completed_turn_ids"] == [turn_id] + assert pages[-1]["has_pending_tool_calls"] is False + assert len({event["projection_id"] for event in events}) == len(events) + ranges = [page["page"]["record_range"] for page in pages] + assert ranges[0]["start"] == 0 and ranges[-1]["end"] == len(rows) + assert all(left["end"] == right["start"] for left, right in zip(ranges, ranges[1:])) + recovered = next(event for event in events if event.get("text") == "complete canonical answer") + latest = read() + assert latest["page"]["recovered_answers"] is True + assert next(event for event in latest["events"] if event.get("text") == recovered["text"]) == recovered + for left, right in zip(pages, pages[1:]): + assert read(before=right["page"]["before_cursor"])["events"] == left["events"] + assert history.read(key) == original_history + + +def test_oversized_legacy_prompt_cursor_finds_backfilled_user_on_cold_page(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 4) + key = "websocket:legacy-record-pages" + rows = [ + *({"event": "message", "kind": "progress", "text": f"step {i}"} for i in range(20)), + {"event": "message", "text": "distinct answer"}, + {"event": "turn_end"}, + ] + for row in rows: + history.append(key, row) + messages = [ + {"role": "user", "content": "restored question"}, + {"role": "assistant", "content": "distinct answer"}, + ] + prompts = history.prompts(key, session_messages_loader=lambda: messages) + assert [prompt["preview"] for prompt in prompts] == ["restored question"] + transcript._PROMPT_SNAPSHOTS.clear() + def read(**kwargs): + stats = transcript.TranscriptReplayStats() + page = history.build(key, session_messages=messages, stats=stats, **kwargs) + assert stats.parsed_records <= 4 + assert stats.source_bytes <= transcript._MAX_TRANSCRIPT_PAGE_BYTES + return page + + page = read(after=prompts[0]["cursor"]) + assert page["events"][0]["event"] == "user_message" + assert page["events"][0]["projection_id"] == prompts[0]["id"] + pages = [page] + while pages[-1]["page"]["has_more_after"]: + pages.append(read(after=pages[-1]["page"]["after_cursor"])) + assert len(pages) < len(rows) + events = [event for current in pages for event in current["events"]] + assert [event["text"] for event in events if event["event"] == "user_message"] == ["restored question"] + assert [event["text"] for event in events if event["event"] == "message" and not event.get("kind")] == [ + "distinct answer", + ] + + +def test_recovered_prompt_cursor_keeps_answers_owned_by_both_inputs(history): + key = "websocket:backfilled-input-recovery" + rows = [ + {"event": "user", "text": "A", "input_id": "user:a", "turn_id": "t", "turn_seq": 1}, + {"event": "message", "text": "Answer A", "response_input_ids": ["user:a"], "turn_id": "t", "turn_seq": 2}, + {"event": "message", "kind": "progress", "text": "Working", "turn_id": "t", "turn_seq": 3}, + {"event": "message", "text": "Answer B", "response_input_ids": ["user:b"], "turn_id": "t", "turn_seq": 4}, + {"event": "message", "kind": "progress", "text": "Finished", "turn_id": "t", "turn_seq": 5}, + {"event": "turn_end", "turn_id": "t", "turn_seq": 6, "transcript_incomplete": True}, + ] + for row in rows: + history.append(key, row) + original = history.read(key) + messages = [ + {"role": "user", "content": "A", "input_id": "user:a"}, + {"role": "assistant", "content": "Answer A", "response_input_ids": ["user:a"]}, + {"role": "user", "content": "B", "input_id": "user:b"}, + {"role": "assistant", "content": "Answer B", "response_input_ids": ["user:b"]}, + ] + whole = history.build(key, session_messages=messages) + prompts = history.prompts(key, session_messages_loader=lambda: messages) + prompt = next(item for item in prompts if item["inputId"] == "user:b") + navigated = history.build(key, after=prompt["cursor"], session_messages=messages) + + def contents(body): + return [event["text"] for event in body["events"] + if event["event"] in {"user_message", "message"} and not event.get("kind")] + + assert contents(whole) == ["A", "Answer A", "B", "Answer B"] + assert contents(navigated) == ["B", "Answer B"] + assert navigated["events"][0]["projection_id"] == prompt["id"] + assert whole["completed_turn_ids"] == navigated["completed_turn_ids"] == [] + assert navigated["has_pending_tool_calls"] is True + assert history.read(key) == original + + +@pytest.mark.parametrize("ambiguous", ["duplicate-canonical-user", "two-physical-users"]) +def test_sliced_incomplete_turn_preserves_partial_answers_when_match_is_ambiguous(history, monkeypatch, ambiguous): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + key = f"websocket:ambiguous-fragments-{ambiguous}" + rows = [ + {"event": "user", "text": "same question", "turn_id": "t"}, + {"event": "delta", "text": "partial", "turn_id": "t"}, + *({"event": "message", "kind": "progress", "text": f"step {i}", "turn_id": "t"} for i in range(8)), + {"event": "turn_end", "turn_id": "t", "transcript_incomplete": True}, + ] + if ambiguous == "two-physical-users": + rows.insert(7, {"event": "user", "text": "another question", "turn_id": "t"}) + for row in rows: + history.append(key, row) + messages = [{"role": "user", "content": "same question"}, {"role": "assistant", "content": "answer"}] + if ambiguous == "duplicate-canonical-user": + messages += [{"role": "user", "content": "same question"}, {"role": "assistant", "content": "another answer"}] + pages = [history.build(key, after=_legacy_cursor(0), session_messages=messages)] + while pages[-1]["page"]["has_more_after"]: + pages.append(history.build(key, after=pages[-1]["page"]["after_cursor"], session_messages=messages)) + events = [event for page in pages for event in page["events"]] + assert [event["text"] for event in events if event["event"] == "delta"] == ["partial"] + assert not any(event.get("text") in {"answer", "another answer"} for event in events) + assert pages[-1]["completed_turn_ids"] == [] + assert pages[-1]["has_pending_tool_calls"] is True + + +def test_legacy_fragment_does_not_backfill_when_user_is_in_another_slice(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + key = "websocket:physical-user-in-later-slice" + rows = [ + *({"event": "message", "kind": "progress", "text": f"step {i}"} for i in range(5)), + {"event": "user", "text": "real user"}, + {"event": "message", "text": "answer"}, + {"event": "turn_end"}, + ] + for row in rows: + history.append(key, row) + messages = [{"role": "user", "content": "wrong user"}, {"role": "assistant", "content": "answer"}] + page = history.build(key, after=_legacy_cursor(0), session_messages=messages) + assert all(event["event"] != "user_message" for event in page["events"]) + prompts = history.prompts(key, session_messages_loader=lambda: messages) + assert [prompt["preview"] for prompt in prompts] == ["real user"] + + +def test_byte_limited_terminal_fragment_recovers_the_answer(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 100) + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_BYTES", 500) + key = "websocket:recovery-byte-budget" + rows = [ + {"event": "user", "text": "question"}, + *({"event": "message", "kind": "progress", "text": "x" * 150} for _ in range(6)), + {"event": "turn_end", "turn_id": "t", "transcript_incomplete": True}, + ] + for row in rows: + history.append(key, row) + messages = [{"role": "user", "content": "question"}, {"role": "assistant", "content": "answer"}] + stats = transcript.TranscriptReplayStats() + page = history.build(key, session_messages=messages, stats=stats) + assert page["completed_turn_ids"] == ["t"] + assert stats.source_bytes <= 500 + pages = [page] + while pages[-1]["page"]["has_more_before"]: + pages.append(history.build(key, session_messages=messages, before=pages[-1]["page"]["before_cursor"])) + answers = [event["text"] for page in pages for event in page["events"] + if event["event"] == "message" and not event.get("kind")] + assert answers == ["answer"] + + +def test_complete_single_user_fragment_keeps_normal_budget_without_loading_canonical(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + key = "websocket:complete-single-user-fragment" + for row in [ + {"event": "user", "text": "question"}, + *({"event": "message", "kind": "progress", "text": "step"} for _ in range(8)), + {"event": "message", "text": "answer"}, + {"event": "turn_end"}, + ]: + history.append(key, row) + + def fail_if_loaded(): + pytest.fail("a complete fragment must not load canonical history") + + stats = transcript.TranscriptReplayStats() + page = history.build(key, after=_legacy_cursor(0), session_messages_loader=fail_if_loaded, stats=stats) + assert page["page"]["record_range"] == {"turn": 0, "start": 0, "end": 3} + assert stats.parsed_records == 3 + assert stats.source_bytes <= transcript._MAX_TRANSCRIPT_PAGE_BYTES + + +def test_legacy_prompt_id_agrees_with_warm_and_cold_snapshots(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + key = "websocket:legacy-prompt-snapshot" + for row in [ + *({"event": "message", "kind": "progress", "text": "step"} for _ in range(8)), + {"event": "message", "text": "answer"}, + {"event": "turn_end"}, + ]: + history.append(key, row) + messages = [{"role": "user", "content": "question"}, {"role": "assistant", "content": "answer"}] + + def version(): + return ("canonical-generation", 1) + + response = history.prompt_response(key, None, session_messages_loader=lambda: messages, session_version_loader=version) + prompt = response["prompts"][0] + warm = history.build(key, after=prompt["cursor"], session_messages=messages, session_version_loader=version) + assert warm["events"][0]["projection_id"] == prompt["id"] + transcript._PROMPT_SNAPSHOTS.clear() + cold = history.build(key, after=prompt["cursor"], session_messages=messages, session_version_loader=version) + assert cold["events"] == warm["events"] + + +def test_legacy_backfill_does_not_make_an_incomplete_turn_physically_recoverable(history, monkeypatch): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + key = "websocket:legacy-incomplete-without-physical-user" + for row in [ + *({"event": "message", "kind": "progress", "text": f"step {i}"} for i in range(7)), + {"event": "message", "text": "partial answer"}, + {"event": "turn_end", "turn_id": "t", "transcript_incomplete": True}, + ]: + history.append(key, row) + messages = [{"role": "user", "content": "restored question"}, + {"role": "assistant", "content": "partial answer"}] + pages = [history.build(key, after=_legacy_cursor(0), session_messages=messages)] + while pages[-1]["page"]["has_more_after"]: + pages.append(history.build(key, after=pages[-1]["page"]["after_cursor"], session_messages=messages)) + events = [event for page in pages for event in page["events"]] + assert [event["text"] for event in events if event["event"] == "user_message"] == ["restored question"] + assert [event["text"] for event in events if event["event"] == "message" and not event.get("kind")] == ["partial answer"] + assert pages[-1]["completed_turn_ids"] == [] + assert pages[-1]["has_pending_tool_calls"] is True + + +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy", [False, True]) +async def test_http_fragment_recovery_reads_persisted_canonical_history(history, tmp_path, monkeypatch, legacy): + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 3) + key = f"websocket:http-recovery-{legacy}" + session = history.sessions.get_or_create(key) + session.add_message("user", "question") + session.add_message("assistant", "canonical answer") + history.sessions.save(session) + rows = [ + *({"event": "message", "kind": "progress", "text": f"step {i}"} for i in range(8)), + {"event": "message" if legacy else "delta", "text": "canonical answer" if legacy else "partial"}, + {"event": "turn_end", "turn_id": "t", **({} if legacy else {"transcript_incomplete": True})}, + ] + if not legacy: + rows.insert(5, {"event": "user", "text": "question"}) + for row in rows: + history.append(key, row) + original = history.read(key) + gateway = build_gateway_services( + config=WebSocketConfig(), bus=MessageBus(), session_manager=history.sessions, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + headers = Headers([("Authorization", "Bearer test-token")]) + path = "/api/sessions/" + key.replace(":", "%3A") + "/webui-thread" + + async def get(query): + response = await gateway.http._dispatch_session_routes(Request(path + query, headers), path) + assert response.status_code == 200 + return json.loads(response.body) + + if legacy: + response = await gateway.http._dispatch_session_routes(Request(path + "/prompts", headers), path + "/prompts") + assert response.status_code == 200 + prompt = json.loads(response.body)["prompts"][0] + transcript._PROMPT_SNAPSHOTS.clear() + first = await get("?after=" + prompt["cursor"]) + assert first["events"][0]["projection_id"] == prompt["id"] + else: + first = await get("?after=" + _legacy_cursor(0)) + pages = [first] + while pages[-1]["page"]["has_more_after"]: + pages.append(await get("?after=" + pages[-1]["page"]["after_cursor"])) + assert len(pages) <= len(rows) + events = [event for page in pages for event in page["events"]] + assert [event["text"] for event in events if event["event"] == "user_message"] == ["question"] + assert [event["text"] for event in events if event["event"] == "message" and not event.get("kind")] == ["canonical answer"] + assert not any(event["event"] == "delta" for event in events) + assert pages[-1]["completed_turn_ids"] == ["t"] + assert pages[-1]["has_pending_tool_calls"] is False + assert history.read(key) == original diff --git a/tests/webui/test_stream_snapshots.py b/tests/webui/test_stream_snapshots.py new file mode 100644 index 000000000..19f5c1c94 --- /dev/null +++ b/tests/webui/test_stream_snapshots.py @@ -0,0 +1,167 @@ +import json +import sqlite3 +import time +from contextlib import closing +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from websockets.datastructures import Headers +from websockets.http11 import Request + +from nanobot.bus.events import OutboundMessage +from nanobot.bus.outbound_events import ProgressEvent, TurnEndEvent +from nanobot.bus.queue import MessageBus +from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig +from nanobot.session.manager import SessionManager +from nanobot.webui import transcript +from nanobot.webui.gateway_services import build_gateway_services +from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY + + +def _gateway(history, tmp_path, monkeypatch): + def media_dir(channel=None): + path = tmp_path / "media" / (channel or "") + path.mkdir(parents=True, exist_ok=True) + return path + + monkeypatch.setattr("nanobot.webui.media_gateway.get_media_dir", media_dir) + monkeypatch.setattr("nanobot.webui.gateway_services.get_media_dir", media_dir) + bus = MessageBus() + gateway = build_gateway_services( + config=WebSocketConfig(), bus=bus, session_manager=history.sessions, + static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json", + default_restrict_to_workspace=False, runtime_model_name=None, + runtime_surface="browser", runtime_capabilities_overrides=None, + ) + channel = WebSocketChannel({"enabled": True, "allowFrom": ["*"], "streaming": True}, bus, gateway=gateway) + return gateway, channel + + +async def _http_thread(gateway, chat_id, query=""): + gateway.tokens.api_tokens["test-token"] = time.monotonic() + 60 + headers = Headers([("Authorization", "Bearer test-token")]) + path = f"/api/sessions/websocket%3A{chat_id}/webui-thread" + response = await gateway.http._dispatch_session_routes(Request(path + query, headers), path) + assert response.status_code == 200 + return json.loads(response.body) + + +def _frames(ws): + return [json.loads(call.args[0]) for call in ws.send.await_args_list] + + +def _stored_records(sessions): + with closing(sqlite3.connect(sessions.sessions_dir / "sessions.sqlite3")) as db: + return db.execute("SELECT session_key, turn_ordinal, position, record FROM history_entries ORDER BY session_key, turn_ordinal, position").fetchall() + + +@pytest.mark.asyncio +async def test_signed_snapshots_survive_http_pagination_and_restart_without_rewriting_history(history, tmp_path, monkeypatch): + (tmp_path / "diagram.png").write_bytes(b"\x89PNG\r\n\x1a\nimage") + gateway, channel = _gateway(history, tmp_path, monkeypatch) + ws = AsyncMock() + channel._attach(ws, "snapshots") + metadata = await history.metadata("snapshots", {WEBUI_TURN_METADATA_KEY: "turn-one"}) + + async def delta(text, stream="primary", **kwargs): + await channel.send_delta("snapshots", text, metadata, stream_id=stream, **kwargs) + + await gateway.transcripts.append_user_message("snapshots", "draw it", metadata=metadata) + await delta("![plot](diagram") + await channel.send(OutboundMessage(channel="websocket", chat_id="snapshots", content="tool()", + event=ProgressEvent(content="tool()"), metadata=metadata)) + await channel.send_reasoning_delta("snapshots", "thinking", metadata, stream_id="primary") + await delta(".png)") + await delta("unrelated", stream="other") + await delta("", stream_end=True, resuming=True, merge_next=True) + await delta(" more") + await delta("", stream_end=True) + await channel.send_reasoning_end("snapshots", metadata, stream_id="primary") + await delta("", stream="other", stream_end=True) + await channel.send(OutboundMessage(channel="websocket", chat_id="snapshots", content="", + event=TurnEndEvent(), metadata=metadata)) + + live = _frames(ws) + frames = [frame for frame in live if frame["event"] == "delta"] + first, second, _ = [frame for frame in live if frame["event"] == "stream_end"] + assert "diagram.png" in "".join(frame["text"] for frame in frames) + assert "/api/media/" in first["text"] and second["text"] == first["text"] + " more" + stored = history.read("websocket:snapshots") + ends = [row for row in stored if row["event"] == "stream_end"] + assert [row["text"] for row in ends] == [first["text"], second["text"], "unrelated"] + reasoning = next(row for row in stored if row["event"] == "reasoning_end") + assert reasoning["text"] == "thinking" + assert [row["text_from_seq"] for row in ends] == [frames[0]["turn_seq"], frames[0]["turn_seq"], frames[2]["turn_seq"]] + assert reasoning["text_from_seq"] == next(frame["turn_seq"] for frame in live if frame["event"] == "reasoning_delta") + assert all(row["event"] not in {"delta", "reasoning_delta"} for row in stored) + records = _stored_records(history.sessions) + assert "diagram.png" not in json.dumps(records) + complete = await _http_thread(gateway, "snapshots") + projected = [event for event in complete["events"] if event["event"] == "stream_end"] + assert [(event["stream_id"], event["turn_seq"], event["text"]) for event in projected] == [ + (row["stream_id"], row["turn_seq"], row["text"]) for row in ends + ] + signed_url = first["text"].split("(", 1)[1].split(")", 1)[0] + _, _, _, signature, signed_payload = signed_url.split("/") + assert gateway.media.serve_signed_media(signature, signed_payload).status_code == 200 + + monkeypatch.setattr(transcript, "_MAX_TRANSCRIPT_PAGE_RECORDS", 2) + + async def all_pages(owner): + pages = [await _http_thread(owner, "snapshots")] + while pages[-1]["page"]["has_more_before"]: + pages.append(await _http_thread(owner, "snapshots", "?before=" + pages[-1]["page"]["before_cursor"])) + assert len(pages) <= len(stored) + pages.reverse() + ranges = [page["page"]["record_range"] for page in pages] + assert ranges[0]["start"] == 0 and ranges[-1]["end"] == len(stored) + assert all(left["end"] == right["start"] for left, right in zip(ranges, ranges[1:])) + assert [event for page in pages for event in page["events"]] == complete["events"] + assert pages[-1]["completed_turn_ids"] == ["turn-one"] + return pages + + pages = await all_pages(gateway) + assert _stored_records(history.sessions) == records + await history.sessions.state.aclose() + restarted_sessions = SessionManager(tmp_path) + try: + restarted, _ = _gateway(SimpleNamespace(sessions=restarted_sessions), tmp_path, monkeypatch) + restarted_pages = await all_pages(restarted) + assert [page["page"] for page in restarted_pages] == [page["page"] for page in pages] + assert _stored_records(restarted_sessions) == records + finally: + await restarted_sessions.state.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("reasoning", [False, True]) +async def test_snapshot_coverage_follows_buffer_resets_after_a_failed_append(history, tmp_path, monkeypatch, reasoning): + gateway, channel = _gateway(history, tmp_path, monkeypatch) + ws = AsyncMock() + channel._attach(ws, "reset") + metadata = await history.metadata("reset", {WEBUI_TURN_METADATA_KEY: "turn-reset"}) + + async def chunk(text): + if reasoning: + await channel.send_reasoning_delta("reset", text, metadata) + else: + await channel.send_delta("reset", text, metadata) + + async def end(): + if reasoning: + await channel.send_reasoning_end("reset", metadata) + else: + await channel.send_delta("reset", "", metadata, stream_end=True) + + await chunk("not persisted") + with monkeypatch.context() as patch: + patch.setattr(gateway.transcripts, "append", AsyncMock(return_value=False)) + await end() + await chunk("next buffer") + await end() + frames = _frames(ws) + snapshot = history.read("websocket:reset")[0] + assert snapshot["text"] == "next buffer" + assert snapshot["text_from_seq"] == frames[2]["turn_seq"] > frames[1]["turn_seq"] + assert frames[3]["text_from_seq"] == snapshot["text_from_seq"] diff --git a/webui/browser/history-hydration.spec.ts b/webui/browser/history-hydration.spec.ts index 0474f2e8f..ec766fa51 100644 --- a/webui/browser/history-hydration.spec.ts +++ b/webui/browser/history-hydration.spec.ts @@ -22,7 +22,7 @@ function delta(sequence: number, text: string, streamId = "live-wire"): ThreadPr return { ...at(TURN, sequence, "answer"), event: "delta", stream_id: streamId, text }; } -function end(sequence: number, text: string, streamId: string, merge = false): ThreadProjectionEvent { +function end(sequence: number, text: string, streamId: string, merge = false): Extract { return { ...at(TURN, sequence, "answer"), event: "stream_end", stream_id: streamId, text, ...(merge ? { resuming: true, merge_next: true } : { resuming: true }) }; } @@ -157,6 +157,99 @@ async function expectBefore(body: Locator, first: string, second: string) { expect(text.indexOf(second), `${second} must follow ${first}`).toBeGreaterThan(text.indexOf(first)); } +test("loading an earlier fragment restores a long turn without duplicating its answer", async ({ page }) => { + const { backend, body } = await openFixture(page); + const events: ThreadProjectionEvent[] = [ + input(TURN, "Long-turn question"), + end(1, "First answer segment.", "long-wire", true), + { ...at(TURN, 2, "activity"), event: "message", kind: "tool_hint", text: "Inspecting long history" }, + end(3, "First answer segment. Final answer segment.", "long-wire"), + { ...at(TURN, 4, "complete"), event: "turn_end" }, + ]; + const tail = history(events.slice(3), { before: "inside-turn", more: true }); + tail.page = { ...tail.page, record_range: { turn: 0, start: 3, end: 5 }, truncated_oversized_turn: true }; + await backend.release(await backend.read(), tail); + await expect(body.getByText("First answer segment. Final answer segment.", { exact: true })).toBeVisible(); + + const older = await requestOlder(page, backend, body, "inside-turn"); + const prefix = history(events.slice(0, 3)); + prefix.page = { ...prefix.page, record_range: { turn: 0, start: 0, end: 3 }, truncated_oversized_turn: true }; + await backend.release(older, prefix); + await expect(body.getByText("Long-turn question", { exact: true })).toHaveCount(1); + await expect(body.getByText("First answer segment.", { exact: true })).toHaveCount(1); + await expect(body.getByText("Final answer segment.", { exact: true })).toHaveCount(1); + await expectBefore(body, "Long-turn question", "Final answer segment."); + const answer = body.locator("[data-thread-display-unit]").filter({ has: page.getByText("Final answer segment.", { exact: true }) }); + await answer.hover(); + await answer.getByRole("button", { name: "Message actions", exact: true }).click(); + await page.locator("[data-message-block-activity-action]").click(); + await expect(answer.getByText("Completed step Inspecting long history", { exact: true })).toBeVisible(); + backend.healthy(); +}); + +test("canonical recovery replaces the partial answer in an open oversized turn", async ({ page }) => { + const { backend, body } = await openFixture(page); + const active = history([end(3, "Partial answer", "partial-wire")], { before: "before-1", more: true, active: TURN }); + active.page = { ...active.page, history_generation: "generation", record_range: { turn: 0, start: 1, end: 4001 }, truncated_oversized_turn: true }; + await backend.release(await backend.read(), active); + await expect(body.getByText("Partial answer", { exact: true })).toBeVisible(); + const recovered = history([ + { chat_id: A, turn_id: TURN, event: "message", text: "Correct final answer" }, + { ...at(TURN, 4002, "complete"), event: "turn_end" }, + ], { before: "before-2", more: true }); + recovered.page = { ...recovered.page, history_generation: "generation", record_range: { turn: 0, start: 2, end: 4002 }, + truncated_oversized_turn: true, recovered_answers: true }; + backend.refreshThread(); + await backend.release(await backend.read(A, null, 1), recovered); + await expect(body.getByText("Correct final answer", { exact: true })).toBeVisible(); + await expect(body.getByText("Partial answer", { exact: true })).toHaveCount(0); + await page.reload(); + await backend.ready(); + await backend.release(await backend.read(A, null, 2), recovered); + await expect(body.getByText("Correct final answer", { exact: true })).toHaveCount(1); + await expect(body.getByText("Partial answer", { exact: true })).toHaveCount(0); + backend.healthy(); +}); + +test("prepending a fragment keeps the same answer at the reading position", async ({ page }) => { + const { backend, body } = await openFixture(page); + const prefix: ThreadProjectionEvent[] = [ + input(TURN, "Earlier question"), + end(1, "Earlier answer", "earlier-wire"), + { ...at(TURN, 2, "activity"), event: "message", kind: "tool_hint", text: "Earlier tool" }, + ]; + const tail: ThreadProjectionEvent[] = []; + for (let index = 0; index < 24; index++) { + tail.push(end(3 + index * 2, `Tail answer ${index}`, `tail-${index}`)); + tail.push({ ...at(TURN, 4 + index * 2, "activity"), event: "message", kind: "tool_hint", text: `Tail tool ${index}` }); + } + tail.push({ ...at(TURN, 51, "complete"), event: "turn_end" }); + const latest = history(tail, { before: "inside-turn", more: true }); + latest.page = { ...latest.page, record_range: { turn: 0, start: 3, end: 3 + tail.length }, truncated_oversized_turn: true }; + await backend.release(await backend.read(), latest); + await expect(body.getByText("Tail answer 23", { exact: true })).toBeAttached(); + const older = await requestOlder(page, backend, body, "inside-turn"); + const anchor = body.getByText("Tail answer 5", { exact: true }); + await expect(anchor).toBeAttached(); + await body.evaluate(async (node) => { + const unit = Array.from(node.querySelectorAll("[data-thread-display-unit]")) + .find((item) => item.textContent?.includes("Tail answer 5"))!; + // Establish the reading anchor through the native scroll event before HTTP commits. + const scrolled = new Promise((resolve) => node.addEventListener("scroll", () => resolve(), { once: true })); + node.scrollTop += unit.getBoundingClientRect().top - node.getBoundingClientRect().top - 280; + await scrolled; + }); + const position = () => anchor.evaluate((node) => node.getBoundingClientRect().top); + const before = await position(); + const first = history(prefix); + first.page = { ...first.page, record_range: { turn: 0, start: 0, end: 3 }, truncated_oversized_turn: true }; + await backend.release(older, first); + await expect(body.getByText("Earlier question", { exact: true })).toBeAttached(); + await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0); + await expect.poll(async () => Math.abs((await position()) - before)).toBeLessThan(2); + backend.healthy(); +}); + test("idle compaction stays singular across live updates, thread refresh and cold replay", async ({ page }) => { const { backend, body } = await openFixture(page); const base = closedTurn("idle-completed", "Before idle compression", "Completed answer before idle compression."); @@ -322,7 +415,8 @@ test("synthetic HTTP-first cumulative text suppresses delayed covered chunks but const { backend, body } = await openFixture(page); const latest = await backend.read(); const canonical = "Canonical answer"; - await backend.release(latest, history([input(TURN, "HTTP-first question"), end(3, canonical, "resume-wire", true)], { active: TURN })); + await backend.release(latest, history([input(TURN, "HTTP-first question"), + { ...end(3, canonical, "resume-wire", true), text_from_seq: 1 }], { active: TURN })); await expect(body.getByText(canonical, { exact: true })).toBeVisible(); await backend.send(delta(1, "Canonical ", "resume-wire")); diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx index 9c5cb4104..1e887054c 100644 --- a/webui/src/components/thread/ThreadMessages.tsx +++ b/webui/src/components/thread/ThreadMessages.tsx @@ -136,6 +136,7 @@ export function ThreadMessages({ ? activeTurnStartIndex(units, activeTurnId) : units.length; const unitKeys = useMemo(() => unitKeysForDisplay(units), [units]); + const scrollAnchors = useMemo(() => scrollAnchorsForUnits(units), [units]); const messageBlocks = useMemo( () => completedMessageBlocks( units, @@ -251,6 +252,7 @@ export function ThreadMessages({ { + const messages = unit.type === "message" ? [unit.message] : unit.messages; + // Either edge of an activity cluster can survive when the other grows. + const edges = messages.length > 1 ? [messages[0], messages[messages.length - 1]] : messages; + const streams: string[] = []; + const sequences: string[] = []; + const ids: string[] = []; + for (const message of edges) { + const stream = unit.type === "message" ? message.streamId : message.reasoningStreamId; + if (message.turnId && stream) streams.push(JSON.stringify([unit.type, "stream", message.turnId, stream])); + const sequence = message.projectionStartSeq ?? message.turnSeq; + if (message.turnId && Number.isFinite(sequence)) { + sequences.push(JSON.stringify([unit.type, "sequence", message.turnId, sequence])); + } + ids.push(JSON.stringify([unit.type, "id", message.id])); + } + return [...new Set([...streams, ...sequences, ...ids])]; + }); + const sourceCounts = new Map(); + const bases = units.map(unitKeyBase); + const baseCounts = new Map(); + for (const sources of sourceKeys) for (const source of sources) { + sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1); + } + for (const base of bases) baseCounts.set(base, (baseCounts.get(base) ?? 0) + 1); + return sourceKeys.map((sources, index) => ({ + sources: JSON.stringify(sources.filter((source) => sourceCounts.get(source) === 1)), + // A sole turn/phase row can keep its live identity when replay replaces + // both its source id and sequence. Occurrence keys are unsafe otherwise. + ...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1 + ? { fallback: bases[index] } : {}), + })); +} + function unitKeyBase(unit: DisplayUnit, index: number): string { if (unit.type === "activity") { const anchor = unit.messages[0]; diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 6650fb995..067d5d3ae 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -663,7 +663,7 @@ export function ThreadShell({ dismissStreamError, } = useNanobotStream( chatId, undefined, false, handleTurnEnd, undefined, undefined, - { key: historyKey, cache: messageCacheRef.current }, + { key: historyKey, cache: messageCacheRef.current, temporary }, ); const displayMessages = useMemo(() => projectWebuiThreadMessages(messages), [messages]); const initialHistoryLoading = loading; diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx index 1d81537c0..f5e807134 100644 --- a/webui/src/components/thread/ThreadViewport.tsx +++ b/webui/src/components/thread/ThreadViewport.tsx @@ -92,13 +92,25 @@ export const INITIAL_HISTORY_WINDOW = 120; export const HISTORY_WINDOW_INCREMENT = 120; interface HistoryScrollAnchor { - key: string; + sources: string[]; + fallback?: string; offsetTop: number; scrollTop: number; } const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]"; +function scrollSourceKind(source: string): string { + return (JSON.parse(source) as string[])[1]; +} + +function scrollSourcesDisagree(left: string[], right: string[], kind: string): boolean { + const leftKeys = left.filter((source) => scrollSourceKind(source) === kind); + const rightKeys = right.filter((source) => scrollSourceKind(source) === kind); + return leftKeys.length > 0 && rightKeys.length > 0 + && !leftKeys.some((source) => rightKeys.includes(source)); +} + function promptTopInset(scroller: HTMLElement): number { const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop); return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX; @@ -500,13 +512,19 @@ export const ThreadViewport = forwardRef= 0.5) { return captureHistoryScrollAnchor(); } - const element = Array.from( - content.querySelectorAll("[data-thread-display-unit]"), - ).find((candidate) => candidate.dataset.threadDisplayUnit === anchor.key); + const candidates = Array.from(content.querySelectorAll(THREAD_DISPLAY_UNIT_SELECTOR)); + const bySource = new Map(); + for (const candidate of candidates) { + const sources = JSON.parse(candidate.dataset.threadScrollSources ?? "[]") as string[]; + for (const source of sources) bySource.set(source, { element: candidate, sources }); + } + let element: HTMLElement | undefined; + for (const source of anchor.sources) { + const candidate = bySource.get(source); + if (!candidate) continue; + const kind = scrollSourceKind(source); + // An index-generated replay id can be reused by a different message. + if (kind !== "stream" && scrollSourcesDisagree(anchor.sources, candidate.sources, "stream")) continue; + if (kind === "id" && scrollSourcesDisagree(anchor.sources, candidate.sources, "sequence")) continue; + element = candidate.element; + break; + } + if (!element && anchor.fallback) { + element = candidates.find((candidate) => candidate.dataset.threadScrollFallback === anchor.fallback); + } if (!element) { historyScrollAnchorRef.current = null; return false; diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index b558198bb..2e3fb60ed 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -107,8 +107,8 @@ function transitionTurnDelivery( return changed ? next : messages; } -function createTranscript(messages: UIMessage[], saved: ThreadTranscriptSnapshot | undefined, historyKey: string | null) { - const owner = new ThreadTranscript(messages, saved); +function createTranscript(messages: UIMessage[], saved: ThreadTranscriptSnapshot | undefined, historyKey: string | null, temporary: boolean) { + const owner = new ThreadTranscript(messages, saved, { recordLiveContributions: !temporary }); // The first paint must not enter the welcome layout while history is pending. owner.paging = { ...owner.paging, loading: !!historyKey && owner.paging.version === 0, hasMoreBefore: historyKey ? owner.paging.hasMoreBefore : false }; @@ -122,7 +122,7 @@ export function useNanobotStream( onTurnEnd?: () => void, onStreamDetach?: (messages: UIMessage[]) => void, completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS, - history?: { key: string | null; cache?: ThreadMessageCache }, + history?: { key: string | null; cache?: ThreadMessageCache; temporary?: boolean }, historyActiveTurnId: string | null = null, ): { messages: UIMessage[]; @@ -158,9 +158,10 @@ export function useNanobotStream( } { const { client, getToken } = useClient(); const historyKey = history?.key ?? null; + const temporary = history?.temporary === true; const messageCache = history?.cache; const [initialTranscript] = useState(() => createTranscript(initialMessages, - chatId ? messageCache?.get(chatId) : undefined, historyKey)); + chatId ? messageCache?.get(chatId) : undefined, historyKey, temporary)); const transcriptRef = useRef(initialTranscript); const [historyState, setHistoryState] = useState(initialTranscript.paging); const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []); @@ -310,6 +311,7 @@ export function useNanobotStream( for (let index = 0; index < events.length; index++) { const event = events[index]; const chunks = [event.text]; + const parts = [event]; const members = event.turn.turnSeq === undefined ? [] : [event.turn.turnSeq]; let turn = event.turn; while (index + 1 < events.length) { @@ -323,6 +325,7 @@ export function useNanobotStream( || JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources) || JSON.stringify(nextEvent.responseInputIds) !== JSON.stringify(event.responseInputIds)))) break; chunks.push(nextEvent.text); + parts.push(nextEvent); if (nextEvent.turn.turnSeq !== undefined) members.push(nextEvent.turn.turnSeq); turn = { ...turn, ...nextEvent.turn }; index++; @@ -359,8 +362,12 @@ export function useNanobotStream( } projectedEvent.projection_receipts = [{ turn_id: turn.turnId, ranges }]; } + const contributions = parts.map((part) => ({ + ...projectedEvent, text: part.text, turn_id: part.turn.turnId, turn_phase: part.turn.turnPhase, + turn_seq: part.turn.turnSeq, stream_id: part.streamId, projection_receipts: undefined, + })); transcriptRef.current.project(projectedEvent, { - createId: () => crypto.randomUUID(), now: Date.now(), startSeq: event.turn.turnSeq, + createId: () => crypto.randomUUID(), now: Date.now(), startSeq: event.turn.turnSeq, contributions, }); } return transcriptRef.current.messages; @@ -475,7 +482,7 @@ export function useNanobotStream( // ``initialMessages`` update: a brand-new chat can receive an empty/404 // history response after the optimistic first message has already rendered. useEffect(() => { - transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey); + transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey, temporary); setMessages(transcriptRef.current.messages); setMessageScope({ chatId, historyKey, client }); setRunState(chatId ? client.getRunState(chatId) : null); @@ -484,7 +491,7 @@ export function useNanobotStream( setGoalState(chatId ? client.getGoalState(chatId) : undefined); setRecoveryState(null); clearPendingStreamWork(); - }, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]); + }, [chatId, client, historyKey, temporary, clearActivitySegment, clearPendingStreamWork, setMessages]); useEffect(() => { if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return; @@ -515,6 +522,20 @@ export function useNanobotStream( }, [publishHistory]); const latestReadOwnerRef = useRef(); const detailRequestsRef = useRef(new Map>()); + const reconcileCanonical = useCallback((generation: number, canonical: ReturnType, accepted: boolean) => { + if (!chatId) return; + const settle = !canonical.snapshot.hasPendingToolCalls + && client.canReconcileCanonicalCompletion(chatId, generation, canonical.completedTurnIds, canonical.snapshot); + if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation, + canonical.completedTurnIds, canonical.snapshot)) { + setRetryStatus(null); + } else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds); + }, [chatId, client]); + const settleFragment = useCallback((owner: ThreadTranscript) => { + if (!chatId || !owner.fragmentCompletedTurnIds.length) return; + client.settleFragmentRunLifecycle(chatId, owner.fragmentCompletedTurnIds); + if (!client.getRunState(chatId)?.active) setRetryStatus(null); + }, [chatId, client]); useEffect(() => { if (!historyKey) return; @@ -532,8 +553,6 @@ export function useNanobotStream( flushPendingStreamEvents(); const decision = ownRead ? read : owner.begin(seed ? "initial" : "latest"); const canonical = body ? persistedCanonicalRunState(body) : null; - const settle = chatId && canonical && !canonical.snapshot.hasPendingToolCalls - && client.canReconcileCanonicalCompletion(chatId, generation, canonical.completedTurnIds, canonical.snapshot); const accepted = owner.accept(body, decision); // Commit the received owner before cache listeners/ledger callbacks can reenter. setMessages(owner.messages); @@ -544,11 +563,12 @@ export function useNanobotStream( else webuiThreadCache.delete(historyKey); publishing = false; } - if (ownRead && chatId && canonical) { - if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation, - canonical.completedTurnIds, canonical.snapshot)) { - setRetryStatus(null); - } else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds); + if (chatId && canonical && (ownRead || !seed)) { + if (body?.page?.record_range) { + if (accepted) settleFragment(owner); + } else if (ownRead && !owner.hasPendingFragmentGap) { + reconcileCanonical(generation, canonical, accepted); + } } }; const cached = webuiThreadCache.get(historyKey); @@ -568,7 +588,7 @@ export function useNanobotStream( else { owner.finishRead(read, (error as Error).message); publishHistory(); } }); return () => { disposed = true; controller.abort(); cancelOlderRead(); unsubscribe(); }; - }, [cancelOlderRead, chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, refreshSeq, setMessages]); + }, [cancelOlderRead, chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, reconcileCanonical, refreshSeq, setMessages, settleFragment]); const loadOlder = useCallback(async () => { const owner = transcriptRef.current; @@ -583,8 +603,12 @@ export function useNanobotStream( const body = await fetchWebuiThread(getToken(), historyKey, { before, limit: 120, signal: controller.signal }); if (olderReadRef.current !== operation || transcriptRef.current !== owner) return; flushPendingStreamEvents(); - owner.accept(body, read); + const accepted = owner.accept(body, read); setMessages(owner.messages); + if (accepted) { + if (chatId) messageCache?.set(chatId, owner.save()); + settleFragment(owner); + } } catch (error) { if (olderReadRef.current === operation && transcriptRef.current === owner) { owner.finishRead(read, (error as Error).message); @@ -593,7 +617,14 @@ export function useNanobotStream( } finally { if (olderReadRef.current === operation) olderReadRef.current = null; } - }, [flushPendingStreamEvents, getToken, historyKey, publishHistory, setMessages]); + }, [chatId, client, flushPendingStreamEvents, getToken, historyKey, messageCache, publishHistory, setMessages, settleFragment]); + + useEffect(() => { + const bridging = transcriptRef.current.hasPendingFragmentGap; + if (historyKey && historyState.version > 0 && historyState.hasMoreBefore + && !historyState.loading && !historyState.loadingOlder && !historyState.olderError + && (bridging || (messages.length === 0 && !historyState.error))) void loadOlder(); + }, [historyKey, historyState, loadOlder, messages.length]); const loadTraceDetails = useCallback(async (refs: string[]) => { const owner = transcriptRef.current; diff --git a/webui/src/hooks/usePromptHistory.ts b/webui/src/hooks/usePromptHistory.ts index 5bab32af2..2cd0fc26c 100644 --- a/webui/src/hooks/usePromptHistory.ts +++ b/webui/src/hooks/usePromptHistory.ts @@ -3,6 +3,7 @@ import { useClient } from "@/providers/ClientProvider"; import { fetchPromptIndex, fetchWebuiThread } from "@/lib/api"; import { projectThreadEvents } from "@/lib/thread-event-projection"; import { projectWebuiThreadMessages } from "@/lib/thread-display-projection"; +import { joinThreadFragments } from "@/lib/thread-page-fragments"; import { isModelCommandText } from "@/lib/format"; import { isSystemCommandTurnId } from "@/lib/nanobot-client"; import type { PromptIndex, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types"; @@ -45,6 +46,8 @@ export function usePromptHistory(key: string | null, version: number, messages: const [index, setIndex] = useState<{ key: string; prompts: PromptAnchor[] } | null>(null); const indexSnapshot = useRef(); const [pages, setPages] = useState([]); + const pagesRef = useRef(pages); + pagesRef.current = pages; const [target, setTarget] = useState(null); const [operation, setOperation] = useState(null); const [loading, setLoading] = useState(false); @@ -54,6 +57,7 @@ export function usePromptHistory(key: string | null, version: number, messages: const request = useRef(null); const sequence = useRef(0); const retry = useRef<() => void>(() => setRefresh((value) => value + 1)); + const emptyScan = useRef<{ direction: "before" | "after"; reversed: boolean }>({ direction: "after", reversed: false }); const scope = useRef({ key, client }); const currentScope = scope.current.key === key && scope.current.client === client; @@ -140,9 +144,10 @@ export function usePromptHistory(key: string | null, version: number, messages: setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) }))); }, []); - const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string) => { + const read = useCallback(async (cursor: string, direction: "before" | "after", id?: string, automatic = false) => { // Boundary inputs can arrive before loading renders; only a new jump supersedes a read. if (!key || (!id && request.current)) return; + if (!automatic) emptyScan.current = { direction, reversed: false }; request.current?.abort(); const controller = new AbortController(); request.current = controller; @@ -156,6 +161,11 @@ export function usePromptHistory(key: string | null, version: number, messages: }); if (controller.signal.aborted) return; if (!body) throw new Error("History is no longer available"); + const generation = body.page?.history_generation; + const previousGeneration = pagesRef.current[0]?.body.page?.history_generation; + if (!id && generation && previousGeneration && generation !== previousGeneration) { + throw new Error("History changed; select the message again"); + } const page = { body, messages: projectWebuiThreadMessages(projectThreadEvents(body.events)) }; if (id && !page.messages.some((message) => message.id === id)) { setRefresh((value) => value + 1); @@ -179,19 +189,43 @@ export function usePromptHistory(key: string | null, version: number, messages: const last = pages[pages.length - 1]?.body.page; const window = useMemo(() => { if (!currentScope || !pages.length) return null; - let count = 0; + const messages: UIMessage[] = []; let boundary: number | null = null; - for (const page of pages) { - const eventIndex = page.body.fork_boundary_event_index; - if (eventIndex !== undefined) boundary = count + projectWebuiThreadMessages(projectThreadEvents(page.body.events.slice(0, eventIndex))).length; - count += page.messages.length; + for (let index = 0; index < pages.length; index++) { + const page = pages[index]; + let body = page.body; + let rows = page.messages; + const range = body.page?.record_range; + if (range) { + let joined = joinThreadFragments([], body); + while (pages[index + 1]?.body.page?.record_range?.turn === range.turn) { + joined = joinThreadFragments(joined.pages, pages[++index].body); + } + body = joined.body; + rows = projectWebuiThreadMessages(projectThreadEvents(body.events)); + } + const eventIndex = body.fork_boundary_event_index; + if (eventIndex !== undefined) boundary = messages.length + projectWebuiThreadMessages(projectThreadEvents(body.events.slice(0, eventIndex))).length; + messages.push(...rows); } - return { messages: pages.flatMap((page) => page.messages), + return { messages, userMessageOffset: first?.user_message_offset ?? 0, hasMoreBefore: first?.has_more_before === true, hasMoreAfter: last?.has_more_after === true, forkBoundaryMessageCount: boundary }; }, [currentScope, pages, first, last]); + useEffect(() => { + if (!window || window.messages.length || loading || error) return; + let direction = emptyScan.current.direction; + let cursor = direction === "after" ? last?.after_cursor : first?.before_cursor; + if (!cursor && !emptyScan.current.reversed) { + direction = direction === "after" ? "before" : "after"; + emptyScan.current = { direction, reversed: true }; + cursor = direction === "after" ? last?.after_cursor : first?.before_cursor; + } + if (cursor) void read(cursor, direction, undefined, true); + }, [error, first?.before_cursor, last?.after_cursor, loading, read, window]); + return { prompts, window, target: currentScope ? target : null, loading: currentScope && loading, operation: currentScope && (loading || error) ? operation : null, error: currentScope ? error ?? indexError : null, cancel, latest, updateMessages, diff --git a/webui/src/hooks/useReconnectRuns.ts b/webui/src/hooks/useReconnectRuns.ts index f5cfc3d9f..0832b8259 100644 --- a/webui/src/hooks/useReconnectRuns.ts +++ b/webui/src/hooks/useReconnectRuns.ts @@ -29,6 +29,18 @@ export function useReconnectRuns(client: NanobotClient, getToken: () => string): const body = await fetchLatestWebuiThread(client, getToken(), key, signal); if (!body || signal.aborted) return; const { completedTurnIds, snapshot } = persistedCanonicalRunState(body); + if (body.page?.record_range) { + if (!Array.isArray(body.completed_turn_ids)) return; + const mounted = client.hasTranscript(chatId); + if (client.canReconcileCanonicalCompletion(chatId, generation, completedTurnIds, snapshot)) { + webuiThreadCache.set(key, body); + } + // A mounted owner must accept (or stage) the fragment before settling. + // Explicit completion is otherwise independent of a newer run, but the + // fragment is not proof that its WS content is covered. + if (!mounted) client.settleFragmentRunLifecycle(chatId, completedTurnIds); + return; + } const explicitlyCompleted = turnId !== null && completedTurnIds.includes(turnId); if (!explicitlyCompleted && (snapshot.hasPendingToolCalls || snapshot.activeTurnId)) return; if (turnId && !explicitlyCompleted && !snapshot.observedTurnIds.includes(turnId)) return; diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index e3ce0a5a4..1bacec523 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -385,6 +385,10 @@ function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet case "stream_end": case "reasoning_end": if (value.text !== undefined && typeof value.text !== "string") break; + if (value.text_from_seq !== undefined && ( + !Number.isSafeInteger(value.text_from_seq) || Number(value.text_from_seq) < 0 + || !Number.isSafeInteger(value.turn_seq) || Number(value.text_from_seq) > Number(value.turn_seq) + )) break; return value as unknown as ThreadProjectionEvent; case "context_compaction": if (value.context_graph !== undefined && !validatedGraphs.has(value.context_graph) && !isContextGraph(value.context_graph)) break; @@ -421,6 +425,21 @@ export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPay if (value.projection !== "events" || !Array.isArray(value.events)) { throw new Error("Invalid WebUI thread events"); } + if (isRecord(value.page) && value.page.history_generation != null + && (typeof value.page.history_generation !== "string" || !value.page.history_generation)) { + throw new Error("Invalid WebUI thread history generation"); + } + if (isRecord(value.page) && value.page.record_range !== undefined) { + const range = value.page.record_range; + if (!isRecord(range) || !Number.isSafeInteger(range.turn) || Number(range.turn) < 0 + || !Number.isSafeInteger(range.start) || Number(range.start) < 0 + || !Number.isSafeInteger(range.end) || Number(range.end) <= Number(range.start)) { + throw new Error("Invalid WebUI thread record range"); + } + } + if (isRecord(value.page) && value.page.recovered_answers !== undefined && typeof value.page.recovered_answers !== "boolean") { + throw new Error("Invalid WebUI thread answer recovery"); + } const graphs = new Map(); if (value.context_graphs !== undefined) { if (!isRecord(value.context_graphs)) throw new Error("Invalid context graph dictionary"); diff --git a/webui/src/lib/canonical-run-snapshot.ts b/webui/src/lib/canonical-run-snapshot.ts index 5de7c6e27..231cabf2e 100644 --- a/webui/src/lib/canonical-run-snapshot.ts +++ b/webui/src/lib/canonical-run-snapshot.ts @@ -28,16 +28,16 @@ export function persistedCanonicalRunState(body: WebuiThreadPersistedPayload): { completedTurnIds: string[]; snapshot: CanonicalRunSnapshot; } { - const messages = projectThreadEvents(body.events); const suppliedCompletionIds = Array.isArray(body.completed_turn_ids) ? body.completed_turn_ids : null; - // The older protocol-1 host may omit active_turn_id. Its explicit pending - // flag still confirms idle; a missing flag cannot establish completion. - const snapshot = canonicalRunSnapshot( - messages, - body.has_pending_tool_calls !== false, - typeof body.active_turn_id === "string" ? body.active_turn_id : null, - suppliedCompletionIds !== null, - ); + // User identities and explicit completion are wire facts, not rendered messages. + const snapshot: CanonicalRunSnapshot = { + observedTurnIds: Array.from(new Set(body.events.flatMap((event) => ( + event.event === "user_message" && event.turn_id ? [event.turn_id] : [] + )))), + hasPendingToolCalls: body.has_pending_tool_calls !== false, + activeTurnId: typeof body.active_turn_id === "string" ? body.active_turn_id : null, + completionIdsProvided: suppliedCompletionIds !== null, + }; const completedTurnIds = suppliedCompletionIds?.filter( (turnId) => typeof turnId === "string" && turnId.length > 0, ) ?? []; @@ -47,7 +47,7 @@ export function persistedCanonicalRunState(body: WebuiThreadPersistedPayload): { completedTurnIds.push(...body.events.flatMap((event) => ( event.event === "turn_end" && event.turn_id ? [event.turn_id] : [] ))); - completedTurnIds.push(...completedAssistantTurnIds(messages)); + completedTurnIds.push(...completedAssistantTurnIds(projectThreadEvents(body.events))); } return { completedTurnIds: Array.from(new Set(completedTurnIds)), snapshot }; } diff --git a/webui/src/lib/client-run-ledger.ts b/webui/src/lib/client-run-ledger.ts index b6f8b5e35..d3d2dc90a 100644 --- a/webui/src/lib/client-run-ledger.ts +++ b/webui/src/lib/client-run-ledger.ts @@ -17,7 +17,7 @@ interface ChatRecord { effectiveStartedAt: number | null; anonymousActive: boolean; turns: Map; - /** Closed turns permit late inputs, messages, completions and idle. */ + /** Lifecycle tombstones permit late content without reopening ownership. */ closed: Set; /** Canonical fences discard every frame with a matching top-level turn id. */ fenced: Set; @@ -45,6 +45,7 @@ export type RunObservation = Readonly<{ chatId: string; turnId: string | null; systemCommand?: boolean; + lifecycleSignal?: boolean; }> & ( | { kind: "admission" | "input"; owner?: { turnId: string; startedAt?: number } } | { kind: "status"; activity: "running" | "idle"; startedAt?: number } @@ -57,14 +58,14 @@ type Command = | ({ kind: "written" | "reject" } & TurnRef) | { kind: "transport-lost" } | { kind: "local-stop" | "forget"; chatId: string } - | { kind: "fence"; chatId: string; completedTurnIds: readonly string[] } + | { kind: "fence" | "settle-fragment-lifecycle"; chatId: string; completedTurnIds: readonly string[] } | { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null }; export type RunEffect = | { kind: "run-status"; chatId: string; state: RunState } | { kind: "completion"; chatId: string } | ({ kind: "discard-send" } & TurnRef) - | { kind: "prune-inbound"; chatId: string; turnIds: readonly string[] }; + | { kind: "prune-inbound" | "prune-lifecycle-inbound"; chatId: string; turnIds: readonly string[] }; interface ObservationResult { forward: "normal" | "without-owner" | "drop"; @@ -209,6 +210,9 @@ export class ClientRunLedger { case "fence": this.fence(command.chatId, command.completedTurnIds, effects); break; + case "settle-fragment-lifecycle": + this.settleFragmentLifecycle(command.chatId, command.completedTurnIds, effects); + break; default: { const unhandled: never = command; throw new Error(`Unexpected run command: ${unhandled}`); @@ -228,12 +232,15 @@ export class ClientRunLedger { let chat = this.chats.get(chatId); const effects: RunEffect[] = []; if (turnId !== null && chat?.fenced.has(turnId)) return { forward: "drop", effects }; - if ( - turnId && chat?.closed.has(turnId) - && observation.kind !== "admission" && observation.kind !== "input" - && observation.kind !== "message" && observation.kind !== "completed" - && !(observation.kind === "status" && observation.activity === "idle") - ) return { forward: "drop", effects }; + if (turnId && chat?.closed.has(turnId)) { + if (observation.lifecycleSignal || observation.kind === "recovery" || observation.kind === "rejection" + || (observation.kind === "status" && observation.activity === "running")) { + return { forward: "drop", effects }; + } + // Content delivery is independent of lifecycle ownership. In particular, + // delta/stream_end may arrive after an explicit canonical completion. + if (observation.kind === "activity" || observation.kind === "progress") return { forward: "normal", effects }; + } let forward: ObservationResult["forward"] = "normal"; if ((observation.kind === "admission" || observation.kind === "input") && observation.owner?.turnId) { @@ -456,7 +463,21 @@ export class ClientRunLedger { private rememberClosed(chat: ChatRecord, turnId: string): void { chat.closed.add(turnId); - this.trimTerminalSet(chat.closed); + this.trimTerminalSet(chat.closed, chat.latestTurnId); + } + + private settleFragmentLifecycle(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void { + for (const turnId of turnIds) { + if (!turnId) continue; + const chat = this.ensureChat(chatId); + this.rememberClosed(chat, turnId); + this.settle(chatId, turnId, effects); + if (chat.latestTurnId === turnId) { + chat.anonymousActive = false; + chat.effectiveStartedAt = null; + } + } + effects.push({ kind: "prune-lifecycle-inbound", chatId, turnIds }); } private fence(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void { @@ -470,10 +491,10 @@ export class ClientRunLedger { effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) }); } - private trimTerminalSet(turnIds: Set): void { + private trimTerminalSet(turnIds: Set, retainedTurnId?: string | null): void { for (const oldest of turnIds) { if (turnIds.size <= COMPLETED_TURN_FENCE_MAX) break; - turnIds.delete(oldest); + if (oldest !== retainedTurnId) turnIds.delete(oldest); } } diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts index f853ade3e..bb93b8d9a 100644 --- a/webui/src/lib/nanobot-client.ts +++ b/webui/src/lib/nanobot-client.ts @@ -200,7 +200,7 @@ function runObservation(event: InboundEvent): RunObservation | null { case "stream_end": return { ...base, kind: "activity" }; case "retry_status": - return { ...base, kind: event.state === "recovered" || event.state === "cleared" ? "progress" : "activity" }; + return { ...base, lifecycleSignal: true, kind: event.state === "recovered" || event.state === "cleared" ? "progress" : "activity" }; case "recovery_state": // Supersession resolves the old recovery, not the new user turn that caused it. return event.status === "recovered" && event.reason === "superseded" @@ -435,6 +435,16 @@ export class NanobotClient { this.applyRunEffects(this.runs.transition({ kind: "fence", chatId, completedTurnIds })); } + /** Settle explicit fragment completions without claiming coverage of live content. */ + settleFragmentRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void { + this.applyRunEffects(this.runs.transition({ kind: "settle-fragment-lifecycle", chatId, completedTurnIds })); + } + + /** Whether a mounted transcript owns delivery for this chat. */ + hasTranscript(chatId: string): boolean { + return this.transcriptHandlers.has(chatId); + } + /** Last ``goal_state`` payload for *chatId*, if any frame has arrived this connection. */ getGoalState(chatId: string): GoalStateWsPayload | undefined { return this.goalStateByChatId.get(chatId); @@ -469,7 +479,8 @@ export class NanobotClient { && frame.turn_id === effect.turnId )); break; - case "prune-inbound": { + case "prune-inbound": + case "prune-lifecycle-inbound": { const pending = this.pendingInboundByChat.get(effect.chatId); if (!pending) break; const turnIds = new Set(effect.turnIds); @@ -477,6 +488,8 @@ export class NanobotClient { !("turn_id" in event) || typeof event.turn_id !== "string" || !turnIds.has(event.turn_id) + || (effect.kind === "prune-lifecycle-inbound" + && event.event !== "goal_status" && event.event !== "recovery_state" && event.event !== "retry_status") )); if (remaining.length > 0) this.pendingInboundByChat.set(effect.chatId, remaining); else this.pendingInboundByChat.delete(effect.chatId); diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index 20a3e60d3..81fc25750 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -1,4 +1,5 @@ import { toMediaAttachment } from "@/lib/media"; +import { ThreadProjectionIndex } from "./thread-projection-index"; import { mergeToolProgressEvents, mergeToolProgressTraceLines, @@ -51,6 +52,9 @@ export interface ThreadProjectionOptions { /** First sequence of a coalesced batch; event.turn_seq is its last contribution. */ startSeq?: number; effects?: ThreadProjectionEffects; + index?: ThreadProjectionIndex; + /** Scratch replay owns these collections and does not expose intermediate states. */ + mutableCollections?: boolean; } export function turnFieldsFromEvent( @@ -90,7 +94,18 @@ function findStreamingAssistantIndex( closedStreamIds: ReadonlySet, turn: UIMessageTurnFields = {}, streamId?: string, + lookup?: ThreadProjectionIndex, ): number | null { + if (streamId && lookup) { + let target: number | null = null; + for (const index of lookup.answer("")) { + const row = prev[index]; + if (index > lookup.lastUser && row.kind !== "trace" && row.isStreaming + && !closedStreamIds.has(row.id) && matchesTurn(row, turn) + && (target === null || index > target)) target = index; + } + return target; + } for (let i = prev.length - 1; i >= 0; i -= 1) { const m = prev[i]; if (m.kind === "trace") continue; @@ -440,9 +455,10 @@ export function clearThreadProjectionActivity( export function closeThreadProjectionAnswer( state: ThreadProjectionState, + mutableCollections = false, ): ThreadProjectionState { if (!state.activeAssistantId) return state; - const closedAssistantIds = new Set(state.closedAssistantIds); + const closedAssistantIds = mutableCollections ? state.closedAssistantIds : new Set(state.closedAssistantIds); closedAssistantIds.add(state.activeAssistantId); return { ...state, @@ -479,7 +495,7 @@ function turnFieldsForProjection( if (!alias) { const suffix = event.projection_id || event.created_at_ms || state.messages.length; alias = `${rawTurnId}:replay:${suffix}`; - state.turnAliases.set(rawTurnId, alias); + state.turnAliases = new Map(state.turnAliases).set(rawTurnId, alias); } return { ...fields, turnId: alias }; } @@ -499,9 +515,11 @@ function detachedProjectionActivitySegment(state: ThreadProjectionState): string function activeAssistantIndex( state: ThreadProjectionState, turn: UIMessageTurnFields, + lookup?: ThreadProjectionIndex, ): number | null { if (!state.activeAssistantId) return null; - const index = state.messages.findIndex((message) => message.id === state.activeAssistantId); + const index = lookup ? lookup.position(state.activeAssistantId) ?? -1 + : state.messages.findIndex((message) => message.id === state.activeAssistantId); if (index < 0) { state.activeAssistantId = null; state.mergeReasoning = false; @@ -529,14 +547,21 @@ function answerStreamIndex( state: ThreadProjectionState, turn: UIMessageTurnFields, streamId?: string, + lookup?: ThreadProjectionIndex, ): number | null { - if (streamId) { + if (streamId && lookup) { + let target: number | null = null; + for (const index of lookup.answer(streamId)) { + if (matchesTurn(state.messages[index], turn) && (target === null || index > target)) target = index; + } + if (target !== null) return target; + } else if (streamId) { for (let index = state.messages.length - 1; index >= 0; index--) { const message = state.messages[index]; if (message.role === "assistant" && message.streamId === streamId && matchesTurn(message, turn)) return index; } } - const active = activeAssistantIndex(state, turn); + const active = activeAssistantIndex(state, turn, lookup); if (active !== null && (!streamId || !state.messages[active].streamId || state.messages[active].streamId === streamId)) { return active; } @@ -544,7 +569,7 @@ function answerStreamIndex( if (placeholder !== null && (!streamId || !state.messages[placeholder].streamId || state.messages[placeholder].streamId === streamId)) { return placeholder; } - return findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn, streamId); + return findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn, streamId, lookup); } function appendAnswerText( @@ -555,10 +580,10 @@ function appendAnswerText( const turn = turnFieldsForProjection(state, event, "answer"); const streamKey = answerStreamKey(turn, event.stream_id); if (streamKey && state.closedAnswerStreamIds.has(streamKey)) return; - let targetIndex = answerStreamIndex(state, turn, event.stream_id); + let targetIndex = answerStreamIndex(state, turn, event.stream_id, options.index); if (targetIndex !== null && state.closedAssistantIds.has(state.messages[targetIndex].id)) targetIndex = null; if (targetIndex === null) { - Object.assign(state, closeThreadProjectionAnswer(state)); + Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections)); const id = projectionMessageId(event, options); state.messages = [ ...state.messages, @@ -583,7 +608,10 @@ function appendAnswerText( ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), ...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}), }; - state.closedAssistantIds.delete(merged.id); + if (state.closedAssistantIds.has(merged.id)) { + state.closedAssistantIds = new Set(state.closedAssistantIds); + state.closedAssistantIds.delete(merged.id); + } state.activeAssistantId = merged.id; state.mergeReasoning = false; state.messages = replaceMessageAt(state.messages, targetIndex, merged); @@ -633,9 +661,9 @@ function attachProjectedReasoning( if (state.fileEditSegmentId || activeAssistantBeforeContinuation) { if (activeAssistantBeforeContinuation && !state.activeAssistantId) { - state.closedAssistantIds.add(activeAssistantBeforeContinuation); + state.closedAssistantIds = new Set(state.closedAssistantIds).add(activeAssistantBeforeContinuation); } - const closed = closeThreadProjectionAnswer(state); + const closed = closeThreadProjectionAnswer(state, options.mutableCollections); Object.assign(state, clearThreadProjectionActivity(closed)); } for (let index = state.messages.length - 1; index >= 0; index -= 1) { @@ -721,7 +749,7 @@ function projectToolActivity( event: Extract, options: ThreadProjectionOptions, ): void { - Object.assign(state, closeThreadProjectionAnswer(state)); + Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections)); const structuredEvents = normalizeToolProgressEvents(event.tool_events); const visibleEvents = filterCoveredFileEditToolEvents(state.messages, structuredEvents); const structuredLines = toolTraceLinesFromEvents(visibleEvents); @@ -802,7 +830,7 @@ function projectFileEdits( event: Extract, options: ThreadProjectionOptions, ): void { - Object.assign(state, closeThreadProjectionAnswer(state)); + Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections)); const normalized = mergeFileEdits(undefined, event.edits); if (normalized.length === 0) return; const turn = turnFieldsForProjection(state, event, "activity"); @@ -854,13 +882,20 @@ export function projectThreadEvent( event: ThreadProjectionEvent, options: ThreadProjectionOptions, ): ThreadProjectionState { - const state: ThreadProjectionState = { - ...previous, - closedAssistantIds: new Set(previous.closedAssistantIds), - closedAnswerStreamIds: new Set(previous.closedAnswerStreamIds), - closedTurnIds: new Set(previous.closedTurnIds), - turnAliases: new Map(previous.turnAliases), - }; + if (!options.index) return reduceThreadEvent(previous, event, options); + options.index.sync(previous.messages); + const effects = options.effects ?? { bodyWrites: new Set(), consumed: new Set() }; + const state = reduceThreadEvent(previous, event, { ...options, effects }); + options.index?.sync(state.messages, effects); + return state; +} + +function reduceThreadEvent( + previous: ThreadProjectionState, + event: ThreadProjectionEvent, + options: ThreadProjectionOptions, +): ThreadProjectionState { + const state: ThreadProjectionState = { ...previous }; if (event.event === "model_request") { if (!event.turn_id || state.closedTurnIds.has(event.turn_id)) return state; @@ -973,14 +1008,24 @@ export function projectThreadEvent( const mergeNext = event.resuming === true && event.merge_next === true; const streamKey = answerStreamKey(turn, event.stream_id); const wireClosed = streamKey !== undefined && state.closedAnswerStreamIds.has(streamKey); - if (streamKey && !mergeNext) state.closedAnswerStreamIds.add(streamKey); - let targetIndex = answerStreamIndex(state, turn, event.stream_id); + if (streamKey && !mergeNext && !wireClosed) { + if (!options.mutableCollections) state.closedAnswerStreamIds = new Set(state.closedAnswerStreamIds); + state.closedAnswerStreamIds.add(streamKey); + } + let targetIndex = answerStreamIndex(state, turn, event.stream_id, options.index); let text = event.text; // Older completed records can span a hosted tool. Their snapshots already // use rewritten text; live streams now end before the tool starts. if (options.persisted && event.stream_id && typeof text === "string") { let offset = 0; - for (let index = 0; index < (targetIndex ?? state.messages.length); index++) { + const positions = options.index?.answer(event.stream_id); + if (positions) { + for (const index of positions) { + if (index < (targetIndex ?? state.messages.length) && matchesTurn(state.messages[index], turn)) { + offset += state.messages[index].content.length; + } + } + } else for (let index = 0; index < (targetIndex ?? state.messages.length); index++) { const row = state.messages[index]; if (row.streamId === event.stream_id && matchesTurn(row, turn)) offset += row.content.length; } @@ -1026,7 +1071,7 @@ export function projectThreadEvent( if (wasClosed || wireClosed) return state; if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id; state.mergeReasoning = mergeNext && state.activeAssistantId !== null; - if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state)); + if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections)); return state; } @@ -1050,7 +1095,7 @@ export function projectThreadEvent( } if (event.event === "context_compaction") { - Object.assign(state, closeThreadProjectionAnswer(state)); + Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections)); if (event.phase === "succeeded") { state.modelRequests = new Map(Array.from(state.modelRequests, ([turn, request]) => [turn, { ...request, contextSnapshots: [] }])); @@ -1135,7 +1180,7 @@ export function projectThreadEvent( return state; } const activeId = state.activeAssistantId; - Object.assign(state, closeThreadProjectionAnswer(state)); + Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections)); if (activeId) { state.messages = state.messages.filter((message) => { if (message.id !== activeId) return true; @@ -1189,23 +1234,28 @@ export function projectThreadEvent( turn.turnId, ); state.activeAssistantId = null; - state.closedAssistantIds.clear(); - state.closedAnswerStreamIds.clear(); + state.closedAssistantIds = new Set(); + state.closedAnswerStreamIds = new Set(); state.mergeReasoning = false; if (event.turn_id) { - if (state.turnAliases.has(event.turn_id)) state.turnAliases.delete(event.turn_id); - else state.closedTurnIds.add(event.turn_id); + if (state.turnAliases.has(event.turn_id)) { + state.turnAliases = new Map(state.turnAliases); + state.turnAliases.delete(event.turn_id); + } else state.closedTurnIds = new Set(state.closedTurnIds).add(event.turn_id); } return state; } export function projectThreadEvents(events: ThreadProjectionEvent[]): UIMessage[] { let state = createThreadProjectionState(); + const lookup = new ThreadProjectionIndex(); events.forEach((event, index) => { state = projectThreadEvent(state, event, { createId: () => `history-${index}`, now: 0, persisted: true, + index: lookup, + mutableCollections: true, }); }); return state.messages.map((row) => { diff --git a/webui/src/lib/thread-page-fragments.ts b/webui/src/lib/thread-page-fragments.ts new file mode 100644 index 000000000..69c14ca50 --- /dev/null +++ b/webui/src/lib/thread-page-fragments.ts @@ -0,0 +1,80 @@ +import type { ThreadProjectionEvent, WebuiThreadPersistedPayload } from "./types"; + +function isAnswer(event: ThreadProjectionEvent): boolean { + return event.event === "delta" || event.event === "stream_end" + || (event.event === "message" && event.kind !== "tool_hint" && event.kind !== "progress" && event.kind !== "reasoning"); +} + +/** Coalesce continuous raw ranges; canonical recovery replaces stored answers, not other activities. */ +export function joinThreadFragments( + previous: readonly WebuiThreadPersistedPayload[], + current: WebuiThreadPersistedPayload, +): { pages: WebuiThreadPersistedPayload[]; body: WebuiThreadPersistedPayload; withdrawn: ThreadProjectionEvent[] } { + const range = current.page?.record_range; + if (!range) return { pages: [...previous], body: current, withdrawn: [] }; + const same = (page: WebuiThreadPersistedPayload) => page.page?.record_range?.turn === range.turn + && page.page.history_generation === current.page?.history_generation; + const ordered = [...previous.filter(same), current].sort((a, b) => { + const left = a.page!.record_range!; + const right = b.page!.record_range!; + return left.start - right.start || right.end - left.end; + }); + const groups: WebuiThreadPersistedPayload[][] = []; + for (const page of ordered) { + const group = groups.at(-1); + const end = group ? Math.max(...group.map((item) => item.page!.record_range!.end)) : -1; + if (!group || page.page!.record_range!.start > end) groups.push([page]); + else group.push(page); + } + + const recovered = ordered.some((page) => page.page?.recovered_answers === true); + const withdrawn: ThreadProjectionEvent[] = []; + const latestEvents = new Map(current.events.map((event) => [event.projection_id, event])); + let selected: WebuiThreadPersistedPayload | undefined; + const pages = groups.map((group) => { + const first = group[0]; + const last = group.reduce((a, b) => a.page!.record_range!.end >= b.page!.record_range!.end ? a : b); + const events: ThreadProjectionEvent[] = []; + const seen = new Set(); + const completed = new Set(); + let boundary: number | undefined; + for (const page of group) { + for (const turn of page.completed_turn_ids ?? []) completed.add(turn); + for (const [index, event] of page.events.entries()) { + if (boundary === undefined && page.fork_boundary_event_index === index) boundary = events.length; + if (recovered && !page.page?.recovered_answers && isAnswer(event)) { + if (page !== current) withdrawn.push(event); + continue; + } + if (event.projection_id && seen.has(event.projection_id)) continue; + if (event.projection_id) seen.add(event.projection_id); + events.push(event.projection_id ? latestEvents.get(event.projection_id) ?? event : event); + } + if (boundary === undefined && page.fork_boundary_event_index === page.events.length) boundary = events.length; + } + const start = first.page!.record_range!.start; + const end = last.page!.record_range!.end; + const complete = start === 0 && events.some((event) => event.event === "turn_end"); + const merged: WebuiThreadPersistedPayload = { + ...first, + events, + completed_turn_ids: [...completed], + page: { ...first.page!, after_cursor: last.page!.after_cursor, has_more_after: last.page!.has_more_after, + record_range: { turn: range.turn, start, end }, truncated_oversized_turn: !complete, + ...(recovered ? { recovered_answers: true } : {}) }, + }; + if (boundary === undefined) delete merged.fork_boundary_event_index; + else merged.fork_boundary_event_index = boundary; + if (group.includes(current)) selected = merged; + return merged; + }); + const group = selected!; + const body = { ...current, events: group.events, completed_turn_ids: group.completed_turn_ids, + page: { ...current.page!, before_cursor: group.page!.before_cursor, has_more_before: group.page!.has_more_before, + user_message_offset: group.page!.user_message_offset, after_cursor: group.page!.after_cursor, + has_more_after: group.page!.has_more_after, record_range: group.page!.record_range, + truncated_oversized_turn: group.page!.truncated_oversized_turn, recovered_answers: group.page!.recovered_answers } }; + if (group.fork_boundary_event_index === undefined) delete body.fork_boundary_event_index; + else body.fork_boundary_event_index = group.fork_boundary_event_index; + return { pages: [...previous.filter((page) => !same(page)), ...pages], body, withdrawn }; +} diff --git a/webui/src/lib/thread-projection-index.ts b/webui/src/lib/thread-projection-index.ts new file mode 100644 index 000000000..126763afe --- /dev/null +++ b/webui/src/lib/thread-projection-index.ts @@ -0,0 +1,47 @@ +import type { UIMessage } from "./types"; +import type { ThreadProjectionEffects } from "./thread-event-projection"; + +/** Owned by one projector, never shared with its immutable checkpoints. */ +export class ThreadProjectionIndex { + private messages: UIMessage[] | null = null; + private ids = new Map(); + private answers = new Map>(); + lastUser = -1; + + position(id: string): number | undefined { return this.ids.get(id); } + answer(stream: string): ReadonlySet { return this.answers.get(stream) ?? new Set(); } + + private record(row: UIMessage, index: number, remove = false): void { + if (!remove) this.ids.set(row.id, index); + if (row.role === "user" && !remove) this.lastUser = index; + if (row.role !== "assistant") return; + const key = row.streamId ?? ""; + const positions = this.answers.get(key) ?? new Set(); + if (remove) positions.delete(index); + else positions.add(index); + if (positions.size) this.answers.set(key, positions); + else this.answers.delete(key); + } + + sync(messages: UIMessage[], effects?: ThreadProjectionEffects): void { + if (messages === this.messages) return; + const previous = this.messages; + if (!previous || !effects || effects.consumed.size || messages.length < previous.length) { + this.ids.clear(); + this.answers.clear(); + this.lastUser = -1; + messages.forEach((row, index) => this.record(row, index)); + } else { + for (const id of effects.bodyWrites) { + const index = this.ids.get(id); + if (index === undefined) continue; + if (messages[index].streamId !== previous[index].streamId) { + this.record(previous[index], index, true); + this.record(messages[index], index); + } + } + for (let index = previous.length; index < messages.length; index++) this.record(messages[index], index); + } + this.messages = messages; + } +} diff --git a/webui/src/lib/thread-transcript.ts b/webui/src/lib/thread-transcript.ts index 051bfe058..3c287ef04 100644 --- a/webui/src/lib/thread-transcript.ts +++ b/webui/src/lib/thread-transcript.ts @@ -7,6 +7,8 @@ import { persistedCanonicalRunState } from "./canonical-run-snapshot"; import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "./thread-checkpoint"; import { hasPendingAgentActivity } from "./activity-timeline"; import { reconcileModelRequest } from "./model-request"; +import { joinThreadFragments } from "./thread-page-fragments"; +import { ThreadProjectionIndex } from "./thread-projection-index"; import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "./types"; type Ranges = Array<[number, number]>; @@ -19,8 +21,21 @@ interface TextSource { through: number; end: number | null; snapshot: boolean; + certified: boolean; members: Ranges; } +interface LiveContribution { + event: ThreadProjectionEvent; + now: number; + revision: number; + startSeq?: number; + sideChannel?: boolean; +} +interface PendingFragmentGap { + turn: number; + oldEnd: number; + front: number; +} interface Unit { rows: Set; sources: Set; @@ -63,13 +78,17 @@ export interface ThreadTranscriptSnapshot extends ThreadCheckpoint { knownTurns: Set; paging: ThreadPaging; revision: number; + fragments: WebuiThreadPersistedPayload[]; + live: LiveContribution[]; + historyGeneration: string | null; + pendingFragmentGap: PendingFragmentGap | null; + withdrawnSources: Set; } function addRange(ranges: Ranges, first: number, last = first): void { let start = first; let end = last; - let index = 0; - while (index < ranges.length && ranges[index][1] + 1 < start) index++; + let index = rangeAt(ranges, start - 1); const from = index; while (index < ranges.length && ranges[index][0] <= end + 1) { start = Math.min(start, ranges[index][0]); @@ -78,8 +97,20 @@ function addRange(ranges: Ranges, first: number, last = first): void { } ranges.splice(from, index - from, [start, end]); } +function rangeAt(ranges: Ranges, seq: number): number { + let low = 0; + let high = ranges.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (ranges[mid][1] < seq) low = mid + 1; + else high = mid; + } + return low; +} function contains(ranges: Ranges | undefined, seq: number): boolean { - return ranges?.some(([first, last]) => first <= seq && seq <= last) === true; + if (!ranges) return false; + const index = rangeAt(ranges, seq); + return index < ranges.length && ranges[index][0] <= seq; } function mergeMembers(target: Members, source: Members): void { for (const [turn, ranges] of source) { @@ -91,6 +122,19 @@ function mergeMembers(target: Members, source: Members): void { function copyMembers(value: Members): Members { return new Map(Array.from(value, ([key, ranges]) => [key, ranges.map(([a, b]) => [a, b])])); } +function mergeCoveredMembers(target: Members, members: Members, coverage: Members): void { + for (const [turn, ranges] of members) { + const covered = coverage.get(turn) ?? []; + for (const [first, last] of ranges) { + for (let index = rangeAt(covered, first); index < covered.length && covered[index][0] <= last; index++) { + const [a, b] = covered[index]; + const kept = target.get(turn) ?? []; + addRange(kept, Math.max(first, a), Math.min(last, b)); + target.set(turn, kept); + } + } + } +} function copyText(value: TextSource): TextSource { return { ...value, members: value.members.map(([a, b]) => [a, b]) }; } @@ -111,12 +155,62 @@ function coversText(certificate: TextSource, text: TextSource): boolean { return certificate.snapshot && certificate.after !== null && sameWire(certificate, text) && text.members.every(([first, last]) => first > certificate.after! && last <= certificate.through); } -function sourcesOverlap(candidate: Unit, retained: Unit): boolean { - if (Array.from(candidate.sources).some((key) => !key.startsWith("text:") && retained.sources.has(key))) return true; - return candidate.text.some((left) => retained.text.some((right) => sameWire(left, right) - && ((left.phase === "answer" && left.stream !== "") - // Ordered canonical ends identify reset buffers even when attachment missed a prior end. - || right.members.some(([first, last]) => last > (left.after ?? -1) && first <= (left.end ?? Infinity))))); +function matchUnits(candidates: Set, retained: Set): { + byOld: Map>; byNew: Map>; +} { + const sources = new Map(); + type Interval = { unit: Unit; start: number; end: number; maxEnd: number }; + const wires = new Map(); + const wireKey = (text: TextSource) => JSON.stringify([text.turn, text.phase, text.stream]); + for (const unit of candidates) { + for (const source of unit.sources) if (!source.startsWith("text:")) sources.set(source, unit); + for (const text of unit.text) { + const key = wireKey(text); + const intervals = wires.get(key) ?? []; + const namedAnswer = text.phase === "answer" && text.stream !== ""; + intervals.push({ unit, start: namedAnswer ? -Infinity : text.after ?? -1, + end: namedAnswer ? Infinity : text.end ?? Infinity, maxEnd: -Infinity }); + wires.set(key, intervals); + } + } + for (const intervals of wires.values()) { + intervals.sort((a, b) => a.start - b.start); + let max = -Infinity; + for (const interval of intervals) interval.maxEnd = max = Math.max(max, interval.end); + } + const byOld = new Map>(); + const byNew = new Map>(); + for (const old of retained) { + const matches = new Set(); + for (const source of old.sources) { + const unit = sources.get(source); + if (unit) matches.add(unit); + } + for (const text of old.text) { + const intervals = wires.get(wireKey(text)); + if (!intervals) continue; + for (const [first, last] of text.members) { + let low = 0; + let high = intervals.length; + while (low < high) { + const mid = (low + high) >>> 1; + if (intervals[mid].start < last) low = mid + 1; + else high = mid; + } + for (let i = low - 1; i >= 0 && intervals[i].maxEnd >= first; i--) { + if (intervals[i].end >= first) matches.add(intervals[i].unit); + } + } + } + if (!matches.size) continue; + byOld.set(old, matches); + for (const unit of matches) { + const previous = byNew.get(unit) ?? new Set(); + previous.add(old); + byNew.set(unit, previous); + } + } + return { byOld, byNew }; } function unitPosition(unit: Unit | undefined, turn: string): number | null { if (!unit) return null; @@ -127,7 +221,11 @@ function unitPosition(unit: Unit | undefined, turn: string): number | null { return positions.length ? Math.min(...positions) : null; } -/** One received projection and accepted history frontier. HTTP replay is scratch only. */ +/** One received projection and accepted history frontier. HTTP replay is scratch only. + * Record ranges identify stored pages; text_from_seq identifies the live text a + * stored end replaces, scoped to its turn, phase and stream. Neither range + * implies that intervening tools or the rest of the turn have been loaded. + */ export class ThreadTranscript { projection: ThreadProjectionState; sideChannelTurnIds = new Set(); @@ -135,14 +233,25 @@ export class ThreadTranscript { private units = new Set(); private byRow = new Map(); private bySource = new Map(); + private projectionIndex = new ThreadProjectionIndex(); + private historyReplay: { events: ThreadProjectionEvent[]; generation: string | null; owner: ThreadTranscript } | null = null; private installed: Members = new Map(); private textCoverage: TextSource[] = []; private boundaries = new Map(); private knownTurns = new Set(); + private fragments: WebuiThreadPersistedPayload[] = []; + private live: LiveContribution[] = []; + private historyGeneration: string | null = null; + private pendingFragmentGap: PendingFragmentGap | null = null; + private withdrawnSources = new Set(); + fragmentCompletedTurnIds: string[] = []; + private readonly recordLiveContributions: boolean; private revision = 0; private order = 0; - constructor(messages: UIMessage[] = [], saved?: ThreadTranscriptSnapshot) { + constructor(messages: UIMessage[] = [], saved?: ThreadTranscriptSnapshot, + options: { recordLiveContributions?: boolean } = {}) { + this.recordLiveContributions = options.recordLiveContributions !== false; const checkpoint = saved ? copyThreadCheckpoint(saved) : createThreadCheckpoint(messages); this.projection = checkpoint.projection; this.sideChannelTurnIds = checkpoint.sideChannelTurnIds; @@ -151,6 +260,11 @@ export class ThreadTranscript { this.textCoverage = saved.textCoverage.map(copyText); this.boundaries = new Map(saved.boundaries); this.knownTurns = new Set(saved.knownTurns); + this.fragments = [...saved.fragments]; + this.live = this.recordLiveContributions ? [...saved.live] : []; + this.historyGeneration = saved.historyGeneration; + this.pendingFragmentGap = saved.pendingFragmentGap ? { ...saved.pendingFragmentGap } : null; + this.withdrawnSources = new Set(saved.withdrawnSources); this.paging = { ...saved.paging, loading: false, loadingOlder: false }; this.revision = saved.revision; for (const unit of saved.units) this.installUnit({ ...unit, rows: new Set(unit.rows), @@ -162,6 +276,7 @@ export class ThreadTranscript { get messages(): UIMessage[] { return this.projection.messages; } get modelRequests() { return this.projection.modelRequests; } + get hasPendingFragmentGap(): boolean { return this.pendingFragmentGap !== null; } private installUnit(unit: Unit): void { this.order = Math.max(this.order, unit.order + 1); @@ -171,6 +286,7 @@ export class ThreadTranscript { } rejectTurn(turn: string): void { + this.live = this.live.filter((entry) => entry.event.turn_id !== turn); for (const unit of this.units) if (unit.members.has(turn) || unit.sources.has(`user:${turn}`)) { this.units.delete(unit); for (const id of unit.rows) this.byRow.delete(id); @@ -217,7 +333,8 @@ export class ThreadTranscript { const phase = event.event.startsWith("reasoning") ? "reasoning" : "answer"; const stream = event.stream_id ?? ""; const boundaryKey = JSON.stringify([turn, phase, stream]); - let after = phase === "answer" && stream ? 0 + let after = "text_from_seq" in event && event.text_from_seq !== undefined ? event.text_from_seq - 1 + : phase === "answer" && stream ? 0 : this.boundaries.get(boundaryKey) ?? (this.knownTurns.has(turn) ? 0 : null); if (after !== null && after >= seq) { after = this.knownTurns.has(turn) ? 0 : null; @@ -233,6 +350,7 @@ export class ThreadTranscript { const text: TextSource = { turn, phase, stream, after, through: seq, end, snapshot: event.event.endsWith("end") && typeof event.text === "string" && (phase === "answer" || event.text.length > 0), + certified: "text_from_seq" in event && event.text_from_seq !== undefined, members: copyMembers(members).get(turn)! }; return { source: `text:${textKey(text)}`, members, text }; } @@ -248,6 +366,7 @@ export class ThreadTranscript { project(event: ThreadProjectionEvent, options: { createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number; + contributions?: ThreadProjectionEvent[]; sourceRevision?: number; mutableCollections?: boolean; }): UIMessage[] { if (!options.persisted && event.event === "user_message" && !event.provenance?.session_message) { event = { turn_seq: 0, ...event }; @@ -289,6 +408,10 @@ export class ThreadTranscript { const targets = projection.messages.filter((row) => destinations.has(this.byRow.get(row.id)!)); const scratchState = { ...copyThreadCheckpoint(this, targets).projection, activeAssistantId: null, mergeReasoning: false, activitySegmentId: null, fileEditSegmentId: null }; + // Sequence ordering proves this belongs before the installed completion, + // rather than a new execution that happens to reuse its transport id. + scratchState.closedTurnIds.delete(event.turn_id!); + scratchState.turnAliases.delete(event.turn_id!); const scratch = projectThreadEvent(scratchState, event, { ...options, effects }); const updates = new Map(scratch.messages.map((row) => [row.id, row])); const targetIds = new Set(targets.map((row) => row.id)); @@ -308,10 +431,9 @@ export class ThreadTranscript { } const before = index < 0 ? lastInTurn + 1 : index; projection = { ...projection, messages: [...messages.slice(0, before), ...additions, ...messages.slice(before)], - closedAssistantIds: scratch.closedAssistantIds, closedAnswerStreamIds: scratch.closedAnswerStreamIds, - closedTurnIds: scratch.closedTurnIds }; + closedAssistantIds: scratch.closedAssistantIds, closedAnswerStreamIds: scratch.closedAnswerStreamIds }; } else { - projection = projectThreadEvent(projection, event, { ...options, effects }); + projection = projectThreadEvent(projection, event, { ...options, effects, index: this.projectionIndex }); } if (event.event === "user_message" && projection.messages === this.messages) return this.messages; this.projection = projection; @@ -322,7 +444,8 @@ export class ThreadTranscript { const unit = this.byRow.get(id); if (unit) connected.add(unit); } - const revision = options.persisted ? 0 : ++this.revision; + const revision = options.persisted ? 0 : options.sourceRevision ?? ++this.revision; + this.revision = Math.max(this.revision, revision); const unit: Unit = { rows: new Set(), sources: new Set([source]), members, text: text ? [text] : [], introduced: revision, order: this.order++, received: revision }; for (const previous of connected) { @@ -336,7 +459,11 @@ export class ThreadTranscript { if (prior.end !== null) matching.end = Math.max(matching.end ?? 0, prior.end); for (const [first, last] of prior.members) addRange(matching.members, first, last); if (prior.snapshot) { - matching.through = matching.snapshot ? Math.max(matching.through, prior.through) : prior.through; + if (!matching.snapshot || prior.through > matching.through) { + matching.through = prior.through; + matching.after = prior.after; + matching.certified = prior.certified; + } matching.snapshot = true; } else if (!matching.snapshot) matching.through = Math.max(matching.through, prior.through); } else unit.text.push(copyText(prior)); @@ -355,6 +482,10 @@ export class ThreadTranscript { const key = JSON.stringify([text.turn, text.phase, text.stream]); this.boundaries.set(key, Math.max(text.end, this.boundaries.get(key) ?? 0)); } + if (!options.persisted && this.recordLiveContributions) for (const contribution of options.contributions ?? [event]) { + this.live.push({ event: contribution, now: options.now, revision, + startSeq: contribution.turn_seq ?? options.startSeq, sideChannel: options.sideChannel }); + } return this.messages; } @@ -370,9 +501,10 @@ export class ThreadTranscript { if (unit.text.length === 0 && Array.from(unit.sources).every((source) => candidate.bySource.has(source))) return true; if (unit.members.size === 0) return false; const represented = copyMembers(candidate.installed); - for (const text of unit.text) { - if (Array.from(candidate.units).some((other) => other.text.some((certificate) => coversText(certificate, text)))) { - mergeMembers(represented, new Map([[text.turn, text.members]])); + for (const text of unit.text) for (const certificate of candidate.textCoverage) { + if (certificate.after !== null && sameWire(certificate, text)) { + mergeCoveredMembers(represented, new Map([[text.turn, text.members]]), + new Map([[text.turn, [[certificate.after + 1, certificate.through]]]])); } } return Array.from(unit.members).every(([turn, ranges]) => ranges.every(([first, last]) => @@ -380,60 +512,216 @@ export class ThreadTranscript { } + private stageFragment(joined: ReturnType, read: ThreadRead, + gap: PendingFragmentGap | null): true { + const page = joined.body.page!; + this.fragments = joined.pages; + // The visible projection is retained until admission, including across cache restore. + for (const event of joined.withdrawn) this.withdrawnSources.add(this.describe(event).source); + this.pendingFragmentGap = gap; + this.historyGeneration = page.history_generation ?? this.historyGeneration; + this.paging = { ...this.paging, loading: false, loadingOlder: false, error: null, olderError: null, + beforeCursor: page.before_cursor ?? null, hasMoreBefore: page.has_more_before === true, truncated: true, + version: this.paging.version + (read.kind === "older" ? 0 : 1), + lineage: this.paging.lineage + (read.kind === "older" ? 0 : 1) }; + return true; + } + + private projectHistory(events: ThreadProjectionEvent[], generation: string | null): ThreadTranscript { + const previous = this.historyReplay; + const reuse = previous?.generation === generation && events.length >= previous.events.length + && previous.events.every((event, index) => event === events[index] + || JSON.stringify(event) === JSON.stringify(events[index])); + const candidate = new ThreadTranscript([], undefined, { recordLiveContributions: false }); + if (reuse) { + const owner = previous.owner; + candidate.projection = copyThreadCheckpoint(owner).projection; + candidate.units = new Set(owner.units); + candidate.byRow = new Map(owner.byRow); + candidate.bySource = new Map(owner.bySource); + candidate.boundaries = new Map(owner.boundaries); + candidate.knownTurns = new Set(owner.knownTurns); + candidate.order = owner.order; + } + for (let index = reuse ? previous.events.length : 0; index < events.length; index++) { + candidate.project(events[index], { createId: () => `history-${index}`, now: 0, persisted: true, mutableCollections: true }); + } + // Only canonical replay is reusable; live overlays and admission never enter this cache. + this.historyReplay = { events, generation, owner: candidate }; + return candidate; + } + accept(body: WebuiThreadPersistedPayload | null, read: ThreadRead): boolean { + this.fragmentCompletedTurnIds = []; if (read.kind === "older" && (read.lineage !== this.paging.lineage || read.before !== this.paging.beforeCursor)) return false; + // An initial network read may have started just before its cached seed was installed. + if (read.kind !== "older" && read.lineage !== this.paging.lineage + && !(read.kind === "initial" && read.lineage === 0 && this.paging.lineage === 1)) return false; if (read.kind === "older" && !body?.page) { this.finishRead(read, "Earlier history did not include a page cursor"); return false; } - const candidate = new ThreadTranscript(); - for (const [index, event] of (body?.events ?? []).entries()) candidate.project(event, - { createId: () => `history-${index}`, now: 0, persisted: true }); - for (const unit of candidate.units) mergeMembers(candidate.installed, unit.members); - const overlaps = new Set(Array.from(this.units).filter((old) => - Array.from(candidate.units).some((unit) => sourcesOverlap(unit, old)))); - const firstOverlap = this.messages.findIndex((row) => overlaps.has(this.byRow.get(row.id)!)); - const windowRows = new Set(this.messages.slice(Math.max(0, firstOverlap)).map((row) => row.id)); - const received = Array.from(this.units).filter((unit) => unit.received > 0 - && Array.from(unit.rows).some((id) => windowRows.has(id))); + if (read.kind === "older" && body?.page?.has_more_before === true + && (!body.page.before_cursor || body.page.before_cursor === read.before)) { + this.finishRead(read, "Earlier history cursor did not advance"); + return false; + } + const generation = body?.page?.history_generation ?? null; + const replacedHistory = generation !== null && this.historyGeneration !== null + && generation !== this.historyGeneration; + if (replacedHistory && (read.kind === "older" || this.live.length > 0 || this.revision > read.revision)) { + this.finishRead(read, "History changed during loading"); + return false; + } + const incoming = body?.page?.record_range; + const pending = this.pendingFragmentGap; + if (pending && (!incoming || incoming.turn !== pending.turn + || (read.kind === "older" && incoming.end !== pending.front))) { + this.finishRead(read, "Could not bridge the missing history records"); + return false; + } + const prior = incoming && !replacedHistory ? this.fragments.filter((page) => + (page.page?.history_generation ?? null) === generation && page.page?.record_range?.turn === incoming.turn) : []; + const priorEnd = prior.length ? Math.max(...prior.map((page) => page.page!.record_range!.end)) : null; + if (read.kind !== "older" && incoming && priorEnd !== null && incoming.end < priorEnd) { + this.finishRead(read, "History changed during loading"); + return false; + } + const joined = incoming && body ? joinThreadFragments(replacedHistory ? [] : this.fragments, body) : null; + if (joined) body = joined.body; + const groupRange = joined?.body.page?.record_range; + const gap = pending ?? (read.kind !== "older" && incoming && priorEnd !== null && incoming.start > priorEnd + ? { turn: incoming.turn, oldEnd: priorEnd, front: incoming.start } : null); + const hasGap = !!gap && !!groupRange && groupRange.start > gap.oldEnd; + const replaceWindow = hasGap && !pending && this.live.length === 0 + && Array.from(this.units).every((unit) => unit.received === 0); + if (hasGap && !replaceWindow && joined && groupRange && gap) { + const page = body!.page!; + if (!page.has_more_before || !page.before_cursor || page.before_cursor === read.before) { + this.finishRead(read, "Could not bridge the missing history records"); + return false; + } + return this.stageFragment(joined, read, { ...gap, front: groupRange.start }); + } const canonical = body ? persistedCanonicalRunState(body) : null; const completed = new Set(canonical?.completedTurnIds); - const protectedUnits = received.filter((unit) => !this.unitCovered(unit, candidate) - || (unit.text.length > 0 && (body?.page?.truncated_oversized_turn - || unit.text.some((text) => !completed.has(text.turn))))); + const completeSnapshot = !body?.page?.truncated_oversized_turn && (!joined || groupRange?.start === 0); + let candidate = this.projectHistory(body?.events ?? [], generation); + const durableText = new Map(); + for (const unit of candidate.units) { + mergeMembers(candidate.installed, unit.members); + for (const text of unit.text) if (text.snapshot && text.after !== null + && (text.certified || (completeSnapshot && completed.has(text.turn)))) { + const previous = durableText.get(textKey(text)); + if (!previous || text.through > previous.through) durableText.set(textKey(text), copyText(text)); + } + } + const durableMembers = joined ? candidate.installed : null; + candidate.textCoverage = Array.from(durableText.values()); + // Rebuild a fragment only when it has unpersisted contributions. Those + // events join the same projection as history, rather than a second overlay. + if (joined && body) { + const turns = new Set(body.events.map((event) => event.turn_id)); + const remaining = this.live.filter(({ event }) => event.turn_id && event.turn_seq !== undefined + && turns.has(event.turn_id) && !candidate.represented(event)); + if (remaining.length) { + const replay: Array<{ event: ThreadProjectionEvent; live?: LiveContribution }> = body.events.map((event) => ({ event })); + for (const entry of remaining) { + const { event } = entry; + let position = replay.findIndex((item) => item.event.turn_id === event.turn_id + && item.event.turn_seq !== undefined && item.event.turn_seq > event.turn_seq!); + if (position < 0) { + position = replay.findIndex((item) => item.event.event === "user_message" + && (this.bySource.get(this.describe(item.event).source)?.introduced ?? 0) > entry.revision); + if (position < 0) position = replay.length; + } + replay.splice(position, 0, { event, live: entry }); + } + candidate = new ThreadTranscript(); + for (const [index, item] of replay.entries()) candidate.project(item.event, item.live + ? { createId: () => `live-${item.live!.revision}-${index}`, now: item.live.now, + startSeq: item.live.startSeq, sideChannel: item.live.sideChannel, sourceRevision: item.live.revision } + : { createId: () => `history-${index}`, now: 0, persisted: true }); + for (const unit of candidate.units) mergeMembers(candidate.installed, unit.members); + candidate.textCoverage = Array.from(durableText.values()); + } + } + // Canonical recovery may replace an unfinished stream with a final message. + if (durableMembers && completeSnapshot) for (const event of body?.events ?? []) { + if (event.event !== "message" || event.kind !== undefined || !event.turn_id || !completed.has(event.turn_id)) continue; + const unit = candidate.bySource.get(this.describe(event).source); + if (unit) mergeMembers(durableMembers, unit.members); + } + // An unknown-left end may overwrite an unpersisted live buffer. Stage the + // fragment before admission, keeping the visible projection until its prefix arrives. + const overwritesLive = joined && candidate.live.some(({ event }) => { + if ((event.event !== "delta" && event.event !== "reasoning_delta") || !event.turn_id + || event.turn_seq === undefined || contains(durableMembers?.get(event.turn_id), event.turn_seq)) return false; + return body?.events.some((end) => { + if (end.turn_id !== event.turn_id || end.turn_seq === undefined || end.turn_seq <= event.turn_seq!) return false; + if (event.event === "delta" && end.event === "message" && end.kind === undefined) return true; + if (end.event !== "stream_end" && end.event !== "reasoning_end") return false; + return (end.stream_id ?? "") === (event.stream_id ?? "") + && ((event.event === "delta" && end.event === "stream_end" && typeof end.text === "string") + || (event.event === "reasoning_delta" && end.event === "reasoning_end" && !!end.text)); + }); + }); + if (overwritesLive && joined && groupRange) { + return this.stageFragment(joined, read, groupRange.start > 0 + ? { turn: groupRange.turn, oldEnd: 0, front: groupRange.start } : null); + } + const withdrawnSources = new Set([...this.withdrawnSources, ...(joined?.withdrawn ?? []).map((event) => this.describe(event).source)]); + const withdrawn = new Set(Array.from(withdrawnSources).flatMap((source) => { + const unit = this.bySource.get(source); + return unit ? [unit] : []; + })); + const matches = matchUnits(candidate.units, this.units); + const overlaps = new Set([...withdrawn, ...matches.byOld.keys()]); + const firstOverlap = this.messages.findIndex((row) => overlaps.has(this.byRow.get(row.id)!)); + const windowRows = new Set(this.messages.slice(Math.max(0, firstOverlap)).map((row) => row.id)); + const received = replacedHistory ? [] : Array.from(this.units).filter((unit) => unit.received > 0 + && Array.from(unit.rows).some((id) => windowRows.has(id))); + const protectedUnits = received.filter((unit) => !this.unitCovered(unit, candidate)); const newTail = read.empty && protectedUnits.length > 0 && protectedUnits.every((unit) => unit.received > read.revision); const appendedInputs = this.messages.filter((row) => row.role === "user" && row.turnId && this.byRow.get(row.id)!.introduced > read.revision); const appendedTurns = new Set(appendedInputs.map((row) => row.turnId!)); const appendedInputUnits = new Set(appendedInputs.map((row) => this.byRow.get(row.id)!)); - const reset = read.kind === "latest" && overlaps.size === 0 + const reset = replacedHistory || replaceWindow || (read.kind === "latest" && overlaps.size === 0 && !body?.page?.truncated_oversized_turn && protectedUnits.every((unit) => unit.introduced > read.revision && (appendedInputUnits.has(unit) || (unit.members.size > 0 - && Array.from(unit.members.keys()).every((turn) => appendedTurns.has(turn))))); + && Array.from(unit.members.keys()).every((turn) => appendedTurns.has(turn)))))); if (read.kind !== "older" && this.messages.length > 0 && overlaps.size === 0 && !newTail && !reset) { this.finishRead(read); return false; } const held = new Set(); - for (const unit of candidate.units) { - if (protectedUnits.some((old) => sourcesOverlap(unit, old))) held.add(unit); - for (const old of protectedUnits) for (const turn of old.members.keys()) { - const at = unitPosition(unit, turn); + const protectedStarts = new Map(); + for (const old of protectedUnits) { + for (const unit of matches.byOld.get(old) ?? []) held.add(unit); + for (const turn of old.members.keys()) { const start = unitPosition(old, turn); - if (at !== null && start !== null && at >= start) held.add(unit); + if (start !== null) protectedStarts.set(turn, Math.min(start, protectedStarts.get(turn) ?? Infinity)); } } + for (const unit of candidate.units) for (const turn of unit.members.keys()) { + const start = protectedStarts.get(turn); + const at = start === undefined ? null : unitPosition(unit, turn); + if (at !== null && at >= start!) held.add(unit); + } const rows = candidate.messages; let cut = rows.findIndex((row) => held.has(candidate.byRow.get(row.id)!)); if (cut < 0) cut = rows.length; + const lastRow = new Map(); + rows.forEach((row, index) => lastRow.set(candidate.byRow.get(row.id)!, index)); // A whole source can straddle several rows: never install only part of it. for (let changed = true; changed;) { changed = false; for (let index = 0; index < cut; index++) { const unit = candidate.byRow.get(rows[index].id)!; - if (rows.slice(cut).some((row) => unit.rows.has(row.id))) { cut = index; changed = true; break; } + if (lastRow.get(unit)! >= cut) { cut = index; changed = true; break; } } } const admittedRows = rows.slice(0, cut); @@ -443,21 +731,17 @@ export class ThreadTranscript { if (unit.rows.size === 0 && unit.order < cutOrder && !held.has(unit)) admitted.add(unit); } if (read.kind === "older" && Array.from(candidate.units).some((unit) => !admitted.has(unit) - && !Array.from(this.units).some((old) => sourcesOverlap(unit, old)))) { + && !matches.byNew.has(unit))) { this.finishRead(read, "Could not place earlier history"); return false; } - if (read.kind === "older" && body?.page?.has_more_before === true - && (!body.page.before_cursor || body.page.before_cursor === read.before)) { - this.finishRead(read, "Earlier history cursor did not advance"); - return false; - } const fullyAdopt = protectedUnits.length === 0 && cut === rows.length && !body?.page?.truncated_oversized_turn && (this.messages.length === 0 || reset || overlaps.size > 0); const replaced = new Set(); - for (const old of this.units) if ((reset && !protectedUnits.includes(old)) || Array.from(admitted) - .some((unit) => sourcesOverlap(unit, old) && (old.received === 0 || this.unitCovered(old, candidate)))) replaced.add(old); + for (const old of this.units) if ((reset && !protectedUnits.includes(old)) + || ((withdrawn.has(old) || Array.from(matches.byOld.get(old) ?? []).some((unit) => admitted.has(unit))) + && (old.received === 0 || this.unitCovered(old, candidate)))) replaced.add(old); const previousCount = this.messages.length; const firstReplaced = this.messages.findIndex((row) => replaced.has(this.byRow.get(row.id)!)); const prefix = read.kind !== "older" && !reset && firstReplaced > 0 @@ -467,8 +751,8 @@ export class ThreadTranscript { if (keepSuffix) for (const [index, row] of this.messages.entries()) { const old = this.byRow.get(row.id)!; if (!replaced.has(old)) continue; - for (const unit of admitted) { - if (!anchors.has(unit) && sourcesOverlap(unit, old)) anchors.set(unit, index); + for (const unit of matches.byOld.get(old) ?? []) { + if (admitted.has(unit) && !anchors.has(unit)) anchors.set(unit, index); } } const segments = new Map(); @@ -497,15 +781,26 @@ export class ThreadTranscript { for (const [turn, snapshot] of candidate.modelRequests) { modelRequests.set(turn, reconcileModelRequest(modelRequests.get(turn), snapshot)); } - this.projection = fullyAdopt && read.kind !== "older" + const oldActive = this.projection.activeAssistantId; + const activeReplaced = !!joined && !!oldActive && replaced.has(this.byRow.get(oldActive)!); + const adoptProjection = (fullyAdopt || replacedHistory) && read.kind !== "older"; + this.projection = adoptProjection ? { ...candidate.projection, messages: nextMessages, modelRequests, activitySegmentId: candidate.projection.activitySegmentId ? segments.get(candidate.projection.activitySegmentId) ?? null : null, fileEditSegmentId: candidate.projection.fileEditSegmentId ? segments.get(candidate.projection.fileEditSegmentId) ?? null : null, - closedTurnIds: new Set([...this.projection.closedTurnIds, ...candidate.projection.closedTurnIds]), - closedAnswerStreamIds: new Set([...this.projection.closedAnswerStreamIds, ...candidate.projection.closedAnswerStreamIds]) } - : { ...this.projection, messages: nextMessages, modelRequests }; + closedTurnIds: new Set([...(replacedHistory ? [] : this.projection.closedTurnIds), ...candidate.projection.closedTurnIds]), + closedAnswerStreamIds: new Set([...(replacedHistory ? [] : this.projection.closedAnswerStreamIds), ...candidate.projection.closedAnswerStreamIds]) } + : { ...this.projection, messages: nextMessages, modelRequests, + ...(activeReplaced ? { + activeAssistantId: candidate.projection.activeAssistantId, + mergeReasoning: candidate.projection.mergeReasoning, + activitySegmentId: candidate.projection.activitySegmentId + ? segments.get(candidate.projection.activitySegmentId) ?? null : null, + fileEditSegmentId: candidate.projection.fileEditSegmentId + ? segments.get(candidate.projection.fileEditSegmentId) ?? null : null, + } : {}) }; if (fullyAdopt && read.kind !== "older") { const retained = new Set(prefix.map((row) => row.id)); for (const unit of this.units) if (!Array.from(unit.rows).some((id) => retained.has(id))) replaced.add(unit); @@ -516,29 +811,37 @@ export class ThreadTranscript { for (const key of unit.sources) this.bySource.delete(key); } for (const unit of admitted) this.installUnit(unit); + this.withdrawnSources = new Set(Array.from(withdrawnSources).filter((source) => withdrawn.has(this.bySource.get(source)!))); const retainedMembers: Members = new Map(); for (const unit of this.units) mergeMembers(retainedMembers, unit.members); const installed: Members = new Map(); - for (const [turn, ranges] of this.installed) { - const kept: Ranges = []; - for (const [first, last] of ranges) for (const [a, b] of retainedMembers.get(turn) ?? []) { - if (first <= b && a <= last) addRange(kept, Math.max(first, a), Math.min(last, b)); - } - if (kept.length) installed.set(turn, kept); - } + mergeCoveredMembers(installed, this.installed, retainedMembers); const certificates = new Map(this.textCoverage .filter((text) => this.bySource.has(`text:${textKey(text)}`)) .map((text) => [textKey(text), text])); for (const unit of admitted) { - mergeMembers(installed, unit.members); - for (const text of unit.text) if (text.snapshot && text.after !== null) { - const previous = certificates.get(textKey(text)); - if (!previous || text.through > previous.through) certificates.set(textKey(text), copyText(text)); + if (durableMembers) mergeCoveredMembers(installed, unit.members, durableMembers); + else mergeMembers(installed, unit.members); + for (const text of unit.text) { + const evidence = durableText.get(textKey(text)); + if (!evidence?.snapshot || evidence.after === null) continue; + const previous = certificates.get(textKey(evidence)); + if (!previous || evidence.through > previous.through) certificates.set(textKey(evidence), copyText(evidence)); } } this.installed = installed; this.textCoverage = Array.from(certificates.values()); - if (fullyAdopt && read.kind !== "older") { + const confirmedInputs = new Set(); + for (const event of body?.events ?? []) { + if (event.event !== "user_message" || !admitted.has(candidate.bySource.get(candidate.describe(event).source)!)) continue; + if (event.input_id) confirmedInputs.add(`id:${event.input_id}`); + if (event.provenance?.session_message?.message_id) confirmedInputs.add(`message:${event.provenance.session_message.message_id}`); + } + this.live = this.live.filter(({ event }) => !(event.event === "user_message" + && ((event.input_id && confirmedInputs.has(`id:${event.input_id}`)) + || (event.provenance?.session_message?.message_id && confirmedInputs.has(`message:${event.provenance.session_message.message_id}`)))) + && !this.represented(event)); + if (adoptProjection) { this.boundaries = new Map(candidate.boundaries); this.knownTurns = new Set(candidate.knownTurns); } @@ -550,12 +853,16 @@ export class ThreadTranscript { this.boundaries.set(key, Math.max(end, this.boundaries.get(key) ?? 0)); } } + this.projection.closedTurnIds = new Set(this.projection.closedTurnIds); + this.projection.closedAssistantIds = new Set(this.projection.closedAssistantIds); + this.projection.closedAnswerStreamIds = new Set(this.projection.closedAnswerStreamIds); for (const event of body?.events ?? []) { if (event.event === "turn_end" && event.turn_id && event.turn_seq !== undefined && contains(this.installed.get(event.turn_id), event.turn_seq)) this.projection.closedTurnIds.add(event.turn_id); } + const admittedRowIds = new Set(admittedRows.map((row) => row.id)); for (const id of candidate.projection.closedAssistantIds) { - if (admittedRows.some((row) => row.id === id)) this.projection.closedAssistantIds.add(id); + if (admittedRowIds.has(id)) this.projection.closedAssistantIds.add(id); } const admittedStreams = new Set(admittedRows.filter((row) => row.streamId) .map((row) => JSON.stringify([row.turnId ?? "", row.streamId]))); @@ -600,6 +907,10 @@ export class ThreadTranscript { if (forkRows && boundary !== undefined) for (const [index, event] of (body?.events ?? []).slice(0, boundary).entries()) { forkRows.project(event, { createId: () => `boundary-${index}`, now: 0, persisted: true }); } + if (reset) this.fragments = []; + if (joined) this.fragments = joined.pages; + if (pending && !hasGap) this.pendingFragmentGap = null; + if (generation !== null) this.historyGeneration = generation; this.paging = { ...this.paging, loading: false, loadingOlder: false, error: null, olderError: read.kind !== "older" && !reset && (preserveFrontier || this.paging.beforeCursor === page?.before_cursor) ? this.paging.olderError : null, @@ -620,6 +931,7 @@ export class ThreadTranscript { activeTurnId: body?.active_turn_id ?? null, }), }; + if (joined && admitted.size === candidate.units.size) this.fragmentCompletedTurnIds = [...completed]; return true; } @@ -634,11 +946,14 @@ export class ThreadTranscript { const scratch = new ThreadTranscript(); events.forEach((event, index) => scratch.project(event, { createId: () => `detail:${ref}:${index}`, now: 0, persisted: true })); - const unit = this.byRow.get(target.id)!; + const previous = this.byRow.get(target.id)!; + const unit = { ...previous, rows: new Set(previous.rows) }; + this.units.delete(previous); unit.rows.delete(target.id); this.byRow.delete(target.id); const replacements = scratch.messages.map((row) => ({ ...row, activitySegmentId: target.activitySegmentId })); - for (const row of replacements) { unit.rows.add(row.id); this.byRow.set(row.id, unit); } + for (const row of replacements) unit.rows.add(row.id); + this.installUnit(unit); this.projection = { ...this.projection, messages: this.messages.flatMap((row) => row === target ? replacements : [row]) }; } @@ -648,6 +963,9 @@ export class ThreadTranscript { members: copyMembers(unit.members), text: unit.text.map(copyText) })), installed: copyMembers(this.installed), textCoverage: this.textCoverage.map(copyText), boundaries: new Map(this.boundaries), knownTurns: new Set(this.knownTurns), - paging: { ...this.paging }, revision: this.revision }; + paging: { ...this.paging }, revision: this.revision, fragments: [...this.fragments], live: [...this.live], + historyGeneration: this.historyGeneration, + pendingFragmentGap: this.pendingFragmentGap ? { ...this.pendingFragmentGap } : null, + withdrawnSources: new Set(this.withdrawnSources) }; } } diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index b191261ad..7bcbc9df6 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1595,6 +1595,8 @@ export type InboundEvent = chat_id: string; stream_id?: string; text?: string; + /** Inclusive first turn sequence covered by this stream's cumulative text. */ + text_from_seq?: number; /** Lightweight provenance for proactive streamed assistant messages. */ source?: UIMessageSource; response_sources?: ResponseSource[]; @@ -1614,8 +1616,8 @@ export type InboundEvent = event: "reasoning_end"; chat_id: string; stream_id?: string; - /** Legacy persisted transcripts may carry the final reasoning text here. */ text?: string; + text_from_seq?: number; } & InboundTurnMetadata) | { event: "pairing_changed" } | { @@ -1762,7 +1764,17 @@ export interface OutboundMcpPresetMention { brand_color?: string | null; } +export interface WebuiThreadRecordRange { + turn: number; + start: number; + end: number; +} + interface WebuiThreadPagePayload { + history_generation?: string | null; + record_range?: WebuiThreadRecordRange; + /** The fragment includes the canonical replacement for this turn's stored answers. */ + recovered_answers?: boolean; before_cursor?: string | null; has_more_before?: boolean; after_cursor?: string | null; diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index d375a03f6..a03f04f63 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -202,6 +202,7 @@ describe("webui API helpers", () => { it.each([ {}, { stream_id: "answer-1" }, + { stream_id: "answer-1", text_from_seq: 2 }, { projection_receipts: [] }, { stream_id: "answer-1", projection_receipts: [{ turn_id: "turn-1", ranges: [[1, 3], [5, 5]] }] }, ])("accepts optional stream identity and projection receipts: %j", async (metadata) => { @@ -233,6 +234,25 @@ describe("webui API helpers", () => { ); }); + it("preserves the fragment answer-recovery declaration at the HTTP boundary", () => { + const payload = { schemaVersion: 3, projection: "events", events: [], + page: { record_range: { turn: 0, start: 2, end: 4002 }, recovered_answers: true } }; + expect(parseWebuiThreadPayload(payload).page).toEqual(payload.page); + expect(() => parseWebuiThreadPayload({ ...payload, page: { ...payload.page, recovered_answers: "true" } })) + .toThrow("Invalid WebUI thread answer recovery"); + }); + + it.each(["stream_end", "reasoning_end"])("validates %s text snapshot coverage", (event) => { + const payload = (fields: Record) => ({ schemaVersion: 3, projection: "events", + events: [{ event, chat_id: "chat-1", turn_id: "turn-1", turn_seq: 6, text: "Reply", ...fields }] }); + expect(parseWebuiThreadPayload(payload({ text_from_seq: 2 })).events[0]) + .toMatchObject({ text_from_seq: 2, turn_seq: 6 }); + for (const fields of [{ text_from_seq: -1 }, { text_from_seq: 7 }, { text_from_seq: 2.5 }, + { text_from_seq: 2, turn_seq: undefined }]) { + expect(() => parseWebuiThreadPayload(payload(fields))).toThrow(`Invalid WebUI thread projection event: ${event}`); + } + }); + it.each([ null, "backup", diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts index 01e9f8a77..92710b766 100644 --- a/webui/src/tests/nanobot-client.test.ts +++ b/webui/src/tests/nanobot-client.test.ts @@ -174,6 +174,83 @@ describe("NanobotClient", () => { client.close(); }); + it.each(["recovery_state", "attached"] as const)("waits for a canonical running identity after unscoped %s starts a new recovery", (event) => { + const client = new NanobotClient({ url: "ws://test", reconnect: false, + socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); + client.connect(); + const socket = lastSocket(); + socket.fakeOpen(); + socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "recovery:old-recovery", status: "running", started_at: 100 }); + socket.fakeMessage({ event: "turn_end", chat_id: "chat", turn_id: "recovery:old-recovery" }); + const state = { status: "resuming", recovery_id: "new-recovery", attempts: 1 }; + socket.fakeMessage(event === "recovery_state" + ? { event, chat_id: "chat", ...state } + : { event, chat_id: "chat", recovery_state: state }); + expect(client.getRunState("chat")).toMatchObject({ active: true, unsettled: false, latestTurnId: "recovery:old-recovery" }); + socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "recovery:new-recovery", status: "running", started_at: 200 }); + expect(client.getRunState("chat")).toMatchObject({ active: true, unsettled: true, + latestTurnId: "recovery:new-recovery", startedAt: 200 }); + client.close(); + }); + + it.each(["recovery_state", "attached"] as const)("prefers an explicit turn_id over recovery_id on %s", (event) => { + const client = new NanobotClient({ url: "ws://test", reconnect: false, + socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); + client.connect(); + const socket = lastSocket(); + socket.fakeOpen(); + socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "turn-explicit", status: "running", started_at: 100 }); + socket.fakeMessage({ event: "turn_end", chat_id: "chat", turn_id: "turn-explicit" }); + const state = { status: "resuming", recovery_id: "new-recovery", attempts: 1 }; + socket.fakeMessage(event === "recovery_state" + ? { event, chat_id: "chat", turn_id: "turn-explicit", ...state } + : { event, chat_id: "chat", turn_id: "turn-explicit", recovery_state: state }); + expect(client.getRunState("chat")).toMatchObject({ active: false, unsettled: false, latestTurnId: "turn-explicit" }); + client.close(); + }); + + it("delivers a recovered state after the recovery turn ends", () => { + const client = new NanobotClient({ url: "ws://test", reconnect: false, + socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); + client.connect(); + const socket = lastSocket(); + socket.fakeOpen(); + const received = vi.fn(); + client.onTranscript("chat", received); + socket.fakeMessage({ event: "recovery_state", chat_id: "chat", status: "resuming", recovery_id: "r1" }); + socket.fakeMessage({ event: "turn_end", chat_id: "chat", turn_id: "recovery:r1" }); + const recovered = { event: "recovery_state", chat_id: "chat", status: "recovered", recovery_id: "r1", reason: "continued" }; + socket.fakeMessage(recovered); + expect(received).toHaveBeenCalledWith(recovered); + expect(client.getRunState("chat").active).toBe(false); + client.close(); + }); + + it("allows Continue after fragment completion and loop guard, preserving the reused canonical id's live content", () => { + const client = new NanobotClient({ url: "ws://test", reconnect: false, + socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); + client.connect(); + const socket = lastSocket(); + socket.fakeOpen(); + socket.fakeMessage({ event: "recovery_state", chat_id: "chat", status: "resuming", recovery_id: "r1", attempts: 1 }); + socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "recovery:r1", status: "running", started_at: 100 }); + client.settleFragmentRunLifecycle("chat", ["recovery:r1"]); + socket.fakeMessage({ event: "attached", chat_id: "chat", recovery_state: { + status: "awaiting_user", recovery_id: "r1", reason: "loop_guard", attempts: 1, + } }); + expect(client.getRunState("chat").active).toBe(false); + socket.fakeMessage({ event: "recovery_state", chat_id: "chat", status: "resuming", recovery_id: "r1", attempts: 2 }); + expect(client.getRunState("chat").active).toBe(true); + const content = { event: "delta", chat_id: "chat", turn_id: "recovery:r1", text: "Continued output" }; + socket.fakeMessage(content); + const replay = vi.fn(); + client.onTranscript("chat", replay); + expect(replay).toHaveBeenCalledWith(content); + socket.fakeMessage({ event: "turn_end", chat_id: "chat", turn_id: "recovery:r1" }); + expect(client.getRunState("chat").active).toBe(false); + client.close(); + }); + it("reconciles simultaneous client submissions to the gateway-owned turn", () => { const client = new NanobotClient({ url: "ws://test", @@ -1803,6 +1880,40 @@ describe("NanobotClient", () => { ); }); + it("bounds fragment lifecycle tombstones without pruning buffered content or releasing the latest owner", () => { + const client = new NanobotClient({ url: "ws://test", reconnect: false, + socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket }); + client.connect(); + const socket = lastSocket(); + socket.fakeOpen(); + socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "current", status: "running", started_at: 100 }); + const buffered = { event: "delta", chat_id: "chat", turn_id: "current", text: "Unconsumed live content" }; + const oldContent = { event: "message", chat_id: "chat", turn_id: "history-0", text: "Unconsumed older content" }; + socket.fakeMessage(buffered); + socket.fakeMessage(oldContent); + client.settleFragmentRunLifecycle("chat", ["current"]); + const history = Array.from({ length: 300 }, (_, index) => `history-${index}`); + client.settleFragmentRunLifecycle("chat", history); + + expect(history.filter((id) => client.isRunCompleted("chat", id))).toHaveLength(255); + expect(client.isRunCompleted("chat", "history-0")).toBe(false); + expect(client.isRunCompleted("chat", "history-299")).toBe(true); + expect(client.isRunCompleted("chat", "current")).toBe(true); + const settled = client.getRunState("chat"); + const late = { event: "delta", chat_id: "chat", turn_id: "current", text: "Late live content" }; + const streamEnd = { event: "stream_end", chat_id: "chat", turn_id: "current", stream_id: "wire" }; + socket.fakeMessage(late); + socket.fakeMessage(streamEnd); + socket.fakeMessage({ event: "goal_status", chat_id: "chat", turn_id: "current", status: "running", started_at: 999 }); + expect(client.getRunState("chat")).toEqual(settled); + expect(settled).toMatchObject({ active: false, unsettled: false, latestTurnId: "current", startedAt: null }); + const replay = vi.fn(); + client.onTranscript("chat", replay); + for (const content of [buffered, oldContent, late, streamEnd]) expect(replay).toHaveBeenCalledWith(content); + expect(replay).not.toHaveBeenCalledWith(expect.objectContaining({ event: "goal_status" })); + client.close(); + }); + it("clears the run cache and fences delayed frames after canonical completion", () => { const client = new NanobotClient({ url: "ws://test", diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.ts index 94a8f5190..154ed70d0 100644 --- a/webui/src/tests/thread-event-projection.test.ts +++ b/webui/src/tests/thread-event-projection.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { createThreadProjectionState, projectThreadEvent, projectThreadEvents } from "@/lib/thread-event-projection"; import { normalizeActivityTimeline } from "@/lib/activity-timeline"; +import { ThreadProjectionIndex } from "@/lib/thread-projection-index"; import type { ThreadProjectionEvent, UIMessage } from "@/lib/types"; import projectionFixture from "./fixtures/live-replay-event-projection.json"; @@ -77,8 +78,9 @@ function normalizeProjection(messages: UIMessage[]): Array { it("routes late snapshots by stream without moving same-text answers or stealing the active cursor", () => { let state = createThreadProjectionState(); + const index = new ThreadProjectionIndex(); const emit = (event: ThreadProjectionEvent) => { - state = projectThreadEvent(state, event, { createId: () => `live-${state.messages.length}`, now: 100 }); + state = projectThreadEvent(state, event, { createId: () => `live-${state.messages.length}`, now: 100, index }); }; emit({ event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 1, text: "Same answer" }); emit({ event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 2, resuming: true }); @@ -97,6 +99,28 @@ describe("canonical thread event projection", () => { expect(state.messages[2]).toMatchObject({ projectionStartSeq: 4, turnSeq: 6, streamId: "second" }); }); + it("can resume an earlier checkpoint after another branch closes the same stream", () => { + const index = new ThreadProjectionIndex(); + const options = { createId: () => "answer", now: 100, index }; + const initial = createThreadProjectionState(); + const open = projectThreadEvent(initial, { + event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "wire", text: "Prefix", + }, options); + const ended = projectThreadEvent(open, { + event: "stream_end", chat_id: "chat", turn_id: "turn", stream_id: "wire", text: "Prefix final", + }, options); + expect(ended.closedAnswerStreamIds.size).toBe(1); + expect(open.closedAnswerStreamIds.size).toBe(0); + expect(open.closedAssistantIds.size).toBe(0); + const resumed = projectThreadEvent(open, { + event: "delta", chat_id: "chat", turn_id: "turn", stream_id: "wire", text: " continues", + }, options); + expect(initial.messages).toEqual([]); + expect(open.messages.map((row) => row.content)).toEqual(["Prefix"]); + expect(ended.messages.map((row) => row.content)).toEqual(["Prefix final"]); + expect(resumed.messages.map((row) => row.content)).toEqual(["Prefix continues"]); + }); + it("updates an identified reasoning snapshot without duplicating it or closing another phase", () => { const messages = projectThreadEvents([ { event: "reasoning_delta", chat_id: "chat", turn_id: "turn", stream_id: "first", turn_seq: 1, text: "First thought" }, diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index e999cbf0f..a5fc1a57f 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -95,6 +95,7 @@ function makeClient() { getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle), canReconcileCanonicalCompletion, reconcileCanonicalCompletion, + settleFragmentRunLifecycle: vi.fn(lifecycle.settleFragmentRunLifecycle.bind(lifecycle)), fenceCanonicalCompletedTurns: lifecycle.fenceCanonicalCompletedTurns.bind(lifecycle), getGoalState: lifecycle.getGoalState.bind(lifecycle), onTranscript: lifecycle.onTranscript.bind(lifecycle), @@ -244,7 +245,7 @@ function streamedThreadPayload( projection_id: `answer:${row.turnId}:${row.streamId}:${endSeq}`, turn_id: row.turnId, turn_phase: "answer", turn_seq: endSeq, stream_id: row.streamId, text: row.content, - projection_receipts: [{ turn_id: row.turnId, ranges: [[textSeq, endSeq]] }], + text_from_seq: textSeq, ...(row.mergeNext ? { resuming: true, merge_next: true } : {}), }); } @@ -4568,7 +4569,7 @@ describe("ThreadShell", () => { )); }); - it("keeps the live answer cursor when a resumed turn is still running", async () => { + it("catches up the active answer and keeps its cursor when a resumed turn is still running", async () => { const client = makeClient(); let historyCalls = 0; const turnId = "turn-active-resume"; @@ -4644,6 +4645,7 @@ describe("ThreadShell", () => { expect(client.sendMessage).not.toHaveBeenCalled(); act(() => client._emitStatus("open")); await waitFor(() => expect(historyCalls).toBe(2)); + await screen.findByText("partial answer missed"); expect(client.sendMessage).not.toHaveBeenCalled(); act(() => { @@ -4655,7 +4657,7 @@ describe("ThreadShell", () => { }); }); - await waitFor(() => expect(screen.getByText("partial answer resumed")).toBeInTheDocument()); + await waitFor(() => expect(screen.getByText("partial answer missed resumed")).toBeInTheDocument()); expect(screen.queryByText(" resumed")).not.toBeInTheDocument(); expect(client.sendMessage).not.toHaveBeenCalled(); diff --git a/webui/src/tests/thread-transcript.test.ts b/webui/src/tests/thread-transcript.test.ts index 84ee1b244..ee4e3b78f 100644 --- a/webui/src/tests/thread-transcript.test.ts +++ b/webui/src/tests/thread-transcript.test.ts @@ -1,7 +1,8 @@ -import { beforeEach, describe, expect, it } from "vitest"; +import { beforeEach, describe, expect, it, vi } from "vitest"; import { ThreadTranscript } from "@/lib/thread-transcript"; -import type { ThreadProjectionEvent, WebuiThreadPersistedPayload } from "@/lib/types"; +import * as eventProjection from "@/lib/thread-event-projection"; +import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types"; const NOW = 1_800_000_000_000; let nextId = 0; @@ -12,7 +13,7 @@ function at(turn_id: string, turn_seq: number) { return { chat_id: "hydration-chat", turn_id, turn_seq }; } -function input(turnId: string, text: string): ThreadProjectionEvent { +function input(turnId: string, text: string): Extract { return { ...at(turnId, 1), event: "user_message", text, starts_turn: true }; } @@ -41,6 +42,43 @@ function receive(thread: ThreadTranscript, ...events: ThreadProjectionEvent[]): } describe("ThreadTranscript admission", () => { + it("reuses an unchanged fragment prefix but replaces a revised answer with the same identity", () => { + const thread = new ThreadTranscript(); + const events: ThreadProjectionEvent[] = [ + input("append", "Question"), + { ...at("append", 2), event: "stream_end", stream_id: "first", text: "First", text_from_seq: 2 }, + { ...at("append", 3), event: "message", kind: "tool_hint", text: "Tool" }, + { ...at("append", 4), event: "stream_end", stream_id: "second", text: "Second", text_from_seq: 4 }, + ]; + const page = (start: number, end: number, values = events) => history(values.slice(start, end), { + completed_turn_ids: [], has_pending_tool_calls: true, + page: { record_range: { turn: 0, start, end }, history_generation: "append-generation", + truncated_oversized_turn: true, before_cursor: start ? `before-${start}` : null, + has_more_before: start > 0, user_message_offset: 0 }, + }); + expect(thread.accept(page(0, 3), thread.begin("initial"))).toBe(true); + const saved = thread.save(); + const project = vi.spyOn(eventProjection, "projectThreadEvent"); + try { + expect(thread.accept(page(2, 4), thread.begin("latest"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "First", "Tool", "Second"]); + expect(project).toHaveBeenCalledTimes(1); + expect(project.mock.calls[0][1]).toMatchObject({ event: "stream_end", text: "Second" }); + project.mockClear(); + expect(thread.accept(page(2, 4), thread.begin("latest"))).toBe(true); + expect(project).toHaveBeenCalledTimes(0); + const revised = events.map((event) => event.event === "stream_end" && event.stream_id === "second" + ? { ...event, text: "Corrected second" } : event); + expect(thread.accept(page(2, 4, revised), thread.begin("latest"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "First", "Tool", "Corrected second"]); + const restored = new ThreadTranscript([], saved); + expect(restored.accept(page(2, 4), restored.begin("latest"))).toBe(true); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "First", "Tool", "Second"]); + } finally { + project.mockRestore(); + } + }); + it("updates a represented live input's final image URL without duplicating it", () => { const thread = new ThreadTranscript(); const first: ThreadProjectionEvent = { ...at("upload", 1), event: "user_message", text: "look", starts_turn: true, @@ -237,7 +275,7 @@ describe("ThreadTranscript admission", () => { const thread = new ThreadTranscript(); const installed: ThreadProjectionEvent = { ...at("turn-history-first", 4), event: "stream_end", stream_id: "answer-first", - text: "Installed ", resuming: true, merge_next: true, + text: "Installed ", text_from_seq: 2, resuming: true, merge_next: true, }; expect(thread.accept(history([input("turn-history-first", "Continue"), installed]), thread.begin("initial"))).toBe(true); const answerId = thread.messages[1].id; @@ -281,9 +319,9 @@ describe("ThreadTranscript admission", () => { const thread = new ThreadTranscript(); expect(thread.accept(history([ input("turn-no-id", "Think in stages"), - { ...at("turn-no-id", 3), event: "reasoning_end", text: "First thought" }, + { ...at("turn-no-id", 3), event: "reasoning_end", text: "First thought", text_from_seq: 2 }, { ...at("turn-no-id", 4), event: "message", kind: "progress", text: "Read a file" }, - { ...at("turn-no-id", 7), event: "reasoning_end", text: "Second thought" }, + { ...at("turn-no-id", 7), event: "reasoning_end", text: "Second thought", text_from_seq: 6 }, ]), thread.begin("initial"))).toBe(true); receive(thread, @@ -407,8 +445,8 @@ describe("ThreadTranscript admission", () => { const original = new ThreadTranscript(); expect(original.accept(history([ input("turn-cached", "Continue after returning"), - { ...at("turn-cached", 3), event: "reasoning_end", text: "Plan." }, - { ...at("turn-cached", 5), event: "stream_end", stream_id: "answer-cached", text: "First", resuming: true, merge_next: true }, + { ...at("turn-cached", 3), event: "reasoning_end", text: "Plan.", text_from_seq: 2 }, + { ...at("turn-cached", 5), event: "stream_end", stream_id: "answer-cached", text: "First", text_from_seq: 4, resuming: true, merge_next: true }, ]), original.begin("initial"))).toBe(true); const sharedId = original.messages[1].id; expect(original.accept(history([ @@ -641,6 +679,520 @@ describe("ThreadTranscript admission", () => { expect(saved.units.every((unit) => Array.from(unit.members.keys()).every((turn) => turn === "turn-window-3"))).toBe(true); }); + it("refreshes a disjoint latest fragment and pages back across the gap after restoring the cache", () => { + const events: ThreadProjectionEvent[] = [ + input("growing", "Question"), + ...["B", "C", "D", "E", "F"].map((text, index) => ({ + ...at("growing", index + 2), event: "message" as const, text, + })), + ]; + const fragment = (start: number, end: number) => history(events.slice(start, end), { + active_turn_id: "growing", + page: { history_generation: "generation", record_range: { turn: 0, start, end }, + before_cursor: start ? `before-${start}` : null, has_more_before: start > 0, truncated_oversized_turn: true }, + }); + const initial = new ThreadTranscript(); + expect(initial.accept(fragment(1, 3), initial.begin("initial"))).toBe(true); + const thread = new ThreadTranscript([], initial.save()); + const staleOlder = thread.begin("older"); + // A restored owner issues an initial read even though it has a cached window. + expect(thread.accept(fragment(4, 6), thread.begin("initial"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["E", "F"]); + expect(thread.hasPendingFragmentGap).toBe(false); + expect(thread.paging).toMatchObject({ beforeCursor: "before-4", hasMoreBefore: true }); + expect(thread.accept(fragment(0, 1), staleOlder)).toBe(false); + expect(thread.paging.beforeCursor).toBe("before-4"); + + expect(thread.accept(fragment(2, 4), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["B", "C", "D", "E", "F"]); + expect(thread.paging.beforeCursor).toBe("before-1"); + expect(thread.accept(fragment(0, 1), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "B", "C", "D", "E", "F"]); + expect(thread.paging.hasMoreBefore).toBe(false); + }); + + it("keeps an unpersisted live contribution visible while paging across a multi-page gap", () => { + // D was delivered live but never persisted, so record positions and turn_seq differ. + const events: ThreadProjectionEvent[] = [ + input("gap-live", "Question"), + ...[[2, "B"], [3, "C"], [5, "E"], [6, "F"], [7, "G"], [8, "H"], [9, "I"]].map(([seq, text]) => ({ + ...at("gap-live", seq as number), event: "delta" as const, stream_id: "wire", text: text as string, + })), + ]; + const fragment = (start: number, end: number) => history(events.slice(start, end), { + active_turn_id: "gap-live", + page: { history_generation: "generation", record_range: { turn: 0, start, end }, + before_cursor: start ? `before-${start}` : null, has_more_before: start > 0, truncated_oversized_turn: true }, + }); + const thread = new ThreadTranscript(); + expect(thread.accept(fragment(1, 3), thread.begin("initial"))).toBe(true); + receive(thread, { ...at("gap-live", 4), event: "delta", stream_id: "wire", text: "D" }); + const staleOlder = thread.begin("older"); + const staleLatest = thread.begin("latest"); + expect(thread.accept(fragment(6, 8), thread.begin("latest"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["BCD"]); + expect(thread.hasPendingFragmentGap).toBe(true); + expect(thread.paging).toMatchObject({ beforeCursor: "before-6", hasMoreBefore: true, error: null }); + expect(thread.accept(fragment(0, 1), staleOlder)).toBe(false); + expect(thread.accept(fragment(1, 3), staleLatest)).toBe(false); + expect(thread.accept(fragment(4, 6), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["BCD"]); + expect(thread.paging.beforeCursor).toBe("before-4"); + + const restored = new ThreadTranscript([], thread.save()); + expect(restored.hasPendingFragmentGap).toBe(true); + expect(restored.accept(fragment(2, 4), restored.begin("older"))).toBe(true); + expect(restored.hasPendingFragmentGap).toBe(false); + expect(restored.messages.map((row) => row.content)).toEqual(["BCDEFGHI"]); + expect(restored.accept(fragment(0, 2), restored.begin("older"))).toBe(true); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "BCDEFGHI"]); + receive(restored, { ...at("gap-live", 10), event: "delta", stream_id: "wire", text: "J" }); + expect(restored.messages.at(-1)?.content).toBe("BCDEFGHIJ"); + }); + + it("loads the missing prefix before adopting an unknown-left media-signed snapshot", () => { + const turn = "gap-snapshot-conflict"; + const chunk = (seq: number, text: string): ThreadProjectionEvent => ({ ...at(turn, seq), event: "delta", text }); + const fragment = (start: number, end: number, events: ThreadProjectionEvent[], completed = false) => history(events, { + active_turn_id: completed ? null : turn, + completed_turn_ids: completed ? [turn] : [], + page: { history_generation: "generation", record_range: { turn: 0, start, end }, + before_cursor: start ? `before-${start}` : null, has_more_before: start > 0, truncated_oversized_turn: true }, + }); + const thread = new ThreadTranscript(); + expect(thread.accept(fragment(1, 3, [chunk(2, "B"), chunk(3, "C")]), thread.begin("initial"))).toBe(true); + receive(thread, chunk(4, "![image](images/photo.png)")); + expect(thread.accept(fragment(6, 8, [ + { ...at(turn, 8), event: "stream_end", text: "BC![image](/api/media/signed.png)EFG" }, + { ...at(turn, 9), event: "turn_end" }, + ], true), thread.begin("latest"))).toBe(true); + receive(thread, chunk(5, "E")); + + expect(thread.accept(fragment(3, 6, [chunk(5, "E"), chunk(6, "F"), chunk(7, "G")]), thread.begin("older"))).toBe(true); + expect(thread.paging.olderError).toBeNull(); + expect(thread.paging.beforeCursor).toBe("before-1"); + expect(thread.hasPendingFragmentGap).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["BC![image](images/photo.png)E"]); + expect(thread.save().live.map(({ event }) => event.turn_seq)).toEqual([4, 5]); + expect(thread.accept(fragment(0, 1, [input(turn, "Question")]), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "BC![image](/api/media/signed.png)EFG"]); + expect(thread.hasPendingFragmentGap).toBe(false); + expect(thread.save().live).toEqual([]); + }); + + it("adopts a completed canonical message only after its missing prefix has loaded", () => { + const turn = "gap-message-conflict"; + const chunk = (seq: number, text: string): ThreadProjectionEvent => ({ ...at(turn, seq), event: "delta", stream_id: "wire", text }); + const fragment = (start: number, end: number, events: ThreadProjectionEvent[], completed = false) => history(events, { + active_turn_id: completed ? null : turn, + completed_turn_ids: completed ? [turn] : [], + page: { history_generation: "generation", record_range: { turn: 0, start, end }, + before_cursor: start ? `before-${start}` : null, has_more_before: start > 0, truncated_oversized_turn: true }, + }); + const thread = new ThreadTranscript(); + expect(thread.accept(fragment(1, 3, [chunk(2, "B"), chunk(3, "C")]), thread.begin("initial"))).toBe(true); + receive(thread, chunk(4, "D")); + expect(thread.accept(fragment(6, 8, [ + { ...at(turn, 8), event: "message", text: "Canonical answer" }, + { ...at(turn, 9), event: "turn_end" }, + ], true), thread.begin("latest"))).toBe(true); + receive(thread, chunk(5, "E")); + + expect(thread.accept(fragment(3, 6, [chunk(5, "E"), chunk(6, "F"), chunk(7, "G")]), thread.begin("older"))).toBe(true); + expect(thread.paging.olderError).toBeNull(); + expect(thread.hasPendingFragmentGap).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["BCDE"]); + expect(thread.save().live.map(({ event }) => event.turn_seq)).toEqual([4, 5]); + expect(thread.accept(fragment(0, 1, [input(turn, "Question")]), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "Canonical answer"]); + expect(thread.hasPendingFragmentGap).toBe(false); + expect(thread.save().live).toEqual([]); + }); + + it.each(["before", "after"] as const)("keeps live output ordered when a session input arrives %s it", (order) => { + const thread = new ThreadTranscript(); + const turn = "injected-fragment"; + const prefix: ThreadProjectionEvent[] = [input(turn, "Question"), + { ...at(turn, 2), event: "message", kind: "progress", text: "Working" }]; + const provenance = { message_id: "injected", session: { id: "handle_0123456789abcdef0123456789abcdef", name: "mira" } }; + const injected: ThreadProjectionEvent = { chat_id: "hydration-chat", event: "user_message", starts_turn: false, + text: "Please review", provenance: { session_message: provenance }, projection_id: "injected-record" }; + const fragment = (events: ThreadProjectionEvent[], end: number) => history(events, { active_turn_id: turn, + page: { record_range: { turn: 0, start: 0, end }, truncated_oversized_turn: true } }); + expect(thread.accept(fragment(prefix, 2), thread.begin("initial"))).toBe(true); + const admit = () => { + const row: UIMessage = { id: "session-message:injected", role: "user", content: "Please review", createdAt: NOW, sessionMessage: provenance }; + thread.projection = { ...thread.projection, messages: [...thread.messages, row] }; + thread.registerInput(row); + }; + const output = () => receive(thread, + { ...at(turn, 3), event: "model_request", request_id: "new-request", run_id: turn, sequence: 2, phase: "started" }, + { ...at(turn, 4), event: "delta", stream_id: "new-wire", text: "Answer" }); + if (order === "before") { admit(); output(); } else { output(); admit(); } + expect(thread.accept(fragment([...prefix, injected], 3), thread.begin("latest"))).toBe(true); + const body = thread.messages.filter((message) => message.role === "user" || message.kind !== "trace").map((message) => message.content); + expect(body).toEqual(order === "before" ? ["Question", "Please review", "Answer"] : ["Question", "Answer", "Please review"]); + if (order === "before") { + receive(thread, { ...at(turn, 5), event: "delta", stream_id: "new-wire", text: " continued" }); + expect(thread.messages.at(-1)?.content).toBe("Answer continued"); + } + }); + + it("keeps a late unpersisted tool activity in its completed historical turn", () => { + const thread = new ThreadTranscript(); + const turn = "late-history-tool"; + const answer: ThreadProjectionEvent = { ...at(turn, 5), event: "stream_end", stream_id: "wire", text: "Answer" }; + expect(thread.accept(history([answer, + { ...at(turn, 6), event: "turn_end" }], { completed_turn_ids: [turn], + page: { record_range: { turn: 0, start: 3, end: 5 }, before_cursor: "before", has_more_before: true } }), thread.begin("initial"))).toBe(true); + receive(thread, { ...at(turn, 4), event: "message", kind: "tool_hint", text: "read_file()" }); + const tool = thread.messages.find((message) => message.kind === "trace")!; + expect(tool.turnId).toBe(turn); + expect(thread.messages.indexOf(tool)).toBeLessThan(thread.messages.findIndex((message) => message.content === "Answer")); + expect(thread.messages.at(-1)?.content).toBe("Answer"); + expect(thread.projection.closedTurnIds.has(turn)).toBe(true); + }); + + it("stores each raw event once when many latest pages slide over each other", () => { + // Some raw positions have no projected event; equal text is not an identity. + const records = Array.from({ length: 28 }, (_, position): ThreadProjectionEvent | null => + position % 7 === 0 ? null : { chat_id: "hydration-chat", event: "message", + projection_id: `raw-record-${position}`, text: position % 2 ? "same" : "other" }); + const fragment = (start: number) => history(records.slice(start, start + 5).filter((event): event is ThreadProjectionEvent => !!event), { + page: { history_generation: "generation", record_range: { turn: 0, start, end: start + 5 }, + before_cursor: `before-${start}`, has_more_before: true, truncated_oversized_turn: true }, + }); + const thread = new ThreadTranscript(); + for (let start = 1; start <= 23; start++) { + expect(thread.accept(fragment(start), thread.begin(start === 1 ? "initial" : "latest"))).toBe(true); + } + const expected = records.slice(1, 28).filter((event): event is ThreadProjectionEvent => !!event); + expect(thread.messages.map((row) => row.content)).toEqual(expected.map((event) => "text" in event ? event.text : "")); + const stored = thread.save().fragments.flatMap((page) => page.events.map((event) => event.projection_id)); + expect(stored).toEqual(expected.map((event) => event.projection_id)); + expect(new Set(stored).size).toBe(stored.length); + }); + + it.each([{ position: 1, gap: false }, { position: 2, gap: false }, { position: 2, gap: true }])("withdraws recovered answers from an open fragment (%j)", ({ position, gap }) => { + const thread = new ThreadTranscript(); + const partial: ThreadProjectionEvent = { ...at("recovery", position + 1), event: "stream_end", stream_id: "old-answer", text: "Partial answer" }; + const reasoning: ThreadProjectionEvent = { ...at("recovery", 4), event: "reasoning_end", text: "Retained reasoning" }; + const tool: ThreadProjectionEvent = { ...at("recovery", 5), event: "message", kind: "tool_hint", text: "read_file()" }; + // Telemetry accounts for the raw positions that have no projected body event. + const active = history([partial, reasoning, tool], { active_turn_id: "recovery", + page: { history_generation: "generation", record_range: { turn: 0, start: 1, end: 4001 }, + before_cursor: "before-1", has_more_before: true, truncated_oversized_turn: true } }); + const recovered = history([...(gap ? [] : [reasoning, tool]), + { chat_id: "hydration-chat", turn_id: "recovery", event: "message", text: "Correct final answer", projection_id: "canonical-recovery" }, + { ...at("recovery", gap ? 12000 : 4002), event: "turn_end" }, + ], { completed_turn_ids: ["recovery"], + page: { history_generation: "generation", record_range: { turn: 0, start: gap ? 6002 : 2, end: gap ? 10002 : 4002 }, recovered_answers: true, + before_cursor: gap ? "before-6002" : "before-2", has_more_before: true, truncated_oversized_turn: true } }); + expect(thread.accept(active, thread.begin("initial"))).toBe(true); + if (gap) receive(thread, { ...at("recovery", 9000), event: "delta", stream_id: "unpersisted", text: "Unconfirmed live tail" }); + let restored = new ThreadTranscript([], thread.save()); + expect(restored.accept(recovered, restored.begin("latest"))).toBe(true); + if (gap) { + restored = new ThreadTranscript([], restored.save()); + expect(restored.accept(history([], { + page: { history_generation: "generation", record_range: { turn: 0, start: 4001, end: 6002 }, before_cursor: "before-4001", has_more_before: true }, + }), restored.begin("older"))).toBe(true); + } + const reopened = new ThreadTranscript(); + expect(reopened.accept(recovered, reopened.begin("initial"))).toBe(true); + const answers = (owner: ThreadTranscript) => owner.messages.filter((row) => row.role === "assistant" && row.kind !== "trace" && row.content).map((row) => row.content); + const expected = [...(gap ? ["Unconfirmed live tail"] : []), ...answers(reopened)]; + expect(answers(reopened)).toEqual(["Correct final answer"]); + expect(answers(restored)).toEqual(expected); + expect(restored.messages.filter((row) => row.reasoning).map((row) => row.reasoning)).toEqual(["Retained reasoning"]); + expect(restored.messages.filter((row) => row.kind === "trace").map((row) => row.content)).toEqual(["read_file()"]); + expect(restored.accept(history([input("recovery", "Question")], { + page: { history_generation: "generation", record_range: { turn: 0, start: 0, end: 2 }, before_cursor: null, has_more_before: false }, + }), restored.begin("older"))).toBe(true); + expect(answers(restored)).toEqual(expected); + expect(restored.messages.filter((row) => row.role === "user").map((row) => row.content)).toEqual(["Question"]); + }); + + it("reprojects adjacent pages of one turn without losing a cumulative answer", () => { + const events: ThreadProjectionEvent[] = [ + input("long-turn", "Question"), + { ...at("long-turn", 2), event: "reasoning_end", text: "Earlier reasoning" }, + { ...at("long-turn", 3), event: "stream_end", stream_id: "long-answer", text: "First", resuming: true, merge_next: true }, + { ...at("long-turn", 4), event: "message", kind: "progress", text: "tool()" }, + { ...at("long-turn", 5), event: "stream_end", stream_id: "long-answer", text: "First second" }, + { ...at("long-turn", 6), event: "turn_end" }, + ]; + const complete = new ThreadTranscript(); + expect(complete.accept(history(events, { completed_turn_ids: ["long-turn"] }), complete.begin("initial"))).toBe(true); + + const thread = new ThreadTranscript(); + expect(thread.accept(history(events.slice(3), { + completed_turn_ids: ["long-turn"], + page: { before_cursor: "inside-turn", has_more_before: true, truncated_oversized_turn: true, + record_range: { turn: 0, start: 3, end: 6 } }, + }), thread.begin("initial"))).toBe(true); + expect(thread.accept(history(events.slice(0, 3), { + page: { before_cursor: null, has_more_before: false, truncated_oversized_turn: true, + record_range: { turn: 0, start: 0, end: 3 } }, + }), thread.begin("older"))).toBe(true); + + const visible = (value: ThreadTranscript) => value.messages.map((row) => ({ + role: row.role, kind: row.kind, content: row.content, reasoning: row.reasoning, traces: row.traces, + })); + expect(visible(thread)).toEqual(visible(complete)); + expect(thread.paging.hasMoreBefore).toBe(false); + }); + + it("keeps tool activity in order when an older fragment meets a live answer", () => { + const thread = new ThreadTranscript(); + const question = input("long-tool", "Question"); + const a: ThreadProjectionEvent = { ...at("long-tool", 2), event: "delta", stream_id: "wire", text: "A" }; + const b: ThreadProjectionEvent = { ...at("long-tool", 3), event: "delta", stream_id: "wire", text: "B" }; + const tool: ThreadProjectionEvent = { ...at("long-tool", 4), event: "message", kind: "progress", text: "tool()" }; + const c: ThreadProjectionEvent = { ...at("long-tool", 5), event: "delta", stream_id: "wire", text: "C" }; + expect(thread.accept(history([b], { active_turn_id: "long-tool", has_pending_tool_calls: true, + page: { before_cursor: "inside", has_more_before: true, truncated_oversized_turn: true, + record_range: { turn: 0, start: 2, end: 3 } } }), thread.begin("initial"))).toBe(true); + const read = thread.begin("older"); + receive(thread, tool, c); + expect(thread.accept(history([question, a], { + page: { before_cursor: null, has_more_before: false, truncated_oversized_turn: true, + record_range: { turn: 0, start: 0, end: 2 } } }), read)).toBe(true); + const expected = new ThreadTranscript(); + expect(expected.accept(history([question, a, b, tool, c], { active_turn_id: "long-tool", has_pending_tool_calls: true }), + expected.begin("initial"))).toBe(true); + const visible = (value: ThreadTranscript) => value.messages.map((row) => ({ + role: row.role, kind: row.kind, content: row.content, reasoning: row.reasoning, traces: row.traces, + })); + expect(visible(thread)).toEqual(visible(expected)); + receive(thread, { ...at("long-tool", 6), event: "delta", stream_id: "wire", text: "D" }); + expect(thread.messages.at(-1)?.content).toBe("CD"); + }); + + it("prunes only exactly persisted live records through repeated overlapping latest reads", () => { + const thread = new ThreadTranscript(); + const delta = (seq: number): ThreadProjectionEvent => ({ + ...at("journal", seq), event: "delta", stream_id: "wire", text: String(seq), + }); + const fragment = (end: number) => history(Array.from({ length: end - 1 }, (_, index) => delta(index + 2)), { + active_turn_id: "journal", + page: { history_generation: "generation", record_range: { turn: 0, start: 1, end }, + before_cursor: "before-1", has_more_before: true, truncated_oversized_turn: true }, + }); + expect(thread.accept(fragment(2), thread.begin("initial"))).toBe(true); + receive(thread, delta(3)); + for (let seq = 3; seq <= 12; seq++) { + receive(thread, delta(seq + 1)); + expect(thread.accept(fragment(seq), thread.begin("latest"))).toBe(true); + expect(thread.save().live.map(({ event }) => event.turn_seq)).toEqual([seq + 1]); + expect(thread.messages.at(-1)?.content).toBe(Array.from({ length: seq }, (_, index) => String(index + 2)).join("")); + } + }); + + it("can project and restore temporary live output without retaining a raw journal", () => { + const thread = new ThreadTranscript([], undefined, { recordLiveContributions: false }); + for (let seq = 1; seq <= 200; seq++) { + receive(thread, { ...at("temporary", seq), event: "delta", stream_id: "wire", text: "x" }); + } + expect(thread.messages.at(-1)?.content).toBe("x".repeat(200)); + expect(thread.save().live).toHaveLength(0); + const restored = new ThreadTranscript([], thread.save(), { recordLiveContributions: false }); + receive(restored, { ...at("temporary", 201), event: "delta", stream_id: "wire", text: "y" }); + expect(restored.messages.at(-1)?.content).toBe(`${"x".repeat(200)}y`); + expect(restored.save().live).toHaveLength(0); + }); + + it("retires live chunks after ordinary completed turns persist cumulative end snapshots without receipts", () => { + const thread = new ThreadTranscript(); + const persisted: ThreadProjectionEvent[] = []; + const completed: string[] = []; + for (let index = 0; index < 6; index++) { + const turn = `ordinary-${index}`; + const stream_id = `ordinary-wire-${index}`; + const question = input(turn, `Question ${index}`); + const a: ThreadProjectionEvent = { ...at(turn, 2), event: "delta", stream_id, text: "First " }; + const b: ThreadProjectionEvent = { ...at(turn, 3), event: "delta", stream_id, text: "second" }; + const end: ThreadProjectionEvent = { ...at(turn, 4), event: "stream_end", stream_id }; + const done: ThreadProjectionEvent = { ...at(turn, 5), event: "turn_end" }; + const read = thread.begin(index ? "latest" : "initial"); + receive(thread, question, a, b, end, done); + persisted.push(question, { ...end, text: "First second" }, done); + completed.push(turn); + expect(thread.accept(history(persisted, { completed_turn_ids: [...completed] }), read)).toBe(true); + expect(thread.save().live).toHaveLength(0); + } + expect(thread.messages.filter((row) => row.role === "assistant").map((row) => row.content)) + .toEqual(Array(6).fill("First second")); + }); + + it("retires covered deltas across successive cumulative stream snapshots", () => { + const thread = new ThreadTranscript(); + const question = input("ordinary-resume", "Question"); + const a: ThreadProjectionEvent = { ...at("ordinary-resume", 2), event: "delta", stream_id: "wire", text: "A" }; + const first: ThreadProjectionEvent = { ...at("ordinary-resume", 3), event: "stream_end", stream_id: "wire", + text_from_seq: 2, resuming: true, merge_next: true }; + receive(thread, question, a, first); + expect(thread.accept(history([question, { ...first, text: "A" }]), thread.begin("initial"))).toBe(true); + expect(thread.save().live).toHaveLength(0); + const b: ThreadProjectionEvent = { ...at("ordinary-resume", 4), event: "delta", stream_id: "wire", text: "B" }; + const last: ThreadProjectionEvent = { ...at("ordinary-resume", 5), event: "stream_end", stream_id: "wire", text_from_seq: 2 }; + const done: ThreadProjectionEvent = { ...at("ordinary-resume", 6), event: "turn_end" }; + receive(thread, b, last, done); + expect(thread.accept(history([question, { ...first, text: "A" }, { ...last, text: "AB" }, done], { + completed_turn_ids: ["ordinary-resume"], + }), thread.begin("latest"))).toBe(true); + expect(thread.messages.at(-1)?.content).toBe("AB"); + expect(thread.save().live).toHaveLength(0); + }); + + it("retires completed legacy text without swallowing an intervening tool", () => { + const thread = new ThreadTranscript(); + const question = input("ordinary-tool", "Question"); + const a: ThreadProjectionEvent = { ...at("ordinary-tool", 2), event: "delta", stream_id: "wire", text: "A" }; + const tool: ThreadProjectionEvent = { ...at("ordinary-tool", 3), event: "message", kind: "progress", text: "tool()" }; + const b: ThreadProjectionEvent = { ...at("ordinary-tool", 4), event: "delta", stream_id: "wire", text: "B" }; + const end: ThreadProjectionEvent = { ...at("ordinary-tool", 5), event: "stream_end", stream_id: "wire" }; + const done: ThreadProjectionEvent = { ...at("ordinary-tool", 6), event: "turn_end" }; + const read = thread.begin("initial"); + receive(thread, question, a, tool, b, end, done); + expect(thread.accept(history([question, tool, { ...end, text: "AB" }, done], { + completed_turn_ids: ["ordinary-tool"], + }), read)).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "tool()", "AB"]); + expect(thread.save().live).toEqual([]); + }); + + it("uses a partial snapshot's coverage without fetching its prefix or comparing signed text", () => { + const thread = new ThreadTranscript(); + const turn = "explicit-coverage"; + receive(thread, + input(turn, "Question"), + { ...at(turn, 2), event: "reasoning_delta", stream_id: "wire", text: "Unpersisted reasoning" }, + { ...at(turn, 3), event: "delta", stream_id: "wire", text: "![image](local.png)" }, + { ...at(turn, 4), event: "message", kind: "progress", text: "Unpersisted tool" }, + { ...at(turn, 5), event: "delta", stream_id: "other", text: "Other stream" }, + ); + const read = thread.begin("initial"); + receive(thread, { ...at(turn, 7), event: "delta", stream_id: "wire", text: " fresh tail" }); + expect(thread.accept(history([ + { ...at(turn, 6), event: "stream_end", stream_id: "wire", text_from_seq: 3, + text: "![image](/api/media/signed)", resuming: true, merge_next: true }, + ], { active_turn_id: turn, page: { record_range: { turn: 0, start: 5, end: 6 }, + truncated_oversized_turn: true, has_more_before: true, before_cursor: "older" } }), read)).toBe(true); + expect(thread.messages.filter((row) => row.streamId === "wire").map((row) => row.content)) + .toEqual(["![image](/api/media/signed) fresh tail"]); + expect(thread.messages.some((row) => row.reasoning === "Unpersisted reasoning")).toBe(true); + expect(thread.messages.some((row) => row.content === "Unpersisted tool")).toBe(true); + expect(thread.messages.some((row) => row.content === "Other stream")).toBe(true); + expect(thread.save().live.map(({ event }) => event.turn_seq)).toEqual([1, 2, 4, 5, 7]); + expect(thread.hasPendingFragmentGap).toBe(false); + expect(thread.paging).toMatchObject({ beforeCursor: "older", hasMoreBefore: true }); + }); + + it("retires live deltas covered by persisted stream snapshots", () => { + const thread = new ThreadTranscript(); + const events: ThreadProjectionEvent[] = [input("journal-snapshots", "Question")]; + const fragment = () => history(events, { + active_turn_id: "journal-snapshots", + page: { history_generation: "generation", record_range: { turn: 1, start: 0, end: events.length }, + before_cursor: "before-turn", has_more_before: true, truncated_oversized_turn: true }, + }); + expect(thread.accept(fragment(), thread.begin("initial"))).toBe(true); + for (let index = 0; index < 8; index++) { + const stream_id = `wire-${index}`; + const text = `piece-${index}`; + const delta: ThreadProjectionEvent = { ...at("journal-snapshots", index * 2 + 2), event: "delta", stream_id, text }; + const end: ThreadProjectionEvent = { ...at("journal-snapshots", index * 2 + 3), event: "stream_end", stream_id, + text_from_seq: delta.turn_seq }; + receive(thread, delta, end); + events.push({ ...end, text }); + expect(thread.accept(fragment(), thread.begin("latest"))).toBe(true); + expect(thread.save().live).toHaveLength(0); + } + expect(thread.messages.filter((row) => row.role === "assistant").map((row) => row.content)) + .toEqual(Array.from({ length: 8 }, (_, index) => `piece-${index}`)); + }); + + it("retains live records covered only by an incomplete cumulative snapshot", () => { + const thread = new ThreadTranscript(); + const question = input("journal-hole", "Question"); + const c: ThreadProjectionEvent = { ...at("journal-hole", 3), event: "reasoning_delta", text: "C" }; + const end: ThreadProjectionEvent = { ...at("journal-hole", 4), event: "reasoning_end", text: "Earlier C" }; + const e: ThreadProjectionEvent = { ...at("journal-hole", 5), event: "delta", stream_id: "wire", text: "E" }; + const fragment = (events: ThreadProjectionEvent[], endPosition: number) => history(events, { + active_turn_id: "journal-hole", + page: { history_generation: "generation", record_range: { turn: 1, start: 0, end: endPosition }, + before_cursor: "before-turn", has_more_before: true, truncated_oversized_turn: true }, + }); + expect(thread.accept(fragment([question], 1), thread.begin("initial"))).toBe(true); + receive(thread, c, e); + expect(thread.accept(fragment([question, end], 2), thread.begin("latest"))).toBe(true); + expect(thread.messages.at(-1)).toMatchObject({ content: "E", reasoning: "C" }); + expect(thread.save().live.map(({ event }) => event.turn_seq)).toEqual([3, 5]); + const restored = new ThreadTranscript([], thread.save()); + expect(restored.accept(fragment([question, end], 2), restored.begin("latest"))).toBe(true); + expect(restored.messages.at(-1)).toMatchObject({ content: "E", reasoning: "C" }); + expect(restored.save().live.map(({ event }) => event.turn_seq)).toEqual([3, 5]); + }); + + it("reconciles partially persisted live batches after restoring a fragment cache", () => { + const thread = new ThreadTranscript(); + const b: ThreadProjectionEvent = { ...at("long-cache", 3), event: "delta", stream_id: "wire", text: "B" }; + const c: ThreadProjectionEvent = { ...at("long-cache", 4), event: "delta", stream_id: "wire", text: "C" }; + const d: ThreadProjectionEvent = { ...at("long-cache", 5), event: "delta", stream_id: "wire", text: "D" }; + const fragment = (events: ThreadProjectionEvent[], start: number, end: number, before: string | null) => history(events, { + page: { before_cursor: before, has_more_before: before !== null, truncated_oversized_turn: true, + record_range: { turn: 0, start, end } }, + }); + expect(thread.accept(fragment([b], 2, 3, "inside"), thread.begin("initial"))).toBe(true); + thread.project({ ...d, text: "CD", projection_receipts: [{ turn_id: "long-cache", ranges: [[4, 5]] }] }, { + createId: () => "live-batch", now: NOW, startSeq: 4, contributions: [c, d], + }); + const restored = new ThreadTranscript([], thread.save()); + expect(restored.accept(fragment([b, c], 2, 4, "inside"), restored.begin("latest"))).toBe(true); + expect(restored.messages.map((row) => row.content)).toEqual(["BCD"]); + expect(restored.accept(fragment([ + input("long-cache", "Question"), + { ...at("long-cache", 2), event: "delta", stream_id: "wire", text: "A" }, + ], 0, 2, null), restored.begin("older"))).toBe(true); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "ABCD"]); + receive(restored, { ...at("long-cache", 6), event: "delta", stream_id: "wire", text: "E" }); + expect(restored.messages.at(-1)?.content).toBe("ABCDE"); + }); + + it.each(["history", "live-user", "live-session-input"] as const)("does not join fragments from a deleted and recreated session (%s)", (delivery) => { + const fragment = (generation: string, events: ThreadProjectionEvent[], start: number, end: number, before: string | null) => history(events, { + page: { history_generation: generation, before_cursor: before, has_more_before: before !== null, + truncated_oversized_turn: true, record_range: { turn: 0, start, end } }, + }); + const thread = new ThreadTranscript(); + expect(thread.accept(fragment("old", [ + { ...at("same-turn", 3), event: "message", text: "Old tail" }, + { ...at("same-turn", 4), event: "turn_end" }, + ], 2, 4, "old-prefix"), thread.begin("initial"))).toBe(true); + const question: ThreadProjectionEvent = { ...input("same-turn", "Old question"), input_id: "user:old", + ...(delivery === "live-session-input" ? { input_id: "session-message:old", provenance: { session_message: { + message_id: "old", session: { id: "handle_0123456789abcdef0123456789abcdef", name: "mira" }, + } } } : {}) }; + if (delivery !== "history") receive(thread, { ...question, turn_seq: undefined }); + expect(thread.accept(fragment("old", [question, + { ...at("same-turn", 2), event: "message", text: "Old middle" }], 0, 2, null), thread.begin("older"))).toBe(true); + expect(thread.accept(fragment("new", [ + { ...at("same-turn", 3), event: "message", text: "New tail" }, + { ...at("same-turn", 4), event: "turn_end" }, + ], 2, 4, "new-prefix"), thread.begin("latest"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["New tail"]); + expect(thread.accept(fragment("new", [input("same-turn", "New question"), + { ...at("same-turn", 2), event: "message", text: "New middle" }], 0, 2, null), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["New question", "New middle", "New tail"]); + if (delivery !== "history") { + receive(thread, { ...question, turn_id: "pending-turn", turn_seq: undefined, input_id: "pending-input", text: "Pending question", + ...(question.provenance ? { provenance: { session_message: { ...question.provenance.session_message!, message_id: "pending-message" } } } : {}) }); + expect(thread.accept(fragment("third", [input("third-turn", "Replacement")], 0, 1, null), thread.begin("latest"))).toBe(false); + expect(thread.messages.at(-1)?.content).toBe("Pending question"); + } + }); + it("does not certify earlier reasoning from a truncated snapshot with an unknown left boundary", () => { const thread = new ThreadTranscript(); expect(thread.accept(history([ @@ -683,6 +1235,75 @@ describe("ThreadTranscript admission", () => { expect(thread.paging.truncated).toBe(true); }); + it("restores a fragmented turn when the gateway signs a live markdown image", () => { + const thread = new ThreadTranscript(); + const turn = "signed-image-fragment"; + const question = input(turn, "Question"); + const request: ThreadProjectionEvent = { ...at(turn, 2), event: "model_request", request_id: "request", + run_id: "run", sequence: 1, phase: "started", projection_id: "request" }; + const answer: ThreadProjectionEvent = { ...at(turn, 4), event: "stream_end", stream_id: "wire", + text: "![image](/api/media/signed.png)", projection_id: "answer" }; + const done: ThreadProjectionEvent = { ...at(turn, 5), event: "turn_end", projection_id: "done" }; + const fragment = (events: ThreadProjectionEvent[], start: number, end: number, before: string | null) => history(events, { + completed_turn_ids: end === 4 ? [turn] : [], + page: { history_generation: "generation", record_range: { turn: 0, start, end }, + before_cursor: before, has_more_before: before !== null, truncated_oversized_turn: true }, + }); + expect(thread.accept(fragment([request], 1, 2, "inside"), thread.begin("initial"))).toBe(true); + receive(thread, { ...at(turn, 3), event: "delta", stream_id: "wire", text: "![image](images/photo.png)" }); + expect(thread.accept(fragment([request, answer, done], 1, 4, "inside"), thread.begin("latest"))).toBe(true); + expect(thread.accept(fragment([question], 0, 1, null), thread.begin("older"))).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "![image](/api/media/signed.png)"]); + expect(thread.paging.hasMoreBefore).toBe(false); + }); + + it("uses the signed canonical image and does not duplicate a delayed live suffix", () => { + const thread = new ThreadTranscript(); + const read = thread.begin("initial"); + const question = input("turn-completed-conflict", "Question"); + const live: ThreadProjectionEvent = { ...at("turn-completed-conflict", 2), event: "delta", stream_id: "wire", + text: "![image](images/photo.png)" }; + receive(thread, question, live); + // The completed HTTP read can precede the final live chunk. The gateway + // signs the image path for display. + const complete = history([ + question, + { ...at("turn-completed-conflict", 4), event: "stream_end", stream_id: "wire", + text: "![image](/api/media/signed.png) tail" }, + { ...at("turn-completed-conflict", 5), event: "turn_end" }, + ], { completed_turn_ids: ["turn-completed-conflict"] }); + expect(thread.accept(complete, read)).toBe(true); + expect(thread.messages.map((row) => row.content)).toEqual(["Question", "![image](/api/media/signed.png) tail"]); + + const restored = new ThreadTranscript([], thread.save()); + receive(restored, { ...at("turn-completed-conflict", 3), event: "delta", stream_id: "wire", text: " tail" }); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "![image](/api/media/signed.png) tail"]); + expect(restored.accept(complete, restored.begin("latest"))).toBe(true); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "![image](/api/media/signed.png) tail"]); + }); + + it("does not duplicate a delayed local image chunk after the signed snapshot is installed", () => { + const thread = new ThreadTranscript(); + const question = input("turn-prefix-conflict", "Question"); + const first: ThreadProjectionEvent = { ...at("turn-prefix-conflict", 2), event: "delta", stream_id: "wire", text: "See " }; + const complete = history([ + question, + { ...at("turn-prefix-conflict", 4), event: "stream_end", stream_id: "wire", + text: "See ![image](/api/media/signed.png)" }, + { ...at("turn-prefix-conflict", 5), event: "turn_end" }, + ], { completed_turn_ids: ["turn-prefix-conflict"] }); + const read = thread.begin("initial"); + receive(thread, question, first); + expect(thread.accept(complete, read)).toBe(true); + + const restored = new ThreadTranscript([], thread.save()); + receive(restored, { ...at("turn-prefix-conflict", 3), event: "delta", stream_id: "wire", + text: "![image](images/photo.png)" }); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "See ![image](/api/media/signed.png)"]); + expect(restored.accept(complete, restored.begin("latest"))).toBe(true); + expect(restored.messages.map((row) => row.content)).toEqual(["Question", "See ![image](/api/media/signed.png)"]); + }); + it("can replace a fully represented received turn with a nontruncated explicit canonical completion", () => { const thread = new ThreadTranscript(); const read = thread.begin("initial"); diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsx index ccf85ca4f..e4e30f265 100644 --- a/webui/src/tests/thread-viewport.test.tsx +++ b/webui/src/tests/thread-viewport.test.tsx @@ -1802,6 +1802,98 @@ describe("ThreadViewport", () => { } }); + it.each(["sequence", "stream", "shared-stream", "missing"] as const)( + "handles a fragment prepend with %s identity without selecting the wrong answer", + (identity) => { + const turnId = "partial-turn"; + const answer = (id: string, content: string, turnSeq: number): UIMessage => ({ + id, role: "assistant", content, createdAt: turnSeq, turnId, turnPhase: "answer", turnSeq, + ...(identity === "stream" ? { streamId: `stream-${content}` } : {}), + ...(identity === "shared-stream" ? { streamId: "shared-stream" } : {}), + }); + const activity = (id: string, turnSeq: number): UIMessage => ({ + id, role: "tool", kind: "trace", content: "tool", traces: ["tool"], + createdAt: turnSeq, turnId, turnPhase: "activity", turnSeq, + }); + const tail = [answer("history-1", "tail one", 3), activity("history-2", 4), answer("history-3", "tail two", 5)]; + const { container, rerender } = render(); + const scroller = getScroller(container); + let prepended = false; + Object.defineProperties(scroller, { + scrollHeight: { configurable: true, get: () => prepended ? 2_580 : 2_400 }, + clientHeight: { configurable: true, value: 600 }, + scrollTop: { configurable: true, writable: true, value: 80 }, + }); + const originalRect = HTMLElement.prototype.getBoundingClientRect; + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) { + if (this === scroller) return DOMRect.fromRect({ width: 800, height: 600 }); + if (this.hasAttribute("data-thread-display-unit")) { + const top = this.textContent?.includes("tail one") ? (prepended ? 380 : 200) : 150; + return DOMRect.fromRect({ y: top - scroller.scrollTop, width: 800, height: 40 }); + } + return originalRect.call(this); + }); + const hitTest = stubElementsFromPoint(() => [ + screen.getByText("tail one").closest("[data-thread-display-unit]")!, + ]); + try { + act(() => dispatchUserScroll(scroller)); + prepended = true; + const replayedSequence = identity === "stream" || identity === "missing"; + rerender(); + // Without a matching source, do not jump to the earlier answer which reused its old id. + expect(scroller.scrollTop).toBe(identity === "missing" ? 80 : 260); + expect(screen.getByText("tail one").closest("[data-thread-display-unit]")! + .getBoundingClientRect().top).toBe(identity === "missing" ? 300 : 120); + } finally { + hitTest.restore(); + } + }, + ); + + it("keeps a unique answer anchored when live identity changes on replay", () => { + const live: UIMessage = { + id: "live-answer", role: "assistant", content: "same answer", createdAt: 1, + turnId: "live-turn", turnPhase: "answer", turnSeq: 2, + }; + const { container, rerender } = render(); + const scroller = getScroller(container); + let replayed = false; + Object.defineProperties(scroller, { + scrollHeight: { configurable: true, get: () => replayed ? 2_480 : 2_400 }, + clientHeight: { configurable: true, value: 600 }, + scrollTop: { configurable: true, writable: true, value: 80 }, + }); + const originalRect = HTMLElement.prototype.getBoundingClientRect; + vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) { + if (this === scroller) return DOMRect.fromRect({ width: 800, height: 600 }); + if (this.hasAttribute("data-thread-display-unit")) { + return DOMRect.fromRect({ y: (replayed ? 280 : 200) - scroller.scrollTop, width: 800, height: 40 }); + } + return originalRect.call(this); + }); + const hitTest = stubElementsFromPoint(() => [ + screen.getByText("same answer").closest("[data-thread-display-unit]")!, + ]); + try { + act(() => dispatchUserScroll(scroller)); + const answerNode = screen.getByText("same answer"); + replayed = true; + rerender(); + expect(screen.getByText("same answer")).toBe(answerNode); + expect(scroller.scrollTop).toBe(160); + expect(answerNode.closest("[data-thread-display-unit]")!.getBoundingClientRect().top).toBe(120); + } finally { + hitTest.restore(); + } + }); + it.each(["wheel", "touch", "keyboard"] as const)( "requests older history on %s intent when the initial page does not overflow", (input) => { diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 9ac6719cd..935a9104c 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -159,6 +159,31 @@ async function flushStreamFrame() { } describe("useNanobotStream", () => { + it.each([true, false])("keeps temporary and new persistent streams separate when the history key is absent (temporary=%s)", (temporary) => { + const fake = fakeClient(); + const cache = new ThreadMessageCache(() => temporary); + const options = { key: null, cache, temporary }; + const first = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], options), { wrapper: wrap(fake.client) }); + act(() => { + fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 1, text: "First " }); + }); + first.unmount(); + const snapshot = cache.get("checkpoint")!; + expect(snapshot.live).toHaveLength(temporary ? 0 : 1); + expect(snapshot.projection.messages[0].content).toBe("First "); + const restored = renderHook(() => useNanobotStream("checkpoint", EMPTY_MESSAGES, false, + undefined, undefined, [], options), { wrapper: wrap(fake.client) }); + act(() => { + fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 2, text: "First ", resuming: true, merge_next: true }); + fake.emit("checkpoint", { event: "delta", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 3, text: "last" }); + fake.emit("checkpoint", { event: "stream_end", chat_id: "checkpoint", turn_id: "turn", stream_id: "answer", turn_seq: 4, text: "First last" }); + }); + expect(restored.result.current.messages[0].content).toBe("First last"); + restored.unmount(); + if (temporary) expect(cache.get("checkpoint")!.live).toEqual([]); + }); + it("resumes a merge_next cached snapshot including reasoning queued before detach", () => { const fake = fakeClient(); const cache = new ThreadMessageCache(() => false); diff --git a/webui/src/tests/usePromptHistory.test.tsx b/webui/src/tests/usePromptHistory.test.tsx index c4a8612a7..923c090b4 100644 --- a/webui/src/tests/usePromptHistory.test.tsx +++ b/webui/src/tests/usePromptHistory.test.tsx @@ -7,6 +7,8 @@ import { NanobotClient } from "@/lib/nanobot-client"; import { ClientProvider } from "@/providers/ClientProvider"; import type { UIMessage, WebuiThreadPersistedPayload } from "@/lib/types"; import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport"; +import { projectThreadEvents } from "@/lib/thread-event-projection"; +import { projectWebuiThreadMessages } from "@/lib/thread-display-projection"; vi.mock("@/lib/api", async (original) => ({ ...await original(), fetchPromptIndex: vi.fn(), fetchWebuiThread: vi.fn() })); const index = Array.from({ length: 2000 }, (_, index) => ({ id: `u${index}`, preview: `question ${index}`, @@ -55,6 +57,73 @@ it("loads the complete index without bodies, reads bounded windows and leaves li expect(latest).toHaveLength(1); }); +it("reprojects adjacent pages of a long turn when navigating forward", async () => { + const events = [ + { event: "user_message" as const, chat_id: "a", projection_id: "u10", turn_id: "long", turn_seq: 1, text: "question", starts_turn: true }, + { event: "stream_end" as const, chat_id: "a", projection_id: "answer-1", turn_id: "long", turn_seq: 2, stream_id: "wire", text: "First", resuming: true, merge_next: true }, + { event: "message" as const, chat_id: "a", projection_id: "tool", turn_id: "long", turn_seq: 3, kind: "progress" as const, text: "tool()" }, + { event: "stream_end" as const, chat_id: "a", projection_id: "answer-2", turn_id: "long", turn_seq: 4, stream_id: "wire", text: "First second" }, + { event: "turn_end" as const, chat_id: "a", projection_id: "end", turn_id: "long", turn_seq: 5 }, + ]; + vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [{ ...index[10], id: "u10", turnId: "long" }] }); + vi.mocked(api.fetchWebuiThread).mockImplementation(async (_token, _key, options) => { + if (typeof options === "string") throw new Error("expected page options"); + const newer = options?.after === "next"; + return { schemaVersion: 3, projection: "events", events: newer ? events.slice(2) : events.slice(0, 2), + page: { before_cursor: newer ? "next" : null, after_cursor: newer ? null : "next", + has_more_before: newer, has_more_after: !newer, truncated_oversized_turn: true, + record_range: { turn: 0, start: newer ? 2 : 0, end: newer ? 5 : 2 } } }; + }); + const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() }); + await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u10")); + await act(async () => result.current.jump("u10")); + await act(async () => result.current.newer()); + const visible = (rows: UIMessage[]) => rows.map((row) => ({ + role: row.role, kind: row.kind, content: row.content, reasoning: row.reasoning, traces: row.traces, + })); + expect(visible(result.current.window!.messages)).toEqual(visible(projectWebuiThreadMessages(projectThreadEvents(events)))); + expect(result.current.window?.messages.filter((row) => row.role === "user")).toHaveLength(1); +}); + +it("continues through telemetry-only fragments until another message is visible", async () => { + vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [{ ...index[10], id: "u10", turnId: "long" }] }); + vi.mocked(api.fetchWebuiThread).mockImplementation(async (_token, _key, options) => { + if (typeof options === "string") throw new Error("expected page options"); + const part = Number(options?.after === "10" ? 0 : options?.after); + const events = part === 0 + ? [{ event: "user_message" as const, chat_id: "a", projection_id: "u10", turn_id: "long", turn_seq: 1, text: "question", starts_turn: true }] + : part === 4 + ? [{ event: "message" as const, chat_id: "a", projection_id: "answer", turn_id: "long", turn_seq: 5, text: "Visible answer" }] + : [{ event: "model_request" as const, chat_id: "a", projection_id: `request-${part}`, turn_id: "long", turn_seq: part + 1, + request_id: `r${part}`, run_id: "run", sequence: part, phase: "started" as const }]; + return { schemaVersion: 3, projection: "events", events, + page: { before_cursor: part ? String(part) : null, after_cursor: part < 4 ? String(part + 1) : null, + has_more_before: part > 0, has_more_after: part < 4, truncated_oversized_turn: true, + record_range: { turn: 0, start: part, end: part + 1 } } }; + }); + const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() }); + await waitFor(() => expect(result.current.prompts[0]?.id).toBe("u10")); + await act(async () => result.current.jump("u10")); + await act(async () => result.current.newer()); + await act(async () => result.current.newer()); + await act(async () => result.current.newer()); + await waitFor(() => expect(result.current.window?.messages.map((row) => row.content)).toContain("Visible answer")); + expect(api.fetchWebuiThread).toHaveBeenCalledTimes(5); +}); + +it("does not mix navigation pages from a replaced session", async () => { + vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(10), + page: { ...page(10).page, history_generation: "old" } }); + const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() }); + await waitFor(() => expect(result.current.prompts).toHaveLength(2000)); + await act(async () => result.current.jump("u10")); + vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce({ ...page(11), + page: { ...page(11).page, history_generation: "new" } }); + await act(async () => result.current.newer()); + expect(result.current.error).toBe("History changed; select the message again"); + expect(result.current.window?.messages.map((message) => message.content)).toEqual(["question 10", "answer"]); +}); + it.each(["older", "newer"] as const)("keeps one pending %s page when boundary inputs arrive before the next render", async (operation) => { const { result } = renderHook(() => usePromptHistory("a", 1, latest), { wrapper: wrapper() }); await waitFor(() => expect(result.current.prompts).toHaveLength(2000)); diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsx index eaaaec508..938f80664 100644 --- a/webui/src/tests/useReconnectRuns.test.tsx +++ b/webui/src/tests/useReconnectRuns.test.tsx @@ -80,6 +80,334 @@ afterEach(() => { }); describe("durable run recovery", () => { + it("settles an unmounted run without losing buffered or late output absent from its completed latest fragment", async () => { + const chatId = "inactive"; + const turnId = "turn-old"; + const body: WebuiThreadPersistedPayload = { + schemaVersion: 3, sessionKey: `websocket:${chatId}`, projection: "events", + has_pending_tool_calls: false, active_turn_id: null, completed_turn_ids: [turnId], + page: { history_generation: "generation", record_range: { turn: 0, start: 5, end: 8 }, + before_cursor: "before-5", has_more_before: true, truncated_oversized_turn: true }, + events: [ + { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 7, text: "Later persisted answer" }, + { event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 8 }, + ], + }; + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body))); + const { client, sockets, running, reopen, close } = setup(); + const early = { event: "delta", chat_id: chatId, turn_id: turnId, turn_seq: 2, stream_id: "wire", text: "Unpersisted earlier output" }; + const late = { event: "delta", chat_id: chatId, turn_id: turnId, turn_seq: 3, stream_id: "wire", text: "Late output" }; + const activity = { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 4, kind: "tool_hint", text: "search(query)" }; + running(); + sockets[0].receive(early); + sockets[0].receive({ event: "recovery_state", chat_id: chatId, turn_id: turnId, + status: "resuming", recovery_id: "buffered-recovery", attempts: 0 }); + + await reopen(); + + expect(client.getRunState(chatId)).toMatchObject({ active: false, unsettled: false, startedAt: null }); + expect(client.isRunCompleted(chatId, turnId)).toBe(true); + expect(webuiThreadCache.get(`websocket:${chatId}`)).toEqual(body); + act(() => { + sockets.at(-1)!.receive(late); + sockets.at(-1)!.receive(activity); + running(chatId, turnId, 999); + sockets.at(-1)!.receive({ event: "recovery_state", chat_id: chatId, turn_id: turnId, + status: "resuming", recovery_id: "r1", attempts: 0 }); + client.restorePendingRun(chatId, client.getRunGeneration(chatId), turnId); + }); + expect(client.getRunState(chatId)).toMatchObject({ active: false, unsettled: false, startedAt: null }); + const replay = vi.fn(); + client.onTranscript(chatId, replay); + expect(replay).toHaveBeenCalledWith(early); + expect(replay).toHaveBeenCalledWith(late); + expect(replay).toHaveBeenCalledWith(activity); + expect(replay).not.toHaveBeenCalledWith(expect.objectContaining({ event: "goal_status", turn_id: turnId, status: "running" })); + expect(replay).not.toHaveBeenCalledWith(expect.objectContaining({ event: "recovery_state", status: "resuming" })); + close(); + }); + + it("projects an unpersisted buffered tool event when the user returns to the recovered thread", async () => { + const chatId = "inactive"; + const turnId = "turn-old"; + const body: WebuiThreadPersistedPayload = { + schemaVersion: 3, sessionKey: `websocket:${chatId}`, projection: "events", + has_pending_tool_calls: false, active_turn_id: null, completed_turn_ids: [turnId], + page: { history_generation: "generation", record_range: { turn: 0, start: 5, end: 8 }, + before_cursor: "before-5", has_more_before: true, truncated_oversized_turn: true }, + events: [ + { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 7, text: "Persisted answer", projection_id: "answer" }, + { event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 8, projection_id: "end" }, + ], + }; + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response(body))); + const { client, sockets, running, reopen, close } = setup(); + running(); + sockets[0].receive({ event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 2, + kind: "tool_hint", text: "search(unpersisted)" }); + await reopen(); + expect(client.getRunState(chatId).active).toBe(false); + + const wrapper = ({ children }: { children: ReactNode }) => {children}; + const mounted = renderHook(() => useNanobotStream(chatId, [], false, undefined, undefined, [], { key: `websocket:${chatId}` }), { wrapper }); + await act(async () => {}); + expect(mounted.result.current.messages.map((message) => message.content)).toContain("search(unpersisted)"); + expect(mounted.result.current.messages.map((message) => message.content)).toContain("Persisted answer"); + expect(mounted.result.current.isStreaming).toBe(false); + act(() => sockets.at(-1)!.receive({ event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 3, + kind: "tool_hint", text: "search(late)" })); + expect(mounted.result.current.messages.map((message) => message.content)).toContain("search(late)"); + expect(client.getRunState(chatId).active).toBe(false); + mounted.unmount(); + close(); + }); + + it("settles only the explicitly completed T when U starts during a fragment read", async () => { + let finishRead!: (value: Response) => void; + vi.stubGlobal("fetch", vi.fn(() => new Promise((resolve) => { finishRead = resolve; }))); + const { client, sockets, running, reopen, close } = setup(); + const chatId = "inactive"; + const earlyT = { event: "delta", chat_id: chatId, turn_id: "turn-old", turn_seq: 2, stream_id: "T", text: "T buffered" }; + const frameU = { event: "delta", chat_id: chatId, turn_id: "turn-new", turn_seq: 2, stream_id: "U", text: "U buffered" }; + const lateT = { event: "delta", chat_id: chatId, turn_id: "turn-old", turn_seq: 3, stream_id: "T", text: "T late" }; + running(); + sockets[0].receive(earlyT); + await reopen(); + act(() => { + running(chatId, "turn-new", 456); + sockets.at(-1)!.receive(frameU); + }); + const body: WebuiThreadPersistedPayload = { + schemaVersion: 3, sessionKey: `websocket:${chatId}`, projection: "events", + has_pending_tool_calls: false, active_turn_id: null, completed_turn_ids: ["turn-old"], + page: { history_generation: "generation", record_range: { turn: 0, start: 5, end: 8 }, + before_cursor: "before-5", has_more_before: true, truncated_oversized_turn: true }, + events: [{ event: "turn_end", chat_id: chatId, turn_id: "turn-old", turn_seq: 8 }], + }; + await act(async () => { finishRead(response(body)); }); + expect(client.isRunCompleted(chatId, "turn-old")).toBe(true); + expect(client.getRunState(chatId)).toMatchObject({ active: true, unsettled: true, latestTurnId: "turn-new", startedAt: 456 }); + expect(webuiThreadCache.get(`websocket:${chatId}`)).toBeUndefined(); + const generationU = client.getRunGeneration(chatId); + act(() => { + sockets.at(-1)!.receive(lateT); + running(chatId, "turn-old", 999); + sockets.at(-1)!.receive({ event: "recovery_state", chat_id: chatId, turn_id: "turn-old", + status: "resuming", recovery_id: "r1", attempts: 0 }); + sockets.at(-1)!.receive({ event: "user_message", chat_id: chatId, turn_id: "guidance", + text: "A delayed input", starts_turn: false, active_turn_id: "turn-old", started_at: 123 }); + }); + expect(client.getRunState(chatId)).toMatchObject({ active: true, unsettled: true, latestTurnId: "turn-new", startedAt: 456, generation: generationU }); + const replay = vi.fn(); + client.onTranscript(chatId, replay); + expect(replay).toHaveBeenCalledWith(earlyT); + expect(replay).toHaveBeenCalledWith(frameU); + expect(replay).toHaveBeenCalledWith(lateT); + act(() => sockets.at(-1)!.receive({ event: "turn_end", chat_id: chatId, turn_id: "turn-new" })); + expect(client.getRunState(chatId)).toMatchObject({ active: false, unsettled: false, latestTurnId: "turn-new" }); + close(); + }); + + it("settles a mounted run after accepting a published reconnect fragment without a gap", async () => { + const chatId = "inactive"; + const turnId = "turn-old"; + const initial: WebuiThreadPersistedPayload = { + schemaVersion: 3, sessionKey: `websocket:${chatId}`, projection: "events", + has_pending_tool_calls: true, active_turn_id: turnId, completed_turn_ids: [], + page: { history_generation: "generation", record_range: { turn: 0, start: 1, end: 3 }, + before_cursor: "before-1", has_more_before: true, truncated_oversized_turn: true }, + events: [{ event: "delta", chat_id: chatId, turn_id: turnId, turn_seq: 2, stream_id: "wire", text: "Before" }], + }; + const latest: WebuiThreadPersistedPayload = { + ...initial, has_pending_tool_calls: false, active_turn_id: null, completed_turn_ids: [turnId], + page: { ...initial.page, record_range: { turn: 0, start: 1, end: 5 } }, + events: [ + ...initial.events, + { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 4, text: "Answer" }, + { event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 5 }, + ], + }; + let finishLatest!: (value: Response) => void; + let reads = 0; + vi.stubGlobal("fetch", vi.fn(() => { + const read = reads++; + if (read === 0) return Promise.resolve(response(initial)); + if (read === 1) return new Promise((resolve) => { finishLatest = resolve; }); + return Promise.resolve(response(latest)); + })); + const { client, running, reopen, close } = setup(); + const wrapper = ({ children }: { children: ReactNode }) => {children}; + const mounted = renderHook(() => { + const stream = useNanobotStream(chatId, [], false, undefined, undefined, [], { key: `websocket:${chatId}` }); + useEffect(() => { + let refreshOnOpen = false; + return client.onStatus((status) => { + if (status !== "open") refreshOnOpen = true; + else if (refreshOnOpen) { refreshOnOpen = false; stream.refreshHistory(); } + }); + }, [stream.refreshHistory]); + return stream; + }, { wrapper }); + await act(async () => { running(); }); + await act(async () => {}); + await reopen(); + await act(async () => { finishLatest(response(latest)); }); + expect(webuiThreadCache.get(`websocket:${chatId}`)).toEqual(latest); + expect(mounted.result.current.messages.map((message) => message.content)).toContain("Answer"); + expect(client.getRunState(chatId).active).toBe(false); + expect(mounted.result.current.isStreaming).toBe(false); + mounted.unmount(); + close(); + }); + + it("settles a held overlapping signed-image fragment only after loading its user prefix", async () => { + const chatId = "inactive"; + const turnId = "turn-old"; + const rawImage = "![image](images/photo.png)"; + const signedImage = "![image](/api/media/signed.png)"; + const initial: WebuiThreadPersistedPayload = { + schemaVersion: 3, sessionKey: `websocket:${chatId}`, projection: "events", + has_pending_tool_calls: true, active_turn_id: turnId, completed_turn_ids: [], + page: { history_generation: "generation", record_range: { turn: 0, start: 1, end: 2 }, + before_cursor: "inside", has_more_before: true, truncated_oversized_turn: true }, + events: [{ event: "model_request", chat_id: chatId, turn_id: turnId, turn_seq: 2, + request_id: "request", run_id: "run", sequence: 1, phase: "started", projection_id: "request" }], + }; + const latest: WebuiThreadPersistedPayload = { + ...initial, has_pending_tool_calls: false, active_turn_id: null, completed_turn_ids: [turnId], + page: { ...initial.page, record_range: { turn: 0, start: 1, end: 4 } }, + events: [...initial.events, + { event: "stream_end", chat_id: chatId, turn_id: turnId, turn_seq: 4, + stream_id: "wire", text: signedImage, projection_id: "answer" }, + { event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 5, projection_id: "done" }], + }; + const prefix: WebuiThreadPersistedPayload = { + ...initial, has_pending_tool_calls: false, active_turn_id: null, + page: { ...initial.page, record_range: { turn: 0, start: 0, end: 1 }, + before_cursor: null, has_more_before: false }, + events: [{ event: "user_message", chat_id: chatId, turn_id: turnId, turn_seq: 1, + text: "Show the image", starts_turn: true, projection_id: "question" }], + }; + let latestReads = 0; + let finishPrefix!: (value: Response) => void; + const fetchMock = vi.fn((url: string) => url.includes("before=") + ? new Promise((resolve) => { finishPrefix = resolve; }) + : Promise.resolve(response(latestReads++ ? latest : initial))); + vi.stubGlobal("fetch", fetchMock); + const { client, sockets, running, close } = setup(); + const wrapper = ({ children }: { children: ReactNode }) => {children}; + const mounted = renderHook(() => useNanobotStream(chatId, [], false, undefined, undefined, [], + { key: `websocket:${chatId}` }), { wrapper }); + act(() => { + running(); + sockets.at(-1)!.receive({ event: "delta", chat_id: chatId, turn_id: turnId, turn_seq: 3, + stream_id: "wire", text: rawImage }); + }); + await act(async () => {}); + expect(mounted.result.current.messages.map((message) => message.content)).toEqual([rawImage]); + await act(async () => { mounted.result.current.refreshHistory(); }); + await act(async () => {}); + expect(mounted.result.current.history.error).toBeNull(); + expect(mounted.result.current.history.hasMoreBefore).toBe(true); + expect(mounted.result.current.messages.map((message) => message.content)).toEqual([rawImage]); + expect(mounted.result.current.isStreaming).toBe(true); + expect(client.getRunState(chatId)).toMatchObject({ active: true, unsettled: true }); + + let older!: Promise; + act(() => { older = mounted.result.current.loadOlder(); }); + expect(fetchMock.mock.calls.at(-1)?.[0]).toContain("before=inside"); + await act(async () => { finishPrefix(response(prefix)); await older; }); + expect(mounted.result.current.messages.map((message) => message.content)).toEqual(["Show the image", signedImage]); + expect(mounted.result.current.messages.filter((message) => message.role === "assistant")).toHaveLength(1); + expect(mounted.result.current.history.hasMoreBefore).toBe(false); + expect(mounted.result.current.isStreaming).toBe(false); + expect(client.getRunState(chatId)).toMatchObject({ active: false, unsettled: false }); + mounted.unmount(); + close(); + }); + + it.each(["reconnect", "refresh"] as const)("keeps live delivery until the %s fragment joins the visible history", async (trigger) => { + const chatId = "inactive"; + const turnId = "turn-old"; + const chunk = (seq: number, text: string) => ({ + event: "delta" as const, chat_id: chatId, turn_id: turnId, turn_seq: seq, + stream_id: "wire", text, projection_id: `history-${seq}`, + }); + const page = (start: number, end: number, events: WebuiThreadPersistedPayload["events"], completed = false): WebuiThreadPersistedPayload => ({ + schemaVersion: 3, sessionKey: `websocket:${chatId}`, projection: "events", events, + has_pending_tool_calls: !completed, active_turn_id: completed ? null : turnId, + completed_turn_ids: completed ? [turnId] : [], + page: { history_generation: "generation", record_range: { turn: 0, start, end }, + before_cursor: `before-${start}`, has_more_before: start > 0, truncated_oversized_turn: true }, + }); + const initial = page(1, 3, [chunk(2, "B"), chunk(3, "C")]); + const latest = page(6, 9, [chunk(8, "H"), chunk(9, "I"), + { event: "turn_end", chat_id: chatId, turn_id: turnId, turn_seq: 10, projection_id: "history-end" }], true); + const missing = page(3, 6, [chunk(5, "E"), chunk(6, "F"), chunk(7, "G")]); + let finishLatest!: (value: Response) => void; + let finishMissing!: (value: Response) => void; + let latestReads = 0; + vi.stubGlobal("fetch", vi.fn((url: string) => { + if (url.includes("before=")) return new Promise((resolve) => { finishMissing = resolve; }); + const read = latestReads++; + if (read === 0) return Promise.resolve(response(initial)); + if (read === 1) return new Promise((resolve) => { finishLatest = resolve; }); + return Promise.resolve(response(latest)); + })); + const { client, sockets, running, reopen, close } = setup(); + const wrapper = ({ children }: { children: ReactNode }) => {children}; + const mounted = renderHook(() => { + const stream = useNanobotStream(chatId, [], false, undefined, undefined, [], { key: `websocket:${chatId}` }); + useEffect(() => { + let refreshOnOpen = false; + return client.onStatus((status) => { + if (status !== "open") refreshOnOpen = true; + else if (refreshOnOpen) { refreshOnOpen = false; stream.refreshHistory(); } + }); + }, [stream.refreshHistory]); + return stream; + }, { wrapper }); + await act(async () => { running(); }); + await act(async () => {}); + act(() => sockets[0].receive({ event: "delta", chat_id: chatId, turn_id: turnId, + turn_seq: 4, stream_id: "wire", text: "D" })); + await act(async () => { await vi.advanceTimersByTimeAsync(100); }); + expect(mounted.result.current.messages.at(-1)?.content).toBe("BCD"); + const reconcile = vi.spyOn(client, "reconcileCanonicalCompletion"); + const fence = vi.spyOn(client, "fenceCanonicalCompletedTurns"); + + if (trigger === "reconnect") await reopen(); + else await act(async () => { mounted.result.current.refreshHistory(); }); + await act(async () => { finishLatest(response(latest)); }); + expect(webuiThreadCache.get(`websocket:${chatId}`)).toEqual(latest); + expect(mounted.result.current.history.error).toBeNull(); + expect(mounted.result.current.history.loadingOlder).toBe(true); + expect(finishMissing).toBeTypeOf("function"); + expect(reconcile).not.toHaveBeenCalled(); + expect(fence).not.toHaveBeenCalled(); + expect(client.getRunState(chatId).active).toBe(true); + expect(mounted.result.current.isStreaming).toBe(true); + act(() => sockets.at(-1)!.receive({ event: "delta", chat_id: chatId, turn_id: turnId, + turn_seq: 5, stream_id: "wire", text: "E" })); + await act(async () => { await vi.advanceTimersByTimeAsync(100); }); + expect(mounted.result.current.messages.at(-1)?.content).toBe("BCDE"); + await act(async () => { finishMissing(response(missing)); }); + expect(mounted.result.current.messages.at(-1)?.content).toBe("BCDEFGHI"); + expect(client.getRunState(chatId).active).toBe(false); + expect(mounted.result.current.isStreaming).toBe(false); + const late = { event: "message", chat_id: chatId, turn_id: turnId, turn_seq: 11, + kind: "tool_hint", text: "late activity" }; + const observed = vi.fn(); + const unsubscribe = client.onChat(chatId, observed); + act(() => sockets.at(-1)!.receive(late)); + expect(observed).toHaveBeenCalledWith(late); + expect(mounted.result.current.messages.map((message) => message.content)).toContain("late activity"); + expect(client.getRunState(chatId).active).toBe(false); + unsubscribe(); + mounted.unmount(); + close(); + }); + it("bounds recovery reads while draining all chats and preserving a newer queued turn", async () => { const reads: Array<{ chatId: string; resolve: (value: Response) => void }> = []; let active = 0; diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsx index 531ada6bd..49add3adf 100644 --- a/webui/src/tests/useSessions.test.tsx +++ b/webui/src/tests/useSessions.test.tsx @@ -1139,6 +1139,35 @@ describe("useSessions", () => { expect(result.current.lineage).toBe(latestLineage); }); + it("continues past an empty latest fragment to the visible history", async () => { + vi.mocked(api.fetchWebuiThread) + .mockResolvedValueOnce({ + schemaVersion: 3, projection: "events", completed_turn_ids: ["long"], + events: [ + { event: "model_request", chat_id: "empty-tail", projection_id: "request", turn_id: "long", turn_seq: 4, + request_id: "request", run_id: "run", sequence: 1, phase: "completed" }, + { event: "turn_end", chat_id: "empty-tail", projection_id: "end", turn_id: "long", turn_seq: 5 }, + ], + page: { before_cursor: "inside", has_more_before: true, truncated_oversized_turn: true, + record_range: { turn: 0, start: 3, end: 5 } }, + }) + .mockResolvedValueOnce({ + schemaVersion: 3, projection: "events", + events: [{ event: "user_message", chat_id: "empty-tail", projection_id: "question", turn_id: "long", + turn_seq: 1, text: "Question", starts_turn: true }], + page: { before_cursor: null, has_more_before: false, truncated_oversized_turn: true, + record_range: { turn: 0, start: 0, end: 3 } }, + }); + const { result } = renderHook(() => useSessionHistory("websocket:empty-tail"), { + wrapper: wrap(fakeClient()), + }); + await waitFor(() => expect(result.current.messages.map((row) => row.content)).toEqual(["Question"])); + expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2); + expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("tok", "websocket:empty-tail", + expect.objectContaining({ before: "inside", limit: 120 })); + expect(result.current.hasMoreBefore).toBe(false); + }); + it("keeps older-history failures separate and retries them explicitly", async () => { vi.mocked(api.fetchWebuiThread) .mockResolvedValueOnce(canonicalThreadPayload({