refactor(webui): remove legacy message projection (#5823)
* refactor(webui): defer oversized replay traces as events * fix(webui): type deferred trace index set * refactor(webui): remove legacy message projection * fix(webui): type event protocol boundaries * test(webui): assert canonical thread events
This commit is contained in:
1 parent
756c8bb7ed
commit
0983762fe5
23 files changed
+943
-2839
No files matched your search
@@ -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_reco
|
||||
assert body is not None
|
||||
assert read_transcript_lines(key)[-1]["transcript_incomplete"] is True
|
||||
assert 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_res
|
||||
|
||||
assert response.status_code == 200
|
||||
body = 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 == 200
|
||||
body = 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 == 200
|
||||
body = 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 == 200
|
||||
body = 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_pending
|
||||
assert 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 == 200
|
||||
body = 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 True
|
||||
assert 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.0
|
||||
encoded = 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 == 200
|
||||
body = 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 == 200
|
||||
body = 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 == 200
|
||||
body = 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 == 200
|
||||
body = 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",
|
||||
]
|
||||
@@ -331,7 +331,14 @@ async def test_sessions_list_and_thread_restore_transcript_without_canonical_fil
|
||||
assert [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())) == 1
|
||||
|
||||
fetched = 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 == 200
|
||||
assert 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"] == trace
|
||||
|
||||
append_transcript_object(
|
||||
key,
|
||||
|
||||
@@ -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.
|
||||
|
||||
+180
-1265
File diff suppressed because it is too large.
Load diff
@@ -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:
|
||||
|
||||
@@ -24,8 +24,8 @@ from nanobot.providers.fallback_provider import FallbackProvider
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from 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"] == expected
|
||||
|
||||
|
||||
async 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"] == expected
|
||||
|
||||
|
||||
async 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, monkeyp
|
||||
sources[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 True
|
||||
@@ -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 0
|
||||
calls.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)
|
||||
|
||||
|
||||
@@ -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"]
|
||||
+131
-1244
File diff suppressed because it is too large.
Load diff
@@ -1,54 +0,0 @@
|
||||
"""WebUI replay behavior for structured context-compaction events."""
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.webui.transcript import replay_transcript_to_ui_messages
|
||||
|
||||
|
||||
@pytest.mark.parametrize("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)
|
||||
@@ -202,7 +202,11 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
|
||||
f"{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 contents
|
||||
assert any("Current model: `custom/smoke-model`" in text for text in contents)
|
||||
assert "!printf shell-ok" in contents
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+36
-8
@@ -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(
|
||||
|
||||
+1
-22
@@ -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; message
|
||||
function 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)
|
||||
@@ -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),
|
||||
|
||||
+12
-15
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
+3
-20
@@ -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", {
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSession
|
||||
import * 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;
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user