diff --git a/docs/guides/configure-model-fallback.md b/docs/guides/configure-model-fallback.md index 93a428df9..2246eb296 100644 --- a/docs/guides/configure-model-fallback.md +++ b/docs/guides/configure-model-fallback.md @@ -63,6 +63,12 @@ for common providers. ## Production notes +- In the WebUI, a reply produced by a named fallback preset shows its provider + logo and preset name next to the reply timestamp. Hover, focus, or click the + badge for an explanation. The composer still shows your selected preset; + primary replies have no fallback badge. Saved replies retain the name used + for that invocation, even after a preset is renamed or deleted. Older replies + without recorded attribution and unnamed inline fallback objects are not labeled. - Keep fallback context windows realistic; smaller fallback windows constrain how much context can fit. - Put cheaper or faster fallbacks before expensive ones when acceptable. diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py index 757e9f0d9..b985c7480 100644 --- a/nanobot/agent/runner.py +++ b/nanobot/agent/runner.py @@ -6,7 +6,7 @@ import asyncio import time from collections.abc import Awaitable, Callable, Iterable from copy import deepcopy -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, cast @@ -36,6 +36,7 @@ from nanobot.providers.base import ( LLMProvider, LLMResponse, LLMUsage, + ProviderCallContext, ProviderConversationState, ) from nanobot.providers.conversation_state import ProviderConversationStateController @@ -885,6 +886,10 @@ class AgentRunner: tools=tool_definitions, ) wants_streaming = hook.wants_streaming() + provider_context = replace( + provider_context or ProviderCallContext(), + response_preset=spec.runtime.model_preset or "", + ) active_hosted_tools: dict[str, dict[str, Any]] = {} native_reasoning_open = False @@ -1235,7 +1240,10 @@ class AgentRunner: ) response = await spec.runtime.provider.chat_stream_with_retry( **kwargs, - provider_context=provider_context, + provider_context=replace( + provider_context or ProviderCallContext(), + response_preset=spec.runtime.model_preset or "", + ), ) await self.context_governor.summarize_provider_compaction( request_state, diff --git a/nanobot/agent/turn_delivery.py b/nanobot/agent/turn_delivery.py index 3a035da22..672e2ef5c 100644 --- a/nanobot/agent/turn_delivery.py +++ b/nanobot/agent/turn_delivery.py @@ -20,9 +20,10 @@ from nanobot.bus.outbound_events import ( from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import RuntimeEventPublisher from nanobot.channels.notification_routes import notification_metadata -from nanobot.events import AgentEvent, EventSink +from nanobot.events import AgentEvent, EventSink, ResponseSource, ResponseSourceEvent from nanobot.providers.base import LLMUsage from nanobot.session.keys import UNIFIED_SESSION_KEY, last_channel_from_metadata +from nanobot.utils.helpers import strip_think if TYPE_CHECKING: from nanobot.utils.llm_runtime import LLMRuntime @@ -194,6 +195,11 @@ class TurnDelivery: _stop_reason: str | None = field(init=False, default=None) _failure_error_kind: str | None = field(init=False, default=None) _retry_status: RetryStatusEvent | None = field(init=False, default=None) + _response_source: ResponseSource | None = field(init=False, default=None) + _response_source_seen: bool = field(init=False, default=False) + _response_content: str | None = field(init=False, default=None) + _stream_sources: list[ResponseSource] = field(init=False, default_factory=list) + _stream_source_unknown: bool = field(init=False, default=False) def __post_init__(self) -> None: self._routed_events = _bind_events(self.bus, self.route) @@ -305,6 +311,16 @@ class TurnDelivery: if response is not None: completed_channel = response.channel completed_chat_id = response.chat_id + if ( + self._response_source is not None + and self._response_content is not None + and strip_think(self._response_content).strip() == response.content.strip() + and stop_reason not in {"error", "tool_error"} + ): + response = dataclasses.replace(response, metadata={ + **response.metadata, + "response_sources": [dataclasses.asdict(self._response_source)], + }) if response.channel != "websocket" or stop_reason != "error": await self.bus.publish_outbound(response) elif self.lifecycle_message.channel == "cli": @@ -365,13 +381,40 @@ class TurnDelivery: return f"{self._stream_base_id}:{self._stream_segment}" async def _publish_event(self, event: AgentEvent) -> None: + if isinstance(event, ResponseSourceEvent): + self._response_source_seen = True + self._response_source = event.source + self._response_content = event.content + return if isinstance(event, RetryStatusEvent): self._retry_status = event if event.state == "exhausted" else None if isinstance(event, StreamDeltaEvent | StreamEndEvent): if not self.streaming: return event = dataclasses.replace(event, stream_id=self._stream_id()) - if self._routed_events.publish is not None: + if isinstance(event, StreamDeltaEvent) and event.content: + source = self._response_source + if ( + self._response_content is not None + and event.content.strip() not in strip_think(self._response_content) + ): + source = None + if source is None: + self._stream_source_unknown = True + if source is not None and source not in self._stream_sources: + self._stream_sources.append(source) + if self._routed_events.accepts(type(event)): + metadata = deepcopy(self.route.metadata) + if self._response_source_seen and self._routed_events.accepts(ResponseSourceEvent): + metadata["response_sources"] = ( + [] if self._stream_source_unknown else + [dataclasses.asdict(source) for source in self._stream_sources] + ) + await self.bus.publish_event( + event, channel=self.route.channel, chat_id=self.route.chat_id, + metadata=metadata, + ) + elif self._routed_events.publish is not None: await self._routed_events.publish(event) if isinstance(event, StreamDeltaEvent): self._stream_open = True @@ -379,6 +422,8 @@ class TurnDelivery: self._stream_open = event.merge_next if not event.merge_next: self._stream_segment += 1 + self._stream_sources.clear() + self._stream_source_unknown = False async def abort_stream(self) -> None: """Close an interrupted stream so stateful channels can release its buffer.""" diff --git a/nanobot/bus/notification_delivery.py b/nanobot/bus/notification_delivery.py index c08934717..a821849fc 100644 --- a/nanobot/bus/notification_delivery.py +++ b/nanobot/bus/notification_delivery.py @@ -9,7 +9,13 @@ from nanobot.bus.outbound_events import ( StreamDeltaEvent, StreamEndEvent, ) -from nanobot.events import AgentEvent, ContextCompactionEvent, RecoveryStateEvent, RetryWaitEvent +from nanobot.events import ( + AgentEvent, + ContextCompactionEvent, + RecoveryStateEvent, + ResponseSourceEvent, + RetryWaitEvent, +) NotificationAudience = Literal["channel", "lifecycle", "interactive"] @@ -22,6 +28,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = { RetryWaitEvent: "lifecycle", RecoveryStateEvent: "interactive", RetryStatusEvent: "interactive", + ResponseSourceEvent: "interactive", } diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index 1da6aad9a..9d6a7f1e1 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -975,7 +975,11 @@ class ChannelManager: is_delta = isinstance(next_event, StreamDeltaEvent) is_end = isinstance(next_event, StreamEndEvent) - if same_target and (is_delta or (is_end and next_msg.content)): + same_response_sources = ( + next_msg.metadata.get("response_sources") + == first_msg.metadata.get("response_sources") + ) + if same_target and same_response_sources and (is_delta or (is_end and next_msg.content)): # Accumulate content combined_content += next_msg.content # If we see stream_end, remember it and stop coalescing this stream diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index 1105e4a7c..6454c09f4 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -1106,6 +1106,9 @@ class WebSocketChannel(BaseChannel): ) -> bool: """Persist one canonical turn event and retain unsafe owners on failure.""" if not self._temporary_chats.should_persist_transcript(chat_id): + self._transcripts.prepare_event( + chat_id, event, metadata=metadata, phase=phase, include_source=include_source, + ) return True persisted = self._transcripts.prepare_and_append( chat_id, @@ -1150,6 +1153,9 @@ class WebSocketChannel(BaseChannel): ) -> bool: """Persist the canonical end of a live stream, never its wire chunks.""" if not self._temporary_chats.should_persist_transcript(chat_id): + self._transcripts.prepare_event( + chat_id, event, metadata=metadata, phase=phase, include_source=include_source, + ) return True persisted = self._transcripts.prepare_and_append_stream_event( chat_id, diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index b8ce94ca5..b624c82a2 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -6032,9 +6032,15 @@ def test_handle_webui_thread_get_accepts_pagination_query(tmp_path, monkeypatch) assert body["page"]["before_cursor"] +@pytest.mark.parametrize("sources", [ + None, + [], + [{"provider": "xai", "model": "grok", "preset": "saved backup", "fallback": True}], +]) def test_handle_webui_thread_get_negotiates_client_event_projection( tmp_path, monkeypatch, + sources, ) -> None: from urllib.parse import quote @@ -6051,7 +6057,10 @@ def test_handle_webui_thread_get_negotiates_client_event_projection( ) append_transcript_object( key, - {"event": "message", "chat_id": "event-route", "text": "answer"}, + { + "event": "message", "chat_id": "event-route", "text": "answer", + **({"response_sources": sources} if sources is not None else {}), + }, ) append_transcript_object(key, {"event": "turn_end", "chat_id": "event-route"}) @@ -6074,6 +6083,11 @@ def test_handle_webui_thread_get_negotiates_client_event_projection( "message", "turn_end", ] + answer = body["events"][1] + if sources is None: + assert "response_sources" not in answer + else: + assert answer["response_sources"] == sources def test_handle_file_preview_returns_workspace_file(tmp_path) -> None: diff --git a/nanobot/events.py b/nanobot/events.py index e4308f768..fa7504ecd 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -13,6 +13,26 @@ class AgentEvent: """A typed event; only explicitly projected events cross a client boundary.""" +@dataclass(frozen=True) +class ResponseSource: + """Display-safe identity captured at the actual provider invocation.""" + + provider: str + model: str + preset: str + fallback: bool = False + + +@dataclass(frozen=True) +class ResponseSourceEvent(AgentEvent): + """Set the source of subsequent answer text in this operation only.""" + + source: ResponseSource | None + # Completed provider text authorizes attribution of a non-streamed reply; + # synthetic runner/command messages must not inherit the last model's name. + content: str | None = None + + @dataclass(frozen=True) class ContextCompactionEvent(AgentEvent): compaction_id: str diff --git a/nanobot/providers/base.py b/nanobot/providers/base.py index 31176c708..53fdc41c1 100644 --- a/nanobot/providers/base.py +++ b/nanobot/providers/base.py @@ -19,7 +19,14 @@ from typing import TYPE_CHECKING, Any, Literal, cast import json_repair from loguru import logger -from nanobot.events import NO_EVENTS, EventSink, RetryStatusEvent, RetryWaitEvent +from nanobot.events import ( + NO_EVENTS, + EventSink, + ResponseSource, + ResponseSourceEvent, + RetryStatusEvent, + RetryWaitEvent, +) from nanobot.utils.helpers import sanitize_surrogates_deep if TYPE_CHECKING: @@ -263,6 +270,9 @@ class ProviderCallContext: context_window_tokens: int | None = None session_id: str | None = field(default=None, repr=False) events: EventSink = field(default=NO_EVENTS, repr=False, compare=False) + # None opts out (auxiliary calls); an empty name denotes an unnamed preset. + response_preset: str | None = None + response_is_fallback: bool = False @dataclass(frozen=True, slots=True) @@ -1599,8 +1609,47 @@ class LLMProvider(ABC): ) -> LLMResponse: """Run one chat entry point through this provider's retry policy.""" call = self._safe_chat_stream if stream else self._safe_chat + + async def attributed_call(**kwargs: Any) -> LLMResponse: + context = kwargs.get("provider_context") + if ( + not isinstance(context, ProviderCallContext) + or context.response_preset is None + or not context.events.accepts(ResponseSourceEvent) + ): + return await call(**kwargs) + source = ( + ResponseSource( + provider=self.provider_name, + model=kwargs.get("model") or self.get_default_model(), + preset=context.response_preset, + fallback=context.response_is_fallback, + ) + if context.response_preset else None + ) + await context.events.emit(ResponseSourceEvent(None)) + delta_callback = kwargs.get("on_content_delta") + source_sent = False + + async def attributed_delta(text: str) -> None: + nonlocal source_sent + if text and not source_sent: + await context.events.emit(ResponseSourceEvent(source)) + source_sent = True + if delta_callback is not None: + await delta_callback(text) + + if delta_callback is not None: + kwargs["on_content_delta"] = attributed_delta + response = await call(**kwargs) + await context.events.emit(ResponseSourceEvent( + source if response.finish_reason != "error" and response.content else None, + content=response.content if response.finish_reason != "error" else None, + )) + return response + return await self._run_with_retry( - call, + attributed_call, kw, original_messages, retry_mode=retry_mode, @@ -1826,6 +1875,8 @@ class LLMProvider(ABC): ), session_id=provider_context.session_id, events=provider_context.events, + response_preset=provider_context.response_preset, + response_is_fallback=provider_context.response_is_fallback, ) if stripped is not None or stripped_context is not None: logger.warning( diff --git a/nanobot/providers/factory.py b/nanobot/providers/factory.py index d6f0483b6..7f186f2b4 100644 --- a/nanobot/providers/factory.py +++ b/nanobot/providers/factory.py @@ -292,6 +292,10 @@ def make_provider( fallback_presets=fallback_presets, provider_factory=lambda fb: _make_provider_core(config, preset=fb), primary_context_window_tokens=resolved.context_window_tokens, + fallback_preset_names=[ + fallback if isinstance(fallback, str) else None + for fallback in config.agents.defaults.fallback_models + ], ) return provider @@ -366,6 +370,10 @@ def provider_signature( resolved.context_window_tokens, getattr(p, "proxy", None) if p else None, p.thinking_style if p else None, + tuple( + fallback if isinstance(fallback, str) else None + for fallback in config.agents.defaults.fallback_models + ), tuple(_fallback_signature(fallback) for fallback in fallback_presets), ) diff --git a/nanobot/providers/fallback_provider.py b/nanobot/providers/fallback_provider.py index 75dc9dfb6..2831d5151 100644 --- a/nanobot/providers/fallback_provider.py +++ b/nanobot/providers/fallback_provider.py @@ -128,12 +128,18 @@ class FallbackProvider(LLMProvider): provider_factory: Callable[[Any], LLMProvider], fallback_model_observer: FallbackModelObserver | None = None, primary_context_window_tokens: int | None = None, + fallback_preset_names: list[str | None] | None = None, ): primary_generation = primary.generation self._primary = primary super().__init__(provider_name=primary.provider_name) self._primary.generation = primary_generation self._fallback_presets = list(fallback_presets) + self._fallback_preset_names = tuple( + fallback_preset_names or [None] * len(fallback_presets) + ) + if len(self._fallback_preset_names) != len(self._fallback_presets): + raise ValueError("fallback preset names must match fallback candidates") self._provider_factory = provider_factory self._fallback_model_observer = fallback_model_observer self._primary_context_window_tokens = primary_context_window_tokens @@ -188,6 +194,8 @@ class FallbackProvider(LLMProvider): context_window_tokens=context_window_tokens, session_id=provider_context.session_id, events=provider_context.events, + response_preset=provider_context.response_preset, + response_is_fallback=provider_context.response_is_fallback, ) def _primary_available(self) -> bool: @@ -579,6 +587,11 @@ class FallbackProvider(LLMProvider): context_window_tokens=context_window_tokens, session_id=provider_context.session_id, events=provider_context.events, + response_preset=( + self._fallback_preset_names[idx] or "" + if provider_context.response_preset is not None else None + ), + response_is_fallback=provider_context.response_preset is not None, ) if fallback.reasoning_effort is None: fallback_kwargs.pop("reasoning_effort", None) diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index ec9c1f17b..734387d4a 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -88,6 +88,26 @@ _SESSION_MENTION_NAME_RE = re.compile(r"^[\w-]+$") _SESSION_HANDLE_ID_RE = re.compile(r"^handle_[0-9a-f]{32}$") +def _response_sources(value: object) -> list[dict[str, str | bool]]: + """Allow only recorded display identity, never settings or credential blobs.""" + if not isinstance(value, list): + return [] + result: list[dict[str, str | bool]] = [] + keys = ("provider", "model", "preset") + for item in cast(list[object], value): + if not isinstance(item, dict): + return [] + fields = cast(dict[str, object], item) + if any(not isinstance(fields.get(key), str) or not fields[key] for key in keys): + return [] + source: dict[str, str | bool] = {key: cast(str, fields[key]) for key in keys} + # Old records without an explicit fallback flag must not guess from model names. + source["fallback"] = fields.get("fallback") is True + if source not in result: + result.append(source) + return result + + def _sanitize_turn_usage(value: object) -> dict[str, int] | None: if not isinstance(value, dict): return None @@ -1186,6 +1206,8 @@ class WebUITranscriptRecorder: ) -> None: if include_source and (source := webui_message_source(metadata)): event["source"] = source + if include_source and metadata is not None and "response_sources" in metadata: + event["response_sources"] = _response_sources(metadata["response_sources"]) self._annotate_turn(chat_id, event, metadata, phase) def prepare_and_append( @@ -2265,14 +2287,17 @@ def replay_transcript_to_ui_messages( 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 {} + 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: dict[str, Any] = {"source": {"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() @@ -3241,6 +3266,8 @@ def _client_projection_event( ) -> dict[str, Any] | None: event = record.get("event") common = _client_projection_common_fields(record) + if event in {"delta", "stream_end", "message"} and "response_sources" in record: + common["response_sources"] = _response_sources(record["response_sources"]) if event == "user": projected: dict[str, Any] = { "event": "user_message", diff --git a/tests/agent/test_response_source.py b/tests/agent/test_response_source.py new file mode 100644 index 000000000..65746ff41 --- /dev/null +++ b/tests/agent/test_response_source.py @@ -0,0 +1,358 @@ +"""Actual invocation identity survives delivery and the display transcript.""" + +import asyncio +import json +from copy import deepcopy +from dataclasses import asdict +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from nanobot.agent.progress_hook import AgentProgressHook +from nanobot.agent.runner import AgentRunner, AgentRunSpec +from nanobot.agent.tools.registry import ToolRegistry +from nanobot.agent.turn_delivery import TurnDeliveryFactory +from nanobot.bus.events import InboundMessage, OutboundMessage +from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent +from nanobot.bus.queue import MessageBus +from nanobot.channels.websocket.runtime import WebSocketChannel +from nanobot.config.schema import Config, ModelPresetConfig +from nanobot.events import EventSink, ResponseSource, ResponseSourceEvent +from nanobot.providers.base import LLMProvider, LLMResponse, ProviderCallContext +from nanobot.providers.factory import make_provider, provider_signature +from nanobot.providers.fallback_provider import FallbackProvider +from nanobot.utils.llm_runtime import LLMRuntime +from nanobot.webui.transcript import ( + WebUITranscriptRecorder, + build_webui_thread_response, + replay_transcript_to_ui_messages, + webui_transcript_path, +) + + +class AnswerProvider(LLMProvider): + def __init__(self, name, text="answer", *, fail=False, chunks=()): + super().__init__(provider_name=name) + self.text, self.fail, self.chunks = text, fail, chunks + + def get_default_model(self): + return "same-model" + + async def chat(self, **kwargs): + return LLMResponse( + content=self.text, + finish_reason="error" if self.fail else "stop", + error_status_code=401 if self.fail else None, + ) + + async def chat_stream(self, on_content_delta=None, **kwargs): + if on_content_delta: + for text in self.chunks: + await asyncio.sleep(0) + await on_content_delta(text) + return await self.chat(**kwargs) + + +def delivery(chat="chat", *, streaming=True): + bus = MessageBus() + turn = TurnDeliveryFactory(bus).create(InboundMessage( + channel="websocket", sender_id="user", chat_id=chat, content="hello", + metadata={"_wants_stream": streaming, "webui_turn_id": f"turn-{chat}"}, + ), f"websocket:{chat}", enable_stream=streaming) + return bus, turn + + +@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): + bus, turn = delivery(streaming=streaming) + candidates = [AnswerProvider( + f"provider-{i}", fail=i < failures, + chunks=("answer",) if streaming and i >= failures else (), + ) for i in range(3)] + fallback = FallbackProvider( + candidates[0], [ModelPresetConfig(model="same-model")] * 2, + lambda _: candidates.pop(1), fallback_preset_names=["backup-one", "backup-two"], + ) + + async def delta(text): + await turn.events.emit(StreamDeltaEvent(text)) + + result = await fallback.chat_stream_with_retry( + messages=[{"role": "user", "content": "hello"}], + model="same-model", on_content_delta=delta if streaming else None, + provider_context=ProviderCallContext(events=turn.events, response_preset="chosen"), + ) + if streaming: + await turn.events.emit(StreamEndEvent()) + else: + turn.record_stop_reason("error" if result.finish_reason == "error" else "completed") + await turn.complete(OutboundMessage( + channel="websocket", chat_id="chat", content=result.content or "", + ), publish_completion=False) + records = [] + recorder = WebUITranscriptRecorder() + while not bus.outbound.empty(): + msg = bus.outbound.get_nowait() + if msg.event is not None and not isinstance(msg.event, StreamDeltaEvent | StreamEndEvent): + continue + record = { + "event": "stream_end" if isinstance(msg.event, StreamEndEvent) else + "delta" if isinstance(msg.event, StreamDeltaEvent) else "message", + "text": "answer" if isinstance(msg.event, StreamEndEvent) and failures < 3 else msg.content, + } + 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"]) + if failures == 3: + assert all(not r.get("response_sources") for r in records) + assert all(not r.get("responseSources") for r in replay) + else: + 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 + + +async def test_fallback_flag_is_call_scoped_even_with_identical_identity(): + seen = [] + + async def publish(event): + if isinstance(event, ResponseSourceEvent) and event.source is not None: + seen.append(event.source) + + primary = AnswerProvider("openai", fail=True) + provider = FallbackProvider( + primary, [ModelPresetConfig(model="same-model")], lambda _: AnswerProvider("openai"), + fallback_preset_names=["chosen"], + ) + context = ProviderCallContext(events=EventSink(publish), response_preset="chosen") + await provider.chat_with_retry(messages=[], provider_context=context) + primary.fail = False + await provider.chat_with_retry(messages=[], provider_context=context) + assert seen == [ + ResponseSource("openai", "same-model", "chosen", fallback=True), + ResponseSource("openai", "same-model", "chosen", fallback=False), + ] + + +async def test_auxiliary_calls_do_not_publish_response_identity(): + seen = [] + + async def publish(event): + seen.append(event) + + await AnswerProvider("auxiliary").chat_stream_with_retry( + messages=[], provider_context=ProviderCallContext(events=EventSink(publish)), + ) + assert not any(isinstance(event, ResponseSourceEvent) for event in seen) + + +@pytest.mark.parametrize("with_tools", [False, True]) +@pytest.mark.parametrize("with_images", [False, True]) +@pytest.mark.parametrize("fallback", [False, True]) +async def test_attribution_does_not_change_provider_requests(with_tools, with_images, fallback): + """Display metadata must not modify the cacheable prompt or generation payload.""" + requests = [] + + class CapturingProvider(AnswerProvider): + async def chat(self, **kwargs): + requests.append((self.provider_name, deepcopy({ + key: value for key, value in kwargs.items() if not key.startswith("on_") + }))) + if with_images and len(requests) == 1: + return LLMResponse(content="Images unsupported", finish_reason="error", + error_status_code=400) + return await super().chat(**kwargs) + + messages = [{"role": "system", "content": "Stable system prompt"}, + {"role": "user", "content": "Hello"}] + if with_images: + messages[-1]["content"] = [ + {"type": "text", "text": "Hello"}, + {"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}}, + ] + tools = [{"type": "function", "function": {"name": "test_tool", "parameters": { + "type": "object", "properties": {}, + }}}] if with_tools else None + original = deepcopy(messages) + results = [] + for preset in (None, "primary"): + requests.clear() + provider = FallbackProvider( + CapturingProvider("primary", fail=fallback), + [ModelPresetConfig(model="same-model")], lambda _: CapturingProvider("backup"), + fallback_preset_names=["backup"], + ) + result = await provider.chat_stream_with_retry( + messages=deepcopy(messages), tools=tools, model="same-model", + provider_context=ProviderCallContext(events=EventSink(AsyncMock()), response_preset=preset), + ) + assert result.content == "answer" + results.append(deepcopy(requests)) + assert results[0] == results[1] + assert messages == original + + +@pytest.mark.parametrize("streaming", [False, True]) +async def test_synthetic_final_text_does_not_inherit_an_earlier_model(streaming): + bus, turn = delivery(streaming=streaming) + await turn.events.emit(ResponseSourceEvent(ResponseSource("openai", "gpt", "codex"), "Working")) + if streaming: + await turn.events.emit(StreamDeltaEvent("Reached the iteration limit")) + await turn.events.emit(StreamEndEvent()) + else: + await turn.complete(OutboundMessage(channel="websocket", chat_id="chat", content="Reached the iteration limit"), publish_completion=False) + while not bus.outbound.empty(): + assert not bus.outbound.get_nowait().metadata.get("response_sources") + + +async def test_unnamed_fallback_does_not_borrow_the_primary_preset(): + bus, turn = delivery() + provider = FallbackProvider(AnswerProvider("openai", fail=True), [ModelPresetConfig(model="grok")], + lambda _: AnswerProvider("xai", chunks=("answer",))) + + async def delta(text): + await turn.events.emit(StreamDeltaEvent(text)) + + await provider.chat_stream_with_retry(messages=[], on_content_delta=delta, + provider_context=ProviderCallContext(events=turn.events, response_preset="primary")) + await turn.events.emit(StreamEndEvent()) + while not bus.outbound.empty(): + assert not bus.outbound.get_nowait().metadata.get("response_sources") + + +async def test_concurrent_calls_and_segments_have_independent_snapshots(): + async def run(chat, preset): + bus, turn = delivery(chat) + + async def delta(text): + await turn.events.emit(StreamDeltaEvent(text)) + + await AnswerProvider("openai", chunks=("one", "two")).chat_stream_with_retry( + messages=[], on_content_delta=delta, + provider_context=ProviderCallContext(events=turn.events, response_preset=preset), + ) + await turn.events.emit(StreamEndEvent()) + return [bus.outbound.get_nowait() for _ in range(bus.outbound.qsize())] + + left, right = await asyncio.gather(run("left", "writer"), run("right", "reviewer")) + assert {m.metadata["response_sources"][0]["preset"] for m in left if isinstance(m.event, StreamDeltaEvent | StreamEndEvent)} == {"writer"} + assert {m.metadata["response_sources"][0]["preset"] for m in right if isinstance(m.event, StreamDeltaEvent | StreamEndEvent)} == {"reviewer"} + + +async def test_merged_segments_keep_all_actual_sources_and_unknown_text_is_not_mislabeled(): + bus, turn = delivery() + a = ResponseSource("openai", "a", "writer") + b = ResponseSource("xai", "b", "reviewer", fallback=True) + for source in (a, b): + await turn.events.emit(ResponseSourceEvent(source)) + await turn.events.emit(StreamDeltaEvent("text")) + await turn.events.emit(StreamEndEvent(resuming=True, merge_next=True)) + assert bus.outbound.get_nowait().metadata["response_sources"] == [asdict(a)] + bus.outbound.get_nowait() + assert bus.outbound.get_nowait().metadata["response_sources"] == [asdict(a), asdict(b)] + bus.outbound.get_nowait() + await turn.events.emit(ResponseSourceEvent(None)) + await turn.events.emit(StreamDeltaEvent("unattributed text")) + await turn.events.emit(StreamEndEvent()) + assert bus.outbound.get_nowait().metadata["response_sources"] == [] + assert bus.outbound.get_nowait().metadata["response_sources"] == [] + await turn.events.emit(ResponseSourceEvent(b)) + await turn.events.emit(StreamDeltaEvent("new segment")) + assert bus.outbound.get_nowait().metadata["response_sources"] == [asdict(b)] + + +def test_factory_captures_names_even_when_models_and_settings_are_identical(): + config = Config.model_validate({ + "agents": {"defaults": {"modelPreset": "primary", "fallbackModels": ["backup"]}}, + "modelPresets": {name: {"provider": "openai", "model": "same-model"} + for name in ("primary", "backup", "renamed")}, + "providers": {"openai": {"apiKey": "test-only"}}, + }) + before = provider_signature(config) + provider = make_provider(config) + config.agents.defaults.fallback_models = ["renamed"] + assert provider_signature(config) != before + assert provider._fallback_preset_names == ("backup",) + assert make_provider(config)._fallback_preset_names == ("renamed",) + + +def test_old_history_and_malformed_identity_are_not_guessed(): + messages = replay_transcript_to_ui_messages([ + {"event": "message", "text": "legacy"}, + {"event": "message", "text": "invalid", "response_sources": [{"model": "gpt"}]}, + {"event": "message", "text": "recorded", "response_sources": [ + {"provider": "xai", "model": "grok", "preset": "old name", "api_key": "never expose"}, + ]}, + {"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"] == [] + expected = [{"provider": "xai", "model": "grok", "preset": "old name", "fallback": False}] + assert messages[2]["responseSources"] == expected + assert messages[3]["responseSources"] == expected + + +async def test_runner_records_each_provider_when_streaming_times_out_and_recovers(): + class StalledProvider(AnswerProvider): + _CHAT_RETRY_DELAYS = () + + async def chat(self, **kwargs): + return LLMResponse(content="stalled", finish_reason="error", error_kind="timeout") + + bus, turn = delivery() + primary = StalledProvider("openai_codex", chunks=("Partial answer",)) + backup = AnswerProvider("xai", text="Recovered answer", chunks=("Recovered answer",)) + provider = FallbackProvider(primary, [ModelPresetConfig(model="grok")], lambda _: backup, + fallback_preset_names=["grok"]) + runtime = LLMRuntime.capture(provider, "gpt", context_window_tokens=32_000, model_preset="codex") + result = await AgentRunner().run(AgentRunSpec( + initial_messages=[{"role": "user", "content": "hello"}], tools=ToolRegistry(), + runtime=runtime, max_iterations=2, max_tool_result_chars=4096, + session_key="websocket:chat", events=turn.events, + hook=AgentProgressHook(turn.events, streaming=True), + )) + assert result.final_content == "Recovered answer" + outgoing = [bus.outbound.get_nowait() for _ in range(bus.outbound.qsize())] + ends = [msg for msg in outgoing if isinstance(msg.event, StreamEndEvent)] + assert [m.metadata["response_sources"][0]["preset"] for m in ends if m.metadata["response_sources"]] == ["codex", "grok"] + assert [m.metadata["response_sources"][0]["fallback"] for m in ends if m.metadata["response_sources"]] == [False, True] + assert len({m.event.stream_id for m in ends}) == len(ends) + # Display provenance stays out of canonical model input/history. + assert all("response_sources" not in message for message in result.messages) + + +@pytest.mark.parametrize("temporary", [False, True]) +async def test_websocket_wire_and_disk_replay_preserve_sources(tmp_path, monkeypatch, temporary): + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + channel = WebSocketChannel({"allowFrom": ["*"]}, MessageBus(), gateway=MagicMock()) + channel._media.rewrite_local_markdown_images.side_effect = lambda text: text + channel._transcripts = WebUITranscriptRecorder() + channel._temporary_chats.should_persist_transcript = lambda _: not temporary + channel._safe_send_to = AsyncMock() + channel._subs["source-chat"] = {MagicMock()} + sources = [{"provider": "xai", "model": "grok", "preset": "snapshot name", "fallback": True}] + metadata = {"webui_turn_id": "source-turn", "response_sources": sources} + await channel.send_delta("source-chat", "Hello", metadata, stream_id="s") + await channel.send_delta("source-chat", "", metadata, stream_id="s", stream_end=True) + frames = [json.loads(call.args[1]) for call in channel._safe_send_to.call_args_list] + assert [frame["event"] for frame in frames] == ["delta", "stream_end"] + assert all(frame["response_sources"] == sources for frame in frames) + if temporary: + assert not webui_transcript_path("websocket:source-chat").exists() + else: + # A fresh reader after an unrelated preset rename/delete sees the saved snapshot. + 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"] diff --git a/tests/channels/test_channel_manager_delta_coalescing.py b/tests/channels/test_channel_manager_delta_coalescing.py index db4099ea1..5340fbf75 100644 --- a/tests/channels/test_channel_manager_delta_coalescing.py +++ b/tests/channels/test_channel_manager_delta_coalescing.py @@ -111,6 +111,16 @@ def _end( class TestDeltaCoalescing: """Tests for stream delta message coalescing.""" + async def test_response_source_change_is_a_coalescing_boundary(self, manager, bus): + first, second = _delta("primary"), _delta("backup") + first.metadata["response_sources"] = [{"provider": "openai", "model": "m", "preset": "a"}] + second.metadata["response_sources"] = [{"provider": "openai", "model": "m", "preset": "b"}] + await bus.publish_outbound(second) + merged, pending = manager._coalesce_stream_deltas(first) + assert merged.content == "primary" + assert merged.metadata == first.metadata + assert pending == [second] + @pytest.mark.asyncio async def test_single_delta_not_coalesced(self, manager, bus): msg = _delta("Hello") diff --git a/tests/providers/test_provider_retry.py b/tests/providers/test_provider_retry.py index a9b2b244e..ed44a7824 100644 --- a/tests/providers/test_provider_retry.py +++ b/tests/providers/test_provider_retry.py @@ -522,6 +522,8 @@ async def test_image_retry_discards_provider_state_with_images( provider_context=ProviderCallContext( conversation_state=state, session_id="webui:cache-test", + response_preset="saved fallback", + response_is_fallback=True, ), ) @@ -530,6 +532,8 @@ async def test_image_retry_discards_provider_state_with_images( assert isinstance(retry_context, ProviderCallContext) assert retry_context.conversation_state is None assert retry_context.session_id == "webui:cache-test" + assert retry_context.response_preset == "saved fallback" + assert retry_context.response_is_fallback is True public_content = messages[0]["content"] if isinstance(public_content, list): assert all(block.get("type") != "image_url" for block in public_content) diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 5220e09a8..def6095bc 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -23,6 +23,7 @@ import { DisclosureContent } from "@/components/ui/disclosure"; import { AttachmentTile } from "@/components/AttachmentTile"; import { SessionHandleLabel } from "@/components/SessionHandleLabel"; +import { ResponseSourceBadge } from "@/components/ResponseSourceBadge"; import { ImageLightbox } from "@/components/ImageLightbox"; import { MarkdownText } from "@/components/MarkdownText"; import { SlashCommandText } from "@/components/SlashCommandText"; @@ -497,8 +498,9 @@ export function MessageBubble({ && (!empty || hasReasoning || media.length > 0); const assistantTimestampTitle = showAssistantTimestamp ? fmtDateTime(assistantTimestamp) : ""; const showAutomationTrigger = showAssistantTimestamp && automationSourceLabel.length > 0; + const fallbackSources = message.responseSources?.filter((source) => source.fallback === true) ?? []; const showAssistantFooterRow = - showCopyButton || showForkButton || showAssistantTimestamp; + showCopyButton || showForkButton || showAssistantTimestamp || fallbackSources.length > 0; const hasAssistantFooterContent = message.role === "assistant" && (!empty || hasReasoning || media.length > 0); @@ -577,6 +579,13 @@ export function MessageBubble({ {assistantTimestampLabel} ) : null} + {fallbackSources.length > 0 ? ( +
+ {fallbackSources.map((source) => ( + + ))} +
+ ) : null} {showAutomationTrigger ? ( + + + + + + + + {description} + + + event.preventDefault()} + className="max-w-[min(18rem,calc(100vw-2rem))] rounded-control px-3 py-2 text-xs leading-relaxed break-words"> + {description} + + + ); +} diff --git a/webui/src/components/settings/TokenUsageModelTrend.tsx b/webui/src/components/settings/TokenUsageModelTrend.tsx index bdee10878..7e86822f5 100644 --- a/webui/src/components/settings/TokenUsageModelTrend.tsx +++ b/webui/src/components/settings/TokenUsageModelTrend.tsx @@ -47,10 +47,14 @@ export function TokenUsageModelTrend({ days, modelDays, models }: { return

{title}

-
- {[peak, peak / 2, 0].map((value, index) =>
{compact.format(value)}
)} -
-
+
+
+ {[peak, peak / 2, 0].map((value, index) =>
+ {compact.format(value)} + +
)} +
+
{columns.map(column => column.total === 0 ? ( @@ -75,6 +79,7 @@ export function TokenUsageModelTrend({ days, modelDays, models }: { )}
+
{days[0].date.slice(5)}{days[14].date.slice(5)}{days[days.length - 1].date.slice(5)}
diff --git a/webui/src/components/thread/ModelPresetBadge.tsx b/webui/src/components/thread/ModelPresetBadge.tsx index b27c230ac..aae7c828e 100644 --- a/webui/src/components/thread/ModelPresetBadge.tsx +++ b/webui/src/components/thread/ModelPresetBadge.tsx @@ -92,7 +92,6 @@ interface ModelPresetBadgeProps { providerLabel?: string | null; needsSetup?: boolean; attentionRequest?: number; - fallbackModelName?: string | null; isHero: boolean; onClick?: () => void; } @@ -109,7 +108,6 @@ export function ModelPresetBadge({ providerLabel, needsSetup = false, attentionRequest = 0, - fallbackModelName, isHero, onClick, }: ModelPresetBadgeProps) { @@ -128,22 +126,10 @@ export function ModelPresetBadge({ model: modelDetail ?? modelPresets[listedIndex]?.model, provider: provider || modelPresets[listedIndex]?.provider, }; - const fallbackPreset = fallbackModelName - ? modelPresets.find((preset) => preset.model?.trim() === fallbackModelName.trim()) - : undefined; - const fallbackDisplayLabel = fallbackPreset?.name - || fallbackModelName?.trim().split(/[/:]/).pop() - || null; - const displayLabel = needsSetup ? label : fallbackDisplayLabel || label; - const displayModelDetail = fallbackPreset - ? fallbackPreset.model - : fallbackModelName || modelDetail; - const displayProvider = fallbackPreset?.provider - || (fallbackModelName ? inferProviderFromModelName(fallbackModelName) : provider); const tooltipLabel = needsSetup ? label : [...new Set([ - displayLabel, - displayModelDetail, - fallbackModelName ? null : providerLabel, + label, + modelDetail, + providerLabel, ].filter(Boolean))].join(" · "); const presets = !activeName ? modelPresets @@ -280,12 +266,11 @@ export function ModelPresetBadge({ const pill = ( 0} - fallbackModelName={needsSetup ? null : fallbackModelName} isHero={isHero} /> ); @@ -294,7 +279,7 @@ export function ModelPresetBadge({ const badge = !canSwitch ? ( void; onManageModels?: () => void; contextUsage?: ComposerContextUsage | null; @@ -907,7 +906,6 @@ export function ThreadComposer({ modelProvider = null, modelProviderLabel = null, modelNeedsSetup = false, - fallbackModelName = null, onModelBadgeClick, onManageModels, contextUsage = null, @@ -2274,7 +2272,6 @@ export function ThreadComposer({ providerLabel={modelProviderLabel} needsSetup={modelNeedsSetup} attentionRequest={modelSetupAttentionRequest} - fallbackModelName={fallbackModelName} isHero={isHero && !compactControls} onClick={modelNeedsSetup ? onModelBadgeClick : undefined} /> diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 3604df192..4737de7bb 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -672,7 +672,6 @@ export function ThreadShell({ ); return typeof response.path === "string" ? response.path : null; }, [client]); - const [fallbackModelName, setFallbackModelName] = useState(null); const [booting, setBooting] = useState(false); const [slashCommands, setSlashCommands] = useState([]); const cliApps = useInstalledSettingItems({ @@ -737,7 +736,6 @@ export function ThreadShell({ const handleTurnEnd = useCallback(() => { if (chatId) activeViewportTurnByChatIdRef.current.delete(chatId); setSubmittedViewportTurnId(null); - setFallbackModelName(null); onTurnEnd?.(); }, [chatId, onTurnEnd]); const { @@ -1031,18 +1029,6 @@ export function ThreadShell({ }); }, [client, refreshModelSettings]); - useEffect(() => { - if (!chatId) { - setFallbackModelName(null); - return; - } - setFallbackModelName(null); - return client.onChat(chatId, (event) => { - if (event.event !== "turn_model_updated" || event.fallback !== true) return; - setFallbackModelName(event.model_name); - }); - }, [chatId, client]); - useEffect(() => { if (!historyKey || !chatId || loading) return; const cached = messageCacheRef.current.get(chatId); @@ -1421,7 +1407,6 @@ export function ThreadShell({ const handleThreadSend = useCallback( (content: string, images?: SendAttachment[], options?: SendOptions) => { - setFallbackModelName(null); const submitted = send(content, images, withWorkspaceScope(options)); if ( chatId @@ -1570,7 +1555,6 @@ export function ThreadShell({ modelProvider={modelBadge.provider} modelProviderLabel={modelBadge.providerLabel} modelNeedsSetup={modelBadge.needsSetup} - fallbackModelName={fallbackModelName} onModelBadgeClick={modelBadge.needsSetup ? onOpenModelSettings : undefined} onManageModels={onOpenModelSettings} contextUsage={composerContextUsage} @@ -1620,7 +1604,6 @@ export function ThreadShell({ modelProvider={modelBadge.provider} modelProviderLabel={modelBadge.providerLabel} modelNeedsSetup={modelBadge.needsSetup} - fallbackModelName={fallbackModelName} onModelBadgeClick={modelBadge.needsSetup ? onOpenModelSettings : undefined} onManageModels={onOpenModelSettings} contextUsage={composerContextUsage} diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index ea8be178a..f00a14f3b 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -39,7 +39,7 @@ import type { } from "@/lib/types"; type PendingStreamEvent = - | { kind: "delta"; text: string; turn: UIMessageTurnFields; source?: UIMessage["source"] } + | { kind: "delta"; text: string; turn: UIMessageTurnFields; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"] } | { kind: "reasoning"; text: string; turn: UIMessageTurnFields }; const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000; @@ -318,7 +318,9 @@ export function useNanobotStream( if (nextEvent.kind !== event.kind || nextEvent.turn.turnId !== event.turn.turnId || nextEvent.turn.turnPhase !== event.turn.turnPhase - || (nextEvent.kind === "delta" && event.kind === "delta" && nextEvent.source !== event.source)) break; + || (nextEvent.kind === "delta" && event.kind === "delta" + && (nextEvent.source !== event.source + || JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources)))) break; chunks.push(nextEvent.text); turn = { ...turn, ...nextEvent.turn }; index++; @@ -333,6 +335,7 @@ export function useNanobotStream( turn_phase: turn.turnPhase, turn_seq: turn.turnSeq, source: event.source, + response_sources: event.responseSources, } : { event: "reasoning_delta", @@ -359,6 +362,7 @@ export function useNanobotStream( finalAnswerText?: string; turn?: UIMessageTurnFields; source?: UIMessage["source"]; + responseSources?: UIMessage["responseSources"]; }) => { lastStreamFlushRef.current = 0; if (streamFrameRef.current !== null) { @@ -373,7 +377,8 @@ export function useNanobotStream( const finalAnswerText = options?.finalAnswerText; const turn = options?.turn ?? {}; const source = options?.source; - if (events.length === 0 && finalAnswerText === undefined && source === undefined + const responseSources = options?.responseSources; + if (events.length === 0 && finalAnswerText === undefined && source === undefined && responseSources === undefined && !options?.mergeReasoning) { if (options?.closeAnswerSegment) closeActiveAssistantStream(); return; @@ -385,6 +390,7 @@ export function useNanobotStream( if ( finalAnswerText !== undefined || source !== undefined + || responseSources !== undefined || options?.mergeReasoning || options?.closeAnswerSegment ) { @@ -393,6 +399,7 @@ export function useNanobotStream( chat_id: chatId ?? "", ...(finalAnswerText !== undefined ? { text: finalAnswerText } : {}), ...(source ? { source } : {}), + ...(responseSources !== undefined ? { response_sources: responseSources } : {}), ...(options?.mergeReasoning ? { resuming: true, merge_next: true } : {}), turn_id: turn.turnId, turn_phase: turn.turnPhase, @@ -661,6 +668,7 @@ export function useNanobotStream( text: chunk, turn: turnFieldsFromEvent(ev, "answer"), source: ev.source, + responseSources: ev.response_sources, }); schedulePendingStreamFlush(); return; @@ -689,6 +697,7 @@ export function useNanobotStream( ...(typeof ev.text === "string" ? { finalAnswerText: ev.text } : {}), turn, source: ev.source, + responseSources: ev.response_sources, }); if (projectionRef.current.suppressUntilTurnEnd) return; if (ev.resuming) { diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 50c90bba5..192eda216 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1826,6 +1826,7 @@ "automationTriggered": "Triggered automatically", "askAboutSelection": "Ask about this", "forkFromHere": "Fork", + "fallbackResponse": "This reply switched to a fallback model, answered by {{preset}}.", "copyReply": "Copy", "copiedReply": "Copied", "turnLatencyTitle": "Response time (end-to-end)", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 2af5bfa1b..97663ddc7 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -1601,6 +1601,7 @@ "skill": "Habilidad: {{name}}", "askAboutSelection": "Preguntar sobre esto", "forkFromHere": "Bifurcar", + "fallbackResponse": "Esta respuesta usa un modelo de respaldo: {{preset}}.", "copyReply": "Copiar", "copiedReply": "Copiado", "turnLatencyTitle": "Tiempo de respuesta (extremo a extremo)", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index 7f62d069f..8ec5a9f49 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -1600,6 +1600,7 @@ "skill": "Compétence : {{name}}", "askAboutSelection": "Poser une question à ce sujet", "forkFromHere": "Bifurquer", + "fallbackResponse": "Cette réponse utilise un modèle de secours : {{preset}}.", "copyReply": "Copier", "copiedReply": "Copié", "turnLatencyTitle": "Temps de réponse (de bout en bout)", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 9a18dbbab..9a8f2d4e1 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -1600,6 +1600,7 @@ "skill": "Keterampilan: {{name}}", "askAboutSelection": "Tanyakan tentang ini", "forkFromHere": "Buat cabang", + "fallbackResponse": "Balasan ini beralih ke model cadangan dan dijawab oleh {{preset}}.", "copyReply": "Salin", "copiedReply": "Disalin", "turnLatencyTitle": "Waktu respons (ujung ke ujung)", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 9fff712db..5692eadc1 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1600,6 +1600,7 @@ "skill": "スキル: {{name}}", "askAboutSelection": "この内容について質問", "forkFromHere": "分岐", + "fallbackResponse": "この返信では代替モデルに切り替わり、{{preset}} が回答しています。", "copyReply": "コピー", "copiedReply": "コピー済み", "turnLatencyTitle": "応答時間(全行程)", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index c5cdd7179..57b2e1f2c 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1600,6 +1600,7 @@ "skill": "스킬: {{name}}", "askAboutSelection": "이 내용에 대해 질문하기", "forkFromHere": "분기", + "fallbackResponse": "이 응답은 대체 모델로 전환되어 {{preset}}이(가) 답변합니다.", "copyReply": "복사", "copiedReply": "복사됨", "turnLatencyTitle": "응답 시간(엔드투엔드)", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 17bab2fa5..67dbffafb 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1640,6 +1640,7 @@ "automationTriggered": "Acionada automaticamente", "askAboutSelection": "Perguntar sobre isto", "forkFromHere": "Fazer fork", + "fallbackResponse": "Esta resposta usa um modelo alternativo: {{preset}}.", "copyReply": "Copiar", "copiedReply": "Copiado", "turnLatencyTitle": "Tempo de resposta (ponta a ponta)", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 5a1dd450e..01682c111 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -1600,6 +1600,7 @@ "skill": "Kỹ năng: {{name}}", "askAboutSelection": "Hỏi về nội dung này", "forkFromHere": "Tách nhánh", + "fallbackResponse": "Phản hồi này đã chuyển sang mô hình dự phòng, do {{preset}} trả lời.", "copyReply": "Sao chép", "copiedReply": "Đã sao chép", "turnLatencyTitle": "Thời gian phản hồi (end-to-end)", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index f4a4fab69..e1c9bd849 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1826,6 +1826,7 @@ "automationTriggered": "自动触发", "askAboutSelection": "询问此内容", "forkFromHere": "从此处分叉", + "fallbackResponse": "本条回复已切换至备用模型,由 {{preset}} 回答。", "copyReply": "复制", "copiedReply": "已复制", "turnLatencyTitle": "本轮耗时(端到端)", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 1969bfcb1..1bc5032c8 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1599,6 +1599,7 @@ "openAttachment": "開啟 {{name}}", "skill": "技能:{{name}}", "forkFromHere": "建立分支", + "fallbackResponse": "本則回覆已切換至備用模型,由 {{preset}} 回答。", "copyReply": "複製", "copiedReply": "已複製", "turnLatencyTitle": "本輪耗時(端到端)", diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index ac5db9ce8..80834f383 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -270,6 +270,15 @@ function hasValidProjectionMetadata(value: Record): boolean { "user", "reasoning", "activity", "answer", "complete", ].includes(String(value.turn_phase))) && (value.turn_seq === undefined || typeof value.turn_seq === "number") + && ( + value.response_sources === undefined + || (isRecordArray(value.response_sources) && value.response_sources.every((source) => ( + typeof source.provider === "string" && source.provider.length > 0 + && typeof source.model === "string" && source.model.length > 0 + && typeof source.preset === "string" && source.preset.length > 0 + && (source.fallback === undefined || typeof source.fallback === "boolean") + ))) + ) && ( value.source === undefined || ( diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index b032d2391..b1d338596 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -521,6 +521,7 @@ function appendAnswerText( isStreaming: true, ...turn, ...(event.source ? { source: event.source } : {}), + ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), }; state.closedAssistantIds.delete(merged.id); state.activeAssistantId = merged.id; @@ -832,6 +833,7 @@ export function projectThreadEvent( isStreaming: true, ...turn, ...(event.source ? { source: event.source } : {}), + ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), createdAt: projectionCreatedAt(event, options), }, ]; @@ -844,13 +846,15 @@ export function projectThreadEvent( isStreaming: true, ...turn, ...(event.source ? { source: event.source } : {}), + ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), }); } - } else if (event.source && targetIndex !== null) { + } else if ((event.source || event.response_sources !== undefined) && targetIndex !== null) { state.messages = replaceMessageAt(state.messages, targetIndex, { ...state.messages[targetIndex], ...turn, - source: event.source, + ...(event.source ? { source: event.source } : {}), + ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), }); } if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id; @@ -936,6 +940,7 @@ export function projectThreadEvent( ...(media?.length ? { media } : {}), ...(latencyMs !== undefined ? { latencyMs } : {}), ...(event.source ? { source: event.source } : {}), + ...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}), ...turnFieldsForProjection(state, event, "answer"), }; if (options.sideChannel) { diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index ddc93f5d9..8726fdd17 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -64,6 +64,13 @@ export interface TurnUsage { export type RoundUsage = TurnUsage; +export interface ResponseSource { + provider: string; + model: string; + preset: string; + fallback?: boolean; +} + export interface RetryStatus extends WireRetryStatus { next_retry_at?: number; turn_id?: string; @@ -72,6 +79,8 @@ export interface UIMessage { id: string; role: Role; content: string; + /** Invocation-time snapshots, never resolved from today's model presets. */ + responseSources?: ResponseSource[]; kind?: MessageKind; isStreaming?: boolean; createdAt: number; @@ -1385,6 +1394,7 @@ export type InboundEvent = latency_ms?: number; /** Lightweight provenance for proactive assistant messages. */ source?: UIMessageSource; + response_sources?: ResponseSource[]; /** Optional structured payload on progress frames (channel-specific). */ agent_ui?: AgentUIBlob; } & InboundTurnMetadata) @@ -1401,6 +1411,7 @@ export type InboundEvent = stream_id?: string; /** Lightweight provenance for proactive streamed assistant messages. */ source?: UIMessageSource; + response_sources?: ResponseSource[]; } & InboundTurnMetadata) | ({ event: "stream_end"; @@ -1409,6 +1420,7 @@ export type InboundEvent = text?: string; /** Lightweight provenance for proactive streamed assistant messages. */ source?: UIMessageSource; + response_sources?: ResponseSource[]; /** This answer segment ended, but the active agent turn will continue. */ resuming?: boolean; /** The next answer segment continues this same assistant message. */ diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index 9c6f32eb4..4ae7873da 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -168,6 +168,42 @@ describe("webui API helpers", () => { ); }); + it.each([ + null, + "backup", + [null], + [{ provider: "xai", model: "grok" }], + [{ provider: "xai", model: "grok", preset: "backup", fallback: "true" }], + ])("rejects malformed response sources: %j", async (response_sources) => { + vi.mocked(fetch).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ + schemaVersion: 3, + projection: "events", + events: [{ event: "message", chat_id: "chat-1", text: "Reply", response_sources }], + }), + } as Response); + await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow( + "Invalid WebUI thread event metadata", + ); + }); + + it.each([ + undefined, + [], + [{ provider: "xai", model: "grok", preset: "snapshot", fallback: true }], + [{ provider: "xai", model: "grok", preset: "legacy snapshot" }], + ])("accepts optional recorded response sources: %j", async (response_sources) => { + const event = { event: "stream_end", chat_id: "chat-1", text: "Reply", response_sources }; + vi.mocked(fetch).mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => ({ schemaVersion: 3, projection: "events", events: [event] }), + } as Response); + await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({ events: [event] }); + }); + it("fetches deferred trace details with encoded session and ref", async () => { await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef"); diff --git a/webui/src/tests/i18n-chat-resources.test.ts b/webui/src/tests/i18n-chat-resources.test.ts index 4e31c305d..202440d0a 100644 --- a/webui/src/tests/i18n-chat-resources.test.ts +++ b/webui/src/tests/i18n-chat-resources.test.ts @@ -15,6 +15,7 @@ describe("chat translation resources", () => { for (const key of [ "chat.groups.all", "chat.groups.projects", "chat.newChat", "chat.fallbackTitle", "chat.activity.running", "chat.rename", "chat.loading", + "message.fallbackResponse", ]) { expect(i18n.exists(key), key).toBe(true); expect(i18n.t(key), key).not.toBe(key); diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsx index d0e667b6f..d69a23945 100644 --- a/webui/src/tests/message-bubble.test.tsx +++ b/webui/src/tests/message-bubble.test.tsx @@ -97,6 +97,59 @@ const SLASH_COMMANDS: SlashCommand[] = [ ]; describe("MessageBubble", () => { + it.each([false, undefined])("hides normal and legacy source badges (fallback: %s)", (fallback) => { + const message: UIMessage = { id: "primary", role: "assistant", content: "Hello", createdAt: 0, + isStreaming: true, responseSources: [{ provider: "openai_codex", model: "gpt", preset: "codex", fallback }] }; + const { container, rerender } = render(); + expect(screen.queryByText("codex")).not.toBeInTheDocument(); + expect(container.querySelector("[data-assistant-footer]")).toHaveAttribute("data-state", "reserved"); + rerender(); + expect(screen.queryByText("codex")).not.toBeInTheDocument(); + }); + + it("shows only fallback provider logos and preset names while streaming and after completion", () => { + const message: UIMessage = { id: "actual", role: "assistant", content: "Hello", createdAt: 0, + isStreaming: true, responseSources: [ + { provider: "openai_codex", model: "gpt", preset: "codex", fallback: false }, + { provider: "xai", model: "grok-4.5", preset: "grok", fallback: true }, + ] }; + const { container, rerender } = render(); + expect(screen.getByText("grok")).toBeVisible(); + expect(screen.queryByText("codex")).not.toBeInTheDocument(); + expect(screen.queryByText("grok-4.5")).not.toBeInTheDocument(); + expect(container.querySelector("[data-assistant-footer]")).toHaveAttribute("data-state", "visible"); + expect(container.querySelector("img")).toHaveAttribute("alt", ""); + fireEvent.error(container.querySelector("img")!); + expect(screen.getByText("grok")).toBeVisible(); + rerender(); + expect(screen.getByText("grok")).toBeVisible(); + rerender(); + expect(screen.queryByText("grok")).not.toBeInTheDocument(); + }); + + it("explains fallback on focus and click, with the source directly after the timestamp", async () => { + await setAppLanguage("zh-CN"); + const description = "本条回复已切换至备用模型,由 grok 回答。"; + const { container } = render(); + const trigger = screen.getByRole("button", { name: description }); + const footer = container.querySelector("[data-assistant-footer]")!; + const sourceGroup = footer.querySelector("[data-message-timestamp]")!.nextElementSibling; + expect(sourceGroup).toContainElement(trigger); + expect(sourceGroup).not.toHaveClass("ml-auto"); + fireEvent.focus(trigger); + expect(await screen.findByRole("tooltip")).toHaveTextContent(description); + fireEvent.blur(trigger); + fireEvent.click(trigger); + const popover = await screen.findByRole("dialog", { name: description }); + expect(popover).toHaveTextContent(description); + expect(screen.queryByRole("tooltip")).not.toBeInTheDocument(); + fireEvent.keyDown(popover, { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + }); + it("copies the localized compact reply instead of the stored English text", async () => { await setAppLanguage("zh-CN"); const writeText = vi.fn().mockResolvedValue(undefined); diff --git a/webui/src/tests/model-preset-badge.test.tsx b/webui/src/tests/model-preset-badge.test.tsx index 43e6828f7..81ff10692 100644 --- a/webui/src/tests/model-preset-badge.test.tsx +++ b/webui/src/tests/model-preset-badge.test.tsx @@ -37,16 +37,15 @@ describe("ModelPresetBadge setup tooltip", () => { expect(onClick).toHaveBeenCalledTimes(1); }); - it.each(["openai-codex/gpt-5.5", "deepseek/deepseek-chat"])( - "keeps the localized setup prompt despite a stale fallback (%s)", - async (fallbackModelName) => { + it( + "keeps the localized setup prompt instead of an available preset", + async () => { render( { ); }); -describe("ModelPresetBadge fallback tooltip", () => { - it("shows only the effective preset on hover and preserves the preset picker", async () => { +describe("ModelPresetBadge selected preset tooltip", () => { + it("shows the selected preset on hover and preserves the preset picker", async () => { const user = userEvent.setup(); const onPresetChange = vi.fn(); const { container } = render( @@ -73,18 +72,17 @@ describe("ModelPresetBadge fallback tooltip", () => { modelDetail="glm-5" provider="zhipu" modelPresets={presets} - fallbackModelName="openai-codex/gpt-5.5" onPresetChange={onPresetChange} isHero={false} />, ); - const trigger = screen.getByRole("button", { name: "codex" }); + const trigger = screen.getByRole("button", { name: "zhipu" }); expect(container.querySelector("[title]")).toBeNull(); await user.hover(trigger); const tooltip = await screen.findByRole("tooltip"); - expect(tooltip).toHaveTextContent("codex · openai-codex/gpt-5.5"); - expect(tooltip).not.toHaveTextContent("zhipu"); + expect(tooltip).toHaveTextContent("zhipu · glm-5"); + expect(tooltip).not.toHaveTextContent("codex"); await user.click(trigger); expect(await screen.findByRole("listbox")).toBeInTheDocument(); await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument()); @@ -96,16 +94,16 @@ describe("ModelPresetBadge fallback tooltip", () => { render( , ); - const trigger = screen.getByLabelText("codex"); + const trigger = screen.getByLabelText("zhipu"); expect(trigger).toHaveAttribute("tabindex", "0"); fireEvent.focus(trigger); expect(await screen.findByRole("tooltip")).toHaveTextContent( - "codex · openai-codex/gpt-5.5", + "zhipu · glm-5", ); fireEvent.keyDown(trigger, { key: "Escape" }); await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument()); diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.ts index b8c8feaa4..1223a7afb 100644 --- a/webui/src/tests/thread-event-projection.test.ts +++ b/webui/src/tests/thread-event-projection.test.ts @@ -29,6 +29,7 @@ const SEMANTIC_MESSAGE_FIELDS = [ "reasoning", "latencyMs", "source", + "responseSources", "turnId", "turnPhase", "turnSeq", @@ -72,6 +73,27 @@ function normalizeProjection(messages: UIMessage[]): Array { + it.each(["message", "stream_end"] as const)("preserves recorded sources in %s replay", (event) => { + const source = { provider: "xai", model: "grok", preset: "saved backup", fallback: true }; + const messages = projectThreadEvents([ + { event, chat_id: "chat", text: "Recovered", response_sources: [source] }, + { event: "turn_end", chat_id: "chat" }, + { event: "message", chat_id: "chat", text: "Legacy response" }, + ]); + expect(messages[0].responseSources).toEqual([source]); + expect(messages[1].responseSources).toBeUndefined(); + }); + + it("clears unknown source metadata on a textless stream end", () => { + const source = { provider: "xai", model: "grok", preset: "backup", fallback: true }; + const messages = projectThreadEvents([ + { event: "delta", chat_id: "chat", text: "Mixed answer", response_sources: [source] }, + { event: "stream_end", chat_id: "chat", response_sources: [] }, + { event: "turn_end", chat_id: "chat" }, + ]); + expect(messages[0].responseSources).toEqual([]); + }); + it.each(cases)("projects persisted $name events", (fixtureCase) => { const messages = projectThreadEvents(fixtureEvents(fixtureCase.transcript)); expect(normalizeProjection(messages)).toEqual(fixtureCase.expected); diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 0dd3b595c..761afb73d 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -1086,7 +1086,7 @@ describe("ThreadShell", () => { expect(screen.queryByRole("button", { name: "Choose your AI" })).not.toBeInTheDocument(); }); - it("shows the effective fallback model in the composer badge", async () => { + it("keeps the selected composer preset and attributes only the reply to its actual source", async () => { const client = makeClient(); render(wrap( client, @@ -1127,23 +1127,21 @@ describe("ThreadShell", () => { }); }); - const logo = await screen.findByTestId("composer-model-logo-deepseek"); - const badge = logo.parentElement; - expect(badge).not.toBeNull(); - expect(badge).toBe(configuredBadge); - expect(screen.queryByText("Default")).not.toBeInTheDocument(); - expect(screen.getByText("deepseek-chat")).toBeInTheDocument(); - expect(badge).toHaveAttribute("data-fallback", "true"); - expect(badge).not.toHaveAttribute("title"); - fireEvent.focus(screen.getByLabelText("deepseek-chat")); + expect(screen.getByTestId("composer-model-logo-openai_codex").parentElement).toBe(configuredBadge); + expect(screen.getByText("Default")).toBeInTheDocument(); + expect(screen.queryByTestId("composer-model-logo-deepseek")).not.toBeInTheDocument(); + expect(configuredBadge).not.toHaveAttribute("data-fallback"); + fireEvent.focus(screen.getByLabelText("Default")); expect(await screen.findByRole("tooltip")).toHaveTextContent( - "deepseek-chat · deepseek/deepseek-chat", + "Default · gpt-5.5 · OpenAI Codex", ); - expect(screen.getByRole("tooltip")).not.toHaveTextContent("Default"); - fireEvent.blur(screen.getByLabelText("deepseek-chat")); - expect(logo).toBeInTheDocument(); + fireEvent.blur(screen.getByLabelText("Default")); act(() => { + client._emitChat("fallback-model", { + event: "message", chat_id: "fallback-model", text: "Reply from the actual provider", + response_sources: [{provider: "deepseek", model: "deepseek-chat", preset: "backup", fallback: true}], + }); client._emitChat("fallback-model", { event: "turn_end", chat_id: "fallback-model", @@ -1156,6 +1154,7 @@ describe("ThreadShell", () => { ).not.toHaveAttribute("data-fallback"); }); expect(screen.getByText("Default")).toBeInTheDocument(); + expect(await screen.findByText("backup")).toBeInTheDocument(); }); it.each([false, true])("hides unconfigured model details in setup tooltips (existing history: %s)", async (hasHistory) => { diff --git a/webui/src/tests/token-usage-card.test.tsx b/webui/src/tests/token-usage-card.test.tsx index ebf8a6eb5..c023f4efd 100644 --- a/webui/src/tests/token-usage-card.test.tsx +++ b/webui/src/tests/token-usage-card.test.tsx @@ -17,6 +17,28 @@ function usage(days: Usage["days"]): Usage { } describe("Token usage card", () => { + it("uses the same plot box for stacked bars and the zero baseline, with dates outside", () => { + const days = Array.from({ length: 30 }, (_, index) => { + const date = `2026-09-${String(index + 1).padStart(2, "0")}`; + return { date, usage: day(date, index === 0 ? 30_000_000 : index === 1 ? 1 : 0) }; + }); + const { container } = render(); + const plot = container.querySelector("[data-model-usage-plot]")!; + const bars = within(screen.getByRole("group", { name: "Model usage over time" })).getAllByRole("img"); + expect(plot).toContainElement(bars[0]); + const baseline = container.querySelector('[data-model-usage-gridline="2"]')!; + expect(plot).toContainElement(baseline); + expect(baseline.parentElement).toHaveStyle({ top: "100%" }); + expect(plot).not.toContainElement(screen.getByText("09-01")); + expect(bars[0].firstElementChild).toHaveStyle({ height: "100%" }); + expect(bars[0].firstElementChild?.children).toHaveLength(2); + expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` }); + expect(bars[2].children).toHaveLength(0); + }); beforeEach(() => { vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date("2026-09-09T12:00:00Z")); diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 257896cf8..fcfd3ff0e 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -43,6 +43,7 @@ const SEMANTIC_MESSAGE_FIELDS = [ "reasoning", "latencyMs", "source", + "responseSources", "turnId", "turnPhase", "turnSeq", @@ -201,6 +202,42 @@ async function flushStreamFrame() { } describe("useNanobotStream", () => { + it("keeps invocation snapshots across streaming, recovery segments, completion and reload", async () => { + const fake = fakeClient(); + const a = { provider: "openai_codex", model: "gpt", preset: "writer", fallback: false }; + const b = { provider: "xai", model: "grok", preset: "reviewer", fallback: true }; + const { result, unmount } = renderHook(() => useNanobotStream("sources", EMPTY_MESSAGES), { + wrapper: wrap(fake.client), + }); + act(() => fake.emit("sources", { event: "delta", chat_id: "sources", text: "First", response_sources: [a] })); + await flushStreamFrame(); + expect(result.current.messages[0].responseSources).toEqual([a]); + act(() => { + fake.emit("sources", { event: "stream_end", chat_id: "sources", resuming: true, response_sources: [a] }); + fake.emit("sources", { event: "delta", chat_id: "sources", text: "Recovered", response_sources: [b] }); + fake.emit("sources", { event: "stream_end", chat_id: "sources", response_sources: [b] }); + fake.emit("sources", { event: "turn_end", chat_id: "sources" }); + }); + expect(result.current.messages.map(m => m.responseSources)).toEqual([[a], [b]]); + const history = result.current.messages; + unmount(); + const reloaded = renderHook(() => useNanobotStream("sources", history), { wrapper: wrap(fake.client) }); + expect(reloaded.result.current.messages.map(m => m.responseSources)).toEqual([[a], [b]]); + }); + + it("honors complete and end-only sources and clears an ambiguous merged attribution", () => { + const fake = fakeClient(); + const a = { provider: "openai", model: "shared-model", preset: "primary", fallback: false }; + const b = { provider: "openai", model: "shared-model", preset: "backup", fallback: true }; + const { result } = renderHook(() => useNanobotStream("sources", EMPTY_MESSAGES), { wrapper: wrap(fake.client) }); + act(() => { + fake.emit("sources", { event: "message", chat_id: "sources", text: "Complete", response_sources: [b] }); + fake.emit("sources", { event: "stream_end", chat_id: "sources", text: "Mixed", response_sources: [a, b], resuming: true, merge_next: true }); + }); + expect(result.current.messages.map(m => m.responseSources)).toEqual([[b], [a, b]]); + act(() => fake.emit("sources", { event: "stream_end", chat_id: "sources", response_sources: [] })); + expect(result.current.messages[1].responseSources).toEqual([]); + }); it.each(["succeeded", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => { const fake = fakeClient(); const { result } = renderHook(