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
@@ -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