diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index 7f147161e..3646d3769 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -256,6 +256,11 @@ class ModelRequestState: provider_compaction_applied: bool = False compacted_tool_results: set[str] = field(default_factory=set) events: EventSink = NO_EVENTS + request_run_id: str = field(default_factory=lambda: uuid4().hex) + request_sequence: int = 0 + request_usage: LLMUsage | None = None + # Reported usage per runner round; recovery requests update the same slot. + recent_round_usages: list[LLMUsage | None] = field(default_factory=list) class ContextGovernor: diff --git a/nanobot/agent/hook.py b/nanobot/agent/hook.py index 9b4f1154a..69f398e99 100644 --- a/nanobot/agent/hook.py +++ b/nanobot/agent/hook.py @@ -109,6 +109,13 @@ class AgentHook: """Observe a provider-hosted tool lifecycle event.""" pass + async def on_tool_execution_event(self, context: AgentHookContext) -> None: + """One call's start or terminal result with call-local tool lists. + + Cancellation notification is best-effort; channels own queued delivery. + """ + pass + async def before_execute_tools(self, context: AgentHookContext) -> None: pass @@ -228,6 +235,9 @@ class CompositeHook(AgentHook): ) -> None: await self._for_each_hook_safe("on_provider_tool_event", context, event) + async def on_tool_execution_event(self, context: AgentHookContext) -> None: + await self._for_each_hook_safe("on_tool_execution_event", context) + async def before_execute_tools(self, context: AgentHookContext) -> None: await self._for_each_hook_safe("before_execute_tools", context) diff --git a/nanobot/agent/progress_hook.py b/nanobot/agent/progress_hook.py index ec9daa764..ad2f4125a 100644 --- a/nanobot/agent/progress_hook.py +++ b/nanobot/agent/progress_hook.py @@ -125,8 +125,7 @@ class AgentProgressHook(AgentHook): thought = self._strip_think(context.response.content if context.response else None) if thought: await self._publish(ProgressEvent(content=thought)) - tool_events = [build_tool_event_start_payload(tc) for tc in context.tool_calls] - await self._publish(ProgressEvent(tool_hint=True, tool_events=tool_events)) + for tc in context.tool_calls: args_str = ( json.dumps(tc.arguments, ensure_ascii=False)[:200] @@ -148,15 +147,16 @@ class AgentProgressHook(AgentHook): else: self._reasoning_open = False + async def on_tool_execution_event(self, context: AgentHookContext) -> None: + if self._publish: + finished = bool(context.tool_events) + payloads = ( + build_tool_event_finish_payloads(context) if finished + else [build_tool_event_start_payload(tc) for tc in context.tool_calls] + ) + await self._publish(ProgressEvent(tool_hint=not finished, tool_events=payloads)) + async def after_iteration(self, context: AgentHookContext) -> None: - if ( - self._publish - and context.tool_calls - and context.tool_events - ): - tool_events = build_tool_event_finish_payloads(context) - if tool_events: - await self._publish(ProgressEvent(tool_events=tool_events)) u = context.usage logger.debug( "LLM usage: input={} output={} cache_read={} cache_write={} source={}", diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.py index 73d4ce133..aaeb6d871 100644 --- a/nanobot/agent/runner.py +++ b/nanobot/agent/runner.py @@ -6,7 +6,8 @@ from collections.abc import Awaitable, Callable, Iterable from copy import deepcopy from dataclasses import dataclass, field, replace from pathlib import Path -from typing import Any, ParamSpec, TypeVar, cast +from typing import Any, Literal, ParamSpec, TypeVar, cast +from uuid import uuid4 from loguru import logger @@ -23,9 +24,9 @@ from nanobot.agent.context_governance import ( from nanobot.agent.execution_policy import ExecutionControlError from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext from nanobot.agent.tools.context import tool_log_content_allowed -from nanobot.agent.tools.execution import execute_tool_calls +from nanobot.agent.tools.execution import ToolCallResult, execute_tool_calls from nanobot.agent.tools.registry import ToolRegistry -from nanobot.events import NO_EVENTS, EventSink +from nanobot.events import NO_EVENTS, EventSink, ModelRequestEvent from nanobot.llm_usage.context import ( LLMUsageSource, bind_llm_usage_source, @@ -42,6 +43,7 @@ from nanobot.providers.base import ( from nanobot.providers.conversation_state import ProviderConversationStateController from nanobot.session.history_visibility import HIDDEN_HISTORY_META, is_hidden_history_message from nanobot.session.summary import SessionSummaryCheckpoint +from nanobot.utils.cancellation import shield_and_drain from nanobot.utils.helpers import ( build_assistant_message, estimate_message_tokens, @@ -448,6 +450,7 @@ class AgentRunner: request_messages = await self.prepare_prompt( request_state.compaction.request_messages, messages, ) + request_state.recent_round_usages.append(None) response, raw_usage = await self._request_model( spec, request_messages, @@ -512,7 +515,67 @@ class AgentRunner: await hook.before_execute_tools(context) - results, new_events = await execute_tool_calls( + async def settle_tool_results(completed: list[ToolCallResult]) -> None: + tool_events.extend(entry.event for entry in completed) + tools_used.extend( + entry.tool_call.name for entry in completed + if entry.event.get("status") == "ok" + ) + context.tool_results = [entry.result for entry in completed] + context.tool_events = [entry.event for entry in completed] + completed_by_id = {entry.tool_call.id: entry for entry in completed} + interrupted = len(completed) != len(response.tool_calls) + completed_tool_results: list[dict[str, Any]] = [] + for tool_call in response.tool_calls: + entry = completed_by_id.get(tool_call.id) + tool_message: dict[str, Any] = { + "role": "tool", + "tool_call_id": tool_call.id, + "name": tool_call.name, + } + if entry is not None: + tool_message["content"] = self.context_governor.normalize_tool_result( + governance_config, + tool_call.id, + tool_call.name, + entry.result, + ) + else: + # Close interrupted calls as recovery does, without + # inventing a result or permitting an implicit retry. + tool_message["content"] = ( + "Error: Task interrupted; this tool's outcome is unknown. " + "Check its effects before retrying." + ) + tool_message["_recovery_interrupted"] = True + messages.append(tool_message) + completed_tool_results.append(tool_message) + checkpoint_model_messages = ( + await self.prepare_prompt( + self.context_governor.prepare_messages_for_model, governance_config, + messages, + ) + if response.provider_state is not None and not interrupted + else None + ) + await self._emit_checkpoint( + spec, + { + "phase": "tools_completed", + "iteration": iteration, + "model": spec.runtime.model, + "assistant_message": assistant_message, + "completed_tool_results": completed_tool_results, + "pending_tool_calls": [], + "provider_state": conversation_state.checkpoint( + messages, + model_messages=checkpoint_model_messages, + ) if not interrupted else None, + }, + messages, + ) + + await execute_tool_calls( spec.tools, response.tool_calls, concurrent=spec.concurrent_tools, @@ -522,53 +585,7 @@ class AgentRunner: context=context, model_messages=messages_for_model, compacted_tool_results=request_state.compacted_tool_results, - ) - tool_events.extend(new_events) - tools_used.extend( - tool_call.name - for tool_call, event in zip(response.tool_calls, new_events) - if event.get("status") == "ok" - ) - context.tool_results = list(results) - context.tool_events = list(new_events) - completed_tool_results: list[dict[str, Any]] = [] - for tool_call, result in zip(response.tool_calls, results): - tool_message = { - "role": "tool", - "tool_call_id": tool_call.id, - "name": tool_call.name, - "content": self.context_governor.normalize_tool_result( - governance_config, - tool_call.id, - tool_call.name, - result, - ), - } - messages.append(tool_message) - completed_tool_results.append(tool_message) - checkpoint_model_messages = ( - await self.prepare_prompt( - self.context_governor.prepare_messages_for_model, governance_config, - messages, - ) - if response.provider_state is not None - else None - ) - await self._emit_checkpoint( - spec, - { - "phase": "tools_completed", - "iteration": iteration, - "model": spec.runtime.model, - "assistant_message": assistant_message, - "completed_tool_results": completed_tool_results, - "pending_tool_calls": [], - "provider_state": conversation_state.checkpoint( - messages, - model_messages=checkpoint_model_messages, - ), - }, - messages, + on_settled=settle_tool_results, ) empty_content_retries = 0 length_recovery_parts.clear() @@ -609,6 +626,7 @@ class AgentRunner: ) if hook.wants_streaming(): await hook.on_stream_end(context, resuming=False) + request_state.recent_round_usages.append(None) response = await self._request_finalization_retry( spec, messages_for_model, @@ -885,6 +903,59 @@ class AgentRunner: ), } + async def _invoke_model( + self, spec: AgentRunSpec, state: ModelRequestState, kwargs: dict[str, Any], + *, record_timing: Callable[[LLMResponse], None] | None = None, + ) -> LLMResponse: + """Observe the logical provider invocation, after request preparation. + + Physical retries/fallbacks and provider-internal pre-request compaction + remain inside the call. Post-return compaction summarization is outside. + Only provider-returned usage is published here, never estimated zeros. + Callers reserve a live round slot; recovery invocations update it. + """ + request_id = uuid4().hex + + async def emit(phase: Literal["started", "completed", "failed", "cancelled"]) -> None: + state.request_sequence += 1 + if not spec.events.accepts(ModelRequestEvent): + return + await spec.events.emit(ModelRequestEvent( + request_id=request_id, run_id=state.request_run_id, + sequence=state.request_sequence, phase=phase, + usage=state.request_usage, + round_usages=tuple(usage for usage in state.recent_round_usages if usage is not None), + context_window_tokens=spec.runtime.context_window_tokens, + )) + + try: + await emit("started") + _raise_if_cancelling() + response = await spec.runtime.provider.chat_stream_with_retry(**kwargs) + _raise_if_cancelling() + except asyncio.CancelledError: + try: + await shield_and_drain(emit("cancelled")) + except asyncio.CancelledError: + pass + raise + except Exception: + await emit("failed") + raise + if record_timing is not None: + record_timing(response) + if response.usage is not None: + reported_usage = response.usage.with_timing( + generation_ms=response.generation_ms, ttft_ms=response.ttft_ms, + ) + state.request_usage = self._merge_usage(state.request_usage, reported_usage) + state.recent_round_usages[-1] = self._merge_usage( + state.recent_round_usages[-1], reported_usage, + ) + del state.recent_round_usages[:-8] + await emit("failed" if response.finish_reason == "error" else "completed") + return response + async def _request_model( self, spec: AgentRunSpec, @@ -1018,7 +1089,14 @@ class AgentRunner: on_tool_call_delta=_provider_tool_event, on_stream_recover=_stream_recover, ) - coro = spec.runtime.provider.chat_stream_with_retry(**kwargs) + def record_timing(response: LLMResponse) -> None: + _pause_generation() + if first_output_at is not None: + response.ttft_ms = max(0, round((first_output_at - request_started_at) * 1000)) + if generation_elapsed_s > 0: + response.generation_ms = max(1, round(generation_elapsed_s * 1000)) + + coro = self._invoke_model(spec, request_state, kwargs, record_timing=record_timing) # Providers bound the wait for each stream event, including reasoning and tool deltas. request_started_at = time.perf_counter() @@ -1032,10 +1110,6 @@ class AgentRunner: _pause_generation() await _close_native_reasoning() _end_stream_segment() - if first_output_at is not None: - response.ttft_ms = max(0, round((first_output_at - request_started_at) * 1000)) - if generation_elapsed_s > 0: - response.generation_ms = max(1, round(generation_elapsed_s * 1000)) await self.context_governor.summarize_provider_compaction( request_state, response, @@ -1205,6 +1279,7 @@ class AgentRunner: if iteration > spec.max_iterations else self._budget_exhausted_finalization_messages(request_messages) ) + request_state.recent_round_usages.append(None) try: response = await self._request_no_tools( spec, @@ -1261,7 +1336,7 @@ class AgentRunner: transcript=transcript, ) _raise_if_cancelling() - response = await spec.runtime.provider.chat_stream_with_retry(**kwargs) + response = await self._invoke_model(spec, request_state, kwargs) _raise_if_cancelling() await self.context_governor.summarize_provider_compaction( request_state, diff --git a/nanobot/agent/tools/execution.py b/nanobot/agent/tools/execution.py index a97dade09..f7eb661ce 100644 --- a/nanobot/agent/tools/execution.py +++ b/nanobot/agent/tools/execution.py @@ -1,8 +1,9 @@ from __future__ import annotations import asyncio -from collections.abc import Callable +from collections.abc import Awaitable, Callable from contextlib import nullcontext +from dataclasses import dataclass, replace from functools import cache from typing import Any, cast @@ -43,6 +44,13 @@ _WORKSPACE_VIOLATION_MARKERS: tuple[str, ...] = ( ) +@dataclass(frozen=True) +class ToolCallResult: + tool_call: ToolCallRequest + result: Any + event: dict[str, str] + + async def execute_tool_calls( tools: ToolRegistry, tool_calls: list[ToolCallRequest], @@ -54,8 +62,9 @@ async def execute_tool_calls( context: AgentHookContext, model_messages: list[dict[str, Any]] | None = None, compacted_tool_results: set[str] | None = None, -) -> tuple[list[Any], list[dict[str, str]]]: - """Execute one model response's tool calls in stable result order.""" + on_settled: Callable[[list[ToolCallResult]], Awaitable[None]] | None = None, +) -> None: + """Own tool tasks through settlement, including results whose notification failed.""" @cache def read_results() -> dict[str, str]: """Index once, on the first read-dedup check in this batch.""" @@ -67,41 +76,63 @@ async def execute_tool_calls( and isinstance(message.get("content"), str) and message["tool_call_id"] not in (compacted_tool_results or ()) } - tool_results: list[tuple[Any, dict[str, str]]] = [] - for batch in _partition_tool_batches(tools, tool_calls, concurrent=concurrent): - if concurrent and len(batch) > 1: - batch_results = await asyncio.gather(*( - _execute_tool_call( - tools, - tool_call, - external_lookup_counts, - workspace_violation_counts, - hook, - context, - read_results, - ) - for tool_call in batch - )) - tool_results.extend(batch_results) - else: - for tool_call in batch: - result = await _execute_tool_call( - tools, - tool_call, - external_lookup_counts, - workspace_violation_counts, - hook, - context, - read_results, - ) - tool_results.append(result) + tool_results: list[ToolCallResult | None] = [None] * len(tool_calls) - results = [result for result, _event in tool_results] - events = [event for _result, event in tool_results] - return results, events + async def execute(index: int, tool_call: ToolCallRequest) -> None: + call_context = replace(context, tool_calls=[tool_call], tool_results=[], tool_events=[]) + try: + await hook.on_tool_execution_event(call_context) + result, event = await _execute_tool_call_inner( + tools, tool_call, external_lookup_counts, workspace_violation_counts, + hook, context, read_results, + ) + except asyncio.CancelledError: + cancelled = replace(call_context, tool_results=["Tool execution cancelled"], tool_events=[{ + "name": tool_call.name, "status": "error", "detail": "cancelled", + }]) + # Give immediate consumers a terminal event, but do not wait for a + # blocked consumer during cancellation. Own and drain the attempt. + notification = asyncio.create_task(hook.on_tool_execution_event(cancelled)) + try: + await asyncio.sleep(0) + finally: + notification.cancel() + await asyncio.gather(notification, return_exceptions=True) + raise + # Notification failure or cancellation must not discard an actual result. + tool_results[index] = ToolCallResult(tool_call, result, event) + await hook.on_tool_execution_event(replace( + call_context, tool_results=[result], tool_events=[event], + )) + + try: + offset = 0 + for batch in _partition_tool_batches(tools, tool_calls, concurrent=concurrent): + if concurrent and len(batch) > 1: + tasks = [ + asyncio.create_task(execute(offset + index, tool_call)) + for index, tool_call in enumerate(batch) + ] + try: + await asyncio.gather(*tasks) + except BaseException: + # gather propagates ordinary errors before siblings finish. + # The run must not release ownership while they can act. + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + raise + else: + for index, tool_call in enumerate(batch): + await execute(offset + index, tool_call) + offset += len(batch) + finally: + settled = [result for result in tool_results if result is not None] + if settled and on_settled is not None: + await on_settled(settled) -async def _execute_tool_call( +async def _execute_tool_call_inner( tools: ToolRegistry, tool_call: ToolCallRequest, external_lookup_counts: dict[str, int], diff --git a/nanobot/bus/notification_delivery.py b/nanobot/bus/notification_delivery.py index a0000b78a..77cb62c14 100644 --- a/nanobot/bus/notification_delivery.py +++ b/nanobot/bus/notification_delivery.py @@ -10,6 +10,7 @@ from nanobot.bus.outbound_events import ( from nanobot.events import ( AgentEvent, ContextCompactionEvent, + ModelRequestEvent, RecoveryStateEvent, ResponseSourceEvent, RetryWaitEvent, @@ -27,6 +28,7 @@ NOTIFICATION_AUDIENCES: dict[type[AgentEvent], NotificationAudience] = { RecoveryStateEvent: "interactive", RetryStatusEvent: "interactive", ResponseSourceEvent: "interactive", + ModelRequestEvent: "interactive", } diff --git a/nanobot/channels/base.py b/nanobot/channels/base.py index cb076138b..6e8d3e7e4 100644 --- a/nanobot/channels/base.py +++ b/nanobot/channels/base.py @@ -1,6 +1,7 @@ from __future__ import annotations from abc import ABC, abstractmethod +from collections.abc import Sequence from dataclasses import replace from pathlib import Path from typing import Any, cast @@ -117,6 +118,22 @@ class BaseChannel(ABC): """ pass + def can_batch_send(self, previous: OutboundMessage, following: OutboundMessage) -> bool: + """Opt in to sending adjacent, unscheduled envelopes together. + + The synchronous predicate must preserve channel-owned event, turn and + generation boundaries. Returning True requires implementing ``send_batch``. + """ + return False + + async def send_batch(self, messages: Sequence[OutboundMessage]) -> None: + """Send an ordered batch approved by ``can_batch_send``. + + The manager does not retry a batch: a failure may follow partial delivery. + Like ``send``, returning confirms completion of the adapter's work. + """ + raise NotImplementedError("Channels opting into batching must implement send_batch") + def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage: """Project tool activity once before delivery; override for native UI. diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index 8bbe04a97..d8404e98f 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -63,6 +63,7 @@ def _default_webui_dist() -> Path | None: _SEND_RETRY_DELAYS = (1, 2, 4) _OUTBOUND_CONCURRENCY = 32 _OUTBOUND_PENDING_LIMIT = 256 +_OUTBOUND_BATCH_LIMIT = 32 _RESTART_NOTICE_START_TIMEOUT_S = 30.0 _RESTART_NOTICE_START_POLL_S = 0.25 ORIGIN_REPLY_FINGERPRINTS_MAX_SIZE = 1000 @@ -152,6 +153,7 @@ class ChannelManager: self._restart_notice_task: asyncio.Task[None] | None = None self._outbound_tasks: dict[asyncio.Task[None], tuple[str, str]] = {} self._outbound_tails: dict[tuple[str, str], asyncio.Task[None]] = {} + self._outbound_batches: dict[tuple[str, str], list[OutboundMessage]] = {} self._outbound_pending: list[OutboundMessage] = [] self._outbound_dispatching = False self._outbound_slots = asyncio.Semaphore(_OUTBOUND_PENDING_LIMIT) @@ -776,9 +778,10 @@ class ChannelManager: await asyncio.gather(*tasks, return_exceptions=True) async def _queue_outbound(self, channel: BaseChannel, msg: OutboundMessage) -> None: - """Bound scheduled sends; preserve FIFO per destination, not across chats. + """Bound queued envelopes; preserve FIFO per destination, not across chats. Retry waits retain their destination tail and admission, not a send permit. + Only an unscheduled tail still waiting to start can accept a bounded batch. Saturation pauses dispatch rather than creating unbounded tasks or dropping messages. """ if msg.delivery_id in self._scheduled_deliveries: @@ -790,14 +793,35 @@ class ChannelManager: self._outbound_slots.release() return key = (msg.channel, msg.chat_id) + pending = self._outbound_batches.get(key) + if ( + pending is not None + and msg.delivery_id is None + and len(pending) < _OUTBOUND_BATCH_LIMIT + and channel.can_batch_send(pending[-1], msg) is True + ): + pending.append(msg) + return + previous = self._outbound_tails.get(key) + messages = [msg] if msg.delivery_id is not None: self._scheduled_deliveries.add(msg.delivery_id) + self._outbound_batches.pop(key, None) + else: + self._outbound_batches[key] = messages async def send() -> None: if previous is not None: await asyncio.shield(asyncio.gather(previous, return_exceptions=True)) - if msg.delivery_id is not None: + if self._outbound_batches.get(key) is messages: + self._outbound_batches.pop(key, None) + batch = tuple(messages) + if len(batch) > 1: + async with self._outbound_sends: + # Partial delivery must never cause a blind replay of the batch. + await channel.send_batch(batch) + elif msg.delivery_id is not None: # Acquire before claiming: queued cancellation must remain pending. async with self._outbound_sends: await self._send_scheduled(channel, msg) @@ -814,7 +838,10 @@ class ChannelManager: self._scheduled_deliveries.discard(msg.delivery_id) if self._outbound_tails.get(key) is done: self._outbound_tails.pop(key, None) - self._outbound_slots.release() + if self._outbound_batches.get(key) is messages: + self._outbound_batches.pop(key, None) + for _ in messages: + self._outbound_slots.release() if not done.cancelled() and (error := done.exception()) is not None: logger.error("Outbound delivery to {}:{} failed: {}", *key, error) diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py index 143303071..be80fae6c 100644 --- a/nanobot/channels/websocket/runtime.py +++ b/nanobot/channels/websocket/runtime.py @@ -7,6 +7,7 @@ import json import socket import ssl import uuid +from collections.abc import Sequence from contextlib import suppress from dataclasses import dataclass from pathlib import Path @@ -1108,6 +1109,12 @@ class WebSocketChannel(BaseChannel): async def send(self, msg: OutboundMessage) -> None: await self._outbound.send(msg) + def can_batch_send(self, previous: OutboundMessage, following: OutboundMessage) -> bool: + return self._outbound.can_batch_send(previous, following) + + async def send_batch(self, messages: Sequence[OutboundMessage]) -> None: + await self._outbound.send_batch(messages) + def prepare_tool_events(self, msg: OutboundMessage) -> OutboundMessage: return msg diff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.py index e168a5b60..5cf02730a 100644 --- a/nanobot/channels/websocket/tests/test_websocket_channel.py +++ b/nanobot/channels/websocket/tests/test_websocket_channel.py @@ -6922,3 +6922,76 @@ async def test_webui_commands_keep_session_io_off_event_loop( assert "save" in calls or "replace_metadata" in calls assert all(json.loads(call.args[0])["event"] != "error" for call in conn.send.await_args_list) await channel._cleanup_connection(conn) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("connected", [False, True]) +async def test_model_request_delivery_persists_started_and_terminal_offline(history, connected): + from nanobot.events import ModelRequestEvent + + bus = MagicMock() + channel = WebSocketChannel( + {"enabled": True, "allowFrom": ["*"]}, bus, + gateway=_basic_handler(bus, session_manager=history.sessions), + ) + ws = AsyncMock() + if connected: + channel._attach(ws, "model-requests") + for sequence, phase in enumerate(("started", "completed"), 1): + await channel.send(await history.message( + channel="websocket", chat_id="model-requests", content="", + event=ModelRequestEvent("request", "run", sequence, phase), + )) + rows = history.read("websocket:model-requests") + assert [r["event"] for r in rows] == ["model_request", "model_request"] + assert [r["phase"] for r in rows] == ["started", "completed"] + if connected: + assert [r["phase"] for r in _sent_ws_payloads(ws)] == ["started", "completed"] + + +@pytest.mark.asyncio +async def test_history_model_request_opt_in_preserves_old_clients_cursors_and_etags(history): + from urllib.parse import quote + + from websockets.datastructures import Headers + from websockets.http11 import Request + + key = "websocket:model-capability" + for number in range(3): + history.append(key, {"event": "user", "chat_id": "model-capability", "text": f"question {number}"}) + history.append(key, { + "event": "model_request", "chat_id": "model-capability", + "request_id": f"request-{number}", "run_id": f"run-{number}", + "sequence": 2, "phase": "completed", "round_usages": [], + }) + history.append(key, {"event": "message", "chat_id": "model-capability", "text": "answer"}) + history.append(key, {"event": "turn_end", "chat_id": "model-capability"}) + channel = _ch(MagicMock(), session_manager=history.sessions) + channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300 + encoded = quote(key, safe="") + + async def fetch(query, etag=None): + headers = [("Authorization", "Bearer tok")] + if etag: + headers.append(("If-None-Match", etag)) + response = await channel.gateway.http._handle_webui_thread_get_async(Request( + f"/api/sessions/{encoded}/webui-thread?{query}", Headers(headers), + ), encoded) + return response, json.loads(response.body) if response.body else None + + old_response, old = await fetch("limit=2&direction=latest") + modern_response, modern = await fetch( + "limit=2&direction=latest&include_model_requests=1", old_response.headers["ETag"], + ) + assert old_response.status_code == modern_response.status_code == 200 + assert old_response.headers["ETag"] != modern_response.headers["ETag"] + assert all(event["event"] != "model_request" for event in old["events"]) + assert any(event["event"] == "model_request" for event in modern["events"]) + assert old["events"] == [event for event in modern["events"] if event["event"] != "model_request"] + assert old["page"]["before_cursor"] == modern["page"]["before_cursor"] + cursor = quote(old["page"]["before_cursor"], safe="") + _, old_page = await fetch(f"limit=2&before={cursor}") + _, modern_page = await fetch(f"limit=2&before={cursor}&include_model_requests=1") + assert old_page["events"] == [event for event in modern_page["events"] if event["event"] != "model_request"] + assert old_page["page"]["loaded_event_count"] == len(old_page["events"]) + assert modern_page["page"]["loaded_event_count"] == len(modern_page["events"]) diff --git a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py index 34bdca81a..948661ef6 100644 --- a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py +++ b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py @@ -546,3 +546,225 @@ async def test_shell_output_is_literal_without_changing_other_command_replies( assert message.content == output finally: await channel._cleanup_connection(cast(Any, connection)) + + +@pytest.mark.asyncio +async def test_ready_activity_group_commits_before_ordered_fanout(history, monkeypatch, tmp_path) -> None: + from nanobot.bus.outbound_events import ProgressEvent, RetryStatusEvent, TurnEndEvent + from nanobot.events import ModelRequestEvent + from nanobot.providers.base import LLMUsage + + channel = _channel(history.sessions) + manager = ChannelManager( + Config.model_validate({"channels": {"websocket": {"enabled": False}}}), channel.bus, + config_path=tmp_path / "config.json", + ) + manager.channels["websocket"] = channel + chat = "group-commit" + metadata = await history.metadata(chat, {"webui_turn_id": "turn-group"}) + connection, late = _RecordingConnection(), _RecordingConnection() + channel._attach(cast(Any, connection), chat) + entered, release = [asyncio.Event(), asyncio.Event()], [asyncio.Event(), asyncio.Event()] + append = history.sessions.state.append_history + writes = [] + + async def gated_append(key, facts, **kwargs): + index = len(writes) + writes.append(list(facts)) + if index < 2: + entered[index].set() + await release[index].wait() + await append(key, facts, **kwargs) + + monkeypatch.setattr(history.sessions.state, "append_history", gated_append) + usage = LLMUsage.reported(input_tokens=100, output_tokens=20) + events = [ + ModelRequestEvent("request", "run", 1, "started"), + RetryStatusEvent(state="cleared", attempt=1, max_attempts=None, error_kind="unknown"), + ModelRequestEvent("request", "run", 2, "completed", usage=usage, round_usages=(usage,)), + ProgressEvent(tool_hint=True, tool_events=[{"call_id": "tool", "name": "read", "phase": "start"}]), + ProgressEvent(tool_events=[{"call_id": "tool", "name": "read", "phase": "end", "result": "complete"}]), + ] + try: + await manager._queue_outbound(channel, OutboundMessage( + "websocket", chat, "seed", metadata=metadata, event=ProgressEvent(content="seed"), + )) + await asyncio.wait_for(entered[0].wait(), 1) + for event in events: + await manager._queue_outbound(channel, OutboundMessage("websocket", chat, "", metadata=metadata, event=event)) + await manager._queue_outbound(channel, OutboundMessage("websocket", chat, "answer", metadata=metadata)) + await manager._queue_outbound(channel, OutboundMessage( + "websocket", chat, "", metadata=metadata, event=TurnEndEvent(usage=usage), + )) + assert connection.sent.empty() + release[0].set() + await asyncio.wait_for(entered[1].wait(), 1) + assert await _next_text(connection) == "seed" + assert connection.sent.empty() + assert [row["text"] for row in history.read(f"websocket:{chat}")] == ["seed"] + channel._attach(cast(Any, late), chat) + release[1].set() + async with asyncio.timeout(2): + while manager.has_pending_delivery: + await asyncio.sleep(0) + frames = [json.loads(connection.sent.get_nowait()) for _ in range(connection.sent.qsize())] + assert [frame["event"] for frame in frames] == [ + "model_request", "retry_status", "model_request", "message", "message", "message", "turn_end", "session_updated", + ] + assert frames[2]["usage"] == usage.to_turn_dict() + assert frames[4]["tool_events"][0]["result"] == "complete" + assert [len(facts) for facts in writes] == [1, 4, 1, 1] + durable = history.read(f"websocket:{chat}") + assert [row["turn_seq"] for row in durable] == list(range(1, 8)) + assert durable[4]["tool_events"][0]["result"] == "complete" + assert durable[-1]["event"] == "turn_end" + late_frames = [json.loads(late.sent.get_nowait()) for _ in range(late.sent.qsize())] + assert [frame["event"] for frame in late_frames] == ["message", "turn_end", "session_updated"] + assert late_frames[0]["text"] == "answer" + finally: + for gate in release: + gate.set() + await manager.stop_all() + + +@pytest.mark.asyncio +async def test_activity_batches_keep_replaced_session_generations_separate(history, tmp_path) -> None: + from nanobot.bus.outbound_events import ProgressEvent + + channel = _channel(history.sessions) + manager = ChannelManager( + Config.model_validate({"channels": {"websocket": {"enabled": False}}}), channel.bus, + config_path=tmp_path / "config.json", + ) + manager.channels["websocket"] = channel + chat = "replaced-batch" + key = f"websocket:{chat}" + old = await history.metadata(chat, {"webui_turn_id": "reused-turn"}) + await history.sessions.state.reset(key) + fresh = await history.metadata(chat, {"webui_turn_id": "reused-turn"}) + try: + for metadata, prefix in ((old, "stale"), (fresh, "current")): + for index in range(2): + text = f"{prefix}-{index}" + await manager._queue_outbound(channel, OutboundMessage( + "websocket", chat, text, metadata=metadata, event=ProgressEvent(content=text), + )) + async with asyncio.timeout(2): + while manager.has_pending_delivery: + await asyncio.sleep(0) + assert [row["text"] for row in history.read(key)] == ["current-0", "current-1"] + finally: + await manager.stop_all() + + +@pytest.mark.asyncio +async def test_cancelled_activity_batch_settles_admitted_write_without_fanout(history, monkeypatch) -> None: + import threading + + from nanobot.bus.outbound_events import ProgressEvent + + channel = _channel(history.sessions) + chat = "cancelled-batch" + metadata = await history.metadata(chat, {"webui_turn_id": "turn-cancel"}) + connection = _RecordingConnection() + channel._attach(cast(Any, connection), chat) + entered = asyncio.Event() + release = threading.Event() + loop = asyncio.get_running_loop() + append = history.sessions._store.append_history + + def gated_append(*args, **kwargs): + loop.call_soon_threadsafe(entered.set) + assert release.wait(2), "test did not release admitted write" + return append(*args, **kwargs) + + monkeypatch.setattr(history.sessions._store, "append_history", gated_append) + sending = asyncio.create_task(channel.send_batch([ + OutboundMessage("websocket", chat, text, metadata=metadata, event=ProgressEvent(content=text)) + for text in ("one", "two") + ])) + try: + await asyncio.wait_for(entered.wait(), 1) + sending.cancel() + await asyncio.sleep(0) + assert not sending.done() + assert connection.sent.empty() + release.set() + with pytest.raises(asyncio.CancelledError): + await sending + assert [row["text"] for row in history.read(f"websocket:{chat}")] == ["one", "two"] + assert connection.sent.empty() + finally: + release.set() + await asyncio.gather(sending, return_exceptions=True) + await channel.stop() + + +@pytest.mark.asyncio +async def test_activity_batch_byte_limit_preserves_large_progress(history, monkeypatch) -> None: + from nanobot.bus.outbound_events import ProgressEvent + from nanobot.webui import outbound_delivery + + monkeypatch.setattr(outbound_delivery, "_ACTIVITY_BATCH_BYTES", 1024) + channel = _channel(history.sessions) + chat = "large-batch" + metadata = await history.metadata(chat, {"webui_turn_id": "turn-large"}) + append = AsyncMock(wraps=history.sessions.state.append_history) + monkeypatch.setattr(history.sessions.state, "append_history", append) + texts = ["a" * 600, "b" * 1500, "c" * 100, "d" * 100] + await channel.send_batch([ + OutboundMessage("websocket", chat, text, metadata=metadata, event=ProgressEvent(content=text)) + for text in texts + ]) + assert [len(call.args[1]) for call in append.await_args_list] == [1, 1, 2] + assert [row["text"] for row in history.read(f"websocket:{chat}")] == texts + + +@pytest.mark.asyncio +async def test_oversized_activity_does_not_poison_valid_batch_neighbors(history, monkeypatch) -> None: + from nanobot.bus.outbound_events import ProgressEvent + from nanobot.session import display_history + + monkeypatch.setattr(display_history, "MAX_HISTORY_FACT_BYTES", 1024) + channel = _channel(history.sessions) + chat = "invalid-batch-member" + metadata = await history.metadata(chat, {"webui_turn_id": "turn-size"}) + connection = _RecordingConnection() + channel._attach(cast(Any, connection), chat) + texts = ["first", "x" * 1500, "last"] + try: + await channel.send_batch([ + OutboundMessage("websocket", chat, text, metadata=metadata, event=ProgressEvent(content=text)) + for text in texts + ]) + assert [await _next_text(connection) for _ in texts] == texts + assert [row["text"] for row in history.read(f"websocket:{chat}")] == ["first", "last"] + finally: + await channel.stop() + + +@pytest.mark.asyncio +async def test_unencodable_tool_argument_does_not_discard_neighboring_activity(history) -> None: + from nanobot.bus.outbound_events import ProgressEvent + + channel = _channel(history.sessions) + chat = "invalid-tool-argument" + metadata = await history.metadata(chat, {"webui_turn_id": "turn-encoding"}) + connection = _RecordingConnection() + channel._attach(cast(Any, connection), chat) + # JSON decoding accepts this provider argument, but UTF-8 transport cannot. + arguments = json.loads('{"query":"\\ud800"}') + messages = [ + OutboundMessage("websocket", chat, "first", metadata=metadata, event=ProgressEvent(content="first")), + OutboundMessage("websocket", chat, "", metadata=metadata, event=ProgressEvent(tool_events=[{ + "call_id": "bad", "name": "search", "phase": "start", "arguments": arguments, + }])), + OutboundMessage("websocket", chat, "last", metadata=metadata, event=ProgressEvent(content="last")), + ] + try: + await channel.send_batch(messages) + assert [await _next_text(connection) for _ in range(2)] == ["first", "last"] + assert connection.sent.empty() + assert [row["text"] for row in history.read(f"websocket:{chat}")] == ["first", "last"] + finally: + await channel.stop() diff --git a/nanobot/events.py b/nanobot/events.py index c7c5fee77..c2e7c4bea 100644 --- a/nanobot/events.py +++ b/nanobot/events.py @@ -6,11 +6,26 @@ from typing import Literal from loguru import logger +from nanobot.llm_usage.types import LLMUsage + class AgentEvent: """A typed event; only explicitly projected events cross a client boundary.""" +@dataclass(frozen=True) +class ModelRequestEvent(AgentEvent): + """Bounded snapshot of logical calls (provider retries stay inside a call).""" + + request_id: str + run_id: str + sequence: int + phase: Literal["started", "completed", "failed", "cancelled"] + usage: LLMUsage | None = None + round_usages: tuple[LLMUsage, ...] = () + context_window_tokens: int | None = None + + @dataclass(frozen=True) class ResponseSource: """Display-safe identity captured at the actual provider invocation.""" diff --git a/nanobot/session/display_history.py b/nanobot/session/display_history.py index 6e753645e..498e5f46b 100644 --- a/nanobot/session/display_history.py +++ b/nanobot/session/display_history.py @@ -24,6 +24,7 @@ class HistoryKind(StrEnum): COMPLETION = "completion" FORK_BOUNDARY = "fork_boundary" COMPACTION = "compaction" + MODEL_REQUEST = "model_request" # Only old transcripts can contain unfinished transport fragments. ANSWER_FRAGMENT = "answer_fragment" REASONING_FRAGMENT = "reasoning_fragment" diff --git a/nanobot/webui/history.py b/nanobot/webui/history.py index ba345550b..bfb888604 100644 --- a/nanobot/webui/history.py +++ b/nanobot/webui/history.py @@ -16,6 +16,7 @@ _EVENTS = { "turn_end": HistoryKind.COMPLETION, "fork_marker": HistoryKind.FORK_BOUNDARY, "context_compaction": HistoryKind.COMPACTION, + "model_request": HistoryKind.MODEL_REQUEST, "delta": HistoryKind.ANSWER_FRAGMENT, "reasoning_delta": HistoryKind.REASONING_FRAGMENT, } @@ -30,6 +31,7 @@ _CONTENT_FIELDS = frozenset({ "merge_next", "latency_ms", "usage", "round_usages", "context_window_tokens", "goal_state", "outcome", "failure_kind", "failure_error_kind", "failure_attempts", "failure_message", "transcript_incomplete", "stream_id", "compaction_id", "phase", "reason", "render_as", + "request_id", "run_id", "sequence", }) diff --git a/nanobot/webui/outbound_delivery.py b/nanobot/webui/outbound_delivery.py index 2c6a4714e..5a0621953 100644 --- a/nanobot/webui/outbound_delivery.py +++ b/nanobot/webui/outbound_delivery.py @@ -1,7 +1,7 @@ from __future__ import annotations import json -from collections.abc import Callable, Mapping +from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeAlias @@ -24,7 +24,9 @@ from nanobot.bus.outbound_events import ( ) from nanobot.bus.queue import MessageBus from nanobot.bus.runtime_events import SubagentTaskChanged +from nanobot.events import ModelRequestEvent from nanobot.pairing.events import PairingChanged +from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY from nanobot.session.webui_turns import ( clear_websocket_turn_if_current, mark_websocket_turn_transcript_persistence_failed, @@ -68,6 +70,7 @@ class ChatAudience: WebUIAudience: TypeAlias = ChatAudience | Literal["all_connections", "authenticated_webui"] +_ACTIVITY_BATCH_BYTES = 128 * 1024 class WebUIOutboundTransport(Protocol): @@ -135,6 +138,78 @@ class WebUIOutboundDelivery: for connection in recipients: await self._transport.webui_send_raw(connection, raw, label=label) + def can_batch_send(self, previous: OutboundMessage, following: OutboundMessage) -> bool: + def activity(msg: OutboundMessage) -> bool: + event = msg.event + return ( + not msg.media and not msg.metadata.get(WEBUI_RESTART_CONTROL_METADATA_KEY) + and ( + isinstance(event, ModelRequestEvent | RetryStatusEvent) + or isinstance(event, ProgressEvent) and not ( + event.reasoning or event.reasoning_delta or event.reasoning_end or event.file_edit_events + ) + ) + ) + + generation = following.metadata.get(HISTORY_GENERATION_METADATA_KEY) + turn_id = following.metadata.get(WEBUI_TURN_METADATA_KEY) + return ( + activity(previous) and activity(following) + and previous.chat_id == following.chat_id + and isinstance(generation, str) and bool(generation) + and isinstance(turn_id, str) and bool(turn_id) + and all(previous.metadata.get(key) == following.metadata.get(key) for key in ( + HISTORY_GENERATION_METADATA_KEY, WEBUI_TURN_METADATA_KEY, WEBSOCKET_TURN_OWNER_METADATA_KEY, + )) + and self._temporary_chats.should_persist_transcript(following.chat_id) + ) + + async def send_batch(self, messages: Sequence[OutboundMessage]) -> None: + first = messages[0] + frames: list[tuple[tuple[ServerConnection, ...], str, str]] = [] + records: list[dict[str, Any]] = [] + byte_count = 0 + + async def flush() -> None: + if records: + await self._transcripts.append_many(first.chat_id, records, metadata=first.metadata) + for recipients, raw, label in frames: + for connection in recipients: + await self._transport.webui_send_raw(connection, raw, label=label) + frames.clear() + records.clear() + + for msg in messages: + progress = msg.event if isinstance(msg.event, ProgressEvent) else None + if progress is not None: + body = self._message_payload(msg, progress) + persistent, label = True, " " + else: + notification = project_notification(msg.chat_id, msg.event, msg.metadata) + assert notification is not None + body = dict(notification.payload) + persistent = notification.persistence == "turn_activity" + label = f" {body['event']} " + if persistent: + self._transcripts.prepare_event( + msg.chat_id, body, metadata=msg.metadata, phase="activity", include_source=progress is not None, + ) + try: + raw = json.dumps(body, ensure_ascii=False) + size = len(raw.encode("utf-8")) + except (TypeError, ValueError, RecursionError) as exc: + logger.warning("WebUI activity encoding failed for {}: {}", msg.chat_id, exc) + continue + if frames and byte_count + size > _ACTIVITY_BATCH_BYTES: + await flush() + byte_count = 0 + recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) + frames.append((recipients, raw, label)) + if persistent: + records.append({**body, "text": msg.content} if progress is not None else body) + byte_count += size + await flush() + async def send(self, msg: OutboundMessage) -> None: event = msg.event if isinstance(event, PairingChanged): @@ -153,7 +228,7 @@ class WebUIOutboundDelivery: recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) if not recipients: quiet_events = ( - ProgressEvent, RetryStatusEvent, UserInputEvent, TurnEndEvent, SessionUpdatedEvent, + ModelRequestEvent, ProgressEvent, RetryStatusEvent, UserInputEvent, TurnEndEvent, SessionUpdatedEvent, GoalStatusEvent, GoalStateSyncEvent, SubagentTaskChanged, ContextCompactionEvent, ) log = logger.debug if isinstance(event, quiet_events) else logger.warning @@ -298,8 +373,7 @@ class WebUIOutboundDelivery: chat_id, persisted=persisted, metadata=metadata, phase=phase, ) - async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None: - recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) + def _message_payload(self, msg: OutboundMessage, progress: ProgressEvent | None) -> dict[str, Any]: text = msg.content user_shell = msg.metadata.get(INBOUND_META_USER_SHELL) is True payload: MessageWirePayload = { @@ -332,11 +406,15 @@ class WebUIOutboundDelivery: payload["agent_ui"] = agent_ui if progress: payload["kind"] = "tool_hint" if progress.tool_hint else "progress" - body: dict[str, Any] = dict(payload) + return dict(payload) + + async def _send_message(self, msg: OutboundMessage, progress: ProgressEvent | None) -> None: + recipients = self._transport.webui_recipients(ChatAudience(msg.chat_id)) + body = self._message_payload(msg, progress) await self._persist_turn_transcript_event( msg.chat_id, body, metadata=msg.metadata, phase="activity" if progress else "answer", include_source=True, - transcript_overrides={"text": text}, + transcript_overrides={"text": msg.content}, ) await self._fanout(recipients, body, label=" ") diff --git a/nanobot/webui/outbound_wire.py b/nanobot/webui/outbound_wire.py index b2a061274..d8997dfcb 100644 --- a/nanobot/webui/outbound_wire.py +++ b/nanobot/webui/outbound_wire.py @@ -11,7 +11,7 @@ from nanobot.bus.outbound_events import ( RetryStatusEvent, TurnEndEvent, ) -from nanobot.events import AgentEvent, CompactionReason +from nanobot.events import AgentEvent, CompactionReason, ModelRequestEvent from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY _JSONValue: TypeAlias = ( @@ -96,6 +96,17 @@ class TurnEndWirePayload(_ChatWirePayload): failure_message: NotRequired[str] +class ModelRequestWirePayload(_ChatWirePayload): + event: Literal["model_request"] + request_id: str + run_id: str + sequence: int + phase: Literal["started", "completed", "failed", "cancelled"] + usage: NotRequired[dict[str, int]] + round_usages: NotRequired[list[dict[str, int]]] + context_window_tokens: NotRequired[int] + + class ContextCompactionWirePayload(_ChatWirePayload): event: Literal["context_compaction"] compaction_id: str @@ -178,6 +189,7 @@ class TurnModelWirePayload(_ChatWirePayload): WebUIWirePayload: TypeAlias = ( + ModelRequestWirePayload | RetryStatusWirePayload | ContextCompactionWirePayload | RecoveryStateWirePayload | TurnEndWirePayload | SubagentTaskWirePayload | MessageWirePayload | StreamWirePayload | FileEditWirePayload | GoalStateWirePayload | GoalStatusWirePayload | SessionUpdatedWirePayload | UserInputWirePayload @@ -243,6 +255,20 @@ def project_notification( chat_id: str, event: AgentEvent | None, metadata: Mapping[str, object] | None = None, ) -> NotificationProjection | None: """Keep notification serialization and persistence decisions at one boundary.""" + if isinstance(event, ModelRequestEvent): + payload: ModelRequestWirePayload = { + "event": "model_request", "chat_id": chat_id, + "request_id": event.request_id, "run_id": event.run_id, + "sequence": event.sequence, "phase": event.phase, + } + if event.usage is not None: + payload["usage"] = event.usage.to_turn_dict() + payload["round_usages"] = [usage.to_turn_dict() for usage in event.round_usages[-8:]] + if event.context_window_tokens is not None: + payload["context_window_tokens"] = event.context_window_tokens + return NotificationProjection( + payload, persistence="turn_activity", deliver_offline=True, attach_turn_metadata=True, + ) if isinstance(event, ContextCompactionEvent): return NotificationProjection( encode_context_compaction(chat_id, event), diff --git a/nanobot/webui/transcript.py b/nanobot/webui/transcript.py index 722906956..d3f840e3a 100644 --- a/nanobot/webui/transcript.py +++ b/nanobot/webui/transcript.py @@ -80,6 +80,7 @@ _TURN_DISPLAY_EVENTS: frozenset[str] = frozenset({ "stream_end", "message", "file_edit", + "model_request", "turn_end", }) MAX_SESSION_MENTIONS = 8 @@ -563,6 +564,11 @@ class WebUITranscriptRecorder: async def append( self, chat_id: str, event: dict[str, Any], *, metadata: dict[str, Any] | None, + ) -> bool: + return await self.append_many(chat_id, [event], metadata=metadata) + + async def append_many( + self, chat_id: str, events: Sequence[dict[str, Any]], *, metadata: dict[str, Any] | None, ) -> bool: if self.sessions is None: return True # A transport-only channel has no durable session service. @@ -570,14 +576,27 @@ class WebUITranscriptRecorder: if not isinstance(generation, str) or not generation: self._log.warning("history event has no admitted generation for {}", chat_id) return False + facts: list[HistoryFact] = [] + valid = True + for event in events: + try: + fact = fact_from_record(_record_for_append(event)) + if len(events) > 1: + # An invalid member must not roll back otherwise valid activity. + fact.encode() + facts.append(fact) + except (ValueError, TypeError) as exc: + self._log.warning("history append failed for {}: {}", chat_id, exc) + valid = False + if not facts: + return False try: - fact = fact_from_record(_record_for_append(event)) - await self.sessions.state.append_history(webui_session_key(chat_id), [fact], + await self.sessions.state.append_history(webui_session_key(chat_id), facts, expected_generation=generation) except (OSError, ValueError, TypeError, sqlite3.Error, SessionConflictError, SessionOperationQueueFullError) as exc: self._log.warning("history append failed for {}: {}", chat_id, exc) return False - return True + return valid def _next_turn_seq(self, chat_id: str, turn_id: str) -> int: key = (chat_id, turn_id) @@ -1292,7 +1311,7 @@ def build_webui_trace_detail_response( events = [ event for record in lines[group.start:group.stop] - if ( + if record.get("event") != "model_request" and ( event := _client_projection_event( record, augment_user_media=None, @@ -1496,8 +1515,19 @@ def _client_projection_event( projected["reason"] = reason return projected - if event == "turn_end": - projected = {"event": "turn_end", **common} + if event in {"turn_end", "model_request"}: + projected = {"event": event, **common} + if event == "model_request": + request_id, run_id = record.get("request_id"), record.get("run_id") + sequence, phase = record.get("sequence"), record.get("phase") + if ( + not isinstance(request_id, str) or not request_id + or not isinstance(run_id, str) or not run_id + or not isinstance(sequence, int) or isinstance(sequence, bool) or sequence < 1 + or phase not in ("started", "completed", "failed", "cancelled") + ): + return None + projected.update(request_id=request_id, run_id=run_id, sequence=sequence, phase=phase) latency_ms = record.get("latency_ms") if isinstance(latency_ms, int | float) and latency_ms >= 0: projected["latency_ms"] = int(latency_ms) @@ -1511,8 +1541,8 @@ def _client_projection_event( for item in cast(list[object], raw_round_usages) if (sanitized := _sanitize_turn_usage(item)) is not None ] - if round_usages: - projected["round_usages"] = round_usages + if round_usages or event == "model_request": + projected["round_usages"] = round_usages[-8:] if event == "model_request" else round_usages context_window = record.get("context_window_tokens") if isinstance(context_window, int | float) and context_window >= 0: projected["context_window_tokens"] = int(context_window) @@ -1552,6 +1582,10 @@ def _client_projection_deferred_trace_groups( trace_count = 0 for index, record in enumerate(lines): + # Usage belongs to the turn, not the activity body. It must not split + # one deferred tool group into many eagerly loaded fragments. + if record.get("event") == "model_request": + continue is_activity = ( record.get("event") == "message" and record.get("kind") in {"tool_hint", "progress"} @@ -1591,6 +1625,7 @@ def _client_projection_page_event_count(turn: list[dict[str, Any]]) -> int: "message", "file_edit", "context_compaction", + "model_request", "turn_end", } return max(1, sum(record.get("event") in supported for record in turn)) @@ -1608,7 +1643,7 @@ def _client_projection_events( deferred_groups = _client_projection_deferred_trace_groups(lines) deferred_until = 0 for index, record in enumerate(lines): - if index < deferred_until: + if index < deferred_until and record.get("event") != "model_request": continue if record.get("event") == WEBUI_FORK_MARKER_EVENT: if fork_boundary_event_index is None: @@ -1635,7 +1670,10 @@ def _client_projection_events( ) event["text"] = _trace_summary(last_text) event.pop("tool_events", None) - receipts = _projection_receipts(lines[group.start:group.stop]) + receipts = _projection_receipts([ + grouped for grouped in lines[group.start:group.stop] + if grouped.get("event") != "model_request" + ]) if receipts: event["projection_receipts"] = receipts if detail_ref is not None: @@ -1737,8 +1775,9 @@ def build_webui_thread_response( before: str | None = None, after: str | None = None, stats: TranscriptReplayStats | None = None, + include_model_requests: bool = False, ) -> dict[str, Any] | None: - """Return canonical transcript events for the WebUI projector.""" + """Return canonical events, hiding additive request events from old clients.""" replay_stats = stats or TranscriptReplayStats() lines, page = _select_transcript_page( history=history, @@ -1821,6 +1860,14 @@ def build_webui_thread_response( augment_assistant_media=augment_assistant_media, augment_assistant_text=augment_assistant_text, ) + if not include_model_requests: + # Select pages and stable identities before capability filtering, so an + # older client's cursors still navigate the same durable transcript. + if fork_boundary_event_index is not None: + fork_boundary_event_index = sum( + event["event"] != "model_request" for event in events[:fork_boundary_event_index] + ) + events = [event for event in events if event["event"] != "model_request"] replay_stats.replay_ms += int((time.perf_counter() - replay_started) * 1000) payload["projection"] = "events" payload["events"] = events diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index 324908ebb..3431d0295 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -1221,7 +1221,9 @@ class GatewayHTTPHandler: active_turn_transcript_persistence_failed = ( websocket_turn_transcript_persistence_failed(chat_id) ) + include_model_requests = _query_first(query, "include_model_requests") == "1" revision_variant = { + "include_model_requests": include_model_requests, "active_turn_id": active_turn_id, "active_turn_started_at": active_turn_started_at, "active_turn_transcript_persistence_failed": ( @@ -1243,7 +1245,7 @@ class GatewayHTTPHandler: build_started = time.perf_counter() replay_stats = diagnostics.transcript if diagnostics is not None else TranscriptReplayStats() data = build_webui_thread_response( - decoded_key, history=history, + decoded_key, history=history, include_model_requests=include_model_requests, augment_user_media=lambda paths, local: self.media.augment_transcript_user_media(paths, local, session_key=decoded_key), augment_assistant_media=self.media.augment_transcript_media, augment_assistant_text=lambda text: self.media.rewrite_local_markdown_images( diff --git a/tests/agent/test_loop_direct_websocket_status.py b/tests/agent/test_loop_direct_websocket_status.py index fc42187cf..0ec025eb4 100644 --- a/tests/agent/test_loop_direct_websocket_status.py +++ b/tests/agent/test_loop_direct_websocket_status.py @@ -43,6 +43,7 @@ def _make_loop(tmp_path): async def test_process_direct_websocket_clears_run_status(tmp_path) -> None: loop = _make_loop(tmp_path) gateway = MagicMock() + gateway.transcripts.prepare_and_append = AsyncMock(return_value=True) channel = WebSocketChannel( {"enabled": True, "allowFrom": ["*"]}, loop.bus, diff --git a/tests/agent/test_loop_runner_integration.py b/tests/agent/test_loop_runner_integration.py index ab0d1d2e9..f22a37ca0 100644 --- a/tests/agent/test_loop_runner_integration.py +++ b/tests/agent/test_loop_runner_integration.py @@ -13,7 +13,7 @@ from nanobot.bus.events import InboundMessage from nanobot.bus.outbound_events import StreamedResponseEvent from nanobot.bus.queue import MessageBus from nanobot.config.schema import AgentDefaults -from nanobot.events import RetryStatusEvent +from nanobot.events import ModelRequestEvent, RetryStatusEvent from nanobot.goal.assembly import install_goal from nanobot.providers.base import ( GenerationSettings, @@ -92,11 +92,14 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path): assert result is not None assert captured["provider_context"].events.accepts(RetryStatusEvent) - assert bus.outbound_size == 1 - outbound = bus.outbound.get_nowait() - assert isinstance(outbound.event, RetryStatusEvent) - assert outbound.event.state == "waiting" - assert outbound.chat_id == "chat-a" + outbound = [bus.outbound.get_nowait() for _ in range(bus.outbound_size)] + assert [type(message.event) for message in outbound] == [ + ModelRequestEvent, RetryStatusEvent, ModelRequestEvent, + ] + retry = outbound[1].event + assert isinstance(retry, RetryStatusEvent) + assert retry.state == "waiting" + assert all(message.chat_id == "chat-a" for message in outbound) @pytest.mark.asyncio diff --git a/tests/agent/test_mcp_transient_retry.py b/tests/agent/test_mcp_transient_retry.py index 492b77d5d..a5f329cc1 100644 --- a/tests/agent/test_mcp_transient_retry.py +++ b/tests/agent/test_mcp_transient_retry.py @@ -790,13 +790,16 @@ async def test_resource_prompt_results_keep_runtime_classification(case): assert direct == (with_tool_error_hint(expected) if failed else expected) hook = _RecordingToolHook() - outputs, events = await execute_tool_calls( + settled = [] + await execute_tool_calls( registry, [call], concurrent=False, external_lookup_counts={}, workspace_violation_counts={}, hook=hook, context=AgentHookContext(iteration=0, messages=[]), + on_settled=AsyncMock(side_effect=settled.extend), ) - assert events[0]["status"] == ("error" if failed else "ok") - assert expected in outputs[0] + [completed] = settled + assert completed.event["status"] == ("error" if failed else "ok") + assert expected in completed.result assert hook.errors == ([expected] if failed else []) assert hook.successes == ([] if failed else [expected]) diff --git a/tests/agent/test_model_request_events.py b/tests/agent/test_model_request_events.py new file mode 100644 index 000000000..c42f0843f --- /dev/null +++ b/tests/agent/test_model_request_events.py @@ -0,0 +1,259 @@ +from __future__ import annotations + +import asyncio +from contextlib import nullcontext +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from agent.runner_helpers import make_run_spec +from nanobot.agent.hook import AgentHookContext +from nanobot.agent.progress_hook import AgentProgressHook +from nanobot.agent.runner import AgentRunner +from nanobot.agent.tools.execution import execute_tool_calls +from nanobot.events import EventSink, ModelRequestEvent +from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest + + +def spec(provider, sink, **kwargs): + tools = MagicMock() + tools.get_definitions.return_value = [] + return make_run_spec( + provider, initial_messages=[{"role": "user", "content": "hi"}], + tools=tools, model="test-model", max_iterations=2, + max_tool_result_chars=10000, events=sink, **kwargs, + ) + + +@pytest.mark.asyncio +async def test_requests_arrive_before_runner_finishes_and_cancel_is_terminal(): + events = [] + entered = asyncio.Event() + block = asyncio.Event() + + async def publish(event): + events.append(event) + + async def provider_call(**kwargs): + entered.set() + await block.wait() + return LLMResponse(content="done") + + provider = MagicMock() + provider.chat_stream_with_retry = provider_call + task = asyncio.create_task(AgentRunner().run(spec(provider, EventSink(publish)))) + await asyncio.wait_for(entered.wait(), 2) + assert not task.done() + assert [e.phase for e in events if isinstance(e, ModelRequestEvent)] == ["started"] + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + requests = [e for e in events if isinstance(e, ModelRequestEvent)] + assert [e.phase for e in requests] == ["started", "cancelled"] + assert requests[0].request_id == requests[1].request_id + assert [e.sequence for e in requests] == [1, 2] + assert requests[1].usage is None + + +@pytest.mark.asyncio +async def test_completed_request_usage_is_visible_while_tool_is_blocked(): + events = [] + entered = asyncio.Event() + release = asyncio.Event() + usage = LLMUsage.reported(input_tokens=12, output_tokens=3) + + async def publish(event): + events.append(event) + + async def tool_call(*args): + entered.set() + await release.wait() + return "ok" + + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock(side_effect=[ + LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})], usage=usage), + LLMResponse(content="done", usage=usage), + ]) + run_spec = spec(provider, EventSink(publish)) + run_spec.tools.prepare_call.return_value = (None, {}, None) + run_spec.tools.execute = tool_call + task = asyncio.create_task(AgentRunner().run(run_spec)) + try: + await asyncio.wait_for(entered.wait(), 2) + assert not task.done() + requests = [e for e in events if isinstance(e, ModelRequestEvent)] + assert [e.phase for e in requests] == ["started", "completed"] + assert requests[-1].usage == usage + assert requests[-1].round_usages == (usage,) + finally: + release.set() + await task + requests = [e for e in events if isinstance(e, ModelRequestEvent)] + assert [e.sequence for e in requests] == [1, 2, 3, 4] + assert len({e.run_id for e in requests}) == 1 + assert requests[0].request_id != requests[2].request_id + assert requests[-1].usage == usage + usage + + +@pytest.mark.asyncio +async def test_live_round_usage_folds_recovery_before_tool_finishes(): + events = [] + entered = asyncio.Event() + release = asyncio.Event() + usages = [LLMUsage.reported(input_tokens=value, output_tokens=1) for value in (10, 20, 30)] + + async def publish(event): + if isinstance(event, ModelRequestEvent): + events.append(event) + + async def tool_call(*args): + entered.set() + await release.wait() + return "ok" + + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock(side_effect=[ + LLMResponse(content=None, tool_calls=[ToolCallRequest("bad", "", {})], + finish_reason="tool_calls", usage=usages[0]), + LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})], + finish_reason="tool_calls", usage=usages[1]), + LLMResponse(content="done", usage=usages[2]), + ]) + run_spec = spec(provider, EventSink(publish)) + run_spec.tools.prepare_call.return_value = (None, {}, None) + run_spec.tools.execute = tool_call + task = asyncio.create_task(AgentRunner().run(run_spec)) + try: + await asyncio.wait_for(entered.wait(), 2) + assert not task.done() + completed = [event for event in events if event.phase == "completed"] + assert completed[0].round_usages == (usages[0],) + assert completed[-1].round_usages == (usages[0] + usages[1],) + assert completed[-1].usage == usages[0] + usages[1] + finally: + release.set() + result = await task + assert events[-1].round_usages == tuple(result.round_usages) + assert events[-1].usage == result.usage + assert [usage.input_tokens for usage in result.round_usages] == [30, 30] + + +@pytest.mark.asyncio +async def test_individual_tool_finishes_before_blocked_sibling(): + emitted = [] + settled = [] + fast_finished = asyncio.Event() + release = asyncio.Event() + tools = MagicMock() + tools.prepare_call.return_value = (None, {}, None) + + async def execute(name, args): + if name == "slow": + await release.wait() + return name + + tools.execute = execute + + async def publish(event): + emitted.extend(event.tool_events or []) + if any(e["call_id"] == "fast" and e["phase"] == "end" for e in event.tool_events or []): + fast_finished.set() + + task = asyncio.create_task(execute_tool_calls( + tools, [ToolCallRequest("slow", "slow", {}), ToolCallRequest("fast", "fast", {})], + concurrent=True, external_lookup_counts={}, workspace_violation_counts={}, + hook=AgentProgressHook(EventSink(publish)), context=AgentHookContext(0, []), + on_settled=AsyncMock(side_effect=settled.extend), + )) + try: + await asyncio.wait_for(fast_finished.wait(), 2) + assert not task.done() + assert not any(e["call_id"] == "slow" and e["phase"] == "end" for e in emitted) + finally: + release.set() + await task + assert [completed.result for completed in settled] == ["slow", "fast"] + assert [(e["call_id"], e["phase"]) for e in emitted].count(("fast", "end")) == 1 + + +@pytest.mark.asyncio +async def test_request_snapshots_bound_rounds_without_losing_cumulative_usage(): + events = [] + usage = LLMUsage.reported(input_tokens=12, output_tokens=3) + + async def publish(event): + events.append(event) + + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock(side_effect=[ + *[LLMResponse(content=None, tool_calls=[ToolCallRequest(str(i), "tool", {})], usage=usage) + for i in range(9)], + LLMResponse(content="done", usage=usage), + ]) + run_spec = spec(provider, EventSink(publish)) + run_spec.max_iterations = 10 + run_spec.tools.prepare_call.return_value = (None, {}, None) + run_spec.tools.execute = AsyncMock(return_value="ok") + result = await AgentRunner().run(run_spec) + completed = [e for e in events if isinstance(e, ModelRequestEvent) and e.phase == "completed"] + assert len(completed) == 10 + assert len(completed[-1].round_usages) == 8 + assert completed[-1].usage == result.usage + assert len(result.round_usages) == 10 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("response", [LLMResponse(content="error", finish_reason="error"), RuntimeError("failure")]) +async def test_request_failure_has_one_terminal_event(response): + events = [] + + async def publish(event): + events.append(event) + + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock(side_effect=[response]) + expected = pytest.raises(RuntimeError, match="failure") if isinstance(response, RuntimeError) else nullcontext() + with expected: + await AgentRunner().run(spec(provider, EventSink(publish))) + requests = [e for e in events if isinstance(e, ModelRequestEvent)] + assert [e.phase for e in requests] == ["started", "failed"] + assert requests[-1].usage is None + + +@pytest.mark.asyncio +async def test_tool_cancellation_closes_started_call_without_masking_cancel(): + emitted = [] + entered = asyncio.Event() + tools = MagicMock() + tools.prepare_call.return_value = (None, {}, None) + + async def execute(*args): + entered.set() + await asyncio.Event().wait() + + tools.execute = execute + + async def publish(event): + emitted.extend(event.tool_events or []) + if event.tool_events and event.tool_events[0]["phase"] == "error": + raise RuntimeError("notification failure must not replace cancellation") + + task = asyncio.create_task(execute_tool_calls( + tools, [ToolCallRequest("blocked", "blocked", {})], concurrent=False, + external_lookup_counts={}, workspace_violation_counts={}, + hook=AgentProgressHook(EventSink(publish)), context=AgentHookContext(0, []), + )) + await asyncio.wait_for(entered.wait(), 2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert [event["phase"] for event in emitted] == ["start", "error"] + + +def test_model_requests_are_optional_for_non_webui_channels(): + from nanobot.bus.notification_delivery import notification_is_deliverable + + for channel in ("telegram", "slack", "cli", "discord"): + assert not notification_is_deliverable(ModelRequestEvent, channel=channel, publish_lifecycle=True) + assert notification_is_deliverable(ModelRequestEvent, channel="websocket", publish_lifecycle=True) diff --git a/tests/agent/test_runner_core.py b/tests/agent/test_runner_core.py index 03d9cee57..d4289f067 100644 --- a/tests/agent/test_runner_core.py +++ b/tests/agent/test_runner_core.py @@ -8,6 +8,7 @@ from agent.runner_helpers import make_run_spec from nanobot.agent.context import TranscriptInput from nanobot.agent.context_governance import ContextWindowExceededError from nanobot.config.schema import AgentDefaults +from nanobot.events import EventSink, ModelRequestEvent from nanobot.providers.base import ( LLMProvider, LLMResponse, @@ -609,6 +610,7 @@ async def test_runner_returns_max_iterations_fallback(): async def test_runner_uses_no_tools_finalization_after_max_iterations(): from nanobot.agent.runner import AgentRunner + publish = AsyncMock() provider = MagicMock(spec=LLMProvider) calls: list[dict] = [] @@ -644,6 +646,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations(): model="test-model", max_iterations=2, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, + events=EventSink(publish), )) assert result.stop_reason == "max_iterations" @@ -664,6 +667,10 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations(): (1, 1), (10, 7), ] + completed = [call.args[0] for call in publish.await_args_list + if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"] + assert completed[-1].round_usages == tuple(result.round_usages) + assert completed[-1].usage == result.usage @pytest.mark.asyncio @@ -671,6 +678,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery(): from nanobot.agent.hook import AgentHook from nanobot.agent.runner import AgentRunner + publish = AsyncMock() provider = MagicMock(spec=LLMProvider) calls: list[dict] = [] @@ -703,6 +711,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery(): max_iterations=1, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, hook=hook, + events=EventSink(publish), )) assert result.final_content == "recovered answer" @@ -722,6 +731,11 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery(): assert result.usage is not None assert (result.usage.input_tokens, result.usage.output_tokens) == (60, 6) assert [(item.input_tokens, item.output_tokens) for item in result.round_usages] == [(60, 6)] + completed = [call.args[0] for call in publish.await_args_list + if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"] + assert [len(event.round_usages) for event in completed] == [1, 1, 1] + assert completed[-1].round_usages == tuple(result.round_usages) + assert completed[-1].usage == result.usage @pytest.mark.asyncio @@ -766,6 +780,7 @@ async def test_runner_replaces_empty_tool_result_with_marker(): async def test_runner_retries_empty_final_response_with_summary_prompt(): from nanobot.agent.runner import AgentRunner + publish = AsyncMock() provider = MagicMock(spec=LLMProvider) calls: list[dict] = [] @@ -794,6 +809,7 @@ async def test_runner_retries_empty_final_response_with_summary_prompt(): model="test-model", max_iterations=3, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, + events=EventSink(publish), )) assert result.final_content == "final answer" @@ -809,6 +825,10 @@ async def test_runner_retries_empty_final_response_with_summary_prompt(): (5, 1), (3, 7), ] + completed = [call.args[0] for call in publish.await_args_list + if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"] + assert completed[-1].round_usages == tuple(result.round_usages) + assert completed[-1].usage == result.usage @pytest.mark.asyncio @@ -1190,7 +1210,7 @@ async def test_runner_carries_retry_notifications_in_provider_context(): assert "on_retry_wait" not in captured event = RetryWaitEvent("waiting") await captured["provider_context"].events.emit(event) - retry_wait_cb.assert_awaited_once_with(event) + retry_wait_cb.assert_any_await(event) @pytest.mark.asyncio diff --git a/tests/agent/test_runner_errors.py b/tests/agent/test_runner_errors.py index 86aa9a395..d9a947430 100644 --- a/tests/agent/test_runner_errors.py +++ b/tests/agent/test_runner_errors.py @@ -71,7 +71,8 @@ async def test_tool_execution_does_not_duplicate_existing_error_hint(): execute=AsyncMock(return_value=ToolResult.error("Error: boom" + error_hint)), ) - results, events = await execute_tool_calls( + settled = [] + await execute_tool_calls( tools, [ToolCallRequest(id="call_1", name="list_dir", arguments={})], concurrent=False, @@ -79,11 +80,13 @@ async def test_tool_execution_does_not_duplicate_existing_error_hint(): workspace_violation_counts={}, hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]), + on_settled=AsyncMock(side_effect=settled.extend), ) - assert results == ["Error: boom" + error_hint] - assert results[0].count(error_hint) == 1 - assert events[0]["status"] == "error" + [completed] = settled + assert completed.result == "Error: boom" + error_hint + assert completed.result.count(error_hint) == 1 + assert completed.event["status"] == "error" @pytest.mark.asyncio diff --git a/tests/agent/test_runner_file_reads.py b/tests/agent/test_runner_file_reads.py index b049c03d0..4a38b14b3 100644 --- a/tests/agent/test_runner_file_reads.py +++ b/tests/agent/test_runner_file_reads.py @@ -147,11 +147,13 @@ async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, ope if operation == "repeat_batch": calls.append(ToolCallRequest(id="batch-2", name=name, arguments=arguments)) - results, _ = await execute_tool_calls( + settled = [] + await execute_tool_calls( tools, calls, concurrent=True, external_lookup_counts={}, workspace_violation_counts={}, hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]), - model_messages=messages, + model_messages=messages, on_settled=AsyncMock(side_effect=settled.extend), ) + results = [completed.result for completed in settled] if operation == "repeat_batch": assert results == ["[File unchanged since last read: data.txt]"] * 2 @@ -176,18 +178,20 @@ async def test_failed_file_read_restores_context(tmp_path, monkeypatch, error): raise error("read interrupted") monkeypatch.setattr(tool, "execute", fail) + settled = [] request = execute_tool_calls( tools, [ToolCallRequest(id="failed-read", name="read_file", arguments={"path": "data.txt"})], concurrent=False, external_lookup_counts={}, workspace_violation_counts={}, hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]), - model_messages=first.messages, + model_messages=first.messages, on_settled=AsyncMock(side_effect=settled.extend), ) if error is asyncio.CancelledError: with pytest.raises(asyncio.CancelledError): await request else: - results, _ = await request - assert results[0].startswith("Error: RuntimeError: read interrupted") + await request + [completed] = settled + assert completed.result.startswith("Error: RuntimeError: read interrupted") monkeypatch.setattr(tool, "execute", original_execute) assert await tools.execute("read_file", {"path": "data.txt"}) == contents diff --git a/tests/agent/test_runner_governance.py b/tests/agent/test_runner_governance.py index 466a2669f..caa550a34 100644 --- a/tests/agent/test_runner_governance.py +++ b/tests/agent/test_runner_governance.py @@ -97,7 +97,7 @@ async def test_provider_can_emit_without_an_event_specific_runner_callback(): initial_messages=[{"role": "user", "content": "hello"}], events=EventSink(observe), )) - assert received == [event] + assert received.count(event) == 1 async def test_runner_propagates_context_governance_failure(): @@ -347,7 +347,8 @@ async def test_native_compaction_uses_provider_request_boundary( compaction_events: list[ContextCompactionEvent] = [] async def observe_compaction(event: ContextCompactionEvent) -> None: - compaction_events.append(event) + if isinstance(event, ContextCompactionEvent): + compaction_events.append(event) result = await AgentRunner().run(make_run_spec( provider, @@ -530,7 +531,8 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch): compaction_events: list[ContextCompactionEvent] = [] async def observe_compaction(event: ContextCompactionEvent) -> None: - compaction_events.append(event) + if isinstance(event, ContextCompactionEvent): + compaction_events.append(event) result = await AgentRunner().run(make_run_spec( provider, diff --git a/tests/agent/test_runner_hooks.py b/tests/agent/test_runner_hooks.py index a5b7fde62..ee043a511 100644 --- a/tests/agent/test_runner_hooks.py +++ b/tests/agent/test_runner_hooks.py @@ -7,6 +7,7 @@ import pytest from agent.runner_helpers import make_run_spec from nanobot.config.schema import AgentDefaults +from nanobot.events import EventSink, ModelRequestEvent from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage, ToolCallRequest _MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars @@ -147,13 +148,14 @@ async def test_runner_measures_stream_generation_without_time_to_first_token(): from nanobot.agent.runner import AgentRunner provider = MagicMock(spec=LLMProvider) + publish = AsyncMock() async def chat_stream_with_retry(*, on_content_delta, **kwargs): await on_content_delta("he") await on_content_delta("llo") return LLMResponse( content="hello", - usage=LLMUsage.reported(input_tokens=100, output_tokens=12), + usage=LLMUsage.reported(input_tokens=100, output_tokens=12, cache_read_tokens=4), ) provider.chat_stream_with_retry = chat_stream_with_retry @@ -177,6 +179,7 @@ async def test_runner_measures_stream_generation_without_time_to_first_token(): max_iterations=1, max_tool_result_chars=_MAX_TOOL_RESULT_CHARS, hook=StreamingHook(), + events=EventSink(publish), )) assert result.usage is not None @@ -184,6 +187,11 @@ async def test_runner_measures_stream_generation_without_time_to_first_token(): assert result.usage.measured_output_tokens == 12 assert result.usage.ttft_ms == 200 assert result.usage.timed_requests == 1 + assert result.usage.cache_read_tokens == 4 + [completed] = [call.args[0] for call in publish.await_args_list + if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"] + assert completed.usage == result.usage + assert completed.round_usages == tuple(result.round_usages) @pytest.mark.asyncio diff --git a/tests/agent/test_runner_progress_events.py b/tests/agent/test_runner_progress_events.py index 264c6bb9c..be9096045 100644 --- a/tests/agent/test_runner_progress_events.py +++ b/tests/agent/test_runner_progress_events.py @@ -1,3 +1,4 @@ +import asyncio from unittest.mock import AsyncMock, MagicMock import pytest @@ -175,12 +176,172 @@ async def test_batched_file_reads_keep_each_call_and_complete_arguments() -> Non )) assert result.final_content == "Done" - assert [(content, hint) for content, hint, _events in progress] == [("", True), ("", False)] - for _content, _hint, events in progress: + assert len(progress) == 4 + for phase, hint in (("start", True), ("end", False)): + events = [item for content, is_hint, items in progress if is_hint == hint for item in items] assert [(item["call_id"], item["name"], item["arguments"]) for item in events] == [ (call.id, call.name, call.arguments) for call in calls ] - assert [item["phase"] for item in progress[0][2]] == ["start", "start"] - assert [(item["phase"], item["result"]) for item in progress[1][2]] == [ - ("end", "file contents"), ("end", "file contents"), - ] + assert [item["phase"] for item in events] == [phase, phase] + if phase == "end": + assert [item["result"] for item in events] == ["file contents", "file contents"] + + +def _notification_run_spec(execute, on_progress, calls, checkpoints): + provider = MagicMock() + provider.chat_stream_with_retry = AsyncMock(side_effect=[ + LLMResponse(content=None, tool_calls=calls), + LLMResponse(content="Done"), + ]) + tools = MagicMock() + tools.get_definitions.return_value = [] + tools.prepare_call.return_value = (None, {}, None) + tools.execute = execute + + async def checkpoint(payload): + checkpoints.append(payload) + + return make_run_spec( + provider, initial_messages=[], tools=tools, model="test-model", + max_iterations=2, max_tool_result_chars=_DEFAULTS.max_tool_result_chars, + concurrent_tools=True, hook=AgentProgressHook(output_events(on_progress=on_progress)), + checkpoint_callback=checkpoint, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure_phase", ["start", "end"]) +async def test_tool_notification_failure_settles_results_and_cancels_siblings(failure_phase): + entered = asyncio.Event() + release = asyncio.Event() + stopped = asyncio.Event() + effects = [] + checkpoints = [] + error = BrokenPipeError("progress consumer closed") + + async def execute(name, arguments): + if name == "slow": + entered.set() + try: + await release.wait() + effects.append("slow") + return "slow result" + finally: + stopped.set() + effects.append("fast") + return "fast result" + + async def progress(content, *, tool_events=None, **kwargs): + if any(event["call_id"] == "fast" and event["phase"] == failure_phase + for event in tool_events or []): + await entered.wait() + raise error + + task = asyncio.create_task(AgentRunner().run(_notification_run_spec( + execute, progress, + [ToolCallRequest("slow", "slow", {}), ToolCallRequest("fast", "fast", {})], + checkpoints, + ))) + try: + with pytest.raises(BrokenPipeError) as raised: + await asyncio.wait_for(task, 2) + assert raised.value is error + assert stopped.is_set() + assert effects == (["fast"] if failure_phase == "end" else []) + if failure_phase == "end": + checkpoint = checkpoints[-1] + assert checkpoint["phase"] == "tools_completed" + slow, fast = checkpoint["completed_tool_results"] + assert (fast["tool_call_id"], fast["content"]) == ("fast", "fast result") + assert slow["tool_call_id"] == "slow" + assert slow["_recovery_interrupted"] is True + assert "outcome is unknown" in slow["content"] + assert checkpoint["pending_tool_calls"] == [] + from nanobot.session.recovery import runtime_checkpoint_is_well_formed + + assert runtime_checkpoint_is_well_formed(checkpoint) + else: + assert [checkpoint["phase"] for checkpoint in checkpoints] == ["awaiting_tools"] + finally: + release.set() + await asyncio.gather(task, return_exceptions=True) + await asyncio.wait_for(stopped.wait(), 2) + + +@pytest.mark.asyncio +async def test_tool_completion_notification_error_preserves_completed_checkpoint(): + checkpoints = [] + error = BrokenPipeError("progress consumer closed") + + async def progress(content, *, tool_events=None, **kwargs): + if any(event["phase"] == "end" for event in tool_events or []): + raise error + + with pytest.raises(BrokenPipeError) as raised: + await AgentRunner().run(_notification_run_spec( + AsyncMock(return_value="completed effect"), progress, + [ToolCallRequest("fast", "fast", {})], checkpoints, + )) + assert raised.value is error + assert [checkpoint["phase"] for checkpoint in checkpoints] == ["awaiting_tools", "tools_completed"] + assert checkpoints[-1]["completed_tool_results"][0]["content"] == "completed effect" + assert checkpoints[-1]["pending_tool_calls"] == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cancel_during", ["start", "execution", "end"]) +async def test_tool_cancellation_does_not_wait_for_blocked_progress(cancel_during): + queue = asyncio.Queue(maxsize=1) + if cancel_during == "start": + queue.put_nowait([]) + entered = asyncio.Event() + release = asyncio.Event() + stopped = asyncio.Event() + checkpoints = [] + effects = [] + notifications = set() + + async def execute(name, arguments): + if cancel_during == "execution": + entered.set() + try: + await release.wait() + finally: + stopped.set() + effects.append(name) + return "completed effect" + + async def progress(content, *, tool_events=None, **kwargs): + if tool_events: + notification = asyncio.current_task() + notifications.add(notification) + try: + if any(event["phase"] == cancel_during for event in tool_events): + entered.set() + await queue.put(tool_events) + finally: + notifications.remove(notification) + + task = asyncio.create_task(AgentRunner().run(_notification_run_spec( + execute, progress, [ToolCallRequest("tool", "tool", {})], checkpoints, + ))) + try: + await asyncio.wait_for(entered.wait(), 2) + task.cancel() + done, _ = await asyncio.wait({task}, timeout=1) + assert done, "cancellation must settle without a second cancel or queue consumer" + with pytest.raises(asyncio.CancelledError): + await task + assert not notifications + assert effects == (["tool"] if cancel_during == "end" else []) + if cancel_during == "end": + assert checkpoints[-1]["phase"] == "tools_completed" + assert checkpoints[-1]["completed_tool_results"][0]["content"] == "completed effect" + elif cancel_during == "execution": + assert stopped.is_set() + finally: + # Keep the failure reproduction bounded even with the old shielded send. + if not queue.empty(): + queue.get_nowait() + release.set() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/agent/test_turn_hooks.py b/tests/agent/test_turn_hooks.py index 700224912..92d609248 100644 --- a/tests/agent/test_turn_hooks.py +++ b/tests/agent/test_turn_hooks.py @@ -42,6 +42,7 @@ async def test_tool_log_privacy_preserves_user_visible_progress(ephemeral, hoste }) else: await hook.before_execute_tools(context) + await hook.on_tool_execution_event(context) finally: logger.remove(sink) diff --git a/tests/agent/tools/test_subagent_tools.py b/tests/agent/tools/test_subagent_tools.py index e30515045..0dfcf7d32 100644 --- a/tests/agent/tools/test_subagent_tools.py +++ b/tests/agent/tools/test_subagent_tools.py @@ -470,6 +470,7 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path): ), ] + settled = [] with request_context(RequestContext( channel="test", chat_id="c1", @@ -484,14 +485,15 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path): workspace_violation_counts={}, hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[], session_key="test:c1"), + on_settled=AsyncMock(side_effect=settled.extend), )) await asyncio.wait_for(both_entered.wait(), timeout=1.0) release.set() - results, events = await execution + await execution assert set(entered) == {"first", "second"} - assert results == ["first", "second"] - assert [event["status"] for event in events] == ["ok", "ok"] + assert [completed.result for completed in settled] == ["first", "second"] + assert [completed.event["status"] for completed in settled] == ["ok", "ok"] assert manager._running_tasks == {} diff --git a/tests/channels/test_channel_manager_concurrency.py b/tests/channels/test_channel_manager_concurrency.py index db2b49498..796ddb849 100644 --- a/tests/channels/test_channel_manager_concurrency.py +++ b/tests/channels/test_channel_manager_concurrency.py @@ -12,9 +12,9 @@ from nanobot.config.schema import Config from nanobot.runtime_admission import RuntimeBusyError -def make_manager(): +def make_manager(*, config_path=None): config = Config.model_validate({"channels": {"websocket": {"enabled": False}}}) - manager = ChannelManager(config, MessageBus()) + manager = ChannelManager(config, MessageBus(), config_path=config_path) channel = MagicMock(spec=BaseChannel) channel.send = AsyncMock() channel.stop = AsyncMock() @@ -114,6 +114,181 @@ async def test_ten_chats_keep_order_while_one_destination_is_blocked(): await manager.stop_all() +async def test_ready_batches_are_capped_at_32_and_keep_fifo(): + manager, channel = make_manager() + channel.can_batch_send.return_value = True + delivered = [] + + async def send(msg): + delivered.append([msg]) + + async def send_batch(messages): + delivered.append(list(messages)) + + channel.send.side_effect = send + channel.send_batch.side_effect = send_batch + messages = [OutboundMessage("websocket", "chat", str(i)) for i in range(65)] + try: + for msg in messages: + await manager._queue_outbound(channel, msg) + await wait_until(lambda: not manager._outbound_tasks) + assert delivered == [messages[:32], messages[32:64], messages[64:]] + assert channel.send_batch.await_count == 2 + channel.send.assert_awaited_once_with(messages[-1]) + finally: + await manager._cancel_outbound() + + +async def test_batches_keep_fifo_across_noneligible_and_scheduled_boundaries(tmp_path): + from nanobot.bus.delivery import DeliveryRequest + + manager, channel = make_manager(config_path=tmp_path / "config.json") + channel.can_batch_send.side_effect = lambda previous, following: ( + previous.content != "boundary" and following.content != "boundary" + ) + delivered = [] + + async def send(msg): + delivered.append([msg]) + + async def send_batch(messages): + delivered.append(list(messages)) + + channel.send.side_effect = send + channel.send_batch.side_effect = send_batch + messages = [OutboundMessage("websocket", "chat", content) for content in ( + "first-a", "first-b", "boundary", "second-a", "second-b", + "scheduled", "third-a", "third-b", + )] + scheduled = messages[5] + scheduled.delivery = DeliveryRequest("run", "websocket:chat", None) + manager._outbox.record(scheduled) + try: + for msg in messages: + await manager._queue_outbound(channel, msg) + await wait_until(lambda: not manager._outbound_tasks) + assert delivered == [messages[:2], messages[2:3], messages[3:5], messages[5:6], messages[6:]] + assert [call.args[0] for call in channel.send.await_args_list] == [messages[2], scheduled] + assert manager._outbox.ready() == [] + assert not manager._scheduled_deliveries + finally: + await manager._cancel_outbound() + + +@pytest.mark.parametrize("start_batch", [False, True], ids=["before-start", "active"]) +async def test_batch_admission_counts_envelopes_and_cancellation_releases_them(monkeypatch, start_batch): + monkeypatch.setattr(manager_module, "_OUTBOUND_PENDING_LIMIT", 4) + monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 1) + manager, channel = make_manager() + channel.can_batch_send.return_value = True + started, release = asyncio.Event(), asyncio.Event() + extra = None + + async def send_batch(messages): + started.set() + await release.wait() + + channel.send_batch.side_effect = send_batch + try: + for i in range(4): + await manager._queue_outbound(channel, OutboundMessage("websocket", "chat", str(i))) + assert manager.has_pending_delivery + if start_batch: + await asyncio.wait_for(started.wait(), 2) + else: + # No yielding since queueing: cancel before the batch task starts. + channel.send_batch.assert_not_awaited() + await manager._cancel_outbound() + assert not manager.has_pending_delivery + + started.clear() + recovered = [OutboundMessage("websocket", "chat", f"recovered-{i}") for i in range(4)] + async with asyncio.timeout(2): + for msg in recovered: + await manager._queue_outbound(channel, msg) + await asyncio.wait_for(started.wait(), 2) + extra = asyncio.create_task(manager._queue_outbound( + channel, OutboundMessage("websocket", "other", "blocked admission"), + )) + await asyncio.sleep(0) + assert not extra.done() + extra.cancel() + await asyncio.gather(extra, return_exceptions=True) + release.set() + await wait_until(lambda: not manager.has_pending_delivery) + channel.send_batch.assert_awaited_with(tuple(recovered)) + assert channel.send_batch.await_count == 1 + int(start_batch) + channel.send.assert_not_awaited() + finally: + if extra is not None: + extra.cancel() + await asyncio.gather(extra, return_exceptions=True) + release.set() + await manager._cancel_outbound() + + +async def test_batch_waiting_for_send_permit_cannot_absorb_later_envelopes(monkeypatch): + monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 1) + manager, channel = make_manager() + channel.can_batch_send.return_value = True + messages = [OutboundMessage("websocket", "chat", str(i)) for i in range(4)] + try: + async with manager._outbound_sends: + for msg in messages[:2]: + await manager._queue_outbound(channel, msg) + await asyncio.sleep(0) + channel.send_batch.assert_not_awaited() + for msg in messages[2:]: + await manager._queue_outbound(channel, msg) + await wait_until(lambda: not manager._outbound_tasks) + assert [list(call.args[0]) for call in channel.send_batch.await_args_list] == [ + messages[:2], messages[2:], + ] + channel.send.assert_not_awaited() + finally: + await manager._cancel_outbound() + + +async def test_partially_failed_batch_is_not_replayed_and_later_message_proceeds(monkeypatch): + monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0,)) + manager, channel = make_manager() + manager.config.channels.send_max_retries = 3 + channel.can_batch_send.return_value = True + channel.should_retry_send_error.return_value = True + started, fail = asyncio.Event(), asyncio.Event() + delivered = [] + + async def send_batch(messages): + delivered.append(messages[0].content) + started.set() + await fail.wait() + raise OSError("transport failed after the first envelope") + + async def send(msg): + delivered.append(msg.content) + + channel.send_batch.side_effect = send_batch + channel.send.side_effect = send + batch = [OutboundMessage("websocket", "chat", content) for content in ("first", "unsent")] + later = OutboundMessage("websocket", "chat", "later") + try: + for msg in batch: + await manager._queue_outbound(channel, msg) + await asyncio.wait_for(started.wait(), 2) + await manager._queue_outbound(channel, later) + await asyncio.sleep(0) + assert delivered == ["first"] + fail.set() + await wait_until(lambda: not manager._outbound_tasks) + channel.send_batch.assert_awaited_once_with(tuple(batch)) + channel.send.assert_awaited_once_with(later) + assert delivered == ["first", "later"] + assert not manager.has_pending_delivery + finally: + fail.set() + await manager._cancel_outbound() + + async def test_retry_does_not_block_other_chats(monkeypatch): monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.1,)) manager, channel = make_manager() diff --git a/tests/tools/test_private_tool_logging.py b/tests/tools/test_private_tool_logging.py index b86c845bc..3793918bc 100644 --- a/tests/tools/test_private_tool_logging.py +++ b/tests/tools/test_private_tool_logging.py @@ -239,16 +239,18 @@ async def test_search_refresh_traceback_cannot_capture_private_call_arguments( lambda message: rendered.append(str(message)), format="{message}", diagnose=True, backtrace=True, ) + settled = [] try: with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)): - results, _ = await execute_tool_calls( + await execute_tool_calls( tools, [ToolCallRequest(id="test", name="web_search", arguments={"query": _SECRET})], concurrent=False, external_lookup_counts={}, workspace_violation_counts={}, hook=AgentHook(), context=AgentHookContext(iteration=1, messages=[]), + on_settled=AsyncMock(side_effect=settled.extend), ) finally: logger.remove(sink) - assert results == ["synthetic result"] + assert [completed.result for completed in settled] == ["synthetic result"] assert "Failed to refresh web search config" in "\n".join(rendered) assert (_SECRET in "\n".join(rendered)) is log_content diff --git a/tests/utils/test_webui_transcript.py b/tests/utils/test_webui_transcript.py index 008c3869e..96f356870 100644 --- a/tests/utils/test_webui_transcript.py +++ b/tests/utils/test_webui_transcript.py @@ -474,7 +474,8 @@ def test_many_short_trace_rows_are_bounded_and_resolved(history, tmp_path, monke assert detail["events"][-1]["text"] == f"tool_{trace_count - 1}(value)" -def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(history) -> None: +@pytest.mark.parametrize("with_model_requests", [False, True]) +def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(history, with_model_requests) -> None: key = "websocket:summary-receipts" history.append(key, {"event": "user", "text": "run tools", "turn_id": "turn-T", "turn_seq": 1}) members = [("turn-T", 3), ("turn-T", 4), ("turn-U", 2), ("turn-T", 8)] @@ -483,13 +484,25 @@ def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(his "event": "message", "kind": "progress", "text": f'exec({"x" * 10_000})', "turn_id": turn_id, "turn_seq": sequence, "turn_phase": "activity", }) + if with_model_requests and (turn_id, sequence) == ("turn-T", 4): + history.append(key, { + "event": "model_request", "turn_id": "turn-T", "turn_seq": 5, + "request_id": "request-one", "run_id": "run-one", "sequence": 2, + "phase": "completed", "usage": {"prompt_tokens": 100, "completion_tokens": 10}, + }) history.append(key, {"event": "turn_end", "turn_id": "turn-T", "turn_seq": 9}) original_rows = history.read(key) - payload = history.build(key) + payload = history.build(key, include_model_requests=True) assert payload is not None - assert len(payload["events"]) == 3 + assert len(payload["events"]) == 3 + int(with_model_requests) + if with_model_requests: + request = payload["events"][2] + assert (request["event"], request["turn_seq"], request["usage"]["prompt_tokens"]) == ("model_request", 5, 100) + legacy = history.build(key) + assert legacy is not None + assert len(legacy["events"]) == 3 summary = payload["events"][1] assert summary["trace_detail"]["traceCount"] == len(members) assert summary["projection_receipts"] == [ @@ -639,6 +652,10 @@ def test_build_response_reports_fork_boundary_from_marker(history, tmp_path, mon {"event": "message", "chat_id": "fork", "text": "answer1"}, ): history.append(key, ev) + history.append(key, { + "event": "model_request", "chat_id": "fork", "request_id": "request", + "run_id": "run", "sequence": 2, "phase": "completed", "round_usages": [], + }) history.append(key, {"event": "fork_marker"}) history.append(key, {"event": "user", "chat_id": "fork", "text": "new branch"}) @@ -649,6 +666,9 @@ def test_build_response_reports_fork_boundary_from_marker(history, tmp_path, mon "round1", "answer1", "new branch", ] assert out["fork_boundary_event_index"] == 2 + modern = history.build(key, include_model_requests=True) + assert modern is not None + assert modern["fork_boundary_event_index"] == 3 def test_thread_response_does_not_mark_completed_message_tool_tail_pending(history, @@ -1232,3 +1252,33 @@ def test_existing_shell_output_uses_canonical_command_identity_not_bang_text(his assert answer.get("render_as") == ("text" if command else None) assert history.read(key)[1]["text"] == output assert messages[1]["content"] == output + + +@pytest.mark.parametrize("phase", ["started", "completed", "failed", "cancelled"]) +def test_model_request_persists_through_reconnect_projection(history, tmp_path, phase): + from nanobot.events import ModelRequestEvent + from nanobot.providers.base import LLMUsage + from nanobot.session.manager import SessionManager + from nanobot.webui.outbound_wire import project_notification + + key = "websocket:requests" + history.append(key, {"event": "user", "chat_id": "requests", "text": "hello"}) + usage = LLMUsage.reported(input_tokens=12, output_tokens=3) + projection = project_notification("requests", ModelRequestEvent( + request_id="request", run_id="run", sequence=2, phase=phase, + usage=usage, round_usages=(usage,) * 10, context_window_tokens=32000, + )) + assert projection is not None + assert projection.persistence == "turn_activity" + assert projection.deliver_offline + record = {**projection.payload, "turn_id": "turn", "turn_seq": 2} + history.append(key, record) + reopened = SessionManager(tmp_path) + response = reopened.project_history(key, lambda snapshot: transcript_module.build_webui_thread_response( + key, history=snapshot, include_model_requests=True, + )) + assert response is not None + [event] = [e for e in response["events"] if e["event"] == "model_request"] + assert {field: event[field] for field in record} == record + assert len(event["round_usages"]) == 8 + assert event["usage"] == usage.to_turn_dict() diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.py index 2a5c46148..c2d66b0ed 100644 --- a/tests/webui/test_gateway_webui_smoke.py +++ b/tests/webui/test_gateway_webui_smoke.py @@ -645,8 +645,25 @@ main() assert len(requests) == 17 else: await asyncio.wait_for(closing_request.wait(), 20) - await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "running") + waiting = await receive_until(lambda event: ( + event.get("event") == "model_request" + and event.get("phase") == "started" + and event.get("usage", {}).get("request_count") == 16 + )) + assert waiting["usage"]["context_tokens"] == 10 + assert len(waiting["round_usages"]) == 8 assert not any(event.get("event") == "turn_end" for event in events) + history_url = f"http://127.0.0.1:{ws_port}/api/sessions/{quote('websocket:' + chat_id, safe='')}/webui-thread" + headers = {"Authorization": f"Bearer {bootstrap['api_token']}"} + async with httpx.AsyncClient(trust_env=False) as client: + modern = await client.get(history_url, params={"include_model_requests": "1"}, headers=headers) + modern.raise_for_status() + persisted = [event for event in modern.json()["events"] if event["event"] == "model_request"] + assert persisted[-1]["request_id"] == waiting["request_id"] + assert persisted[-1]["usage"] == waiting["usage"] + legacy = await client.get(history_url, headers={**headers, "If-None-Match": modern.headers["etag"]}) + assert legacy.status_code == 200 + assert not any(event["event"] == "model_request" for event in legacy.json()["events"]) release_close.set() end = await receive_until(lambda event: event.get("event") == "turn_end") assert end.get("turn_id") == "goal-e2e" diff --git a/webui/browser/history-boundary.spec.ts b/webui/browser/history-boundary.spec.ts index 6957972cc..2f5aa9cf3 100644 --- a/webui/browser/history-boundary.spec.ts +++ b/webui/browser/history-boundary.spec.ts @@ -714,7 +714,10 @@ for (const elapsedMs of [0, 80]) test(`fast responses reclaim completed slots an expect(nextHeld.anchorTop - atNewHead.anchorTop).toBeCloseTo(48, 0); await completePrepend(history, body, "Question 16", "Question 28", nextHeld.anchorTop); await expect(body.locator(".thread-history-slot")).toHaveCount(0); - expect(history.reads).toEqual(["?limit=120&before=40", "?limit=120&before=28"]); + expect(history.reads).toEqual([ + "?limit=120&before=40&include_model_requests=1", + "?limit=120&before=28&include_model_requests=1", + ]); }); test("ordinary middle reading never reveals an exhausted overlay, even when the complete beginning is cached", async ({ page }) => { @@ -920,7 +923,12 @@ test("navigation-window loading and errors remain visible and retry uses the nav expect(Math.abs(navigationSpacing.boundaryGap! - navigationSpacing.referenceGap!)).toBeLessThan(1); await positionAtTop(body); await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0); - expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&after=50", "?limit=24&before=38", "?limit=24&before=38"]); + expect(history.reads).toEqual([ + "?limit=24&after=38&include_model_requests=1", + "?limit=24&after=50&include_model_requests=1", + "?limit=24&before=38&include_model_requests=1", + "?limit=24&before=38&include_model_requests=1", + ]); }); async function jumpViaRail(page: Page, index: number) { @@ -963,7 +971,10 @@ test("failed Blocks animate without visible error text; pulling retries once and await expect.poll(() => displacement(body)).toBe(0); expect((await historyGeometry(body, "Question 40")).slotBeforeKey).toBe("u40"); await expectCoordinates(body, "Question 40", held); - expect(history.reads).toEqual(["?limit=120&before=40", "?limit=120&before=40"]); + expect(history.reads).toEqual([ + "?limit=120&before=40&include_model_requests=1", + "?limit=120&before=40&include_model_requests=1", + ]); history.complete(); await expect(body.getByText("Question 28", { exact: true })).toBeAttached(); @@ -1003,7 +1014,11 @@ test("cross-path unloaded rail jump has visible navigation feedback outside a sc await retry.click(); await expect.poll(() => history.reads.length).toBe(3); await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport(); - expect(history.reads).toEqual(["?limit=120&before=40", "?limit=24&after=10", "?limit=24&after=10"]); + expect(history.reads).toEqual([ + "?limit=120&before=40&include_model_requests=1", + "?limit=24&after=10&include_model_requests=1", + "?limit=24&after=10&include_model_requests=1", + ]); history.complete(); await expect(body.getByText("Question 10", { exact: true })).toBeInViewport(); await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0); @@ -1044,7 +1059,12 @@ test("cross-path newer has visible navigation feedback and forward input retries await page.mouse.wheel(0, 120); await expect.poll(() => history.reads.length).toBe(4); await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport(); - expect(history.reads).toEqual(["?limit=24&after=10", "?limit=24&before=10", "?limit=24&after=22", "?limit=24&after=22"]); + expect(history.reads).toEqual([ + "?limit=24&after=10&include_model_requests=1", + "?limit=24&before=10&include_model_requests=1", + "?limit=24&after=22&include_model_requests=1", + "?limit=24&after=22&include_model_requests=1", + ]); history.complete(); await expect(body.getByText("Question 33", { exact: true })).toBeAttached(); await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0); @@ -1088,7 +1108,10 @@ test("cross-path older errors never float after latest or a loaded rail jump, bu expect(history.reads).toHaveLength(initialReads + 1); await retry.click(); await expect.poll(() => history.reads.length).toBe(initialReads + 2); - expect(history.reads.slice(initialReads)).toEqual(["?limit=120&before=40", "?limit=120&before=40"]); + expect(history.reads.slice(initialReads)).toEqual([ + "?limit=120&before=40&include_model_requests=1", + "?limit=120&before=40&include_model_requests=1", + ]); history.complete(); await expect(body.getByText("Question 28", { exact: true })).toBeAttached(); await expect(body.locator(".thread-history-slot")).toHaveCount(0); @@ -1178,7 +1201,11 @@ test("bounded navigation retains three pages and reclaims each completed wheel o await expect(slot).toHaveCount(0); await expectAnchorCoordinate(body, "Question 26", secondHeld.anchorTop); expect((await historyGeometry(body, "Question 26")).slotBeforeKey).toBeNull(); - expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26"]); + expect(history.reads).toEqual([ + "?limit=24&after=38&include_model_requests=1", + "?limit=24&before=38&include_model_requests=1", + "?limit=24&before=26&include_model_requests=1", + ]); const atNewHead = await approachNextHead("Question 14"); expect(atNewHead.firstKey).toBe("u14"); @@ -1201,7 +1228,12 @@ test("bounded navigation retains three pages and reclaims each completed wheel o await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(36); await expect(header).toHaveCount(0); await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0); - expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14"]); + expect(history.reads).toEqual([ + "?limit=24&after=38&include_model_requests=1", + "?limit=24&before=38&include_model_requests=1", + "?limit=24&before=26&include_model_requests=1", + "?limit=24&before=14&include_model_requests=1", + ]); const atKeyboardHead = await approachNextHead("Question 2"); expect(atKeyboardHead.firstKey).toBe("u2"); @@ -1228,7 +1260,13 @@ test("bounded navigation retains three pages and reclaims each completed wheel o await expect(body.getByText("Question 25", { exact: true })).toBeAttached(); await expect(body.getByText("Question 26", { exact: true })).toHaveCount(0); await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(26); - expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14", "?limit=24&before=2"]); + expect(history.reads).toEqual([ + "?limit=24&after=38&include_model_requests=1", + "?limit=24&before=38&include_model_requests=1", + "?limit=24&before=26&include_model_requests=1", + "?limit=24&before=14&include_model_requests=1", + "?limit=24&before=2&include_model_requests=1", + ]); }); diff --git a/webui/browser/prompt-rail.spec.ts b/webui/browser/prompt-rail.spec.ts index d723d1996..2d11bb04e 100644 --- a/webui/browser/prompt-rail.spec.ts +++ b/webui/browser/prompt-rail.spec.ts @@ -52,20 +52,22 @@ test("complete rail scrolls independently, jumps to unloaded history and returns await expect(first).toBeFocused(); await first.press("Enter"); await expect(body.getByText("Question 0", { exact: true })).toBeInViewport(); - expect(reads).toEqual(["?limit=24&after=0"]); + expect(reads).toEqual(["?limit=24&after=0&include_model_requests=1"]); await expect(body.getByText("Question 1999", { exact: true })).toHaveCount(0); // Force input-before-scroll ordering instead of relying on compositor timing. await body.evaluate((node) => node.addEventListener("wheel", () => undefined, { passive: false })); for (const after of [10, 20, 30, 40]) { await body.hover(); await page.mouse.wheel(0, 10000); - await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}`)).toBe(true); + await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}&include_model_requests=1`)).toBe(true); await expect(body.getByText(`Question ${after + 9}`, { exact: true })).toBeAttached(); } expect(await body.locator("[data-user-prompt-id]").count()).toBeLessThanOrEqual(30); await body.hover(); await page.mouse.wheel(0, -100000); - await expect.poll(() => reads.some((query) => query.startsWith("?limit=24&before="))).toBe(true); + await expect.poll(() => reads.some((query) => ( + query.startsWith("?limit=24&before=") && query.endsWith("&include_model_requests=1") + ))).toBe(true); await page.getByRole("button", { name: "Scroll to bottom" }).click(); await expect(body.getByText("Question 1999", { exact: true })).toBeVisible(); await expect(rail.locator('[aria-current="location"]')).toBeInViewport(); diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx index 01759f667..65014aaea 100644 --- a/webui/src/components/thread/ThreadShell.tsx +++ b/webui/src/components/thread/ThreadShell.tsx @@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr import type { PointerEvent as ReactPointerEvent, ReactNode } from "react"; import { createPortal } from "react-dom"; import { useTranslation } from "react-i18next"; +import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request"; import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext"; import { FilePreviewPanel } from "@/components/FilePreviewPanel"; @@ -77,18 +78,15 @@ import { providerDisplayLabel } from "@/lib/provider-brand"; import { cn } from "@/lib/utils"; import { useClient } from "@/providers/ClientProvider"; -function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage | null { +function latestComposerContextUsage(messages: ComposerUsageSnapshot[]): ComposerContextUsage | null { for (let index = messages.length - 1; index >= 0; index -= 1) { const message = messages[index]; - if (message.kind === "compaction" && message.compaction?.phase === "succeeded") { + if (message.compacted) { return null; } const contextTokens = message.usage?.context_tokens; if ( - message.role !== "assistant" - || message.kind === "trace" - || message.isStreaming - || typeof contextTokens !== "number" + typeof contextTokens !== "number" || !Number.isFinite(contextTokens) || contextTokens < 0 ) { @@ -104,23 +102,19 @@ function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage return null; } -function recentComposerRoundUsage(messages: UIMessage[]): ComposerRoundUsage[] { +function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRoundUsage[] { const recent: ComposerRoundUsage[] = []; const seenTurns = new Set(); for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) { const message = messages[index]; const turnKey = message.turnId || message.id; - if ( - message.role !== "assistant" - || message.kind === "trace" - || message.isStreaming - || seenTurns.has(turnKey) - ) { + if (seenTurns.has(turnKey)) { continue; } - seenTurns.add(turnKey); const rounds: RoundUsage[] = message.roundUsages ?? []; + if (!rounds.length) continue; + seenTurns.add(turnKey); for (let roundIndex = rounds.length - 1; roundIndex >= 0; roundIndex -= 1) { const round = rounds[roundIndex]; const inputTokens = round.prompt_tokens; @@ -589,6 +583,7 @@ export function ThreadShell({ }, [chatId, onTurnEnd]); const { messages, + modelRequests, messagesKey, messagesReady, isStreaming, @@ -700,13 +695,14 @@ export function ThreadShell({ useEffect(() => { if (hasAppMentions) requestMentionCatalogs(); }, [hasAppMentions, requestMentionCatalogs]); + const usageSnapshots = useMemo(() => composerUsageSnapshots(messages, modelRequests), [messages, modelRequests]); const composerContextUsage = useMemo( - () => latestComposerContextUsage(displayMessages), - [displayMessages], + () => latestComposerContextUsage(usageSnapshots), + [usageSnapshots], ); const composerRoundUsage = useMemo( - () => recentComposerRoundUsage(displayMessages), - [displayMessages], + () => recentComposerRoundUsage(usageSnapshots), + [usageSnapshots], ); const currentGoalState = messagesReady ? goalState : undefined; // Recovery decisions gate queued input, not the ledger-owned run state. diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts index 19c3dd045..7c3b55fa4 100644 --- a/webui/src/hooks/useNanobotStream.ts +++ b/webui/src/hooks/useNanobotStream.ts @@ -36,6 +36,7 @@ import type { RetryStatus, UIMediaAttachment, UIMessage, + UIModelRequestSnapshot, WorkspaceScopePayload, } from "@/lib/types"; @@ -147,6 +148,7 @@ export function useNanobotStream( historyActiveTurnId: string | null = null, ): { messages: UIMessage[]; + modelRequests: ReadonlyMap; /** Conversation owning these messages, including while a selection is handing over. */ messagesKey: string | null; /** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */ @@ -197,6 +199,7 @@ export function useNanobotStream( historyRunGenerationRef.current = { chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 }; } const [messages, setRenderedMessages] = useState(initialTranscript.messages); + const [modelRequests, setModelRequests] = useState(initialTranscript.modelRequests); const messagesRef = useRef(messages); // Keep received state ahead of React's batched render: navigation can unmount // this hook after a stream flush but before the queued render commits. @@ -205,6 +208,7 @@ export function useNanobotStream( messagesRef.current = next; transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: next }; setRenderedMessages(next); + setModelRequests(transcriptRef.current.modelRequests); setHistoryState(transcriptRef.current.paging); }, []); const [messageScope, setMessageScope] = useState({ chatId, historyKey, client }); @@ -717,6 +721,11 @@ export function useNanobotStream( }); return; } + if (ev.event === "model_request") { + flushPendingStreamEvents(); + applyProjectionEvent(ev); + return; + } const sideChannelEvent = isSideChannelEvent(ev); if (ev.event === "context_compaction") { flushPendingStreamEvents(); @@ -1042,8 +1051,11 @@ export function useNanobotStream( flushPendingStreamEvents(); setRetryStatus(null); setMessages((prev) => { - const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); - transcriptRef.current.projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled); + const settled = prev.map((m) => ({ ...m, isStreaming: false })); + const projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled); + const modelRequests = new Map(projection.modelRequests); + for (const [turn, snapshot] of modelRequests) modelRequests.set(turn, { ...snapshot, ended: true }); + transcriptRef.current.projection = { ...projection, modelRequests }; return settled; }); client.finishRunLocally(chatId); @@ -1075,6 +1087,7 @@ export function useNanobotStream( return { messages, + modelRequests, messagesKey: messageScope.historyKey ?? messageScope.chatId, messagesReady: messageScope.chatId === chatId && messageScope.historyKey === historyKey && messageScope.client === client, isStreaming, diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index 0950027a6..81733d681 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -387,6 +387,19 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent { || !isCompactionPhase(value.phase) || (value.reason !== undefined && !isCompactionReason(value.reason))) break; return value as unknown as ThreadProjectionEvent; + case "model_request": { + const isUsage = (usage: unknown) => isRecord(usage) + && Object.values(usage).every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0); + if (typeof value.request_id !== "string" || !value.request_id + || typeof value.run_id !== "string" || !value.run_id + || !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0 + || !["started", "completed", "failed", "cancelled"].includes(String(value.phase)) + || (value.usage !== undefined && !isUsage(value.usage)) + || (value.round_usages !== undefined && (!Array.isArray(value.round_usages) || !value.round_usages.every(isUsage))) + || (value.context_window_tokens !== undefined && (typeof value.context_window_tokens !== "number" + || !Number.isFinite(value.context_window_tokens) || value.context_window_tokens < 0))) break; + return value as unknown as ThreadProjectionEvent; + } case "turn_end": return value as unknown as ThreadProjectionEvent; } @@ -436,6 +449,7 @@ export async function fetchWebuiThread( if (options?.direction) params.set("direction", options.direction); if (options?.before) params.set("before", options.before); if (options?.after) params.set("after", options.after); + params.set("include_model_requests", "1"); const query = params.toString(); const suffix = query ? `?${query}` : ""; const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`; diff --git a/webui/src/lib/model-request.ts b/webui/src/lib/model-request.ts new file mode 100644 index 000000000..7c39c99a1 --- /dev/null +++ b/webui/src/lib/model-request.ts @@ -0,0 +1,72 @@ +import type { UIMessage, UIModelRequestSnapshot } from "@/lib/types"; + +export type ComposerUsageSnapshot = Pick & { compacted?: boolean }; + +export function reconcileModelRequest( + current: UIModelRequestSnapshot | undefined, + incoming: UIModelRequestSnapshot, +): UIModelRequestSnapshot { + if (!current) return incoming; + if ((current.ended && !incoming.ended) || current.retiredRunIds.includes(incoming.runId)) return current; + if (current.turnSeq !== undefined && incoming.turnSeq !== undefined) { + if (incoming.turnSeq < current.turnSeq + || (incoming.turnSeq === current.turnSeq && !(incoming.ended && !current.ended))) return current; + } else if (current.runId === incoming.runId) { + if (incoming.sequence < current.sequence + || (incoming.sequence === current.sequence && !(incoming.ended && !current.ended))) return current; + } else if (!incoming.retiredRunIds.includes(current.runId)) return current; + return { ...incoming, retiredRunIds: Array.from(new Set([ + ...current.retiredRunIds, ...incoming.retiredRunIds, + ...(current.runId !== incoming.runId ? [current.runId] : []), + ])) }; +} + +/** Select one authoritative usage snapshot per turn, independent of text rows. */ +export function composerUsageSnapshots( + messages: UIMessage[], + snapshots: ReadonlyMap, +): ComposerUsageSnapshot[] { + const lastRows = new Map(); + const compactions = new Map(); + messages.forEach((row, index) => { + if (!row.turnId) return; + lastRows.set(row.turnId, index); + if (row.kind === "compaction" && row.compaction?.phase === "succeeded") { + compactions.set(row.turnId, row.compaction.turnSeq); + } + }); + const rows = messages.flatMap((row, index): ComposerUsageSnapshot[] => { + const snapshot = row.turnId ? snapshots.get(row.turnId) : undefined; + if (snapshot) { + if (lastRows.get(row.turnId!) !== index) return []; + const compactionSeq = compactions.get(row.turnId!); + const compacted = compactions.has(row.turnId!) && !(snapshot.usageTurnSeq !== undefined + && compactionSeq !== undefined && snapshot.usageTurnSeq > compactionSeq); + return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted, + completedAt: snapshot.completedAt ?? row.completedAt, usage: snapshot.usage, + roundUsages: snapshot.roundUsages, contextWindowTokens: snapshot.contextWindowTokens }]; + } + if (row.kind === "compaction" && row.compaction?.phase === "succeeded") { + return [{ id: row.id, createdAt: row.createdAt, compacted: true }]; + } + if (row.role !== "assistant" || row.kind === "trace" || row.isStreaming) return []; + return [row]; + }); + // Proactive requests can precede any body. They need usage, not placeholder rows. + const unanchored = Array.from(snapshots, ([turnId, snapshot]) => ({ + id: `model-request:${turnId}`, turnId, ...snapshot, + })).filter((snapshot) => !lastRows.has(snapshot.turnId)) + .sort((left, right) => left.createdAt - right.createdAt); + if (!unanchored.length) return rows; + const result: ComposerUsageSnapshot[] = []; + let index = 0; + for (const row of rows) { + while (index < unanchored.length && unanchored[index].createdAt <= row.createdAt) { + result.push(unanchored[index++]); + } + result.push(row); + } + return [...result, ...unanchored.slice(index)]; +} diff --git a/webui/src/lib/thread-checkpoint.ts b/webui/src/lib/thread-checkpoint.ts index c9da505d2..b8a95bece 100644 --- a/webui/src/lib/thread-checkpoint.ts +++ b/webui/src/lib/thread-checkpoint.ts @@ -19,6 +19,7 @@ export function copyThreadCheckpoint( projection: { ...checkpoint.projection, messages, + modelRequests: new Map(checkpoint.projection.modelRequests), closedAssistantIds: new Set(checkpoint.projection.closedAssistantIds), closedAnswerStreamIds: new Set(checkpoint.projection.closedAnswerStreamIds), closedTurnIds: new Set(checkpoint.projection.closedTurnIds), diff --git a/webui/src/lib/thread-event-projection.ts b/webui/src/lib/thread-event-projection.ts index 70361c9b3..6c65fe53f 100644 --- a/webui/src/lib/thread-event-projection.ts +++ b/webui/src/lib/thread-event-projection.ts @@ -10,6 +10,7 @@ import type { ToolProgressEvent, UIFileEdit, UIMessage, + UIModelRequestSnapshot, UITurnPhase, } from "@/lib/types"; @@ -21,6 +22,7 @@ const FILE_EDIT_TOOL_NAMES = new Set(["write_file", "edit_file", "apply_patch"]) export interface ThreadProjectionState { messages: UIMessage[]; + modelRequests: ReadonlyMap; activeAssistantId: string | null; closedAssistantIds: Set; /** Completed wire identities also fence late deltas for textless ends. */ @@ -399,6 +401,7 @@ export function createThreadProjectionState( ): ThreadProjectionState { return { messages, + modelRequests: new Map(), activeAssistantId: null, closedAssistantIds: new Set(), closedAnswerStreamIds: new Set(), @@ -418,6 +421,7 @@ export function resetThreadProjectionCursor( ): ThreadProjectionState { return { ...createThreadProjectionState(messages), + modelRequests: state.modelRequests, activitySegmentCounter: state.activitySegmentCounter, closedTurnIds: new Set(state.closedTurnIds), turnAliases: new Map(state.turnAliases), @@ -727,9 +731,9 @@ function projectToolActivity( : event.text ? [event.text] : []; - if (lines.length === 0) return; - const deferredDetail = event.trace_detail; + if (lines.length === 0 && !deferredDetail) return; + const segmentId = ensureProjectionActivitySegment(state); const turn = turnFieldsForProjection(state, event, "activity"); const last = state.messages[state.messages.length - 1]; @@ -780,7 +784,7 @@ function projectToolActivity( id, role: "tool", kind: "trace", - content: lines[lines.length - 1], + content: lines[lines.length - 1] ?? "", traces: lines, ...(visibleEvents.length ? { toolEvents: visibleEvents } : {}), ...(deferredDetail ? { traceDetail: deferredDetail } : {}), @@ -857,6 +861,35 @@ export function projectThreadEvent( turnAliases: new Map(previous.turnAliases), }; + if (event.event === "model_request") { + if (!event.turn_id || state.closedTurnIds.has(event.turn_id)) return state; + const previousRequest = state.modelRequests.get(event.turn_id); + if (previousRequest?.ended + || previousRequest?.retiredRunIds.includes(event.run_id) + || (previousRequest?.runId === event.run_id && event.sequence <= previousRequest.sequence) + || (previousRequest?.turnSeq !== undefined && event.turn_seq !== undefined + && event.turn_seq <= previousRequest.turnSeq)) return state; + const modelRequest: UIModelRequestSnapshot = { + ...previousRequest, + createdAt: previousRequest?.createdAt ?? projectionCreatedAt(event, options), + runId: event.run_id, + sequence: event.sequence, + turnSeq: event.turn_seq, + ...((event.phase === "completed" || event.phase === "failed") + && (event.usage?.request_count ?? 0) > ( + previousRequest?.runId === event.run_id ? previousRequest.usage?.request_count ?? 0 : 0 + ) ? { usageTurnSeq: event.turn_seq } : {}), + retiredRunIds: previousRequest && previousRequest.runId !== event.run_id + ? [...previousRequest.retiredRunIds, previousRequest.runId] + : previousRequest?.retiredRunIds ?? [], + ...(event.usage !== undefined ? { usage: event.usage } : {}), + ...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}), + ...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}), + }; + state.modelRequests = new Map(state.modelRequests).set(event.turn_id, modelRequest); + return state; + } + if (event.event === "user_message") { if (event.provenance?.session_message) { const messageId = event.provenance.session_message.message_id?.trim(); @@ -1002,6 +1035,7 @@ export function projectThreadEvent( compaction: { id: event.compaction_id, phase: event.phase, + turnSeq: event.turn_seq, reason: event.reason, ...(!options.persisted ? { announce: true } : {}), }, @@ -1089,6 +1123,18 @@ export function projectThreadEvent( state.activitySegmentId = null; state.fileEditSegmentId = null; state.messages = finalizeStreamedTurn(state.messages); + const modelRequests = new Map(state.modelRequests); + for (const [turnId, snapshot] of modelRequests) { + if (turn.turnId && turnId !== turn.turnId) continue; + modelRequests.set(turnId, { ...snapshot, ended: true, + turnSeq: event.turn_seq ?? snapshot.turnSeq, + ...(!options.persisted ? { completedAt: options.now } : {}), + ...(event.usage !== undefined ? { usage: event.usage } : {}), + ...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}), + ...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}), + }); + } + state.modelRequests = modelRequests; const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0 ? Math.round(event.latency_ms) : undefined; diff --git a/webui/src/lib/thread-transcript.ts b/webui/src/lib/thread-transcript.ts index 741c1dbbc..924b13539 100644 --- a/webui/src/lib/thread-transcript.ts +++ b/webui/src/lib/thread-transcript.ts @@ -6,6 +6,7 @@ import { import { persistedCanonicalRunState } from "./canonical-run-snapshot"; import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "./thread-checkpoint"; import { hasPendingAgentActivity } from "./activity-timeline"; +import { reconcileModelRequest } from "./model-request"; import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "./types"; type Ranges = Array<[number, number]>; @@ -159,6 +160,7 @@ export class ThreadTranscript { } get messages(): UIMessage[] { return this.projection.messages; } + get modelRequests() { return this.projection.modelRequests; } private installUnit(unit: Unit): void { this.order = Math.max(this.order, unit.order + 1); @@ -246,6 +248,11 @@ export class ThreadTranscript { project(event: ThreadProjectionEvent, options: { createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number; }): UIMessage[] { + // Telemetry never contributes body sources, memberships, or admission barriers. + if (event.event === "model_request") { + this.projection = projectThreadEvent(this.projection, event, options); + return this.messages; + } if (!options.persisted && this.represented(event)) return this.messages; if (!event.projection_id && (!event.turn_id || event.turn_seq === undefined)) { event = { ...event, projection_id: options.createId() }; @@ -478,15 +485,19 @@ export class ThreadTranscript { } if (keepSuffix) nextMessages.push(...this.messages.slice(previous) .filter((row) => !replaced.has(this.byRow.get(row.id)!))); + const modelRequests = new Map(this.modelRequests); + for (const [turn, snapshot] of candidate.modelRequests) { + modelRequests.set(turn, reconcileModelRequest(modelRequests.get(turn), snapshot)); + } this.projection = fullyAdopt && read.kind !== "older" - ? { ...candidate.projection, messages: nextMessages, + ? { ...candidate.projection, messages: nextMessages, modelRequests, activitySegmentId: candidate.projection.activitySegmentId ? segments.get(candidate.projection.activitySegmentId) ?? null : null, fileEditSegmentId: candidate.projection.fileEditSegmentId ? segments.get(candidate.projection.fileEditSegmentId) ?? null : null, closedTurnIds: new Set([...this.projection.closedTurnIds, ...candidate.projection.closedTurnIds]), closedAnswerStreamIds: new Set([...this.projection.closedAnswerStreamIds, ...candidate.projection.closedAnswerStreamIds]) } - : { ...this.projection, messages: nextMessages }; + : { ...this.projection, messages: nextMessages, modelRequests }; if (fullyAdopt && read.kind !== "older") { const retained = new Set(prefix.map((row) => row.id)); for (const unit of this.units) if (!Array.from(unit.rows).some((id) => retained.has(id))) replaced.add(unit); @@ -559,6 +570,11 @@ export class ThreadTranscript { .filter((key) => retainedStreams.has(key))); const retainedTurns = new Set(Array.from(this.units).flatMap((unit) => Array.from(unit.members.keys()))); for (const row of nextMessages) if (row.turnId) retainedTurns.add(row.turnId); + for (const [turn, snapshot] of modelRequests) { + if (reset && snapshot.ended && !retainedTurns.has(turn) && !candidate.modelRequests.has(turn)) { + modelRequests.delete(turn); + } else retainedTurns.add(turn); + } const retainedRows = new Set(nextMessages.map((row) => row.id)); const retainedBoundaries = new Set(Array.from(this.units).flatMap((unit) => unit.text .map((text) => JSON.stringify([text.turn, text.phase, text.stream])))); diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.ts index 610502127..59d92b26b 100644 --- a/webui/src/lib/types.ts +++ b/webui/src/lib/types.ts @@ -8,6 +8,8 @@ type Role = "user" | "assistant" | "tool" | "system"; type MessageKind = "message" | "trace" | "compaction"; export interface UIContextCompaction extends ContextCompaction { + /** Lifecycle event sequence, independent of the row's display position. */ + turnSeq?: number; /** Live wire transitions announce; hydrated transcript rows stay silent. */ announce?: boolean; } @@ -180,6 +182,22 @@ export interface UIMessage { deliveryErrorKind?: MessageDeliveryErrorKind; } +/** Turn-owned telemetry, not a transcript row or body-history source. */ +export interface UIModelRequestSnapshot { + runId: string; + sequence: number; + turnSeq?: number; + retiredRunIds: string[]; + createdAt: number; + completedAt?: number; + /** Last turn sequence reporting fresh context usage. */ + usageTurnSeq?: number; + ended?: boolean; + usage?: TurnUsage; + roundUsages?: RoundUsage[]; + contextWindowTokens?: number; +} + export interface UICliAppAttachment { name: string; display_name?: string; @@ -1583,6 +1601,17 @@ export type InboundEvent = fallback?: boolean; reauth_provider?: string; } + | ({ + event: "model_request"; + chat_id: string; + request_id: string; + run_id: string; + sequence: number; + phase: "started" | "completed" | "failed" | "cancelled"; + usage?: TurnUsage; + round_usages?: RoundUsage[]; + context_window_tokens?: number; + } & InboundTurnMetadata) | ({ event: "turn_end"; chat_id: string; @@ -1650,6 +1679,7 @@ export type InboundEvent = }; type ThreadProjectionEventName = + | "model_request" | "user_message" | "message" | "file_edit" diff --git a/webui/src/tests/agent-activity-cluster.test.tsx b/webui/src/tests/agent-activity-cluster.test.tsx index 1ab1a3794..ccb938595 100644 --- a/webui/src/tests/agent-activity-cluster.test.tsx +++ b/webui/src/tests/agent-activity-cluster.test.tsx @@ -185,7 +185,7 @@ describe("AgentActivityCluster", () => { .toHaveAttribute("aria-label", `${path} 編集`); }); - it("loads deferred trace details only after completed activity is expanded", async () => { + it.each(["exec(…)", ""])("loads deferred trace details only after completed activity is expanded (summary=%s)", async (summary) => { const onLoadTraceDetails = vi.fn(); render( { id: "t-deferred", role: "tool", kind: "trace", - content: "exec(…)", - traces: ["exec(…)"], + content: summary, + traces: summary ? [summary] : [], traceDetail: { ref: "9.tr-deadbeefdeadbeef", bytes: 40_000, diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.ts index 689a0b4ea..9649e8694 100644 --- a/webui/src/tests/api.test.ts +++ b/webui/src/tests/api.test.ts @@ -32,6 +32,7 @@ import { fetchSkills, fetchTrendingMarketplaceSkills, fetchWebuiThread, + fetchSubagentThread, fetchWebuiThreadTraceDetail, fetchWorkspaces, importMcpConfig, @@ -97,11 +98,19 @@ describe("webui API helpers", () => { vi.unstubAllGlobals(); }); + it("fetches a subagent thread from its parent session", async () => { + await fetchSubagentThread("tok", "websocket:chat-1", "task-1"); + expect(fetch).toHaveBeenCalledWith( + "/api/sessions/websocket%3Achat-1/subagents/task-1/webui-thread", + expect.objectContaining({ headers: { Authorization: "Bearer tok" } }), + ); + }); + it("percent-encodes websocket keys when fetching webui-thread snapshot", async () => { await fetchWebuiThread("tok", "websocket:chat-1"); expect(fetch).toHaveBeenCalledWith( - "/api/sessions/websocket%3Achat-1/webui-thread", + "/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1", expect.objectContaining({ headers: { Authorization: "Bearer tok" }, credentials: "same-origin", @@ -117,7 +126,7 @@ describe("webui API helpers", () => { }); expect(fetch).toHaveBeenCalledWith( - "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D", + "/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1", expect.objectContaining({ headers: { Authorization: "Bearer tok" }, credentials: "same-origin", @@ -163,7 +172,7 @@ describe("webui API helpers", () => { })).resolves.toBe(cached); expect(fetch).toHaveBeenCalledWith( - "/api/sessions/websocket%3Achat-1/webui-thread", + "/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1", expect.objectContaining({ headers: { Authorization: "Bearer tok", diff --git a/webui/src/tests/latest-thread-request.test.ts b/webui/src/tests/latest-thread-request.test.ts index ed8c07a71..58b803783 100644 --- a/webui/src/tests/latest-thread-request.test.ts +++ b/webui/src/tests/latest-thread-request.test.ts @@ -43,7 +43,7 @@ describe("shared latest thread requests", () => { const surviving = fetchLatestWebuiThread(client, "token", KEY); expect(fetchMock).toHaveBeenCalledTimes(1); expect(fetchMock).toHaveBeenCalledWith( - "/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest", + "/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1", expect.objectContaining({ headers: { Authorization: "Bearer token", "If-None-Match": '"cached"' } }), ); const rejected = expect(first).rejects.toMatchObject({ name: "AbortError" }); diff --git a/webui/src/tests/model-request.test.ts b/webui/src/tests/model-request.test.ts new file mode 100644 index 000000000..bf2552ac0 --- /dev/null +++ b/webui/src/tests/model-request.test.ts @@ -0,0 +1,205 @@ +import { describe, expect, it } from "vitest"; +import { parseWebuiThreadPayload } from "@/lib/api"; +import { composerUsageSnapshots } from "@/lib/model-request"; +import { projectWebuiThreadMessages } from "@/lib/thread-display-projection"; +import { ThreadTranscript } from "@/lib/thread-transcript"; +import type { ThreadProjectionEvent } from "@/lib/types"; + +const envelope = { chat_id: "chat", turn_id: "turn" }; +const request = (sequence: number, extra: Partial> = {}): ThreadProjectionEvent => ({ + ...envelope, event: "model_request", run_id: "run", request_id: `request-${sequence}`, + sequence, turn_seq: sequence, phase: "started", ...extra, +}); +const usage = (count: number) => ({ prompt_tokens: count * 100, completion_tokens: count * 10, + context_tokens: 100 + count, request_count: count }); +const rounds = (count: number) => Array.from({ length: count }, (_, index) => ({ prompt_tokens: 100 + index, completion_tokens: 10 })); +function project(transcript: ThreadTranscript, event: ThreadProjectionEvent, persisted = false) { + return transcript.project(event, { createId: () => `event-${event.turn_seq}`, now: 1, persisted }); +} + +describe("model request snapshots", () => { + it("validates request identity, phase, sequence, and usage at the history boundary", () => { + for (const invalid of [{ phase: "unknown" }, { sequence: -1 }, { run_id: null }, { usage: { context_tokens: "123" } }]) { + expect(() => parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...request(1), ...invalid }] })).toThrow(); + } + expect(parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [] }).events).toEqual([]); + }); + it("updates active usage cumulatively, retains it during the next call, and replaces the final snapshot", () => { + const transcript = new ThreadTranscript(); + const events: ThreadProjectionEvent[] = [{ ...envelope, event: "user_message", text: "hello", starts_turn: true, turn_seq: 0 }]; + project(transcript, events[0]); + for (let count = 1; count <= 3; count++) { + const event = request(count * 2, { phase: "completed", usage: usage(count), round_usages: rounds(count), context_window_tokens: 128000 }); + events.push(event); project(transcript, event); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage?.request_count).toBe(count); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.roundUsages).toHaveLength(count); + } + const started = request(7); + events.push(started); project(transcript, started); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage?.context_tokens).toBe(103); + const answer: ThreadProjectionEvent = { ...envelope, event: "delta", text: "answer", turn_seq: 8 }; + events.push(answer); project(transcript, answer); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests)).toHaveLength(1); + const end: ThreadProjectionEvent = { ...envelope, event: "turn_end", turn_seq: 9, usage: usage(3), round_usages: rounds(3) }; + events.push(end); project(transcript, end); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).flatMap((entry) => entry.roundUsages ?? [])).toHaveLength(3); + const replay = new ThreadTranscript(); + events.forEach((event) => project(replay, event, true)); + expect(composerUsageSnapshots(replay.messages, replay.modelRequests).at(-1)?.usage).toEqual(usage(3)); + project(transcript, request(10, { usage: usage(99) })); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage).toEqual(usage(3)); + }); + + it.each([false, true])("invalidates compacted context until fresh completion (persisted=%s)", (persisted) => { + const transcript = new ThreadTranscript(); + const send = (event: ThreadProjectionEvent) => project(transcript, event, persisted); + const latest = () => composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!; + send(request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) })); + expect(projectWebuiThreadMessages(transcript.messages)).toEqual([]); + send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "started", turn_seq: 2 }); + expect(latest().compacted).toBe(false); + send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 }); + expect(latest().compacted).toBe(true); + expect(latest().roundUsages).toEqual(rounds(1)); + send(request(4, { usage: usage(1), round_usages: rounds(1) })); + expect(latest().compacted).toBe(true); + expect(latest().roundUsages).toEqual(rounds(1)); + expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]); + const smaller = { ...usage(2), context_tokens: 50 }; + send(request(5, { request_id: "request-4", phase: "completed", usage: smaller, round_usages: rounds(2) })); + expect(latest().compacted).toBe(false); + expect(latest().usage?.context_tokens).toBe(50); + send({ ...envelope, event: "turn_end", turn_seq: 6, usage: smaller, round_usages: rounds(2) }); + expect(latest().compacted).toBe(false); + expect(latest().usage?.context_tokens).toBe(50); + expect(latest().roundUsages).toEqual(rounds(2)); + expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]); + }); + + it.each([false, true])("does not treat turn-end cumulative usage as fresh after compaction (persisted=%s)", (persisted) => { + const transcript = new ThreadTranscript(); + for (const event of [ + request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) }), + { ...envelope, event: "context_compaction", compaction_id: "compact", phase: "started", turn_seq: 2 }, + { ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 }, + { ...envelope, event: "turn_end", turn_seq: 4, usage: usage(1), round_usages: rounds(1) }, + ] as ThreadProjectionEvent[]) project(transcript, event, persisted); + const snapshot = composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!; + expect(snapshot.compacted).toBe(true); + expect(snapshot.roundUsages).toEqual(rounds(1)); + }); + + it("preserves legacy compaction invalidation and historical rounds without request events", () => { + const transcript = new ThreadTranscript(); + project(transcript, { ...envelope, event: "delta", text: "answer", turn_seq: 1 }); + project(transcript, { ...envelope, event: "turn_end", usage: usage(1), round_usages: rounds(1), turn_seq: 2 }); + project(transcript, { ...envelope, turn_id: "compact-turn", event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 1 }); + const snapshots = composerUsageSnapshots(transcript.messages, transcript.modelRequests); + expect(snapshots.at(-1)?.compacted).toBe(true); + expect(snapshots.flatMap((row) => row.roundUsages ?? [])).toEqual(rounds(1)); + }); + + it("rejects duplicates, reordered snapshots, and superseded runs after checkpoint restoration", () => { + const transcript = new ThreadTranscript(); + project(transcript, request(2, { usage: usage(2) })); + project(transcript, request(1, { usage: usage(1) })); + project(transcript, request(2, { usage: usage(99) })); + project(transcript, request(1, { run_id: "new-run", turn_seq: 3, usage: usage(3) })); + const restored = new ThreadTranscript([], transcript.save()); + project(restored, request(4, { usage: usage(99) })); + expect(composerUsageSnapshots(restored.messages, restored.modelRequests).at(-1)?.usage).toEqual(usage(3)); + expect(projectWebuiThreadMessages(restored.messages)).toEqual([]); + }); + + it("reconciles reconnect history without replacing newer live usage", () => { + const transcript = new ThreadTranscript(); + const initial = request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) }); + project(transcript, initial); + const read = transcript.begin("latest"); + project(transcript, request(2, { phase: "completed", usage: usage(2), round_usages: rounds(2) })); + expect(transcript.accept({ schemaVersion: 3, projection: "events", events: [initial] }, read)).toBe(true); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage).toEqual(usage(2)); + const fresh = new ThreadTranscript(); + expect(fresh.accept(parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [initial, request(2)] }), fresh.begin("initial"))).toBe(true); + expect(composerUsageSnapshots(fresh.messages, fresh.modelRequests).at(-1)?.roundUsages).toHaveLength(1); + }); + + it("retains proactive usage without body rows across history and clears it with a completed history reset", () => { + const transcript = new ThreadTranscript(); + const events: ThreadProjectionEvent[] = [ + { ...envelope, turn_id: "old", event: "message", text: "Old answer", turn_seq: 1, created_at_ms: 1000 }, + { ...envelope, turn_id: "old", event: "turn_end", turn_seq: 2, usage: usage(1), round_usages: rounds(1) }, + ]; + const body = { schemaVersion: 3 as const, projection: "events" as const, events, completed_turn_ids: ["old"] }; + expect(transcript.accept(body, transcript.begin("initial"))).toBe(true); + const read = transcript.begin("latest"); + project(transcript, request(1, { phase: "completed", created_at_ms: 2000, usage: usage(2), round_usages: rounds(2) })); + expect(transcript.accept(body, read)).toBe(true); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).map((row) => row.usage)).toEqual([usage(1), usage(2)]); + project(transcript, { ...envelope, event: "turn_end", turn_seq: 2, usage: usage(2), round_usages: rounds(2) }); + const restored = new ThreadTranscript([], transcript.save()); + expect(composerUsageSnapshots(restored.messages, restored.modelRequests).at(-1)?.usage).toEqual(usage(2)); + expect(restored.accept({ schemaVersion: 3, projection: "events", events: [] }, restored.begin("latest"))).toBe(true); + expect(composerUsageSnapshots(restored.messages, restored.modelRequests)).toEqual([]); + }); + + it("backfills missed answer and tool history while retaining newer live usage", () => { + const transcript = new ThreadTranscript(); + const user: ThreadProjectionEvent = { ...envelope, event: "user_message", text: "question", starts_turn: true, turn_seq: 0 }; + const initial = request(1); + project(transcript, user); + project(transcript, initial); + const read = transcript.begin("latest"); + const latest = request(3, { turn_seq: 5, phase: "completed", usage: usage(2), round_usages: rounds(2), context_window_tokens: 128000 }); + project(transcript, latest); + const events: ThreadProjectionEvent[] = [user, initial, + request(2, { phase: "completed", usage: usage(1), round_usages: rounds(1) }), + { ...envelope, event: "stream_end", turn_seq: 3, stream_id: "missed-answer", text: "missed answer", resuming: true }, + { ...envelope, event: "message", turn_seq: 4, kind: "tool_hint", text: "", tool_events: [{ + version: 1, name: "read_file", call_id: "missed-tool", phase: "end", + arguments: { path: "example.txt" }, result: "missed tool result", + }] }, + ]; + expect(transcript.accept({ schemaVersion: 3, projection: "events", events, + active_turn_id: "turn", completed_turn_ids: [], has_pending_tool_calls: true }, read)).toBe(true); + expect(transcript.messages.map((row) => row.content)).toContain("missed answer"); + expect(transcript.messages.flatMap((row) => row.toolEvents ?? [])).toMatchObject([ + { call_id: "missed-tool", phase: "end", result: "missed tool result" }, + ]); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({ + usage: usage(2), roundUsages: rounds(2), contextWindowTokens: 128000, + }); + const restored = new ThreadTranscript([], transcript.save()); + const final: ThreadProjectionEvent = { ...envelope, event: "turn_end", turn_seq: 6, + usage: usage(3), round_usages: rounds(3), context_window_tokens: 64000 }; + project(restored, final); + expect(composerUsageSnapshots(restored.messages, restored.modelRequests).at(-1)).toMatchObject({ + usage: usage(3), roundUsages: rounds(3), contextWindowTokens: 64000, + }); + const reloaded = new ThreadTranscript(); + expect(reloaded.accept({ schemaVersion: 3, projection: "events", events: [...events, latest, final], + completed_turn_ids: ["turn"] }, reloaded.begin("initial"))).toBe(true); + expect(composerUsageSnapshots(reloaded.messages, reloaded.modelRequests).at(-1)?.usage).toEqual(usage(3)); + expect(reloaded.messages.map((row) => row.content)).toContain("missed answer"); + }); + + it.each([false, true])("does not treat a missing-usage completion as fresh after compaction (replay=%s)", (persisted) => { + const transcript = new ThreadTranscript(); + project(transcript, request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) }), persisted); + project(transcript, { ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 2 }, persisted); + project(transcript, request(3, { usage: usage(1), round_usages: rounds(1) }), persisted); + project(transcript, request(4, { phase: "completed", usage: usage(1), round_usages: rounds(1) }), persisted); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.compacted).toBe(true); + project(transcript, request(5, { phase: "failed", usage: usage(2), round_usages: rounds(2) }), persisted); + expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.compacted).toBe(false); + }); + + it("keeps active history snapshots and bounds rounds to the latest eight calls", () => { + const replay = new ThreadTranscript(); + project(replay, request(1, { phase: "completed", usage: usage(10), round_usages: rounds(10) }), true); + project(replay, request(2), true); + const snapshot = composerUsageSnapshots(replay.messages, replay.modelRequests).at(-1)!; + expect(snapshot.roundUsages).toHaveLength(8); + expect(snapshot.roundUsages?.[0].prompt_tokens).toBe(102); + }); +}); diff --git a/webui/src/tests/thread-event-projection.test.ts b/webui/src/tests/thread-event-projection.test.ts index 39156b735..f6d792600 100644 --- a/webui/src/tests/thread-event-projection.test.ts +++ b/webui/src/tests/thread-event-projection.test.ts @@ -193,7 +193,7 @@ describe("canonical thread event projection", () => { expect(normalizeProjection(messages)).toEqual(fixtureCase.expected); }); - it("keeps deferred activity rows separately addressable in one segment", () => { + it.each(["read_file(…)", ""])("keeps deferred activity rows separately addressable in one segment (summary=%s)", (summary) => { const firstDetail = { ref: "2.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 }; const secondDetail = { ref: "2.history-bbbbbbbbbbbbbbbbbbbb", bytes: 41_000, traceCount: 1 }; @@ -209,7 +209,7 @@ describe("canonical thread event projection", () => { { event: "message", chat_id: "chat-1", - text: "read_file(…)", + text: summary, kind: "tool_hint", projection_id: "history-bbbbbbbbbbbbbbbbbbbb", trace_detail: secondDetail, @@ -217,6 +217,7 @@ describe("canonical thread event projection", () => { ]); expect(messages).toHaveLength(2); + expect(messages.map((message) => message.content)).toEqual(["exec(…)", summary]); expect(messages.map((message) => message.traceDetail)).toEqual([ firstDetail, secondDetail, diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx index 00bb09b0e..ceb1c0d70 100644 --- a/webui/src/tests/thread-shell.test.tsx +++ b/webui/src/tests/thread-shell.test.tsx @@ -1032,6 +1032,38 @@ describe("ThreadShell", () => { expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(4); }); + it("updates composer usage from active model snapshots without changing the body", async () => { + const client = makeClient(); + const envelope = { chat_id: "live-usage", turn_id: "live-turn" }; + vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => Promise.resolve( + String(input).includes("websocket%3Alive-usage/webui-thread") + ? httpJson({ schemaVersion: 3, projection: "events", active_turn_id: "live-turn", has_pending_tool_calls: true, + events: [{ ...envelope, event: "user_message", text: "Waiting for answer", starts_turn: true, turn_seq: 0 }] }) + : { ok: false, status: 404, json: async () => ({}) }, + ))); + render(wrap(client, {}} + settingsSnapshot={modelSettings("test-model", "deepseek")} + />)); + await screen.findByText("Waiting for answer"); + act(() => client._emitChat("live-usage", { ...envelope, event: "model_request", request_id: "first", run_id: "run", + phase: "completed", sequence: 1, turn_seq: 1, context_window_tokens: 1000, + usage: { prompt_tokens: 100, completion_tokens: 10, context_tokens: 100, request_count: 1 }, + round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }], + })); + const trigger = await screen.findByTestId("composer-context-usage"); + expect(trigger).toHaveAccessibleName("Context 10%. Open context usage"); + act(() => client._emitChat("live-usage", { ...envelope, event: "model_request", request_id: "second", run_id: "run", + phase: "completed", sequence: 2, turn_seq: 2, context_window_tokens: 1000, + usage: { prompt_tokens: 300, completion_tokens: 20, context_tokens: 200, request_count: 2 }, + round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }, { prompt_tokens: 200, completion_tokens: 10 }], + })); + expect(trigger).toHaveAccessibleName("Context 20%. Open context usage"); + fireEvent.click(trigger); + expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(2); + expect(screen.getByText("Waiting for answer")).toBeInTheDocument(); + }); + it.each([false, true])("restores context after compaction only with newer usage (%s)", async (newReply) => { const client = makeClient(); const messages: UIMessage[] = [ diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx index 719c71c01..8bf5e2fc6 100644 --- a/webui/src/tests/useNanobotStream.test.tsx +++ b/webui/src/tests/useNanobotStream.test.tsx @@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { useNanobotStream } from "@/hooks/useNanobotStream"; import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility"; import { normalizeActivityTimeline } from "@/lib/activity-timeline"; +import { composerUsageSnapshots } from "@/lib/model-request"; import { ThreadMessageCache } from "@/lib/thread-message-cache"; import type { NanobotClient, StreamError } from "@/lib/nanobot-client"; import type { @@ -3837,3 +3838,30 @@ describe("live canonical event projection", () => { ]); }); }); + + +it("projects active model usage without ending the turn and ignores late usage after stop", () => { + const fake = fakeClient(); + const { result } = renderHook(() => useNanobotStream("chat-model", EMPTY_MESSAGES), { + wrapper: wrap(fake.client), + }); + const envelope = { chat_id: "chat-model", turn_id: "turn-model" }; + act(() => { + fake.emit("chat-model", { ...envelope, event: "goal_status", status: "running", started_at: 1700 }); + fake.emit("chat-model", { ...envelope, event: "user_message", text: "hello", starts_turn: true, turn_seq: 0 }); + fake.emit("chat-model", { ...envelope, event: "model_request", request_id: "first", run_id: "run", + sequence: 1, turn_seq: 1, phase: "completed", usage: { prompt_tokens: 105000, completion_tokens: 100, + context_tokens: 105000, request_count: 1 }, round_usages: [{ prompt_tokens: 105000, completion_tokens: 100 }] }); + fake.emit("chat-model", { ...envelope, event: "model_request", request_id: "second", run_id: "run", + sequence: 2, turn_seq: 2, phase: "started" }); + }); + expect(result.current.isStreaming).toBe(true); + expect(composerUsageSnapshots(result.current.messages, result.current.modelRequests).at(-1)?.usage?.context_tokens).toBe(105000); + act(() => result.current.stop()); + expect(result.current.isStreaming).toBe(false); + act(() => fake.emit("chat-model", { ...envelope, event: "model_request", request_id: "late", run_id: "run", + sequence: 3, turn_seq: 3, phase: "completed", usage: { prompt_tokens: 999, completion_tokens: 1, + context_tokens: 999, request_count: 2 } })); + expect(result.current.isStreaming).toBe(false); + expect(composerUsageSnapshots(result.current.messages, result.current.modelRequests).at(-1)?.usage?.context_tokens).toBe(105000); +}); diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsx index a1fadbdf7..b10d3bdd4 100644 --- a/webui/src/tests/useReconnectRuns.test.tsx +++ b/webui/src/tests/useReconnectRuns.test.tsx @@ -306,7 +306,7 @@ describe("durable run recovery", () => { await reopen(); expect(fetchMock).toHaveBeenCalledWith( - "/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest", + "/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1", expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }), ); expect(client.getRunStartedAt("inactive")).toBeNull();