diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index 37a4b16be..b8ce94ca5 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -6032,6 +6032,50 @@ def test_handle_webui_thread_get_accepts_pagination_query(tmp_path, monkeypatch) assert body["page"]["before_cursor"] +def test_handle_webui_thread_get_negotiates_client_event_projection( + tmp_path, + monkeypatch, +) -> None: + from urllib.parse import quote + + from websockets.datastructures import Headers + from websockets.http11 import Request + + from nanobot.webui.transcript import append_transcript_object + + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:event-route" + append_transcript_object( + key, + {"event": "user", "chat_id": "event-route", "text": "question"}, + ) + append_transcript_object( + key, + {"event": "message", "chat_id": "event-route", "text": "answer"}, + ) + append_transcript_object(key, {"event": "turn_end", "chat_id": "event-route"}) + + channel = _ch(MagicMock()) + channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0 + encoded = quote(key, safe="") + request = Request( + f"/api/sessions/{encoded}/webui-thread?projection=events", + Headers([("Authorization", "Bearer tok")]), + ) + + response = channel.gateway.http._handle_webui_thread_get(request, encoded) + + assert response.status_code == 200 + body = json.loads(response.body.decode()) + assert "messages" not in body + assert body["projection"] == "events" + assert [event["event"] for event in body["events"]] == [ + "user_message", + "message", + "turn_end", + ] + + def test_handle_file_preview_returns_workspace_file(tmp_path) -> None: from urllib.parse import quote diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 1d279beca..ec9c1f17b 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -919,6 +919,7 @@ def _select_transcript_page( limit: int | None, before: str | None, stats: TranscriptReplayStats | None = None, + page_unit_counter: Callable[[list[dict[str, Any]]], int] | None = None, _manifest_rebuilt: bool = False, ) -> tuple[list[dict[str, Any]], dict[str, Any]]: stats = stats or TranscriptReplayStats() @@ -963,6 +964,7 @@ def _select_transcript_page( limit=limit, before=before, stats=stats, + page_unit_counter=page_unit_counter, _manifest_rebuilt=True, ) local_upper = min(local_upper, len(turns)) @@ -999,9 +1001,12 @@ def _select_transcript_page( selected.append(_TranscriptTurnRef(ordinal, turn, trace_details_safe)) selected_record_count += turn_record_count selected_bytes += turn_bytes - replay_started = time.perf_counter() - selected_message_count += len(replay_transcript_to_ui_messages(turn)) - stats.replay_ms += int((time.perf_counter() - replay_started) * 1000) + if page_unit_counter is not None: + selected_message_count += page_unit_counter(turn) + else: + replay_started = time.perf_counter() + selected_message_count += len(replay_transcript_to_ui_messages(turn)) + stats.replay_ms += int((time.perf_counter() - replay_started) * 1000) if selected_message_count >= page_limit: break if selected_message_count >= page_limit or budget_reached: @@ -3176,6 +3181,315 @@ def build_webui_trace_detail_response( return None +def _client_projection_event_id(record: Mapping[str, Any]) -> str: + identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY) + if not isinstance(identity, str) or not identity: + identity = _stable_record_digest(dict(record)) + digest = hashlib.sha256(f"event\0{identity}".encode("utf-8")).hexdigest()[:20] + return f"history-{digest}" + + +def _client_projection_turn_fields(record: Mapping[str, Any]) -> dict[str, Any]: + fields: dict[str, Any] = {} + turn_id = record.get("turn_id") + if isinstance(turn_id, str) and turn_id: + fields["turn_id"] = turn_id + turn_phase = record.get("turn_phase") + if isinstance(turn_phase, str) and turn_phase in { + "user", "reasoning", "activity", "answer", "complete", + }: + fields["turn_phase"] = turn_phase + turn_seq = record.get("turn_seq") + if isinstance(turn_seq, int | float) and not isinstance(turn_seq, bool): + fields["turn_seq"] = int(turn_seq) + return fields + + +def _client_projection_common_fields(record: dict[str, Any]) -> dict[str, Any]: + fields: dict[str, Any] = { + "chat_id": str(record.get("chat_id") or ""), + "projection_id": _client_projection_event_id(record), + **_client_projection_turn_fields(record), + } + created_at_ms = _valid_created_at_ms(record.get("created_at_ms")) + if created_at_ms is not None: + fields["created_at_ms"] = created_at_ms + return fields + + +def _client_projection_source(record: dict[str, Any]) -> dict[str, Any] | None: + source = record.get("source") + if not isinstance(source, dict): + return None + source_data = cast(dict[str, Any], source) + kind = source_data.get("kind") + if not isinstance(kind, str) or not is_automation_kind(kind): + return None + projected: dict[str, Any] = {"kind": kind} + label = source_data.get("label") + if isinstance(label, str) and label.strip(): + projected["label"] = label.strip() + return projected + + +def _client_projection_event( + record: dict[str, Any], + *, + augment_user_media: Callable[[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, +) -> dict[str, Any] | None: + event = record.get("event") + common = _client_projection_common_fields(record) + if event == "user": + projected: dict[str, Any] = { + "event": "user_message", + **common, + "text": record.get("text") if isinstance(record.get("text"), str) else "", + "starts_turn": True, + } + raw_paths = record.get("media_paths") + paths = [ + str(path) + for path in cast(list[Any], raw_paths) + if path + ] if isinstance(raw_paths, list) else [] + if paths and augment_user_media is not None: + media = augment_user_media(paths) + if media: + projected["media_urls"] = media + for source_key, target_key in ( + ("cli_apps", "cli_apps"), + ("mcp_presets", "mcp_presets"), + ): + value = record.get(source_key) + if isinstance(value, list): + rows = [ + dict(cast(dict[str, Any], row)) + for row in cast(list[Any], value) + if isinstance(row, dict) + ] + if rows: + projected[target_key] = rows + mentions = normalize_session_mentions_metadata(record.get("session_mentions")) + if mentions: + projected["session_mentions"] = mentions + session_message = normalize_session_message_ui_metadata(record.get("session_message")) + if session_message: + projected["provenance"] = {"session_message": session_message} + return projected + + if event in {"delta", "stream_end", "reasoning_delta", "reasoning_end"}: + projected = {"event": event, **common} + text = record.get("text") + if isinstance(text, str): + if event == "stream_end" and augment_assistant_text is not None: + text = augment_assistant_text(text) + projected["text"] = text + if event == "stream_end": + if record.get("resuming") is True: + projected["resuming"] = True + if record.get("merge_next") is True: + projected["merge_next"] = True + source = _client_projection_source(record) + if source: + projected["source"] = source + return projected + + if event == "message": + text = record.get("text") + content = text if isinstance(text, str) else "" + if augment_assistant_text is not None: + content = augment_assistant_text(content) + projected = {"event": "message", **common, "text": content} + kind = record.get("kind") + if kind in {"tool_hint", "progress", "reasoning"}: + projected["kind"] = kind + tool_events = _normalize_tool_events(record.get("tool_events")) + if tool_events: + projected["tool_events"] = tool_events + raw_media = record.get("media") + media_paths = [ + path + for path in cast(list[Any], raw_media) + if isinstance(path, str) and path + ] if isinstance(raw_media, list) else [] + media = ( + augment_assistant_media(media_paths) + if media_paths and augment_assistant_media is not None + else [] + ) + if not media and (not media_paths or augment_assistant_media is None): + media = _media_from_signed_urls(record.get("media_urls")) + if media: + projected["media_urls"] = media + latency_ms = record.get("latency_ms") + if isinstance(latency_ms, int | float) and latency_ms >= 0: + projected["latency_ms"] = int(latency_ms) + source = _client_projection_source(record) + if source: + projected["source"] = source + return projected + + if event == "file_edit": + raw_edits = record.get("edits") + edits = [ + dict(cast(dict[str, Any], edit)) + for edit in cast(list[Any], raw_edits) + if isinstance(edit, dict) + ] if isinstance(raw_edits, list) else [] + return {"event": "file_edit", **common, "edits": edits} + + if event == "context_compaction": + compaction_id = record.get("compaction_id") + phase = record.get("phase") + if ( + not isinstance(compaction_id, str) + or not compaction_id + or not isinstance(phase, str) + or phase not in {"started", "succeeded", "failed", "cancelled"} + ): + return None + return { + "event": "context_compaction", + **common, + "compaction_id": compaction_id, + "phase": phase, + } + + if event == "turn_end": + projected = {"event": "turn_end", **common} + latency_ms = record.get("latency_ms") + if isinstance(latency_ms, int | float) and latency_ms >= 0: + projected["latency_ms"] = int(latency_ms) + usage = _sanitize_turn_usage(record.get("usage")) + if usage: + projected["usage"] = usage + raw_round_usages = record.get("round_usages") + if isinstance(raw_round_usages, list): + round_usages = [ + sanitized + for item in cast(list[object], raw_round_usages) + if (sanitized := _sanitize_turn_usage(item)) is not None + ] + if round_usages: + projected["round_usages"] = round_usages + context_window = record.get("context_window_tokens") + if isinstance(context_window, int | float) and context_window >= 0: + projected["context_window_tokens"] = int(context_window) + return projected + return None + + +def _client_projection_requires_legacy_messages(lines: list[dict[str, Any]]) -> bool: + """Keep the established deferred-detail response for unusually large traces.""" + trace_bytes = 0 + conservative_limit = _MAX_INLINE_TRACE_DETAIL_BYTES // 2 + for record in lines: + if record.get("event") == "message" and record.get("kind") in { + "tool_hint", + "progress", + }: + trace_bytes += len(_record_json_line(record).encode("utf-8")) + if trace_bytes > conservative_limit: + return True + elif record.get("event") in {"user", "delta", "stream_end", "turn_end"}: + trace_bytes = 0 + return False + + +def _client_projection_page_units(turn: list[dict[str, Any]]) -> int: + """Bound event pages without invoking the legacy UI-message projector. + + The limit is intentionally a soft display-unit budget. Completed stream + deltas have already been compacted, so ordinary user/answer turns retain + the same two-unit shape as the legacy message count. + """ + units = 0 + reasoning_placeholder = False + answer_open = False + activity_open = False + for record in turn: + event = record.get("event") + if event == "user": + units += 1 + reasoning_placeholder = False + answer_open = False + activity_open = False + elif event in {"reasoning_delta", "reasoning_end"}: + text = record.get("text") + if isinstance(text, str) and text and not answer_open and not reasoning_placeholder: + units += 1 + reasoning_placeholder = True + activity_open = False + elif event in {"delta", "stream_end"}: + text = record.get("text") + if isinstance(text, str) and text and not answer_open: + if not reasoning_placeholder: + units += 1 + answer_open = True + reasoning_placeholder = False + if event == "stream_end" and not ( + record.get("resuming") is True and record.get("merge_next") is True + ): + answer_open = False + activity_open = False + elif event == "message": + kind = record.get("kind") + if kind == "reasoning": + if record.get("text") and not answer_open and not reasoning_placeholder: + units += 1 + reasoning_placeholder = True + activity_open = False + elif kind in {"tool_hint", "progress"}: + if not activity_open: + units += 1 + activity_open = True + answer_open = False + reasoning_placeholder = False + else: + if not reasoning_placeholder: + units += 1 + reasoning_placeholder = False + answer_open = False + activity_open = False + elif event == "file_edit": + if not activity_open: + units += 1 + activity_open = True + answer_open = False + reasoning_placeholder = False + elif event == "context_compaction": + units += 1 + activity_open = False + return max(1, units) + + +def _client_projection_events( + lines: list[dict[str, Any]], + *, + augment_user_media: Callable[[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, +) -> tuple[list[dict[str, Any]], int | None]: + events: list[dict[str, Any]] = [] + fork_boundary_event_index: int | None = None + for record in lines: + if record.get("event") == WEBUI_FORK_MARKER_EVENT: + if fork_boundary_event_index is None: + fork_boundary_event_index = len(events) + continue + event = _client_projection_event( + record, + augment_user_media=augment_user_media, + augment_assistant_media=augment_assistant_media, + augment_assistant_text=augment_assistant_text, + ) + if event is not None: + events.append(event) + return events, fork_boundary_event_index + + def build_webui_thread_response( session_key: str, *, @@ -3190,6 +3504,7 @@ def build_webui_thread_response( limit: int | None = None, direction: str | None = None, before: str | None = None, + projection: str = "messages", stats: TranscriptReplayStats | None = None, ) -> dict[str, Any] | None: """Return a payload compatible with ``WebuiThreadPersistedPayload``.""" @@ -3199,6 +3514,9 @@ def build_webui_thread_response( limit=limit, before=before, stats=replay_stats, + page_unit_counter=( + _client_projection_page_units if projection == "events" else None + ), ) if not lines and active_turn_started_at is None: return None @@ -3217,20 +3535,9 @@ def build_webui_thread_response( if needs_incomplete_recovery: lines = _recover_incomplete_turns(lines, session_turns) lines = _ensure_replay_identities(lines) - fork_boundary = fork_boundary_message_count(lines) - replay_started = time.perf_counter() - msgs = replay_transcript_to_ui_messages( - lines, - augment_user_media=augment_user_media, - augment_assistant_media=augment_assistant_media, - augment_assistant_text=augment_assistant_text, - defer_trace_details=True, - ) - replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000) payload: dict[str, Any] = { "schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION, "sessionKey": session_key, - "messages": msgs, "completed_turn_ids": completed_turn_ids(lines), "has_pending_tool_calls": has_pending_tool_calls( lines, @@ -3242,8 +3549,38 @@ def build_webui_thread_response( ), "active_turn_id": active_turn_id, } - page["loaded_message_count"] = len(msgs) + # TODO: Remove the server-owned UI-message projection after the event response + # owns deferred trace details and the unnegotiated ``messages`` contract ends. + use_client_projection = ( + projection == "events" + and not _client_projection_requires_legacy_messages(lines) + ) + if use_client_projection: + events, fork_boundary_event_index = _client_projection_events( + lines, + augment_user_media=augment_user_media, + augment_assistant_media=augment_assistant_media, + augment_assistant_text=augment_assistant_text, + ) + payload["projection"] = "events" + payload["events"] = events + page["loaded_event_count"] = len(events) + if fork_boundary_event_index is not None: + payload["fork_boundary_event_index"] = fork_boundary_event_index + else: + fork_boundary = fork_boundary_message_count(lines) + replay_started = time.perf_counter() + msgs = replay_transcript_to_ui_messages( + lines, + augment_user_media=augment_user_media, + augment_assistant_media=augment_assistant_media, + augment_assistant_text=augment_assistant_text, + defer_trace_details=True, + ) + replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000) + payload["messages"] = msgs + page["loaded_message_count"] = len(msgs) + if fork_boundary is not None: + payload["fork_boundary_message_count"] = fork_boundary payload["page"] = page - if fork_boundary is not None: - payload["fork_boundary_message_count"] = fork_boundary return payload diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 51ccdea78..c34af8f83 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -1001,6 +1001,9 @@ class GatewayHTTPHandler: if direction is not None and direction not in {"latest"}: return _http_error(400, "invalid direction") before = _query_first(query, "before") + projection = _query_first(query, "projection") + if projection is not None and projection not in {"events"}: + return _http_error(400, "invalid projection") from nanobot.session.webui_turns import ( websocket_turn_id, websocket_turn_transcript_persistence_failed, @@ -1028,6 +1031,7 @@ class GatewayHTTPHandler: "direction": direction, "gateway_instance": self.tokens.instance_id, "limit": limit, + "projection": projection, "session_updated_at": ( session_metadata.get("updated_at") if session_metadata is not None else None ), @@ -1062,6 +1066,7 @@ class GatewayHTTPHandler: limit=limit, direction=direction, before=before, + projection=projection or "messages", stats=diagnostics.transcript if diagnostics is not None else None, ) if diagnostics is not None: diff --git a/tests/utils/test_webui_event_projection_equivalence.py b/tests/utils/test_webui_event_projection_equivalence.py index e20384b98..30d50786e 100644 --- a/tests/utils/test_webui_event_projection_equivalence.py +++ b/tests/utils/test_webui_event_projection_equivalence.py @@ -56,8 +56,8 @@ def _normalize_projection(messages: list[dict[str, Any]]) -> list[dict[str, Any] return normalized -def test_replay_matches_shared_live_projection_before_canonical_revision_migration() -> None: - """Lock the known-equivalent subset without defining the future snapshot protocol.""" +def test_legacy_message_projection_keeps_canonical_fixture_compatibility() -> None: + """Keep the old-client and oversized-trace fallback compatible during migration.""" fixture = json.loads(_FIXTURE_PATH.read_text(encoding="utf-8")) for case in fixture["cases"]: diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index f7703d4bf..7ead850d0 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -184,6 +184,134 @@ def test_large_trace_details_are_deferred_and_resolved(tmp_path, monkeypatch) -> } +def test_event_projection_response_exposes_sanitized_canonical_events( + tmp_path, + monkeypatch, +) -> None: + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:project-events" + for event in ( + { + "event": "user", + "chat_id": "project-events", + "text": "explain", + "media_paths": ["private/input.png"], + "turn_id": "turn-1", + }, + { + "event": "reasoning_delta", + "chat_id": "project-events", + "text": "thinking", + "turn_id": "turn-1", + }, + { + "event": "message", + "chat_id": "project-events", + "text": "done", + "turn_id": "turn-1", + }, + { + "event": "turn_end", + "chat_id": "project-events", + "turn_id": "turn-1", + "latency_ms": 12, + }, + ): + append_transcript_object(key, event) + + def fail_legacy_projection(*args, **kwargs): + pytest.fail("event projection must not invoke the legacy message projector") + + monkeypatch.setattr( + transcript_module, + "replay_transcript_to_ui_messages", + fail_legacy_projection, + ) + + payload = build_webui_thread_response( + key, + projection="events", + augment_user_media=lambda paths: [ + {"kind": "image", "url": "/api/media/signed", "name": Path(paths[0]).name}, + ], + ) + + assert payload is not None + assert "messages" not in payload + assert payload["projection"] == "events" + assert payload["events"][0] == { + "event": "user_message", + "chat_id": "project-events", + "projection_id": payload["events"][0]["projection_id"], + "created_at_ms": payload["events"][0]["created_at_ms"], + "turn_id": "turn-1", + "text": "explain", + "starts_turn": True, + "media_urls": [ + {"kind": "image", "url": "/api/media/signed", "name": "input.png"}, + ], + } + assert [event["event"] for event in payload["events"]] == [ + "user_message", + "reasoning_delta", + "message", + "turn_end", + ] + assert payload["page"]["loaded_event_count"] == 4 + + +def test_event_projection_augments_complete_stream_text(tmp_path, monkeypatch) -> None: + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:project-stream-media" + for event in ( + { + "event": "delta", + "chat_id": "project-stream-media", + "text": "![plot](output.png)", + }, + { + "event": "stream_end", + "chat_id": "project-stream-media", + "text": "![plot](output.png)", + }, + ): + append_transcript_object(key, event) + + payload = build_webui_thread_response( + key, + projection="events", + augment_assistant_text=lambda text: text.replace("output.png", "/api/media/signed"), + ) + + assert payload is not None + assert [event["text"] for event in payload["events"]] == [ + "![plot](output.png)", + "![plot](/api/media/signed)", + ] + + +def test_event_projection_falls_back_for_deferred_trace_details(tmp_path, monkeypatch) -> None: + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + key = "websocket:event-trace-fallback" + for event in ( + {"event": "user", "chat_id": "event-trace-fallback", "text": "run"}, + { + "event": "message", + "chat_id": "event-trace-fallback", + "kind": "progress", + "text": f'exec({json.dumps({"command": "x" * 40_000})})', + }, + {"event": "turn_end", "chat_id": "event-trace-fallback"}, + ): + append_transcript_object(key, event) + + payload = build_webui_thread_response(key, projection="events") + + assert payload is not None + assert "events" not in payload + assert any(message.get("traceDetail") for message in payload["messages"]) + + @pytest.mark.parametrize( ("delta_event", "end_event"), [("reasoning_delta", "reasoning_end"), ("delta", "stream_end")], diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 1372fed4f..ea8be178a 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -4,32 +4,23 @@ import { useTranslation } from "react-i18next"; import { useThreadVisibility } from "@/hooks/useThreadVisibility"; import { useClient } from "@/providers/ClientProvider"; -import { toMediaAttachment } from "@/lib/media"; import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure"; -import { - mergeToolProgressEvents, - mergeToolProgressTraceLines, - normalizeToolProgressEvents, - toolTraceLinesFromEvents, -} from "@/lib/tool-traces"; import { hasPendingAgentActivity } from "@/lib/activity-timeline"; import type { StreamError } from "@/lib/nanobot-client"; import { - closeReasoningStream, - filterCoveredFileEditToolEvents, + clearThreadProjectionActivity, + closeThreadProjectionAnswer, + createThreadProjectionState, finalizeStreamedTurn, - findActiveAssistantPlaceholderIndex, - findFileEditTraceIndex, - findStreamingAssistantIndex, - isReasoningOnlyPlaceholder, - matchesTurn, - mergeFileEdits, - replaceMessageAt, - stampLastAssistantCompletion, - stripCoveredFileEditToolHintsFromMessages, + projectThreadEvent, + resetThreadProjectionCursor, turnFieldsFromEvent, } from "@/lib/thread-event-projection"; -import type { UIMessageTurnFields } from "@/lib/thread-event-projection"; +import type { + ThreadProjectionEvent, + ThreadProjectionState, + UIMessageTurnFields, +} from "@/lib/thread-event-projection"; import { formatQuotedUserMessage } from "@/lib/user-message-quote"; import { readLocalPreferences } from "@/lib/local-preferences"; import type { @@ -47,17 +38,6 @@ import type { WorkspaceScopePayload, } from "@/lib/types"; -interface StreamBuffer { - /** ID of the assistant message currently receiving deltas (cleared when its segment closes). */ - messageId: string; - mergeReasoning?: boolean; -} - -interface ActiveAssistantCursor { - id: string; - index: number; -} - type PendingStreamEvent = | { kind: "delta"; text: string; turn: UIMessageTurnFields; source?: UIMessage["source"] } | { kind: "reasoning"; text: string; turn: UIMessageTurnFields }; @@ -66,98 +46,6 @@ const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000; // Markdown and layout work must leave room for input between visible updates. const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50; -/** - * Append a reasoning chunk to the last open reasoning stream in ``prev``. - * - * Lookup rule: reasoning can only extend the current reasoning placeholder. - * Once ordinary answer text has appeared, the next reasoning chunk starts a - * fresh activity surface so streamed output stays in arrival order while the - * final answer remains the only visible answer bubble. - */ -function attachReasoningChunk( - prev: UIMessage[], - chunk: string, - segments?: { - ensure: () => string; - }, - turn: UIMessageTurnFields = {}, -): UIMessage[] { - for (let i = prev.length - 1; i >= 0; i -= 1) { - const candidate = prev[i]; - // A user turn is a hard boundary: reasoning after it belongs to the new - // assistant turn, never to an earlier assistant reply. - if (candidate.role === "user") break; - // A trace row (e.g. Used tools) is also a phase boundary. Reasoning after - // tools belongs to the next assistant iteration, not the assistant turn - // that produced those tool calls. - if (candidate.kind === "trace") break; - if (candidate.role !== "assistant") continue; - if (!matchesTurn(candidate, turn)) break; - const activitySegmentId = candidate.activitySegmentId ?? segments?.ensure(); - const hasAnswer = candidate.content.length > 0; - if (hasAnswer) break; - // ``reasoning_end`` closes this row even though the assistant placeholder - // stays streaming for the rest of the turn. The next reasoning stream must - // get its own row when an intervening tool trace is delayed or unavailable. - if ( - candidate.reasoningStreaming - || (candidate.isStreaming && candidate.reasoning === undefined) - ) { - const merged: UIMessage = { - ...candidate, - reasoning: (candidate.reasoning ?? "") + chunk, - reasoningStreaming: true, - ...(activitySegmentId ? { activitySegmentId } : {}), - ...turn, - }; - return [...prev.slice(0, i), merged, ...prev.slice(i + 1)]; - } - break; - } - const activitySegmentId = segments?.ensure(); - return [ - ...prev, - { - id: crypto.randomUUID(), - role: "assistant", - content: "", - isStreaming: true, - reasoning: chunk, - reasoningStreaming: true, - ...(activitySegmentId ? { activitySegmentId } : {}), - ...turn, - createdAt: Date.now(), - }, - ]; -} - -function absorbCompleteAssistantMessage( - prev: UIMessage[], - message: Omit, -): UIMessage[] { - const last = prev[prev.length - 1]; - if (!last || !isReasoningOnlyPlaceholder(last) || !matchesTurn(last, message)) { - return [ - ...prev, - { - id: crypto.randomUUID(), - role: "assistant", - createdAt: Date.now(), - ...message, - }, - ]; - } - return [ - ...prev.slice(0, -1), - { - ...last, - ...message, - isStreaming: false, - reasoningStreaming: false, - }, - ]; -} - /** * Subscribe to a chat by ID. Returns the in-memory message list for the chat, * a streaming flag, and a ``send`` function. Initial history must be seeded @@ -297,17 +185,13 @@ export function useNanobotStream( const [goalState, setGoalState] = useState(undefined); const [recoveryState, setRecoveryState] = useState(null); const [streamError, setStreamError] = useState(null); - const buffer = useRef(null); - const activeAssistantRef = useRef(null); - const closedAssistantStreamIdsRef = useRef>(new Set()); - const activitySegmentRef = useRef(null); - const fileEditSegmentRef = useRef(null); - const activitySegmentCounterRef = useRef(0); + const projectionRef = useRef( + createThreadProjectionState(initialMessages), + ); const pendingStreamEventsRef = useRef([]); const streamFrameRef = useRef(null); const streamTimerRef = useRef(null); const lastStreamFlushRef = useRef(0); - const suppressStreamUntilTurnEndRef = useRef(false); const sideChannelTurnIdsRef = useRef>(new Set()); const dismissStreamError = useCallback(() => setStreamError(null), []); @@ -340,39 +224,14 @@ export function useNanobotStream( return turnId !== undefined && sideChannelTurnIdsRef.current.has(turnId); }, []); - const createActivitySegmentId = useCallback((activate = true) => { - activitySegmentCounterRef.current += 1; - const id = `activity-${activitySegmentCounterRef.current}`; - if (activate) activitySegmentRef.current = id; - return id; - }, []); - - const freshActivitySegmentId = useCallback( - () => createActivitySegmentId(true), - [createActivitySegmentId], - ); - - const detachedActivitySegmentId = useCallback( - () => createActivitySegmentId(false), - [createActivitySegmentId], - ); - - const ensureActivitySegmentId = useCallback(() => { - if (activitySegmentRef.current) return activitySegmentRef.current; - return freshActivitySegmentId(); - }, [freshActivitySegmentId]); - const clearActivitySegment = useCallback(() => { - activitySegmentRef.current = null; - fileEditSegmentRef.current = null; + projectionRef.current = clearThreadProjectionActivity(projectionRef.current); }, []); const closeActiveAssistantStream = useCallback(() => { - const closedStreamId = buffer.current?.messageId ?? activeAssistantRef.current?.id; - if (closedStreamId) closedAssistantStreamIdsRef.current.add(closedStreamId); - buffer.current = null; - activeAssistantRef.current = null; - return !!closedStreamId; + const hadActiveAssistant = projectionRef.current.activeAssistantId !== null; + projectionRef.current = closeThreadProjectionAnswer(projectionRef.current); + return hadActiveAssistant; }, []); const applyStreamError = useCallback((err: StreamError) => { @@ -398,37 +257,36 @@ export function useNanobotStream( .map((message) => message.activitySegmentId) .filter((segmentId): segmentId is string => typeof segmentId === "string"), ); - if ( - activeAssistantRef.current - && rejectedIds.has(activeAssistantRef.current.id) - ) { - activeAssistantRef.current = null; - } - if (buffer.current && rejectedIds.has(buffer.current.messageId)) { - buffer.current = null; - } - for (const id of rejectedIds) closedAssistantStreamIdsRef.current.delete(id); - if ( - activitySegmentRef.current - && rejectedSegments.has(activitySegmentRef.current) - ) { - activitySegmentRef.current = null; - } - if ( - fileEditSegmentRef.current - && rejectedSegments.has(fileEditSegmentRef.current) - ) { - fileEditSegmentRef.current = null; - } - return prev.flatMap((message) => { + const projection = projectionRef.current; + const closedAssistantIds = new Set(projection.closedAssistantIds); + for (const id of rejectedIds) closedAssistantIds.delete(id); + const nextMessages = prev.flatMap((message) => { if (message.turnId !== rejectedTurnId) return [message]; if (message.role !== "user") return []; return [{ ...message, - deliveryStatus: "failed", + deliveryStatus: "failed" as const, deliveryErrorKind: err.kind, }]; }); + projectionRef.current = { + ...projection, + messages: nextMessages, + activeAssistantId: projection.activeAssistantId + && rejectedIds.has(projection.activeAssistantId) + ? null + : projection.activeAssistantId, + closedAssistantIds, + activitySegmentId: projection.activitySegmentId + && rejectedSegments.has(projection.activitySegmentId) + ? null + : projection.activitySegmentId, + fileEditSegmentId: projection.fileEditSegmentId + && rejectedSegments.has(projection.fileEditSegmentId) + ? null + : projection.fileEditSegmentId, + }; + return nextMessages; }); const remainingStartedAt = client.getRunStartedAt(chatId); @@ -438,96 +296,19 @@ export function useNanobotStream( ); setRunStartedAt(remainingStartedAt); setIsStreaming(hasRemainingRun); - if (!hasRemainingRun) suppressStreamUntilTurnEndRef.current = false; + if (!hasRemainingRun) { + projectionRef.current = { + ...projectionRef.current, + suppressUntilTurnEnd: false, + }; + } }, [chatId, client]); useEffect(() => client.onError(applyStreamError), [applyStreamError, client]); - const resolveActiveAssistantIndex = useCallback(( - prev: UIMessage[], - turn: UIMessageTurnFields = {}, - ): number | null => { - const cursor = activeAssistantRef.current; - if (!cursor) return null; - const indexed = prev[cursor.index]; - if ( - indexed?.id === cursor.id - && indexed.role === "assistant" - && indexed.kind !== "trace" - && indexed.isStreaming - && matchesTurn(indexed, turn) - ) { - return cursor.index; - } - const idx = prev.findIndex((m) => m.id === cursor.id); - if (idx === -1) { - activeAssistantRef.current = null; - return null; - } - const found = prev[idx]; - if ( - found.role !== "assistant" - || found.kind === "trace" - || !found.isStreaming - || !matchesTurn(found, turn) - ) { - activeAssistantRef.current = null; - return null; - } - activeAssistantRef.current = { id: cursor.id, index: idx }; - return idx; - }, []); - - const appendAnswerChunk = useCallback( - ( - prev: UIMessage[], - chunk: string, - turn: UIMessageTurnFields = {}, - source?: UIMessage["source"], - ): UIMessage[] => { - let next = prev; - let targetIndex = resolveActiveAssistantIndex(next, turn); - - if (targetIndex === null) { - targetIndex = findActiveAssistantPlaceholderIndex(next, turn); - } - if (targetIndex === null) { - targetIndex = findStreamingAssistantIndex(next, closedAssistantStreamIdsRef.current, turn); - } - if (targetIndex === null) { - const id = crypto.randomUUID(); - next = [ - ...next, - { - id, - role: "assistant", - content: "", - isStreaming: true, - createdAt: Date.now(), - }, - ]; - targetIndex = next.length - 1; - } - - const target = next[targetIndex]; - const merged: UIMessage = { - ...target, - content: target.content + chunk, - isStreaming: true, - ...turn, - ...(source ? { source } : {}), - }; - closedAssistantStreamIdsRef.current.delete(merged.id); - activeAssistantRef.current = { id: merged.id, index: targetIndex }; - if (buffer.current?.messageId !== merged.id) buffer.current = { messageId: merged.id }; - return replaceMessageAt(next, targetIndex, merged); - }, - [resolveActiveAssistantIndex], - ); - const applyPendingStreamEvents = useCallback( (prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => { - let next = prev; + let projection = { ...projectionRef.current, messages: prev }; for (let index = 0; index < events.length; index++) { const event = events[index]; const chunks = [event.text]; @@ -543,39 +324,33 @@ export function useNanobotStream( index++; } const text = chunks.join(""); - if (event.kind === "delta") { - next = appendAnswerChunk(next, text, turn, event.source); - } else { - const continuationIndex = buffer.current?.mergeReasoning - ? resolveActiveAssistantIndex(next, turn) - : null; - if (continuationIndex !== null) { - // Length continuation keeps one Markdown answer and its reasoning - // together. Ordinary reasoning still opens a new activity surface. - const target = next[continuationIndex]; - const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : ""; - next = replaceMessageAt(next, continuationIndex, { - ...target, - reasoning: (target.reasoning ?? "") + separator + text, - reasoningStreaming: true, - }); - continue; - } - if (closeActiveAssistantStream()) clearActivitySegment(); - next = attachReasoningChunk( - next, - text, - { ensure: ensureActivitySegmentId }, - turn, - ); - } + const projectedEvent: ThreadProjectionEvent = event.kind === "delta" + ? { + event: "delta", + chat_id: chatId ?? "", + text, + turn_id: turn.turnId, + turn_phase: turn.turnPhase, + turn_seq: turn.turnSeq, + source: event.source, + } + : { + event: "reasoning_delta", + chat_id: chatId ?? "", + text, + turn_id: turn.turnId, + turn_phase: turn.turnPhase, + turn_seq: turn.turnSeq, + }; + projection = projectThreadEvent(projection, projectedEvent, { + createId: () => crypto.randomUUID(), + now: Date.now(), + }); } - return next; + projectionRef.current = projection; + return projection.messages; }, - [ - appendAnswerChunk, clearActivitySegment, closeActiveAssistantStream, - ensureActivitySegmentId, resolveActiveAssistantIndex, - ], + [chatId], ); const flushPendingStreamEvents = useCallback((options?: { @@ -605,65 +380,32 @@ export function useNanobotStream( } pendingStreamEventsRef.current = []; setMessages((prev) => { - let next = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev; - if (finalAnswerText !== undefined) { - const targetIndex = - resolveActiveAssistantIndex(next, turn) - ?? findStreamingAssistantIndex(next, closedAssistantStreamIdsRef.current, turn); - if (targetIndex !== null) { - const target = next[targetIndex]; - const merged = { - ...target, - content: finalAnswerText, - isStreaming: true, - ...turn, - ...(source ? { source } : {}), - }; - next = replaceMessageAt(next, targetIndex, merged); - if (!options?.closeAnswerSegment) { - closedAssistantStreamIdsRef.current.delete(merged.id); - activeAssistantRef.current = { id: merged.id, index: targetIndex }; - buffer.current = { messageId: merged.id }; - } - } else { - const id = crypto.randomUUID(); - next = [ - ...next, - { - id, - role: "assistant", - content: finalAnswerText, - isStreaming: true, - ...turn, - ...(source ? { source } : {}), - createdAt: Date.now(), - }, - ]; - if (options?.closeAnswerSegment) { - closedAssistantStreamIdsRef.current.add(id); - } else { - activeAssistantRef.current = { id, index: next.length - 1 }; - buffer.current = { messageId: id }; - } - } - } else if (source) { - const targetIndex = - resolveActiveAssistantIndex(next, turn) - ?? findStreamingAssistantIndex(next, closedAssistantStreamIdsRef.current, turn); - if (targetIndex !== null) { - const target = next[targetIndex]; - next = replaceMessageAt(next, targetIndex, { - ...target, - ...turn, - source, - }); - } + const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev; + let projection = { ...projectionRef.current, messages: nextMessages }; + if ( + finalAnswerText !== undefined + || source !== undefined + || options?.mergeReasoning + || options?.closeAnswerSegment + ) { + projection = projectThreadEvent(projection, { + event: "stream_end", + chat_id: chatId ?? "", + ...(finalAnswerText !== undefined ? { text: finalAnswerText } : {}), + ...(source ? { source } : {}), + ...(options?.mergeReasoning ? { resuming: true, merge_next: true } : {}), + turn_id: turn.turnId, + turn_phase: turn.turnPhase, + turn_seq: turn.turnSeq, + }, { + createId: () => crypto.randomUUID(), + now: Date.now(), + }); } - if (options?.mergeReasoning && buffer.current) buffer.current.mergeReasoning = true; - if (options?.closeAnswerSegment) closeActiveAssistantStream(); - return next; + projectionRef.current = projection; + return projection.messages; }); - }, [applyPendingStreamEvents, closeActiveAssistantStream, resolveActiveAssistantIndex]); + }, [applyPendingStreamEvents, chatId, closeActiveAssistantStream]); const schedulePendingStreamFlush = useCallback(function schedule() { if (streamFrameRef.current !== null || streamTimerRef.current !== null) return; @@ -735,13 +477,16 @@ export function useNanobotStream( return; } flushPendingStreamEvents(); - buffer.current = null; - activeAssistantRef.current = null; - closedAssistantStreamIdsRef.current.clear(); - clearActivitySegment(); - setMessages((prev) => prev.map((message) => ( - message.isStreaming ? { ...message, isStreaming: false } : message - ))); + setMessages((prev) => { + const settled = prev.map((message) => ( + message.isStreaming ? { ...message, isStreaming: false } : message + )); + projectionRef.current = resetThreadProjectionCursor( + projectionRef.current, + settled, + ); + return settled; + }); setRunStartedAt(null); setIsStreaming(false); }); @@ -764,13 +509,9 @@ export function useNanobotStream( setRetryStatus(null); setGoalState(chatId ? client.getGoalState(chatId) : undefined); setRecoveryState(null); - buffer.current = null; - activeAssistantRef.current = null; - closedAssistantStreamIdsRef.current.clear(); - clearActivitySegment(); + projectionRef.current = createThreadProjectionState(initialMessages); clearPendingStreamWork(); sideChannelTurnIdsRef.current.clear(); - suppressStreamUntilTurnEndRef.current = false; // eslint-disable-next-line react-hooks/exhaustive-deps }, [chatId, client, clearActivitySegment, clearPendingStreamWork]); @@ -778,6 +519,25 @@ export function useNanobotStream( if (hasPendingToolCalls) setIsStreaming(true); }, [hasPendingToolCalls]); + const applyProjectionEvent = useCallback(( + event: ThreadProjectionEvent, + options?: { sideChannel?: boolean }, + ) => { + setMessages((prev) => { + const projection = projectThreadEvent( + { ...projectionRef.current, messages: prev }, + event, + { + createId: () => crypto.randomUUID(), + now: Date.now(), + sideChannel: options?.sideChannel, + }, + ); + projectionRef.current = projection; + return projection.messages; + }); + }, []); + useEffect(() => { if (!chatId) return; @@ -892,10 +652,9 @@ export function useNanobotStream( || ev.event === "stream_end" ) setRetryStatus(null); if (ev.event === "delta") { - if (suppressStreamUntilTurnEndRef.current) return; + if (projectionRef.current.suppressUntilTurnEnd) return; const chunk = typeof ev.text === "string" ? ev.text : ""; if (!chunk) return; - clearActivitySegment(); setIsStreaming(true); pendingStreamEventsRef.current.push({ kind: "delta", @@ -908,10 +667,9 @@ export function useNanobotStream( } if (ev.event === "reasoning_delta") { - if (suppressStreamUntilTurnEndRef.current) return; + if (projectionRef.current.suppressUntilTurnEnd) return; const chunk = ev.text; if (!chunk) return; - if (fileEditSegmentRef.current) clearActivitySegment(); setIsStreaming(true); pendingStreamEventsRef.current.push({ kind: "reasoning", @@ -932,7 +690,7 @@ export function useNanobotStream( turn, source: ev.source, }); - if (suppressStreamUntilTurnEndRef.current) return; + if (projectionRef.current.suppressUntilTurnEnd) return; if (ev.resuming) { setIsStreaming(true); return; @@ -944,17 +702,11 @@ export function useNanobotStream( return; } - const shouldCloseAnswerBeforeEvent = - ev.event === "file_edit" - || ( - ev.event === "message" - && (ev.kind === "tool_hint" || ev.kind === "progress") - ); - flushPendingStreamEvents({ closeAnswerSegment: shouldCloseAnswerBeforeEvent }); + flushPendingStreamEvents(); if (ev.event === "reasoning_end") { - if (suppressStreamUntilTurnEndRef.current) return; - setMessages((prev) => closeReasoningStream(prev, Date.now())); + if (projectionRef.current.suppressUntilTurnEnd) return; + applyProjectionEvent(ev); return; } @@ -1034,33 +786,7 @@ export function useNanobotStream( } : null; if (modelFailure) setStreamError(modelFailure); - const completedAt = Date.now(); - setMessages((prev) => { - let finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); - const latencyMs = - typeof ev.latency_ms === "number" && ev.latency_ms >= 0 - ? Math.round(ev.latency_ms) - : undefined; - finalized = stampLastAssistantCompletion( - finalized, - { - ...(latencyMs !== undefined ? { latencyMs } : {}), - ...(ev.usage ? { usage: ev.usage } : {}), - ...(ev.round_usages?.length ? { roundUsages: ev.round_usages } : {}), - ...(typeof ev.context_window_tokens === "number" - ? { contextWindowTokens: ev.context_window_tokens } - : {}), - completedAt, - }, - ev.turn_id, - ); - buffer.current = null; - activeAssistantRef.current = null; - clearActivitySegment(); - closedAssistantStreamIdsRef.current.clear(); - return finalized; - }); - suppressStreamUntilTurnEndRef.current = false; + applyProjectionEvent(ev); notifyInBackground( modelFailure ? resolveModelRequestFailureCopy(modelFailure, t).body @@ -1134,193 +860,14 @@ export function useNanobotStream( } if (ev.event === "message") { - if ( - suppressStreamUntilTurnEndRef.current && - (ev.kind === "tool_hint" || ev.kind === "progress" || ev.kind === "reasoning") - ) { - return; - } - // Back-compat: a legacy ``kind: "reasoning"`` message (no streaming - // partner) is treated as one complete delta + immediate end so the - // bubble renders identically to the streaming path. - if (ev.kind === "reasoning") { - const line = ev.text; - if (!line) return; - if (fileEditSegmentRef.current) clearActivitySegment(); - setMessages((prev) => closeReasoningStream( - attachReasoningChunk( - prev, - line, - { ensure: ensureActivitySegmentId }, - turnFieldsFromEvent(ev, "reasoning"), - ), - Date.now(), - )); - return; - } - // Intermediate agent breadcrumbs (tool-call hints, raw progress). - // Attach them to the last trace row if it was the last emitted item - // so a sequence of calls collapses into one compact trace group. - if (ev.kind === "tool_hint" || ev.kind === "progress") { - const structuredEvents = normalizeToolProgressEvents(ev.tool_events); - const turn = turnFieldsFromEvent(ev, "activity"); - setMessages((prev) => { - const segmentId = ensureActivitySegmentId(); - const base = prev; - const visibleStructuredEvents = filterCoveredFileEditToolEvents(base, structuredEvents); - const structuredLines = toolTraceLinesFromEvents(visibleStructuredEvents); - const lines = structuredLines.length > 0 - ? structuredLines - : structuredEvents.length > 0 - ? [] - : ev.text - ? [ev.text] - : []; - if (lines.length === 0) return base; - const last = base[base.length - 1]; - if ( - last - && last.kind === "trace" - && !last.isStreaming - && (!last.activitySegmentId || last.activitySegmentId === segmentId) - ) { - const previousTraces = last.traces?.length - ? last.traces - : last.content - ? [last.content] - : []; - const mergedEvents = visibleStructuredEvents.length > 0 - ? mergeToolProgressEvents(last.toolEvents, visibleStructuredEvents) - : last.toolEvents; - const mergedLines = visibleStructuredEvents.length > 0 - ? mergeToolProgressTraceLines( - previousTraces, - last.toolEvents, - structuredLines, - visibleStructuredEvents, - ) - : null; - const merged: UIMessage = { - ...last, - traces: mergedLines ?? [...previousTraces, ...lines], - content: mergedLines - ? mergedLines[mergedLines.length - 1] - : lines[lines.length - 1], - toolEvents: mergedEvents, - activitySegmentId: last.activitySegmentId ?? segmentId, - ...turn, - }; - return [...base.slice(0, -1), merged]; - } - return [ - ...base, - { - id: crypto.randomUUID(), - role: "tool", - kind: "trace", - content: lines[lines.length - 1], - traces: lines, - ...(visibleStructuredEvents.length ? { toolEvents: visibleStructuredEvents } : {}), - activitySegmentId: segmentId, - ...turn, - createdAt: Date.now(), - }, - ]; - }); - return; - } - - const media = ev.media_urls?.length - ? ev.media_urls.map((m) => toMediaAttachment(m)) - : ev.media?.map((url) => toMediaAttachment({ url })); - const hasMedia = !!media && media.length > 0; - if (sideChannelEvent) { - setMessages((prev) => absorbCompleteAssistantMessage(prev, { - content: ev.text, - ...(hasMedia ? { media } : {}), - ...(ev.source ? { source: ev.source } : {}), - ...turnFieldsFromEvent(ev, "answer"), - })); - if (typeof ev.turn_id === "string") sideChannelTurnIdsRef.current.delete(ev.turn_id); - return; - } - - // A complete (non-streamed) assistant message. If a stream was in - // flight, drop the placeholder so we don't render the text twice. - // ``turn_end`` is the turn boundary. ``stream_end`` only closes the - // current text segment so a following tool/reasoning segment remains - // part of the same live activity surface. - clearActivitySegment(); - setMessages((prev) => { - const activeId = buffer.current?.messageId; - buffer.current = null; - activeAssistantRef.current = null; - const filtered = activeId ? prev.filter((m) => m.id !== activeId) : prev; - const content = ev.text; - const lat = - typeof ev.latency_ms === "number" && ev.latency_ms >= 0 - ? Math.round(ev.latency_ms) - : undefined; - return absorbCompleteAssistantMessage(filtered, { - content, - ...(hasMedia ? { media } : {}), - ...(lat !== undefined ? { latencyMs: lat } : {}), - ...(ev.source ? { source: ev.source } : {}), - ...turnFieldsFromEvent(ev, "answer"), - }); - }); - if (hasMedia) { - suppressStreamUntilTurnEndRef.current = true; + applyProjectionEvent(ev, { sideChannel: sideChannelEvent }); + if (sideChannelEvent && typeof ev.turn_id === "string") { + sideChannelTurnIdsRef.current.delete(ev.turn_id); } return; } if (ev.event === "file_edit") { - const edits = Array.isArray(ev.edits) ? ev.edits : []; - if (edits.length === 0) return; - const normalized = mergeFileEdits(undefined, edits); - if (normalized.length === 0) return; - const turn = turnFieldsFromEvent(ev, "activity"); - const opensFileEditPhase = normalized.some( - (edit) => edit.status === "editing" || edit.phase === "start", - ); - let eventSegmentId = fileEditSegmentRef.current; - if (!eventSegmentId && opensFileEditPhase) { - eventSegmentId = detachedActivitySegmentId(); - fileEditSegmentRef.current = eventSegmentId; - } - setMessages((prev) => { - let segmentId = eventSegmentId; - const base = stripCoveredFileEditToolHintsFromMessages(prev, normalized, turn); - const targetIndex = findFileEditTraceIndex(base, segmentId, normalized); - if (targetIndex !== null) { - const target = base[targetIndex]; - segmentId = target.activitySegmentId ?? segmentId ?? detachedActivitySegmentId(); - if (opensFileEditPhase) fileEditSegmentRef.current = segmentId; - const merged: UIMessage = { - ...target, - fileEdits: mergeFileEdits(target.fileEdits, normalized), - activitySegmentId: segmentId, - ...turn, - }; - return replaceMessageAt(base, targetIndex, merged); - } - segmentId = segmentId ?? detachedActivitySegmentId(); - if (opensFileEditPhase) fileEditSegmentRef.current = segmentId; - return [ - ...base, - { - id: crypto.randomUUID(), - role: "tool", - kind: "trace", - content: "", - traces: [], - fileEdits: normalized, - activitySegmentId: segmentId, - ...turn, - createdAt: Date.now(), - }, - ]; - }); + applyProjectionEvent(ev); return; } }; @@ -1328,21 +875,17 @@ export function useNanobotStream( const unsub = client.onChat(chatId, handle); return () => { unsub(); - buffer.current = null; - activeAssistantRef.current = null; - closedAssistantStreamIdsRef.current.clear(); - clearActivitySegment(); + projectionRef.current = resetThreadProjectionCursor(projectionRef.current); clearPendingStreamWork(); }; }, [ + applyProjectionEvent, applyStreamError, chatId, closeActiveAssistantStream, client, clearActivitySegment, clearPendingStreamWork, - detachedActivitySegmentId, - ensureActivitySegmentId, flushPendingStreamEvents, isSideChannelEvent, notifyInBackground, @@ -1376,29 +919,26 @@ export function useNanobotStream( if (sideChannel) sideChannelTurnIdsRef.current.add(turnId); const previews = hasAttachments ? images!.map((i) => i.preview) : undefined; setMessages((prev) => { + let projection = { ...projectionRef.current, messages: prev }; if ((!sideChannel && !continueActiveTurn) || finalizeActiveTurn) { - buffer.current = null; - activeAssistantRef.current = null; - closedAssistantStreamIdsRef.current.clear(); - clearActivitySegment(); - suppressStreamUntilTurnEndRef.current = false; + projection = resetThreadProjectionCursor(projection, prev); } else if (continueActiveTurn) { // Guidance belongs to the active backend turn. Preserve the answer // cursor so its resuming stream_end can finalize the text already // shown before the new user row, while starting fresh activity after it. - clearActivitySegment(); + projection = clearThreadProjectionActivity(projection); } const base = finalizeActiveTurn ? finalizeStreamedTurn(prev) : prev; - return [ + const next: UIMessage[] = [ ...base, { id: userMessageId, - role: "user", + role: "user" as const, content: outboundContent, turnId, turnPhase: "user", turnSeq: 0, - deliveryStatus: "sending", + deliveryStatus: "sending" as const, createdAt: Date.now(), ...(previews ? { media: previews } : {}), ...(options?.cliApps?.length ? { cliApps: options.cliApps } : {}), @@ -1406,8 +946,10 @@ export function useNanobotStream( ...(options?.sessionMentions?.length ? { sessionMentions: options.sessionMentions } : {}), - }, + }, ]; + projectionRef.current = { ...projection, messages: next }; + return next; }); if (!sideChannel) setIsStreaming(true); const wireMedia = hasAttachments ? images!.map((i) => i.media) : undefined; @@ -1432,13 +974,10 @@ export function useNanobotStream( setIsStreaming(false); setRetryStatus(null); setMessages((prev) => { - buffer.current = null; - activeAssistantRef.current = null; - closedAssistantStreamIdsRef.current.clear(); - clearActivitySegment(); - return prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); + const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); + projectionRef.current = resetThreadProjectionCursor(projectionRef.current, settled); + return settled; }); - suppressStreamUntilTurnEndRef.current = false; setRunStartedAt(null); client.finishRunLocally(chatId); client.sendMessage(chatId, "/stop"); @@ -1446,11 +985,7 @@ export function useNanobotStream( const reconcileTurnComplete = useCallback(() => { clearPendingStreamWork(); - buffer.current = null; - activeAssistantRef.current = null; - closedAssistantStreamIdsRef.current.clear(); - clearActivitySegment(); - suppressStreamUntilTurnEndRef.current = false; + projectionRef.current = resetThreadProjectionCursor(projectionRef.current); setRunStartedAt(null); setRetryStatus(null); setIsStreaming(false); diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.ts index e85300731..7214012a7 100644 --- a/webui/src/hooks/useSessions.ts +++ b/webui/src/hooks/useSessions.ts @@ -11,6 +11,7 @@ import { } from "@/lib/api"; import { hasPendingAgentActivity } from "@/lib/activity-timeline"; import { deriveTitle } from "@/lib/format"; +import { projectThreadEvents } from "@/lib/thread-event-projection"; import { webuiThreadCache } from "@/lib/webui-thread-cache"; import type { ChatSummary, @@ -45,6 +46,30 @@ function persistedMessagesToUi(messages: UIMessage[]): UIMessage[] { })); } +function projectPersistedThread(body: WebuiThreadPersistedPayload | null): { + messages: UIMessage[]; + forkBoundaryMessageCount: number | null; +} { + if (body?.events) { + const messages = projectThreadEvents(body.events); + const boundaryIndex = body.fork_boundary_event_index; + const forkBoundaryMessageCount = typeof boundaryIndex === "number" + && Number.isInteger(boundaryIndex) + && boundaryIndex >= 0 + && boundaryIndex <= body.events.length + ? projectThreadEvents(body.events.slice(0, boundaryIndex)).length + : null; + return { messages, forkBoundaryMessageCount }; + } + const messages = persistedMessagesToUi(body?.messages ?? []); + return { + messages, + forkBoundaryMessageCount: typeof body?.fork_boundary_message_count === "number" + ? Math.max(0, Math.min(body.fork_boundary_message_count, messages.length)) + : null, + }; +} + function sameSemanticMessage(a: UIMessage, b: UIMessage): boolean { return ( a.role === b.role @@ -166,7 +191,8 @@ function cachedHistoryState( body: WebuiThreadPersistedPayload, version: number, ): SessionHistoryState { - const messages = persistedMessagesToUi(body.messages ?? []); + const projected = projectPersistedThread(body); + const messages = projected.messages; return { key, messages, @@ -175,9 +201,7 @@ function cachedHistoryState( error: null, hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages), completedTurnIds: completedTurnIdsFromThread(body), - forkBoundaryMessageCount: typeof body.fork_boundary_message_count === "number" - ? Math.max(0, Math.min(body.fork_boundary_message_count, messages.length)) - : null, + forkBoundaryMessageCount: projected.forkBoundaryMessageCount, beforeCursor: body.page?.before_cursor ?? null, hasMoreBefore: body.page?.has_more_before === true, userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0), @@ -458,11 +482,10 @@ export function useSessionHistory(key: string | null): { historyVersionRef.current += 1; const responseVersion = historyVersionRef.current; const completedTurnIds = completedTurnIdsFromThread(body); - const ui = persistedMessagesToUi(body?.messages ?? []); + const projected = projectPersistedThread(body); + const ui = projected.messages; const hasPending = hasPendingToolCallsFromThread(body, ui); - const forkBoundary = typeof body?.fork_boundary_message_count === "number" - ? Math.max(0, Math.min(body.fork_boundary_message_count, ui.length)) - : null; + const forkBoundary = projected.forkBoundaryMessageCount; setState((prev) => { const merged = prev.key === key ? mergeLatestHistory(prev.messages, ui, prev.lineage === 0) @@ -571,7 +594,8 @@ export function useSessionHistory(key: string | null): { }); setState((prev) => { if (!matchesRequest(prev)) return prev; - if (!body?.messages?.length) { + const projected = projectPersistedThread(body); + if (!body || !projected.messages.length) { return { ...prev, loadingOlder: false, @@ -579,10 +603,8 @@ export function useSessionHistory(key: string | null): { beforeCursor: null, }; } - const older = persistedMessagesToUi(body.messages); - const olderBoundary = typeof body.fork_boundary_message_count === "number" - ? Math.max(0, Math.min(body.fork_boundary_message_count, older.length)) - : null; + const older = projected.messages; + const olderBoundary = projected.forkBoundaryMessageCount; const shiftedBoundary = prev.forkBoundaryMessageCount === null ? null : prev.forkBoundaryMessageCount + older.length; diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index e6c83df7b..ac5db9ce8 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -38,6 +38,7 @@ import type { SlashCommand, SlashCommandLifecycle, TranscriptionSettingsUpdate, + ThreadProjectionEvent, WebSearchSettingsUpdate, WorkspacesPayload, WebuiThreadPersistedPayload, @@ -231,6 +232,134 @@ export interface FetchWebuiThreadOptions { cached?: WebuiThreadPersistedPayload; } +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isRecordArray(value: unknown): value is Array> { + return Array.isArray(value) && value.every(isRecord); +} + +function isProjectionMedia(value: unknown): boolean { + return isRecord(value) + && typeof value.url === "string" + && (value.name === undefined || typeof value.name === "string") + && (value.kind === undefined || ["image", "video", "file"].includes(String(value.kind))); +} + +function hasStringField(value: Record, field: string): boolean { + return typeof value[field] === "string"; +} + +function isProjectionFileEdit(value: unknown): boolean { + return isRecord(value) + && hasStringField(value, "call_id") + && hasStringField(value, "tool") + && hasStringField(value, "path") + && typeof value.added === "number" + && typeof value.deleted === "number" + && ["editing", "done", "error"].includes(String(value.status)); +} + +function hasValidProjectionMetadata(value: Record): boolean { + return ( + (value.projection_id === undefined || typeof value.projection_id === "string") + && (value.created_at_ms === undefined || typeof value.created_at_ms === "number") + && (value.turn_id === undefined || typeof value.turn_id === "string") + && (value.turn_phase === undefined || [ + "user", "reasoning", "activity", "answer", "complete", + ].includes(String(value.turn_phase))) + && (value.turn_seq === undefined || typeof value.turn_seq === "number") + && ( + value.source === undefined + || ( + isRecord(value.source) + && typeof value.source.kind === "string" + && (value.source.label === undefined || typeof value.source.label === "string") + ) + ) + ); +} + +function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent { + if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") { + throw new Error("Invalid WebUI thread event"); + } + if (!hasValidProjectionMetadata(value)) { + throw new Error("Invalid WebUI thread event metadata"); + } + switch (value.event) { + case "user_message": + if (typeof value.text !== "string" || typeof value.starts_turn !== "boolean") break; + if (value.media_urls !== undefined && ( + !Array.isArray(value.media_urls) || !value.media_urls.every(isProjectionMedia) + )) break; + if (value.cli_apps !== undefined && ( + !isRecordArray(value.cli_apps) || !value.cli_apps.every((item) => hasStringField(item, "name")) + )) break; + if (value.mcp_presets !== undefined && ( + !isRecordArray(value.mcp_presets) + || !value.mcp_presets.every((item) => hasStringField(item, "name")) + )) break; + if (value.session_mentions !== undefined && ( + !isRecordArray(value.session_mentions) + || !value.session_mentions.every((item) => ( + hasStringField(item, "name") + && hasStringField(item, "session_key") + && hasStringField(item, "title") + )) + )) break; + if (value.provenance !== undefined && ( + !isRecord(value.provenance) + || !isRecord(value.provenance.session_message) + || !hasStringField(value.provenance.session_message, "message_id") + || !isRecord(value.provenance.session_message.session) + )) break; + return value as unknown as ThreadProjectionEvent; + case "message": + if (typeof value.text !== "string") break; + if (value.tool_events !== undefined && !isRecordArray(value.tool_events)) break; + if (value.media_urls !== undefined && ( + !Array.isArray(value.media_urls) || !value.media_urls.every(isProjectionMedia) + )) break; + return value as unknown as ThreadProjectionEvent; + case "file_edit": + if (!Array.isArray(value.edits) || !value.edits.every(isProjectionFileEdit)) break; + return value as unknown as ThreadProjectionEvent; + case "delta": + case "reasoning_delta": + if (typeof value.text !== "string") break; + return value as unknown as ThreadProjectionEvent; + case "stream_end": + case "reasoning_end": + if (value.text !== undefined && typeof value.text !== "string") break; + return value as unknown as ThreadProjectionEvent; + case "context_compaction": + if (typeof value.compaction_id !== "string" || typeof value.phase !== "string") break; + return value as unknown as ThreadProjectionEvent; + case "turn_end": + return value as unknown as ThreadProjectionEvent; + } + throw new Error(`Invalid WebUI thread projection event: ${value.event}`); +} + +function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayload { + if (!isRecord(value) || typeof value.schemaVersion !== "number") { + throw new Error("Invalid WebUI thread response"); + } + if (value.messages !== undefined && !Array.isArray(value.messages)) { + throw new Error("Invalid WebUI thread messages"); + } + if (value.events !== undefined && !Array.isArray(value.events)) { + throw new Error("Invalid WebUI thread events"); + } + const events = value.events?.map(parseThreadProjectionEvent); + return { + ...value, + ...(events ? { events } : {}), + } as unknown as WebuiThreadPersistedPayload; +} + export async function fetchWebuiThread( token: string, key: string, @@ -243,6 +372,7 @@ export async function fetchWebuiThread( if (options?.limit !== undefined) params.set("limit", String(options.limit)); if (options?.direction) params.set("direction", options.direction); if (options?.before) params.set("before", options.before); + params.set("projection", "events"); const query = params.toString(); const suffix = query ? `?${query}` : ""; const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`; @@ -257,7 +387,7 @@ export async function fetchWebuiThread( if (res.status === 304 && options?.cached) return options.cached; if (res.status === 404) return null; if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`); - return (await res.json()) as WebuiThreadPersistedPayload; + return parseWebuiThreadPayload(await res.json()); } export async function fetchWebuiThreadTraceDetail( diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index 1715129e1..b032d2391 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -1,21 +1,43 @@ -import { toolTraceLinesFromEvents } from "@/lib/tool-traces"; +import { toMediaAttachment } from "@/lib/media"; +import { + mergeToolProgressEvents, + mergeToolProgressTraceLines, + normalizeToolProgressEvents, + toolTraceLinesFromEvents, +} from "@/lib/tool-traces"; import type { + ThreadProjectionEvent, ToolProgressEvent, UIFileEdit, UIMessage, UITurnPhase, } from "@/lib/types"; +export type { ThreadProjectionEvent } from "@/lib/types"; + export type UIMessageTurnFields = Pick; const FILE_EDIT_TOOL_NAMES = new Set(["write_file", "edit_file", "apply_patch"]); -/** - * PR3 projection seam: replay can share these folds once GatewayContext exposes - * an ordered canonical-event sequence and a monotonic per-thread revision. - * Snapshot acceptance and revision comparison stay outside this projection; - * until then, history continues to consume server-projected UIMessage snapshots. - */ +export interface ThreadProjectionState { + messages: UIMessage[]; + activeAssistantId: string | null; + closedAssistantIds: Set; + mergeReasoning: boolean; + activitySegmentId: string | null; + fileEditSegmentId: string | null; + activitySegmentCounter: number; + suppressUntilTurnEnd: boolean; + closedTurnIds: Set; + turnAliases: Map; +} + +export interface ThreadProjectionOptions { + createId: () => string; + now: number; + persisted?: boolean; + sideChannel?: boolean; +} export function turnFieldsFromEvent( ev: { turn_id?: string; turn_phase?: UITurnPhase; turn_seq?: number }, @@ -88,12 +110,13 @@ export function replaceMessageAt( /** Close the active reasoning stream segment. ``now`` is supplied by the caller * so the projection remains deterministic for replay and fixture tests. */ -export function closeReasoningStream(prev: UIMessage[], now: number): UIMessage[] { +export function closeReasoningStream(prev: UIMessage[], now?: number): UIMessage[] { for (let i = prev.length - 1; i >= 0; i -= 1) { const candidate = prev[i]; if (!candidate.reasoningStreaming) continue; const latencyMs = - candidate.latencyMs === undefined + now !== undefined + && candidate.latencyMs === undefined && Number.isFinite(candidate.createdAt) && candidate.createdAt > 1_000_000_000_000 ? Math.max(0, Math.round(now - candidate.createdAt)) @@ -343,3 +366,644 @@ export function finalizeStreamedTurn( : m, ); } + +export function createThreadProjectionState( + messages: UIMessage[] = [], +): ThreadProjectionState { + return { + messages, + activeAssistantId: null, + closedAssistantIds: new Set(), + mergeReasoning: false, + activitySegmentId: null, + fileEditSegmentId: null, + activitySegmentCounter: 0, + suppressUntilTurnEnd: false, + closedTurnIds: new Set(), + turnAliases: new Map(), + }; +} + +export function resetThreadProjectionCursor( + state: ThreadProjectionState, + messages: UIMessage[] = state.messages, +): ThreadProjectionState { + return { + ...createThreadProjectionState(messages), + activitySegmentCounter: state.activitySegmentCounter, + closedTurnIds: new Set(state.closedTurnIds), + turnAliases: new Map(state.turnAliases), + }; +} + +export function clearThreadProjectionActivity( + state: ThreadProjectionState, +): ThreadProjectionState { + return { + ...state, + activitySegmentId: null, + fileEditSegmentId: null, + }; +} + +export function closeThreadProjectionAnswer( + state: ThreadProjectionState, +): ThreadProjectionState { + if (!state.activeAssistantId) return state; + const closedAssistantIds = new Set(state.closedAssistantIds); + closedAssistantIds.add(state.activeAssistantId); + return { + ...state, + activeAssistantId: null, + closedAssistantIds, + mergeReasoning: false, + }; +} + +function projectionCreatedAt(event: ThreadProjectionEvent, options: ThreadProjectionOptions): number { + return typeof event.created_at_ms === "number" && Number.isFinite(event.created_at_ms) + ? event.created_at_ms + : options.now; +} + +function projectionMessageId( + event: ThreadProjectionEvent, + options: ThreadProjectionOptions, +): string { + return typeof event.projection_id === "string" && event.projection_id.length > 0 + ? event.projection_id + : options.createId(); +} + +function turnFieldsForProjection( + state: ThreadProjectionState, + event: ThreadProjectionEvent, + fallbackPhase?: UITurnPhase, +): UIMessageTurnFields { + const fields = turnFieldsFromEvent(event, fallbackPhase); + const rawTurnId = fields.turnId; + if (!rawTurnId || !state.closedTurnIds.has(rawTurnId)) return fields; + let alias = state.turnAliases.get(rawTurnId); + if (!alias) { + const suffix = event.projection_id || event.created_at_ms || state.messages.length; + alias = `${rawTurnId}:replay:${suffix}`; + state.turnAliases.set(rawTurnId, alias); + } + return { ...fields, turnId: alias }; +} + +function ensureProjectionActivitySegment(state: ThreadProjectionState): string { + if (state.activitySegmentId) return state.activitySegmentId; + state.activitySegmentCounter += 1; + state.activitySegmentId = `activity-${state.activitySegmentCounter}`; + return state.activitySegmentId; +} + +function detachedProjectionActivitySegment(state: ThreadProjectionState): string { + state.activitySegmentCounter += 1; + return `activity-${state.activitySegmentCounter}`; +} + +function activeAssistantIndex( + state: ThreadProjectionState, + turn: UIMessageTurnFields, +): number | null { + if (!state.activeAssistantId) return null; + const index = state.messages.findIndex((message) => message.id === state.activeAssistantId); + if (index < 0) { + state.activeAssistantId = null; + state.mergeReasoning = false; + return null; + } + const message = state.messages[index]; + if ( + message.role !== "assistant" + || message.kind === "trace" + || !message.isStreaming + || !matchesTurn(message, turn) + ) { + state.activeAssistantId = null; + state.mergeReasoning = false; + return null; + } + return index; +} + +function appendAnswerText( + state: ThreadProjectionState, + event: Extract, + options: ThreadProjectionOptions, +): void { + const turn = turnFieldsForProjection(state, event, "answer"); + let targetIndex = activeAssistantIndex(state, turn); + if (targetIndex === null) targetIndex = findActiveAssistantPlaceholderIndex(state.messages, turn); + if (targetIndex === null) { + targetIndex = findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn); + } + if (targetIndex === null) { + const id = projectionMessageId(event, options); + state.messages = [ + ...state.messages, + { + id, + role: "assistant", + content: "", + isStreaming: true, + createdAt: projectionCreatedAt(event, options), + }, + ]; + targetIndex = state.messages.length - 1; + } + const target = state.messages[targetIndex]; + const merged: UIMessage = { + ...target, + content: target.content + event.text, + isStreaming: true, + ...turn, + ...(event.source ? { source: event.source } : {}), + }; + state.closedAssistantIds.delete(merged.id); + state.activeAssistantId = merged.id; + state.mergeReasoning = false; + state.messages = replaceMessageAt(state.messages, targetIndex, merged); +} + +function attachProjectedReasoning( + state: ThreadProjectionState, + event: Extract, + text: string, + options: ThreadProjectionOptions, +): void { + const turn = turnFieldsForProjection(state, event, "reasoning"); + const activeAssistantBeforeContinuation = state.activeAssistantId; + const continuationIndex = state.mergeReasoning + ? activeAssistantIndex(state, turn) + : null; + if (continuationIndex !== null) { + const target = state.messages[continuationIndex]; + const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : ""; + state.messages = replaceMessageAt(state.messages, continuationIndex, { + ...target, + reasoning: (target.reasoning ?? "") + separator + text, + reasoningStreaming: true, + }); + return; + } + + if (state.fileEditSegmentId || activeAssistantBeforeContinuation) { + if (activeAssistantBeforeContinuation && !state.activeAssistantId) { + state.closedAssistantIds.add(activeAssistantBeforeContinuation); + } + const closed = closeThreadProjectionAnswer(state); + Object.assign(state, clearThreadProjectionActivity(closed)); + } + for (let index = state.messages.length - 1; index >= 0; index -= 1) { + const candidate = state.messages[index]; + if (candidate.role === "user" || candidate.kind === "trace") break; + if (candidate.role !== "assistant") continue; + if (!matchesTurn(candidate, turn) || candidate.content.length > 0) break; + if (candidate.reasoningStreaming || (candidate.isStreaming && candidate.reasoning === undefined)) { + const activitySegmentId = candidate.activitySegmentId + ?? ensureProjectionActivitySegment(state); + state.messages = replaceMessageAt(state.messages, index, { + ...candidate, + reasoning: (candidate.reasoning ?? "") + text, + reasoningStreaming: true, + activitySegmentId, + ...turn, + }); + return; + } + break; + } + + const activitySegmentId = ensureProjectionActivitySegment(state); + state.messages = [ + ...state.messages, + { + id: projectionMessageId(event, options), + role: "assistant", + content: "", + isStreaming: true, + reasoning: text, + reasoningStreaming: true, + activitySegmentId, + ...turn, + createdAt: projectionCreatedAt(event, options), + }, + ]; +} + +function absorbProjectedAssistantMessage( + state: ThreadProjectionState, + event: Extract, + message: Omit, + options: ThreadProjectionOptions, +): void { + const last = state.messages[state.messages.length - 1]; + if (last && isReasoningOnlyPlaceholder(last) && matchesTurn(last, message)) { + state.messages = [ + ...state.messages.slice(0, -1), + { + ...last, + ...message, + isStreaming: false, + reasoningStreaming: false, + }, + ]; + return; + } + state.messages = [ + ...state.messages, + { + id: projectionMessageId(event, options), + role: "assistant", + createdAt: projectionCreatedAt(event, options), + ...message, + }, + ]; +} + +function projectToolActivity( + state: ThreadProjectionState, + event: Extract, + options: ThreadProjectionOptions, +): void { + Object.assign(state, closeThreadProjectionAnswer(state)); + const structuredEvents = normalizeToolProgressEvents(event.tool_events); + const visibleEvents = filterCoveredFileEditToolEvents(state.messages, structuredEvents); + const structuredLines = toolTraceLinesFromEvents(visibleEvents); + const lines = structuredLines.length > 0 + ? structuredLines + : structuredEvents.length > 0 + ? [] + : event.text + ? [event.text] + : []; + if (lines.length === 0) return; + + const segmentId = ensureProjectionActivitySegment(state); + const turn = turnFieldsForProjection(state, event, "activity"); + const last = state.messages[state.messages.length - 1]; + if ( + last + && last.kind === "trace" + && !last.isStreaming + && (!last.activitySegmentId || last.activitySegmentId === segmentId) + ) { + const previousTraces = last.traces?.length + ? last.traces + : last.content + ? [last.content] + : []; + const mergedEvents = visibleEvents.length > 0 + ? mergeToolProgressEvents(last.toolEvents, visibleEvents) + : last.toolEvents; + const mergedLines = visibleEvents.length > 0 + ? mergeToolProgressTraceLines( + previousTraces, + last.toolEvents, + structuredLines, + visibleEvents, + ) + : null; + state.messages = [ + ...state.messages.slice(0, -1), + { + ...last, + traces: mergedLines ?? [...previousTraces, ...lines], + content: mergedLines + ? mergedLines[mergedLines.length - 1] + : lines[lines.length - 1], + toolEvents: mergedEvents, + activitySegmentId: last.activitySegmentId ?? segmentId, + ...turn, + }, + ]; + return; + } + state.messages = [ + ...state.messages, + { + id: projectionMessageId(event, options), + role: "tool", + kind: "trace", + content: lines[lines.length - 1], + traces: lines, + ...(visibleEvents.length ? { toolEvents: visibleEvents } : {}), + activitySegmentId: segmentId, + ...turn, + createdAt: projectionCreatedAt(event, options), + }, + ]; +} + +function projectFileEdits( + state: ThreadProjectionState, + event: Extract, + options: ThreadProjectionOptions, +): void { + Object.assign(state, closeThreadProjectionAnswer(state)); + const normalized = mergeFileEdits(undefined, event.edits); + if (normalized.length === 0) return; + const turn = turnFieldsForProjection(state, event, "activity"); + const opensPhase = normalized.some( + (edit) => edit.status === "editing" || edit.phase === "start", + ); + let segmentId = state.fileEditSegmentId; + if (!segmentId && opensPhase) { + segmentId = detachedProjectionActivitySegment(state); + state.fileEditSegmentId = segmentId; + } + const base = stripCoveredFileEditToolHintsFromMessages(state.messages, normalized, turn); + const targetIndex = findFileEditTraceIndex(base, segmentId, normalized); + if (targetIndex !== null) { + const target = base[targetIndex]; + segmentId = target.activitySegmentId ?? segmentId ?? detachedProjectionActivitySegment(state); + if (opensPhase) state.fileEditSegmentId = segmentId; + state.messages = replaceMessageAt(base, targetIndex, { + ...target, + fileEdits: mergeFileEdits(target.fileEdits, normalized), + activitySegmentId: segmentId, + ...turn, + }); + return; + } + segmentId = segmentId ?? detachedProjectionActivitySegment(state); + if (opensPhase) state.fileEditSegmentId = segmentId; + state.messages = [ + ...base, + { + id: projectionMessageId(event, options), + role: "tool", + kind: "trace", + content: "", + traces: [], + fileEdits: normalized, + activitySegmentId: segmentId, + ...turn, + createdAt: projectionCreatedAt(event, options), + }, + ]; +} + +/** Canonical UI-message reducer shared by WebSocket delivery and transcript replay. */ +export function projectThreadEvent( + previous: ThreadProjectionState, + event: ThreadProjectionEvent, + options: ThreadProjectionOptions, +): ThreadProjectionState { + const state: ThreadProjectionState = { + ...previous, + closedAssistantIds: new Set(previous.closedAssistantIds), + closedTurnIds: new Set(previous.closedTurnIds), + turnAliases: new Map(previous.turnAliases), + }; + + if (event.event === "user_message") { + if (event.provenance?.session_message) { + const messageId = event.provenance.session_message.message_id?.trim(); + if (!messageId || state.messages.some( + (message) => message.sessionMessage?.message_id === messageId, + )) return state; + } else if (event.turn_id && state.messages.some( + (message) => message.role === "user" && message.turnId === event.turn_id, + )) return state; + if (state.activeAssistantId) { + state.messages = state.messages.map((message) => ( + message.id === state.activeAssistantId ? { ...message, isStreaming: false } : message + )); + } + state.messages = closeReasoningStream( + state.messages, + options.persisted ? undefined : options.now, + ); + Object.assign(state, resetThreadProjectionCursor(state, state.messages)); + const media = event.media_urls?.map((item) => toMediaAttachment(item)); + const turn = turnFieldsForProjection(state, event, "user"); + const row: UIMessage = { + id: projectionMessageId(event, options), + role: "user", + content: event.text, + createdAt: projectionCreatedAt(event, options), + ...turn, + ...(!options.persisted ? { deliveryStatus: "accepted" as const } : {}), + ...(media?.length ? { media } : {}), + ...(event.cli_apps?.length ? { cliApps: event.cli_apps } : {}), + ...(event.mcp_presets?.length ? { mcpPresets: event.mcp_presets } : {}), + ...(event.session_mentions?.length ? { sessionMentions: event.session_mentions } : {}), + ...(event.provenance?.session_message + ? { sessionMessage: event.provenance.session_message } + : {}), + }; + if (media?.length && media.every((item) => item.kind === "image")) { + row.images = media.map(({ url, name }) => ({ url, name })); + } + state.messages = [...state.messages, row]; + return state; + } + + if (event.event === "delta") { + if (!state.suppressUntilTurnEnd && event.text) { + state.activitySegmentId = null; + state.fileEditSegmentId = null; + appendAnswerText(state, event, options); + } + return state; + } + + if (event.event === "stream_end") { + if (state.suppressUntilTurnEnd) return state; + const turn = turnFieldsForProjection(state, event, "answer"); + const mergeNext = event.resuming === true && event.merge_next === true; + let targetIndex = activeAssistantIndex(state, turn); + if (targetIndex === null) { + targetIndex = findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn); + } + if (typeof event.text === "string") { + if (targetIndex === null) { + const id = projectionMessageId(event, options); + state.messages = [ + ...state.messages, + { + id, + role: "assistant", + content: event.text, + isStreaming: true, + ...turn, + ...(event.source ? { source: event.source } : {}), + createdAt: projectionCreatedAt(event, options), + }, + ]; + targetIndex = state.messages.length - 1; + } else { + const target = state.messages[targetIndex]; + state.messages = replaceMessageAt(state.messages, targetIndex, { + ...target, + content: event.text, + isStreaming: true, + ...turn, + ...(event.source ? { source: event.source } : {}), + }); + } + } else if (event.source && targetIndex !== null) { + state.messages = replaceMessageAt(state.messages, targetIndex, { + ...state.messages[targetIndex], + ...turn, + source: event.source, + }); + } + if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id; + state.mergeReasoning = mergeNext && state.activeAssistantId !== null; + if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state)); + return state; + } + + if (event.event === "reasoning_delta") { + if (!state.suppressUntilTurnEnd && event.text) { + attachProjectedReasoning(state, event, event.text, options); + } + return state; + } + + if (event.event === "reasoning_end") { + if (state.suppressUntilTurnEnd) return state; + if (event.text) attachProjectedReasoning(state, event, event.text, options); + state.messages = closeReasoningStream( + state.messages, + options.persisted ? undefined : options.now, + ); + return state; + } + + if (event.event === "context_compaction") { + Object.assign(state, closeThreadProjectionAnswer(state)); + const id = `compaction-${event.compaction_id}`; + const existing = state.messages.findIndex((message) => message.id === id); + const message: UIMessage = { + id, + role: "assistant", + content: "", + kind: "compaction", + createdAt: projectionCreatedAt(event, options), + compaction: { + id: event.compaction_id, + phase: event.phase, + ...(!options.persisted ? { announce: true } : {}), + }, + ...turnFieldsForProjection(state, event, "activity"), + }; + if (existing < 0) state.messages = [...state.messages, message]; + else state.messages = replaceMessageAt(state.messages, existing, { + ...message, + createdAt: state.messages[existing].createdAt, + }); + state.activitySegmentId = null; + state.fileEditSegmentId = null; + return state; + } + + if (event.event === "message") { + if ( + state.suppressUntilTurnEnd + && (event.kind === "tool_hint" || event.kind === "progress" || event.kind === "reasoning") + ) return state; + if (event.kind === "reasoning") { + if (event.text) { + attachProjectedReasoning(state, { + ...event, + event: "reasoning_delta", + }, event.text, options); + state.messages = closeReasoningStream( + state.messages, + options.persisted ? undefined : options.now, + ); + } + return state; + } + if (event.kind === "tool_hint" || event.kind === "progress") { + projectToolActivity(state, event, options); + return state; + } + + const media = event.media_urls?.map((item) => toMediaAttachment(item)) + ?? event.media?.map((url) => toMediaAttachment({ url })); + const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0 + ? Math.round(event.latency_ms) + : undefined; + const projected = { + content: event.text, + ...(media?.length ? { media } : {}), + ...(latencyMs !== undefined ? { latencyMs } : {}), + ...(event.source ? { source: event.source } : {}), + ...turnFieldsForProjection(state, event, "answer"), + }; + if (options.sideChannel) { + absorbProjectedAssistantMessage(state, event, projected, options); + return state; + } + const activeId = state.activeAssistantId; + Object.assign(state, closeThreadProjectionAnswer(state)); + if (activeId) state.messages = state.messages.filter((message) => message.id !== activeId); + absorbProjectedAssistantMessage(state, event, projected, options); + state.activitySegmentId = null; + state.fileEditSegmentId = null; + if (media?.length) state.suppressUntilTurnEnd = true; + return state; + } + + if (event.event === "file_edit") { + projectFileEdits(state, event, options); + return state; + } + + const turn = turnFieldsForProjection(state, event, "complete"); + state.suppressUntilTurnEnd = false; + state.activitySegmentId = null; + state.fileEditSegmentId = null; + state.messages = finalizeStreamedTurn(state.messages); + const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0 + ? Math.round(event.latency_ms) + : undefined; + state.messages = stampLastAssistantCompletion( + state.messages, + { + ...(latencyMs !== undefined ? { latencyMs } : {}), + ...(event.usage ? { usage: event.usage } : {}), + ...(event.round_usages?.length ? { roundUsages: event.round_usages } : {}), + ...(typeof event.context_window_tokens === "number" + ? { contextWindowTokens: event.context_window_tokens } + : {}), + ...(!options.persisted ? { completedAt: options.now } : {}), + }, + turn.turnId, + ); + state.activeAssistantId = null; + state.closedAssistantIds.clear(); + 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); + } + return state; +} + +export function projectThreadEvents(events: ThreadProjectionEvent[]): UIMessage[] { + let state = createThreadProjectionState(); + const fallbackNow = Date.now(); + events.forEach((event, index) => { + state = projectThreadEvent(state, event, { + createId: () => `history-${index}`, + now: typeof event.created_at_ms === "number" + ? event.created_at_ms + : fallbackNow + index, + persisted: true, + }); + }); + return state.messages.map((row) => { + const message = { ...row }; + delete message.isStreaming; + delete message.reasoningStreaming; + return message; + }); +} diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 59fbe05d1..ddc93f5d9 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -1424,6 +1424,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; } & InboundTurnMetadata) | { event: "runtime_model_updated"; @@ -1503,6 +1505,25 @@ export type InboundEvent = turn_id?: string; }; +type ThreadProjectionEventName = + | "user_message" + | "message" + | "file_edit" + | "delta" + | "stream_end" + | "reasoning_delta" + | "reasoning_end" + | "context_compaction" + | "turn_end"; + +export type ThreadProjectionEvent = Extract< + InboundEvent, + { event: ThreadProjectionEventName } +> & { + projection_id?: string; + created_at_ms?: number; +}; + /** Base64-encoded file attached to an outbound ``message`` envelope. * * ``data_url`` must use a server-whitelisted image, video, or document MIME @@ -1542,6 +1563,7 @@ interface WebuiThreadPagePayload { loaded_message_count?: number; total_known_message_count?: number; user_message_offset?: number; + loaded_event_count?: number; } export interface WebuiThreadPersistedPayload { @@ -1550,8 +1572,13 @@ export interface WebuiThreadPersistedPayload { savedAt?: string; /** Cheap server revision used for application-managed conditional revalidation. */ revision?: string; - messages: UIMessage[]; + /** Legacy server-projected snapshots, retained as a compatibility fallback. */ + messages?: UIMessage[]; + /** Canonical transcript events projected by the same reducer as live events. */ + events?: ThreadProjectionEvent[]; + projection?: "events"; fork_boundary_message_count?: number; + fork_boundary_event_index?: number; /** Turn ids backed by an explicit persisted ``turn_end`` event. */ completed_turn_ids?: string[]; has_pending_tool_calls?: boolean; diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index e68d3267a..9c6f32eb4 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -81,7 +81,12 @@ describe("webui API helpers", () => { "fetch", vi.fn().mockResolvedValue({ ok: true, - json: async () => ({ deleted: true, key: "websocket:chat-1", messages: [] }), + json: async () => ({ + schemaVersion: 3, + deleted: true, + key: "websocket:chat-1", + messages: [], + }), }), ); }); @@ -95,7 +100,7 @@ describe("webui API helpers", () => { await fetchWebuiThread("tok", "websocket:chat-1"); expect(fetch).toHaveBeenCalledWith( - "/api/sessions/websocket%3Achat-1/webui-thread", + "/api/sessions/websocket%3Achat-1/webui-thread?projection=events", expect.objectContaining({ headers: { Authorization: "Bearer tok" }, credentials: "same-origin", @@ -111,7 +116,7 @@ describe("webui API helpers", () => { }); expect(fetch).toHaveBeenCalledWith( - "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D", + "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&projection=events", expect.objectContaining({ headers: { Authorization: "Bearer tok" }, credentials: "same-origin", @@ -136,7 +141,7 @@ describe("webui API helpers", () => { })).resolves.toBe(cached); expect(fetch).toHaveBeenCalledWith( - "/api/sessions/websocket%3Achat-1/webui-thread", + "/api/sessions/websocket%3Achat-1/webui-thread?projection=events", expect.objectContaining({ headers: { Authorization: "Bearer tok", @@ -147,6 +152,22 @@ describe("webui API helpers", () => { ); }); + it("rejects malformed canonical thread events at the HTTP boundary", async () => { + vi.mocked(fetch).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ + schemaVersion: 3, + projection: "events", + events: [{ event: "file_edit", chat_id: "chat-1", edits: [{ tool: "edit_file" }] }], + }), + } as Response); + + await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow( + "Invalid WebUI thread projection event: file_edit", + ); + }); + it("fetches deferred trace details with encoded session and ref", async () => { await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef"); diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.ts new file mode 100644 index 000000000..b8c8feaa4 --- /dev/null +++ b/webui/src/tests/thread-event-projection.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; + +import { projectThreadEvents } from "@/lib/thread-event-projection"; +import type { ThreadProjectionEvent, UIMessage } from "@/lib/types"; +import projectionFixture from "./fixtures/live-replay-event-projection.json"; + +interface ProjectionFixtureCase { + name: string; + transcript: Array>; + expected: Array>; +} + +const cases = ( + projectionFixture as unknown as { cases: ProjectionFixtureCase[] } +).cases; + +const SEMANTIC_MESSAGE_FIELDS = [ + "role", + "content", + "kind", + "traces", + "toolEvents", + "fileEdits", + "images", + "media", + "cliApps", + "mcpPresets", + "sessionMentions", + "reasoning", + "latencyMs", + "source", + "turnId", + "turnPhase", + "turnSeq", +] as const satisfies ReadonlyArray; + +function fixtureEvents(records: Array>): ThreadProjectionEvent[] { + return records.flatMap((record, index) => { + if (record.event === "user") { + return [{ + ...record, + event: "user_message" as const, + starts_turn: true, + projection_id: `fixture-${index}`, + } as unknown as ThreadProjectionEvent]; + } + return [{ + ...record, + projection_id: `fixture-${index}`, + } as unknown as ThreadProjectionEvent]; + }); +} + +function normalizeProjection(messages: UIMessage[]): Array> { + const segmentAliases = new Map(); + return messages.map((message) => { + const row: Record = {}; + for (const field of SEMANTIC_MESSAGE_FIELDS) { + const value = message[field]; + if (value !== undefined && value !== null) row[field] = value; + } + if (message.activitySegmentId) { + let alias = segmentAliases.get(message.activitySegmentId); + if (!alias) { + alias = `segment-${segmentAliases.size + 1}`; + segmentAliases.set(message.activitySegmentId, alias); + } + row.activitySegmentId = alias; + } + return row; + }); +} + +describe("canonical thread event projection", () => { + it.each(cases)("projects persisted $name events", (fixtureCase) => { + const messages = projectThreadEvents(fixtureEvents(fixtureCase.transcript)); + expect(normalizeProjection(messages)).toEqual(fixtureCase.expected); + }); +}); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 166650826..257896cf8 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -3539,7 +3539,7 @@ describe("useNanobotStream", () => { }); -describe("live/replay projection before canonical-event revision migration", () => { +describe("live canonical event projection", () => { it.each(PROJECTION_FIXTURE_CASES)("matches the shared $name fixture", (fixtureCase) => { // Keep client-only elapsed-time estimates out of the transport contract. const clock = vi.spyOn(Date, "now").mockReturnValue(0); diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsx index b2940966a..af5feae46 100644 --- a/webui/src/tests/useSessions.test.tsx +++ b/webui/src/tests/useSessions.test.tsx @@ -568,6 +568,75 @@ describe("useSessions", () => { expect(result.current.messages[2]!.content).toBe("summary"); }); + it("projects canonical transcript events with the live event reducer", async () => { + vi.mocked(api.fetchWebuiThread).mockResolvedValue({ + schemaVersion: 3, + projection: "events", + events: [ + { + event: "user_message", + chat_id: "chat-event-history", + text: "explain", + starts_turn: true, + projection_id: "history-user", + turn_id: "turn-history", + turn_phase: "user", + turn_seq: 1, + }, + { + event: "reasoning_delta", + chat_id: "chat-event-history", + text: "thinking", + projection_id: "history-reasoning", + turn_id: "turn-history", + turn_phase: "reasoning", + turn_seq: 2, + }, + { + event: "reasoning_end", + chat_id: "chat-event-history", + projection_id: "history-reasoning-end", + turn_id: "turn-history", + turn_phase: "reasoning", + turn_seq: 3, + }, + { + event: "delta", + chat_id: "chat-event-history", + text: "answer", + projection_id: "history-answer", + turn_id: "turn-history", + turn_phase: "answer", + turn_seq: 4, + }, + { + event: "turn_end", + chat_id: "chat-event-history", + projection_id: "history-end", + latency_ms: 25, + turn_id: "turn-history", + turn_phase: "complete", + turn_seq: 5, + }, + ], + }); + + const { result } = renderHook(() => useSessionHistory("websocket:chat-event-history"), { + wrapper: wrap(fakeClient()), + }); + + await waitFor(() => expect(result.current.loading).toBe(false)); + + expect(result.current.messages).toHaveLength(2); + expect(result.current.messages[1]).toMatchObject({ + role: "assistant", + content: "answer", + reasoning: "thinking", + latencyMs: 25, + turnId: "turn-history", + }); + }); + it("shows a cached transcript immediately while revalidating it", async () => { const cached = { schemaVersion: 3,