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:
chengyongru authored and GitHub committed 2026-11-04 16:27:24 +08:00
1 parent 006a535537
commit 8ff04aad2b
52 files changed
+2065 -211

No files matched your search

+7
View File
@@ -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()