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
@@ -43,6 +43,7 @@ def _make_loop(tmp_path):
|
||||
async def test_process_direct_websocket_clears_run_status(tmp_path) -> None:
|
||||
loop = _make_loop(tmp_path)
|
||||
gateway = MagicMock()
|
||||
gateway.transcripts.prepare_and_append = AsyncMock(return_value=True)
|
||||
channel = WebSocketChannel(
|
||||
{"enabled": True, "allowFrom": ["*"]},
|
||||
loop.bus,
|
||||
|
||||
@@ -13,7 +13,7 @@ from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import StreamedResponseEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import RetryStatusEvent
|
||||
from nanobot.events import ModelRequestEvent, RetryStatusEvent
|
||||
from nanobot.goal.assembly import install_goal
|
||||
from nanobot.providers.base import (
|
||||
GenerationSettings,
|
||||
@@ -92,11 +92,14 @@ async def test_loop_uses_structured_retry_status_without_legacy_text(tmp_path):
|
||||
|
||||
assert result is not None
|
||||
assert captured["provider_context"].events.accepts(RetryStatusEvent)
|
||||
assert bus.outbound_size == 1
|
||||
outbound = bus.outbound.get_nowait()
|
||||
assert isinstance(outbound.event, RetryStatusEvent)
|
||||
assert outbound.event.state == "waiting"
|
||||
assert outbound.chat_id == "chat-a"
|
||||
outbound = [bus.outbound.get_nowait() for _ in range(bus.outbound_size)]
|
||||
assert [type(message.event) for message in outbound] == [
|
||||
ModelRequestEvent, RetryStatusEvent, ModelRequestEvent,
|
||||
]
|
||||
retry = outbound[1].event
|
||||
assert isinstance(retry, RetryStatusEvent)
|
||||
assert retry.state == "waiting"
|
||||
assert all(message.chat_id == "chat-a" for message in outbound)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -790,13 +790,16 @@ async def test_resource_prompt_results_keep_runtime_classification(case):
|
||||
assert direct == (with_tool_error_hint(expected) if failed else expected)
|
||||
|
||||
hook = _RecordingToolHook()
|
||||
outputs, events = await execute_tool_calls(
|
||||
settled = []
|
||||
await execute_tool_calls(
|
||||
registry, [call], concurrent=False, external_lookup_counts={},
|
||||
workspace_violation_counts={}, hook=hook,
|
||||
context=AgentHookContext(iteration=0, messages=[]),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
assert events[0]["status"] == ("error" if failed else "ok")
|
||||
assert expected in outputs[0]
|
||||
[completed] = settled
|
||||
assert completed.event["status"] == ("error" if failed else "ok")
|
||||
assert expected in completed.result
|
||||
assert hook.errors == ([expected] if failed else [])
|
||||
assert hook.successes == ([] if failed else [expected])
|
||||
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.hook import AgentHookContext
|
||||
from nanobot.agent.progress_hook import AgentProgressHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
from nanobot.agent.tools.execution import execute_tool_calls
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest
|
||||
|
||||
|
||||
def spec(provider, sink, **kwargs):
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
return make_run_spec(
|
||||
provider, initial_messages=[{"role": "user", "content": "hi"}],
|
||||
tools=tools, model="test-model", max_iterations=2,
|
||||
max_tool_result_chars=10000, events=sink, **kwargs,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_requests_arrive_before_runner_finishes_and_cancel_is_terminal():
|
||||
events = []
|
||||
entered = asyncio.Event()
|
||||
block = asyncio.Event()
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
async def provider_call(**kwargs):
|
||||
entered.set()
|
||||
await block.wait()
|
||||
return LLMResponse(content="done")
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = provider_call
|
||||
task = asyncio.create_task(AgentRunner().run(spec(provider, EventSink(publish))))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
assert not task.done()
|
||||
assert [e.phase for e in events if isinstance(e, ModelRequestEvent)] == ["started"]
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.phase for e in requests] == ["started", "cancelled"]
|
||||
assert requests[0].request_id == requests[1].request_id
|
||||
assert [e.sequence for e in requests] == [1, 2]
|
||||
assert requests[1].usage is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completed_request_usage_is_visible_while_tool_is_blocked():
|
||||
events = []
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
usage = LLMUsage.reported(input_tokens=12, output_tokens=3)
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
async def tool_call(*args):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return "ok"
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})], usage=usage),
|
||||
LLMResponse(content="done", usage=usage),
|
||||
])
|
||||
run_spec = spec(provider, EventSink(publish))
|
||||
run_spec.tools.prepare_call.return_value = (None, {}, None)
|
||||
run_spec.tools.execute = tool_call
|
||||
task = asyncio.create_task(AgentRunner().run(run_spec))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
assert not task.done()
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.phase for e in requests] == ["started", "completed"]
|
||||
assert requests[-1].usage == usage
|
||||
assert requests[-1].round_usages == (usage,)
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.sequence for e in requests] == [1, 2, 3, 4]
|
||||
assert len({e.run_id for e in requests}) == 1
|
||||
assert requests[0].request_id != requests[2].request_id
|
||||
assert requests[-1].usage == usage + usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_round_usage_folds_recovery_before_tool_finishes():
|
||||
events = []
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
usages = [LLMUsage.reported(input_tokens=value, output_tokens=1) for value in (10, 20, 30)]
|
||||
|
||||
async def publish(event):
|
||||
if isinstance(event, ModelRequestEvent):
|
||||
events.append(event)
|
||||
|
||||
async def tool_call(*args):
|
||||
entered.set()
|
||||
await release.wait()
|
||||
return "ok"
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest("bad", "", {})],
|
||||
finish_reason="tool_calls", usage=usages[0]),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest("c", "tool", {})],
|
||||
finish_reason="tool_calls", usage=usages[1]),
|
||||
LLMResponse(content="done", usage=usages[2]),
|
||||
])
|
||||
run_spec = spec(provider, EventSink(publish))
|
||||
run_spec.tools.prepare_call.return_value = (None, {}, None)
|
||||
run_spec.tools.execute = tool_call
|
||||
task = asyncio.create_task(AgentRunner().run(run_spec))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
assert not task.done()
|
||||
completed = [event for event in events if event.phase == "completed"]
|
||||
assert completed[0].round_usages == (usages[0],)
|
||||
assert completed[-1].round_usages == (usages[0] + usages[1],)
|
||||
assert completed[-1].usage == usages[0] + usages[1]
|
||||
finally:
|
||||
release.set()
|
||||
result = await task
|
||||
assert events[-1].round_usages == tuple(result.round_usages)
|
||||
assert events[-1].usage == result.usage
|
||||
assert [usage.input_tokens for usage in result.round_usages] == [30, 30]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_individual_tool_finishes_before_blocked_sibling():
|
||||
emitted = []
|
||||
settled = []
|
||||
fast_finished = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
tools = MagicMock()
|
||||
tools.prepare_call.return_value = (None, {}, None)
|
||||
|
||||
async def execute(name, args):
|
||||
if name == "slow":
|
||||
await release.wait()
|
||||
return name
|
||||
|
||||
tools.execute = execute
|
||||
|
||||
async def publish(event):
|
||||
emitted.extend(event.tool_events or [])
|
||||
if any(e["call_id"] == "fast" and e["phase"] == "end" for e in event.tool_events or []):
|
||||
fast_finished.set()
|
||||
|
||||
task = asyncio.create_task(execute_tool_calls(
|
||||
tools, [ToolCallRequest("slow", "slow", {}), ToolCallRequest("fast", "fast", {})],
|
||||
concurrent=True, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentProgressHook(EventSink(publish)), context=AgentHookContext(0, []),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
))
|
||||
try:
|
||||
await asyncio.wait_for(fast_finished.wait(), 2)
|
||||
assert not task.done()
|
||||
assert not any(e["call_id"] == "slow" and e["phase"] == "end" for e in emitted)
|
||||
finally:
|
||||
release.set()
|
||||
await task
|
||||
assert [completed.result for completed in settled] == ["slow", "fast"]
|
||||
assert [(e["call_id"], e["phase"]) for e in emitted].count(("fast", "end")) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_snapshots_bound_rounds_without_losing_cumulative_usage():
|
||||
events = []
|
||||
usage = LLMUsage.reported(input_tokens=12, output_tokens=3)
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
*[LLMResponse(content=None, tool_calls=[ToolCallRequest(str(i), "tool", {})], usage=usage)
|
||||
for i in range(9)],
|
||||
LLMResponse(content="done", usage=usage),
|
||||
])
|
||||
run_spec = spec(provider, EventSink(publish))
|
||||
run_spec.max_iterations = 10
|
||||
run_spec.tools.prepare_call.return_value = (None, {}, None)
|
||||
run_spec.tools.execute = AsyncMock(return_value="ok")
|
||||
result = await AgentRunner().run(run_spec)
|
||||
completed = [e for e in events if isinstance(e, ModelRequestEvent) and e.phase == "completed"]
|
||||
assert len(completed) == 10
|
||||
assert len(completed[-1].round_usages) == 8
|
||||
assert completed[-1].usage == result.usage
|
||||
assert len(result.round_usages) == 10
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("response", [LLMResponse(content="error", finish_reason="error"), RuntimeError("failure")])
|
||||
async def test_request_failure_has_one_terminal_event(response):
|
||||
events = []
|
||||
|
||||
async def publish(event):
|
||||
events.append(event)
|
||||
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[response])
|
||||
expected = pytest.raises(RuntimeError, match="failure") if isinstance(response, RuntimeError) else nullcontext()
|
||||
with expected:
|
||||
await AgentRunner().run(spec(provider, EventSink(publish)))
|
||||
requests = [e for e in events if isinstance(e, ModelRequestEvent)]
|
||||
assert [e.phase for e in requests] == ["started", "failed"]
|
||||
assert requests[-1].usage is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_cancellation_closes_started_call_without_masking_cancel():
|
||||
emitted = []
|
||||
entered = asyncio.Event()
|
||||
tools = MagicMock()
|
||||
tools.prepare_call.return_value = (None, {}, None)
|
||||
|
||||
async def execute(*args):
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
tools.execute = execute
|
||||
|
||||
async def publish(event):
|
||||
emitted.extend(event.tool_events or [])
|
||||
if event.tool_events and event.tool_events[0]["phase"] == "error":
|
||||
raise RuntimeError("notification failure must not replace cancellation")
|
||||
|
||||
task = asyncio.create_task(execute_tool_calls(
|
||||
tools, [ToolCallRequest("blocked", "blocked", {})], concurrent=False,
|
||||
external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentProgressHook(EventSink(publish)), context=AgentHookContext(0, []),
|
||||
))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert [event["phase"] for event in emitted] == ["start", "error"]
|
||||
|
||||
|
||||
def test_model_requests_are_optional_for_non_webui_channels():
|
||||
from nanobot.bus.notification_delivery import notification_is_deliverable
|
||||
|
||||
for channel in ("telegram", "slack", "cli", "discord"):
|
||||
assert not notification_is_deliverable(ModelRequestEvent, channel=channel, publish_lifecycle=True)
|
||||
assert notification_is_deliverable(ModelRequestEvent, channel="websocket", publish_lifecycle=True)
|
||||
@@ -8,6 +8,7 @@ from agent.runner_helpers import make_run_spec
|
||||
from nanobot.agent.context import TranscriptInput
|
||||
from nanobot.agent.context_governance import ContextWindowExceededError
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import (
|
||||
LLMProvider,
|
||||
LLMResponse,
|
||||
@@ -609,6 +610,7 @@ async def test_runner_returns_max_iterations_fallback():
|
||||
async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
publish = AsyncMock()
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
@@ -644,6 +646,7 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
model="test-model",
|
||||
max_iterations=2,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.stop_reason == "max_iterations"
|
||||
@@ -664,6 +667,10 @@ async def test_runner_uses_no_tools_finalization_after_max_iterations():
|
||||
(1, 1),
|
||||
(10, 7),
|
||||
]
|
||||
completed = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert completed[-1].round_usages == tuple(result.round_usages)
|
||||
assert completed[-1].usage == result.usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -671,6 +678,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
from nanobot.agent.hook import AgentHook
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
publish = AsyncMock()
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
@@ -703,6 +711,7 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
hook=hook,
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.final_content == "recovered answer"
|
||||
@@ -722,6 +731,11 @@ async def test_runner_accounts_for_malformed_retry_and_no_tools_recovery():
|
||||
assert result.usage is not None
|
||||
assert (result.usage.input_tokens, result.usage.output_tokens) == (60, 6)
|
||||
assert [(item.input_tokens, item.output_tokens) for item in result.round_usages] == [(60, 6)]
|
||||
completed = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert [len(event.round_usages) for event in completed] == [1, 1, 1]
|
||||
assert completed[-1].round_usages == tuple(result.round_usages)
|
||||
assert completed[-1].usage == result.usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -766,6 +780,7 @@ async def test_runner_replaces_empty_tool_result_with_marker():
|
||||
async def test_runner_retries_empty_final_response_with_summary_prompt():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
publish = AsyncMock()
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
calls: list[dict] = []
|
||||
|
||||
@@ -794,6 +809,7 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
|
||||
model="test-model",
|
||||
max_iterations=3,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.final_content == "final answer"
|
||||
@@ -809,6 +825,10 @@ async def test_runner_retries_empty_final_response_with_summary_prompt():
|
||||
(5, 1),
|
||||
(3, 7),
|
||||
]
|
||||
completed = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert completed[-1].round_usages == tuple(result.round_usages)
|
||||
assert completed[-1].usage == result.usage
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1190,7 +1210,7 @@ async def test_runner_carries_retry_notifications_in_provider_context():
|
||||
assert "on_retry_wait" not in captured
|
||||
event = RetryWaitEvent("waiting")
|
||||
await captured["provider_context"].events.emit(event)
|
||||
retry_wait_cb.assert_awaited_once_with(event)
|
||||
retry_wait_cb.assert_any_await(event)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -71,7 +71,8 @@ async def test_tool_execution_does_not_duplicate_existing_error_hint():
|
||||
execute=AsyncMock(return_value=ToolResult.error("Error: boom" + error_hint)),
|
||||
)
|
||||
|
||||
results, events = await execute_tool_calls(
|
||||
settled = []
|
||||
await execute_tool_calls(
|
||||
tools,
|
||||
[ToolCallRequest(id="call_1", name="list_dir", arguments={})],
|
||||
concurrent=False,
|
||||
@@ -79,11 +80,13 @@ async def test_tool_execution_does_not_duplicate_existing_error_hint():
|
||||
workspace_violation_counts={},
|
||||
hook=AgentHook(),
|
||||
context=AgentHookContext(iteration=0, messages=[]),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
|
||||
assert results == ["Error: boom" + error_hint]
|
||||
assert results[0].count(error_hint) == 1
|
||||
assert events[0]["status"] == "error"
|
||||
[completed] = settled
|
||||
assert completed.result == "Error: boom" + error_hint
|
||||
assert completed.result.count(error_hint) == 1
|
||||
assert completed.event["status"] == "error"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -147,11 +147,13 @@ async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, ope
|
||||
if operation == "repeat_batch":
|
||||
calls.append(ToolCallRequest(id="batch-2", name=name, arguments=arguments))
|
||||
|
||||
results, _ = await execute_tool_calls(
|
||||
settled = []
|
||||
await execute_tool_calls(
|
||||
tools, calls, concurrent=True, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
|
||||
model_messages=messages,
|
||||
model_messages=messages, on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
results = [completed.result for completed in settled]
|
||||
|
||||
if operation == "repeat_batch":
|
||||
assert results == ["[File unchanged since last read: data.txt]"] * 2
|
||||
@@ -176,18 +178,20 @@ async def test_failed_file_read_restores_context(tmp_path, monkeypatch, error):
|
||||
raise error("read interrupted")
|
||||
|
||||
monkeypatch.setattr(tool, "execute", fail)
|
||||
settled = []
|
||||
request = execute_tool_calls(
|
||||
tools, [ToolCallRequest(id="failed-read", name="read_file", arguments={"path": "data.txt"})],
|
||||
concurrent=False, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
|
||||
model_messages=first.messages,
|
||||
model_messages=first.messages, on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
if error is asyncio.CancelledError:
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await request
|
||||
else:
|
||||
results, _ = await request
|
||||
assert results[0].startswith("Error: RuntimeError: read interrupted")
|
||||
await request
|
||||
[completed] = settled
|
||||
assert completed.result.startswith("Error: RuntimeError: read interrupted")
|
||||
|
||||
monkeypatch.setattr(tool, "execute", original_execute)
|
||||
assert await tools.execute("read_file", {"path": "data.txt"}) == contents
|
||||
|
||||
@@ -97,7 +97,7 @@ async def test_provider_can_emit_without_an_event_specific_runner_callback():
|
||||
initial_messages=[{"role": "user", "content": "hello"}],
|
||||
events=EventSink(observe),
|
||||
))
|
||||
assert received == [event]
|
||||
assert received.count(event) == 1
|
||||
|
||||
|
||||
async def test_runner_propagates_context_governance_failure():
|
||||
@@ -347,7 +347,8 @@ async def test_native_compaction_uses_provider_request_boundary(
|
||||
compaction_events: list[ContextCompactionEvent] = []
|
||||
|
||||
async def observe_compaction(event: ContextCompactionEvent) -> None:
|
||||
compaction_events.append(event)
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
compaction_events.append(event)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
@@ -530,7 +531,8 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
|
||||
compaction_events: list[ContextCompactionEvent] = []
|
||||
|
||||
async def observe_compaction(event: ContextCompactionEvent) -> None:
|
||||
compaction_events.append(event)
|
||||
if isinstance(event, ContextCompactionEvent):
|
||||
compaction_events.append(event)
|
||||
|
||||
result = await AgentRunner().run(make_run_spec(
|
||||
provider,
|
||||
|
||||
@@ -7,6 +7,7 @@ import pytest
|
||||
|
||||
from agent.runner_helpers import make_run_spec
|
||||
from nanobot.config.schema import AgentDefaults
|
||||
from nanobot.events import EventSink, ModelRequestEvent
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, LLMUsage, ToolCallRequest
|
||||
|
||||
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
|
||||
@@ -147,13 +148,14 @@ async def test_runner_measures_stream_generation_without_time_to_first_token():
|
||||
from nanobot.agent.runner import AgentRunner
|
||||
|
||||
provider = MagicMock(spec=LLMProvider)
|
||||
publish = AsyncMock()
|
||||
|
||||
async def chat_stream_with_retry(*, on_content_delta, **kwargs):
|
||||
await on_content_delta("he")
|
||||
await on_content_delta("llo")
|
||||
return LLMResponse(
|
||||
content="hello",
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=12),
|
||||
usage=LLMUsage.reported(input_tokens=100, output_tokens=12, cache_read_tokens=4),
|
||||
)
|
||||
|
||||
provider.chat_stream_with_retry = chat_stream_with_retry
|
||||
@@ -177,6 +179,7 @@ async def test_runner_measures_stream_generation_without_time_to_first_token():
|
||||
max_iterations=1,
|
||||
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
|
||||
hook=StreamingHook(),
|
||||
events=EventSink(publish),
|
||||
))
|
||||
|
||||
assert result.usage is not None
|
||||
@@ -184,6 +187,11 @@ async def test_runner_measures_stream_generation_without_time_to_first_token():
|
||||
assert result.usage.measured_output_tokens == 12
|
||||
assert result.usage.ttft_ms == 200
|
||||
assert result.usage.timed_requests == 1
|
||||
assert result.usage.cache_read_tokens == 4
|
||||
[completed] = [call.args[0] for call in publish.await_args_list
|
||||
if isinstance(call.args[0], ModelRequestEvent) and call.args[0].phase == "completed"]
|
||||
assert completed.usage == result.usage
|
||||
assert completed.round_usages == tuple(result.round_usages)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -175,12 +176,172 @@ async def test_batched_file_reads_keep_each_call_and_complete_arguments() -> Non
|
||||
))
|
||||
|
||||
assert result.final_content == "Done"
|
||||
assert [(content, hint) for content, hint, _events in progress] == [("", True), ("", False)]
|
||||
for _content, _hint, events in progress:
|
||||
assert len(progress) == 4
|
||||
for phase, hint in (("start", True), ("end", False)):
|
||||
events = [item for content, is_hint, items in progress if is_hint == hint for item in items]
|
||||
assert [(item["call_id"], item["name"], item["arguments"]) for item in events] == [
|
||||
(call.id, call.name, call.arguments) for call in calls
|
||||
]
|
||||
assert [item["phase"] for item in progress[0][2]] == ["start", "start"]
|
||||
assert [(item["phase"], item["result"]) for item in progress[1][2]] == [
|
||||
("end", "file contents"), ("end", "file contents"),
|
||||
]
|
||||
assert [item["phase"] for item in events] == [phase, phase]
|
||||
if phase == "end":
|
||||
assert [item["result"] for item in events] == ["file contents", "file contents"]
|
||||
|
||||
|
||||
def _notification_run_spec(execute, on_progress, calls, checkpoints):
|
||||
provider = MagicMock()
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=calls),
|
||||
LLMResponse(content="Done"),
|
||||
])
|
||||
tools = MagicMock()
|
||||
tools.get_definitions.return_value = []
|
||||
tools.prepare_call.return_value = (None, {}, None)
|
||||
tools.execute = execute
|
||||
|
||||
async def checkpoint(payload):
|
||||
checkpoints.append(payload)
|
||||
|
||||
return make_run_spec(
|
||||
provider, initial_messages=[], tools=tools, model="test-model",
|
||||
max_iterations=2, max_tool_result_chars=_DEFAULTS.max_tool_result_chars,
|
||||
concurrent_tools=True, hook=AgentProgressHook(output_events(on_progress=on_progress)),
|
||||
checkpoint_callback=checkpoint,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failure_phase", ["start", "end"])
|
||||
async def test_tool_notification_failure_settles_results_and_cancels_siblings(failure_phase):
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
stopped = asyncio.Event()
|
||||
effects = []
|
||||
checkpoints = []
|
||||
error = BrokenPipeError("progress consumer closed")
|
||||
|
||||
async def execute(name, arguments):
|
||||
if name == "slow":
|
||||
entered.set()
|
||||
try:
|
||||
await release.wait()
|
||||
effects.append("slow")
|
||||
return "slow result"
|
||||
finally:
|
||||
stopped.set()
|
||||
effects.append("fast")
|
||||
return "fast result"
|
||||
|
||||
async def progress(content, *, tool_events=None, **kwargs):
|
||||
if any(event["call_id"] == "fast" and event["phase"] == failure_phase
|
||||
for event in tool_events or []):
|
||||
await entered.wait()
|
||||
raise error
|
||||
|
||||
task = asyncio.create_task(AgentRunner().run(_notification_run_spec(
|
||||
execute, progress,
|
||||
[ToolCallRequest("slow", "slow", {}), ToolCallRequest("fast", "fast", {})],
|
||||
checkpoints,
|
||||
)))
|
||||
try:
|
||||
with pytest.raises(BrokenPipeError) as raised:
|
||||
await asyncio.wait_for(task, 2)
|
||||
assert raised.value is error
|
||||
assert stopped.is_set()
|
||||
assert effects == (["fast"] if failure_phase == "end" else [])
|
||||
if failure_phase == "end":
|
||||
checkpoint = checkpoints[-1]
|
||||
assert checkpoint["phase"] == "tools_completed"
|
||||
slow, fast = checkpoint["completed_tool_results"]
|
||||
assert (fast["tool_call_id"], fast["content"]) == ("fast", "fast result")
|
||||
assert slow["tool_call_id"] == "slow"
|
||||
assert slow["_recovery_interrupted"] is True
|
||||
assert "outcome is unknown" in slow["content"]
|
||||
assert checkpoint["pending_tool_calls"] == []
|
||||
from nanobot.session.recovery import runtime_checkpoint_is_well_formed
|
||||
|
||||
assert runtime_checkpoint_is_well_formed(checkpoint)
|
||||
else:
|
||||
assert [checkpoint["phase"] for checkpoint in checkpoints] == ["awaiting_tools"]
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await asyncio.wait_for(stopped.wait(), 2)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_completion_notification_error_preserves_completed_checkpoint():
|
||||
checkpoints = []
|
||||
error = BrokenPipeError("progress consumer closed")
|
||||
|
||||
async def progress(content, *, tool_events=None, **kwargs):
|
||||
if any(event["phase"] == "end" for event in tool_events or []):
|
||||
raise error
|
||||
|
||||
with pytest.raises(BrokenPipeError) as raised:
|
||||
await AgentRunner().run(_notification_run_spec(
|
||||
AsyncMock(return_value="completed effect"), progress,
|
||||
[ToolCallRequest("fast", "fast", {})], checkpoints,
|
||||
))
|
||||
assert raised.value is error
|
||||
assert [checkpoint["phase"] for checkpoint in checkpoints] == ["awaiting_tools", "tools_completed"]
|
||||
assert checkpoints[-1]["completed_tool_results"][0]["content"] == "completed effect"
|
||||
assert checkpoints[-1]["pending_tool_calls"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("cancel_during", ["start", "execution", "end"])
|
||||
async def test_tool_cancellation_does_not_wait_for_blocked_progress(cancel_during):
|
||||
queue = asyncio.Queue(maxsize=1)
|
||||
if cancel_during == "start":
|
||||
queue.put_nowait([])
|
||||
entered = asyncio.Event()
|
||||
release = asyncio.Event()
|
||||
stopped = asyncio.Event()
|
||||
checkpoints = []
|
||||
effects = []
|
||||
notifications = set()
|
||||
|
||||
async def execute(name, arguments):
|
||||
if cancel_during == "execution":
|
||||
entered.set()
|
||||
try:
|
||||
await release.wait()
|
||||
finally:
|
||||
stopped.set()
|
||||
effects.append(name)
|
||||
return "completed effect"
|
||||
|
||||
async def progress(content, *, tool_events=None, **kwargs):
|
||||
if tool_events:
|
||||
notification = asyncio.current_task()
|
||||
notifications.add(notification)
|
||||
try:
|
||||
if any(event["phase"] == cancel_during for event in tool_events):
|
||||
entered.set()
|
||||
await queue.put(tool_events)
|
||||
finally:
|
||||
notifications.remove(notification)
|
||||
|
||||
task = asyncio.create_task(AgentRunner().run(_notification_run_spec(
|
||||
execute, progress, [ToolCallRequest("tool", "tool", {})], checkpoints,
|
||||
)))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
task.cancel()
|
||||
done, _ = await asyncio.wait({task}, timeout=1)
|
||||
assert done, "cancellation must settle without a second cancel or queue consumer"
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert not notifications
|
||||
assert effects == (["tool"] if cancel_during == "end" else [])
|
||||
if cancel_during == "end":
|
||||
assert checkpoints[-1]["phase"] == "tools_completed"
|
||||
assert checkpoints[-1]["completed_tool_results"][0]["content"] == "completed effect"
|
||||
elif cancel_during == "execution":
|
||||
assert stopped.is_set()
|
||||
finally:
|
||||
# Keep the failure reproduction bounded even with the old shielded send.
|
||||
if not queue.empty():
|
||||
queue.get_nowait()
|
||||
release.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
@@ -42,6 +42,7 @@ async def test_tool_log_privacy_preserves_user_visible_progress(ephemeral, hoste
|
||||
})
|
||||
else:
|
||||
await hook.before_execute_tools(context)
|
||||
await hook.on_tool_execution_event(context)
|
||||
finally:
|
||||
logger.remove(sink)
|
||||
|
||||
|
||||
@@ -470,6 +470,7 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
),
|
||||
]
|
||||
|
||||
settled = []
|
||||
with request_context(RequestContext(
|
||||
channel="test",
|
||||
chat_id="c1",
|
||||
@@ -484,14 +485,15 @@ async def test_runner_executes_inline_spawn_batch_concurrently(tmp_path):
|
||||
workspace_violation_counts={},
|
||||
hook=AgentHook(),
|
||||
context=AgentHookContext(iteration=0, messages=[], session_key="test:c1"),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
))
|
||||
await asyncio.wait_for(both_entered.wait(), timeout=1.0)
|
||||
release.set()
|
||||
results, events = await execution
|
||||
await execution
|
||||
|
||||
assert set(entered) == {"first", "second"}
|
||||
assert results == ["first", "second"]
|
||||
assert [event["status"] for event in events] == ["ok", "ok"]
|
||||
assert [completed.result for completed in settled] == ["first", "second"]
|
||||
assert [completed.event["status"] for completed in settled] == ["ok", "ok"]
|
||||
assert manager._running_tasks == {}
|
||||
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@ from nanobot.config.schema import Config
|
||||
from nanobot.runtime_admission import RuntimeBusyError
|
||||
|
||||
|
||||
def make_manager():
|
||||
def make_manager(*, config_path=None):
|
||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
||||
manager = ChannelManager(config, MessageBus())
|
||||
manager = ChannelManager(config, MessageBus(), config_path=config_path)
|
||||
channel = MagicMock(spec=BaseChannel)
|
||||
channel.send = AsyncMock()
|
||||
channel.stop = AsyncMock()
|
||||
@@ -114,6 +114,181 @@ async def test_ten_chats_keep_order_while_one_destination_is_blocked():
|
||||
await manager.stop_all()
|
||||
|
||||
|
||||
async def test_ready_batches_are_capped_at_32_and_keep_fifo():
|
||||
manager, channel = make_manager()
|
||||
channel.can_batch_send.return_value = True
|
||||
delivered = []
|
||||
|
||||
async def send(msg):
|
||||
delivered.append([msg])
|
||||
|
||||
async def send_batch(messages):
|
||||
delivered.append(list(messages))
|
||||
|
||||
channel.send.side_effect = send
|
||||
channel.send_batch.side_effect = send_batch
|
||||
messages = [OutboundMessage("websocket", "chat", str(i)) for i in range(65)]
|
||||
try:
|
||||
for msg in messages:
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert delivered == [messages[:32], messages[32:64], messages[64:]]
|
||||
assert channel.send_batch.await_count == 2
|
||||
channel.send.assert_awaited_once_with(messages[-1])
|
||||
finally:
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_batches_keep_fifo_across_noneligible_and_scheduled_boundaries(tmp_path):
|
||||
from nanobot.bus.delivery import DeliveryRequest
|
||||
|
||||
manager, channel = make_manager(config_path=tmp_path / "config.json")
|
||||
channel.can_batch_send.side_effect = lambda previous, following: (
|
||||
previous.content != "boundary" and following.content != "boundary"
|
||||
)
|
||||
delivered = []
|
||||
|
||||
async def send(msg):
|
||||
delivered.append([msg])
|
||||
|
||||
async def send_batch(messages):
|
||||
delivered.append(list(messages))
|
||||
|
||||
channel.send.side_effect = send
|
||||
channel.send_batch.side_effect = send_batch
|
||||
messages = [OutboundMessage("websocket", "chat", content) for content in (
|
||||
"first-a", "first-b", "boundary", "second-a", "second-b",
|
||||
"scheduled", "third-a", "third-b",
|
||||
)]
|
||||
scheduled = messages[5]
|
||||
scheduled.delivery = DeliveryRequest("run", "websocket:chat", None)
|
||||
manager._outbox.record(scheduled)
|
||||
try:
|
||||
for msg in messages:
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert delivered == [messages[:2], messages[2:3], messages[3:5], messages[5:6], messages[6:]]
|
||||
assert [call.args[0] for call in channel.send.await_args_list] == [messages[2], scheduled]
|
||||
assert manager._outbox.ready() == []
|
||||
assert not manager._scheduled_deliveries
|
||||
finally:
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("start_batch", [False, True], ids=["before-start", "active"])
|
||||
async def test_batch_admission_counts_envelopes_and_cancellation_releases_them(monkeypatch, start_batch):
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_PENDING_LIMIT", 4)
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 1)
|
||||
manager, channel = make_manager()
|
||||
channel.can_batch_send.return_value = True
|
||||
started, release = asyncio.Event(), asyncio.Event()
|
||||
extra = None
|
||||
|
||||
async def send_batch(messages):
|
||||
started.set()
|
||||
await release.wait()
|
||||
|
||||
channel.send_batch.side_effect = send_batch
|
||||
try:
|
||||
for i in range(4):
|
||||
await manager._queue_outbound(channel, OutboundMessage("websocket", "chat", str(i)))
|
||||
assert manager.has_pending_delivery
|
||||
if start_batch:
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
else:
|
||||
# No yielding since queueing: cancel before the batch task starts.
|
||||
channel.send_batch.assert_not_awaited()
|
||||
await manager._cancel_outbound()
|
||||
assert not manager.has_pending_delivery
|
||||
|
||||
started.clear()
|
||||
recovered = [OutboundMessage("websocket", "chat", f"recovered-{i}") for i in range(4)]
|
||||
async with asyncio.timeout(2):
|
||||
for msg in recovered:
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
extra = asyncio.create_task(manager._queue_outbound(
|
||||
channel, OutboundMessage("websocket", "other", "blocked admission"),
|
||||
))
|
||||
await asyncio.sleep(0)
|
||||
assert not extra.done()
|
||||
extra.cancel()
|
||||
await asyncio.gather(extra, return_exceptions=True)
|
||||
release.set()
|
||||
await wait_until(lambda: not manager.has_pending_delivery)
|
||||
channel.send_batch.assert_awaited_with(tuple(recovered))
|
||||
assert channel.send_batch.await_count == 1 + int(start_batch)
|
||||
channel.send.assert_not_awaited()
|
||||
finally:
|
||||
if extra is not None:
|
||||
extra.cancel()
|
||||
await asyncio.gather(extra, return_exceptions=True)
|
||||
release.set()
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_batch_waiting_for_send_permit_cannot_absorb_later_envelopes(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 1)
|
||||
manager, channel = make_manager()
|
||||
channel.can_batch_send.return_value = True
|
||||
messages = [OutboundMessage("websocket", "chat", str(i)) for i in range(4)]
|
||||
try:
|
||||
async with manager._outbound_sends:
|
||||
for msg in messages[:2]:
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await asyncio.sleep(0)
|
||||
channel.send_batch.assert_not_awaited()
|
||||
for msg in messages[2:]:
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
assert [list(call.args[0]) for call in channel.send_batch.await_args_list] == [
|
||||
messages[:2], messages[2:],
|
||||
]
|
||||
channel.send.assert_not_awaited()
|
||||
finally:
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_partially_failed_batch_is_not_replayed_and_later_message_proceeds(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0,))
|
||||
manager, channel = make_manager()
|
||||
manager.config.channels.send_max_retries = 3
|
||||
channel.can_batch_send.return_value = True
|
||||
channel.should_retry_send_error.return_value = True
|
||||
started, fail = asyncio.Event(), asyncio.Event()
|
||||
delivered = []
|
||||
|
||||
async def send_batch(messages):
|
||||
delivered.append(messages[0].content)
|
||||
started.set()
|
||||
await fail.wait()
|
||||
raise OSError("transport failed after the first envelope")
|
||||
|
||||
async def send(msg):
|
||||
delivered.append(msg.content)
|
||||
|
||||
channel.send_batch.side_effect = send_batch
|
||||
channel.send.side_effect = send
|
||||
batch = [OutboundMessage("websocket", "chat", content) for content in ("first", "unsent")]
|
||||
later = OutboundMessage("websocket", "chat", "later")
|
||||
try:
|
||||
for msg in batch:
|
||||
await manager._queue_outbound(channel, msg)
|
||||
await asyncio.wait_for(started.wait(), 2)
|
||||
await manager._queue_outbound(channel, later)
|
||||
await asyncio.sleep(0)
|
||||
assert delivered == ["first"]
|
||||
fail.set()
|
||||
await wait_until(lambda: not manager._outbound_tasks)
|
||||
channel.send_batch.assert_awaited_once_with(tuple(batch))
|
||||
channel.send.assert_awaited_once_with(later)
|
||||
assert delivered == ["first", "later"]
|
||||
assert not manager.has_pending_delivery
|
||||
finally:
|
||||
fail.set()
|
||||
await manager._cancel_outbound()
|
||||
|
||||
|
||||
async def test_retry_does_not_block_other_chats(monkeypatch):
|
||||
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.1,))
|
||||
manager, channel = make_manager()
|
||||
|
||||
@@ -239,16 +239,18 @@ async def test_search_refresh_traceback_cannot_capture_private_call_arguments(
|
||||
lambda message: rendered.append(str(message)), format="{message}",
|
||||
diagnose=True, backtrace=True,
|
||||
)
|
||||
settled = []
|
||||
try:
|
||||
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
|
||||
results, _ = await execute_tool_calls(
|
||||
await execute_tool_calls(
|
||||
tools, [ToolCallRequest(id="test", name="web_search", arguments={"query": _SECRET})],
|
||||
concurrent=False, external_lookup_counts={}, workspace_violation_counts={},
|
||||
hook=AgentHook(), context=AgentHookContext(iteration=1, messages=[]),
|
||||
on_settled=AsyncMock(side_effect=settled.extend),
|
||||
)
|
||||
finally:
|
||||
logger.remove(sink)
|
||||
assert results == ["synthetic result"]
|
||||
assert [completed.result for completed in settled] == ["synthetic result"]
|
||||
assert "Failed to refresh web search config" in "\n".join(rendered)
|
||||
assert (_SECRET in "\n".join(rendered)) is log_content
|
||||
|
||||
|
||||
@@ -474,7 +474,8 @@ def test_many_short_trace_rows_are_bounded_and_resolved(history, tmp_path, monke
|
||||
assert detail["events"][-1]["text"] == f"tool_{trace_count - 1}(value)"
|
||||
|
||||
|
||||
def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(history) -> None:
|
||||
@pytest.mark.parametrize("with_model_requests", [False, True])
|
||||
def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(history, with_model_requests) -> None:
|
||||
key = "websocket:summary-receipts"
|
||||
history.append(key, {"event": "user", "text": "run tools", "turn_id": "turn-T", "turn_seq": 1})
|
||||
members = [("turn-T", 3), ("turn-T", 4), ("turn-U", 2), ("turn-T", 8)]
|
||||
@@ -483,13 +484,25 @@ def test_thread_response_summary_receipts_preserve_holes_and_turn_membership(his
|
||||
"event": "message", "kind": "progress", "text": f'exec({"x" * 10_000})',
|
||||
"turn_id": turn_id, "turn_seq": sequence, "turn_phase": "activity",
|
||||
})
|
||||
if with_model_requests and (turn_id, sequence) == ("turn-T", 4):
|
||||
history.append(key, {
|
||||
"event": "model_request", "turn_id": "turn-T", "turn_seq": 5,
|
||||
"request_id": "request-one", "run_id": "run-one", "sequence": 2,
|
||||
"phase": "completed", "usage": {"prompt_tokens": 100, "completion_tokens": 10},
|
||||
})
|
||||
history.append(key, {"event": "turn_end", "turn_id": "turn-T", "turn_seq": 9})
|
||||
original_rows = history.read(key)
|
||||
|
||||
payload = history.build(key)
|
||||
payload = history.build(key, include_model_requests=True)
|
||||
|
||||
assert payload is not None
|
||||
assert len(payload["events"]) == 3
|
||||
assert len(payload["events"]) == 3 + int(with_model_requests)
|
||||
if with_model_requests:
|
||||
request = payload["events"][2]
|
||||
assert (request["event"], request["turn_seq"], request["usage"]["prompt_tokens"]) == ("model_request", 5, 100)
|
||||
legacy = history.build(key)
|
||||
assert legacy is not None
|
||||
assert len(legacy["events"]) == 3
|
||||
summary = payload["events"][1]
|
||||
assert summary["trace_detail"]["traceCount"] == len(members)
|
||||
assert summary["projection_receipts"] == [
|
||||
@@ -639,6 +652,10 @@ def test_build_response_reports_fork_boundary_from_marker(history, tmp_path, mon
|
||||
{"event": "message", "chat_id": "fork", "text": "answer1"},
|
||||
):
|
||||
history.append(key, ev)
|
||||
history.append(key, {
|
||||
"event": "model_request", "chat_id": "fork", "request_id": "request",
|
||||
"run_id": "run", "sequence": 2, "phase": "completed", "round_usages": [],
|
||||
})
|
||||
history.append(key, {"event": "fork_marker"})
|
||||
history.append(key, {"event": "user", "chat_id": "fork", "text": "new branch"})
|
||||
|
||||
@@ -649,6 +666,9 @@ def test_build_response_reports_fork_boundary_from_marker(history, tmp_path, mon
|
||||
"round1", "answer1", "new branch",
|
||||
]
|
||||
assert out["fork_boundary_event_index"] == 2
|
||||
modern = history.build(key, include_model_requests=True)
|
||||
assert modern is not None
|
||||
assert modern["fork_boundary_event_index"] == 3
|
||||
|
||||
|
||||
def test_thread_response_does_not_mark_completed_message_tool_tail_pending(history,
|
||||
@@ -1232,3 +1252,33 @@ def test_existing_shell_output_uses_canonical_command_identity_not_bang_text(his
|
||||
assert answer.get("render_as") == ("text" if command else None)
|
||||
assert history.read(key)[1]["text"] == output
|
||||
assert messages[1]["content"] == output
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", ["started", "completed", "failed", "cancelled"])
|
||||
def test_model_request_persists_through_reconnect_projection(history, tmp_path, phase):
|
||||
from nanobot.events import ModelRequestEvent
|
||||
from nanobot.providers.base import LLMUsage
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.outbound_wire import project_notification
|
||||
|
||||
key = "websocket:requests"
|
||||
history.append(key, {"event": "user", "chat_id": "requests", "text": "hello"})
|
||||
usage = LLMUsage.reported(input_tokens=12, output_tokens=3)
|
||||
projection = project_notification("requests", ModelRequestEvent(
|
||||
request_id="request", run_id="run", sequence=2, phase=phase,
|
||||
usage=usage, round_usages=(usage,) * 10, context_window_tokens=32000,
|
||||
))
|
||||
assert projection is not None
|
||||
assert projection.persistence == "turn_activity"
|
||||
assert projection.deliver_offline
|
||||
record = {**projection.payload, "turn_id": "turn", "turn_seq": 2}
|
||||
history.append(key, record)
|
||||
reopened = SessionManager(tmp_path)
|
||||
response = reopened.project_history(key, lambda snapshot: transcript_module.build_webui_thread_response(
|
||||
key, history=snapshot, include_model_requests=True,
|
||||
))
|
||||
assert response is not None
|
||||
[event] = [e for e in response["events"] if e["event"] == "model_request"]
|
||||
assert {field: event[field] for field in record} == record
|
||||
assert len(event["round_usages"]) == 8
|
||||
assert event["usage"] == usage.to_turn_dict()
|
||||
@@ -645,8 +645,25 @@ main()
|
||||
assert len(requests) == 17
|
||||
else:
|
||||
await asyncio.wait_for(closing_request.wait(), 20)
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "running")
|
||||
waiting = await receive_until(lambda event: (
|
||||
event.get("event") == "model_request"
|
||||
and event.get("phase") == "started"
|
||||
and event.get("usage", {}).get("request_count") == 16
|
||||
))
|
||||
assert waiting["usage"]["context_tokens"] == 10
|
||||
assert len(waiting["round_usages"]) == 8
|
||||
assert not any(event.get("event") == "turn_end" for event in events)
|
||||
history_url = f"http://127.0.0.1:{ws_port}/api/sessions/{quote('websocket:' + chat_id, safe='')}/webui-thread"
|
||||
headers = {"Authorization": f"Bearer {bootstrap['api_token']}"}
|
||||
async with httpx.AsyncClient(trust_env=False) as client:
|
||||
modern = await client.get(history_url, params={"include_model_requests": "1"}, headers=headers)
|
||||
modern.raise_for_status()
|
||||
persisted = [event for event in modern.json()["events"] if event["event"] == "model_request"]
|
||||
assert persisted[-1]["request_id"] == waiting["request_id"]
|
||||
assert persisted[-1]["usage"] == waiting["usage"]
|
||||
legacy = await client.get(history_url, headers={**headers, "If-None-Match": modern.headers["etag"]})
|
||||
assert legacy.status_code == 200
|
||||
assert not any(event["event"] == "model_request" for event in legacy.json()["events"])
|
||||
release_close.set()
|
||||
end = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert end.get("turn_id") == "goal-e2e"
|
||||
|
||||
Reference in new issue
Block a user