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
@@ -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()
|
||||
Reference in new issue
Block a user