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

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