Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
refactor(webui): remove legacy message projection (#5823)
chengyongru0983762fe59f
diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.pyindex b624c82a2..b10a636a9 100644--- a/nanobot/channels/websocket/tests/test_websocket_channel.py+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py@@ -93,6 +93,30 @@ from .ws_test_client import http_get as _http_get_PORT = 29876+def _thread_conversation_events(body: dict[str, Any]) -> list[dict[str, Any]]:+ messages: list[dict[str, Any]] = []+ for event in body["events"]:+ name = event.get("event")+ if name == "turn_end":+ if messages and messages[-1]["role"] == "assistant":+ messages[-1]["latencyMs"] = event.get("latency_ms")+ continue+ if name == "user_message":+ role = "user"+ elif name == "message" and event.get("kind") is None:+ role = "assistant"+ elif name == "stream_end" and isinstance(event.get("text"), str):+ role = "assistant"+ else:+ continue+ messages.append({+ "role": role,+ "content": event.get("text", ""),+ "latencyMs": event.get("latency_ms"),+ })+ return messages++def _ch(bus: Any, **kw: Any) -> WebSocketChannel:cfg: dict[str, Any] = {"enabled": True,@@ -915,8 +939,12 @@ async def test_webui_message_envelope_persists_user_transcript_for_refresh(body = build_webui_thread_response("websocket:chat-1")assert body is not None- assert [message["role"] for message in body["messages"]] == ["user", "assistant"]- assert [message["content"] for message in body["messages"]] == ["hello", "hi back"]+ assert [message["role"] for message in _thread_conversation_events(body)] == [+ "user", "assistant",+ ]+ assert [message["content"] for message in _thread_conversation_events(body)] == [+ "hello", "hi back",+ ]@pytest.mark.asyncio@@ -1532,7 +1560,7 @@ async def test_webui_automation_intent_is_hidden_and_not_inherited_by_cron(}) == {"role": "user", "content": original}body = build_webui_thread_response("websocket:chat-automation")assert body is not None- assert [message["content"] for message in body["messages"]] == [original]+ assert [message["content"] for message in _thread_conversation_events(body)] == [original]store_path = tmp_path / "cron" / "jobs.json"cron = CronService(store_path)@@ -2650,7 +2678,7 @@ async def test_send_delta_keeps_buffer_across_merged_stream_boundary() -> None:assert [line["text"] for line in lines] == ["first ", "first second"]body = build_webui_thread_response("websocket:chat-1")assert body is not None- assert body["messages"][-1]["content"] == "first second"+ assert _thread_conversation_events(body)[-1]["content"] == "first second"@pytest.mark.asyncio@@ -2848,9 +2876,9 @@ async def test_stream_transcript_persists_without_subscribers() -> None:assert lines[0]["text"] == "hello world"body = build_webui_thread_response("websocket:chat-1")assert body is not None- assert body["messages"][-1]["role"] == "assistant"- assert body["messages"][-1]["content"] == "hello world"- assert body["messages"][-1]["latencyMs"] == 42+ assert _thread_conversation_events(body)[-1]["role"] == "assistant"+ assert _thread_conversation_events(body)[-1]["content"] == "hello world"+ assert _thread_conversation_events(body)[-1]["latencyMs"] == 42@pytest.mark.asyncio@@ -3370,7 +3398,10 @@ async def test_durable_incomplete_marker_stays_pending_without_safe_session_recoassert body is not Noneassert read_transcript_lines(key)[-1]["transcript_incomplete"] is Trueassert body["completed_turn_ids"] == []- assert [(message["role"], message["content"]) for message in body["messages"]] == [+ assert [+ (message["role"], message["content"])+ for message in _thread_conversation_events(body)+ ] == [("user", "question"),]assert body["has_pending_tool_calls"] is True@@ -3482,7 +3513,10 @@ async def test_http_replay_recovers_marked_answer_from_session_after_gateway_resassert response.status_code == 200body = json.loads(response.body.decode())- assert [(message["role"], message["content"]) for message in body["messages"]] == [+ assert [+ (message["role"], message["content"])+ for message in _thread_conversation_events(body)+ ] == [("user", "question"),("assistant", "durable answer"),]@@ -5617,9 +5651,9 @@ def test_handle_webui_thread_get_returns_json(tmp_path, monkeypatch) -> None:assert resp.status_code == 200body = json.loads(resp.body.decode())assert body["sessionKey"] == key- assert len(body["messages"]) == 1- assert body["messages"][0]["role"] == "user"- assert body["messages"][0]["content"] == "hi"+ assert len(_thread_conversation_events(body)) == 1+ assert _thread_conversation_events(body)[0]["role"] == "user"+ assert _thread_conversation_events(body)[0]["content"] == "hi"assert body["has_pending_tool_calls"] is False@@ -5785,7 +5819,7 @@ def test_handle_webui_thread_get_reports_registered_turn_as_pending(assert resp.status_code == 200body = json.loads(resp.body.decode())- assert body["messages"][0]["content"] == "hi"+ assert _thread_conversation_events(body)[0]["content"] == "hi"assert body["has_pending_tool_calls"] is True@@ -5988,7 +6022,7 @@ def test_handle_webui_thread_get_reconciles_registered_turn_with_turn_end(assert resp.status_code == 200body = json.loads(resp.body.decode())- assert body["messages"][-1]["content"] == "done"+ assert _thread_conversation_events(body)[-1]["content"] == "done"assert body["has_pending_tool_calls"] is expected_pendingassert body["active_turn_id"] == active_turn_id@@ -6027,7 +6061,9 @@ def test_handle_webui_thread_get_accepts_pagination_query(tmp_path, monkeypatch)assert resp.status_code == 200body = json.loads(resp.body.decode())- assert [message["content"] for message in body["messages"]] == ["q3", "a3"]+ assert [message["content"] for message in _thread_conversation_events(body)] == [+ "q3", "a3",+ ]assert body["page"]["has_more_before"] is Trueassert body["page"]["before_cursor"]@@ -6037,7 +6073,7 @@ def test_handle_webui_thread_get_accepts_pagination_query(tmp_path, monkeypatch)[],[{"provider": "xai", "model": "grok", "preset": "saved backup", "fallback": True}],])-def test_handle_webui_thread_get_negotiates_client_event_projection(+def test_handle_webui_thread_get_returns_canonical_events_by_default(tmp_path,monkeypatch,sources,@@ -6068,7 +6104,7 @@ def test_handle_webui_thread_get_negotiates_client_event_projection(channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300.0encoded = quote(key, safe="")request = Request(- f"/api/sessions/{encoded}/webui-thread?projection=events",+ f"/api/sessions/{encoded}/webui-thread",Headers([("Authorization", "Bearer tok")]),)@@ -6304,8 +6340,10 @@ def test_handle_webui_thread_get_backfills_legacy_missing_user_rows(assert resp.status_code == 200body = json.loads(resp.body.decode())- assert [message["role"] for message in body["messages"]] == ["user", "assistant"]- assert [message["content"] for message in body["messages"]] == [+ assert [message["role"] for message in _thread_conversation_events(body)] == [+ "user", "assistant",+ ]+ assert [message["content"] for message in _thread_conversation_events(body)] == ["legacy question","legacy answer",]@@ -6353,8 +6391,10 @@ def test_handle_webui_thread_get_does_not_backfill_cron_internal_prompt(assert resp.status_code == 200body = json.loads(resp.body.decode())- assert [message["role"] for message in body["messages"]] == ["assistant"]- assert [message["content"] for message in body["messages"]] == ["提醒已经到期。"]+ assert [message["role"] for message in _thread_conversation_events(body)] == ["assistant"]+ assert [message["content"] for message in _thread_conversation_events(body)] == [+ "提醒已经到期。",+ ]def test_handle_webui_thread_get_does_not_backfill_trigger_internal_prompt(@@ -6399,8 +6439,10 @@ def test_handle_webui_thread_get_does_not_backfill_trigger_internal_prompt(assert resp.status_code == 200body = json.loads(resp.body.decode())- assert [message["role"] for message in body["messages"]] == ["assistant"]- assert [message["content"] for message in body["messages"]] == ["PR #4502 已经开始 review。"]+ assert [message["role"] for message in _thread_conversation_events(body)] == ["assistant"]+ assert [message["content"] for message in _thread_conversation_events(body)] == [+ "PR #4502 已经开始 review。",+ ]def test_handle_webui_thread_get_does_not_backfill_hidden_subagent_result(@@ -6445,5 +6487,7 @@ def test_handle_webui_thread_get_does_not_backfill_hidden_subagent_result(assert resp.status_code == 200body = json.loads(resp.body.decode())- assert [message["role"] for message in body["messages"]] == ["assistant"]- assert [message["content"] for message in body["messages"]] == ["subagent summary"]+ assert [message["role"] for message in _thread_conversation_events(body)] == ["assistant"]+ assert [message["content"] for message in _thread_conversation_events(body)] == [+ "subagent summary",+ ]diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.pyindex bbfde53a9..8d11b403a 100644--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py@@ -331,7 +331,14 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_filassert [row["key"] for row in listing.json()["sessions"]] == [key]assert listing.json()["sessions"][0]["preview"] == "original question"assert thread.status_code == 200- assert [message["content"] for message in thread.json()["messages"]] == [+ body = thread.json()+ assert body["projection"] == "events"+ assert "messages" not in body+ assert [+ event["text"]+ for event in body["events"]+ if event["event"] in {"user_message", "message", "stream_end"}+ ] == ["original question","original answer",]@@ -3152,8 +3159,11 @@ async def test_webui_thread_resigns_assistant_media_urls(headers=auth,)assert resp.status_code == 200- assistant = next(m for m in resp.json()["messages"] if m["role"] == "assistant")- media = assistant["media"]+ body = resp.json()+ assert body["projection"] == "events"+ assert "messages" not in body+ assistant = next(event for event in body["events"] if event["event"] == "message")+ media = assistant["media_urls"]assert media[0]["kind"] == "video"assert media[0]["name"] == "clip.mp4"assert media[0]["url"].startswith("/api/media/")@@ -3164,10 +3174,10 @@ async def test_webui_thread_resigns_assistant_media_urls(headers=auth,)repeated_assistant = next(- m for m in repeated.json()["messages"] if m["role"] == "assistant"+ event for event in repeated.json()["events"] if event["event"] == "message")- assert repeated_assistant["id"] == assistant["id"]- assert repeated_assistant["media"][0]["url"] == media[0]["url"]+ assert repeated_assistant["projection_id"] == assistant["projection_id"]+ assert repeated_assistant["media_urls"][0]["url"] == media[0]["url"]assert len(list(websocket_media.iterdir())) == 1fetched = await _http_get(f"http://127.0.0.1:29914{media[0]['url']}")@@ -3243,7 +3253,10 @@ async def test_webui_thread_complete_transcript_skips_session_history_read()assert response.status_code == 200- assert [message["content"] for message in response.json()["messages"]] == [+ body = response.json()+ assert body["projection"] == "events"+ assert "messages" not in body+ assert [event["text"] for event in body["events"] if "text" in event] == ["hi","hello back",]@@ -3290,7 +3303,9 @@ async def test_webui_thread_negotiates_gzip_for_large_payloads(assert compressed.headers["Content-Encoding"] == "gzip"assert compressed.headers["Vary"] == "Accept-Encoding"assert int(compressed.headers["Content-Length"]) < len(compressed.content)- assert compressed.json()["messages"][0]["content"].startswith("compress me")+ assert compressed.json()["projection"] == "events"+ assert "messages" not in compressed.json()+ assert compressed.json()["events"][0]["text"].startswith("compress me")identity = await _http_get(url,@@ -3348,10 +3363,12 @@ async def test_webui_thread_revalidates_and_loads_large_trace_details(assert first.status_code == 200assert first.headers["Cache-Control"] == "no-store"assert first.headers["ETag"] == f'"{first.json()["revision"]}"'- trace_message = next(- message for message in first.json()["messages"] if message.get("kind") == "trace"+ assert first.json()["projection"] == "events"+ assert "messages" not in first.json()+ trace_event = next(+ event for event in first.json()["events"] if event.get("kind") == "progress")- assert trace_message["content"] == "exec(…)"+ assert trace_event["text"] == "exec(…)"unchanged = await _http_get(url,@@ -3363,11 +3380,12 @@ async def test_webui_thread_revalidates_and_loads_large_trace_details(detail = await _http_get(f"http://127.0.0.1:{port}/api/sessions/""websocket%3Arevalidated-thread/webui-thread/trace-detail"- f"?ref={trace_message['traceDetail']['ref']}",+ f"?ref={trace_event['trace_detail']['ref']}",headers=auth,)assert detail.status_code == 200- assert detail.json()["content"] == trace+ assert detail.json()["message_id"] == trace_event["projection_id"]+ assert detail.json()["events"][0]["text"] == traceappend_transcript_object(key,diff --git a/nanobot/webui/session_access.py b/nanobot/webui/session_access.pyindex ba935972a..8e24f8d76 100644--- a/nanobot/webui/session_access.py+++ b/nanobot/webui/session_access.py@@ -87,6 +87,71 @@ def _visible_messages(raw_messages: object) -> list[SessionMessage]:return visible+def _visible_projection_events(raw_events: object) -> list[SessionMessage]:+ """Extract searchable conversation text from the event protocol.++ This is intentionally narrower than the WebUI projector: session tools+ expose only user and assistant answer text, never reasoning or activity.+ """+ if not isinstance(raw_events, list):+ return []+ visible: list[SessionMessage] = []+ stream_parts: list[str] = []+ stream_timestamp: str | int | None = None++ def append(role: str, text: object, timestamp: object) -> None:+ content = text.strip() if isinstance(text, str) else ""+ if not content:+ return+ visible.append({+ "message_index": len(visible),+ "role": role,+ "timestamp": timestamp if isinstance(timestamp, (str, int)) else None,+ "content": content,+ })++ def flush_stream(final_text: object = None) -> None:+ nonlocal stream_timestamp+ text = final_text if isinstance(final_text, str) else "".join(stream_parts)+ append("assistant", text, stream_timestamp)+ stream_parts.clear()+ stream_timestamp = None++ for raw_event in cast(list[object], raw_events):+ if not isinstance(raw_event, dict):+ continue+ event = cast(dict[str, Any], raw_event)+ name = event.get("event")+ timestamp = event.get("created_at_ms")+ if name == "user_message":+ flush_stream()+ append("user", event.get("text"), timestamp)+ elif name == "delta":+ text = event.get("text")+ if isinstance(text, str):+ if not stream_parts:+ stream_timestamp = timestamp if isinstance(timestamp, (str, int)) else None+ stream_parts.append(text)+ elif name == "stream_end":+ if event.get("resuming") is True and event.get("merge_next") is True:+ text = event.get("text")+ if isinstance(text, str):+ stream_parts[:] = [text]+ continue+ flush_stream(event.get("text"))+ elif name == "message":+ kind = event.get("kind")+ if kind in {"tool_hint", "progress", "reasoning"}:+ flush_stream()+ continue+ flush_stream()+ append("assistant", event.get("text"), timestamp)+ elif name in {"reasoning_delta", "reasoning_end", "file_edit", "turn_end"}:+ flush_stream()+ flush_stream()+ return visible++def _text(value: object) -> str:return value.strip()[:160] if isinstance(value, str) else ""@@ -152,13 +217,16 @@ class WebuiSessionAccess:if before is None:return matching(load_session_messages())[-limit:]break- raw_messages = thread.get("messages")- if isinstance(raw_messages, list):- page_messages = cast(list[object], raw_messages)+ raw_events = thread.get("events")+ if isinstance(raw_events, list):+ page_messages = _visible_projection_events(cast(list[object], raw_events))message_count += len(page_messages)remaining = limit - len(matches)if remaining > 0:- page_matches = matching(page_messages)[-remaining:]+ page_matches = [+ message for message in page_messages+ if not needle or needle in message["content"].casefold()+ ][-remaining:]for message in page_matches:# Index relative to the conversation's end until we# know the total number of raw messages across pages.diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.pyindex 734387d4a..78912424c 100644--- a/nanobot/webui/transcript.py+++ b/nanobot/webui/transcript.py@@ -41,16 +41,13 @@ _MAX_TRANSCRIPT_PAGE_LIMIT = 1000_MAX_TRANSCRIPT_PAGE_RECORDS = 4_000_MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024_MAX_INLINE_TRACE_DETAIL_BYTES = 32 * 1024-_MAX_DEFERRED_TRACE_SUMMARY_ROWS = 16-_MAX_DEFERRED_TOOL_EVENT_SUMMARY_ROWS = 8_MANIFEST_REBUILD_LOCKS = tuple(threading.Lock() for _ in range(32))_ACTIVE_TRANSCRIPTS_WITH_DELTAS: set[str] = set()_WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")_WEBUI_REPLAY_IDENTITY_KEY = "_webui_replay_identity"-_WEBUI_TRACE_DETAIL_REF_KEY = "_webui_trace_detail_ref"_WEBUI_TRACE_DETAIL_UNSAFE_KEY = "_webui_trace_detail_unsafe"_WEBUI_TRACE_DETAIL_REF_RE = re.compile(- r"^(?P<turn>\d{1,12})\.(?P<message>tr-[0-9a-f]{16}(?:-\d+)?)$"+ r"^(?P<turn>\d{1,12})\.(?P<message>history-[0-9a-f]{20})$")_MARKDOWN_LOCAL_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)"@@ -69,11 +66,6 @@ _INLINE_MARKDOWN_VIDEO_EXTS: frozenset[str] = frozenset({".webm",})_INLINE_MARKDOWN_MEDIA_EXTS = _INLINE_MARKDOWN_IMAGE_EXTS | _INLINE_MARKDOWN_VIDEO_EXTS-_FILE_EDIT_TOOL_NAMES: frozenset[str] = frozenset({- "write_file",- "edit_file",- "apply_patch",-})_TURN_DISPLAY_EVENTS: frozenset[str] = frozenset({"reasoning_delta","reasoning_end",@@ -262,6 +254,13 @@ class _SessionBackfillTurn(NamedTuple):assistant_records: tuple[dict[str, Any], ...]+class _DeferredTraceGroup(NamedTuple):+ start: int+ stop: int+ detail_bytes: int+ trace_count: int++@dataclass(slots=True)class TranscriptReplayStats:"""Bounded, non-sensitive diagnostics for one history replay."""@@ -939,7 +938,6 @@ 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()@@ -951,7 +949,7 @@ def _select_transcript_page(before_ordinal = _decode_page_cursor(before)upper_ordinal = total_turns if before_ordinal is None else min(before_ordinal, total_turns)selected: list[_TranscriptTurnRef] = []- selected_message_count = 0+ selected_event_count = 0selected_record_count = 0selected_bytes = 0budget_reached = False@@ -984,7 +982,6 @@ 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))@@ -1021,15 +1018,10 @@ def _select_transcript_page(selected.append(_TranscriptTurnRef(ordinal, turn, trace_details_safe))selected_record_count += turn_record_countselected_bytes += turn_bytes- 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:+ selected_event_count += _client_projection_page_event_count(turn)+ if selected_event_count >= page_limit:break- if selected_message_count >= page_limit or budget_reached:+ if selected_event_count >= page_limit or budget_reached:breakselected_chronological = list(reversed(selected))@@ -1048,7 +1040,7 @@ def _select_transcript_page(return [], {"before_cursor": None,"has_more_before": False,- "loaded_message_count": 0,+ "loaded_event_count": 0,"user_message_offset": 0,}@@ -1057,7 +1049,7 @@ def _select_transcript_page(page = {"before_cursor": _encode_page_cursor(first_ref.ordinal) if has_more else None,"has_more_before": has_more,- "loaded_message_count": 0,+ "loaded_event_count": 0,"user_message_offset": _count_user_messages_before_ordinal(session_key,chunks,@@ -1731,13 +1723,40 @@ def _ensure_replay_identities(lines: list[dict[str, Any]]) -> list[dict[str, Anydef _transcript_turn_signature(records: list[dict[str, Any]]) -> tuple[str, ...]:+ """Return durable assistant answer texts used only for backfill matching."""texts: list[str] = []- for message in replay_transcript_to_ui_messages(records):- if message.get("role") != "assistant" or message.get("kind") == "trace":- continue- text = _assistant_text_signature(message.get("content"))- if text:- texts.append(text)+ stream_parts: list[str] = []++ def flush_stream(final_text: object = None) -> None:+ text = final_text if isinstance(final_text, str) else "".join(stream_parts)+ if signature := _assistant_text_signature(text):+ texts.append(signature)+ stream_parts.clear()++ for record in records:+ event = record.get("event")+ if event == "delta":+ chunk = record.get("text")+ if isinstance(chunk, str):+ stream_parts.append(chunk)+ elif event == "stream_end":+ final_text = record.get("text")+ if record.get("resuming") is True and record.get("merge_next") is True:+ if isinstance(final_text, str):+ stream_parts[:] = [final_text]+ continue+ flush_stream(final_text)+ elif event == "message" and record.get("kind") not in {+ "tool_hint",+ "progress",+ "reasoning",+ }:+ flush_stream()+ if signature := _assistant_text_signature(record.get("text")):+ texts.append(signature)+ elif event in {"user", "reasoning_delta", "reasoning_end", "turn_end"}:+ flush_stream()+ flush_stream()return tuple(texts)@@ -1933,13 +1952,10 @@ def tool_trace_lines_from_events(events: Any) -> list[str]:return lines-_PHASE_RANK = {"start": 1, "end": 2, "error": 3}--def _normalize_tool_events(events: Any) -> list[dict[str, Any]]:if not isinstance(events, list):return []- out: list[dict[str, Any]] = []+ normalized: list[dict[str, Any]] = []for event in cast(list[Any], events):if not event or not isinstance(event, dict):continue@@ -1947,177 +1963,14 @@ def _normalize_tool_events(events: Any) -> list[dict[str, Any]]:if tool_event.get("phase") not in {"start", "end", "error"}:continueif not isinstance(tool_event.get("name"), str):- fn = tool_event.get("function")- function = cast(dict[str, Any], fn) if isinstance(fn, dict) else None- if function is None or not isinstance(function.get("name"), str):+ function = tool_event.get("function")+ if not isinstance(function, dict):continue- out.append(tool_event)- return out---def _tool_event_key(event: dict[str, Any]) -> str:- call_id = event.get("call_id")- if isinstance(call_id, str) and call_id:- return f"call:{call_id}"- return _format_tool_call_trace(event) or json.dumps(event, sort_keys=True, ensure_ascii=False)---def _tool_event_file_edit_key(event: dict[str, Any]) -> str | None:- call_id = event.get("call_id")- if not isinstance(call_id, str) or not call_id:- return None- name = event.get("name")- if not isinstance(name, str) or not name:- fn = event.get("function")- function = cast(dict[str, Any], fn) if isinstance(fn, dict) else None- name = function.get("name") if function is not None else ""- if not isinstance(name, str) or name not in _FILE_EDIT_TOOL_NAMES:- return None- return f"{call_id}|{name}"---def _merge_tool_events(previous: Any, incoming: list[dict[str, Any]]) -> list[dict[str, Any]]:- if not isinstance(previous, list) or not previous:- return incoming- if not incoming:- return [- cast(dict[str, Any], event)- for event in cast(list[Any], previous)- if isinstance(event, dict)- ]- merged = [- cast(dict[str, Any], event)- for event in cast(list[Any], previous)- if isinstance(event, dict)- ]- index_by_key = {_tool_event_key(event): idx for idx, event in enumerate(merged)}- for event in incoming:- key = _tool_event_key(event)- existing_index = index_by_key.get(key)- if existing_index is None:- index_by_key[key] = len(merged)- merged.append(event)- continue- existing = merged[existing_index]- incoming_rank = _PHASE_RANK.get(str(event.get("phase")), 0)- existing_rank = _PHASE_RANK.get(str(existing.get("phase")), 0)- if incoming_rank >= existing_rank:- merged[existing_index] = {**existing, **event}- return merged---def _file_edit_key(edit: dict[str, Any]) -> str:- call_id = str(edit.get("call_id") or "")- tool = str(edit.get("tool") or "")- path = str(edit.get("path") or "")- if call_id and path:- return f"{call_id}|{tool}|{path}"- if call_id:- return f"{call_id}|{tool}"- return f"{tool}|{path}"---def _file_edit_tool_event_key(edit: dict[str, Any]) -> str:- call_id = str(edit.get("call_id") or "")- tool = str(edit.get("tool") or "")- if call_id:- return f"{call_id}|{tool}"- return _file_edit_key(edit)---def _message_has_file_edit_for_tool_event(- message: dict[str, Any],- event: dict[str, Any],-) -> bool:- key = _tool_event_file_edit_key(event)- if not key:- return False- edits = message.get("fileEdits")- if not isinstance(edits, list):- return False- return any(- _file_edit_tool_event_key(cast(dict[str, Any], edit)) == key- for edit in cast(list[Any], edits)- if isinstance(edit, dict)- )---def _filter_covered_file_edit_tool_events(- messages: list[dict[str, Any]],- events: list[dict[str, Any]],-) -> list[dict[str, Any]]:- if not events:- return events- return [- event- for event in events- if not any(_message_has_file_edit_for_tool_event(message, event) for message in messages)- ]---def _strip_covered_file_edit_tool_hints(- message: dict[str, Any],- edits: list[dict[str, Any]],-) -> dict[str, Any]:- incoming_keys = {- _file_edit_tool_event_key(edit)- for edit in edits- }- events = message.get("toolEvents")- if not incoming_keys or not isinstance(events, list):- return message-- kept_events: list[dict[str, Any]] = []- removed_trace_lines: set[str] = set()- changed = False- for event in cast(list[Any], events):- if not isinstance(event, dict):- continue- tool_event = cast(dict[str, Any], event)- key = _tool_event_file_edit_key(tool_event)- if key and key in incoming_keys:- changed = True- removed_trace_lines.update(tool_trace_lines_from_events([tool_event]))- continue- kept_events.append(tool_event)- if not changed:- return message-- raw_traces = message.get("traces")- if isinstance(raw_traces, list):- previous_traces = [- trace for trace in cast(list[Any], raw_traces) if isinstance(trace, str)- ]- else:- content = message.get("content")- previous_traces = [content] if isinstance(content, str) and content else []- next_traces = [trace for trace in previous_traces if trace not in removed_trace_lines]- next_message = {- **message,- "traces": next_traces,- "content": next_traces[-1] if next_traces else "",- }- if kept_events:- next_message["toolEvents"] = kept_events- else:- next_message.pop("toolEvents", None)- return next_message---def _merge_unique_tool_trace_lines(- previous_traces: list[str],- lines: list[str],-) -> tuple[list[str], bool]:- seen_lines = set(previous_traces)- traces = list(previous_traces)- added = False- for line in lines:- if line in seen_lines:- continue- seen_lines.add(line)- traces.append(line)- added = True- return traces, added+ typed_function = cast(dict[str, Any], function)+ if not isinstance(typed_function.get("name"), str):+ continue+ normalized.append(tool_event)+ return normalizeddef _media_from_signed_urls(value: Any) -> list[dict[str, Any]]:@@ -2163,938 +2016,6 @@ def _trace_summary(line: str) -> str:return f"{_truncate_utf8(match.group(1), 240)}(…)" if match else _truncate_utf8(line, 240)-def _defer_large_trace_details(messages: list[dict[str, Any]]) -> None:- for message in messages:- if message.get("kind") != "trace":- continue- detail = {- key: message[key]- for key in ("content", "traces", "toolEvents")- if key in message- }- detail_bytes = len(_record_json_line(detail).encode("utf-8"))- detail_ref = message.get(_WEBUI_TRACE_DETAIL_REF_KEY)- if detail_bytes <= _MAX_INLINE_TRACE_DETAIL_BYTES:- continue-- content = message.get("content")- traces = message.get("traces")- if isinstance(content, str):- message["content"] = _trace_summary(content)- if isinstance(traces, list):- message["traces"] = [- _trace_summary(trace)- for trace in cast(list[Any], traces)[-_MAX_DEFERRED_TRACE_SUMMARY_ROWS:]- if isinstance(trace, str)- ]- events = message.get("toolEvents")- if isinstance(events, list):- summarized_events: list[dict[str, Any]] = []- for item in cast(list[Any], events)[-_MAX_DEFERRED_TOOL_EVENT_SUMMARY_ROWS:]:- if not isinstance(item, dict):- continue- event = cast(dict[str, Any], item)- summarized_events.append(- {- key: _truncate_utf8(value, 512)- for key in ("call_id", "name", "phase", "error")- if isinstance((value := event.get(key)), str)- }- )- message["toolEvents"] = summarized_events- trace_count = len(cast(list[Any], traces)) if isinstance(traces, list) else int(bool(content))- if isinstance(detail_ref, str):- message["traceDetail"] = {- "ref": detail_ref,- "bytes": detail_bytes,- "traceCount": trace_count,- }---def replay_transcript_to_ui_messages(- lines: list[dict[str, Any]],- *,- augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,- augment_assistant_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,- augment_assistant_text: Callable[[str], str] | None = None,- defer_trace_details: bool = False,-) -> list[dict[str, Any]]:- """Fold JSONL records into ``UIMessage``-shaped dicts for the WebUI.-- Mirrors the core fold in ``useNanobotStream.ts`` (delta, reasoning,- message+kind, turn_end). ``augment_user_media`` maps persisted filesystem- paths to ``{url, name?}`` / attachment dicts the client expects. Assistant- media gets a separate hook so replay can re-sign outbound attachments after- a gateway restart instead of reusing stale process-local signed URLs.- """- messages: list[dict[str, Any]] = []- buffer_message_id: str | None = None- buffer_parts: list[str] = []- merge_reasoning_message_id: str | None = None- suppress_until_turn_end = False- active_activity_segment_id: str | None = None- active_file_edit_segment_id: str | None = None- activity_segment_counter = 0- _ts_base = _now_ms()- closed_turn_ids: set[str] = set()- replay_turn_aliases: dict[str, str] = {}- generated_id_occurrences: dict[str, int] = {}-- def _new_id(prefix: str, idx: int) -> str:- record = lines[idx] if 0 <= idx < len(lines) else {}- identity = record.get(_WEBUI_REPLAY_IDENTITY_KEY)- if not isinstance(identity, str) or not identity:- identity = f"direct:{idx}:{_stable_record_digest(record)}"- digest = hashlib.sha256(f"{prefix}\0{identity}".encode("utf-8")).hexdigest()[:16]- base = f"{prefix}-{digest}"- occurrence = generated_id_occurrences.get(base, 0)- generated_id_occurrences[base] = occurrence + 1- return base if occurrence == 0 else f"{base}-{occurrence}"-- def _created_at_ms(rec: dict[str, Any], idx: int) -> int:- created_at_ms = _valid_created_at_ms(rec.get("created_at_ms"))- if created_at_ms is not None:- return created_at_ms- return _ts_base + idx-- def _new_activity_segment(*, activate: bool = True) -> str:- nonlocal active_activity_segment_id, activity_segment_counter- activity_segment_counter += 1- segment_id = f"activity-{activity_segment_counter}"- if activate:- active_activity_segment_id = segment_id- return segment_id-- def _turn_fields(rec: dict[str, Any], fallback_phase: str | None = None) -> dict[str, Any]:- fields: dict[str, Any] = {}- turn_id = rec.get("turn_id")- if isinstance(turn_id, str) and turn_id:- if turn_id in closed_turn_ids:- fields["turnId"] = replay_turn_aliases.setdefault(- turn_id,- f"{turn_id}:replay:{idx}",- )- else:- fields["turnId"] = turn_id- phase = rec.get("turn_phase")- if isinstance(phase, str) and phase:- fields["turnPhase"] = phase- elif fallback_phase:- fields["turnPhase"] = fallback_phase- seq = rec.get("turn_seq")- if isinstance(seq, (int, float)):- fields["turnSeq"] = int(seq)- return fields-- def _source_fields(rec: dict[str, Any]) -> dict[str, Any]:- out: dict[str, Any] = {}- if "response_sources" in rec:- out["responseSources"] = _response_sources(rec["response_sources"])- source = rec.get("source")- if not isinstance(source, dict):- return out- source_data = cast(dict[str, Any], source)- kind = source_data.get("kind")- if not isinstance(kind, str) or not is_automation_kind(kind):- return out- out["source"] = {"kind": kind}- label = source_data.get("label")- if isinstance(label, str) and label.strip():- out["source"]["label"] = label.strip()- return out-- def _same_turn(message: dict[str, Any], turn_fields: dict[str, Any]) -> bool:- turn_id = turn_fields.get("turnId")- message_turn_id = message.get("turnId")- return not turn_id or not message_turn_id or turn_id == message_turn_id-- def _ensure_activity_segment() -> str:- return active_activity_segment_id or _new_activity_segment()-- def close_activity_for_answer() -> None:- nonlocal active_activity_segment_id, active_file_edit_segment_id- active_activity_segment_id = None- active_file_edit_segment_id = None-- def close_file_edit_phase_before_activity() -> None:- nonlocal active_activity_segment_id, active_file_edit_segment_id- if active_file_edit_segment_id:- active_activity_segment_id = None- active_file_edit_segment_id = None-- def attach_reasoning_chunk(- prev: list[dict[str, Any]],- chunk: str,- idx: int,- turn_fields: dict[str, Any] | None = None,- created_at_ms: int | None = None,- ) -> None:- turn_fields = turn_fields or {}- if buffer_message_id is not None and buffer_message_id == merge_reasoning_message_id:- for i in range(len(prev) - 1, -1, -1):- candidate = prev[i]- if candidate.get("id") != buffer_message_id:- continue- if _same_turn(candidate, turn_fields):- # A length continuation shares the same Markdown answer.- # Keep its reasoning with that answer, including on replay.- reasoning = str(candidate.get("reasoning") or "")- separator = "\n\n" if reasoning and not candidate.get("reasoningStreaming") else ""- prev[i] = {- **candidate,- "reasoning": reasoning + separator + chunk,- "reasoningStreaming": True,- }- return- break- if buffer_message_id is not None:- close_interrupted_assistant()- close_activity_for_answer()- for i in range(len(prev) - 1, -1, -1):- candidate = prev[i]- if candidate.get("role") == "user":- break- if candidate.get("kind") == "trace":- break- if candidate.get("role") != "assistant":- continue- if not _same_turn(candidate, turn_fields):- break- content = str(candidate.get("content") or "")- has_answer = len(content) > 0- if has_answer:- break- # A completed reasoning field is closed even while its assistant- # placeholder remains streaming for the rest of the turn.- if (- candidate.get("reasoningStreaming")- or (- candidate.get("isStreaming")- and candidate.get("reasoning") is None- )- ):- prev[i] = {- **candidate,- "reasoning": (str(candidate.get("reasoning") or "")) + chunk,- "reasoningStreaming": True,- "activitySegmentId": candidate.get("activitySegmentId") or _ensure_activity_segment(),- **turn_fields,- }- return- break- segment = _ensure_activity_segment()- prev.append(- {- "id": _new_id("as", idx),- "role": "assistant",- "content": "",- "isStreaming": True,- "reasoning": chunk,- "reasoningStreaming": True,- "activitySegmentId": segment,- **turn_fields,- "createdAt": created_at_ms if created_at_ms is not None else _ts_base + idx,- },- )-- def find_active_placeholder(- prev: list[dict[str, Any]],- turn_fields: dict[str, Any] | None = None,- ) -> str | None:- turn_fields = turn_fields or {}- last = prev[-1] if prev else None- if not last:- return None- if last.get("role") != "assistant" or last.get("kind") == "trace":- return None- if str(last.get("content") or ""):- return None- if not last.get("isStreaming"):- return None- if not _same_turn(last, turn_fields):- return None- return str(last.get("id"))-- def close_interrupted_assistant() -> None:- """Close an answer before a new activity phase without changing its semantics.-- The wire protocol already marks answer, reasoning, and activity phases.- A later tool event does not turn previously emitted answer text into- reasoning; preserving ``content`` also keeps live and replay projections- equivalent.- """- nonlocal buffer_message_id, buffer_parts- for i in range(len(messages) - 1, -1, -1):- candidate = messages[i]- if candidate.get("role") == "user":- break- content = candidate.get("content")- if (- candidate.get("role") != "assistant"- or candidate.get("kind") == "trace"- or not candidate.get("isStreaming")- or not isinstance(content, str)- or not content.strip()- or candidate.get("media")- ):- continue- messages[i] = {**candidate, "isStreaming": False}- if buffer_message_id == candidate.get("id"):- buffer_message_id = None- buffer_parts = []- return-- def close_buffer_from_other_turn(turn_fields: dict[str, Any]) -> None:- nonlocal buffer_message_id, buffer_parts- if buffer_message_id is None:- return- for message in reversed(messages):- if message.get("id") != buffer_message_id:- continue- if not _same_turn(message, turn_fields):- message["isStreaming"] = False- buffer_message_id = None- buffer_parts = []- close_activity_for_answer()- return-- def close_reasoning(prev: list[dict[str, Any]]) -> None:- for i in range(len(prev) - 1, -1, -1):- if prev[i].get("reasoningStreaming"):- prev[i] = {**prev[i], "reasoningStreaming": False}- return-- def is_reasoning_only_placeholder(m: dict[str, Any]) -> bool:- return (- m.get("role") == "assistant"- and m.get("kind") != "trace"- and not str(m.get("content") or "").strip()- and bool(m.get("reasoning"))- and not m.get("reasoningStreaming")- and not m.get("media")- )-- def stamp_completion(- *,- latency_ms: int | None = None,- usage: dict[str, int] | None = None,- round_usages: list[dict[str, int]] | None = None,- context_window_tokens: int | None = None,- ) -> None:- for i in range(len(messages) - 1, -1, -1):- if messages[i].get("role") == "assistant" and messages[i].get("kind") != "trace":- completion: dict[str, Any] = {"isStreaming": False}- if latency_ms is not None:- completion["latencyMs"] = latency_ms- if usage:- completion["usage"] = usage- if round_usages:- completion["roundUsages"] = round_usages- if context_window_tokens is not None:- completion["contextWindowTokens"] = context_window_tokens- messages[i] = {- **messages[i],- **completion,- }- return-- def absorb_complete(extra: dict[str, Any], idx: int, created_at_ms: int) -> None:- nonlocal active_activity_segment_id, active_file_edit_segment_id- last = messages[-1] if messages else None- if last and is_reasoning_only_placeholder(last) and _same_turn(last, extra):- messages[-1] = {- **last,- **extra,- "isStreaming": False,- "reasoningStreaming": False,- }- else:- messages.append(- {- "id": _new_id("as", idx),- "role": "assistant",- "createdAt": created_at_ms,- **extra,- },- )- active_activity_segment_id = None- active_file_edit_segment_id = None-- def find_file_edit_trace_index(- segment: str | None,- edits: list[dict[str, Any]],- ) -> int | None:- incoming_keys = {_file_edit_key(edit) for edit in edits}- incoming_tool_event_keys = {- _file_edit_tool_event_key(edit)- for edit in edits- }- for i in range(len(messages) - 1, -1, -1):- candidate = messages[i]- if candidate.get("role") == "user":- break- if candidate.get("kind") != "trace":- continue- if segment and candidate.get("activitySegmentId") == segment:- return i- existing_edits = candidate.get("fileEdits")- if isinstance(existing_edits, list):- for existing in cast(list[Any], existing_edits):- if not isinstance(existing, dict):- continue- existing_edit = cast(dict[str, Any], existing)- if (- _file_edit_key(existing_edit) in incoming_keys- or (- not existing_edit.get("path")- and existing_edit.get("pending")- and _file_edit_tool_event_key(existing_edit) in incoming_tool_event_keys- )- ):- return i- return None-- def trace_message_is_empty(message: dict[str, Any]) -> bool:- traces = message.get("traces")- if isinstance(traces, list):- has_trace = any(- isinstance(trace, str) and trace.strip()- for trace in cast(list[Any], traces)- )- else:- has_trace = bool(str(message.get("content") or "").strip())- return (- message.get("kind") == "trace"- and not has_trace- and not message.get("toolEvents")- and not message.get("fileEdits")- and not message.get("media")- )-- def strip_covered_file_edit_tool_hints_from_recent_messages(- edits: list[dict[str, Any]],- turn_fields: dict[str, Any],- ) -> None:- nonlocal messages- if not edits:- return- next_messages = list(messages)- changed = False- for i in range(len(next_messages) - 1, -1, -1):- candidate = next_messages[i]- if candidate.get("role") == "user":- break- if candidate.get("kind") != "trace":- continue- if not _same_turn(candidate, turn_fields):- continue- cleaned = _strip_covered_file_edit_tool_hints(candidate, edits)- if cleaned is candidate:- continue- changed = True- if trace_message_is_empty(cleaned):- next_messages.pop(i)- else:- next_messages[i] = cleaned- if changed:- messages = next_messages-- def upsert_file_edits(- edits: list[dict[str, Any]],- idx: int,- turn_fields: dict[str, Any] | None = None,- created_at_ms: int | None = None,- ) -> None:- nonlocal active_file_edit_segment_id- turn_fields = turn_fields or {}- if not edits:- return- segment = active_file_edit_segment_id- if not segment:- segment = _new_activity_segment(activate=False)- active_file_edit_segment_id = segment- close_interrupted_assistant()- strip_covered_file_edit_tool_hints_from_recent_messages(edits, turn_fields)- target_index = find_file_edit_trace_index(segment, edits)- if target_index is not None:- last = messages[target_index]- segment = str(last.get("activitySegmentId") or segment or _new_activity_segment(activate=False))- active_file_edit_segment_id = segment- else:- if not segment:- segment = _new_activity_segment(activate=False)- active_file_edit_segment_id = segment- message_id = _new_id("tr", idx)- messages.append(- {- "id": message_id,- "role": "tool",- "kind": "trace",- "content": "",- "traces": [],- "fileEdits": [],- _WEBUI_TRACE_DETAIL_REF_KEY: _trace_detail_ref(message_id, lines[idx]),- "activitySegmentId": segment,- **turn_fields,- "createdAt": created_at_ms if created_at_ms is not None else _ts_base + idx,- },- )- target_index = len(messages) - 1- last = messages[target_index]- if not segment:- segment = _new_activity_segment(activate=False)- active_file_edit_segment_id = segment- raw_existing: Any = last.get("fileEdits") or []- existing: list[Any] = list(cast(list[Any], raw_existing)) if isinstance(raw_existing, list) else []- index_by_key = {- _file_edit_key(cast(dict[str, Any], edit)): pos- for pos, edit in enumerate(existing)- if isinstance(edit, dict)- }- for edit in edits:- key = _file_edit_key(edit)- pos = index_by_key.get(key)- if pos is None and edit.get("path"):- event_key = _file_edit_tool_event_key(edit)- for existing_pos, existing_edit in enumerate(existing):- if (- isinstance(existing_edit, dict)- and not cast(dict[str, Any], existing_edit).get("path")- and cast(dict[str, Any], existing_edit).get("pending")- and _file_edit_tool_event_key(cast(dict[str, Any], existing_edit)) == event_key- ):- pos = existing_pos- break- if pos is not None:- merged = {**existing[pos], **edit}- if edit.get("path") and not edit.get("pending"):- merged.pop("pending", None)- existing[pos] = merged- index_by_key[key] = pos- else:- index_by_key[key] = len(existing)- existing.append(dict(edit))- messages[target_index] = {- **last,- "fileEdits": existing,- "activitySegmentId": last.get("activitySegmentId") or segment,- **turn_fields,- }-- for idx, rec in enumerate(lines):- ev = rec.get("event")- if ev == "user":- if buffer_message_id is not None:- for message_index, message in enumerate(messages):- if message.get("id") == buffer_message_id:- messages[message_index] = {- **message,- "isStreaming": False,- }- break- buffer_message_id = None- buffer_parts = []- close_reasoning(messages)- active_activity_segment_id = None- active_file_edit_segment_id = None- text = rec.get("text")- text_s = text if isinstance(text, str) else ""- media_paths = rec.get("media_paths")- paths: list[str] = []- if isinstance(media_paths, list):- paths = [str(p) for p in cast(list[Any], media_paths) if p]- media_att: list[dict[str, Any]] | None = None- if paths and augment_user_media is not None:- media_att = augment_user_media(paths)- row: dict[str, Any] = {- "id": _new_id("u", idx),- "role": "user",- "content": text_s,- **_turn_fields(rec, "user"),- "createdAt": _created_at_ms(rec, idx),- }- if media_att:- row["media"] = media_att- if all(m.get("kind") == "image" for m in media_att):- row["images"] = [{"url": m.get("url"), "name": m.get("name")} for m in media_att]- cli_apps = rec.get("cli_apps")- if isinstance(cli_apps, list) and cli_apps:- row["cliApps"] = [- dict(cast(dict[str, Any], app)) for app in cast(list[Any], cli_apps) if isinstance(app, dict)- ]- mcp_presets = rec.get("mcp_presets")- if isinstance(mcp_presets, list) and mcp_presets:- row["mcpPresets"] = [- dict(cast(dict[str, Any], preset))- for preset in cast(list[Any], mcp_presets)- if isinstance(preset, dict)- ]- session_mentions = normalize_session_mentions_metadata(- rec.get("session_mentions")- )- if session_mentions:- row["sessionMentions"] = session_mentions- if session_message := normalize_session_message_ui_metadata(- rec.get("session_message")- ):- row["sessionMessage"] = session_message- messages.append(row)- continue-- if ev == "file_edit":- raw_edits = rec.get("edits")- if isinstance(raw_edits, list):- upsert_file_edits(- [cast(dict[str, Any], e) for e in cast(list[Any], raw_edits) if isinstance(e, dict)],- idx,- _turn_fields(rec, "activity"),- _created_at_ms(rec, idx),- )- continue-- if ev == "delta":- if suppress_until_turn_end:- continue- chunk = rec.get("text")- if not isinstance(chunk, str):- continue- close_activity_for_answer()- turn_fields = _turn_fields(rec, "answer")- source_fields = _source_fields(rec)- close_buffer_from_other_turn(turn_fields)- adopted = find_active_placeholder(messages, turn_fields) if buffer_message_id is None else None- if buffer_message_id is None:- if adopted:- buffer_message_id = adopted- else:- buffer_message_id = _new_id("buf", idx)- messages.append(- {- "id": buffer_message_id,- "role": "assistant",- "content": "",- "isStreaming": True,- **turn_fields,- **source_fields,- "createdAt": _created_at_ms(rec, idx),- },- )- buffer_parts.append(chunk)- combined = "".join(buffer_parts)- for i, m in enumerate(messages):- if m.get("id") == buffer_message_id:- messages[i] = {- **m,- "content": combined,- "isStreaming": True,- **turn_fields,- **source_fields,- }- break- continue-- if ev == "stream_end":- if suppress_until_turn_end:- buffer_message_id = None- buffer_parts = []- continue- merge_next = rec.get("resuming") is True and rec.get("merge_next") is True- final_text = rec.get("text")- turn_fields = _turn_fields(rec, "answer")- source_fields = _source_fields(rec)- close_buffer_from_other_turn(turn_fields)- if isinstance(final_text, str):- if buffer_message_id is None:- buffer_message_id = find_active_placeholder(messages, turn_fields)- if buffer_message_id is None:- buffer_message_id = _new_id("buf", idx)- messages.append({- "id": buffer_message_id,- "role": "assistant",- "content": "",- "isStreaming": True,- "createdAt": _created_at_ms(rec, idx),- })- for i, m in enumerate(messages):- if m.get("id") == buffer_message_id:- messages[i] = {- **m,- "content": final_text,- "isStreaming": True,- **turn_fields,- **source_fields,- }- break- if merge_next:- buffer_parts = [final_text]- elif source_fields and buffer_message_id is not None:- for i, m in enumerate(messages):- if m.get("id") == buffer_message_id:- messages[i] = {- **m,- **turn_fields,- **source_fields,- }- break- if not merge_next:- buffer_message_id = None- buffer_parts = []- merge_reasoning_message_id = buffer_message_id if merge_next else None- continue-- if ev == "reasoning_delta":- if suppress_until_turn_end:- continue- chunk = rec.get("text")- if not isinstance(chunk, str) or not chunk:- continue- close_file_edit_phase_before_activity()- attach_reasoning_chunk(- messages,- chunk,- idx,- _turn_fields(rec, "reasoning"),- _created_at_ms(rec, idx),- )- continue-- if ev == "reasoning_end":- if suppress_until_turn_end:- continue- text = rec.get("text")- if isinstance(text, str) and text:- close_file_edit_phase_before_activity()- attach_reasoning_chunk(- messages,- text,- idx,- _turn_fields(rec, "reasoning"),- _created_at_ms(rec, idx),- )- close_reasoning(messages)- continue-- if ev == "context_compaction":- compaction_id = rec.get("compaction_id")- phase = rec.get("phase")- if (- not isinstance(compaction_id, str)- or not compaction_id- or phase not in {"started", "succeeded", "failed", "cancelled"}- ):- continue- compaction: dict[str, Any] = {- "id": compaction_id,- "phase": phase,- }- payload: dict[str, Any] = {- "id": f"compaction-{compaction_id}",- "role": "assistant",- "content": "",- "kind": "compaction",- "createdAt": _created_at_ms(rec, idx),- "compaction": compaction,- **_turn_fields(rec, "activity"),- }- existing = next(- (- message_index- for message_index, message in enumerate(messages)- if message.get("id") == payload["id"]- ),- None,- )- if existing is None:- messages.append(payload)- else:- payload["createdAt"] = messages[existing].get(- "createdAt",- payload["createdAt"],- )- messages[existing] = payload- active_activity_segment_id = None- active_file_edit_segment_id = None- continue-- if ev == "message":- if suppress_until_turn_end and rec.get("kind") in (- "tool_hint",- "progress",- "reasoning",- ):- continue- kind = rec.get("kind")- if kind == "reasoning":- line = rec.get("text")- if not isinstance(line, str) or not line:- continue- close_file_edit_phase_before_activity()- attach_reasoning_chunk(- messages,- line,- idx,- _turn_fields(rec, "reasoning"),- _created_at_ms(rec, idx),- )- close_reasoning(messages)- continue- if kind in ("tool_hint", "progress"):- structured_events = _normalize_tool_events(rec.get("tool_events"))- visible_structured_events = _filter_covered_file_edit_tool_events(messages, structured_events)- structured = tool_trace_lines_from_events(visible_structured_events)- text = rec.get("text")- if structured:- trace_lines = structured- elif structured_events:- trace_lines = []- elif isinstance(text, str) and text:- trace_lines = [text]- else:- trace_lines = []- if not trace_lines:- continue- segment = _ensure_activity_segment()- close_interrupted_assistant()- last = messages[-1] if messages else None- if (- last- and last.get("kind") == "trace"- and not last.get("isStreaming")- and (last.get("activitySegmentId") in (None, segment))- ):- prev_traces = [- trace- for trace in cast(list[Any], last.get("traces") or [last.get("content")])- if isinstance(trace, str)- ]- if structured:- merged_traces, added = _merge_unique_tool_trace_lines(prev_traces, structured)- if not added and not visible_structured_events:- continue- else:- merged_traces = prev_traces + trace_lines- merged = {- **last,- "traces": merged_traces,- "content": merged_traces[-1],- "toolEvents": _merge_tool_events(last.get("toolEvents"), visible_structured_events)- if visible_structured_events- else last.get("toolEvents"),- "activitySegmentId": last.get("activitySegmentId") or segment,- **_turn_fields(rec, "activity"),- }- messages[-1] = merged- else:- message_id = _new_id("tr", idx)- messages.append(- {- "id": message_id,- "role": "tool",- "kind": "trace",- "content": trace_lines[-1],- "traces": trace_lines,- **({"toolEvents": visible_structured_events} if visible_structured_events else {}),- _WEBUI_TRACE_DETAIL_REF_KEY: _trace_detail_ref(message_id, rec),- "activitySegmentId": segment,- **_turn_fields(rec, "activity"),- "createdAt": _created_at_ms(rec, idx),- },- )- continue-- buffer_message_id = None- buffer_parts = []- text = rec.get("text")- content_s = text if isinstance(text, str) else ""- media: list[dict[str, Any]] = []- raw_media = rec.get("media")- raw_media_list = cast(list[Any], raw_media) if isinstance(raw_media, list) else []- media_paths = [path for path in raw_media_list if isinstance(path, str) and path]- if media_paths and augment_assistant_media is not None:- media = augment_assistant_media(media_paths)- if not media and (not media_paths or augment_assistant_media is None):- media = _media_from_signed_urls(rec.get("media_urls"))- extra: dict[str, Any] = {"content": content_s}- if media:- extra["media"] = media- lat = rec.get("latency_ms")- if isinstance(lat, (int, float)) and lat >= 0:- extra["latencyMs"] = int(lat)- extra.update(_turn_fields(rec, "answer"))- extra.update(_source_fields(rec))- absorb_complete(extra, idx, _created_at_ms(rec, idx))- if media:- suppress_until_turn_end = True- continue-- if ev == "turn_end":- suppress_until_turn_end = False- active_activity_segment_id = None- active_file_edit_segment_id = None- turn_id = rec.get("turn_id")- if isinstance(turn_id, str) and turn_id:- if turn_id in replay_turn_aliases:- replay_turn_aliases.pop(turn_id, None)- else:- closed_turn_ids.add(turn_id)- for i, m in enumerate(messages):- if m.get("isStreaming"):- messages[i] = {**m, "isStreaming": False}- lat = rec.get("latency_ms")- usage = rec.get("usage")- sanitized_usage = _sanitize_turn_usage(usage)- raw_round_usages = rec.get("round_usages")- sanitized_round_usages = (- [- sanitized- for item in cast(list[object], raw_round_usages)- if (sanitized := _sanitize_turn_usage(item))- is not None- ]- if isinstance(raw_round_usages, list)- else None- )- context_window = rec.get("context_window_tokens")- stamp_completion(- latency_ms=int(lat) if isinstance(lat, (int, float)) and lat >= 0 else None,- usage=sanitized_usage,- round_usages=sanitized_round_usages,- context_window_tokens=(- int(context_window)- if isinstance(context_window, (int, float)) and context_window >= 0- else None- ),- )- buffer_message_id = None- buffer_parts = []- continue-- if defer_trace_details:- _defer_large_trace_details(messages)- for i, m in enumerate(messages):- if (- augment_assistant_text is not None- and m.get("role") == "assistant"- and m.get("kind") != "trace"- and isinstance(m.get("content"), str)- ):- messages[i] = {**m, "content": augment_assistant_text(m["content"])}- m = messages[i]- m.pop("isStreaming", None)- m.pop("reasoningStreaming", None)- m.pop(_WEBUI_TRACE_DETAIL_REF_KEY, None)- return messages---def fork_boundary_message_count(lines: list[dict[str, Any]]) -> int | None:- """Return the replayed UI message count before the first fork marker, if any."""- for idx, rec in enumerate(lines):- if rec.get("event") != WEBUI_FORK_MARKER_EVENT:- continue- return len(replay_transcript_to_ui_messages(lines[:idx]))- return None--def has_pending_tool_calls(lines: list[dict[str, Any]],*,@@ -3181,7 +2102,7 @@ def build_webui_trace_detail_response(session_key: str,detail_ref: str,) -> dict[str, Any] | None:- """Resolve one deferred trace from its stable turn ordinal and replay id."""+ """Resolve one deferred activity group as canonical projection events."""match = _WEBUI_TRACE_DETAIL_REF_RE.fullmatch(detail_ref)if match is None:return None@@ -3192,17 +2113,23 @@ def build_webui_trace_detail_response(return Noneturn, _ = _compact_completed_stream_deltas(turn)lines = _records_with_replay_identity(turn, turn_ordinal=ordinal)- for message in replay_transcript_to_ui_messages(lines):- if message.get("id") != message_id or message.get("kind") != "trace":+ for group in _client_projection_deferred_trace_groups(lines).values():+ first = lines[group.start]+ if _client_projection_event_id(first) != message_id:continue- return {- "message_id": message_id,- **{- key: message[key]- for key in ("content", "traces", "toolEvents")- if key in message- },- }+ events = [+ event+ for record in lines[group.start:group.stop]+ if (+ event := _client_projection_event(+ record,+ augment_user_media=None,+ augment_assistant_media=None,+ augment_assistant_text=None,+ )+ ) is not None+ ]+ return {"message_id": message_id, "events": events}return None@@ -3408,88 +2335,75 @@ def _client_projection_event(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_deferred_trace_groups(+ lines: list[dict[str, Any]],+) -> dict[int, _DeferredTraceGroup]:+ """Group oversized consecutive activity events behind one stable detail ref."""+ groups: dict[int, _DeferredTraceGroup] = {}+ start: int | None = None+ detail_bytes = 0+ trace_count = 0++ def flush(stop: int) -> None:+ nonlocal start, detail_bytes, trace_count+ if (+ start is not None+ and detail_bytes > _MAX_INLINE_TRACE_DETAIL_BYTES+ ):+ groups[start] = _DeferredTraceGroup(+ start=start,+ stop=stop,+ detail_bytes=detail_bytes,+ trace_count=max(1, trace_count),+ )+ start = None+ detail_bytes = 0+ trace_count = 0++ for index, record in enumerate(lines):+ is_activity = (+ record.get("event") == "message"+ and record.get("kind") in {"tool_hint", "progress"}+ )+ if not is_activity:+ flush(index)+ continue+ event = _client_projection_event(+ record,+ augment_user_media=None,+ augment_assistant_media=None,+ augment_assistant_text=None,+ )+ if event is None:+ flush(index)+ continue+ if start is None:+ start = index+ detail_bytes += len(_record_json_line(event).encode("utf-8"))+ tool_events = _normalize_tool_events(record.get("tool_events"))+ traces = tool_trace_lines_from_events(tool_events)+ if traces:+ trace_count += len(traces)+ elif not tool_events and isinstance(record.get("text"), str) and record["text"]:+ trace_count += 1+ flush(len(lines))+ return groups+++def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int:+ """Apply the soft page limit in canonical protocol events, not UI rows."""+ supported = {+ "user",+ "delta",+ "stream_end",+ "reasoning_delta",+ "reasoning_end",+ "message",+ "file_edit",+ "context_compaction",+ "turn_end",+ }+ return max(1, sum(record.get("event") in supported for record in turn))def _client_projection_events(@@ -3501,7 +2415,11 @@ def _client_projection_events() -> tuple[list[dict[str, Any]], int | None]:events: list[dict[str, Any]] = []fork_boundary_event_index: int | None = None- for record in lines:+ deferred_groups = _client_projection_deferred_trace_groups(lines)+ deferred_until = 0+ for index, record in enumerate(lines):+ if index < deferred_until:+ continueif record.get("event") == WEBUI_FORK_MARKER_EVENT:if fork_boundary_event_index is None:fork_boundary_event_index = len(events)@@ -3512,8 +2430,29 @@ def _client_projection_events(augment_assistant_media=augment_assistant_media,augment_assistant_text=augment_assistant_text,)- if event is not None:- events.append(event)+ if event is None:+ continue+ group = deferred_groups.get(index)+ if group is not None:+ detail_ref = _trace_detail_ref(_client_projection_event_id(record), record)+ last_text = next(+ (+ text+ for grouped in reversed(lines[group.start:group.stop])+ if isinstance((text := grouped.get("text")), str) and text+ ),+ "",+ )+ event["text"] = _trace_summary(last_text)+ event.pop("tool_events", None)+ if detail_ref is not None:+ event["trace_detail"] = {+ "ref": detail_ref,+ "bytes": group.detail_bytes,+ "traceCount": group.trace_count,+ }+ deferred_until = group.stop+ events.append(event)return events, fork_boundary_event_index@@ -3531,19 +2470,15 @@ 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``."""+ """Return canonical transcript events for the WebUI projector."""replay_stats = stats or TranscriptReplayStats()lines, page = _select_transcript_page(session_key,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@@ -3576,38 +2511,18 @@ def build_webui_thread_response(),"active_turn_id": active_turn_id,}- # 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)+ replay_started = time.perf_counter()+ 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,)- 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+ replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000)+ 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_indexpayload["page"] = pagereturn payloaddiff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex c34af8f83..51ccdea78 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -1001,9 +1001,6 @@ 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,@@ -1031,7 +1028,6 @@ 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),@@ -1066,7 +1062,6 @@ 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/agent/test_response_source.py b/tests/agent/test_response_source.pyindex 65746ff41..cef4fb474 100644--- a/tests/agent/test_response_source.py+++ b/tests/agent/test_response_source.py@@ -24,8 +24,8 @@ from nanobot.providers.fallback_provider import FallbackProviderfrom nanobot.utils.llm_runtime import LLMRuntimefrom nanobot.webui.transcript import (WebUITranscriptRecorder,+ append_transcript_object,build_webui_thread_response,- replay_transcript_to_ui_messages,webui_transcript_path,)@@ -64,7 +64,13 @@ def delivery(chat="chat", *, streaming=True):@pytest.mark.parametrize("streaming", [False, True])@pytest.mark.parametrize("failures", [0, 1, 2, 3])-async def test_actual_candidate_is_delivered_and_replayed(streaming, failures):+async def test_actual_candidate_is_delivered_and_replayed(+ streaming,+ failures,+ tmp_path,+ monkeypatch,+):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)bus, turn = delivery(streaming=streaming)candidates = [AnswerProvider(f"provider-{i}", fail=i < failures,@@ -104,16 +110,29 @@ async def test_actual_candidate_is_delivered_and_replayed(streaming, failures):recorder.prepare_event("chat", record, metadata=msg.metadata, phase="answer", include_source=True)records.append(record)# Completed segment is the durable record; token-sized deltas aren't needed on replay.- replay = replay_transcript_to_ui_messages([r for r in records if r["event"] != "delta"])+ for record in (r for r in records if r["event"] != "delta"):+ append_transcript_object("websocket:chat", record)+ replay = build_webui_thread_response("websocket:chat")if failures == 3:assert all(not r.get("response_sources") for r in records)- assert all(not r.get("responseSources") for r in replay)+ if replay is None:+ return+ replayed_answers = [+ event for event in replay["events"]+ if event["event"] in {"message", "stream_end"}+ ]+ assert all(not event.get("response_sources") for event in replayed_answers)else:+ assert replay is not None+ replayed_answers = [+ event for event in replay["events"]+ if event["event"] in {"message", "stream_end"}+ ]expected = [{"provider": f"provider-{failures}", "model": "same-model","preset": ["chosen", "backup-one", "backup-two"][failures],"fallback": failures > 0}]assert all(r.get("response_sources") == expected for r in records)- assert replay[-1]["responseSources"] == expected+ assert replayed_answers[-1]["response_sources"] == expectedasync def test_fallback_flag_is_call_scoped_even_with_identical_identity():@@ -280,8 +299,9 @@ def test_factory_captures_names_even_when_models_and_settings_are_identical():assert make_provider(config)._fallback_preset_names == ("renamed",)-def test_old_history_and_malformed_identity_are_not_guessed():- messages = replay_transcript_to_ui_messages([+def test_old_history_and_malformed_identity_are_not_guessed(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ records = [{"event": "message", "text": "legacy"},{"event": "message", "text": "invalid", "response_sources": [{"model": "gpt"}]},{"event": "message", "text": "recorded", "response_sources": [@@ -290,12 +310,17 @@ def test_old_history_and_malformed_identity_are_not_guessed():{"event": "message", "text": "invalid flag", "response_sources": [{"provider": "xai", "model": "grok", "preset": "old name", "fallback": "true"},]},- ])- assert "responseSources" not in messages[0]- assert messages[1]["responseSources"] == []+ ]+ for record in records:+ append_transcript_object("websocket:source-history", record)+ replay = build_webui_thread_response("websocket:source-history")+ assert replay is not None+ events = replay["events"]+ assert "response_sources" not in events[0]+ assert events[1]["response_sources"] == []expected = [{"provider": "xai", "model": "grok", "preset": "old name", "fallback": False}]- assert messages[2]["responseSources"] == expected- assert messages[3]["responseSources"] == expected+ assert events[2]["response_sources"] == expected+ assert events[3]["response_sources"] == expectedasync def test_runner_records_each_provider_when_streaming_times_out_and_recovers():@@ -350,9 +375,6 @@ async def test_websocket_wire_and_disk_replay_preserve_sources(tmp_path, monkeypsources[0]["preset"] = "renamed later"replay = build_webui_thread_response("websocket:source-chat")assert replay is not None- assert replay["messages"][0]["responseSources"][0]["preset"] == "snapshot name"- assert replay["messages"][0]["responseSources"][0]["fallback"] is True- event_replay = build_webui_thread_response("websocket:source-chat", projection="events")- assert event_replay is not None- end = next(e for e in event_replay["events"] if e["event"] == "stream_end")- assert end["response_sources"] == replay["messages"][0]["responseSources"]+ end = next(e for e in replay["events"] if e["event"] == "stream_end")+ assert end["response_sources"][0]["preset"] == "snapshot name"+ assert end["response_sources"][0]["fallback"] is Truediff --git a/tests/agent/tools/test_session_history_pagination.py b/tests/agent/tools/test_session_history_pagination.pyindex 71b2f6b27..9701ddaf6 100644--- a/tests/agent/tools/test_session_history_pagination.py+++ b/tests/agent/tools/test_session_history_pagination.py@@ -87,15 +87,15 @@ async def test_read_releases_raw_pages_while_preserving_global_indexes(tmp_path,index = int(before) if before is not None else 0calls.append(index)start = (9 - index) * 5- messages = [- TrackedMessage(role="user", content=f"visible {start}"),- TrackedMessage(role="tool", content="private tool result"),- TrackedMessage(role="assistant", content=f"visible {start + 2}"),- TrackedMessage(role="user", content="hidden", _hidden_history=True),- TrackedMessage(role="assistant", content=""),+ events = [+ TrackedMessage(event="user_message", text=f"visible {start}"),+ TrackedMessage(event="message", kind="progress", text="private tool result"),+ TrackedMessage(event="message", text=f"visible {start + 2}"),+ TrackedMessage(event="reasoning_delta", text="private reasoning"),+ TrackedMessage(event="message", text=""),]- refs.extend(weakref.ref(message) for message in messages)- return {"messages": messages, "page": {+ refs.extend(weakref.ref(event) for event in events)+ return {"events": events, "page": {"has_more_before": index < 9,"before_cursor": str(index + 1) if index < 9 else None,}}@@ -105,9 +105,12 @@ async def test_read_releases_raw_pages_while_preserving_global_indexes(tmp_path,channel="websocket", chat_id="current", session_key="websocket:current",)):result = json.loads(await ReadSessionTool(manager).execute(session_key=key, query=query))- expected = [30, 32, 35, 37, 40, 42, 45, 47]- assert [item["message_index"] for item in result["messages"]] == expected- assert [item["content"] for item in result["messages"]] == [f"visible {i}" for i in expected]+ expected_indexes = list(range(12, 20))+ expected_values = [30, 32, 35, 37, 40, 42, 45, 47]+ assert [item["message_index"] for item in result["messages"]] == expected_indexes+ assert [item["content"] for item in result["messages"]] == [+ f"visible {i}" for i in expected_values+ ]assert calls == list(range(10))assert not any(ref() is not None for ref in refs)diff --git a/tests/utils/test_webui_event_projection_equivalence.py b/tests/utils/test_webui_event_projection_equivalence.pydeleted file mode 100644index 30d50786e..000000000--- a/tests/utils/test_webui_event_projection_equivalence.py+++ /dev/null@@ -1,65 +0,0 @@-"""Shared characterization cases for live and persisted WebUI projection."""--from __future__ import annotations--import json-from pathlib import Path-from typing import Any--from nanobot.webui.transcript import replay_transcript_to_ui_messages--_FIXTURE_PATH = (- Path(__file__).parents[2]- / "webui"- / "src"- / "tests"- / "fixtures"- / "live-replay-event-projection.json"-)-_SEMANTIC_MESSAGE_FIELDS = (- "role",- "content",- "kind",- "traces",- "toolEvents",- "fileEdits",- "images",- "media",- "cliApps",- "mcpPresets",- "sessionMentions",- "reasoning",- "latencyMs",- "source",- "turnId",- "turnPhase",- "turnSeq",-)---def _normalize_projection(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:- segment_aliases: dict[str, str] = {}- normalized: list[dict[str, Any]] = []- for message in messages:- row = {- field: message[field]- for field in _SEMANTIC_MESSAGE_FIELDS- if field in message and message[field] is not None- }- segment_id = message.get("activitySegmentId")- if isinstance(segment_id, str) and segment_id:- row["activitySegmentId"] = segment_aliases.setdefault(- segment_id,- f"segment-{len(segment_aliases) + 1}",- )- normalized.append(row)- return normalized---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"]:- actual = replay_transcript_to_ui_messages(case["transcript"])- assert _normalize_projection(actual) == case["expected"], case["name"]diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.pyindex 7ead850d0..0e00ed33c 100644--- a/tests/utils/test_webui_transcript.py+++ b/tests/utils/test_webui_transcript.py@@ -20,10 +20,8 @@ from nanobot.webui.transcript import (build_webui_trace_detail_response,fork_transcript_before_user_index,read_transcript_lines,- replay_transcript_to_ui_messages,webui_transcript_revision,webui_transcript_segments_dir,- write_session_messages_as_transcript,)@@ -72,8 +70,28 @@ def _write_segmented_turns(tmp_path, monkeypatch, key: str, chat_id: str, count:_append_numbered_turn(key, chat_id, idx)+def _conversation_events(payload: dict) -> list[dict]:+ messages: list[dict] = []+ for event in payload["events"]:+ name = event.get("event")+ if name == "user_message":+ role = "user"+ elif name == "message" and event.get("kind") is None:+ role = "assistant"+ elif name == "stream_end" and isinstance(event.get("text"), str):+ role = "assistant"+ else:+ continue+ messages.append({+ "id": event["projection_id"],+ "role": role,+ "content": event.get("text", ""),+ })+ return messages++def _message_contents(payload: dict) -> list[str]:- return [str(message.get("content") or "") for message in payload["messages"]]+ return [str(message.get("content") or "") for message in _conversation_events(payload)]def _numbered_turn_texts(start: int, end: int) -> list[str]:@@ -123,14 +141,17 @@ def test_segmented_transcript_paginates_latest_and_older_without_overlap(full = build_webui_thread_response(key)assert latest_again is not Noneassert full is not None- assert [message["id"] for message in latest_again["messages"]] == [- message["id"] for message in latest["messages"]+ assert [message["id"] for message in _conversation_events(latest_again)] == [+ message["id"] for message in _conversation_events(latest)]full_ids_by_content = {- message["content"]: message["id"] for message in full["messages"]+ message["content"]: message["id"] for message in _conversation_events(full)}- assert [full_ids_by_content[message["content"]] for message in latest["messages"]] == [- message["id"] for message in latest["messages"]+ assert [+ full_ids_by_content[message["content"]]+ for message in _conversation_events(latest)+ ] == [+ message["id"] for message in _conversation_events(latest)]@@ -146,7 +167,7 @@ def test_missing_page_query_uses_bounded_default(tmp_path, monkeypatch) -> None:assert latest is not Noneassert _message_contents(latest) == _numbered_turn_texts(3, 4)assert latest["page"]["has_more_before"] is True- assert latest["page"]["loaded_message_count"] == 4+ assert latest["page"]["loaded_event_count"] == 6def test_large_trace_details_are_deferred_and_resolved(tmp_path, monkeypatch) -> None:@@ -169,95 +190,19 @@ def test_large_trace_details_are_deferred_and_resolved(tmp_path, monkeypatch) ->payload = build_webui_thread_response(key, limit=40, direction="latest")assert payload is not None- trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")- assert trace_message["content"] == "exec(…)"- assert trace_message["traces"] == ["exec(…)"]- assert trace_message["traceDetail"]["bytes"] > 32 * 1024+ trace_event = next(event for event in payload["events"] if event.get("kind") == "progress")+ assert trace_event["text"] == "exec(…)"+ assert trace_event["trace_detail"]["bytes"] > 32 * 1024assert len(json.dumps(payload)) < len(trace)- detail = build_webui_trace_detail_response(key, trace_message["traceDetail"]["ref"])+ detail = build_webui_trace_detail_response(key, trace_event["trace_detail"]["ref"])- assert detail == {- "message_id": trace_message["id"],- "content": trace,- "traces": [trace],- }---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,- )+ assert detail is not None+ assert detail["message_id"] == trace_event["projection_id"]+ assert detail["events"][0]["text"] == trace+ assert "trace_detail" not in detail["events"][0]- 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"] == 4def test_event_projection_augments_complete_stream_text(tmp_path, monkeypatch) -> None:@@ -279,7 +224,6 @@ def test_event_projection_augments_complete_stream_text(tmp_path, monkeypatch) -payload = build_webui_thread_response(key,- projection="events",augment_assistant_text=lambda text: text.replace("output.png", "/api/media/signed"),)@@ -290,7 +234,9 @@ def test_event_projection_augments_complete_stream_text(tmp_path, monkeypatch) -]-def test_event_projection_falls_back_for_deferred_trace_details(tmp_path, monkeypatch) -> None:+def test_event_projection_defers_trace_details_without_legacy_fallback(+ tmp_path, monkeypatch,+) -> None:monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)key = "websocket:event-trace-fallback"for event in (@@ -305,18 +251,32 @@ def test_event_projection_falls_back_for_deferred_trace_details(tmp_path, monkey):append_transcript_object(key, event)- payload = build_webui_thread_response(key, projection="events")+ trace = f'exec({json.dumps({"command": "x" * 40_000})})'++ payload = build_webui_thread_response(key)assert payload is not None- assert "events" not in payload- assert any(message.get("traceDetail") for message in payload["messages"])+ assert "messages" not in payload+ assert payload["projection"] == "events"+ trace_event = next(event for event in payload["events"] if event.get("kind") == "progress")+ assert trace_event["text"] == "exec(…)"+ assert trace_event["trace_detail"]["bytes"] > 32 * 1024+ assert trace_event["trace_detail"]["traceCount"] == 1+ assert len(json.dumps(payload)) < len(trace)++ detail = build_webui_trace_detail_response(key, trace_event["trace_detail"]["ref"])++ assert detail is not None+ assert detail["message_id"] == trace_event["projection_id"]+ assert detail["events"][0]["text"] == trace+ assert "trace_detail" not in detail["events"][0]@pytest.mark.parametrize(("delta_event", "end_event"),[("reasoning_delta", "reasoning_end"), ("delta", "stream_end")],)-def test_legacy_active_trace_details_match_compacted_page(+def test_active_trace_details_match_compacted_event_page(tmp_path, monkeypatch, delta_event: str, end_event: str,) -> None:monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)@@ -341,15 +301,16 @@ def test_legacy_active_trace_details_match_compacted_page(payload = build_webui_thread_response(key, limit=40, direction="latest")assert payload is not None- messages = [message for message in payload["messages"] if message.get("kind") == "trace"]- assert len(messages) == 2- for message, trace in zip(messages, traces, strict=True):- detail = build_webui_trace_detail_response(key, message["traceDetail"]["ref"])- assert detail == {- "message_id": message["id"],- "content": trace,- "traces": [trace],- }+ trace_events = [+ event for event in payload["events"]+ if event.get("kind") == "progress"+ ]+ assert len(trace_events) == 2+ for event, trace in zip(trace_events, traces, strict=True):+ detail = build_webui_trace_detail_response(key, event["trace_detail"]["ref"])+ assert detail is not None+ assert detail["message_id"] == event["projection_id"]+ assert detail["events"][0]["text"] == traceassert path.read_bytes() == original_bytes@@ -381,14 +342,16 @@ def test_large_structured_trace_error_is_bounded_and_resolved(tmp_path, monkeypapayload = build_webui_thread_response(key, limit=40, direction="latest")assert payload is not None- trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")- assert len(json.dumps(trace_message).encode("utf-8")) < 4_096- assert len(trace_message["toolEvents"][0]["error"].encode("utf-8")) <= 512-- detail = build_webui_trace_detail_response(key, trace_message["traceDetail"]["ref"])-- assert detail is not None- assert detail["toolEvents"][0]["error"] == full_error+ trace_event = next(+ event for event in payload["events"] if event.get("kind") == "progress"+ )+ assert len(json.dumps(trace_event).encode("utf-8")) < 4_096+ event_detail = build_webui_trace_detail_response(+ key,+ trace_event["trace_detail"]["ref"],+ )+ assert event_detail is not None+ assert event_detail["events"][0]["tool_events"][0]["error"] == full_errordef test_many_short_trace_rows_are_bounded_and_resolved(tmp_path, monkeypatch) -> None:@@ -418,17 +381,16 @@ def test_many_short_trace_rows_are_bounded_and_resolved(tmp_path, monkeypatch) -payload = build_webui_thread_response(key, limit=40, direction="latest")assert payload is not None- trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")- assert trace_message["traceDetail"]["traceCount"] == trace_count- assert len(trace_message["traces"]) <= 16- assert len(json.dumps(trace_message).encode("utf-8")) < 4_096+ trace_event = next(event for event in payload["events"] if event.get("kind") == "progress")+ assert trace_event["trace_detail"]["traceCount"] == trace_count+ assert len(json.dumps(trace_event).encode("utf-8")) < 4_096- detail = build_webui_trace_detail_response(key, trace_message["traceDetail"]["ref"])+ detail = build_webui_trace_detail_response(key, trace_event["trace_detail"]["ref"])assert detail is not None- assert len(detail["traces"]) == trace_count- assert detail["traces"][0] == "tool_0(value)"- assert detail["traces"][-1] == f"tool_{trace_count - 1}(value)"+ assert len(detail["events"]) == trace_count+ assert detail["events"][0]["text"] == "tool_0(value)"+ assert detail["events"][-1]["text"] == f"tool_{trace_count - 1}(value)"def test_transcript_revision_tracks_artifacts_and_variants(tmp_path, monkeypatch) -> None:@@ -483,8 +445,7 @@ def test_single_oversized_turn_is_bounded_and_marked(tmp_path, monkeypatch) -> Nassert stats.capped_by_bytes is Trueassert stats.truncated_oversized_turn is Trueassert latest["page"]["truncated_oversized_turn"] is True- assert latest["messages"][0]["content"] == "question"- assert latest["messages"][-1]["content"] == "final answer"+ assert _message_contents(latest) == ["question", "final answer"]def test_truncated_turn_does_not_advertise_ambiguous_trace_detail(@@ -532,11 +493,10 @@ def test_truncated_turn_does_not_advertise_ambiguous_trace_detail(assert payload is not Noneassert payload["page"]["truncated_oversized_turn"] is True- trace_message = next(message for message in payload["messages"] if message.get("kind") == "trace")- assert trace_message["content"] == "second_3(…)"- assert all(trace.startswith("second_") for trace in trace_message["traces"])- assert "traceDetail" not in trace_message- assert len(json.dumps(trace_message).encode("utf-8")) < 4_096+ trace_event = next(event for event in payload["events"] if event.get("kind") == "progress")+ assert trace_event["text"] == "second_3(…)"+ assert "trace_detail" not in trace_event+ assert len(json.dumps(trace_event).encode("utf-8")) < 4_096def test_latest_page_reads_active_chunk_once(tmp_path, monkeypatch) -> None:@@ -786,8 +746,10 @@ def test_build_response_reports_fork_boundary_from_marker(tmp_path, monkeypatch)out = build_webui_thread_response(key)assert out is not None- assert [m["content"] for m in out["messages"]] == ["round1", "answer1", "new branch"]- assert out["fork_boundary_message_count"] == 2+ assert [m["content"] for m in _conversation_events(out)] == [+ "round1", "answer1", "new branch",+ ]+ assert out["fork_boundary_event_index"] == 2def test_nested_fork_drops_inherited_fork_marker(tmp_path, monkeypatch) -> None:@@ -820,69 +782,16 @@ def test_nested_fork_drops_inherited_fork_marker(tmp_path, monkeypatch) -> None:"fork_marker",]assert out is not None- assert [m["content"] for m in out["messages"]] == ["round1", "answer1", "round2", "answer2"]- assert out["fork_boundary_message_count"] == 4---def test_write_session_messages_as_transcript_builds_canonical_prefix(- tmp_path,- monkeypatch,-) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)-- write_session_messages_as_transcript(- "websocket:fork",- [- {"role": "user", "content": "round1"},- {"role": "assistant", "content": "answer1"},- ],- )-- lines = read_transcript_lines("websocket:fork")- assert lines == [- {"event": "user", "chat_id": "fork", "text": "round1"},- {"event": "message", "chat_id": "fork", "text": "answer1"},+ assert [m["content"] for m in _conversation_events(out)] == [+ "round1", "answer1", "round2", "answer2",]- msgs = replay_transcript_to_ui_messages(lines)- assert [m["content"] for m in msgs] == ["round1", "answer1"]+ assert out["fork_boundary_event_index"] == 4-def test_direct_transcript_replay_generates_stable_message_ids() -> None:- lines = [- {"event": "user", "chat_id": "stable", "text": "question"},- {"event": "message", "chat_id": "stable", "text": "answer"},- {"event": "turn_end", "chat_id": "stable"},- ]- first = replay_transcript_to_ui_messages(lines)- second = replay_transcript_to_ui_messages(lines)- assert [message["id"] for message in second] == [- message["id"] for message in first- ]-def test_replay_delta_and_turn_end(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t2"- for ev in (- {"event": "user", "chat_id": "t2", "text": "q"},- {"event": "reasoning_delta", "chat_id": "t2", "text": "think"},- {"event": "reasoning_end", "chat_id": "t2"},- {"event": "delta", "chat_id": "t2", "text": "a"},- {"event": "stream_end", "chat_id": "t2"},- {"event": "turn_end", "chat_id": "t2", "latency_ms": 42},- ):- append_transcript_object(key, ev)- lines = read_transcript_lines(key)- msgs = replay_transcript_to_ui_messages(lines)- assert len(msgs) == 2- assert msgs[0]["role"] == "user"- assert msgs[0]["content"] == "q"- assert msgs[1]["role"] == "assistant"- assert msgs[1]["content"] == "a"- assert msgs[1]["reasoning"] == "think"- assert msgs[1]["latencyMs"] == 42def test_completed_turn_persists_canonical_stream_end_text(tmp_path, monkeypatch) -> None:@@ -912,225 +821,16 @@ def test_completed_turn_persists_canonical_stream_end_text(tmp_path, monkeypatchassert lines[2]["text"] == "answer done"-def test_replay_canonical_completed_stream_records() -> None:- msgs = replay_transcript_to_ui_messages([- {"event": "user", "chat_id": "canonical", "text": "q"},- {"event": "reasoning_end", "chat_id": "canonical", "text": "think"},- {"event": "stream_end", "chat_id": "canonical", "text": "answer"},- {"event": "turn_end", "chat_id": "canonical", "latency_ms": 42},- ])- assert len(msgs) == 2- assert msgs[1]["content"] == "answer"- assert msgs[1]["reasoning"] == "think"- assert msgs[1]["latencyMs"] == 42-def test_replay_preserves_closed_reasoning_slices_before_later_tool_trace() -> None:- msgs = replay_transcript_to_ui_messages([- {- "event": "reasoning_delta",- "chat_id": "reasoning-boundary",- "text": "First reasoning.",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "reasoning",- "turn_seq": 1,- },- {- "event": "reasoning_end",- "chat_id": "reasoning-boundary",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "reasoning",- "turn_seq": 2,- },- {- "event": "reasoning_delta",- "chat_id": "reasoning-boundary",- "text": "Second reasoning.",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "reasoning",- "turn_seq": 3,- },- {- "event": "reasoning_end",- "chat_id": "reasoning-boundary",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "reasoning",- "turn_seq": 4,- },- {- "event": "message",- "chat_id": "reasoning-boundary",- "text": "exec()",- "kind": "tool_hint",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "activity",- "turn_seq": 5,- },- {- "event": "message",- "chat_id": "reasoning-boundary",- "text": "Final answer.",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "answer",- "turn_seq": 6,- },- {- "event": "turn_end",- "chat_id": "reasoning-boundary",- "turn_id": "turn-reasoning-boundary",- "turn_phase": "complete",- "turn_seq": 7,- },- ])- assert [- message.get("reasoning")- or (message.get("traces") or [None])[0]- or message.get("content")- for message in msgs- ] == [- "First reasoning.",- "Second reasoning.",- "exec()",- "Final answer.",- ]-def test_replay_preserves_closed_reasoning_slices_without_tool_trace() -> None:- msgs = replay_transcript_to_ui_messages([- {"event": "reasoning_delta", "text": "First reasoning.", "turn_seq": 1},- {"event": "reasoning_end", "turn_seq": 2},- {"event": "reasoning_delta", "text": "Second reasoning.", "turn_seq": 3},- {"event": "reasoning_end", "turn_seq": 4},- {"event": "message", "text": "Final answer.", "turn_seq": 5},- {"event": "turn_end", "turn_seq": 6},- ])- assert [- (message.get("reasoning"), message.get("content"))- for message in msgs- ] == [- ("First reasoning.", ""),- ("Second reasoning.", "Final answer."),- ]-def test_replay_keeps_answer_separate_from_reasoning_before_delayed_tool_trace() -> None:- msgs = replay_transcript_to_ui_messages([- {"event": "delta", "text": "Visible progress.", "turn_phase": "answer"},- {"event": "stream_end", "turn_phase": "answer"},- {"event": "reasoning_delta", "text": "Think again.", "turn_phase": "reasoning"},- {"event": "reasoning_end", "turn_phase": "reasoning"},- {- "event": "message",- "text": "exec()",- "kind": "tool_hint",- "turn_phase": "activity",- },- {"event": "message", "text": "Final answer.", "turn_phase": "answer"},- {"event": "turn_end", "turn_phase": "complete"},- ])- assert [- (- message.get("content"),- message.get("reasoning"),- message.get("kind"),- message.get("turnPhase"),- )- for message in msgs- ] == [- ("Visible progress.", None, None, "answer"),- ("", "Think again.", None, "reasoning"),- ("exec()", None, "trace", "activity"),- ("Final answer.", None, None, "answer"),- ]---def test_replay_turn_end_preserves_usage_semantics(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-usage"- for event in (- {"event": "user", "chat_id": "t-usage", "text": "q"},- {"event": "message", "chat_id": "t-usage", "text": "a"},- {- "event": "turn_end",- "chat_id": "t-usage",- "latency_ms": 18_200,- "usage": {- "prompt_tokens": 12_400,- "completion_tokens": 823,- "cached_tokens": 9_672,- "context_tokens": 8_200,- "request_count": 3,- },- "round_usages": [- {- "prompt_tokens": 4_000,- "completion_tokens": 200,- "cached_tokens": 2_000,- "request_count": 1,- },- {- "prompt_tokens": 4_200,- "completion_tokens": 300,- "cached_tokens": 3_672,- "request_count": 1,- },- {- "prompt_tokens": 4_200,- "completion_tokens": 323,- "cached_tokens": 4_000,- "request_count": 1,- },- ],- "context_window_tokens": 128_000,- },- ):- append_transcript_object(key, event)-- messages = replay_transcript_to_ui_messages(read_transcript_lines(key))-- assert messages[-1]["usage"] == {- "prompt_tokens": 12_400,- "completion_tokens": 823,- "cached_tokens": 9_672,- "context_tokens": 8_200,- "request_count": 3,- }- assert [item["prompt_tokens"] for item in messages[-1]["roundUsages"]] == [- 4_000,- 4_200,- 4_200,- ]- assert messages[-1]["contextWindowTokens"] == 128_000- assert messages[-1]["latencyMs"] == 18_200---def test_replay_uses_persisted_created_at_ms() -> None:- msgs = replay_transcript_to_ui_messages(- [- {- "event": "user",- "chat_id": "t-created-at",- "text": "q",- "created_at_ms": 1_700_000_000_000,- },- {- "event": "message",- "chat_id": "t-created-at",- "kind": "tool_hint",- "text": "exec()",- "created_at_ms": 1_700_000_230_000,- },- ],- )-- assert [message["createdAt"] for message in msgs] == [- 1_700_000_000_000,- 1_700_000_230_000,- ]def test_thread_response_does_not_mark_completed_message_tool_tail_pending(@@ -1196,8 +896,8 @@ def test_thread_response_does_not_mark_completed_message_tool_tail_pending(assert out is not Noneassert out["has_pending_tool_calls"] is Falseassert out["completed_turn_ids"] == [turn_id]- assert out["messages"][-1]["kind"] == "trace"- assert out["messages"][-2]["content"] == "Cron test"+ assert out["events"][-2]["kind"] == "progress"+ assert _conversation_events(out)[-1]["content"] == "Cron test"def test_thread_response_marks_unfinished_tool_tail_pending(tmp_path, monkeypatch) -> None:@@ -1249,7 +949,7 @@ def test_thread_response_reports_active_registry_without_transcript()assert out is not None- assert out["messages"] == []+ assert out["events"] == []assert out["completed_turn_ids"] == []assert out["has_pending_tool_calls"] is Trueassert out["active_turn_id"] == "turn-active"@@ -1274,7 +974,7 @@ def test_thread_response_reports_explicit_completion_without_assistant_row(out = build_webui_thread_response(key)assert out is not None- assert out["messages"][-1]["role"] == "user"+ assert _conversation_events(out)[-1]["role"] == "user"assert out["has_pending_tool_calls"] is Falseassert out["completed_turn_ids"] == [turn_id]@@ -1316,7 +1016,10 @@ def test_incomplete_turn_with_ambiguous_session_match_stays_pending()assert out is not None- assert [(message["role"], message["content"]) for message in out["messages"]] == [+ assert [+ (message["role"], message["content"])+ for message in _conversation_events(out)+ ] == [("user", "repeat"),]assert out["completed_turn_ids"] == []@@ -1373,175 +1076,15 @@ def test_active_registry_does_not_hide_a_newer_queued_turn(tmp_path, monkeypatchassert out["has_pending_tool_calls"] is True-def test_replay_preserves_turn_metadata(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-turn"- for ev in (- {- "event": "user",- "chat_id": "t-turn",- "text": "q",- "turn_id": "turn-1",- "turn_phase": "user",- "turn_seq": 1,- },- {- "event": "reasoning_delta",- "chat_id": "t-turn",- "text": "think",- "turn_id": "turn-1",- "turn_phase": "reasoning",- "turn_seq": 2,- },- {- "event": "delta",- "chat_id": "t-turn",- "text": "a",- "turn_id": "turn-1",- "turn_phase": "answer",- "turn_seq": 3,- },- {- "event": "turn_end",- "chat_id": "t-turn",- "latency_ms": 12,- "turn_id": "turn-1",- "turn_phase": "complete",- "turn_seq": 4,- },- ):- append_transcript_object(key, ev)-- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))-- assert msgs[0]["turnId"] == "turn-1"- assert msgs[0]["turnPhase"] == "user"- assert msgs[0]["turnSeq"] == 1- assert msgs[1]["turnId"] == "turn-1"- assert msgs[1]["turnPhase"] == "answer"- assert msgs[1]["turnSeq"] == 3--def test_replay_reused_turn_id_after_turn_end_starts_new_turn(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-reused-turn"-- def event(- event: str,- phase: str,- seq: int,- text: str | None = None,- source: dict[str, str] | None = None,- ) -> dict[str, object]:- out = {- "event": event,- "chat_id": "t-reused-turn",- "turn_id": "turn-1",- "turn_phase": phase,- "turn_seq": seq,- }- if text is not None:- out["text"] = text- if source is not None:- out["source"] = source- return out-- for record in (- event("user", "user", 1, "remind me later"),- event("message", "answer", 2, "Reminder set."),- event("turn_end", "complete", 3),- event(- "message", "answer", 1, "Time to drink water.",- {"kind": "cron", "label": "drink water"},- ),- event("turn_end", "complete", 2),- ):- append_transcript_object(key, record)- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))- assert [m["content"] for m in msgs] == [- "remind me later",- "Reminder set.",- "Time to drink water.",- ]- assert msgs[1]["turnId"] == "turn-1"- assert msgs[2]["turnId"].startswith("turn-1:replay:")- assert msgs[2]["turnId"] != msgs[1]["turnId"]- assert msgs[2]["source"] == {"kind": "cron", "label": "drink water"}-def test_replay_preserves_local_trigger_source_metadata(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-local-trigger-source"- append_transcript_object(- key,- {- "event": "message",- "chat_id": "t-local-trigger-source",- "text": "PR #4502 review started.",- "source": {"kind": "local_trigger", "label": "PR review"},- },- )- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))- assert msgs[0]["source"] == {"kind": "local_trigger", "label": "PR review"}-def test_replay_preserves_automation_source_metadata_on_streamed_reply(- tmp_path,- monkeypatch,-) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-streamed-cron-source"- source = {"kind": "cron", "label": "Repo check"}-- for record in (- {- "event": "delta",- "chat_id": "t-streamed-cron-source",- "text": "Repo ",- "source": source,- },- {- "event": "delta",- "chat_id": "t-streamed-cron-source",- "text": "clean.",- "source": source,- },- {- "event": "stream_end",- "chat_id": "t-streamed-cron-source",- "source": source,- },- {"event": "turn_end", "chat_id": "t-streamed-cron-source"},- ):- append_transcript_object(key, record)-- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))-- assert msgs[0]["content"] == "Repo clean."- assert msgs[0]["source"] == source---def test_replay_preserves_legacy_trigger_source_metadata(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-trigger-source"- append_transcript_object(- key,- {- "event": "message",- "chat_id": "t-trigger-source",- "text": "PR #4502 review started.",- "source": {"kind": "trigger", "label": "PR review"},- },- )-- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))-- assert msgs[0]["source"] == {"kind": "trigger", "label": "PR review"}-def test_build_response_restores_session_users_for_legacy_transcript(tmp_path,@@ -1571,7 +1114,7 @@ def test_build_response_restores_session_users_for_legacy_transcript()assert out is not None- assert [(m["role"], m["content"]) for m in out["messages"]] == [+ assert [(m["role"], m["content"]) for m in _conversation_events(out)] == [("user", "prompt one"),("assistant", "assistant one"),("user", "prompt two"),@@ -1600,7 +1143,10 @@ def test_complete_transcript_does_not_load_session_messages(tmp_path, monkeypatc)assert out is not None- assert [(message["role"], message["content"]) for message in out["messages"]] == [+ assert [+ (message["role"], message["content"])+ for message in _conversation_events(out)+ ] == [("user", "question"),("assistant", "answer"),]@@ -1649,7 +1195,10 @@ def test_legacy_recovery_loads_session_and_builds_backfill_turns_once(assert out is not Noneassert loader_calls == 1assert backfill_calls == 1- assert [(message["role"], message["content"]) for message in out["messages"]] == [+ assert [+ (message["role"], message["content"])+ for message in _conversation_events(out)+ ] == [("user", "question"),("assistant", "answer"),]@@ -1685,7 +1234,7 @@ def test_build_response_restores_session_users_without_duplicating_new_transcrip)assert out is not None- assert [(m["role"], m["content"]) for m in out["messages"]] == [+ assert [(m["role"], m["content"]) for m in _conversation_events(out)] == [("user", "old prompt"),("assistant", "old assistant"),("user", "new prompt"),@@ -1693,29 +1242,9 @@ def test_build_response_restores_session_users_without_duplicating_new_transcrip]-def test_replay_augments_assistant_text() -> None:- msgs = replay_transcript_to_ui_messages(- [- {"event": "user", "chat_id": "t-img", "text": "draw"},- {"event": "delta", "chat_id": "t-img", "text": ""},- {"event": "stream_end", "chat_id": "t-img"},- ],- augment_assistant_text=lambda text: text.replace("diagram.png", "/api/media/sig/payload"),- )- assert msgs[1]["content"] == ""-def test_replay_uses_stream_end_final_text() -> None:- msgs = replay_transcript_to_ui_messages(- [- {"event": "user", "chat_id": "t-img", "text": "draw"},- {"event": "stream_end", "chat_id": "t-img", "text": ""},- ],- )-- assert msgs[1]["content"] == ""-def test_build_response_backfills_legacy_sse_only_transcripts(tmp_path, monkeypatch) -> None:monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)@@ -1740,13 +1269,13 @@ def test_build_response_backfills_legacy_sse_only_transcripts(tmp_path, monkeypa)assert out is not None- assert [message["role"] for message in out["messages"]] == [+ assert [message["role"] for message in _conversation_events(out)] == ["user","assistant","user","assistant",]- assert [message["content"] for message in out["messages"]] == [+ assert [message["content"] for message in _conversation_events(out)] == ["first question","first answer","second question",@@ -1770,8 +1299,10 @@ def test_backfill_does_not_duplicate_existing_user_transcript(tmp_path, monkeypa)assert out is not None- assert [message["role"] for message in out["messages"]] == ["user", "assistant"]- assert out["messages"][0]["content"] == "already stored"+ assert [message["role"] for message in _conversation_events(out)] == [+ "user", "assistant",+ ]+ assert _conversation_events(out)[0]["content"] == "already stored"def test_backfill_does_not_misalign_when_session_only_has_transcript_tail(@@ -1797,12 +1328,12 @@ def test_backfill_does_not_misalign_when_session_only_has_transcript_tail()assert out is not None- assert [message["role"] for message in out["messages"]] == [+ assert [message["role"] for message in _conversation_events(out)] == ["assistant","user","assistant",]- assert [message["content"] for message in out["messages"]] == [+ assert [message["content"] for message in _conversation_events(out)] == ["old answer","tail question","tail answer",@@ -1844,691 +1375,47 @@ def test_backfill_skips_internal_subagent_results(tmp_path, monkeypatch) -> None)assert out is not None- assert [(message["role"], message["content"]) for message in out["messages"]] == [+ assert [+ (message["role"], message["content"])+ for message in _conversation_events(out)+ ] == [("assistant", "summary one"),("assistant", "summary two"),]-def test_replay_infers_video_media_from_attachment_name() -> None:- msgs = replay_transcript_to_ui_messages(- [- {"event": "user", "chat_id": "t-video", "text": "render"},- {- "event": "message",- "chat_id": "t-video",- "text": "video ready",- "media_urls": [{"url": "/api/media/sig/payload", "name": "intro.mp4"}],- },- ],- )- assert msgs[1]["media"] == [- {"kind": "video", "url": "/api/media/sig/payload", "name": "intro.mp4"},- ]---def test_replay_resigns_assistant_media_paths_before_stale_urls() -> None:- msgs = replay_transcript_to_ui_messages(- [- {"event": "user", "chat_id": "t-video-resign", "text": "render"},- {- "event": "message",- "chat_id": "t-video-resign",- "text": "video ready",- "media": ["/tmp/intro.mp4"],- "media_urls": [{"url": "/api/media/old-sig/old-payload", "name": "intro.mp4"}],- },- ],- augment_assistant_media=lambda paths: [- {"kind": "video", "url": f"/api/media/new-sig/{paths[0].split('/')[-1]}", "name": "intro.mp4"},- ],- )-- assert msgs[1]["media"] == [- {"kind": "video", "url": "/api/media/new-sig/intro.mp4", "name": "intro.mp4"},- ]---def test_replay_infers_svg_media_from_attachment_name() -> None:- msgs = replay_transcript_to_ui_messages(- [- {"event": "user", "chat_id": "t-svg", "text": "send svg"},- {- "event": "message",- "chat_id": "t-svg",- "text": "chart ready",- "media_urls": [{"url": "/api/media/sig/payload", "name": "chart.svg"}],- },- ],- )-- assert msgs[1]["media"] == [- {"kind": "image", "url": "/api/media/sig/payload", "name": "chart.svg"},- ]---def test_replay_infers_file_media_from_attachment_name() -> None:- msgs = replay_transcript_to_ui_messages(- [- {"event": "user", "chat_id": "t-file-media", "text": "send html"},- {- "event": "message",- "chat_id": "t-file-media",- "text": "file ready",- "media_urls": [{"url": "/api/media/sig/payload", "name": "index.html"}],- },- ],- )-- assert msgs[1]["media"] == [- {"kind": "file", "url": "/api/media/sig/payload", "name": "index.html"},- ]---def test_replay_file_edit_event_creates_file_activity(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-file"- for ev in (- {"event": "user", "chat_id": "t-file", "text": "edit"},- {- "event": "message",- "chat_id": "t-file",- "text": 'write_file({"path":"foo.txt"})',- "kind": "tool_hint",- },- {- "event": "file_edit",- "chat_id": "t-file",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "end",- "added": 2,- "deleted": 1,- "approximate": False,- "status": "done",- },- ],- },- ):- append_transcript_object(key, ev)-- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))-- assert len(msgs) == 3- assert msgs[1]["kind"] == "trace"- assert msgs[1]["traces"] == ['write_file({"path":"foo.txt"})']- assert "fileEdits" not in msgs[1]- assert msgs[2]["kind"] == "trace"- assert msgs[2]["traces"] == []- assert msgs[2]["fileEdits"] == [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "end",- "added": 2,- "deleted": 1,- "approximate": False,- "status": "done",- },- ]- assert msgs[2]["activitySegmentId"]- assert msgs[2]["activitySegmentId"] != msgs[1]["activitySegmentId"]---def test_replay_file_edit_absorbs_matching_write_tool_event() -> None:- msgs = replay_transcript_to_ui_messages([- {- "event": "message",- "chat_id": "t-file",- "text": 'write_file({"path":"foo.txt"})',- "kind": "tool_hint",- "tool_events": [- {- "phase": "start",- "call_id": "call-write",- "name": "write_file",- "arguments": {"path": "foo.txt", "content": "hello\n"},- },- ],- },- {- "event": "file_edit",- "chat_id": "t-file",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "start",- "added": 1,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ],- },- {- "event": "message",- "chat_id": "t-file",- "text": "",- "kind": "progress",- "tool_events": [- {- "phase": "end",- "call_id": "call-write",- "name": "write_file",- "arguments": {"path": "foo.txt", "content": "hello\n"},- "result": "ok",- },- ],- },- ])- assert len(msgs) == 1- assert msgs[0]["kind"] == "trace"- assert msgs[0]["traces"] == []- assert "toolEvents" not in msgs[0]- assert msgs[0]["fileEdits"] == [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "start",- "added": 1,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ]-def test_replay_file_edit_stays_separate_from_mixed_tool_trace() -> None:- msgs = replay_transcript_to_ui_messages([- {- "event": "message",- "chat_id": "t-file",- "text": "",- "kind": "tool_hint",- "tool_events": [- {- "phase": "start",- "call_id": "call-read",- "name": "read_file",- "arguments": {"path": "quicksort.py"},- },- {- "phase": "start",- "call_id": "call-write",- "name": "write_file",- "arguments": {"path": "sorting/quicksort.py", "content": "def quicksort():\n"},- },- ],- },- {- "event": "file_edit",- "chat_id": "t-file",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "sorting/quicksort.py",- "phase": "end",- "added": 3,- "deleted": 0,- "approximate": False,- "status": "done",- },- ],- },- ])-- assert len(msgs) == 2- assert msgs[0]["kind"] == "trace"- assert msgs[0]["traces"] == ['read_file({"path": "quicksort.py"})']- assert [event["name"] for event in msgs[0]["toolEvents"]] == ["read_file"]- assert "fileEdits" not in msgs[0]- assert msgs[1]["kind"] == "trace"- assert msgs[1]["traces"] == []- assert "toolEvents" not in msgs[1]- assert msgs[1]["fileEdits"] == [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "sorting/quicksort.py",- "phase": "end",- "added": 3,- "deleted": 0,- "approximate": False,- "status": "done",- },- ]---def test_replay_keeps_every_file_from_one_apply_patch_call() -> None:- msgs = replay_transcript_to_ui_messages([- {- "event": "message",- "chat_id": "t-file",- "text": "apply_patch()",- "kind": "tool_hint",- "tool_events": [- {- "phase": "start",- "call_id": "call-patch",- "name": "apply_patch",- "arguments": {"edits": []},- },- ],- },- {- "event": "file_edit",- "chat_id": "t-file",- "edits": [- {- "version": 1,- "call_id": "call-patch",- "tool": "apply_patch",- "path": "USER.md",- "phase": "end",- "added": 0,- "deleted": 3,- "approximate": False,- "status": "done",- },- {- "version": 1,- "call_id": "call-patch",- "tool": "apply_patch",- "path": "MEMORY.md",- "phase": "end",- "added": 0,- "deleted": 4,- "approximate": False,- "status": "done",- },- ],- },- ])- assert len(msgs) == 1- assert msgs[0]["traces"] == []- assert "toolEvents" not in msgs[0]- assert [edit["path"] for edit in msgs[0]["fileEdits"]] == ["USER.md", "MEMORY.md"]-def test_replay_keeps_interrupted_pre_tool_text_as_answer() -> None:- msgs = replay_transcript_to_ui_messages([- {"event": "delta", "chat_id": "t-stream", "text": "I will inspect first."},- {"event": "stream_end", "chat_id": "t-stream"},- {- "event": "message",- "chat_id": "t-stream",- "text": 'exec({"cmd":"ls"})',- "kind": "tool_hint",- },- {- "event": "stream_end",- "chat_id": "t-stream",- "text": "Done. Open index.html to play.",- },- ])-- assert len(msgs) == 3- assert msgs[0]["role"] == "assistant"- assert msgs[0]["content"] == "I will inspect first."- assert msgs[0]["turnPhase"] == "answer"- assert "reasoning" not in msgs[0]- assert "activitySegmentId" not in msgs[0]- assert "isStreaming" not in msgs[0]- assert msgs[1]["kind"] == "trace"- assert msgs[1]["traces"] == ['exec({"cmd":"ls"})']- assert msgs[2]["role"] == "assistant"- assert msgs[2]["content"] == "Done. Open index.html to play."---def test_replay_merges_length_recovery_segments_into_one_assistant_message() -> None:- msgs = replay_transcript_to_ui_messages([- {"event": "delta", "chat_id": "t-stream", "text": "first "},- {- "event": "stream_end",- "chat_id": "t-stream",- "text": "first ",- "resuming": True,- "merge_next": True,- },- {"event": "delta", "chat_id": "t-stream", "text": "second"},- {"event": "stream_end", "chat_id": "t-stream"},- {"event": "turn_end", "chat_id": "t-stream"},- ])- assert len(msgs) == 1- assert msgs[0]["role"] == "assistant"- assert msgs[0]["content"] == "first second"[email protected]("event", ["delta", "stream_end"])-def test_replay_recovery_answer_does_not_overwrite_an_unfinished_turn(event: str) -> None:- msgs = replay_transcript_to_ui_messages([- {- "event": "stream_end", "text": "Original answer", "turn_id": "original",- "resuming": True, "merge_next": True,- },- {"event": event, "text": "Recovered answer", "turn_id": "recovery"},- {"event": "turn_end", "turn_id": "recovery"},- ])- assert [(m["turnId"], m["content"]) for m in msgs] == [- ("original", "Original answer"), ("recovery", "Recovered answer"),- ]-def test_replay_reasoning_after_an_ordinary_answer_preserves_the_answer_boundary() -> None:- msgs = replay_transcript_to_ui_messages([- {"event": "delta", "text": "First answer"},- {"event": "reasoning_end", "text": "Consider the next answer"},- {"event": "stream_end", "text": "Next answer"},- {"event": "turn_end"},- ])- assert [m["content"] for m in msgs] == ["First answer", "Next answer"]- assert msgs[1]["reasoning"] == "Consider the next answer"-def test_replay_tool_events_dedupes_finish_after_start() -> None:- msgs = replay_transcript_to_ui_messages([- {- "event": "message",- "chat_id": "t-tool",- "text": 'exec({"cmd":"ls"})',- "kind": "tool_hint",- "tool_events": [- {- "phase": "start",- "call_id": "call-exec",- "name": "exec",- "arguments": {"cmd": "ls"},- },- ],- },- {- "event": "message",- "chat_id": "t-tool",- "text": "",- "kind": "progress",- "tool_events": [- {- "phase": "end",- "call_id": "call-exec",- "name": "exec",- "arguments": {"cmd": "ls"},- "result": "ok",- },- {- "phase": "end",- "call_id": "call-read",- "name": "read_file",- "arguments": {"path": "notes.md"},- "result": "done",- },- ],- },- ])- assert len(msgs) == 1- assert msgs[0]["traces"] == [- 'exec({"cmd": "ls"})',- 'read_file({"path": "notes.md"})',- ]- assert msgs[0]["toolEvents"][0]["phase"] == "end"- assert msgs[0]["toolEvents"][0]["call_id"] == "call-exec"-def test_replay_tool_events_keeps_phase_update_when_trace_is_deduped() -> None:- args = {"name": "github", "args": ["repo", "view"], "json": "true"}- msgs = replay_transcript_to_ui_messages([- {- "event": "message",- "chat_id": "t-tool",- "text": "",- "kind": "tool_hint",- "tool_events": [- {- "phase": "start",- "call_id": "call-cli",- "name": "run_cli_app",- "arguments": args,- },- ],- },- {- "event": "message",- "chat_id": "t-tool",- "text": "",- "kind": "progress",- "tool_events": [- {- "phase": "error",- "call_id": "call-cli",- "name": "run_cli_app",- "arguments": args,- "error": "Error: CLI app 'github' not found",- },- ],- },- ])- assert len(msgs) == 1- assert msgs[0]["traces"] == [- 'run_cli_app({"name": "github", "args": ["repo", "view"], "json": "true"})',- ]- assert msgs[0]["toolEvents"][0]["phase"] == "error"- assert msgs[0]["toolEvents"][0]["error"] == "Error: CLI app 'github' not found"-def test_replay_file_edit_progress_merges_after_interleaved_activity(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-file-progress"- for ev in (- {"event": "user", "chat_id": "t-file-progress", "text": "edit"},- {- "event": "message",- "chat_id": "t-file-progress",- "text": 'write_file({"path":"foo.txt"})',- "kind": "tool_hint",- },- {- "event": "file_edit",- "chat_id": "t-file-progress",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "start",- "added": 12,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ],- },- {- "event": "message",- "chat_id": "t-file-progress",- "text": "still working",- "kind": "progress",- },- {- "event": "file_edit",- "chat_id": "t-file-progress",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "end",- "added": 30,- "deleted": 0,- "approximate": False,- "status": "done",- },- ],- },- ):- append_transcript_object(key, ev)- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))- file_edit_messages = [msg for msg in msgs if msg.get("fileEdits")]- assert len(file_edit_messages) == 1- assert file_edit_messages[0]["fileEdits"] == [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "end",- "added": 30,- "deleted": 0,- "approximate": False,- "status": "done",- },- ]-def test_replay_file_edit_pending_placeholder_upgrades_to_path(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-file-pending"- for ev in (- {"event": "user", "chat_id": "t-file-pending", "text": "write"},- {- "event": "file_edit",- "chat_id": "t-file-pending",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "",- "phase": "start",- "added": 1,- "deleted": 0,- "approximate": True,- "status": "editing",- "pending": True,- },- ],- },- {- "event": "file_edit",- "chat_id": "t-file-pending",- "edits": [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "start",- "added": 12,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ],- },- ):- append_transcript_object(key, ev)- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))- file_edit_messages = [msg for msg in msgs if msg.get("fileEdits")]- assert len(file_edit_messages) == 1- assert file_edit_messages[0]["fileEdits"] == [- {- "version": 1,- "call_id": "call-write",- "tool": "write_file",- "path": "foo.txt",- "phase": "start",- "added": 12,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ]-def test_replay_keeps_new_file_edit_after_reasoning_in_order(tmp_path, monkeypatch) -> None:- monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)- key = "websocket:t-file-order"- for ev in (- {"event": "user", "chat_id": "t-file-order", "text": "edit"},- {- "event": "file_edit",- "chat_id": "t-file-order",- "edits": [- {- "version": 1,- "call_id": "call-one",- "tool": "write_file",- "path": "one.txt",- "phase": "start",- "added": 10,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ],- },- {"event": "reasoning_delta", "chat_id": "t-file-order", "text": "Check next."},- {"event": "reasoning_end", "chat_id": "t-file-order"},- {- "event": "file_edit",- "chat_id": "t-file-order",- "edits": [- {- "version": 1,- "call_id": "call-two",- "tool": "write_file",- "path": "two.txt",- "phase": "start",- "added": 20,- "deleted": 0,- "approximate": True,- "status": "editing",- },- ],- },- ):- append_transcript_object(key, ev)- msgs = replay_transcript_to_ui_messages(read_transcript_lines(key))- assert [msg.get("fileEdits", [{}])[0].get("path") if msg.get("fileEdits") else msg.get("reasoning") for msg in msgs[1:]] == [- "one.txt",- "Check next.",- "two.txt",- ]- file_edit_segments = [- msg.get("activitySegmentId")- for msg in msgs- if msg.get("fileEdits")- ]- assert len(file_edit_segments) == 2- assert file_edit_segments[0] != file_edit_segments[1]def test_build_response_schema(monkeypatch, tmp_path) -> None:@@ -2539,4 +1426,4 @@ def test_build_response_schema(monkeypatch, tmp_path) -> None:assert out is not Noneassert out["schemaVersion"] == WEBUI_TRANSCRIPT_SCHEMA_VERSIONassert out["sessionKey"] == key- assert len(out["messages"]) == 1+ assert len(_conversation_events(out)) == 1diff --git a/tests/webui/test_context_compaction.py b/tests/webui/test_context_compaction.pydeleted file mode 100644index aca8ca7ee..000000000--- a/tests/webui/test_context_compaction.py+++ /dev/null@@ -1,54 +0,0 @@-"""WebUI replay behavior for structured context-compaction events."""--import pytest--from nanobot.webui.transcript import replay_transcript_to_ui_messages--[email protected]("phase", ["succeeded", "cancelled"])-def test_replay_folds_compaction_lifecycle_into_one_stable_message(phase) -> None:- messages = replay_transcript_to_ui_messages([- {- "event": "context_compaction",- "compaction_id": "compact-1",- "phase": "started",- "created_at_ms": 1_700_000_000_000,- },- {- "event": "context_compaction",- "compaction_id": "compact-1",- "phase": phase,- "created_at_ms": 1_700_000_001_000,- },- ])-- assert messages == [{- "id": "compaction-compact-1",- "role": "assistant",- "content": "",- "kind": "compaction",- "createdAt": 1_700_000_000_000,- "turnPhase": "activity",- "compaction": {- "id": "compact-1",- "phase": phase,- },- }]---def test_replay_keeps_distinct_compactions_in_one_turn() -> None:- messages = replay_transcript_to_ui_messages([- {- "event": "context_compaction",- "compaction_id": compaction_id,- "phase": phase,- }- for compaction_id in ("compact-1", "compact-2")- for phase in ("started", "succeeded")- ])-- assert [message["id"] for message in messages] == [- "compaction-compact-1",- "compaction-compact-2",- ]- assert all(message["compaction"]["phase"] == "succeeded" for message in messages)diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.pyindex 11b205f00..93331a30b 100644--- a/tests/webui/test_gateway_webui_smoke.py+++ b/tests/webui/test_gateway_webui_smoke.py@@ -202,7 +202,11 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Paf"{base_url}/api/sessions/{encoded_key}/webui-thread",token=api_token,)- contents = [str(message.get("content") or "") for message in thread["messages"]]+ contents = [+ str(event.get("text") or "")+ for event in thread["events"]+ if event.get("event") in {"user_message", "message", "stream_end"}+ ]assert "/model" in contentsassert any("Current model: `custom/smoke-model`" in text for text in contents)assert "!printf shell-ok" in contentsdiff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex 4737de7bb..546106284 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -53,7 +53,8 @@ import type {WorkspaceScopePayload,WorkspacesPayload,} from "@/lib/types";-import { projectWebuiThreadMessages } from "@/lib/thread-display-compat";+import { projectThreadEvents } from "@/lib/thread-event-projection";+import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";import { ThreadMessageCache } from "@/lib/thread-message-cache";import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";@@ -771,17 +772,14 @@ export function ThreadShell({const request = fetchWebuiThreadTraceDetail(getToken(), requestKey, ref).then((detail) => {if (activeHistoryKeyRef.current !== requestKey) return;- setMessages((current) => current.map((message) => (- message.traceDetail?.ref === ref- ? {- ...message,- content: detail.content,- traces: detail.traces,- toolEvents: detail.toolEvents,- traceDetail: undefined,- }- : message- )));+ const projected = projectThreadEvents(detail.events);+ setMessages((current) => current.flatMap((message) => {+ if (message.traceDetail?.ref !== ref) return [message];+ return projected.map((replacement) => ({+ ...replacement,+ activitySegmentId: message.activitySegmentId ?? replacement.activitySegmentId,+ }));+ }));}).catch((error: unknown) => {if (activeHistoryKeyRef.current !== requestKey) return;diff --git a/webui/src/hooks/useSessions.ts b/webui/src/hooks/useSessions.tsindex 7214012a7..37eda7c19 100644--- a/webui/src/hooks/useSessions.ts+++ b/webui/src/hooks/useSessions.ts@@ -38,36 +38,20 @@ function isAbortError(error: unknown): boolean {export type SessionHistoryContinuity = "initial" | "overlap" | "reset";-function persistedMessagesToUi(messages: UIMessage[]): UIMessage[] {- return messages.map((m, idx) => ({- ...m,- id: m.id ?? `hist-${idx}`,- createdAt: typeof m.createdAt === "number" ? m.createdAt : Date.now(),- }));-}-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,- };+ const events = body?.events ?? [];+ const messages = projectThreadEvents(events);+ const boundaryIndex = body?.fork_boundary_event_index;+ const forkBoundaryMessageCount = typeof boundaryIndex === "number"+ && Number.isInteger(boundaryIndex)+ && boundaryIndex >= 0+ && boundaryIndex <= events.length+ ? projectThreadEvents(events.slice(0, boundaryIndex)).length+ : null;+ return { messages, forkBoundaryMessageCount };}function sameSemanticMessage(a: UIMessage, b: UIMessage): boolean {diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.tsindex 80834f383..cc7866d88 100644--- a/webui/src/lib/api.ts+++ b/webui/src/lib/api.ts@@ -290,6 +290,18 @@ function hasValidProjectionMetadata(value: Record<string, unknown>): boolean {);}+function isProjectionTraceDetail(value: unknown): boolean {+ return isRecord(value)+ && typeof value.ref === "string"+ && /^\d{1,12}\.history-[0-9a-f]{20}$/.test(value.ref)+ && typeof value.bytes === "number"+ && Number.isFinite(value.bytes)+ && value.bytes >= 0+ && typeof value.traceCount === "number"+ && Number.isInteger(value.traceCount)+ && value.traceCount >= 0;+}+function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") {throw new Error("Invalid WebUI thread event");@@ -328,6 +340,10 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {case "message":if (typeof value.text !== "string") break;if (value.tool_events !== undefined && !isRecordArray(value.tool_events)) break;+ if (value.trace_detail !== undefined && (+ !["tool_hint", "progress"].includes(String(value.kind))+ || !isProjectionTraceDetail(value.trace_detail)+ )) break;if (value.media_urls !== undefined && (!Array.isArray(value.media_urls) || !value.media_urls.every(isProjectionMedia))) break;@@ -356,19 +372,32 @@ 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)) {+ if (value.projection !== "events" || !Array.isArray(value.events)) {throw new Error("Invalid WebUI thread events");}- const events = value.events?.map(parseThreadProjectionEvent);+ const events = value.events.map(parseThreadProjectionEvent);return {...value,- ...(events ? { events } : {}),+ projection: "events",+ events,} as unknown as WebuiThreadPersistedPayload;}+function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDetailPayload {+ if (+ !isRecord(value)+ || typeof value.message_id !== "string"+ || !/^history-[0-9a-f]{20}$/.test(value.message_id)+ || !Array.isArray(value.events)+ ) {+ throw new Error("Invalid WebUI thread trace detail response");+ }+ return {+ message_id: value.message_id,+ events: value.events.map(parseThreadProjectionEvent),+ };+}+export async function fetchWebuiThread(token: string,key: string,@@ -381,7 +410,6 @@ 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}`;@@ -413,7 +441,7 @@ export async function fetchWebuiThreadTraceDetail(cache: "no-store",});if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);- return (await res.json()) as WebuiThreadTraceDetailPayload;+ return parseWebuiThreadTraceDetailPayload(await res.json());}export async function fetchFilePreview(diff --git a/webui/src/lib/thread-display-compat.ts b/webui/src/lib/thread-display-projection.tssimilarity index 81%rename from webui/src/lib/thread-display-compat.tsrename to webui/src/lib/thread-display-projection.tsindex 184d16f3c..55c1a9479 100644--- a/webui/src/lib/thread-display-compat.ts+++ b/webui/src/lib/thread-display-projection.ts@@ -3,27 +3,6 @@ import { isSystemCommandTurnId } from "@/lib/nanobot-client";import { scrubSubagentUiMessages } from "@/lib/subagent-channel-display";import type { UIMessage } from "@/lib/types";-/**- * Older WebUI disk snapshots and historical sessions may still contain- * ``kind: "long_task"`` rows from the retired orchestrator UI. Map them to- * ordinary trace rows so the thread stays readable without bespoke cards.- */-export function normalizeLegacyLongTaskMessages(messages: UIMessage[]): UIMessage[] {- return messages.map((m) => {- const kind = (m as { kind?: string }).kind;- if (kind !== "long_task") return m;- const text = (m.content ?? "").trim() || "(legacy thread activity)";- return {- id: m.id,- role: "tool",- kind: "trace",- content: text,- traces: [text],- createdAt: m.createdAt,- };- });-}-interface PreparedMessage {message: UIMessage;hidden: boolean;@@ -36,7 +15,7 @@ const completionMessages = new WeakMap<UIMessage, { completedAt: number; messagefunction prepareMessage(original: UIMessage): PreparedMessage {const cached = preparedMessages.get(original);if (cached) return cached;- const message = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages([original]))[0];+ const message = scrubSubagentUiMessages([original])[0];const prepared = {message,hidden: isSystemCommandTurnId(message.turnId)diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.tsindex b1d338596..89749ecb4 100644--- a/webui/src/lib/thread-event-projection.ts+++ b/webui/src/lib/thread-event-projection.ts@@ -643,6 +643,7 @@ function projectToolActivity(: [];if (lines.length === 0) return;+ const deferredDetail = event.trace_detail;const segmentId = ensureProjectionActivitySegment(state);const turn = turnFieldsForProjection(state, event, "activity");const last = state.messages[state.messages.length - 1];@@ -650,6 +651,8 @@ function projectToolActivity(last&& last.kind === "trace"&& !last.isStreaming+ && !last.traceDetail+ && !deferredDetail&& (!last.activitySegmentId || last.activitySegmentId === segmentId)) {const previousTraces = last.traces?.length@@ -692,6 +695,7 @@ function projectToolActivity(content: lines[lines.length - 1],traces: lines,...(visibleEvents.length ? { toolEvents: visibleEvents } : {}),+ ...(deferredDetail ? { traceDetail: deferredDetail } : {}),activitySegmentId: segmentId,...turn,createdAt: projectionCreatedAt(event, options),diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex 8726fdd17..1eea530a1 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -71,6 +71,12 @@ export interface ResponseSource {fallback?: boolean;}+export interface UITraceDetail {+ ref: string;+ bytes: number;+ traceCount: number;+}+export interface RetryStatus extends WireRetryStatus {next_retry_at?: number;turn_id?: string;@@ -91,11 +97,7 @@ export interface UIMessage {* distinguish running, completed, and failed tool phases. */toolEvents?: ToolProgressEvent[];/** Oversized persisted trace content that can be fetched when activity is expanded. */- traceDetail?: {- ref: string;- bytes: number;- traceCount: number;- };+ traceDetail?: UITraceDetail;/** Activity rows: explicit file edits emitted by edit tools. */fileEdits?: UIFileEdit[];/** Activity rows created during the same agent phase share one collapsible block. */@@ -1387,6 +1389,8 @@ export type InboundEvent =media?: string[];media_urls?: Array<{ url: string; name?: string }>;tool_events?: ToolProgressEvent[];+ /** Oversized persisted activity detail, fetched only when the trace is expanded. */+ trace_detail?: UITraceDetail;/** Present when the frame is an agent breadcrumb (e.g. tool hint,* generic progress line) rather than a conversational reply. */kind?: "tool_hint" | "progress" | "reasoning";@@ -1572,8 +1576,6 @@ export interface OutboundMcpPresetMention {interface WebuiThreadPagePayload {before_cursor?: string | null;has_more_before?: boolean;- loaded_message_count?: number;- total_known_message_count?: number;user_message_offset?: number;loaded_event_count?: number;}@@ -1584,12 +1586,9 @@ export interface WebuiThreadPersistedPayload {savedAt?: string;/** Cheap server revision used for application-managed conditional revalidation. */revision?: string;- /** 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;+ events: ThreadProjectionEvent[];+ projection: "events";fork_boundary_event_index?: number;/** Turn ids backed by an explicit persisted ``turn_end`` event. */completed_turn_ids?: string[];@@ -1602,9 +1601,7 @@ export interface WebuiThreadPersistedPayload {export interface WebuiThreadTraceDetailPayload {message_id: string;- content: string;- traces?: string[];- toolEvents?: ToolProgressEvent[];+ events: ThreadProjectionEvent[];}export interface FilePreviewPayload {diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.tsindex 4ae7873da..4538c52a3 100644--- a/webui/src/tests/api.test.ts+++ b/webui/src/tests/api.test.ts@@ -83,9 +83,8 @@ describe("webui API helpers", () => {ok: true,json: async () => ({schemaVersion: 3,- deleted: true,- key: "websocket:chat-1",- messages: [],+ projection: "events",+ events: [],}),}),);@@ -100,7 +99,7 @@ describe("webui API helpers", () => {await fetchWebuiThread("tok", "websocket:chat-1");expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread?projection=events",+ "/api/sessions/websocket%3Achat-1/webui-thread",expect.objectContaining({headers: { Authorization: "Bearer tok" },credentials: "same-origin",@@ -116,7 +115,7 @@ describe("webui API helpers", () => {});expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&projection=events",+ "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D",expect.objectContaining({headers: { Authorization: "Bearer tok" },credentials: "same-origin",@@ -128,7 +127,8 @@ describe("webui API helpers", () => {const cached = {schemaVersion: 3,revision: "rev-1",- messages: [],+ projection: "events" as const,+ events: [],};vi.mocked(fetch).mockResolvedValueOnce({ok: false,@@ -141,7 +141,7 @@ describe("webui API helpers", () => {})).resolves.toBe(cached);expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread?projection=events",+ "/api/sessions/websocket%3Achat-1/webui-thread",expect.objectContaining({headers: {Authorization: "Bearer tok",@@ -204,11 +204,84 @@ describe("webui API helpers", () => {await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({ events: [event] });});+ it("rejects legacy message-projected thread payloads", async () => {+ vi.mocked(fetch).mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({ schemaVersion: 3, messages: [] }),+ } as Response);++ await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(+ "Invalid WebUI thread events",+ );+ });++ it("accepts validated deferred trace metadata on canonical thread events", async () => {+ vi.mocked(fetch).mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({+ schemaVersion: 3,+ projection: "events",+ events: [{+ event: "message",+ chat_id: "chat-1",+ text: "exec(…)",+ kind: "progress",+ trace_detail: {+ ref: "2.history-aaaaaaaaaaaaaaaaaaaa",+ bytes: 40_000,+ traceCount: 1,+ },+ }],+ }),+ } as Response);++ await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({+ events: [{ trace_detail: { bytes: 40_000, traceCount: 1 } }],+ });+ });++ it("rejects malformed deferred trace metadata at the HTTP boundary", async () => {+ vi.mocked(fetch).mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({+ schemaVersion: 3,+ projection: "events",+ events: [{+ event: "message",+ chat_id: "chat-1",+ text: "exec(…)",+ kind: "progress",+ trace_detail: { ref: "bad", bytes: "many", traceCount: 1 },+ }],+ }),+ } as Response);++ await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(+ "Invalid WebUI thread projection event: message",+ );+ });+it("fetches deferred trace details with encoded session and ref", async () => {- await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");+ vi.mocked(fetch).mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({+ message_id: "history-aaaaaaaaaaaaaaaaaaaa",+ events: [],+ }),+ } as Response);++ await fetchWebuiThreadTraceDetail(+ "tok",+ "websocket:chat-1",+ "9.history-aaaaaaaaaaaaaaaaaaaa",+ );expect(fetch).toHaveBeenCalledWith(- "/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.tr-deadbeefdeadbeef",+ "/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.history-aaaaaaaaaaaaaaaaaaaa",expect.objectContaining({headers: { Authorization: "Bearer tok" },credentials: "same-origin",diff --git a/webui/src/tests/thread-display-compat.test.ts b/webui/src/tests/thread-display-projection.test.tssimilarity index 88%rename from webui/src/tests/thread-display-compat.test.tsrename to webui/src/tests/thread-display-projection.test.tsindex 28b70f6e2..7879eb978 100644--- a/webui/src/tests/thread-display-compat.test.ts+++ b/webui/src/tests/thread-display-projection.test.ts@@ -1,10 +1,7 @@import { describe, expect, it } from "vitest";import { deriveTitle, isModelCommandText, visibleSessionPreview } from "@/lib/format";-import {- normalizeLegacyLongTaskMessages,- projectWebuiThreadMessages,-} from "@/lib/thread-display-compat";+import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";import type { UIMessage } from "@/lib/types";const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);@@ -31,21 +28,7 @@ function message(};}-describe("normalizeLegacyLongTaskMessages", () => {- it("maps legacy long_task rows to trace lines", () => {- const legacy = {- id: "x",- role: "assistant",- kind: "long_task",- content: "long_task · done",- createdAt: 1,- } as unknown as UIMessage;- const out = normalizeLegacyLongTaskMessages([legacy]);- expect(out[0]!.kind).toBe("trace");- expect(out[0]!.role).toBe("tool");- expect(out[0]!.traces).toEqual(["long_task · done"]);- });-+describe("command display projection", () => {it("removes model and silent-command turns without hiding concurrent replies", () => {const visible = projectWebuiThreadMessages([message("user", { id: "model", content: "/model fast", turnId: "model-turn" }),@@ -139,7 +122,7 @@ describe("projectWebuiThreadMessages", () => {expect(visible[1]?.completedAt).toBeUndefined();});- it("uses the nearest user start for legacy rows without turn metadata", () => {+ it("uses the nearest user start for rows without turn metadata", () => {const visible = projectWebuiThreadMessages([message("user"),message("assistant", {diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.tsindex 1223a7afb..ee8f48d26 100644--- a/webui/src/tests/thread-event-projection.test.ts+++ b/webui/src/tests/thread-event-projection.test.ts@@ -20,6 +20,7 @@ const SEMANTIC_MESSAGE_FIELDS = ["kind","traces","toolEvents",+ "traceDetail","fileEdits","images","media",@@ -98,4 +99,35 @@ describe("canonical thread event projection", () => {const messages = projectThreadEvents(fixtureEvents(fixtureCase.transcript));expect(normalizeProjection(messages)).toEqual(fixtureCase.expected);});++ it("keeps deferred activity rows separately addressable in one segment", () => {+ const firstDetail = { ref: "2.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 };+ const secondDetail = { ref: "2.history-bbbbbbbbbbbbbbbbbbbb", bytes: 41_000, traceCount: 1 };++ const messages = projectThreadEvents([+ {+ event: "message",+ chat_id: "chat-1",+ text: "exec(…)",+ kind: "progress",+ projection_id: "history-aaaaaaaaaaaaaaaaaaaa",+ trace_detail: firstDetail,+ },+ {+ event: "message",+ chat_id: "chat-1",+ text: "read_file(…)",+ kind: "tool_hint",+ projection_id: "history-bbbbbbbbbbbbbbbbbbbb",+ trace_detail: secondDetail,+ },+ ]);++ expect(messages).toHaveLength(2);+ expect(messages.map((message) => message.traceDetail)).toEqual([+ firstDetail,+ secondDetail,+ ]);+ expect(messages[0].activitySegmentId).toBe(messages[1].activitySegmentId);+ });});diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsxindex 761afb73d..28436764e 100644--- a/webui/src/tests/thread-shell.test.tsx+++ b/webui/src/tests/thread-shell.test.tsx@@ -17,6 +17,7 @@ import type {UIMessage,WebuiThreadPersistedPayload,} from "@/lib/types";+import { canonicalThreadPayload } from "./thread-test-payload";const HERO_GREETING_PATTERN =/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;@@ -248,8 +249,8 @@ function session(chatId: string, modelPreset?: string | null) {function transcriptFromSimpleMessages(rows: Array<{ role: "user" | "assistant"; content: string; turnId?: string }>,-): { schemaVersion: number; messages: UIMessage[] } {- return {+): WebuiThreadPersistedPayload {+ return canonicalThreadPayload({schemaVersion: 3,messages: rows.map((m, i) => ({id: `m-${i}`,@@ -258,14 +259,19 @@ function transcriptFromSimpleMessages(...(m.turnId ? { turnId: m.turnId } : {}),createdAt: 1000 + i,})),- };+ })!;}function httpJson(body: unknown) {+ const normalized = body && typeof body === "object"+ && "schemaVersion" in body+ && "messages" in body+ ? canonicalThreadPayload(body as never)+ : body;return {ok: true,status: 200,- json: async () => body,+ json: async () => normalized,};}@@ -274,7 +280,7 @@ function traceDetailThread(answer: string,revision?: string,): WebuiThreadPersistedPayload {- return {+ return canonicalThreadPayload({schemaVersion: 3,...(revision ? { revision } : {}),messages: [@@ -285,7 +291,13 @@ function traceDetailThread(content: deferred ? "exec(…)" : 'exec({"command":"echo full"})',traces: [deferred ? "exec(…)" : 'exec({"command":"echo full"})'],...(deferred- ? { traceDetail: { ref: "1.trace-shared", bytes: 40_000, traceCount: 1 } }+ ? {+ traceDetail: {+ ref: "1.history-aaaaaaaaaaaaaaaaaaaa",+ bytes: 40_000,+ traceCount: 1,+ },+ }: {}),createdAt: 1_000,},@@ -296,7 +308,7 @@ function traceDetailThread(createdAt: 2_000,},],- };+ })!;}function setDocumentVisibility(value: DocumentVisibilityState): void {@@ -476,9 +488,14 @@ describe("ThreadShell", () => {return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });}return Promise.resolve(httpJson({- message_id: "trace-deferred",- content: 'exec({"command":"echo full"})',- traces: ['exec({"command":"echo full"})'],+ message_id: "history-aaaaaaaaaaaaaaaaaaaa",+ events: [{+ event: "message",+ chat_id: "trace-detail-retry",+ projection_id: "trace-deferred",+ kind: "progress",+ text: 'exec({"command":"echo full"})',+ }],}));}if (url.includes("websocket%3Atrace-detail-retry/webui-thread")) {@@ -491,7 +508,11 @@ describe("ThreadShell", () => {kind: "trace",content: "exec(…)",traces: ["exec(…)"],- traceDetail: { ref: "1.trace-deferred", bytes: 40_000, traceCount: 1 },+ traceDetail: {+ ref: "1.history-aaaaaaaaaaaaaaaaaaaa",+ bytes: 40_000,+ traceCount: 1,+ },createdAt: 1_000,},{ id: "answer", role: "assistant", content: "done", createdAt: 2_000 },@@ -521,9 +542,11 @@ describe("ThreadShell", () => {fireEvent.click(screen.getByRole("button", { name: "Retry" }));await waitFor(() => expect(detailCalls).toBe(2));await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());+ await waitFor(() => expect(document.body).toHaveTextContent("echo full"));- fireEvent.click(activity);- fireEvent.click(activity);+ const resolvedActivity = screen.getByRole("button", { name: /Worked/ });+ fireEvent.click(resolvedActivity);+ fireEvent.click(resolvedActivity);await act(async () => Promise.resolve());expect(detailCalls).toBe(2);});@@ -2652,11 +2675,6 @@ describe("ThreadShell", () => {});await waitFor(() => expect(screen.getByText("strict partial")).toBeInTheDocument());client.reconcileCanonicalCompletion.mockClear();- const reconcileAfterCommit = client.reconcileCanonicalCompletion.getMockImplementation();- client.reconcileCanonicalCompletion.mockImplementation((...args) => {- expect(screen.getByText("strict canonical answer")).toBeInTheDocument();- return reconcileAfterCommit?.(...args) ?? false;- });canonicalComplete = true;act(() => client._emitSessionUpdate("strict-canonical", "thread"));@@ -3673,7 +3691,10 @@ describe("ThreadShell", () => {{ role: "user", content: "question" },{ role: "assistant", content: "answer" },]);- thread.messages[1]!.media = [{+ const answer = thread.events.find(+ (event) => event.event === "message" && event.text === "answer",+ );+ if (answer?.event === "message") answer.media_urls = [{kind: "image",url: "/api/media/stable/image",name: "answer.png",@@ -3724,7 +3745,10 @@ describe("ThreadShell", () => {{ role: "user", content: "question" },{ role: "assistant", content: "answer" },]);- thread.messages[1]!.media = [{+ const answer = thread.events.find(+ (event) => event.event === "message" && event.text === "answer",+ );+ if (answer?.event === "message") answer.media_urls = [{kind: "image",url: "/api/media/stable/token-image",name: "token-answer.png",diff --git a/webui/src/tests/thread-test-payload.ts b/webui/src/tests/thread-test-payload.tsnew file mode 100644index 000000000..55858edff--- /dev/null+++ b/webui/src/tests/thread-test-payload.ts@@ -0,0 +1,154 @@+import type {+ ThreadProjectionEvent,+ UIMessage,+ WebuiThreadPersistedPayload,+} from "@/lib/types";++// UI-focused tests can describe their expected rows compactly here, but this+// builder always feeds the application the canonical event protocol. The HTTP+// boundary separately verifies that message-projected payloads are rejected.+type MessageFixturePayload = Omit<+ Partial<WebuiThreadPersistedPayload>,+ "events" | "projection"+> & {+ schemaVersion: number;+ messages: UIMessage[];+ fork_boundary_message_count?: number;+};++function eventBase(message: UIMessage, suffix = "") {+ return {+ chat_id: "test-history",+ projection_id: `${message.id}${suffix}`,+ created_at_ms: message.createdAt,+ ...(message.turnId ? { turn_id: message.turnId } : {}),+ ...(message.turnPhase ? { turn_phase: message.turnPhase } : {}),+ ...(message.turnSeq !== undefined ? { turn_seq: message.turnSeq } : {}),+ };+}++function completionEvent(message: UIMessage): ThreadProjectionEvent | null {+ if (+ message.latencyMs === undefined+ && message.usage === undefined+ && message.roundUsages === undefined+ && message.contextWindowTokens === undefined+ ) return null;+ return {+ event: "turn_end",+ ...eventBase(message, ":complete"),+ ...(message.latencyMs !== undefined ? { latency_ms: message.latencyMs } : {}),+ ...(message.usage ? { usage: message.usage } : {}),+ ...(message.roundUsages ? { round_usages: message.roundUsages } : {}),+ ...(message.contextWindowTokens !== undefined+ ? { context_window_tokens: message.contextWindowTokens }+ : {}),+ };+}++function messageEvents(message: UIMessage): ThreadProjectionEvent[] {+ const base = eventBase(message);+ if (message.role === "user") {+ return [{+ event: "user_message",+ ...base,+ text: message.content,+ starts_turn: true,+ ...(message.media?.length ? { media_urls: message.media } : {}),+ ...(message.cliApps?.length ? { cli_apps: message.cliApps } : {}),+ ...(message.mcpPresets?.length ? { mcp_presets: message.mcpPresets } : {}),+ ...(message.sessionMentions?.length+ ? { session_mentions: message.sessionMentions }+ : {}),+ }];+ }+ if (message.kind === "compaction" && message.compaction) {+ return [{+ event: "context_compaction",+ ...base,+ compaction_id: message.compaction.id,+ phase: message.compaction.phase,+ }];+ }+ if (message.kind === "trace" || message.role === "tool") {+ const events: ThreadProjectionEvent[] = [];+ const traces = message.traceDetail+ ? [message.content]+ : message.traces?.length+ ? message.traces+ : message.content+ ? [message.content]+ : [];+ traces.forEach((text, index) => {+ events.push({+ event: "message",+ ...eventBase(message, traces.length === 1 ? "" : `:trace:${index}`),+ text,+ kind: "progress",+ ...(index === traces.length - 1 && message.toolEvents?.length+ ? { tool_events: message.toolEvents }+ : {}),+ ...(index === 0 && message.traceDetail+ ? { trace_detail: message.traceDetail }+ : {}),+ });+ });+ if (message.fileEdits?.length) {+ events.push({+ event: "file_edit",+ ...eventBase(message, ":files"),+ edits: message.fileEdits,+ });+ }+ return events;+ }++ const events: ThreadProjectionEvent[] = [];+ if (message.reasoning) {+ events.push({+ event: "reasoning_delta",+ ...eventBase(message, ":reasoning"),+ text: message.reasoning,+ });+ events.push({+ event: "reasoning_end",+ ...eventBase(message, ":reasoning-end"),+ });+ }+ events.push({+ event: "message",+ ...base,+ text: message.content,+ ...(message.media?.length ? { media_urls: message.media } : {}),+ ...(message.latencyMs !== undefined ? { latency_ms: message.latencyMs } : {}),+ });+ const completion = completionEvent(message);+ if (completion) events.push(completion);+ return events;+}++export function canonicalThreadPayload(+ payload: WebuiThreadPersistedPayload | MessageFixturePayload | null,+): WebuiThreadPersistedPayload | null {+ if (payload === null || "events" in payload) return payload;+ const events = payload.messages.flatMap(messageEvents);+ const boundary = payload.fork_boundary_message_count;+ const forkBoundaryEventIndex = typeof boundary === "number"+ ? payload.messages.slice(0, boundary).flatMap(messageEvents).length+ : undefined;+ const rest = { ...payload } as Record<string, unknown>;+ delete rest.messages;+ delete rest.fork_boundary_message_count;+ const canonical = payload as unknown as Record<string, unknown>;+ delete canonical.messages;+ delete canonical.fork_boundary_message_count;+ Object.assign(canonical, {+ ...rest,+ projection: "events",+ events,+ ...(forkBoundaryEventIndex !== undefined+ ? { fork_boundary_event_index: forkBoundaryEventIndex }+ : {}),+ });+ return payload as unknown as WebuiThreadPersistedPayload;+}diff --git a/webui/src/tests/useSessions.test.tsx b/webui/src/tests/useSessions.test.tsxindex af5feae46..6177cbe57 100644--- a/webui/src/tests/useSessions.test.tsx+++ b/webui/src/tests/useSessions.test.tsx@@ -6,6 +6,7 @@ import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessionimport * as api from "@/lib/api";import { webuiThreadCache } from "@/lib/webui-thread-cache";import { ClientProvider } from "@/providers/ClientProvider";+import { canonicalThreadPayload } from "./thread-test-payload";vi.mock("@/lib/api", async (importOriginal) => {const actual = await importOriginal<typeof import("@/lib/api")>();@@ -17,6 +18,16 @@ vi.mock("@/lib/api", async (importOriginal) => {};});+const fetchThreadMock = vi.mocked(api.fetchWebuiThread);+const rawMockResolvedValue = fetchThreadMock.mockResolvedValue.bind(fetchThreadMock);+const rawMockResolvedValueOnce = fetchThreadMock.mockResolvedValueOnce.bind(fetchThreadMock);+fetchThreadMock.mockResolvedValue = ((value) => rawMockResolvedValue(+ canonicalThreadPayload(value as never),+)) as typeof fetchThreadMock.mockResolvedValue;+fetchThreadMock.mockResolvedValueOnce = ((value) => rawMockResolvedValueOnce(+ canonicalThreadPayload(value as never),+)) as typeof fetchThreadMock.mockResolvedValueOnce;+function fakeClient() {const sessionUpdateHandlers = new Set<(chatId: string, scope?: string) => void>();return {@@ -1246,7 +1257,7 @@ describe("useSessions", () => {expect(result.current.lineage).toBeGreaterThan(oldLineage);await act(async () => {- resolveOlder?.({+ resolveOlder?.(canonicalThreadPayload({schemaVersion: 3,messages: [{ id: "stale-prefix", role: "user", content: "stale prefix", createdAt: 1 },@@ -1255,7 +1266,7 @@ describe("useSessions", () => {before_cursor: null,has_more_before: false,},- });+ }));await olderRequest;});