fix(webui): update usage and tool progress during active turns (#6553)
* fix(webui): stream model status and usage during active turns * fix(webui): keep live rounds and active-run status consistent * fix(webui): reuse existing run indicators without extra status text * fix(webui): preserve live activity and batch durable delivery Cancel and drain sibling tools when progress notifications fail, retain balanced checkpoints, and keep model telemetry separate from answer provenance. Group-commit already queued activity at the channel delivery boundary while preserving FIFO, generation ownership, per-envelope admission, and commit-before-fanout semantics. Isolate invalid members without dropping valid neighboring events. Retain tool detail lazy grouping and cover scheduling, cancellation, persistence, encoding failures, and projection regressions. * test(webui): separate standard-library imports in batch regression * test: tighten live execution checks and clarify contracts * refactor: remove redundant live execution comments * refactor: settle tool results through one output path
This commit is contained in:
1 parent
006a535537
commit
8ff04aad2b
52 files changed
+2065
-211
No files matched your search
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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={}",
|
||||
|
||||
+132
-57
@@ -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,
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"])
|
||||
@@ -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()
|
||||
@@ -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."""
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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",
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -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=" ")
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
+58
-11
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user