refactor(events): unify scoped runtime notifications across clients (#5670)

* refactor(events): unify scoped runtime notifications across clients

* style(tests): sort auto-compaction event imports

* refactor(events): scope connections and remove retry callback plumbing

* docs: remove runtime notification design write-up

* refactor(bus): route operation events through the message bus

* fix(channels): isolate outbound sends by destination

* style(events): group shared notification imports

* refactor(events): converge runtime and hook delivery on MessageBus

* test(events): migrate fixtures to unified message bus
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-06 02:11:19 +08:00
1 parent 3495281282
commit 192e2e90dc
78 files changed
+1620 -1194

No files matched your search

+2 -1
View File
@@ -13,6 +13,7 @@ from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.command import CommandContext
from nanobot.config.schema import AgentDefaults, Config
from nanobot.events import NO_EVENTS
from nanobot.providers.base import LLMResponse
@@ -89,7 +90,7 @@ def _make_fake_compact(
runtime,
max_suffix: int = 8,
trigger: str = "policy",
on_compaction=None,
events=NO_EVENTS,
) -> str:
state["count"] += 1
session = loop.sessions.get_or_create(key)
+6 -6
View File
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from nanobot.agent.autocompact import AutoCompact
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.events import NO_EVENTS, ContextCompactionEvent, EventSink
from nanobot.session.manager import Session, SessionManager
@@ -269,7 +269,7 @@ class TestCheckExpired:
"cli:old",
runtime=admitted,
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
on_compaction=None,
events=NO_EVENTS,
)
@pytest.mark.parametrize("resolution_error", [KeyError, ValueError])
@@ -445,7 +445,7 @@ class TestArchiveDelegates:
"cli:test",
runtime=runtime,
max_suffix=ac._RECENT_SUFFIX_MESSAGES,
on_compaction=None,
events=NO_EVENTS,
)
@pytest.mark.asyncio
@@ -457,11 +457,11 @@ class TestArchiveDelegates:
def bind(key: str):
async def publish(event: ContextCompactionEvent) -> None:
observed.append((key, event))
return publish
return EventSink(publish)
async def compact(key: str, **kwargs):
event = ContextCompactionEvent(compaction_id="compact-1", phase="started")
await kwargs["on_compaction"](event)
await kwargs["events"].emit(event)
return "Summary."
consolidator.compact_idle_session = AsyncMock(side_effect=compact)
@@ -469,7 +469,7 @@ class TestArchiveDelegates:
sessions=sessions,
consolidator=consolidator,
session_ttl_minutes=15,
bind_compaction=bind,
bind_events=bind,
)
await ac._archive("cli:test", runtime=_runtime())
+7 -6
View File
@@ -10,7 +10,7 @@ from nanobot.agent.memory import (
Consolidator,
MemoryStore,
)
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.events import AgentEvent, ContextCompactionEvent, EventSink
from nanobot.providers.base import (
GenerationSettings,
LLMResponse,
@@ -569,13 +569,14 @@ class TestCompactIdleSession:
real_consolidator.sessions.save(session)
events: list[ContextCompactionEvent] = []
async def observe(event: ContextCompactionEvent) -> None:
events.append(event)
async def observe(event: AgentEvent) -> None:
if isinstance(event, ContextCompactionEvent):
events.append(event)
result = await real_consolidator.compact_idle_session(
"cli:events",
runtime=runtime,
on_compaction=observe,
events=EventSink(observe),
)
assert result == "Summary."
@@ -593,13 +594,13 @@ class TestCompactIdleSession:
session.add_message("user", "question")
real_consolidator.sessions.save(session)
async def fail_observer(_event: ContextCompactionEvent) -> None:
async def fail_observer(_event: AgentEvent) -> None:
raise RuntimeError("channel unavailable")
result = await real_consolidator.compact_idle_session(
"cli:event-callback-failure",
runtime=runtime,
on_compaction=fail_observer,
events=EventSink(fail_observer),
)
assert result == "Summary."
+5 -3
View File
@@ -15,6 +15,7 @@ from nanobot.agent.hook import (
CompositeHook,
)
from nanobot.agent.tools.context import RequestContext
from nanobot.utils.progress_events import output_events
def _ctx() -> AgentHookContext:
@@ -507,7 +508,7 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):
await loop._run_agent_loop(
TranscriptInput(history=[{"role": "user", "content": "hi"}], current_message=None),
runtime=runtime,
on_progress=on_progress,
events=output_events(on_progress=on_progress),
request_context=RequestContext(
channel="websocket",
chat_id="chat-1",
@@ -521,7 +522,8 @@ async def test_agent_loop_turn_hook_factories_receive_context(tmp_path):
assert events == ["registered:0", "turn:0"]
assert [label for label, _ in captured] == ["registered", "turn"]
assert [context.on_progress for _, context in captured] == [on_progress, on_progress]
assert captured[0][1].events is captured[1][1].events
assert captured[0][1].events.publish is not None
assert [context.workspace for _, context in captured] == [tmp_path, tmp_path]
assert [context.channel for _, context in captured] == ["websocket", "websocket"]
assert [context.chat_id for _, context in captured] == ["chat-1", "chat-1"]
@@ -580,7 +582,7 @@ async def test_agent_loop_extra_hooks_do_not_swallow_loop_hook_errors(tmp_path):
await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=bad_progress,
events=output_events(on_progress=bad_progress),
)
@@ -34,7 +34,7 @@ def _make_loop(tmp_path):
bus=bus,
sessions=loop.sessions,
schedule_background=lambda coro: loop.schedule_background(coro),
).subscribe(loop.runtime_events)
).subscribe()
loop.turn_delivery_factory.route_policy = WebuiTurnRoutePolicy(loop.sessions)
loop.tools.get_definitions = MagicMock(return_value=[])
return loop
+14 -21
View File
@@ -25,10 +25,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.providers.base import LLMResponse, ToolCallRequest
from nanobot.providers.factory import ProviderSnapshot
from nanobot.session.webui_turns import WebuiTurnCoordinator, WebuiTurnRoutePolicy
from nanobot.utils.progress_events import (
invoke_file_edit_progress,
on_progress_accepts_file_edit_events,
)
from nanobot.utils.progress_events import output_events
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_TURN_METADATA_KEY,
@@ -55,7 +52,7 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:
sessions=loop.sessions,
schedule_background=lambda coro: loop.schedule_background(coro),
)
coordinator.subscribe(loop.runtime_events)
coordinator.subscribe()
class TestToolEventProgress:
@@ -87,7 +84,7 @@ class TestToolEventProgress:
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=on_progress,
events=output_events(on_progress=on_progress),
)
assert result.final_content == "Done"
@@ -160,7 +157,7 @@ class TestToolEventProgress:
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=on_progress,
events=output_events(on_progress=on_progress),
)
assert result.final_content == "Done"
@@ -232,7 +229,7 @@ class TestToolEventProgress:
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=on_progress,
events=output_events(on_progress=on_progress),
)
assert result.final_content == "Done"
@@ -272,7 +269,7 @@ class TestToolEventProgress:
await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=on_progress,
events=output_events(on_progress=on_progress),
)
assert file_events == []
@@ -368,10 +365,8 @@ class TestToolEventProgress:
chat_id="chat1",
content="edit",
)
progress = loop.turn_delivery_factory.create(msg, msg.session_key).progress_callback()
assert progress is not None
assert on_progress_accepts_file_edit_events(progress) is True
await invoke_file_edit_progress(progress, edit_events)
events = loop.turn_delivery_factory.create(msg, msg.session_key).events
await events.emit(ProgressEvent(file_edit_events=edit_events))
outbound = await bus.consume_outbound()
assert outbound.channel == "telegram"
assert isinstance(outbound.event, ProgressEvent)
@@ -685,14 +680,12 @@ class TestToolEventProgress:
async def cancel_after_merge(
_msg: InboundMessage,
*,
on_stream,
on_stream_end,
delivery,
**_kwargs,
):
assert on_stream is not None
assert on_stream_end is not None
await on_stream("partial")
await on_stream_end(resuming=True, merge_next=True)
assert delivery.streaming
await delivery.events.emit(StreamDeltaEvent(content="partial"))
await delivery.events.emit(StreamEndEvent(resuming=True, merge_next=True))
raise asyncio.CancelledError
loop._process_message = cancel_after_merge # type: ignore[method-assign]
@@ -1019,8 +1012,8 @@ class TestToolEventProgress:
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=on_progress,
on_stream=on_stream,
events=output_events(on_progress=on_progress, on_stream=on_stream),
streaming=True,
)
assert result.final_content == "Done"
+7 -4
View File
@@ -22,6 +22,7 @@ from nanobot.runtime_context import (
)
from nanobot.session.goal_state import GOAL_STATE_KEY
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.progress_events import output_events
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
_GOAL_RUNTIME_GUIDANCE_TAG = "[Goal Runtime Guidance — host instructions]"
@@ -400,8 +401,8 @@ async def test_loop_stream_filter_handles_think_only_prefix_without_crashing(tmp
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_stream=on_stream,
on_stream_end=on_stream_end,
events=output_events(on_stream=on_stream, on_stream_end=on_stream_end),
streaming=True,
)
assert result.final_content == "Hello"
@@ -427,7 +428,8 @@ async def test_loop_stream_filter_hides_partial_trailing_think_prefix(tmp_path):
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_stream=on_stream,
events=output_events(on_stream=on_stream),
streaming=True,
)
assert result.final_content == "Hello World"
@@ -452,7 +454,8 @@ async def test_loop_stream_filter_hides_complete_trailing_think_tag(tmp_path):
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_stream=on_stream,
events=output_events(on_stream=on_stream),
streaming=True,
)
assert result.final_content == "Hello World"
+5 -6
View File
@@ -129,7 +129,7 @@ def _make_full_loop(tmp_path: Path) -> AgentLoop:
bus=loop.bus,
sessions=loop.sessions,
schedule_background=lambda coro: loop.schedule_background(coro),
).subscribe(loop.runtime_events)
).subscribe()
return loop
@@ -1452,7 +1452,7 @@ async def test_internal_continuation_preserves_streaming_route_metadata(
calls = 0
async def fake_run_agent_loop(transcript_input, *, on_stream=None, on_stream_end=None, **_kwargs):
async def fake_run_agent_loop(transcript_input, *, events, streaming, **_kwargs):
nonlocal calls
initial_messages = _assembled_messages(loop.context, transcript_input)
calls += 1
@@ -1462,10 +1462,9 @@ async def test_internal_continuation_preserves_streaming_route_metadata(
[*initial_messages, {"role": "assistant", "content": "paused"}],
stop_reason="max_iterations",
)
assert on_stream is not None
assert on_stream_end is not None
await on_stream("done")
await on_stream_end(resuming=False)
assert streaming
await events.emit(StreamDeltaEvent(content="done"))
await events.emit(StreamEndEvent())
return _agent_run_result(
"done",
[*initial_messages, {"role": "assistant", "content": "done"}],
+8 -4
View File
@@ -1281,9 +1281,10 @@ async def test_runner_accumulates_usage_and_preserves_cache_reads():
@pytest.mark.asyncio
async def test_runner_binds_on_retry_wait_callback():
"""Provider retry heartbeats use the explicitly supplied callback."""
async def test_runner_carries_retry_notifications_in_provider_context():
"""The runner carries a generic scope, not an event-specific callback."""
from nanobot.agent.runner import AgentRunner
from nanobot.events import EventSink, RetryWaitEvent
captured: dict = {}
@@ -1308,10 +1309,13 @@ async def test_runner_binds_on_retry_wait_callback():
model="test-model",
max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
retry_wait_callback=retry_wait_cb,
events=EventSink(retry_wait_cb),
))
assert captured["on_retry_wait"] is retry_wait_cb
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)
# ---------------------------------------------------------------------------
+64
View File
@@ -169,6 +169,28 @@ def test_fallback_models_accept_preset_refs_and_inline_configs() -> None:
)
async def test_fallback_preserves_the_operation_event_sink():
from nanobot.events import EventSink
async def observe(event):
pass
events = EventSink(observe)
primary = _FakeProvider("primary", _error_response())
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
fb = FallbackProvider(
primary=primary, fallback_presets=[_fallback("fallback-a")],
provider_factory=MagicMock(return_value=fallback),
)
result = await fb.chat_with_context(
messages=[{"role": "user", "content": "hello"}], model="primary",
provider_context=ProviderCallContext(events=events),
)
assert result.content == "fallback ok"
assert primary.context_calls[0].events is events
assert fallback.context_calls[0].events is events
def test_fallback_model_preset_ref_must_exist() -> None:
from nanobot.config.schema import Config
@@ -1047,6 +1069,48 @@ class TestFailoverOnTransientError:
class TestRetryBeforeFailover:
@pytest.mark.parametrize("stream", [False, True])
async def test_scoped_retry_events_preserve_fallback_chain_ownership(self, stream):
from nanobot.events import EventSink, RetryWaitEvent
primary = _FakeProvider("primary", _retryable_error("primary unavailable"))
fallback = _FakeProvider("fallback", _make_response("fallback ok"))
provider = FallbackProvider(primary, [_fallback("fallback-a")],
MagicMock(return_value=fallback))
observe = AsyncMock()
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await call(
[{"role": "user", "content": "hi"}],
provider_context=ProviderCallContext(events=EventSink(observe)),
)
assert result.content == "fallback ok"
events = [call.args[0] for call in observe.await_args_list]
assert len(events) == 3
assert all(isinstance(event, RetryWaitEvent) for event in events)
assert not any("giving up" in event.content for event in events)
async def test_scoped_persistent_retry_includes_chain_wait_and_one_terminal(self):
from nanobot.events import EventSink
primary = _FakeProvider("primary", _retryable_error("primary unavailable"))
fallback = _FakeProvider("fallback", _retryable_error("fallback unavailable"))
provider = FallbackProvider(primary, [_fallback("fallback-a")],
MagicMock(return_value=fallback))
provider._PERSISTENT_IDENTICAL_ERROR_LIMIT = 2
observe = AsyncMock()
with patch("nanobot.providers.base.asyncio.sleep", new_callable=AsyncMock):
result = await provider.chat_with_retry(
[{"role": "user", "content": "hi"}], retry_mode="persistent",
provider_context=ProviderCallContext(events=EventSink(observe)),
)
assert result.finish_reason == "error"
notices = [call.args[0].content for call in observe.await_args_list]
# Two candidates, three waits each, for two chains, plus one chain wait.
assert len(notices) == 14
assert sum("Persistent retry stopped" in text for text in notices) == 1
assert not any("giving up" in text for text in notices)
@pytest.mark.asyncio
@pytest.mark.parametrize("retry_mode", ["standard", "persistent"])
async def test_primary_recovers_before_fallback(self, retry_mode: str) -> None:
+29 -3
View File
@@ -16,8 +16,8 @@ from nanobot.agent.context_governance import (
ModelRequestState,
)
from nanobot.agent.runner import AgentRunner, AgentRunSpec
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.config.schema import AgentDefaults
from nanobot.events import ContextCompactionEvent, EventSink
from nanobot.providers.base import (
LLMProvider,
LLMResponse,
@@ -76,6 +76,32 @@ def _make_loop(tmp_path):
return loop
async def test_provider_can_emit_without_an_event_specific_runner_callback():
from nanobot.events import AgentEvent
event = AgentEvent()
received = []
async def observe(value):
received.append(value)
async def request(*, provider_context, **kwargs):
await provider_context.events.emit(event)
return LLMResponse(content="done")
provider = MagicMock(spec=LLMProvider)
provider.chat_with_retry = request
tools = MagicMock()
tools.get_definitions.return_value = []
await AgentRunner().run(make_run_spec(
provider, model="test-model", tools=tools, max_iterations=1,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
initial_messages=[{"role": "user", "content": "hello"}],
events=EventSink(observe),
))
assert received == [event]
async def test_runner_propagates_context_governance_failure():
from nanobot.agent.runner import AgentRunner
@@ -394,7 +420,7 @@ async def test_native_compaction_uses_provider_request_boundary(
max_tokens=100,
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
compaction_callback=observe_compaction,
events=EventSink(observe_compaction),
))
consolidate.assert_not_awaited()
@@ -534,7 +560,7 @@ async def test_repeated_pressure_advances_summary_boundary(monkeypatch):
max_tokens=100,
max_iterations=3,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
compaction_callback=observe_compaction,
events=EventSink(observe_compaction),
))
assert consolidate.await_count == 2
+7 -6
View File
@@ -12,6 +12,7 @@ from nanobot.agent.runner import AgentRunner
from nanobot.agent.tools.filesystem import EditFileTool, WriteFileTool
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, ToolCallRequest
from nanobot.utils.progress_events import output_events
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
@@ -61,7 +62,7 @@ async def test_runner_routes_hosted_tool_events_to_structured_progress():
async def stream_cb(content: str) -> None:
streamed_text.append(content)
hook = AgentProgressHook(on_progress=progress_cb, on_stream=stream_cb)
hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)
result = await AgentRunner().run(make_run_spec(
provider,
initial_messages=[{"role": "user", "content": "search X"}],
@@ -135,7 +136,7 @@ async def test_runner_fails_pending_hosted_tool_when_model_request_fails():
async def stream_cb(_content: str) -> None:
pass
hook = AgentProgressHook(on_progress=progress_cb, on_stream=stream_cb)
hook = AgentProgressHook(output_events(on_progress=progress_cb, on_stream=stream_cb), streaming=True)
result = await AgentRunner().run(make_run_spec(
provider,
initial_messages=[{"role": "user", "content": "search X"}],
@@ -213,7 +214,7 @@ async def test_runner_emits_write_file_diff_from_tool_execution_snapshots(tmp_pa
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
workspace=tmp_path,
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
))
assert result.final_content == "done"
@@ -283,7 +284,7 @@ async def test_runner_emits_edit_file_diff_from_tool_execution_snapshots(tmp_pat
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
workspace=tmp_path,
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
))
assert result.final_content == "done"
@@ -345,7 +346,7 @@ async def test_runner_marks_file_edit_activity_failed_when_tool_errors(tmp_path)
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
workspace=tmp_path,
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
))
assert result.stop_reason == "completed"
@@ -405,7 +406,7 @@ async def test_runner_marks_file_edit_activity_failed_when_cancelled(tmp_path):
max_iterations=2,
max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,
workspace=tmp_path,
hook=FileEditActivityHook(on_progress=progress_cb, workspace=tmp_path),
hook=FileEditActivityHook(events=output_events(on_progress=progress_cb), workspace=tmp_path),
)))
await asyncio.wait_for(executing.wait(), timeout=1)
+2 -1
View File
@@ -20,6 +20,7 @@ from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.progress_hook import AgentProgressHook
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest
from nanobot.utils.progress_events import output_events
_MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars
@@ -324,7 +325,7 @@ async def test_runner_does_not_double_emit_when_inline_think_already_streamed():
async def _stream(_content: str) -> None:
pass
hook = AgentProgressHook(on_progress=_progress, on_stream=_stream)
hook = AgentProgressHook(output_events(on_progress=_progress, on_stream=_stream), streaming=True)
runner = AgentRunner()
result = await runner.run(make_run_spec(provider,
initial_messages=[{"role": "user", "content": "question"}],
+2 -2
View File
@@ -224,7 +224,7 @@ async def test_config_invalidation_defers_canonical_notification_until_default_r
model_preset="fast",
preset_snapshot_loader=load_preset,
)
loop.runtime_events.subscribe(published.append, RuntimeModelChanged)
loop.bus.subscribe(published.append, RuntimeModelChanged)
session = loop.sessions.get_or_create("websocket:chat")
session.metadata[SESSION_MODEL_PRESET_METADATA_KEY] = "fast"
current_model = "model-b"
@@ -275,7 +275,7 @@ async def test_config_refresh_publishes_renamed_canonical_preset(tmp_path: Path)
model_preset="fast",
preset_snapshot_loader=load_preset,
)
loop.runtime_events.subscribe(published.append, RuntimeModelChanged)
loop.bus.subscribe(published.append, RuntimeModelChanged)
catalog["Codex"] = catalog.pop("fast")
default_name = "Codex"
+5 -6
View File
@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
from nanobot.config.schema import AgentDefaults
from nanobot.providers.base import GenerationSettings
from nanobot.session.keys import UNIFIED_SESSION_KEY
@@ -277,7 +278,6 @@ class TestDispatch:
@pytest.mark.asyncio
async def test_dispatch_streaming_preserves_message_metadata(self):
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import StreamDeltaEvent, StreamEndEvent
loop, bus = _make_loop()
msg = InboundMessage(
@@ -292,11 +292,10 @@ class TestDispatch:
},
)
async def fake_process(_msg, *, on_stream=None, on_stream_end=None, **kwargs):
assert on_stream is not None
assert on_stream_end is not None
await on_stream("hi")
await on_stream_end(resuming=False)
async def fake_process(_msg, *, delivery, **kwargs):
assert delivery.streaming
await delivery.events.emit(StreamDeltaEvent(content="hi"))
await delivery.events.emit(StreamEndEvent())
return None
loop._process_message = fake_process
+13 -19
View File
@@ -6,7 +6,6 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import ContextCompactionEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.session.manager import SessionManager
from nanobot.session.webui_turns import WebuiTurnRoutePolicy
from nanobot.webui.metadata import (
@@ -31,7 +30,7 @@ from nanobot.webui.metadata import (
async def test_idle_compaction_uses_the_session_delivery_route(
key, channel, chat_id, metadata, unified,
) -> None:
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
factory = TurnDeliveryFactory(MessageBus())
event = ContextCompactionEvent(compaction_id="compact-1", phase="started")
key = "unified:default" if unified else key
msg = InboundMessage(
@@ -45,9 +44,9 @@ async def test_idle_compaction_uses_the_session_delivery_route(
session_metadata = {}
delivery.remember_session_route(session_metadata)
callback = factory.session_compaction_callback(key, session_metadata)
assert callback is not None
await callback(event)
sink = factory.session_events(key, session_metadata)
assert sink.publish is not None
await sink.emit(event)
outbound = factory.bus.outbound.get_nowait()
assert (outbound.channel, outbound.chat_id, outbound.metadata) == (channel, chat_id, metadata)
@@ -55,7 +54,7 @@ async def test_idle_compaction_uses_the_session_delivery_route(
async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() -> None:
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
factory = TurnDeliveryFactory(MessageBus())
key = "unified:default"
session_metadata = {}
original = InboundMessage(
@@ -63,15 +62,15 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
metadata={"slack": {"thread_ts": "1700000000.000100"}},
)
factory.create(original, key).remember_session_route(session_metadata)
callback = factory.session_compaction_callback(key, session_metadata)
assert callback is not None
await callback(ContextCompactionEvent("compact-1", "started"))
sink = factory.session_events(key, session_metadata)
assert sink.publish is not None
await sink.emit(ContextCompactionEvent("compact-1", "started"))
latest = InboundMessage(
channel="telegram", sender_id="user", chat_id="42", content="next question",
)
factory.create(latest, key).remember_session_route(session_metadata)
await callback(ContextCompactionEvent("compact-1", "succeeded"))
await sink.emit(ContextCompactionEvent("compact-1", "succeeded"))
events = [factory.bus.outbound.get_nowait() for _ in range(2)]
assert [(msg.channel, msg.chat_id, msg.metadata) for msg in events] == [
@@ -80,11 +79,11 @@ async def test_idle_compaction_keeps_its_route_when_a_unified_session_moves() ->
async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> None:
factory = TurnDeliveryFactory(MessageBus(), RuntimeEventBus())
factory = TurnDeliveryFactory(MessageBus())
event = ContextCompactionEvent(compaction_id="compact-1", phase="succeeded")
callback = factory.session_compaction_callback("websocket:chat", {})
assert callback is not None
await callback(event)
sink = factory.session_events("websocket:chat", {})
assert sink.publish is not None
await sink.emit(event)
outbound = factory.bus.outbound.get_nowait()
assert (outbound.channel, outbound.chat_id, outbound.event) == ("websocket", "chat", event)
@@ -92,7 +91,6 @@ async def test_idle_compaction_can_deliver_to_a_legacy_websocket_session() -> No
def test_websocket_lifecycles_get_distinct_internal_owners(tmp_path: Path) -> None:
factory = TurnDeliveryFactory(
MessageBus(),
RuntimeEventBus(),
route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),
)
first_msg = InboundMessage(
@@ -141,7 +139,6 @@ def test_websocket_lifecycle_reuses_registered_ingress_owner(tmp_path: Path) ->
)
factory = TurnDeliveryFactory(
MessageBus(),
RuntimeEventBus(),
route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),
)
@@ -163,7 +160,6 @@ def test_internal_user_input_uses_the_persisted_webui_route(tmp_path: Path) -> N
sessions.save(target)
factory = TurnDeliveryFactory(
MessageBus(),
RuntimeEventBus(),
route_policy=WebuiTurnRoutePolicy(sessions),
)
msg = InboundMessage(
@@ -194,7 +190,6 @@ async def test_same_chat_different_sessions_restore_previous_active_projection(
factory = TurnDeliveryFactory(
MessageBus(),
RuntimeEventBus(),
route_policy=WebuiTurnRoutePolicy(SessionManager(tmp_path / "sessions")),
)
first_msg = InboundMessage(
@@ -253,7 +248,6 @@ def test_late_subagent_route_requires_webui_owned_session(tmp_path: Path) -> Non
sessions = SessionManager(tmp_path)
factory = TurnDeliveryFactory(
MessageBus(),
RuntimeEventBus(),
route_policy=WebuiTurnRoutePolicy(sessions),
)
session_key = "websocket:chat-a"
+4 -6
View File
@@ -21,7 +21,6 @@ from nanobot.agent.tools.long_task import (
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.outbound_events import GoalStateSyncEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventBus
from nanobot.session.goal_state import GOAL_STATE_KEY, MAX_GOAL_OBJECTIVE_CHARS
from nanobot.session.manager import SessionManager
from nanobot.session.turn_continuation import should_finalize_on_max_iterations
@@ -378,17 +377,16 @@ async def test_registry_does_not_reuse_goal_context_after_request_scope(tmp_path
@pytest.mark.asyncio
async def test_goal_state_events_publish_active_then_inactive(tmp_path):
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
runtime_events = RuntimeEventBus()
sm = SessionManager(tmp_path)
WebuiTurnCoordinator(
bus=bus,
sessions=sm,
schedule_background=lambda _coro: None,
).subscribe(runtime_events)
create = CreateGoalTool(sessions=sm, runtime_events=runtime_events)
update = UpdateGoalTool(sessions=sm, runtime_events=runtime_events)
).subscribe()
create = CreateGoalTool(sessions=sm, bus=bus)
update = UpdateGoalTool(sessions=sm, bus=bus)
rc = _request_context(chat_id="chat-99")
await _execute(
create,
+175
View File
@@ -0,0 +1,175 @@
import asyncio
from dataclasses import dataclass
import pytest
from nanobot.agent.turn_delivery import TurnDeliveryFactory, TurnRoute
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.notification_delivery import NOTIFICATION_AUDIENCES
from nanobot.bus.outbound_events import (
FileEditEvent,
ProgressEvent,
StreamDeltaEvent,
StreamEndEvent,
)
from nanobot.bus.queue import MessageBus
from nanobot.events import AgentEvent, ContextCompactionEvent, EventSink, RetryWaitEvent
from nanobot.utils.progress_events import output_events
from nanobot.webui.outbound_wire import project_notification
async def test_sink_isolates_observer_failure_but_propagates_cancellation():
async def broken(event):
raise ValueError("observer failed")
await EventSink(broken).emit(AgentEvent())
async def cancelled(event):
raise asyncio.CancelledError
with pytest.raises(asyncio.CancelledError):
await EventSink(cancelled).emit(AgentEvent())
async def test_scoped_output_preserves_routing_and_stream_segment_ownership():
bus = MessageBus()
delivery = TurnDeliveryFactory(bus).create(InboundMessage(
channel="websocket", sender_id="u", chat_id="chat", content="",
metadata={"_wants_stream": True, "origin_message_id": "original"},
), "websocket:chat", enable_stream=True)
events = [
ProgressEvent(content="thinking"),
FileEditEvent(file_edit_events=[{"phase": "start", "path": "a.py"}]),
StreamDeltaEvent(content="first"),
StreamEndEvent(resuming=True, merge_next=True),
StreamDeltaEvent(content="tail"),
]
for event in events:
await delivery.events.emit(event)
await delivery.abort_stream()
messages = [bus.outbound.get_nowait() for _ in range(6)]
assert [message.content for message in messages] == ["thinking", "", "first", "", "tail", ""]
assert all(message.chat_id == "chat" for message in messages)
assert all(message.metadata["origin_message_id"] == "original" for message in messages)
streams = [message.event for message in messages[2:]]
assert all(isinstance(event, StreamDeltaEvent | StreamEndEvent) for event in streams)
assert len({event.stream_id for event in streams}) == 1
assert isinstance(streams[-1], StreamEndEvent)
assert streams[-1].merge_next is False
await delivery.abort_stream()
assert bus.outbound.empty()
async def test_output_consumer_capability_survives_callback_adaptation():
bus = MessageBus()
quiet = TurnDeliveryFactory(bus, lambda *_: TurnRoute("websocket", "chat")).create(
InboundMessage(channel="system", sender_id="job", chat_id="websocket:chat", content=""),
"websocket:chat",
)
assert quiet.events.accepts(ContextCompactionEvent)
assert not quiet.events.accepts(FileEditEvent)
received = []
async def text_only(content, *, tool_hint=False):
received.append(content)
events = output_events(default=quiet.events, on_progress=text_only)
assert events.accepts(ProgressEvent)
assert not events.accepts(FileEditEvent)
await events.emit(ProgressEvent(content="working"))
await events.emit(ContextCompactionEvent("compact", "succeeded"))
assert received == ["working"]
assert bus.outbound.get_nowait().event == ContextCompactionEvent("compact", "succeeded")
async def test_scope_snapshots_route_and_queues_events_in_order():
bus = MessageBus()
metadata = {"slack": {"thread_ts": "original"}}
factory = TurnDeliveryFactory(bus)
delivery = factory.create(InboundMessage(
channel="slack", sender_id="u", chat_id="chat", content="", metadata=metadata,
), "unified:default")
metadata["slack"]["thread_ts"] = "moved"
for phase in ("started", "succeeded"):
await delivery.events.emit(ContextCompactionEvent("c1", phase))
for phase in ("started", "succeeded"):
message = bus.outbound.get_nowait()
assert message.metadata == {"slack": {"thread_ts": "original"}}
assert message.event == ContextCompactionEvent("c1", phase)
assert bus.outbound.empty()
async def test_new_internal_event_needs_explicit_audience(monkeypatch):
@dataclass(frozen=True)
class RetryStatus(AgentEvent):
state: str = "waiting"
attempt: int = 1
bus = MessageBus()
factory = TurnDeliveryFactory(bus)
delivery = factory.create(InboundMessage(
channel="websocket", sender_id="u", chat_id="chat", content="",
), "websocket:chat")
event = RetryStatus()
await delivery.events.emit(event)
assert bus.outbound.empty()
assert project_notification("chat", event) is None
monkeypatch.setitem(NOTIFICATION_AUDIENCES, RetryStatus, "interactive")
await delivery.events.emit(event)
assert bus.outbound.get_nowait().event is event
# Routing registration alone does not authorize serialization of private fields.
assert project_notification("chat", event) is None
async def test_background_scope_keeps_retry_quiet_but_delivers_compaction():
bus = MessageBus()
factory = TurnDeliveryFactory(bus,
lambda *_: TurnRoute("websocket", "chat"))
delivery = factory.create(InboundMessage(
channel="system", sender_id="job", chat_id="websocket:chat", content="",
), "websocket:chat")
await delivery.events.emit(RetryWaitEvent("waiting"))
assert bus.outbound.empty()
event = ContextCompactionEvent("c1", "cancelled")
await delivery.events.emit(event)
assert bus.outbound.get_nowait().event is event
@pytest.mark.parametrize("channel", ["websocket", "cli", "slack", "custom"])
async def test_bus_routes_arbitrary_events_and_text_through_one_queue(channel):
@dataclass(frozen=True)
class JobFinished(AgentEvent):
job_id: str
bus = MessageBus()
text = OutboundMessage(channel=channel, chat_id="chat", content="hello")
event = JobFinished("job-1")
await bus.publish_outbound(text)
await bus.publish_event(event, channel=channel, chat_id="chat", metadata={"thread": "1"})
assert await bus.consume_outbound() is text
delivered = await bus.consume_outbound()
assert (delivered.channel, delivered.chat_id) == (channel, "chat")
assert delivered.event is event
assert delivered.content == ""
assert delivered.metadata == {"thread": "1"}
assert bus.outbound.empty()
async def test_bus_event_preserves_existing_text_fallback():
bus = MessageBus()
event = RetryWaitEvent("waiting")
await bus.publish_event(event, channel="slack", chat_id="chat")
delivered = await bus.consume_outbound()
assert delivered.event is event
assert delivered.content == "waiting"
@pytest.mark.parametrize("phase", ["started", "succeeded", "failed", "cancelled"])
def test_compaction_durability_is_independent_of_subscribers(phase):
projection = project_notification("chat", ContextCompactionEvent("c1", phase))
assert projection is not None
assert projection.deliver_offline
assert projection.attach_turn_metadata
assert projection.persistence == ("transient" if phase == "started" else "turn_activity")
+3 -167
View File
@@ -3,17 +3,10 @@ from __future__ import annotations
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import (
ContextCompactionEvent,
GoalStateSyncEvent,
GoalStatusEvent,
ProgressEvent,
RetryWaitEvent,
RuntimeModelUpdatedEvent,
SessionUpdatedEvent,
StreamDeltaEvent,
StreamedResponseEvent,
StreamEndEvent,
TurnEndEvent,
outbound_event_from_message,
outbound_message_for_event,
replace_outbound_event,
)
@@ -52,7 +45,7 @@ def test_progress_event_lives_on_outbound_message_event_field() -> None:
assert msg.content == "working"
assert msg.metadata == {"origin_message_id": "m1"}
event = outbound_event_from_message(msg)
event = msg.event
assert isinstance(event, ProgressEvent)
assert event.content == "working"
assert event.tool_hint is True
@@ -65,169 +58,12 @@ def test_progress_event_lives_on_outbound_message_event_field() -> None:
def test_normal_outbound_message_has_no_runtime_event() -> None:
msg = OutboundMessage(channel="websocket", chat_id="chat-1", content="hello")
assert outbound_event_from_message(msg) is None
assert msg.event is None
def test_legacy_progress_metadata_flags_create_runtime_event() -> None:
tool_events = [{"phase": "start", "name": "read_file"}]
file_edit_events = [{"phase": "end", "path": "app.py"}]
msg = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="legacy progress",
metadata={
"_progress": True,
"_tool_hint": True,
"_reasoning_delta": True,
"_stream_id": "r1",
"_tool_events": tool_events,
"_file_edit_events": file_edit_events,
"message_id": "platform-routing-context",
},
)
event = outbound_event_from_message(msg)
assert isinstance(event, ProgressEvent)
assert event.content == "legacy progress"
assert event.tool_hint is True
assert event.reasoning_delta is True
assert event.stream_id == "r1"
assert event.tool_events == tool_events
assert event.file_edit_events == file_edit_events
def test_legacy_stream_metadata_flags_create_runtime_events() -> None:
delta = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="hello",
metadata={"_stream_delta": True, "_stream_id": "s1"},
)
end = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={
"_stream_end": True,
"_stream_id": "s1",
"_resuming": True,
"_merge_next": True,
},
)
delta_event = outbound_event_from_message(delta)
assert isinstance(delta_event, StreamDeltaEvent)
assert delta_event.content == "hello"
assert delta_event.stream_id == "s1"
end_event = outbound_event_from_message(end)
assert isinstance(end_event, StreamEndEvent)
assert end_event.stream_id == "s1"
assert end_event.resuming is True
assert end_event.merge_next is True
def test_legacy_webui_runtime_metadata_flags_create_runtime_events() -> None:
runtime = OutboundMessage(
channel="websocket",
chat_id="*",
content="",
metadata={
"_runtime_model_updated": True,
"model": "gpt-5.5",
"model_preset": "high",
},
)
goal_state = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={"_goal_state_sync": True, "goal_state": {"active": True}},
)
goal_status = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={"_goal_status": True, "goal_status": "running", "started_at": 1.25},
)
turn_end = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={"_turn_end": True, "latency_ms": 42.0, "goal_state": {"active": False}},
)
session_updated = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={"_session_updated": True, "_session_update_scope": "metadata"},
)
runtime_event = outbound_event_from_message(runtime)
assert isinstance(runtime_event, RuntimeModelUpdatedEvent)
assert runtime_event.model == "gpt-5.5"
assert runtime_event.model_preset == "high"
goal_state_event = outbound_event_from_message(goal_state)
assert isinstance(goal_state_event, GoalStateSyncEvent)
assert goal_state_event.goal_state == {"active": True}
goal_status_event = outbound_event_from_message(goal_status)
assert isinstance(goal_status_event, GoalStatusEvent)
assert goal_status_event.status == "running"
assert goal_status_event.started_at == 1.25
turn_end_event = outbound_event_from_message(turn_end)
assert isinstance(turn_end_event, TurnEndEvent)
assert turn_end_event.latency_ms == 42
assert turn_end_event.goal_state == {"active": False}
session_updated_event = outbound_event_from_message(session_updated)
assert isinstance(session_updated_event, SessionUpdatedEvent)
assert session_updated_event.scope == "metadata"
def test_legacy_metadata_numbers_ignore_bool_values() -> None:
goal_status = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={"_goal_status": True, "goal_status": "running", "started_at": True},
)
turn_end = OutboundMessage(
channel="websocket",
chat_id="chat-1",
content="",
metadata={"_turn_end": True, "latency_ms": True},
)
goal_status_event = outbound_event_from_message(goal_status)
assert isinstance(goal_status_event, GoalStatusEvent)
assert goal_status_event.started_at is None
turn_end_event = outbound_event_from_message(turn_end)
assert isinstance(turn_end_event, TurnEndEvent)
assert turn_end_event.latency_ms is None
def test_legacy_retry_wait_and_streamed_flags_create_runtime_events() -> None:
retry = OutboundMessage(
channel="cli",
chat_id="direct",
content="waiting",
metadata={"_retry_wait": True},
)
streamed = OutboundMessage(
channel="cli",
chat_id="direct",
content="final answer",
metadata={"_streamed": True},
)
retry_event = outbound_event_from_message(retry)
assert isinstance(retry_event, RetryWaitEvent)
assert retry_event.content == "waiting"
assert isinstance(outbound_event_from_message(streamed), StreamedResponseEvent)
def test_replace_outbound_event_keeps_routing_metadata() -> None:
@@ -261,4 +97,4 @@ def test_streamed_response_event_keeps_final_content_outside_event_payload() ->
)
assert msg.content == "final answer"
assert isinstance(outbound_event_from_message(msg), StreamedResponseEvent)
assert isinstance(msg.event, StreamedResponseEvent)
+102 -7
View File
@@ -1,8 +1,11 @@
import asyncio
import pytest
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import ProgressEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import (
RuntimeEventBus,
RuntimeEventContext,
RuntimeEventPublisher,
RuntimeModelChanged,
@@ -15,9 +18,101 @@ from nanobot.bus.runtime_events import (
from nanobot.providers.base import LLMUsage
async def test_local_state_subscriber_does_not_block_routed_delivery():
bus = MessageBus()
entered, release = asyncio.Event(), asyncio.Event()
async def observe(event):
entered.set()
await release.wait()
bus.subscribe(observe, RuntimeModelChanged)
dispatch = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))
try:
await asyncio.wait_for(entered.wait(), timeout=1)
await asyncio.wait_for(
bus.publish_event(ProgressEvent(content="working"), channel="cli", chat_id="other"),
timeout=1,
)
message = await asyncio.wait_for(bus.consume_outbound(), timeout=1)
assert (message.chat_id, message.content) == ("other", "working")
assert not dispatch.done()
finally:
release.set()
await dispatch
async def test_disconnect_skips_a_handler_in_an_existing_dispatch_snapshot():
bus = MessageBus()
seen = []
def first(event):
disconnect()
bus.subscribe(first)
disconnect = bus.subscribe(seen.append)
await bus.publish(RuntimeModelChanged("model", None))
disconnect()
assert seen == []
async def test_awaited_dispatch_preserves_order_and_propagates_cancellation():
bus = MessageBus()
entered, release = asyncio.Event(), asyncio.Event()
seen = []
async def slow(event):
entered.set()
await release.wait()
seen.append("first")
bus.subscribe(slow)
bus.subscribe(lambda event: seen.append("second"))
task = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))
await entered.wait()
assert not task.done()
assert seen == []
release.set()
await task
assert seen == ["first", "second"]
release.clear()
entered.clear()
task = asyncio.create_task(bus.publish(RuntimeModelChanged("model", None)))
await entered.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert seen == ["first", "second"]
async def test_scheduled_dispatch_is_owned_and_can_be_drained():
bus = MessageBus()
entered, release = asyncio.Event(), asyncio.Event()
seen = []
async def slow(event):
entered.set()
await release.wait()
seen.append(event.model)
bus.subscribe(slow, RuntimeModelChanged)
task = bus.publish_nowait(RuntimeModelChanged("model", None))
assert task is not None
assert not entered.is_set()
await entered.wait()
draining = asyncio.create_task(bus.drain())
assert seen == []
release.set()
await draining
assert task.done()
assert seen == ["model"]
await bus.drain()
@pytest.mark.asyncio
async def test_runtime_event_bus_filters_by_event_type() -> None:
bus = RuntimeEventBus()
bus = MessageBus()
seen: list[str] = []
async def handle_run_status(event: TurnRunStatusChanged) -> None:
@@ -42,7 +137,7 @@ async def test_runtime_event_bus_filters_by_event_type() -> None:
@pytest.mark.asyncio
async def test_runtime_event_bus_keeps_catch_all_subscription() -> None:
bus = RuntimeEventBus()
bus = MessageBus()
seen: list[str] = []
def handle_any(event) -> None:
@@ -57,7 +152,7 @@ async def test_runtime_event_bus_keeps_catch_all_subscription() -> None:
@pytest.mark.asyncio
async def test_runtime_event_publisher_builds_context_from_inbound_message() -> None:
bus = RuntimeEventBus()
bus = MessageBus()
seen: list[object] = []
publisher = RuntimeEventPublisher(bus)
msg = InboundMessage(
@@ -93,7 +188,7 @@ async def test_runtime_event_publisher_builds_context_from_inbound_message() ->
@pytest.mark.asyncio
async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> None:
bus = RuntimeEventBus()
bus = MessageBus()
seen: list[object] = []
publisher = RuntimeEventPublisher(bus)
@@ -134,7 +229,7 @@ async def test_runtime_event_publisher_consumes_turn_metadata_on_complete() -> N
@pytest.mark.asyncio
async def test_runtime_event_publisher_exposes_admitted_runtime() -> None:
bus = RuntimeEventBus()
bus = MessageBus()
seen: list[object] = []
publisher = RuntimeEventPublisher(bus)
msg = InboundMessage(
@@ -165,7 +260,7 @@ async def test_runtime_event_publisher_exposes_admitted_runtime() -> None:
@pytest.mark.asyncio
async def test_runtime_event_publisher_emits_persisted_turn_attributes() -> None:
bus = RuntimeEventBus()
bus = MessageBus()
seen: list[object] = []
publisher = RuntimeEventPublisher(bus)
msg = InboundMessage(
@@ -0,0 +1,187 @@
import asyncio
from unittest.mock import AsyncMock, MagicMock
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels import manager as manager_module
from nanobot.channels.base import BaseChannel
from nanobot.channels.manager import ChannelManager
from nanobot.config.schema import Config
def make_manager():
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
manager = ChannelManager(config, MessageBus())
channel = MagicMock(spec=BaseChannel)
channel.send = AsyncMock()
channel.stop = AsyncMock()
manager.channels["websocket"] = channel
return manager, channel
async def wait_until(predicate):
async with asyncio.timeout(2):
while not predicate():
await asyncio.sleep(0)
async def test_ten_chats_keep_order_while_one_destination_is_blocked():
manager, channel = make_manager()
release = asyncio.Event()
started = asyncio.Event()
received = {str(i): [] for i in range(10)}
async def send(msg):
if msg.chat_id == "0":
started.set()
await release.wait()
received[msg.chat_id].append(msg.content)
channel.send.side_effect = send
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
try:
for content in ("first", "last"):
for i in range(10):
await manager.bus.publish_outbound(OutboundMessage("websocket", str(i), content))
await asyncio.wait_for(started.wait(), 2)
await wait_until(lambda: all(len(received[str(i)]) == 2 for i in range(1, 10)))
assert received["0"] == []
assert all(received[str(i)] == ["first", "last"] for i in range(1, 10))
release.set()
await wait_until(lambda: not manager._outbound_tasks)
assert received["0"] == ["first", "last"]
assert manager._outbound_tails == {}
finally:
await manager.stop_all()
async def test_retry_does_not_block_other_chats(monkeypatch):
monkeypatch.setattr(manager_module, "_SEND_RETRY_DELAYS", (0.1,))
manager, channel = make_manager()
retry_started = asyncio.Event()
healthy_sent = asyncio.Event()
attempts = 0
async def send(msg):
nonlocal attempts
if msg.chat_id == "retry":
attempts += 1
if attempts == 1:
retry_started.set()
raise OSError("temporary failure")
assert healthy_sent.is_set()
else:
healthy_sent.set()
channel.send.side_effect = send
channel.should_retry_send_error.return_value = True
try:
await manager._queue_outbound(channel, OutboundMessage("websocket", "retry", "a"))
await asyncio.wait_for(retry_started.wait(), 2)
await manager._queue_outbound(channel, OutboundMessage("websocket", "healthy", "b"))
await wait_until(lambda: not manager._outbound_tasks)
assert attempts == 2
assert healthy_sent.is_set()
finally:
await manager._cancel_outbound()
async def test_pending_and_concurrent_sends_are_bounded_and_cancellable(monkeypatch):
monkeypatch.setattr(manager_module, "_OUTBOUND_PENDING_LIMIT", 4)
monkeypatch.setattr(manager_module, "_OUTBOUND_CONCURRENCY", 2)
manager, channel = make_manager()
blocked = asyncio.Event()
active = 0
peak = 0
async def send(msg):
nonlocal active, peak
active += 1
peak = max(peak, active)
try:
await blocked.wait()
finally:
active -= 1
channel.send.side_effect = send
for i in range(4):
await manager._queue_outbound(channel, OutboundMessage("websocket", str(i), "a"))
extra = asyncio.create_task(manager._queue_outbound(
channel, OutboundMessage("websocket", "extra", "a"),
))
try:
await wait_until(lambda: active == 2)
assert not extra.done()
assert len(manager._outbound_tasks) == 4
extra.cancel()
await asyncio.gather(extra, return_exceptions=True)
await manager._cancel_outbound()
assert peak == 2
assert active == 0
assert not manager._outbound_tasks
assert not manager._outbound_tails
# Cancellation returns admission permits, including tasks not yet sending.
for i in range(4):
await asyncio.wait_for(manager._queue_outbound(
channel, OutboundMessage("websocket", str(i), "b"),
), 2)
finally:
extra.cancel()
await asyncio.gather(extra, return_exceptions=True)
await manager._cancel_outbound()
async def test_channel_stop_cancels_only_its_sends_before_stopping_runtime():
manager, channel = make_manager()
active = asyncio.Event()
cancelled = asyncio.Event()
async def send(msg):
active.set()
try:
await asyncio.Event().wait()
finally:
cancelled.set()
async def stop():
assert cancelled.is_set()
channel.send.side_effect = send
channel.stop.side_effect = stop
other = MagicMock(spec=BaseChannel)
other.send = AsyncMock()
manager.channels["other"] = other
await manager._queue_outbound(channel, OutboundMessage("websocket", "a", "1"))
await asyncio.wait_for(active.wait(), 2)
await manager._stop_channel("websocket")
await manager._queue_outbound(other, OutboundMessage("other", "b", "2"))
await wait_until(lambda: not manager._outbound_tasks)
other.send.assert_awaited_once()
assert not manager._outbound_tails
async def test_dispatcher_shutdown_cleans_active_and_waiting_destination_tasks():
manager, channel = make_manager()
active = asyncio.Event()
cancelled = asyncio.Event()
async def send(msg):
active.set()
try:
await asyncio.Event().wait()
finally:
cancelled.set()
channel.send.side_effect = send
manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
try:
for content in ("one", "two", "three"):
await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", content))
await asyncio.wait_for(active.wait(), 2)
await wait_until(lambda: len(manager._outbound_tasks) == 3)
finally:
await manager.stop_all()
assert cancelled.is_set()
channel.send.assert_awaited_once()
assert not manager._outbound_tasks
assert not manager._outbound_tails
@@ -11,7 +11,6 @@ from nanobot.bus.outbound_events import (
RetryWaitEvent,
StreamDeltaEvent,
StreamEndEvent,
outbound_event_from_message,
outbound_message_for_event,
)
from nanobot.bus.queue import MessageBus
@@ -120,13 +119,13 @@ class TestDeltaCoalescing:
async def process_one():
try:
m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)
event = outbound_event_from_message(m)
event = m.event
if isinstance(event, StreamDeltaEvent):
m, pending = manager._coalesce_stream_deltas(m)
for p in pending:
await bus.publish_outbound(p)
channel = manager.channels.get(m.channel)
event = outbound_event_from_message(m)
event = m.event
if channel and isinstance(event, StreamDeltaEvent):
await channel.send_delta(
m.chat_id,
@@ -274,13 +273,13 @@ class TestDispatchOutboundWithCoalescing:
processed = []
msg = pending.pop(0) if pending else await bus.consume_outbound()
event = outbound_event_from_message(msg)
event = msg.event
if isinstance(event, StreamDeltaEvent):
msg, extra_pending = manager._coalesce_stream_deltas(msg)
pending.extend(extra_pending)
channel = manager.channels.get(msg.channel)
event = outbound_event_from_message(msg)
event = msg.event
if channel and isinstance(event, StreamDeltaEvent):
await channel.send_delta(
msg.chat_id,
@@ -394,38 +393,6 @@ class TestProgressFiltering:
assert send_mock.await_count == 1
assert send_mock.await_args_list[0].args[0].content == "final answer"
@pytest.mark.asyncio
async def test_legacy_progress_flag_uses_runtime_progress_filter(self, manager, bus):
manager.channels["mock"].send_progress = False
await bus.publish_outbound(OutboundMessage(
channel="mock",
chat_id="chat1",
content="legacy progress-shaped message",
metadata={"_progress": True},
))
await bus.publish_outbound(OutboundMessage(
channel="mock",
chat_id="chat1",
content="processing sentinel",
))
task = asyncio.create_task(manager._dispatch_outbound())
try:
for _ in range(30):
if manager.channels["mock"]._send_mock.await_count >= 1:
break
await asyncio.sleep(0.05)
finally:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
send_mock = manager.channels["mock"]._send_mock
assert send_mock.await_count == 1
assert send_mock.await_args.args[0].content == "processing sentinel"
@pytest.mark.asyncio
async def test_channel_override_can_enable_tool_hints(self, manager, bus):
manager.channels["mock"].send_tool_hints = True
@@ -23,7 +23,6 @@ import pytest
from nanobot.bus.events import OutboundMessage
from nanobot.bus.outbound_events import (
ProgressEvent,
outbound_event_from_message,
outbound_message_for_event,
)
from nanobot.bus.queue import MessageBus
@@ -282,7 +281,7 @@ async def _pump_one(manager: ChannelManager) -> None:
"""Process currently queued messages through the reasoning dispatch branch."""
async def dispatch_one(msg: OutboundMessage) -> None:
event = outbound_event_from_message(msg)
event = msg.event
if isinstance(event, ProgressEvent) and (
event.reasoning_delta
or event.reasoning_end
+6
View File
@@ -3534,6 +3534,8 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
ch = _StartableChannel(fake_config, mgr.bus)
mgr.channels = {"startable": ch}
mgr._channel_tasks = {}
mgr._outbound_tasks = {}
mgr._stopping_channels = set()
# Create a real cancelled task
async def dummy_task():
@@ -3612,6 +3614,8 @@ async def test_stop_all_handles_channel_exception():
mgr.bus = MessageBus()
mgr.channels = {"stopfailing": _StopFailingChannel(fake_config, mgr.bus)}
mgr._channel_tasks = {}
mgr._outbound_tasks = {}
mgr._stopping_channels = set()
mgr._dispatch_task = None
# Should not raise even if channel.stop() raises
@@ -3651,6 +3655,8 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
"next": next_channel,
}
mgr._channel_tasks = {}
mgr._outbound_tasks = {}
mgr._stopping_channels = set()
mgr._dispatch_task = None
await mgr.stop_all()
+9 -8
View File
@@ -17,6 +17,7 @@ from nanobot.agent.memory import MemoryStore
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.cli import commands as cli_commands
from nanobot.cli import gateway_runtime as cli_gateway_runtime
from nanobot.cli import provider as provider_commands
@@ -2871,7 +2872,7 @@ def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
)
monkeypatch.setattr("nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
@@ -2938,7 +2939,7 @@ def test_gateway_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path:
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
cron_service=_StopCron,
)
@@ -3290,7 +3291,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
config.agents.defaults.workspace = str(tmp_path / "config-workspace")
config.agents.defaults.dream.enabled = False
config.gateway.heartbeat.enabled = False
bus = MagicMock()
bus = MessageBus()
seen: dict[str, object] = {}
_patch_cli_command_runtime(
@@ -3444,7 +3445,7 @@ def test_gateway_workspace_override_does_not_migrate_legacy_cron(
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
cron_service=_StopCron,
get_cron_dir=lambda: legacy_dir,
@@ -3483,7 +3484,7 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
cron_service=_StopCron,
get_cron_dir=lambda: legacy_dir,
@@ -3684,7 +3685,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
)
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
@@ -3895,7 +3896,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
)
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
@@ -4024,7 +4025,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=lambda: object(),
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
)
monkeypatch.setattr("nanobot.cli.gateway_runtime.AgentLoop", _FakeAgentLoop)
+3 -3
View File
@@ -98,7 +98,7 @@ async def test_empty_compact_finishes_silently_and_does_not_schedule_idle_archiv
session.add_message("assistant", "Nothing to compact.", _command=True)
loop.sessions.save(session)
completions = []
loop.runtime_events.subscribe(completions.append, TurnCompleted)
loop.bus.subscribe(completions.append, TurnCompleted)
await loop._dispatch(InboundMessage(
channel="websocket", sender_id="user", chat_id="test", content="/compact",
@@ -155,7 +155,7 @@ async def test_stop_completes_a_compact_command_waiting_for_the_session_lock(loo
metadata={"webui_turn_id": "queued-compact"},
)
completions = []
loop.runtime_events.subscribe(completions.append, TurnCompleted)
loop.bus.subscribe(completions.append, TurnCompleted)
async with loop._get_session_lock(key):
await loop._dispatch_command_inline(msg, key, msg.content, loop.commands.dispatch)
reply = await cmd_stop(CommandContext(
@@ -181,7 +181,7 @@ async def test_stop_finishes_inflight_compaction_as_cancelled(loop) -> None:
loop.provider.chat_with_retry.side_effect = wait_for_cancel
completions = []
loop.runtime_events.subscribe(completions.append, TurnCompleted)
loop.bus.subscribe(completions.append, TurnCompleted)
msg = InboundMessage(
channel="websocket", sender_id="user", chat_id="test", content="/compact",
metadata={"webui_turn_id": "compact-turn"},
+2 -1
View File
@@ -517,11 +517,12 @@ async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:
async def test_process_direct_accepts_media() -> None:
"""process_direct should forward media paths to _process_message."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import RuntimeEventPublisher
loop = AgentLoop.__new__(AgentLoop)
loop._session_locks = {}
loop.runtime_event_publisher = RuntimeEventPublisher()
loop.runtime_event_publisher = RuntimeEventPublisher(MessageBus())
captured_msg = None
+2 -1
View File
@@ -12,6 +12,7 @@ from nanobot.agent.tools.message import MessageTool
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import LLMResponse, ToolCallRequest
from nanobot.utils.progress_events import output_events
def _make_loop(tmp_path: Path) -> AgentLoop:
@@ -181,7 +182,7 @@ class TestMessageToolSuppressLogic:
result = await loop._run_agent_loop(
TranscriptInput(history=[], current_message=None),
runtime=loop.llm_runtime(),
on_progress=on_progress,
events=output_events(on_progress=on_progress),
)
assert result.final_content == "Done"
+37 -16
View File
@@ -7,8 +7,8 @@ import pytest
from nanobot.agent.tools.context import RequestContext, request_context
from nanobot.bus.events import InboundMessage
from nanobot.bus.outbound_events import GoalStatusEvent, TurnModelUpdatedEvent, UserInputEvent
from nanobot.bus.queue import MessageBus
from nanobot.bus.runtime_events import (
RuntimeEventBus,
RuntimeEventContext,
TurnRuntimeAdmitted,
UserInputAccepted,
@@ -37,7 +37,7 @@ def _clear_turn_wall_clock() -> None:
@pytest.mark.asyncio
async def test_publish_turn_run_status_running_records_wall_clock() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
msg = InboundMessage(
channel="websocket",
@@ -61,7 +61,7 @@ async def test_publish_turn_run_status_running_records_wall_clock() -> None:
@pytest.mark.asyncio
async def test_publish_turn_run_status_reuses_explicit_wall_clock() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
msg = InboundMessage(channel="websocket", sender_id="u", chat_id="chat-a", content="hi")
@@ -75,7 +75,7 @@ async def test_publish_turn_run_status_reuses_explicit_wall_clock() -> None:
@pytest.mark.asyncio
async def test_publish_turn_run_status_idle_retains_registry_until_delivery() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
msg = InboundMessage(
channel="websocket",
@@ -110,7 +110,7 @@ def test_clear_websocket_turn_only_clears_matching_owner() -> None:
@pytest.mark.asyncio
async def test_ownerless_turns_receive_distinct_internal_owners() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
first = InboundMessage(
channel="websocket",
@@ -139,7 +139,7 @@ async def test_ownerless_turns_receive_distinct_internal_owners() -> None:
@pytest.mark.asyncio
async def test_publish_turn_run_status_non_websocket_noop_registry() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
msg = InboundMessage(channel="telegram", sender_id="u", chat_id="1", content="hi")
@@ -151,7 +151,7 @@ async def test_publish_turn_run_status_non_websocket_noop_registry() -> None:
@pytest.mark.asyncio
async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
observer = wth.build_webui_fallback_model_observer(bus)
@@ -182,16 +182,38 @@ async def test_fallback_model_is_scoped_to_its_websocket_chat() -> None:
@pytest.mark.asyncio
async def test_coordinator_connections_end_on_scope_exit_and_can_reconnect(tmp_path):
from nanobot.bus.runtime_events import RuntimeModelChanged
bus = MessageBus()
bus.publish_outbound = AsyncMock()
coordinator = wth.WebuiTurnCoordinator(
bus=bus, sessions=SessionManager(tmp_path),
schedule_background=lambda coro: coro.close(),
)
event = RuntimeModelChanged("model", None)
with pytest.raises(RuntimeError, match="shutdown"):
with coordinator.connected():
await bus.publish(event)
raise RuntimeError("shutdown")
bus.publish_outbound.assert_awaited_once()
await bus.publish(event)
bus.publish_outbound.assert_awaited_once()
with coordinator.connected():
bus.publish_nowait(event)
await bus.drain()
assert bus.publish_outbound.await_count == 2
async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path) -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
runtime_events = RuntimeEventBus()
coordinator = wth.WebuiTurnCoordinator(
bus=bus,
sessions=SessionManager(tmp_path),
schedule_background=lambda coro: coro.close(),
)
coordinator.subscribe(runtime_events)
coordinator.subscribe()
runtime = LLMRuntime(
provider=MagicMock(),
model="openai-codex/gpt-5.6",
@@ -200,7 +222,7 @@ async def test_admitted_runtime_publishes_chat_scoped_model_and_preset(tmp_path)
model_preset="Codex",
)
await runtime_events.publish(
await bus.publish(
TurnRuntimeAdmitted(
context=RuntimeEventContext(
channel="websocket",
@@ -225,7 +247,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
tmp_path,
monkeypatch,
) -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
sessions = SessionManager(tmp_path)
target_session = sessions.get_or_create("websocket:target")
@@ -242,15 +264,14 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
}
append_input = MagicMock()
monkeypatch.setattr(wth, "append_session_message_input", append_input)
runtime_events = RuntimeEventBus()
coordinator = wth.WebuiTurnCoordinator(
bus=bus,
sessions=sessions,
schedule_background=lambda coro: coro.close(),
)
coordinator.subscribe(runtime_events)
coordinator.subscribe()
await runtime_events.publish(UserInputAccepted(
await bus.publish(UserInputAccepted(
context=RuntimeEventContext(
channel="system",
chat_id="websocket:target",
@@ -274,7 +295,7 @@ async def test_session_input_is_projected_by_the_webui_coordinator(
@pytest.mark.asyncio
async def test_fallback_model_ignores_non_websocket_requests() -> None:
bus = MagicMock()
bus = MessageBus()
bus.publish_outbound = AsyncMock()
observer = wth.build_webui_fallback_model_observer(bus)
+12
View File
@@ -76,6 +76,18 @@ def test_inspect_webui_bundle_detects_channel_owned_ui_source(tmp_path: Path) ->
assert status.newest_source == channel_ui
def test_shared_notifications_make_existing_bundle_stale(tmp_path: Path) -> None:
source = tmp_path / "webui"
dist = tmp_path / "nanobot/web/dist"
shared = tmp_path / "packages/client-events/notifications.ts"
_touch(source / "package.json", mtime_ns=10)
_touch(dist / "index.html", mtime_ns=20)
_touch(shared, mtime_ns=30)
status = inspect_webui_bundle(source_dir=source, dist_dir=dist)
assert status.needs_build
assert status.newest_source == shared
def test_channel_owned_ui_sources_are_included_in_distributions() -> None:
project_root = Path(__file__).resolve().parents[2]
pyproject = tomllib.loads((project_root / "pyproject.toml").read_text(encoding="utf-8"))
+34
View File
@@ -0,0 +1,34 @@
import importlib.util
import io
import json
import tarfile
from pathlib import Path
from nanobot.events import ContextCompactionEvent, RecoveryStateEvent
from nanobot.webui.outbound_wire import project_notification
ROOT = Path(__file__).resolve().parents[2]
def test_wire_fixtures_are_real_python_projections():
fixtures = json.loads((ROOT / "packages/client-events/fixtures.json").read_text())
for expected in fixtures:
fields = {key: value for key, value in expected.items() if key not in {"event", "chat_id"}}
event_type = (
ContextCompactionEvent if expected["event"] == "context_compaction" else RecoveryStateEvent
)
projection = project_notification(expected["chat_id"], event_type(**fields))
assert projection is not None
assert projection.payload == expected
def test_tui_source_archive_preserves_shared_module_import_path():
spec = importlib.util.spec_from_file_location("package_release", ROOT / "tui/scripts/package-release.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with tarfile.open(fileobj=io.BytesIO(module._source_archive(ROOT / "tui"))) as archive:
names = set(archive.getnames())
assert "nanobot-tui-source/tui/src/protocol.ts" in names
assert "nanobot-tui-source/packages/client-events/notifications.ts" in names
assert "nanobot-tui-source/tui/bun.lock" in names
assert "nanobot-tui-source/LICENSE" in names