Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
test: replace false-green checks with behavioral coverage (#6282)
chengyongru74942bd1904b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 36fdc7e7e..24dc9aca7 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -316,6 +316,14 @@ jobs:working-directory: webuirun: bun run test:coverage+ - name: Install browser for layout regressions+ working-directory: webui+ run: bun x playwright install --with-deps chromium++ - name: Test browser layout and history motion+ working-directory: webui+ run: bun run test:browser+- name: Build WebUIworking-directory: webuirun: bun run builddiff --git a/nanobot/channels/feishu/tests/test_feishu_domain.py b/nanobot/channels/feishu/tests/test_feishu_domain.pyindex 898a8d226..8b542cdd6 100644--- a/nanobot/channels/feishu/tests/test_feishu_domain.py+++ b/nanobot/channels/feishu/tests/test_feishu_domain.py@@ -1,5 +1,7 @@"""Tests for Feishu/Lark domain configuration."""-from unittest.mock import MagicMock+from unittest.mock import ANY, AsyncMock, MagicMock++import pytestfrom nanobot.bus.queue import MessageBusfrom nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig@@ -44,3 +46,46 @@ class TestFeishuConfigDomain:def test_channel_persists_feishu_domain_from_config(self):ch = _make_channel(domain="feishu")assert ch.config.domain == "feishu"++[email protected]("domain, expected_domain", [+ ("feishu", "https://open.feishu.cn"),+ ("lark", "https://open.larksuite.com"),+])+async def test_start_selects_domain_for_http_and_websocket_sdk_clients(+ domain, expected_domain, monkeypatch, tmp_path,+):+ lark = pytest.importorskip("lark_oapi")+ # Startup must never persist fixture credentials into the active host config.+ monkeypatch.setattr("nanobot.config.loader.get_config_path", lambda: tmp_path / "config.json")+ monkeypatch.setattr(+ "nanobot.channels.feishu.runtime.sync_saved_feishu_identity_boundary",+ lambda **_kwargs: False,+ )+ builder = MagicMock()+ for method in ("app_id", "app_secret", "domain", "log_level"):+ getattr(builder, method).return_value = builder+ monkeypatch.setattr(lark.Client, "builder", lambda: builder)+ ws_client = MagicMock()+ monkeypatch.setattr(lark.ws, "Client", ws_client)+ ch = _make_channel(domain)++ async def started(*_args):+ ch._running = False++ # Keep production start/domain selection, but never open an SDK connection.+ ch._ws_runner = MagicMock(start_client=AsyncMock(side_effect=started), stop_client=AsyncMock())+ monkeypatch.setattr(ch, "_fetch_bot_open_id", lambda: None)+ try:+ await ch.start()+ builder.domain.assert_called_once_with(expected_domain)+ ws_client.assert_called_once_with(+ "cli_test", "secret", domain=expected_domain,+ event_handler=ANY,+ log_level=lark.LogLevel.INFO,+ )+ assert ch._client is builder.build.return_value+ ch._ws_runner.start_client.assert_awaited_once_with(ch.name, ws_client.return_value)+ finally:+ await ch.stop()diff --git a/nanobot/channels/feishu/tests/test_feishu_reaction.py b/nanobot/channels/feishu/tests/test_feishu_reaction.pyindex 94bcf92a9..7b5b21135 100644--- a/nanobot/channels/feishu/tests/test_feishu_reaction.py+++ b/nanobot/channels/feishu/tests/test_feishu_reaction.py@@ -9,7 +9,7 @@ import pytestpytest.importorskip("lark_oapi")from nanobot.bus.queue import MessageBus-from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig, _FeishuStreamBuf+from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfigdef _make_channel() -> FeishuChannel:@@ -187,12 +187,7 @@ class TestStreamEndReactionCleanup:@pytest.mark.asyncioasync def test_removes_reaction_on_stream_end(self):ch = _make_channel()- ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(- text="Done", card_id="card_1", sequence=3, last_edit=0.0,- )- ch._reaction_ids["om_001"] = "rx_42"- ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))- ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))+ ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})ch._remove_reaction = AsyncMock()await ch.send_delta(@@ -201,33 +196,23 @@ class TestStreamEndReactionCleanup:stream_end=True,)- ch._remove_reaction.assert_called_once_with("om_001", "rx_42")+ ch._remove_reaction.assert_awaited_once_with("om_001", "rx_42")+ assert ch._reaction_ids == {"om_other": "rx_other"}@pytest.mark.asyncioasync def test_no_removal_when_message_id_missing(self):ch = _make_channel()- ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(- text="Done", card_id="card_1", sequence=3, last_edit=0.0,- )- ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))- ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))+ ch._reaction_ids["om_001"] = "rx_42"ch._remove_reaction = AsyncMock()- await ch.send_delta(- "oc_chat1", "",- stream_end=True,- )+ await ch.send_delta("oc_chat1", "", stream_end=True)- ch._remove_reaction.assert_not_called()+ ch._remove_reaction.assert_not_awaited()+ assert ch._reaction_ids == {"om_001": "rx_42"}@pytest.mark.asyncioasync def test_no_removal_when_reaction_id_missing(self):ch = _make_channel()- ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(- text="Done", card_id="card_1", sequence=3, last_edit=0.0,- )- ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))- ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))ch._remove_reaction = AsyncMock()await ch.send_delta(@@ -241,26 +226,29 @@ class TestStreamEndReactionCleanup:@pytest.mark.asyncioasync def test_no_removal_when_not_stream_end(self):ch = _make_channel()+ ch._reaction_ids["om_001"] = "rx_42"+ ch._create_streaming_card_sync = MagicMock(return_value=None)ch._remove_reaction = AsyncMock()+ ch._add_reaction = AsyncMock()+ ch.config.done_emoji = "DONE"await ch.send_delta("oc_chat1", "more text",- metadata={"message_id": "om_001", "reaction_id": "rx_42"},+ metadata={"message_id": "om_001"},)- ch._remove_reaction.assert_not_called()+ ch._remove_reaction.assert_not_awaited()+ ch._add_reaction.assert_not_awaited()+ assert ch._reaction_ids == {"om_001": "rx_42"}+ assert ch._stream_bufs["om_001"].text == "more text"+ assert "oc_chat1" not in ch._stream_bufs@pytest.mark.asyncioasync def test_no_removal_when_resuming(self):"""resuming=True means more tool-call rounds follow; reaction must persist."""ch = _make_channel()ch.config.done_emoji = "DONE"- ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(- text="partial", card_id="card_1", sequence=3, last_edit=0.0,- )ch._reaction_ids["om_001"] = "rx_42"- ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))- ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))ch._remove_reaction = AsyncMock()ch._add_reaction = AsyncMock()@@ -281,12 +269,7 @@ class TestStreamEndReactionCleanup:"""Across resuming rounds, done_emoji is added only on the final round."""ch = _make_channel()ch.config.done_emoji = "DONE"- ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(- text="t", card_id="card_1", sequence=3, last_edit=0.0,- )- ch._reaction_ids["om_001"] = "rx_42"- ch._client.cardkit.v1.card_element.content.return_value = MagicMock(success=MagicMock(return_value=True))- ch._client.cardkit.v1.card.settings.return_value = MagicMock(success=MagicMock(return_value=True))+ ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})ch._remove_reaction = AsyncMock()ch._add_reaction = AsyncMock()@@ -300,10 +283,8 @@ class TestStreamEndReactionCleanup:ch._remove_reaction.assert_not_called()ch._add_reaction.assert_not_called()- # Re-prime the stream buffer for the final round (the previous stream end popped it).- ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(- text="t", card_id="card_1", sequence=5, last_edit=0.0,- )+ assert ch._reaction_ids == {"om_001": "rx_42", "om_other": "rx_other"}+# Final stream end (resuming=False): OnIt removed, done_emoji added.await ch.send_delta("oc_chat1", "",@@ -311,5 +292,6 @@ class TestStreamEndReactionCleanup:stream_end=True,resuming=False,)- ch._remove_reaction.assert_called_once_with("om_001", "rx_42")- ch._add_reaction.assert_called_once_with("om_001", "DONE")+ ch._remove_reaction.assert_awaited_once_with("om_001", "rx_42")+ ch._add_reaction.assert_awaited_once_with("om_001", "DONE")+ assert ch._reaction_ids == {"om_other": "rx_other"}diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsxindex 39c817911..ed1a94b0e 100644--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx@@ -1,3 +1,5 @@+import { vi } from "vitest";+import { channelUiContribution } from "@/channel-plugins/registry";import { NanobotClient } from "@/lib/nanobot-client";import type { ConnectionStatus } from "@/lib/types";@@ -253,16 +255,21 @@ describe("Linear channel UI", () => {requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));renderSettingsView({ initialSection: "channels" });fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));- fireEvent.change(await screen.findByRole("textbox", { name: "OAuth client ID" }), {- target: { value: "replacement-client" },- });- fireEvent.blur(screen.getByRole("textbox", { name: "OAuth client ID" }));- expect(await screen.findByText("Unable to save settings")).toBeVisible();- expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toHaveValue("replacement-client");- expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();- await new Promise((resolve) => setTimeout(resolve, 750));- expect(actionCalls()).toHaveLength(1);- expect(actionCalls()[0][1]).not.toHaveProperty("enable");+ const input = await screen.findByRole("textbox", { name: "OAuth client ID" });+ vi.useFakeTimers();+ try {+ fireEvent.change(input, { target: { value: "replacement-client" } });+ fireEvent.blur(input);+ await act(async () => { await vi.advanceTimersByTimeAsync(750); });+ expect(screen.getByText("Unable to save settings")).toBeVisible();+ expect(input).toHaveValue("replacement-client");+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();+ await act(async () => { await vi.advanceTimersByTimeAsync(750); });+ expect(actionCalls()).toHaveLength(1);+ expect(actionCalls()[0][1]).not.toHaveProperty("enable");+ } finally {+ vi.useRealTimers();+ }});it("replaces a saved secret only on explicit save and submits just that field", async () => {@@ -280,10 +287,15 @@ describe("Linear channel UI", () => {fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));const input = screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });expect(input).toHaveFocus();- fireEvent.change(input, { target: { value: "replacement-secret" } });- fireEvent.blur(input);- await new Promise((resolve) => setTimeout(resolve, 750));- expect(actionCalls()).toHaveLength(0);+ vi.useFakeTimers();+ try {+ fireEvent.change(input, { target: { value: "replacement-secret" } });+ fireEvent.blur(input);+ await act(async () => { await vi.advanceTimersByTimeAsync(750); });+ expect(actionCalls()).toHaveLength(0);+ } finally {+ vi.useRealTimers();+ }fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));await waitFor(() => expect(actionCalls()).toHaveLength(1));const params = actionCalls()[0][1] as { values: Record<string, unknown> };@@ -300,14 +312,19 @@ describe("Linear channel UI", () => {fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));- fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {- target: { value: "discarded-draft" },- });- fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));- expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);- expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();- await new Promise(resolve => setTimeout(resolve, 750));- expect(actionCalls()).toHaveLength(0);+ vi.useFakeTimers();+ try {+ fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {+ target: { value: "discarded-draft" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));+ expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);+ expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();+ await act(async () => { await vi.advanceTimersByTimeAsync(750); });+ expect(actionCalls()).toHaveLength(0);+ } finally {+ vi.useRealTimers();+ }fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("");});diff --git a/nanobot/channels/matrix/tests/test_matrix_channel.py b/nanobot/channels/matrix/tests/test_matrix_channel.pyindex b17a5561c..31ce7a5ee 100644--- a/nanobot/channels/matrix/tests/test_matrix_channel.py+++ b/nanobot/channels/matrix/tests/test_matrix_channel.py@@ -951,14 +951,30 @@ async def test_typing_keepalive_refreshes_periodically(monkeypatch) -> None:channel._running = Truemonkeypatch.setattr(matrix_module, "TYPING_KEEPALIVE_INTERVAL_MS", 10)-- await channel._start_typing_keepalive("!room:matrix.org")- await asyncio.sleep(0.03)- await channel._stop_typing_keepalive("!room:matrix.org", clear_typing=True)+ refreshed = asyncio.Event()+ room_typing = client.room_typing++ async def record_typing(**kwargs):+ response = await room_typing(**kwargs)+ if len([call for call in client.typing_calls if call[1] is True]) >= 2:+ refreshed.set()+ return response++ monkeypatch.setattr(client, "room_typing", record_typing)+ task = None+ try:+ await channel._start_typing_keepalive("!room:matrix.org")+ task = channel._typing_tasks["!room:matrix.org"]+ await asyncio.wait_for(refreshed.wait(), timeout=5)+ finally:+ channel._running = False+ await channel._stop_typing_keepalive("!room:matrix.org", clear_typing=True)true_updates = [call for call in client.typing_calls if call[1] is True]assert len(true_updates) >= 2assert client.typing_calls[-1] == ("!room:matrix.org", False, TYPING_NOTICE_TIMEOUT_MS)+ assert task is not None and task.done()+ assert not channel._typing_tasks@pytest.mark.asyncio@@ -1365,10 +1381,14 @@ async def test_on_media_message_sets_thread_metadata_when_threaded_event(monkeypatch.setattr("nanobot.channels.matrix.runtime.get_data_dir", lambda: tmp_path)channel = MatrixChannel(_make_config(), MessageBus())- client = _FakeAsyncClient("", "", "", None)- client.download_bytes = b"image"- channel.client = client+ channel.client = _FakeAsyncClient("", "", "", None)+ downloads: list[tuple[str, int]] = []+ async def _download_media_bytes(mxc_url: str, limit_bytes: int) -> bytes:+ downloads.append((mxc_url, limit_bytes))+ return b"image"++ monkeypatch.setattr(channel, "_download_media_bytes", _download_media_bytes)handled: list[dict[str, object]] = []async def _fake_handle_message(**kwargs) -> None:@@ -1396,8 +1416,15 @@ async def test_on_media_message_sets_thread_metadata_when_threaded_event(await channel._on_media_message(room, event)+ assert len(downloads) == 1+ assert downloads[0][0] == "mxc://example.org/mediaid"+ assert downloads[0][1] >= len(b"image")assert len(handled) == 1+ media_paths = handled[0]["media"]+ assert len(media_paths) == 1+ assert Path(media_paths[0]).read_bytes() == b"image"metadata = handled[0]["metadata"]+ assert metadata["attachments"][0]["path"] == media_paths[0]assert metadata["thread_root_event_id"] == "$root1"assert metadata["thread_reply_to_event_id"] == "$event1"assert metadata["event_id"] == "$event1"@@ -2322,31 +2349,6 @@ def test_build_matrix_text_content_with_event_id_preserves_thread_relation() ->assert result["m.new_content"]["m.relates_to"] == relates_to-def test_build_matrix_text_content_no_event_id() -> None:- """Test that when event_id is not provided, no extra properties are added."""- result = _build_matrix_text_content("Regular message")-- # Basic required properties should be present- assert "msgtype" in result- assert "body" in result- assert result["body"] == "Regular message"-- # Extra properties for replacement should NOT be present- assert "m.relates_to" not in result- assert "m.new_content" not in result- assert "format" not in result- assert "formatted_body" not in result---def test_build_matrix_text_content_plain_text_no_html() -> None:- """Test plain text that should not include HTML formatting."""- result = _build_matrix_text_content("Simple plain text")- assert "msgtype" in result- assert "body" in result- assert "format" not in result- assert "formatted_body" not in result--@pytest.mark.asyncioasync def test_send_room_content_returns_room_send_response():"""Test that _send_room_content returns the response from client.room_send."""diff --git a/nanobot/channels/qq/tests/test_qq_media.py b/nanobot/channels/qq/tests/test_qq_media.pyindex 4082838fd..ce2e00eb6 100644--- a/nanobot/channels/qq/tests/test_qq_media.py+++ b/nanobot/channels/qq/tests/test_qq_media.py@@ -105,8 +105,11 @@ def test_guess_send_file_type_file() -> None:def test_guess_send_file_type_by_mime() -> None:- # A filename with no known extension but whose mime type is image/*- assert _guess_send_file_type("photo.xyz_image_test") == QQ_FILE_TYPE_FILE+ filename = "photo.xyz_image_test"+ assert not _is_image_name(filename)+ with patch.object(qq.mimetypes, "guess_type", return_value=("image/png", None)) as guess_type:+ assert _guess_send_file_type(filename) == QQ_FILE_TYPE_IMAGE+ guess_type.assert_called_once_with(filename)# ── send() exception handling ───────────────────────────────────────diff --git a/nanobot/channels/signal/tests/test_signal_markdown.py b/nanobot/channels/signal/tests/test_signal_markdown.pyindex 4ba4c250a..c19b7e31f 100644--- a/nanobot/channels/signal/tests/test_signal_markdown.py+++ b/nanobot/channels/signal/tests/test_signal_markdown.py@@ -90,10 +90,12 @@ def test_markdown_style_mapping(markdown, expected_plain, styled_text, style):def test_code_block():plain, styles = _markdown_to_signal("```\nprint('hi')\n```")- assert "print('hi')" in plain- assert styles_for(plain, styles).get("print('hi')\n") == ["MONOSPACE"] or "MONOSPACE" in str(- styles_for(plain, styles)- )+ assert plain.rstrip("\n") == "print('hi')"+ assert {+ span.rstrip("\n"): span_styles+ for span, span_styles in utf16_styles_for(plain, styles).items()+ } == {"print('hi')": ["MONOSPACE"]}+ assert_within_utf16_bounds(plain, styles)def test_code_block_with_lang():@@ -167,9 +169,10 @@ def test_header_with_inline_code():"""Header becomes BOLD; code inside becomes MONOSPACE (not double-BOLD)."""plain, styles = _markdown_to_signal("# Use `grep`")assert plain == "Use grep"- sd = styles_for(plain, styles)- assert "BOLD" in sd.get("Use ", []) or "BOLD" in str(styles)- assert "MONOSPACE" in sd.get("grep", [])+ assert utf16_styles_for(plain, styles) == {+ "Use ": ["BOLD"], "grep": ["MONOSPACE"],+ }+ assert_within_utf16_bounds(plain, styles)def test_multiline_mixed():@@ -435,20 +438,16 @@ def test_inline_code_inside_blockquote():assert sd.get("grep") == ["MONOSPACE"]-def test_header_with_inner_bold_produces_contiguous_bold_ranges():- """`# **wrap** me` — header forces BOLD over the whole line; the inner `**`- splits the run, yielding two contiguous BOLD ranges that together cover- "wrap me". This is intentional — Signal renders adjacent same-style ranges- as a single visual span.- """+def test_header_with_inner_bold_covers_whole_header():+ """Header text is bold regardless of equivalent adjacent range fragmentation."""plain, styles = _markdown_to_signal("# **wrap** me")assert plain == "wrap me"- # Both ranges are BOLD; collectively they cover the whole "wrap me".+ assert_within_utf16_bounds(plain, styles)+ assert all(s.endswith(":BOLD") for s in styles)bold_ranges = [s for s in styles if s.endswith(":BOLD")]- assert len(bold_ranges) == 2covered = set()for entry in bold_ranges:start, length, _ = entry.split(":", 2)for i in range(int(start), int(start) + int(length)):covered.add(i)- assert covered == set(range(len(plain)))+ assert covered == set(range(_utf16_len(plain)))diff --git a/nanobot/channels/telegram/tests/test_telegram_channel.py b/nanobot/channels/telegram/tests/test_telegram_channel.pyindex 13b17d8c2..b636d9e24 100644--- a/nanobot/channels/telegram/tests/test_telegram_channel.py+++ b/nanobot/channels/telegram/tests/test_telegram_channel.py@@ -773,9 +773,12 @@ async def test_running_message_handler_reorders_same_session_updates() -> None:MessageBus(),)seen: list[int] = []+ processed = asyncio.Event()async def fake_process(update, context) -> None:seen.append(update.message.message_id)+ if len(seen) == 2:+ processed.set()channel._process_message_update = fake_processchannel._running = True@@ -787,12 +790,20 @@ async def test_running_message_handler_reorders_same_session_updates() -> None:second.update_id = 101second.message.message_id = 2- await channel._on_message(second, None)- await channel._on_message(first, None)- await asyncio.sleep(0.3)- channel._running = False+ workers: set[asyncio.Task[None]] = set()+ try:+ await channel._on_message(second, None)+ workers.update(channel._inbound_workers.values())+ await channel._on_message(first, None)+ await asyncio.wait_for(processed.wait(), timeout=5)+ assert seen == [1, 2]+ finally:+ workers.update(channel._inbound_workers.values())+ await channel.stop()+ await asyncio.wait_for(asyncio.gather(*workers, return_exceptions=True), timeout=5)- assert seen == [1, 2]+ assert workers+ assert all(task.done() for task in workers)@pytest.mark.asynciodiff --git a/nanobot/channels/websocket/tests/test_websocket_channel.py b/nanobot/channels/websocket/tests/test_websocket_channel.pyindex e7dfde6a0..0631d5ad0 100644--- a/nanobot/channels/websocket/tests/test_websocket_channel.py+++ b/nanobot/channels/websocket/tests/test_websocket_channel.py@@ -92,7 +92,7 @@ from .ws_test_client import http_get as _http_get# -- Shared helpers (aligned with test_websocket_integration.py) ----------------_PORT = 29876+_PORT = 0async def _register_running_turn(@@ -180,12 +180,36 @@ def _basic_handler(bus: Any, **kw: Any) -> GatewayServices:)-async def _connect_when_ready(url: str) -> Any:- while True:- try:- return await websockets.connect(url)- except OSError:- await asyncio.sleep(0.02)+async def start_listener():+ """Start test-owned ephemeral listeners and join them even if setup/assertions fail."""+ listeners = []++ async def start(channel: WebSocketChannel):+ assert channel.config.port == 0+ task = asyncio.create_task(channel.start())+ listeners.append((channel, task))+ async with asyncio.timeout(5):+ while True:+ if task.done():+ await task+ raise AssertionError("listener stopped before becoming ready")+ server = channel._server+ if server is not None and server.sockets and server.is_serving():+ return server.sockets[0].getsockname()[1], task+ await asyncio.sleep(0.01)++ try:+ yield start+ finally:+ for channel, task in reversed(listeners):+ try:+ await asyncio.wait_for(channel.stop(), timeout=5)+ await asyncio.wait_for(asyncio.shield(task), timeout=5)+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)async def _wait_for_connection_cleanup(@@ -875,8 +899,8 @@ def test_issue_route_secret_matches_empty_secret() -> None:@pytest.mark.asyncio-async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock) -> None:- port = 29882+async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus,port=port,@@ -885,8 +909,7 @@ async def test_token_issue_route_requires_secret_when_static_token_configured(buwebsocketRequiresToken=True,)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:denied = await _http_get(f"http://127.0.0.1:{port}/custom-token")@@ -4155,17 +4178,14 @@ async def test_stop_is_idempotent() -> None:@pytest.mark.asyncio-async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock) -> None:- port = 29876+async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())+ port, server_task = await start_listener(channel)try:- client = await asyncio.wait_for(- _connect_when_ready(f"ws://127.0.0.1:{port}/ws?client_id=tester"),- timeout=5,- )+ client = await websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=tester")async with client:ready_raw = await client.recv()ready = json.loads(ready_raw)@@ -4194,12 +4214,11 @@ async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: Magi@pytest.mark.asyncio-async def test_token_rejects_handshake_when_mismatch(bus: MagicMock) -> None:- port = 29877+async def test_token_rejects_handshake_when_mismatch(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port, path="/", token="secret")- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:@@ -4212,12 +4231,11 @@ async def test_token_rejects_handshake_when_mismatch(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_wrong_path_returns_404(bus: MagicMock) -> None:- port = 29878+async def test_wrong_path_returns_404(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:@@ -4237,8 +4255,8 @@ def test_registry_discovers_websocket_channel() -> None:@pytest.mark.asyncio-async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock) -> None:- port = 29879+async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port,tokenIssuePath="/auth/token",@@ -4246,8 +4264,7 @@ async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMockwebsocketRequiresToken=True,)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:deny = await _http_get(f"http://127.0.0.1:{port}/auth/token")@@ -4286,8 +4303,9 @@ async def test_settings_api_returns_safe_subset_and_updates_whitelist(bus: MagicMock,monkeypatch,tmp_path,+ start_listener,) -> None:- port = 29891+ port = 0config_path = tmp_path / "config.json"config = Config()config.agents.defaults.model = "openai/gpt-4o"@@ -4321,8 +4339,7 @@ async def test_settings_api_returns_safe_subset_and_updates_whitelist(channel = _ch(bus, port=port, image_generation_reload=image_reload)channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)webui_client = Nonetry:@@ -4700,6 +4717,7 @@ async def test_image_settings_hot_reload_without_restart(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,provider_name: str,+ start_listener,) -> None:from nanobot.agent.loop import AgentLoopfrom nanobot.agent.tools.image_generation import (@@ -4707,7 +4725,7 @@ async def test_image_settings_hot_reload_without_restart(reload_image_generation_tool,)- port = 29935+ port = 0config_path = tmp_path / "config.json"config = Config.model_validate({"providers": {"SenseNova": {"apiKey": "named-image-key", "apiBase": "https://images.test/v1",@@ -4728,8 +4746,7 @@ async def test_image_settings_hot_reload_without_restart(channel = _ch(runtime_bus, port=port, image_generation_reload=image_reload)channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)webui_client = Nonetry:webui_token = channel.gateway.tokens.issue_token(300, audience="webui")@@ -4786,8 +4803,9 @@ async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,runtime_available: bool,+ start_listener,) -> None:- port = 29936+ port = 0config_path = tmp_path / "config.json"config = Config()config.providers.openrouter.api_key = "image-key"@@ -4803,8 +4821,7 @@ async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(channel = _ch(bus, port=port, image_generation_reload=image_reload if runtime_available else None)channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)webui_client = Nonetry:webui_token = channel.gateway.tokens.issue_token(300, audience="webui")@@ -4829,13 +4846,12 @@ async def test_image_settings_fall_back_to_restart_when_hot_reload_fails(@pytest.mark.asyncio-async def test_commands_api_returns_slash_command_metadata(bus: MagicMock) -> None:- port = 29892+async def test_commands_api_returns_slash_command_metadata(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:denied = await _http_get(f"http://127.0.0.1:{port}/api/commands")@@ -4863,8 +4879,8 @@ async def test_commands_api_returns_slash_command_metadata(bus: MagicMock) -> No@pytest.mark.asyncio-async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:- port = 29893+async def test_bootstrap_exposes_native_surface(bus: MagicMock, start_listener) -> None:+ port = 0channel = WebSocketChannel({"enabled": True,@@ -4883,8 +4899,7 @@ async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:),)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:response = await _http_get(@@ -4990,12 +5005,11 @@ def test_update_provider_settings_ignores_api_type_for_non_openai(monkeypatch, t@pytest.mark.asyncio-async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock) -> None:- port = 29880+async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port, streaming=True)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=stream-tester") as client:@@ -5043,12 +5057,11 @@ async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMoc@pytest.mark.asyncio-async def test_token_issue_rejects_when_at_capacity(bus: MagicMock) -> None:- port = 29881+async def test_token_issue_rejects_when_at_capacity(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port, tokenIssuePath="/auth/token", tokenIssueSecret="s")- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:# Fill issued tokens to capacity@@ -5071,12 +5084,11 @@ async def test_token_issue_rejects_when_at_capacity(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock) -> None:- port = 29882+async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port, allowFrom=["alice", "bob"])- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:@@ -5311,12 +5323,11 @@ async def test_side_channel_command_does_not_register_queued_turn(@pytest.mark.asyncio-async def test_client_id_truncation(bus: MagicMock) -> None:- port = 29883+async def test_client_id_truncation(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:long_id = "x" * 200@@ -5330,12 +5341,11 @@ async def test_client_id_truncation(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_non_utf8_binary_frame_ignored(bus: MagicMock) -> None:- port = 29884+async def test_non_utf8_binary_frame_ignored(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bin-test") as client:@@ -5351,8 +5361,8 @@ async def test_non_utf8_binary_frame_ignored(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) -> None:- port = 29885+async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port,token="static-secret",@@ -5360,8 +5370,7 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) ->tokenIssueSecret="route-secret",)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:# Get an issued token@@ -5382,12 +5391,11 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) ->@pytest.mark.asyncio-async def test_allow_from_empty_list_denies_all(bus: MagicMock) -> None:- port = 29886+async def test_allow_from_empty_list_denies_all(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port, allowFrom=[])- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:@@ -5400,13 +5408,12 @@ async def test_allow_from_empty_list_denies_all(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_websocket_requires_token_without_issue_path(bus: MagicMock) -> None:+async def test_websocket_requires_token_without_issue_path(bus: MagicMock, start_listener) -> None:"""When websocket_requires_token is True but no token or issue path configured, all connections are rejected."""- port = 29887+ port = 0channel = _ch(bus, port=port, websocketRequiresToken=True)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:# No token at all → 401@@ -5433,11 +5440,10 @@ async def test_websocket_requires_token_without_issue_path(bus: MagicMock) -> No@pytest.mark.asyncio-async def test_multiplex_legacy_still_works(bus: MagicMock) -> None:- port = 29930+async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=legacy") as client:@@ -5471,11 +5477,10 @@ async def test_multiplex_legacy_still_works(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_multiplex_new_chat_roundtrip(bus: MagicMock) -> None:- port = 29931+async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=mp") as client:@@ -5607,11 +5612,10 @@ async def test_webui_message_envelope_appends_user_transcript(@pytest.mark.asyncio-async def test_multiplex_two_chats_isolated(bus: MagicMock) -> None:- port = 29932+async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=two") as client:@@ -5644,11 +5648,10 @@ async def test_multiplex_two_chats_isolated(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_multiplex_invalid_frames_return_error(bus: MagicMock) -> None:- port = 29933+async def test_multiplex_invalid_frames_return_error(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bad") as client:@@ -5680,11 +5683,10 @@ async def test_multiplex_invalid_frames_return_error(bus: MagicMock) -> None:@pytest.mark.asyncio-async def test_multiplex_cleanup_on_disconnect(bus: MagicMock) -> None:- port = 29934+async def test_multiplex_cleanup_on_disconnect(bus: MagicMock, start_listener) -> None:+ port = 0channel = _ch(bus, port=port)- server_task = asyncio.create_task(channel.start())- await asyncio.sleep(0.3)+ port, server_task = await start_listener(channel)try:async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=dc") as client:diff --git a/nanobot/channels/wecom/tests/test_wecom_channel.py b/nanobot/channels/wecom/tests/test_wecom_channel.pyindex 3dea1982b..a2f5766a0 100644--- a/nanobot/channels/wecom/tests/test_wecom_channel.py+++ b/nanobot/channels/wecom/tests/test_wecom_channel.py@@ -101,7 +101,7 @@ def test_sanitize_filename_empty_or_dots_fallback() -> None:@pytest.mark.asyncio-async def test_download_and_save_success() -> None:+async def test_download_and_save_success(tmp_path: Path) -> None:"""Successful download writes file and returns sanitized path."""channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())client = _FakeWeComClient()@@ -110,14 +110,12 @@ async def test_download_and_save_success() -> None:fake_data = b"\x89PNG\r\nfake image"client.download_file.return_value = (fake_data, "raw_photo.png")- with patch("nanobot.channels.wecom.runtime.get_media_dir", return_value=Path(tempfile.gettempdir())):+ with patch("nanobot.channels.wecom.runtime.get_media_dir", return_value=tmp_path):path = await channel._download_and_save_media("https://example.com/img.png", "aes_key", "image", "photo.png")assert path is not None- assert os.path.isfile(path)- assert os.path.basename(path) == "photo.png"- # Cleanup- os.unlink(path)+ assert Path(path) == tmp_path / "photo.png"+ assert Path(path).read_bytes() == fake_data@pytest.mark.asynciodiff --git a/nanobot/channels/weixin/tests/test_weixin_hardening.py b/nanobot/channels/weixin/tests/test_weixin_hardening.pyindex bce910e84..e23ad9e9c 100644--- a/nanobot/channels/weixin/tests/test_weixin_hardening.py+++ b/nanobot/channels/weixin/tests/test_weixin_hardening.py@@ -253,7 +253,10 @@ async def test_qr_fetch_does_not_retry_invalid_request_without_local_tokens(tmp_@pytest.mark.asyncioasync def test_lifecycle_notifications_are_best_effort() -> None:channel = _ready_channel()- channel._api_post = AsyncMock(return_value={"ret": 0})+ channel._api_post = AsyncMock(side_effect=[+ httpx.ReadTimeout("upstream unavailable"),+ {"ret": -100, "errmsg": "upstream rejected notification"},+ ])await channel._notify_lifecycle("start")await channel._notify_lifecycle("stop")diff --git a/tests/agent/test_autocompact_unit.py b/tests/agent/test_autocompact_unit.pyindex 525c09139..56dcadd6a 100644--- a/tests/agent/test_autocompact_unit.py+++ b/tests/agent/test_autocompact_unit.py@@ -507,26 +507,17 @@ class TestArchiveDelegates:@pytest.mark.asyncioasync def test_no_summary_when_compact_returns_empty(self):- ac = _make_autocompact()mock_sm = _mock_sessions()- ac.sessions = mock_sm+ mock_sm.get_or_create.return_value = _make_session(metadata={+ "_last_summary": {"text": "Previous checkpoint.", "last_active": "2026-05-13T10:00:00"},+ })+ ac = _make_autocompact(sessions=mock_sm)ac.consolidator.compact_idle_session = AsyncMock(return_value="")await ac._archive("cli:test", runtime=_runtime())assert "cli:test" not in ac._summaries- @pytest.mark.asyncio- async def test_no_summary_when_compact_returns_nothing(self):- ac = _make_autocompact()- mock_sm = _mock_sessions()- ac.sessions = mock_sm- ac.consolidator.compact_idle_session = AsyncMock(return_value="(nothing)")-- await ac._archive("cli:test", runtime=_runtime())-- assert "cli:test" not in ac._summaries-@pytest.mark.asyncioasync def test_exception_still_removes_from_archiving(self):ac = _make_autocompact()diff --git a/tests/agent/test_context_aware.py b/tests/agent/test_context_aware.pyindex 1265d35c1..4c12178f7 100644--- a/tests/agent/test_context_aware.py+++ b/tests/agent/test_context_aware.py@@ -1,21 +1,36 @@from __future__ import annotations-from nanobot.agent.tools.context import ContextAware, RequestContext+from nanobot.agent.tools.base import Tool+from nanobot.agent.tools.context import ContextAware, RequestContext, request_context+from nanobot.agent.tools.registry import ToolRegistry-class _ContextTool:+class _ContextTool(Tool):+ name = "legacy_context"+ description = "External-style tool using the legacy context setter."+ parameters = {"type": "object", "properties": {}}+def __init__(self):self.last_ctx = Nonedef set_context(self, ctx: RequestContext) -> None:self.last_ctx = ctx+ async def execute(self, **kwargs):+ return self.last_ctx+-def test_context_aware_sets_request_context():+async def test_registry_injects_request_context_into_legacy_tool():tool = _ContextTool()+ registry = ToolRegistry()+ registry.register(tool)ctx = RequestContext(channel="test", chat_id="123", session_key="test:123")- tool.set_context(ctx)- assert tool.last_ctx.channel == "test"++ with request_context(ctx):+ result = await registry.execute(tool.name, {})++ assert result is ctx+ assert tool.last_ctx is ctxdef test_context_tool_is_instance_of_context_aware():diff --git a/tests/agent/test_context_builder.py b/tests/agent/test_context_builder.pyindex 16c11126b..725cfbd70 100644--- a/tests/agent/test_context_builder.py+++ b/tests/agent/test_context_builder.py@@ -281,16 +281,13 @@ class TestBuildUserContent:class TestBuildSystemPrompt:- def test_returns_nonempty_string(self, tmp_path):- builder = _builder(tmp_path)- result = builder.build_system_prompt()- assert isinstance(result, str)- assert len(result) > 0-def test_includes_identity_section(self, tmp_path):builder = _builder(tmp_path)result = builder.build_system_prompt()- assert "workspace" in result.lower() or "python" in result.lower()++ assert "## Runtime\n" in result+ assert "Agent profile: SOUL.md and USER.md" in result+ assert "History log: memory/history.jsonl" in resultdef test_default_identity_uses_relative_agent_paths(self, tmp_path):result = ContextBuilder(tmp_path)._get_identity()diff --git a/tests/agent/test_hook_composite.py b/tests/agent/test_hook_composite.pyindex 4667502dc..fb41706d7 100644--- a/tests/agent/test_hook_composite.py+++ b/tests/agent/test_hook_composite.py@@ -289,20 +289,6 @@ async def test_composite_error_isolation_all_async():# ----------------------------------------------------------------------------def test_composite_finalize_content_pipeline():- class Upper(AgentHook):- def finalize_content(self, context, content):- return content.upper() if content else content-- class Suffix(AgentHook):- def finalize_content(self, context, content):- return (content + "!") if content else content-- hook = CompositeHook([Upper(), Suffix()])- result = hook.finalize_content(_ctx(), "hello")- assert result == "HELLO!"--def test_composite_finalize_content_none_passthrough():hook = CompositeHook([AgentHook()])assert hook.finalize_content(_ctx(), None) is Nonediff --git a/tests/agent/test_prompt_responsiveness.py b/tests/agent/test_prompt_responsiveness.pyindex 2eed7fb8c..3e53e5735 100644--- a/tests/agent/test_prompt_responsiveness.py+++ b/tests/agent/test_prompt_responsiveness.py@@ -64,8 +64,8 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(release = threading.Event()captured = []finalized = []- ticks = []- ticking = True+ heartbeat_requested = asyncio.Event()+ heartbeat_progress = asyncio.Event()class Lifecycle(AgentHook):async def on_finally(self, context):@@ -77,15 +77,16 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(context.messages[0]["content"] = "hook-only"async def heartbeat():- while ticking:- ticks.append(runtime_loop.time())- await asyncio.sleep(0.01)+ while True:+ await heartbeat_requested.wait()+ heartbeat_requested.clear()+ heartbeat_progress.set()def blocked(operation, *args, **kwargs):captured.append((current_request_context(), current_workspace_scope(), threading.get_ident()))runtime_loop.call_soon_threadsafe(entered.set)try:- assert release.wait(5), "test did not release prompt preparation"+ assert release.wait(10), "test did not release prompt preparation"return operation(*args, **kwargs)finally:runtime_loop.call_soon_threadsafe(finished.set)@@ -127,11 +128,11 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(tasks = [task, pulse]try:await asyncio.wait_for(entered.wait(), timeout=5)- before = len(ticks)- status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 0.5)+ status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 5)assert status is not None and "test-model" in status.content- await asyncio.sleep(0.04)- assert len(ticks) >= before + 2+ heartbeat_requested.set()+ await asyncio.wait_for(heartbeat_progress.wait(), 5)+ assert not release.is_set()assert not finished.is_set()assert captured[0][2] != threading.get_ident()if phase != "history":@@ -145,7 +146,7 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(if cancel:task.cancel()with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(task, 0.5)+ await asyncio.wait_for(task, 5)assert not finished.is_set()if phase != "history":assert len(finalized) == 1@@ -155,15 +156,32 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(assert final_loop is runtime_loopif phase != "prompt":assert snapshot- # A new session queues behind the physical worker, even after its caller exits.+ # Observe the new session entering the real semaphore, not a settling delay.+ slots = loop.runner.context_governor._preparation_slots+ acquire_slot = slots.acquire+ queued = asyncio.Event()+ acquired = asyncio.Event()++ async def acquire():+ # History preparation queues before RequestContext is bound.+ is_waiting = asyncio.current_task() is waiting+ if is_waiting:+ queued.set()+ result = await acquire_slot()+ if is_waiting:+ acquired.set()+ return result++ monkeypatch.setattr(slots, "acquire", acquire)waiting = asyncio.create_task(loop.process_direct("Queued", session_key="cli:waiting"))tasks.append(waiting)- await asyncio.sleep(0.04)+ await asyncio.wait_for(queued.wait(), 5)+ assert not acquired.is_set()assert len(provider.requests) == expected_requestsassert not waiting.done()waiting.cancel()with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(waiting, 0.5)+ await asyncio.wait_for(waiting, 5)elif phase == "history":# The live nested payload may change after capture; the worker owns its copy.live.messages[0]["content"][0]["text"] = "Changed after capture"@@ -184,7 +202,6 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(assert current_request_context() is Noneassert current_workspace_scope() is Nonefinally:- ticking = Falserelease.set()for pending in tasks:if not pending.done():diff --git a/tests/agent/test_runner_governance.py b/tests/agent/test_runner_governance.pyindex 7ea2fca58..d8c1844ce 100644--- a/tests/agent/test_runner_governance.py+++ b/tests/agent/test_runner_governance.py@@ -1487,40 +1487,6 @@ async def test_runner_backfill_only_mutates_model_context_not_returned_messages(]-def test_governance_repairs_orphans_after_history_rewrite():- """A rewritten history drops tool results whose calls are no longer present."""- rewritten = [- {"role": "system", "content": "system"},- {"role": "tool", "tool_call_id": "tc_old", "name": "search",- "content": "old result"},- {"role": "assistant", "content": "old answer"},- {"role": "user", "content": "new msg"},- ]-- cleaned = ContextGovernor.drop_orphan_tool_results(rewritten)- # The orphan tool result should be removed.- assert not any(- m.get("role") == "tool" and m.get("tool_call_id") == "tc_old"- for m in cleaned- )---def test_governance_fallback_still_repairs_orphans():- """When full governance fails, the fallback must still repair orphans."""- # Messages with an orphan tool result (no matching assistant tool_call).- messages = [- {"role": "user", "content": "hello"},- {"role": "tool", "tool_call_id": "orphan_tc", "name": "read",- "content": "stale"},- {"role": "assistant", "content": "hi"},- ]-- repaired = ContextGovernor.drop_orphan_tool_results(messages)- repaired = ContextGovernor.backfill_missing_tool_results(repaired)- # Orphan tool result should be gone.- assert not any(m.get("tool_call_id") == "orphan_tc" for m in repaired)--# ---------------------------------------------------------------------------# Malformed tool_call name guard (missing/non-string name wedges the session# upstream: messages.content.N.tool_use.name: Input should be a valid string)diff --git a/tests/agent/test_runner_safety.py b/tests/agent/test_runner_safety.pyindex 503663265..57d6d3b67 100644--- a/tests/agent/test_runner_safety.py+++ b/tests/agent/test_runner_safety.py@@ -182,6 +182,21 @@ async def test_runner_lets_llm_recover_from_shell_guard_path_outside():assert result.tool_events and result.tool_events[0]["status"] == "error"# v2: detail keeps the breadcrumb but the runner did not raise.assert "workspace_violation" in result.tool_events[0]["detail"]+ calls = [+ call+ for message in captured_second_call if message.get("role") == "assistant"+ for call in message.get("tool_calls", []) if call["id"] == "call_blocked"+ ]+ assert len(calls) == 1+ assert calls[0]["function"]["name"] == "exec"+ rejections = [+ message for message in captured_second_call+ if message.get("role") == "tool" and message.get("tool_call_id") == "call_blocked"+ ]+ assert len(rejections) == 1+ assert rejections[0]["name"] == "exec"+ assert "Command blocked by safety guard (path outside working dir)" in rejections[0]["content"]+ assert "Consider this result in the context of the user's goal" in rejections[0]["content"]@pytest.mark.asynciodiff --git a/tests/agent/tools/test_self_tool.py b/tests/agent/tools/test_self_tool.pyindex 667dd4506..286aa0187 100644--- a/tests/agent/tools/test_self_tool.py+++ b/tests/agent/tools/test_self_tool.py@@ -147,6 +147,7 @@ class TestInspectPathNavigation:@pytest.mark.asyncioasync def test_inspect_config_subfield(self):+ """Positive control for sensitive-field blocking: ordinary config stays inspectable."""loop = _make_mock_loop()tool = _make_tool(loop=loop)result = await tool.execute(action="check", key="web_config.enable")@@ -649,60 +650,6 @@ class TestSubagentHookStatus:assert context.iteration == 1-# ----------------------------------------------------------------------------# Checkpoint callback updates status-# -----------------------------------------------------------------------------class TestCheckpointCallback:-- @pytest.mark.asyncio- async def test_checkpoint_updates_phase_and_iteration(self):- """The _on_checkpoint callback should update status.phase and iteration."""-- from nanobot.agent.subagent import SubagentStatus-- status = SubagentStatus(- task_id="cp",- label="test",- task_description="test",- started_at=time.monotonic(),- )-- # Simulate the checkpoint callback as defined in _run_subagent- async def _on_checkpoint(payload: dict) -> None:- status.phase = payload.get("phase", status.phase)- status.iteration = payload.get("iteration", status.iteration)-- await _on_checkpoint({"phase": "awaiting_tools", "iteration": 2})- assert status.phase == "awaiting_tools"- assert status.iteration == 2-- await _on_checkpoint({"phase": "tools_completed", "iteration": 3})- assert status.phase == "tools_completed"- assert status.iteration == 3-- @pytest.mark.asyncio- async def test_checkpoint_preserves_phase_on_missing_key(self):- """If payload doesn't have 'phase', status.phase should stay unchanged."""- from nanobot.agent.subagent import SubagentStatus-- status = SubagentStatus(- task_id="cp",- label="test",- task_description="test",- started_at=time.monotonic(),- phase="initializing",- )-- async def _on_checkpoint(payload: dict) -> None:- status.phase = payload.get("phase", status.phase)- status.iteration = payload.get("iteration", status.iteration)-- await _on_checkpoint({"iteration": 1})- assert status.phase == "initializing"- assert status.iteration == 1--# ---------------------------------------------------------------------------# read-only mode (tools.my.allow_set=False)# ---------------------------------------------------------------------------@@ -819,13 +766,6 @@ class TestSensitiveSubFieldBlocking:result = await tool.execute(action="set", key="some_config.password", value="evil")assert "not accessible" in result- @pytest.mark.asyncio- async def test_inspect_non_sensitive_subfield_allowed(self):- """web_config.enable should still be inspectable."""- tool = _make_tool()- result = await tool.execute(action="check", key="web_config.enable")- assert "True" in result-@pytest.mark.asyncioasync def test_modify_sensitive_top_level_blocked(self):"""Top-level key matching sensitive name must be blocked for set."""diff --git a/tests/agent/tools/test_subagent_tools.py b/tests/agent/tools/test_subagent_tools.pyindex d5a3fbcce..05876027c 100644--- a/tests/agent/tools/test_subagent_tools.py+++ b/tests/agent/tools/test_subagent_tools.py@@ -110,19 +110,13 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):)mgr._announce_result = AsyncMock()- async def fake_run(spec):- exec_tool = spec.tools.get("exec")- assert exec_tool is not None- assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]- return AgentRunResult(- messages=[],- stop_reason="done",- final_content="done",- error=None,- tool_events=[],- )-- mgr.runner.run = AsyncMock(side_effect=fake_run)+ mgr.runner.run = AsyncMock(return_value=AgentRunResult(+ messages=[],+ stop_reason="done",+ final_content="done",+ error=None,+ tool_events=[],+ ))await mgr.spawn(task="do task",@@ -134,6 +128,11 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)mgr.runner.run.assert_awaited_once()+ spec = mgr.runner.run.await_args.args[0]+ exec_tool = spec.tools.get("exec")+ assert exec_tool is not None+ assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]+ assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]@pytest.mark.asyncio@@ -154,8 +153,53 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):)mgr._announce_result = AsyncMock()+ mgr.runner.run = AsyncMock(return_value=AgentRunResult(+ messages=[],+ stop_reason="done",+ final_content="done",+ error=None,+ tool_events=[],+ ))++ await mgr.spawn(+ task="do task",+ label="label",+ origin_channel="test",+ origin_chat_id="c1",+ runtime=_runtime(provider),+ )+ await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)++ mgr.runner.run.assert_awaited_once()+ spec = mgr.runner.run.await_args.args[0]+ assert spec.max_iterations == 37+ assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]+++async def test_subagent_checkpoint_updates_status_and_preserves_omitted_fields(tmp_path):+ """Runner checkpoints update detached task snapshots without resetting omitted fields."""+ from nanobot.agent.subagent import SubagentManager+ from nanobot.bus.queue import MessageBus++ mgr = SubagentManager(+ consolidator=MagicMock(spec=Consolidator),+ workspace=tmp_path,+ bus=MessageBus(),+ max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,+ )+ mgr._announce_result = AsyncMock()+ snapshots = []+async def fake_run(spec):- assert spec.max_iterations == 37+ for payload in [+ {"phase": "awaiting_tools", "iteration": 2},+ {"phase": "tools_completed", "iteration": 3},+ {"iteration": 4},+ {"phase": "final_response"},+ ]:+ await spec.checkpoint_callback(payload)+ snapshots.extend(mgr.statuses_for_session("test:c1").values())return AgentRunResult(messages=[],stop_reason="done",@@ -166,16 +210,16 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):mgr.runner.run = AsyncMock(side_effect=fake_run)- await mgr.spawn(- task="do task",- label="label",- origin_channel="test",- origin_chat_id="c1",- runtime=_runtime(provider),- )+ await mgr.spawn(task="do task", session_key="test:c1", runtime=_runtime(MagicMock()))await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)- mgr.runner.run.assert_awaited_once()+ assert [(s.state, s.phase, s.iteration) for s in snapshots] == [+ ("running", "awaiting_tools", 2),+ ("running", "tools_completed", 3),+ ("running", "tools_completed", 4),+ ("running", "final_response", 4),+ ]+ assert [s.state for s in mgr.statuses_for_session("test:c1").values()] == ["done"]@pytest.mark.asynciodiff --git a/tests/apps/test_cli_subprocess_env.py b/tests/apps/test_cli_subprocess_env.pyindex 1d41d226f..dc69f3c78 100644--- a/tests/apps/test_cli_subprocess_env.py+++ b/tests/apps/test_cli_subprocess_env.py@@ -3,7 +3,6 @@from __future__ import annotationsimport json-import subprocessimport sysimport pytest@@ -53,59 +52,6 @@ def test_subprocess_env_excludes_api_keys_on_windows(monkeypatch, tmp_path) -> Nassert all(isinstance(value, str) for value in env.values())-def test_run_passes_filtered_env(monkeypatch, tmp_path) -> None:- monkeypatch.setenv("OPENAI_API_KEY", "sk-should-not-leak")- manager = CliAppManager(workspace=tmp_path, data_dir=tmp_path / "cli-apps")- captured: dict[str, object] = {}-- def fake_run(*args, **kwargs):- captured.update(kwargs)-- class Result:- returncode = 0- stdout = "ok"- stderr = ""-- return Result()-- monkeypatch.setattr("nanobot.apps.cli.service.subprocess.run", fake_run)- monkeypatch.setattr(manager, "get_app", lambda name: {"name": name, "entry_point": "echo"})- monkeypatch.setattr(- manager,- "_load_installed",- lambda: {"echo": {"entry_point": "echo"}},- )- monkeypatch.setattr("nanobot.apps.cli.service.shutil.which", lambda entry: "/bin/echo")- monkeypatch.setattr(manager, "_resolve_cwd", lambda *a, **k: tmp_path)- monkeypatch.setattr(manager, "_artifact_snapshot", lambda cwd: {})- monkeypatch.setattr(manager, "_changed_artifacts", lambda cwd, snap: [])-- manager.run("echo", ["hi"])-- env = captured.get("env")- assert isinstance(env, dict)- assert "OPENAI_API_KEY" not in env---def test_management_subprocesses_use_filtered_env(monkeypatch, tmp_path) -> None:- monkeypatch.setenv("OPENAI_API_KEY", "sk-should-not-leak")- captured: dict[str, object] = {}-- def fake_run(*args, **kwargs):- captured.update(kwargs)- return subprocess.CompletedProcess(args[0], 0, stdout="ok", stderr="")-- monkeypatch.setattr("nanobot.apps.cli.service.subprocess.run", fake_run)- manager = CliAppManager(workspace=tmp_path, data_dir=tmp_path / "cli-apps")-- manager._run_argv(["example-cli", "--help"], timeout=5)-- env = captured.get("env")- assert isinstance(env, dict)- assert "OPENAI_API_KEY" not in env- assert env["PYTHONUNBUFFERED"] == "1"--@pytest.mark.parametrize("operation", ["run", "management"])@pytest.mark.parametrize("runtime_dir", ["/run/user/1000", None])def test_child_process_receives_runtime_dir_without_api_keys(diff --git a/tests/channels/test_channel_manager_compaction_notices.py b/tests/channels/test_channel_manager_compaction_notices.pyindex 6d34e6551..fa8da10f9 100644--- a/tests/channels/test_channel_manager_compaction_notices.py+++ b/tests/channels/test_channel_manager_compaction_notices.py@@ -3,10 +3,12 @@from __future__ import annotationsimport asyncio+from contextlib import suppressfrom unittest.mock import AsyncMockimport pytest+from nanobot.bus.events import OutboundMessagefrom nanobot.bus.outbound_events import (ContextCompactionEvent,ProgressEvent,@@ -33,84 +35,77 @@ class _MockChannel(BaseChannel):passasync def send(self, msg):- if isinstance(msg.event, ContextCompactionEvent) and not (- msg.event.notify or self.show_compaction_notices- ):- returnreturn await self._send_mock(msg)@pytest.fixture-def manager() -> ChannelManager:+def manager(tmp_path) -> ChannelManager:config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})- mgr = ChannelManager(config, MessageBus())+ mgr = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")mgr.channels["mock"] = _MockChannel({}, mgr.bus)return mgr-async def _dispatch_until(manager: ChannelManager, expected: int) -> None:- task = asyncio.create_task(manager._dispatch_outbound())- try:- for _ in range(40):- if manager.channels["mock"]._send_mock.await_count >= expected:- break- await asyncio.sleep(0.05)- finally:- task.cancel()- try:- await task- except asyncio.CancelledError:- pass---def _sent_contents(manager: ChannelManager) -> list[str]:- return [call.args[0].content for call in manager.channels["mock"]._send_mock.await_args_list]--@pytest.mark.asyncio-async def test_channel_receives_automatic_compaction_but_does_not_render_it(+async def test_dispatch_forwards_all_compaction_phases_before_adapter_filtering(manager: ChannelManager,) -> None:- manager.channels["mock"].send_progress = False- for event in (- ProgressEvent(content="ordinary progress"),+ channel = manager.channels["mock"]+ channel.send_progress = False+ channel.show_compaction_notices = False+ events = [ContextCompactionEvent(compaction_id="auto", phase="started"),ContextCompactionEvent(compaction_id="auto", phase="succeeded"),ContextCompactionEvent(compaction_id="auto-failed", phase="failed"),ContextCompactionEvent(compaction_id="auto-cancelled", phase="cancelled"),ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),ContextCompactionEvent(compaction_id="c1", phase="succeeded", notify=True),- ):- await manager.bus.publish_outbound(- outbound_message_for_event(channel="mock", chat_id="chat", event=event)- )-- await _dispatch_until(manager, 2)+ ]+ await manager.bus.publish_outbound(outbound_message_for_event(+ channel="mock", chat_id="chat", event=ProgressEvent(content="ordinary progress"),+ ))+ messages = [+ outbound_message_for_event(channel="mock", chat_id="chat", event=event)+ for event in events+ ]+ for msg in messages:+ await manager.bus.publish_outbound(msg)+ final = OutboundMessage(channel="mock", chat_id="chat", content="Final")+ await manager.bus.publish_outbound(final)+ delivered = asyncio.Event()++ def record_send(msg):+ if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat", "Final", None):+ delivered.set()++ channel._send_mock.side_effect = record_send+ task = asyncio.create_task(manager._dispatch_outbound())+ try:+ await asyncio.wait_for(delivered.wait(), timeout=2)+ finally:+ task.cancel()+ with suppress(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=2)- contents = _sent_contents(manager)- assert "ordinary progress" not in contents- assert contents == ["Compressing context…", "Context compacted."]+ # The recorder sees the manager -> adapter boundary, not a fake presentation rule.+ received = [call.args[0] for call in channel._send_mock.await_args_list]+ assert received == [*messages, final]+ assert [msg.event for msg in received] == [*events, None]+ assert [msg.content for msg in received[-3:]] == [+ "Compressing context…", "Context compacted.", "Final",+ ]+ assert not manager._outbound_tasks+ assert not manager._outbound_tails@pytest.mark.parametrize("global_value", [False, True])@pytest.mark.parametrize("override", [None, False, True])@pytest.mark.parametrize("key", ["show_compaction_notices", "showCompactionNotices"])-async def test_global_notice_policy_and_channel_override(manager, global_value, override, key):+def test_global_notice_policy_and_channel_override(manager, global_value, override, key):manager.config.channels.show_compaction_notices = global_valuesection = {} if override is None else {key: override}channel = manager._build_channel("mock", _MockChannel, section)assert channel.show_compaction_notices is (global_value if override is None else override)- channel.send_progress = False # Ordinary progress and compaction are independent policies.- manager.channels["mock"] = channel-- for phase in ("started", "succeeded", "failed", "cancelled"):- for notify in (False, True):- await channel.send(outbound_message_for_event(- channel="mock", chat_id="chat",- event=ContextCompactionEvent("compact", phase, notify=notify),- ))-- assert channel._send_mock.await_count == (8 if channel.show_compaction_notices else 4)def test_global_notice_config_round_trip_and_rebuild(manager):diff --git a/tests/channels/test_channel_manager_delta_coalescing.py b/tests/channels/test_channel_manager_delta_coalescing.pyindex 5340fbf75..18fdf2b23 100644--- a/tests/channels/test_channel_manager_delta_coalescing.py+++ b/tests/channels/test_channel_manager_delta_coalescing.py@@ -1,6 +1,7 @@"""Tests for ChannelManager delta coalescing to reduce streaming latency."""import asyncio+from contextlib import suppressfrom unittest.mock import AsyncMockimport pytest@@ -74,8 +75,8 @@ def bus():@pytest.fixture-def manager(config, bus):- manager = ChannelManager(config, bus)+def manager(config, bus, tmp_path):+ manager = ChannelManager(config, bus, config_path=tmp_path / "config.json")manager.channels["mock"] = manager._build_channel("mock", MockChannel, {})return manager@@ -121,43 +122,6 @@ class TestDeltaCoalescing:assert merged.metadata == first.metadataassert pending == [second]- @pytest.mark.asyncio- async def test_single_delta_not_coalesced(self, manager, bus):- msg = _delta("Hello")- await bus.publish_outbound(msg)-- async def process_one():- try:- m = await asyncio.wait_for(bus.consume_outbound(), timeout=0.1)- 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 = m.event- if channel and isinstance(event, StreamDeltaEvent):- await channel.send_delta(- m.chat_id,- m.content,- m.metadata,- stream_id=event.stream_id,- )- except asyncio.TimeoutError:- pass-- await process_one()-- manager.channels["mock"]._send_delta_mock.assert_called_once_with(- "chat1",- "Hello",- {},- stream_id=None,- stream_end=False,- resuming=False,- merge_next=False,- )-@pytest.mark.asyncioasync def test_multiple_deltas_coalesced(self, manager, bus):for text in ["Hello", " ", "world", "!"]:@@ -270,38 +234,49 @@ class TestDispatchOutboundWithCoalescing:"""Tests for the full _dispatch_outbound flow with coalescing."""@pytest.mark.asyncio- async def test_dispatch_coalesces_and_processes_pending(self, manager, bus):- await bus.publish_outbound(_delta("A"))- await bus.publish_outbound(_delta("B"))- await bus.publish_outbound(OutboundMessage(- channel="mock",- chat_id="chat1",- content="Final",- ))-- pending = []- processed = []-- msg = pending.pop(0) if pending else await bus.consume_outbound()- 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 = msg.event- if channel and isinstance(event, StreamDeltaEvent):- await channel.send_delta(- msg.chat_id,- msg.content,- msg.metadata,- stream_id=event.stream_id,- )- processed.append(("delta", msg.content))-- assert processed == [("delta", "AB")]- assert len(pending) == 1- assert pending[0].content == "Final"+ @pytest.mark.parametrize("end_stream", [False, True])+ async def test_dispatch_coalesces_and_delivers_final(self, manager, bus, end_stream):+ await bus.publish_outbound(_delta("A", stream_id="seg-1"))+ await bus.publish_outbound(_delta("B", stream_id="seg-1"))+ if end_stream:+ await bus.publish_outbound(_end(+ "C", stream_id="seg-1", resuming=True, merge_next=True,+ ))+ final = OutboundMessage(channel="mock", chat_id="chat1", content="Final")+ await bus.publish_outbound(final)+ delivered = asyncio.Event()+ received = []++ def record_delta(chat_id, delta, metadata, **flags):+ received.append(("delta", chat_id, delta, metadata, flags))++ def record_send(msg):+ received.append(("send", msg.channel, msg.chat_id, msg.content, msg.event))+ if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat1", "Final", None):+ delivered.set()++ channel = manager.channels["mock"]+ channel._send_delta_mock.side_effect = record_delta+ channel._send_mock.side_effect = record_send+ task = asyncio.create_task(manager._dispatch_outbound())+ try:+ await asyncio.wait_for(delivered.wait(), timeout=2)+ finally:+ task.cancel()+ with suppress(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=2)++ assert received == [+ ("delta", "chat1", "ABC" if end_stream else "AB", {}, {+ "stream_id": "seg-1",+ "stream_end": end_stream,+ "resuming": end_stream,+ "merge_next": end_stream,+ }),+ ("send", "mock", "chat1", "Final", None),+ ]+ assert not manager._outbound_tasks+ assert not manager._outbound_tailsclass TestProgressFiltering:diff --git a/tests/channels/test_channel_manager_reasoning.py b/tests/channels/test_channel_manager_reasoning.pyindex a916567ff..d7378038c 100644--- a/tests/channels/test_channel_manager_reasoning.py+++ b/tests/channels/test_channel_manager_reasoning.py@@ -16,6 +16,7 @@ plugins only implement the streaming primitives.from __future__ import annotationsimport asyncio+from contextlib import suppressfrom unittest.mock import AsyncMockimport pytest@@ -41,6 +42,7 @@ class _MockChannel(BaseChannel):self._delta_mock = AsyncMock()self._end_mock = AsyncMock()self._file_edit_mock = AsyncMock()+ self.received = []async def start(self): # pragma: no cover - not exercisedpass@@ -49,27 +51,31 @@ class _MockChannel(BaseChannel):passasync def send(self, msg):- return await self._send_mock(msg)+ await self._send_mock(msg)+ self.received.append(("send", msg))async def send_reasoning_delta(self, chat_id, delta, metadata=None, *, stream_id=None):- return await self._delta_mock(chat_id, delta, metadata, stream_id=stream_id)+ await self._delta_mock(chat_id, delta, metadata, stream_id=stream_id)+ self.received.append(("delta", chat_id, delta, metadata, stream_id))async def send_reasoning_end(self, chat_id, metadata=None, *, stream_id=None):- return await self._end_mock(chat_id, metadata, stream_id=stream_id)+ await self._end_mock(chat_id, metadata, stream_id=stream_id)+ self.received.append(("end", chat_id, metadata, stream_id))async def send_file_edit_events(self, chat_id, edits, metadata=None):return await self._file_edit_mock(chat_id, edits, metadata)@pytest.fixture-def manager() -> ChannelManager:+def manager(tmp_path) -> ChannelManager:config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})- mgr = ChannelManager(config, MessageBus())+ mgr = ChannelManager(config, MessageBus(), config_path=tmp_path / "config.json")mgr.channels["mock"] = _MockChannel({}, mgr.bus)return mgrdef test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)monkeypatch.setattr("nanobot.webui.workspaces.read_webui_default_access_mode",lambda: "default",@@ -87,7 +93,9 @@ def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monke})- mgr = ChannelManager(config, MessageBus(), webui_static_dist=False)+ mgr = ChannelManager(+ config, MessageBus(), webui_static_dist=False, config_path=tmp_path / "config.json",+ )channel = mgr.channels["websocket"]scope = channel.gateway.workspaces.default_scope()@@ -142,58 +150,58 @@ async def test_one_shot_reasoning_expands_to_delta_plus_end(manager):@pytest.mark.asyncio-async def test_dispatch_drops_reasoning_when_channel_opts_out(manager):- channel = manager.channels["mock"]- channel.show_reasoning = False- msg = outbound_message_for_event(- channel="mock",- chat_id="c1",- event=ProgressEvent(content="hidden thinking", reasoning_delta=True),- )- await manager.bus.publish_outbound(msg)-- await _pump_one(manager)-- channel._delta_mock.assert_not_awaited()- channel._end_mock.assert_not_awaited()- channel._send_mock.assert_not_awaited()---async def test_dispatch_delivers_reasoning_when_channel_opts_in(manager):[email protected]("show_reasoning", [False, True])[email protected]("send_progress", [False, True])+async def test_dispatch_reasoning_visibility_is_independent_of_progress(+ manager, show_reasoning, send_progress,+):channel = manager.channels["mock"]- channel.show_reasoning = True- for chunk in ("first ", "second"):- await manager.bus.publish_outbound(outbound_message_for_event(- channel="mock",- chat_id="c1",- event=ProgressEvent(content=chunk, reasoning_delta=True, stream_id="r1"),- ))- await manager.bus.publish_outbound(outbound_message_for_event(- channel="mock",- chat_id="c1",- event=ProgressEvent(reasoning_end=True, stream_id="r1"),- ))-- await _pump_one(manager)-- assert channel._delta_mock.await_count == 2- channel._end_mock.assert_awaited_once()+ channel.show_reasoning = show_reasoning+ channel.send_progress = send_progress+ events = [+ ProgressEvent(content="first ", reasoning_delta=True, stream_id="r1"),+ ProgressEvent(content="second", reasoning_delta=True, stream_id="r1"),+ ProgressEvent(reasoning_end=True, stream_id="r1"),+ ProgressEvent(content="one-shot reasoning", reasoning=True, stream_id="r2"),+ ProgressEvent(content="ordinary progress"),+ ]+ messages = [+ outbound_message_for_event(channel="mock", chat_id="c1", event=event)+ for event in events+ ]+ for msg in messages:+ await manager.bus.publish_outbound(msg)++ final = await _dispatch_through_final(manager)++ expected = []+ if show_reasoning:+ expected.extend([+ ("delta", "c1", "first ", messages[0].metadata, "r1"),+ ("delta", "c1", "second", messages[1].metadata, "r1"),+ ("end", "c1", messages[2].metadata, "r1"),+ ("delta", "c1", "one-shot reasoning", messages[3].metadata, "r2"),+ ("end", "c1", messages[3].metadata, "r2"),+ ])+ if send_progress:+ expected.append(("send", messages[-1]))+ assert channel.received == [*expected, ("send", final)]@pytest.mark.asyncioasync def test_dispatch_silently_drops_reasoning_for_unknown_channel(manager):- msg = outbound_message_for_event(+ await manager.bus.publish_outbound(outbound_message_for_event(channel="ghost",chat_id="c1",- event=ProgressEvent(content="nobody home", reasoning_delta=True),- )- await manager.bus.publish_outbound(msg)+ event=ProgressEvent(content="nobody home", reasoning_delta=True, stream_id="ghost-r1"),+ ))- await _pump_one(manager)+ final = await _dispatch_through_final(manager)- manager.channels["mock"]._delta_mock.assert_not_awaited()- manager.channels["mock"]._send_mock.assert_not_awaited()+ channel = manager.channels["mock"]+ assert channel.received == [("send", final)]+ channel._delta_mock.assert_not_awaited()+ channel._end_mock.assert_not_awaited()@pytest.mark.asyncio@@ -259,41 +267,24 @@ async def test_base_channel_file_edit_events_are_noop_safe():assert await channel.send_file_edit_events("c", [{"path": "a.py"}]) is None-async def test_reasoning_routing_does_not_consult_send_progress(manager):- """`show_reasoning` is orthogonal to `send_progress` — turning off- progress streaming must not silence reasoning."""- channel = manager.channels["mock"]- channel.send_progress = False- channel.show_reasoning = True- await manager.bus.publish_outbound(outbound_message_for_event(- channel="mock",- chat_id="c1",- event=ProgressEvent(content="still surfaces", reasoning_delta=True),- ))-- await _pump_one(manager)-- channel._delta_mock.assert_awaited_once()---async def _pump_one(manager: ChannelManager) -> None:- """Process currently queued messages through the reasoning dispatch branch."""-- async def dispatch_one(msg: OutboundMessage) -> None:- event = msg.event- if isinstance(event, ProgressEvent) and (- event.reasoning_delta- or event.reasoning_end- or event.reasoning- ):- channel = manager.channels.get(msg.channel)- if channel is not None and channel.show_reasoning:- await manager._send_with_retry(channel, msg)-- await dispatch_one(await asyncio.wait_for(manager.bus.consume_outbound(), timeout=1.0))- while True:- try:- await dispatch_one(manager.bus.outbound.get_nowait())- except asyncio.QueueEmpty:- break+async def _dispatch_through_final(manager: ChannelManager) -> OutboundMessage:+ """A same-destination send acknowledges completion of earlier callbacks."""+ final = OutboundMessage(channel="mock", chat_id="c1", content="Final")+ delivered = asyncio.Event()++ def record_send(msg):+ if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "c1", "Final", None):+ delivered.set()++ manager.channels["mock"]._send_mock.side_effect = record_send+ await manager.bus.publish_outbound(final)+ task = asyncio.create_task(manager._dispatch_outbound())+ try:+ await asyncio.wait_for(delivered.wait(), timeout=2)+ finally:+ task.cancel()+ with suppress(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=2)+ assert not manager._outbound_tasks+ assert not manager._outbound_tails+ return finaldiff --git a/tests/channels/test_websocket_application_boundary.py b/tests/channels/test_websocket_application_boundary.pyindex 90453554d..4c66bba20 100644--- a/tests/channels/test_websocket_application_boundary.py+++ b/tests/channels/test_websocket_application_boundary.py@@ -1,67 +1,150 @@-"""Executable architecture constraints for the WebSocket transport adapter."""+"""Behavioral delegation and executable ownership boundaries for WebSocket."""from __future__ import annotationsimport ast+import asynciofrom pathlib import Path+from unittest.mock import AsyncMock+import pytest+from websockets.datastructures import Headers+from websockets.http11 import Request, Response++from nanobot.bus.events import OutboundMessage+from nanobot.bus.queue import MessageBusfrom nanobot.channels.websocket import runtime+from nanobot.webui.gateway_services import build_gateway_services_REPOSITORY_ROOT = Path(__file__).resolve().parents[2]-_RUNTIME_PATH = _REPOSITORY_ROOT / "nanobot" / "channels" / "websocket" / "runtime.py"_SESSION_IDENTITY_PATH = _REPOSITORY_ROOT / "nanobot" / "webui" / "session_identity.py"-def _channel_method(name: str) -> ast.AsyncFunctionDef:- tree = ast.parse(_RUNTIME_PATH.read_text(encoding="utf-8"))- channel = next(- node- for node in tree.body- if isinstance(node, ast.ClassDef) and node.name == "WebSocketChannel"+async def channel(tmp_path, monkeypatch):+ monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)+ config = runtime.WebSocketConfig(allow_from=["client-1"], websocket_requires_token=False)+ bus = MessageBus()+ gateway = build_gateway_services(+ config=config,+ bus=bus,+ session_manager=None,+ static_dist_path=None,+ workspace_path=tmp_path,+ default_restrict_to_workspace=True,+ config_path=tmp_path / "config.json",+ runtime_model_name=None,+ runtime_surface="browser",+ runtime_capabilities_overrides=None,)- return next(- node- for node in channel.body- if isinstance(node, ast.AsyncFunctionDef) and node.name == name+ channel = runtime.WebSocketChannel(config, bus, gateway=gateway)+ try:+ yield channel+ finally:+ async with asyncio.timeout(2):+ await channel.stop()+ assert channel._server_task is None+ assert not channel._connection_outbound+ assert not channel._outbound_retire_tasks+ assert not channel._commands.request_tasks+++async def test_send_delegates_the_outbound_message_to_the_projector(channel, monkeypatch):+ send = AsyncMock()+ hydrate = AsyncMock()+ monkeypatch.setattr(channel._outbound, "send", send)+ monkeypatch.setattr(channel._outbound, "hydrate", hydrate)+ msg = OutboundMessage(+ channel="websocket", chat_id="chat-1", content="hello", reply_to="m1",+ media=["/example/image.png"], metadata={"turn_id": "turn-1"},)+ await channel.send(msg)++ send.assert_awaited_once_with(msg)+ hydrate.assert_not_awaited()+++async def test_subscribe_hydration_delegates_the_requested_chat(channel, monkeypatch):+ hydrate = AsyncMock()+ send = AsyncMock()+ monkeypatch.setattr(channel._outbound, "hydrate", hydrate)+ monkeypatch.setattr(channel._outbound, "send", send)++ await channel._hydrate_after_subscribe("chat-2")++ hydrate.assert_awaited_once_with("chat-2")+ send.assert_not_awaited()-def _statements_without_docstring(node: ast.AsyncFunctionDef) -> list[ast.stmt]:- body = list(node.body)- if (- body- and isinstance(body[0], ast.Expr)- and isinstance(body[0].value, ast.Constant)- and isinstance(body[0].value.value, str)- ):- body.pop(0)- return body+async def test_envelope_delegates_connection_client_and_payload_to_application(channel, monkeypatch):+ dispatch = AsyncMock()+ monkeypatch.setattr(channel._commands, "dispatch", dispatch)+ connection = AsyncMock()+ envelope = {"type": "subscribe", "chat_id": "chat-2"}-def test_business_entrypoints_are_thin_transport_delegations() -> None:- for method_name in ("_dispatch_envelope", "_hydrate_after_subscribe", "send"):- statements = _statements_without_docstring(_channel_method(method_name))- assert len(statements) == 1, method_name- assert isinstance(statements[0], ast.Expr), method_name- assert isinstance(statements[0].value, ast.Await), method_name+ await channel._dispatch_envelope(connection, "client-1", envelope)- statements = _statements_without_docstring(_channel_method("_dispatch_http"))- assert len(statements) == 1- assert isinstance(statements[0], ast.Return)- assert isinstance(statements[0].value, ast.Await)+ dispatch.assert_awaited_once_with(connection, "client-1", envelope)++[email protected]("allow_upgrade", [False, True])+async def test_http_delegates_authorization_and_preserves_endpoint_result(+ channel, monkeypatch, allow_upgrade,+):+ response = None if allow_upgrade else Response(+ 403, "Forbidden", Headers({"Content-Type": "text/plain"}), b"access denied",+ )+ process_request = AsyncMock(return_value=response)+ monkeypatch.setattr(channel.gateway.endpoint, "process_request", process_request)+ connection = AsyncMock()+ request = Request("/webui/thread?chat_id=chat-2", Headers())++ result = await channel._dispatch_http(connection, request)++ assert result is response+ process_request.assert_awaited_once_with(connection, request, is_allowed=channel.is_allowed)+ authorize = process_request.await_args.kwargs["is_allowed"]+ assert authorize("client-1") is True+ assert authorize("other-client") is False+++def _session_namespace_literal_lines(source: str) -> list[int]:+ """Locate executable namespace literals, not prose or type annotations."""+ tree = ast.parse(source)+ ignored = set()+ for node in ast.walk(tree):+ annotation = None+ if isinstance(node, ast.AnnAssign | ast.arg):+ annotation = node.annotation+ elif isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):+ annotation = node.returns+ if annotation is not None:+ ignored.update(ast.walk(annotation))+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):+ # A standalone string (including a docstring) does not define runtime policy.+ ignored.add(node.value)+ return [+ node.lineno+ for node in ast.walk(tree)+ if isinstance(node, ast.Constant)+ and isinstance(node.value, str)+ and node.value.startswith("websocket:")+ and node not in ignored+ ]def test_persisted_webui_session_prefix_has_one_production_owner() -> None:- owners = []+ # Consumers import session_identity; independent literal keys/prefixes fork its policy.+ # Exact persisted values and mapping round trips live in test_session_identity.py.+ owners = {}for path in (_REPOSITORY_ROOT / "nanobot").rglob("*.py"):- if "tests" in path.parts or path == _SESSION_IDENTITY_PATH:+ if "tests" in path.parts:continue- if "websocket:" in path.read_text(encoding="utf-8"):- owners.append(path.relative_to(_REPOSITORY_ROOT).as_posix())- assert owners == []- assert 'WEBUI_SESSION_STORAGE_PREFIX = "websocket:"' in _SESSION_IDENTITY_PATH.read_text(- encoding="utf-8"- )+ lines = _session_namespace_literal_lines(path.read_text(encoding="utf-8"))+ if lines:+ owners[path.relative_to(_REPOSITORY_ROOT).as_posix()] = lines+ assert set(owners) == {_SESSION_IDENTITY_PATH.relative_to(_REPOSITORY_ROOT).as_posix()}, ownersdef test_runtime_exports_compatibility_protocol_helpers() -> None:diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.pyindex 830912c18..9a81fae92 100644--- a/tests/cli/test_commands.py+++ b/tests/cli/test_commands.py@@ -2593,7 +2593,7 @@ def test_webui_missing_runtime_env_fails_before_starting_gateway(assert result.exit_code == 1assert missing_env in result.stdoutassert "nanobot status --config" in result.stdout- assert config_file.name in result.stdout+ assert config_file.name in _without_rendered_line_breaks(result.stdout)assert "Traceback" not in result.stdoutassert f"${{{missing_env}}}" in config_file.read_text(encoding="utf-8")diff --git a/tests/cli/test_safe_file_history.py b/tests/cli/test_safe_file_history.pyindex 7c0118732..b3deacc15 100644--- a/tests/cli/test_safe_file_history.py+++ b/tests/cli/test_safe_file_history.py@@ -12,11 +12,6 @@ def test_commands_keeps_safe_file_history_import_compatible() -> None:class TestSanitizeSurrogates:- def test_paired_surrogates_reconstructed(self):- """Windows console produces \\ud83d\\udc08 for U+1F408 — must be restored."""- result = _sanitize_surrogates("你为什么会用 🐈")- assert result == "你为什么会用 🐈"-def test_lone_surrogates_replaced(self):result = _sanitize_surrogates("hello \udce9 world")assert "\udce9" not in result@@ -56,11 +51,15 @@ class TestSafeFileHistory:entries = list(hist.load_history_strings())assert entries[0] == "normal ascii text"- def test_emoji_preserved(self, tmp_path):- hist = SafeFileHistory(str(tmp_path / "history"))- hist.store_string("hello 🐈 nanobot")- entries = list(hist.load_history_strings())- assert entries[0] == "hello 🐈 nanobot"+ def test_windows_surrogate_pair_round_trips_as_emoji(self, tmp_path):+ """Raw UTF-16 console input must survive a UTF-8 history write and reload."""+ history_path = tmp_path / "history"+ hist = SafeFileHistory(str(history_path))+ hist.store_string("hello \ud83d\udc08 nanobot")++ history_path.read_bytes().decode("utf-8") # Strict decoding must not raise.+ reloaded = SafeFileHistory(str(history_path))+ assert list(reloaded.load_history_strings()) == ["hello 🐈 nanobot"]def test_mixed_unicode_preserved(self, tmp_path):"""CJK + emoji + latin should all pass through cleanly."""diff --git a/tests/command/test_builtin_dream.py b/tests/command/test_builtin_dream.pyindex 53baa0bde..07a2b2b1c 100644--- a/tests/command/test_builtin_dream.py+++ b/tests/command/test_builtin_dream.py@@ -174,9 +174,15 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:store = _FakeStore(_FakeGit(initialized=False), dream_prompt_result=("dream prompt", 123))bus = _FakeBus()calls = []+ progress_sentinel = "private Dream progress sentinel"async def process_direct(*args, **kwargs):calls.append((args, kwargs))+ await kwargs["on_progress"](progress_sentinel)+ await kwargs["on_progress"](+ "",+ tool_events=[{"phase": "start", "name": "edit_file", "hint": progress_sentinel}],+ )return OutboundMessage(channel="cli",chat_id="direct",@@ -194,11 +200,17 @@ async def test_dream_internal_run_silences_progress(tmp_path) -> None:)ctx = CommandContext(msg=msg, session=None, key=msg.session_key, raw="/dream", args="", loop=loop)- await _run_dream_command(ctx)+ immediate = await _run_dream_command(ctx)+ assert immediate.content == "Dreaming..."+ assert (immediate.channel, immediate.chat_id) == ("feishu", "chat1")assert len(calls) == 1- assert callable(calls[0][1]["on_progress"])assert calls[0][1]["runtime"] is dream_runtime+ assert len(bus.outbound) == 1+ completion = bus.outbound[0]+ assert (completion.channel, completion.chat_id) == ("feishu", "chat1")+ assert completion.content.startswith("Dream completed")+ assert progress_sentinel not in completion.contentdef _build_runnable_dream(diff --git a/tests/command/test_model_command.py b/tests/command/test_model_command.pyindex d700c1063..00314eb04 100644--- a/tests/command/test_model_command.py+++ b/tests/command/test_model_command.py@@ -92,6 +92,7 @@ async def test_model_command_lists_current_and_available_presets(tmp_path) -> No@pytest.mark.asyncioasync def test_model_command_switches_preset(tmp_path) -> None:loop = _make_loop(tmp_path)+ assert loop.tools_config.my.allow_set is Falseout = await cmd_model(_ctx(loop, "/model fast", args="fast"))@@ -172,16 +173,6 @@ async def test_model_command_reports_provider_configuration_errors(tmp_path) ->assert "No API key configured for provider 'openai'." in status.content-async def test_model_command_does_not_depend_on_my_allow_set(tmp_path) -> None:- loop = _make_loop(tmp_path)- assert loop.tools_config.my.allow_set is False-- await cmd_model(_ctx(loop, "/model fast", args="fast"))-- assert _saved_model_preset(loop) == "fast"--@pytest.mark.asyncioasync def test_model_command_registered_as_exact_and_prefix(tmp_path) -> None:router = CommandRouter()diff --git a/tests/providers/test_azure_openai_provider.py b/tests/providers/test_azure_openai_provider.pyindex 40e880862..e9b37edb5 100644--- a/tests/providers/test_azure_openai_provider.py+++ b/tests/providers/test_azure_openai_provider.py@@ -1,11 +1,14 @@"""Test Azure OpenAI provider (Responses API via OpenAI SDK)."""+import jsonimport sysimport timefrom types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, call, patch+import httpximport pytest+from openai import AsyncOpenAIfrom nanobot.providers.azure_openai_provider import (AzureOpenAIProvider,@@ -79,79 +82,100 @@ def _install_fake_azure_identity(monkeypatch, credential_factory):monkeypatch.setitem(sys.modules, "azure.identity.aio", aio_mod)-def test_init_missing_key_uses_aad_token_provider(monkeypatch):- """Empty api_key falls back to DefaultAzureCredential via _AzureTokenProvider."""- credential_instance = MagicMock()- credential_factory = MagicMock(return_value=credential_instance)- _install_fake_azure_identity(monkeypatch, credential_factory)+async def azure_wire_requests(monkeypatch):+ """Inject only the HTTP transport; keep the SDK's request/auth path real."""+ requests: list[httpx.Request] = []- provider = AzureOpenAIProvider(- api_key="", api_base="https://res.openai.azure.com",- )+ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ body = json.loads(request.content)+ return httpx.Response(200, json={+ "id": f"resp_{len(requests)}", "object": "response", "created_at": 1,+ "status": "completed", "model": body["model"],+ "output": [{+ "type": "message", "id": f"msg_{len(requests)}",+ "role": "assistant", "status": "completed",+ "content": [{+ "type": "output_text", "text": f"reply {len(requests)}", "annotations": [],+ }],+ }],+ "usage": {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15},+ })- assert provider._token_provider is not None- assert isinstance(provider._token_provider, _AzureTokenProvider)- # DefaultAzureCredential must have been instantiated exactly once- credential_factory.assert_called_once_with()- assert provider._token_provider._credential is credential_instance- # The token provider must be wired into the OpenAI SDK as its- # ``_api_key_provider`` callable — that's what the SDK invokes per- # request to refresh the bearer token.- assert provider._client._api_key_provider is provider._token_provider- # Static api_key starts empty until the first refresh.- assert provider._client.api_key == ""+ async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:+ def create_client(**kwargs):+ return AsyncOpenAI(http_client=http_client, **kwargs)++ monkeypatch.setattr("nanobot.providers.azure_openai_provider.AsyncOpenAI", create_client)+ yield requests@pytest.mark.asyncio-async def test_aad_token_provider_wires_into_sdk_auth_headers(monkeypatch):- """Regression guard: the token provider must be wired into the- OpenAI SDK so ``_refresh_api_key`` pulls a fresh token and the- bearer ends up in ``auth_headers``. Without this, a refactor that- constructs ``_AzureTokenProvider`` but forgets to pass it to- ``AsyncOpenAI`` would silently send unauthenticated requests.- """- access_token = SimpleNamespace(token="token-A", expires_on=time.time() + 3600)+async def test_aad_token_provider_sends_rotating_bearer_tokens_on_chat_requests(+ monkeypatch, azure_wire_requests,+):credential_instance = MagicMock()- credential_instance.get_token = AsyncMock(return_value=access_token)+ credential_instance.get_token = AsyncMock(side_effect=[+ SimpleNamespace(token="token-A", expires_on=time.time() + 3600),+ SimpleNamespace(token="token-B", expires_on=time.time() + 3600),+ ])+ credential_instance.close = AsyncMock()credential_factory = MagicMock(return_value=credential_instance)_install_fake_azure_identity(monkeypatch, credential_factory)-provider = AzureOpenAIProvider(- api_key="", api_base="https://res.openai.azure.com",- )-- assert provider._client.api_key == ""- assert provider._client.auth_headers == {}-- await provider._client._refresh_api_key()-- assert provider._client.api_key == "token-A"- assert provider._client.auth_headers == {"Authorization": "Bearer token-A"}- credential_instance.get_token.assert_awaited_with(- "https://cognitiveservices.azure.com/.default"- )-- # Rotated token on second refresh proves per-request delegation (no client-side caching).- credential_instance.get_token = AsyncMock(- return_value=SimpleNamespace(token="token-B", expires_on=time.time() + 3600)- )- await provider._client._refresh_api_key()- assert provider._client.auth_headers == {"Authorization": "Bearer token-B"}+ api_key="", api_base="https://res.openai.azure.com", default_model="gpt-4o-deployment",+ )+ try:+ responses = [+ await provider.chat([{"role": "user", "content": f"turn {turn}"}])+ for turn in (1, 2)+ ]+ finally:+ await provider.aclose()++ assert [response.content for response in responses] == ["reply 1", "reply 2"]+ assert all(response.finish_reason == "stop" for response in responses)+ assert len(azure_wire_requests) == 2+ assert [request.headers.get("Authorization") for request in azure_wire_requests] == [+ "Bearer token-A", "Bearer token-B",+ ]+ assert all(request.method == "POST" for request in azure_wire_requests)+ assert all(+ str(request.url) == "https://res.openai.azure.com/openai/v1/responses"+ for request in azure_wire_requests+ )+ bodies = [json.loads(request.content) for request in azure_wire_requests]+ assert [body["model"] for body in bodies] == ["gpt-4o-deployment", "gpt-4o-deployment"]+ assert [body["input"][0]["content"][0]["text"] for body in bodies] == ["turn 1", "turn 2"]credential_factory.assert_called_once_with()+ assert credential_instance.get_token.await_args_list == [+ call("https://cognitiveservices.azure.com/.default"),+ call("https://cognitiveservices.azure.com/.default"),+ ]-def test_init_explicit_key_does_not_construct_credential(monkeypatch):- """Explicit api_key wins; DefaultAzureCredential must never be touched."""+async def test_explicit_key_sends_bearer_without_constructing_credential(+ monkeypatch, azure_wire_requests,+):+ """Explicit api_key wins through chat(), without invoking Azure credentials."""credential_factory = MagicMock(side_effect=AssertionError("DefaultAzureCredential must not be constructed when api_key is set"))_install_fake_azure_identity(monkeypatch, credential_factory)-provider = AzureOpenAIProvider(api_key="real-key", api_base="https://res.openai.azure.com",)+ try:+ response = await provider.chat([{"role": "user", "content": "hello"}])+ finally:+ await provider.aclose()- assert provider._token_provider is None+ assert response.content == "reply 1"+ assert response.finish_reason == "stop"+ assert len(azure_wire_requests) == 1+ assert azure_wire_requests[0].headers["Authorization"] == "Bearer real-key"credential_factory.assert_not_called()diff --git a/tests/providers/test_extra_body_config.py b/tests/providers/test_extra_body_config.pyindex 4bc5e419d..61fb1713a 100644--- a/tests/providers/test_extra_body_config.py+++ b/tests/providers/test_extra_body_config.py@@ -168,22 +168,6 @@ class TestBuildKwargsExtraBody:assert body.get("custom_param") == "value"assert body["thinking"] == {"type": "enabled"}- def test_nested_extra_body_does_not_clobber_siblings(self) -> None:- """Nested dict merge should preserve sibling keys."""- provider = _make_provider({- "chat_template_kwargs": {"enable_thinking": False},- })- # Simulate internal code having set a sibling key- # by manually calling _build_kwargs — the internal logic- # doesn't set chat_template_kwargs, so we test the merge path- # by having extra_body itself contain nested keys- kwargs = provider._build_kwargs(- messages=_simple_messages(),- tools=None, model=None, max_tokens=100,- temperature=0.1, reasoning_effort=None, tool_choice=None,- )- assert kwargs["extra_body"]["chat_template_kwargs"]["enable_thinking"] is False-def test_guided_json_injection(self) -> None:"""Real-world use case: vLLM guided decoding."""schema = {"type": "object", "properties": {"name": {"type": "string"}}}diff --git a/tests/providers/test_github_copilot_concurrent_token.py b/tests/providers/test_github_copilot_concurrent_token.pyindex cf595c870..fc726d68b 100644--- a/tests/providers/test_github_copilot_concurrent_token.py+++ b/tests/providers/test_github_copilot_concurrent_token.py@@ -12,11 +12,13 @@ from nanobot.providers import github_copilot_provider as gc@pytest.mark.asyncioasync def test_concurrent_token_refresh_fetches_once(monkeypatch):- """Two concurrent _get_copilot_access_token calls should trigger only one- HTTP fetch when the token is expired, not two."""+ """A competing caller waits for the in-flight exchange and reuses its token."""monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))fetch_count = 0+ entered = asyncio.Event()+ release = asyncio.Event()+ competing_started = asyncio.Event()class FakeResponse:def raise_for_status(self):@@ -38,82 +40,37 @@ async def test_concurrent_token_refresh_fetches_once(monkeypatch):async def get(self, url, *, headers):nonlocal fetch_countfetch_count += 1- # Simulate network latency so both coroutines overlap before the- # lock serializes them.- await asyncio.sleep(0.05)+ entered.set()+ await release.wait()return FakeResponse()monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)-provider = gc.GitHubCopilotProvider()- # Force token expiry.- provider._copilot_access_token = None- provider._copilot_expires_at = 0.0-- token_a, token_b = await asyncio.gather(- provider._get_copilot_access_token(),- provider._get_copilot_access_token(),- )-- assert token_a == "copilot-token"- assert token_b == "copilot-token"- assert fetch_count == 1, (- f"Expected exactly 1 token fetch under concurrency, got {fetch_count}"- )---async def test_second_call_returns_cached_token_while_first_in_flight(monkeypatch):- """If task A is mid-fetch inside the lock, task B should wait, then find- the cached token and skip the HTTP call entirely."""- monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))-- fetch_count = 0-- class FakeResponse:- def raise_for_status(self):- pass-- def json(self):- return {"token": "cached-token", "refresh_in": 1500}- class FakeAsyncClient:- def __init__(self, *args, **kwargs):- pass+ async def competing_call():+ # No suspension between this signal and entering the token path.+ competing_started.set()+ return await provider._get_copilot_access_token()- async def __aenter__(self):- return self-- async def __aexit__(self, *args):- return False-- async def get(self, url, *, headers):- nonlocal fetch_count- fetch_count += 1- await asyncio.sleep(0.1)- return FakeResponse()-- monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)-- provider = gc.GitHubCopilotProvider()- provider._copilot_access_token = None- provider._copilot_expires_at = 0.0-- # Start task A, let it acquire the lock and begin the HTTP fetch.task_a = asyncio.create_task(provider._get_copilot_access_token())- await asyncio.sleep(0.02) # task A is now inside the lock, mid-fetch-- # Task B starts while A is still in flight.- token_b = await provider._get_copilot_access_token()- token_a = await task_a-- assert token_a == "cached-token"- assert token_b == "cached-token"- assert fetch_count == 1---async def test_copilot_token_lock_exists():- """Provider should have an asyncio.Lock for token refresh."""- provider = gc.GitHubCopilotProvider()- assert isinstance(provider._copilot_token_lock, asyncio.Lock)+ tasks = [task_a]+ try:+ await asyncio.wait_for(entered.wait(), timeout=5)+ task_b = asyncio.create_task(competing_call())+ tasks.append(task_b)+ await asyncio.wait_for(competing_started.wait(), timeout=5)+ assert not task_a.done()+ assert not task_b.done()+ assert fetch_count == 1++ release.set()+ tokens = await asyncio.wait_for(asyncio.gather(*tasks), timeout=5)+ assert tokens == ["copilot-token", "copilot-token"]+ assert fetch_count == 1+ finally:+ release.set()+ for task in tasks:+ if not task.done():+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ await provider.aclose()diff --git a/tests/providers/test_llm_usage_observer.py b/tests/providers/test_llm_usage_observer.pyindex 3ef6662c4..921831c13 100644--- a/tests/providers/test_llm_usage_observer.py+++ b/tests/providers/test_llm_usage_observer.py@@ -1,8 +1,12 @@from __future__ import annotationsimport asyncio+import json+import sqlite3import threadingfrom collections.abc import Callable, Iterator+from contextlib import closing+from dataclasses import asdictfrom types import SimpleNamespaceimport pytest@@ -127,18 +131,30 @@ async def test_observer_receives_every_retry_attempt(stream: bool) -> None:@pytest.mark.asyncioasync def test_observer_estimates_missing_success_usage_without_storing_content() -> None:- provider = _SequenceProvider(iter([LLMResponse(content="hello")]))+ prompt = "observer-prompt-canary-38a7cf"+ reply = "observer-response-canary-92b6de"+ provider = _SequenceProvider(iter([LLMResponse(content=reply)]))events: list[LLMCallRecord] = []provider.set_llm_call_observer(events.append)response = await provider.chat_with_retry(- messages=[{"role": "user", "content": "hello"}],+ messages=[{"role": "user", "content": prompt}],)+ assert response.content == reply+ assert response.finish_reason == "stop"+ assert provider.calls == 1+ assert len(events) == 1+ assert events[0].finish_reason == "stop"assert response.usage is not Noneassert response.usage.source == "estimated"+ assert response.usage.input_tokens > 0+ assert response.usage.output_tokens > 0+ assert response.usage.estimated_tokens == response.usage.total_tokens > 0assert events[0].usage == response.usage- assert "content" not in LLMCallRecord.__dataclass_fields__+ serialized = json.dumps(asdict(events[0]))+ assert prompt not in serialized+ assert reply not in serialized@pytest.mark.asyncio@@ -342,26 +358,40 @@ async def test_usage_fast_paths_skip_local_estimation(stream: bool, kind: str) -async def test_gateway_usage_observer_records_missing_usage_and_retry(monkeypatch, tmp_path, stream: bool,) -> None:+ prompt = "gateway-prompt-canary-f6d5a4"+ reply = "gateway-response-canary-27be91"+ error = "gateway-error-canary-64a8cd"store = LLMUsageStore(tmp_path / "usage.sqlite3")monkeypatch.setattr("nanobot.llm_usage.service.get_llm_usage_store", lambda: store)provider = _SequenceProvider(iter([- LLMResponse(content="temporary failure", finish_reason="error", error_kind="timeout"),- LLMResponse(content="hello"),+ LLMResponse(content=error, finish_reason="error", error_kind="timeout"),+ LLMResponse(content=reply),]))provider.set_llm_call_observer(record_llm_call)call = provider.chat_stream_with_retry if stream else provider.chat_with_retrytry:with llm_usage_source("api"):- response = await call(messages=[{"role": "user", "content": "hello"}])- assert response.content == "hello"+ response = await call(messages=[{"role": "user", "content": prompt}])+ assert response.content == replyassert response.usage is not None and response.usage.source == "estimated"+ assert response.usage.input_tokens > 0+ assert response.usage.output_tokens > 0+ assert response.usage.estimated_tokens == response.usage.total_tokens > 0assert provider.calls == 2- records = list(reversed(store.recent_calls()))+ with closing(sqlite3.connect(store.path)) as connection:+ connection.row_factory = sqlite3.Row+ records = [dict(row) for row in connection.execute("SELECT * FROM llm_calls ORDER BY id")]+ assert len(records) == 2assert [record["finish_reason"] for record in records] == ["error", "stop"]+ assert records[0]["error_kind"] == "timeout"assert all(record["source"] == "api" for record in records)assert all(record["stream"] == int(stream) for record in records)assert records[0]["total_tokens"] is Noneassert records[1]["total_tokens"] == response.usage.total_tokens+ assert records[1]["estimated_tokens"] == response.usage.estimated_tokens+ serialized = json.dumps(records)+ for canary in (prompt, reply, error):+ assert canary not in serializedfinally:store.close()diff --git a/tests/providers/test_openai_codex_provider.py b/tests/providers/test_openai_codex_provider.pyindex 7070c1916..580334dd5 100644--- a/tests/providers/test_openai_codex_provider.py+++ b/tests/providers/test_openai_codex_provider.py@@ -88,33 +88,19 @@ async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeypassert request_contexts == [context, context, context]-class _WarningCaptureLogger:- def __init__(self) -> None:- self.calls: list[tuple[str, tuple[Any, ...]]] = []-- def warning(self, *args: Any, **kwargs: Any) -> None:- self.calls.append((args[0], args[1:]))-- def exception(self, message: str, *args: Any, **kwargs: Any) -> None:- raise AssertionError("Codex diagnostics must not log exception tracebacks")---def _capture_codex_warnings(monkeypatch: pytest.MonkeyPatch) -> _WarningCaptureLogger:- capture = _WarningCaptureLogger()- monkeypatch.setattr("nanobot.providers.openai_codex_provider.logger", capture)- return capture---def test_codex_blank_timeout_root_cause_reproduction() -> None:- """Document why upstream produced a bare ``Error calling Codex:`` message."""- exc = httpx.ReadTimeout("")- legacy_content = f"Error calling Codex: {exc}"-- assert str(exc) == ""- assert legacy_content == "Error calling Codex: "- legacy_response = provider_base.LLMResponse(content=legacy_content, finish_reason="error")- assert legacy_response.error_kind is None- assert legacy_response.error_should_retry is None+def codex_warning_log(monkeypatch):+ monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)+ sink = io.StringIO()+ logger.enable("nanobot")+ handler_id = logger.add(+ sink, format="{message}", level="WARNING",+ filter="nanobot.providers.openai_codex_provider", backtrace=True, diagnose=True,+ )+ try:+ yield sink+ finally:+ logger.remove(handler_id)def test_codex_http_friendly_error_omits_raw_body() -> None:@@ -245,10 +231,9 @@ async def test_codex_title_failure_logs_request_purpose_and_safe_upstream_detail@pytest.mark.asyncio@pytest.mark.parametrize("failed_stage", ["codex_compaction", "codex_request"])async def test_codex_diagnostics_distinguish_compaction_from_following_request(- monkeypatch, failed_stage,+ monkeypatch, codex_warning_log, failed_stage,) -> None:_mock_codex_token(monkeypatch)- capture = _capture_codex_warnings(monkeypatch)state_provider = "openai_codex:https://chatgpt.com/backend-api/codex/responses"state = build_responses_state(provider=state_provider, model="gpt-5.6-sol",@@ -278,14 +263,17 @@ async def test_codex_diagnostics_distinguish_compaction_from_following_request(),)assert response.finish_reason == "error"- template, args = capture.calls[-1]- log = template.format(*args)+ logs = codex_warning_log.getvalue().splitlines()+ assert len(logs) == 1+ log = logs[0]assert f"stage={failed_stage}" in logassert f"compaction_applied={failed_stage == 'codex_request'}" in logassert "replayed=True" in logassert "reasoning_effort=low" in logassert "error_param=input[1].type" in log+ assert "request_id=req-compaction-test" in logassert "PRIVATE STATE" not in log+ assert "Traceback" not in log@pytest.mark.asyncio@@ -623,47 +611,38 @@ async def test_codex_provider_passes_proxy_to_oauth_and_response_request(monkeyp@pytest.mark.asyncio-async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch) -> None:- log_capture = _capture_codex_warnings(monkeypatch)+async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch, codex_warning_log) -> None:_mock_codex_token(monkeypatch)+ prompt = "timeout-prompt-canary-38bc7a"- async def fake_request(*args: Any, **kwargs: Any):+ async def fake_request(_url, _headers, body, **_kwargs):+ assert body["input"][0]["content"][0]["text"] == promptraise httpx.ReadTimeout("")monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)provider = OpenAICodexProvider()- response = await provider.chat([{"role": "user", "content": "hello"}])+ response = await provider.chat(+ [{"role": "user", "content": prompt}],+ model="openai-codex/gpt-5.6-sol", reasoning_effort="high",+ )assert response.content == ("Error calling Codex (ReadTimeout): timed out waiting for response")- assert log_capture.calls == [- (- "Codex API request failed: stage={} type={} kind={} retryable={} status={} "- "error_type={} error_code={} retry_after={} summary={} "- "model={} reasoning_effort={} replayed={} compaction_applied={} "- "error_param={} error_message={} request_id={}",- (- "codex_request",- "ReadTimeout",- "timeout",- True,- None,- None,- None,- None,- "ReadTimeout timeout",- "gpt-5.6-sol",- None,- False,- False,- None,- None,- None,- ),- )- ]+ logs = codex_warning_log.getvalue().splitlines()+ assert len(logs) == 1+ log = logs[0]+ for field in (+ "Codex API request failed", "stage=codex_request", "type=ReadTimeout",+ "kind=timeout", "retryable=True", "status=None", "error_type=None",+ "error_code=None", "retry_after=None", "summary=ReadTimeout timeout",+ "model=gpt-5.6-sol", "reasoning_effort=high", "replayed=False",+ "compaction_applied=False", "error_param=None", "error_message=None", "request_id=None",+ ):+ assert field in log+ assert prompt not in log+ assert "Traceback" not in log@pytest.mark.asyncio@@ -751,50 +730,60 @@ async def test_codex_http_error_preserves_status_and_retry_after(monkeypatch) ->@pytest.mark.asyncio-async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch) -> None:- log_capture = _capture_codex_warnings(monkeypatch)+async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch, codex_warning_log) -> None:_mock_codex_token(monkeypatch)+ original_client = httpx.AsyncClient+ prompt = "http-prompt-canary-471fde"+ upstream_body = "http-upstream-body-canary-639ca2"+ requests: list[httpx.Request] = []- async def fake_request(*args: Any, **kwargs: Any):- raise _CodexHTTPError(- _friendly_error(500, "raw upstream body with PRIVATE PROMPT MUST NOT APPEAR"),- status_code=500,- error_type="server_error",- error_code="overloaded",- )+ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ assert prompt.encode() in request.content+ return httpx.Response(500, headers={+ "retry-after": "2.5", "x-request-id": "req-http-diagnostic",+ }, json={+ "error": {+ "type": "server_error", "code": "overloaded",+ "param": "input[0].content", "message": upstream_body,+ },+ "private": upstream_body,+ })- monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)+ def fake_client(**kwargs):+ return original_client(transport=httpx.MockTransport(handler))+ monkeypatch.setattr("nanobot.providers.openai_codex_provider.httpx.AsyncClient", fake_client)provider = OpenAICodexProvider()- response = await provider.chat([{"role": "user", "content": "hello"}])+ try:+ response = await provider.chat(+ [{"role": "user", "content": prompt}],+ model="openai-codex/gpt-5.6-sol", reasoning_effort="high",+ )+ finally:+ await provider.aclose()+ assert len(requests) == 1+ assert response.finish_reason == "error"assert response.content == "Error calling Codex (CodexHTTPError): HTTP 500: Codex API request failed"- assert log_capture.calls == [- (- "Codex API request failed: stage={} type={} kind={} retryable={} status={} "- "error_type={} error_code={} retry_after={} summary={} "- "model={} reasoning_effort={} replayed={} compaction_applied={} "- "error_param={} error_message={} request_id={}",- (- "codex_request",- "CodexHTTPError",- "http",- True,- 500,- "server_error",- "overloaded",- None,- "HTTP 500 type=server_error code=overloaded",- "gpt-5.6-sol",- None,- False,- False,- None,- None,- None,- ),- )- ]+ assert response.error_status_code == 500+ assert response.error_should_retry is True+ logs = codex_warning_log.getvalue().splitlines()+ assert len(logs) == 1+ log = logs[0]+ for field in (+ "Codex API request failed", "stage=codex_request", "type=CodexHTTPError",+ "kind=http", "retryable=True", "status=500", "error_type=server_error",+ "error_code=overloaded", "retry_after=2.5",+ "summary=HTTP 500 type=server_error code=overloaded", "model=gpt-5.6-sol",+ "reasoning_effort=high", "replayed=False", "compaction_applied=False",+ "error_param=input[0].content", "error_message=None", "request_id=req-http-diagnostic",+ ):+ assert field in log+ for secret in (prompt, upstream_body):+ assert secret not in log+ assert secret not in response.content+ assert "Traceback" not in log@pytest.mark.asynciodiff --git a/tests/providers/test_sanitize_surrogates.py b/tests/providers/test_sanitize_surrogates.pyindex 9d69eff0f..7c40b62d4 100644--- a/tests/providers/test_sanitize_surrogates.py+++ b/tests/providers/test_sanitize_surrogates.py@@ -62,17 +62,18 @@ class TestSanitizeSurrogatesDeep:"role": "user","content": [{"type": "text", "text": "hello \ud83e world"},- {"type": "text", "text": "normal"},+ {"type": "text", "text": "normal 🤖"},],}cleaned = sanitize_surrogates_deep(dirty)assert cleaned is not dirty # rebuiltfirst = cleaned["content"][0]["text"]assert "\ud83e" not in first+ assert cleaned["content"][1]["text"] == "normal 🤖"# Full payload must be UTF-8 encodable.import json- json.dumps(cleaned).encode("utf-8")+ json.dumps(cleaned, ensure_ascii=False).encode("utf-8")def test_paired_surrogates_in_list_collapse_to_emoji(self):dirty = ["a", "b \ud83e\udd16", "c"]@@ -150,13 +151,16 @@ class TestProviderSanitizeEmptyContent:{"role": "assistant","content": [- {"type": "text", "text": "answer with a lone \ud83e half"},+ {"type": "text", "text": "answer with a lone \ud83e half and paired \ud83e\udd16"},],},]cleaned = LLMProvider._sanitize_empty_content(messages)# This is the operation that previously raised UnicodeEncodeError.- json.dumps({"model": "x", "messages": cleaned}).encode("utf-8")+ json.dumps({"model": "x", "messages": cleaned}, ensure_ascii=False).encode("utf-8")+ assert cleaned[0]["content"] == "You are a 🐱 assistant."+ assert cleaned[1]["content"] == "🤖 fixed?"+ assert cleaned[2]["content"][0]["text"] == "answer with a lone \ufffd half and paired 🤖"class TestBackwardCompatReExport:diff --git a/tests/providers/test_transcription.py b/tests/providers/test_transcription.pyindex 225f0179d..99ae1258a 100644--- a/tests/providers/test_transcription.py+++ b/tests/providers/test_transcription.py@@ -418,38 +418,6 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:# ----------------------------------------------------------------------------async def test_openai_retries_on_5xx_then_succeeds(audio_file: Path) -> None:- """Transient 503 is retried; a subsequent 200 yields the text."""- provider = OpenAITranscriptionProvider(api_key="sk-test")- post = AsyncMock(side_effect=[_response(503), _response(200, {"text": "hello"})])- with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):- result = await provider.transcribe(audio_file)- assert result == "hello"- assert post.await_count == 2---async def test_openai_retries_on_429_then_succeeds(audio_file: Path) -> None:- provider = OpenAITranscriptionProvider(api_key="sk-test")- post = AsyncMock(side_effect=[_response(429), _response(200, {"text": "rate ok"})])- with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):- result = await provider.transcribe(audio_file)- assert result == "rate ok"- assert post.await_count == 2---async def test_openai_retries_on_connect_error(audio_file: Path) -> None:- """Network-level transient errors are retried."""- provider = OpenAITranscriptionProvider(api_key="sk-test")- post = AsyncMock(side_effect=[httpx.ConnectError("boom"), _response(200, {"text": "ok"})])- with patch("httpx.AsyncClient.post", post), patch("asyncio.sleep", AsyncMock()):- result = await provider.transcribe(audio_file)- assert result == "ok"- assert post.await_count == 2--@pytest.mark.asyncioasync def test_openai_does_not_retry_on_auth_error(audio_file: Path) -> None:"""401 is the user's misconfiguration — retrying wastes time and rate-limit quota."""diff --git a/tests/session/test_recovery.py b/tests/session/test_recovery.pyindex e3c0fbc69..249f713b6 100644--- a/tests/session/test_recovery.py+++ b/tests/session/test_recovery.py@@ -22,6 +22,15 @@ from nanobot.webui import session_list_index, transcriptfrom nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator[email protected](autouse=True)+def _isolate_webui_transcripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """Recovery scans must discover only test-owned transcripts, not active user chats."""+ webui_dir = tmp_path / "isolated-webui"+ webui_dir.mkdir()+ monkeypatch.setattr(session_list_index, "get_webui_dir", lambda: webui_dir)+ monkeypatch.setattr(transcript, "get_webui_dir", lambda: webui_dir)++def _persist(manager: SessionManager, session: Session) -> None:session.metadata["webui"] = Truemanager.save(session)@@ -732,26 +741,59 @@ async def test_scan_failure_is_visible_instead_of_aborting_other_sessions(monkeypatch: pytest.MonkeyPatch,) -> None:coordinator, bus, sessions = _coordinator(tmp_path)- session = sessions.get_or_create("websocket:chat")- session.metadata[PENDING_USER_TURN_KEY] = True- _persist(sessions, session)-- async def fail(*_args: object, **_kwargs: object) -> None:- raise RuntimeError("boom")-- monkeypatch.setattr(RecoveryCoordinator, "_recover_session", fail)- await coordinator.scan()-- state = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]- assert state["status"] == "failed"- assert state["can_continue"] is False- assert isinstance(bus.outbound.get_nowait().event, RecoveryStateEvent)-- with pytest.raises(RecoveryActionError, match="context is unavailable"):- await coordinator.handle_action(- "continue",- {"chat_id": "chat", "recovery_id": state["recovery_id"]},- )+ keys = {"websocket:first", "websocket:second"}+ for key in sorted(keys):+ session = sessions.get_or_create(key)+ session.add_message("user", f"finish {key}")+ session.metadata[PENDING_USER_TURN_KEY] = True+ _persist(sessions, session)+ recover_session = RecoveryCoordinator._recover_session+ attempted = []++ async def fail_first(self, session: Session, chat_id: str) -> None:+ attempted.append((session.key, chat_id))+ if len(attempted) == 1:+ raise RuntimeError("boom")+ await recover_session(self, session, chat_id)++ monkeypatch.setattr(RecoveryCoordinator, "_recover_session", fail_first)+ try:+ await coordinator.scan()++ assert len(attempted) == 2+ assert {key for key, _ in attempted} == keys+ failed_key, failed_chat = attempted[0]+ healthy_key, healthy_chat = attempted[1]+ state = sessions.read_session_snapshot(failed_key).metadata[RECOVERY_METADATA_KEY]+ assert state["status"] == "failed"+ assert state["reason"] == "recovery_failed"+ assert state["can_continue"] is False+ healthy = sessions.read_session_snapshot(healthy_key)+ healthy_state = healthy.metadata[RECOVERY_METADATA_KEY]+ assert healthy_state["status"] == "awaiting_user"+ assert healthy_state["reason"] == "restart_requires_confirmation"+ assert healthy.metadata[PENDING_USER_TURN_KEY] is True+ assert [message["content"] for message in healthy.messages] == [f"finish {healthy_key}"]+ assert bus.inbound.empty()+ messages = []+ while not bus.outbound.empty():+ messages.append(bus.outbound.get_nowait())+ recovery_messages = [message for message in messages if isinstance(message.event, RecoveryStateEvent)]+ assert [(message.channel, message.chat_id, message.event.status, message.event.recovery_id)+ for message in recovery_messages] == [+ ("websocket", failed_chat, "failed", state["recovery_id"]),+ ("websocket", healthy_chat, "awaiting_user", healthy_state["recovery_id"]),+ ]+ assert recovery_messages[0].event.can_continue is False+ assert recovery_messages[1].event.reason == "restart_requires_confirmation"++ with pytest.raises(RecoveryActionError, match="context is unavailable"):+ await coordinator.handle_action(+ "continue",+ {"chat_id": failed_chat, "recovery_id": state["recovery_id"]},+ )+ finally:+ await sessions.state.aclose()@pytest.mark.asynciodiff --git a/tests/session/test_sqlite_storage.py b/tests/session/test_sqlite_storage.pyindex 689594e0e..9eb174dc1 100644--- a/tests/session/test_sqlite_storage.py+++ b/tests/session/test_sqlite_storage.py@@ -293,15 +293,27 @@ async def test_detached_reads_do_not_publish_mutations(tmp_path):async def test_checkpoint_does_not_rewrite_messages(tmp_path):manager = SessionManager(tmp_path)state = manager.state- draft = await state.get("chat:a")- draft.add_message("user", "hello")- await state.prepare_input(draft)- path = manager.sessions_dir / "sessions.sqlite3"- with sqlite3.connect(path) as db:- db.execute("CREATE TRIGGER prohibit_rewrite BEFORE UPDATE ON messages BEGIN SELECT RAISE(ABORT, 'rewritten'); END")- await state.checkpoint_view(draft, {"step": 1})- assert (await state.get(draft.key)).metadata["runtime_checkpoint"] == {"step": 1}- await state.aclose()+ try:+ draft = await state.import_messages("chat:a", [+ {"role": "user", "content": "earlier question"},+ {"role": "assistant", "content": "earlier answer"},+ ])+ draft.add_message("user", "hello")+ await state.prepare_input(draft)+ accepted = manager.read_session_snapshot(draft.key).messages+ assert accepted == draft.messages+ path = manager.sessions_dir / "sessions.sqlite3"+ with sqlite3.connect(path) as db:+ for operation in ("INSERT", "UPDATE", "DELETE"):+ db.execute(f"""CREATE TRIGGER prohibit_{operation.lower()} BEFORE {operation} ON messages+ BEGIN SELECT RAISE(ABORT, 'rewritten'); END""")+ await state.checkpoint_view(draft, {"step": 1})+ finally:+ await state.aclose()++ stored = manager.read_session_snapshot(draft.key)+ assert stored.messages == accepted+ assert stored.metadata["runtime_checkpoint"] == {"step": 1}async def test_database_lock_does_not_block_event_loop(tmp_path):diff --git a/tests/session/test_turn_continuation.py b/tests/session/test_turn_continuation.pyindex f7af97eb5..63666cb37 100644--- a/tests/session/test_turn_continuation.py+++ b/tests/session/test_turn_continuation.py@@ -156,15 +156,6 @@ def test_internal_continuation_requires_budget_boundary_and_queue():)-def test_save_skip_matches_prefix_when_current_message_was_persisted():- skip = _save_skip_for_turn(- message_metadata=None,- initial_message_count=3, # [system, history user, current user]- input_persisted_early=True,- )- assert skip == 3--def test_save_skip_unchanged_for_standalone_current_message():# [system, history user, current user] with the current user already saved.assert _save_skip_for_turn(diff --git a/tests/test_api_attachment.py b/tests/test_api_attachment.pyindex 625d23285..7b9df945c 100644--- a/tests/test_api_attachment.py+++ b/tests/test_api_attachment.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport base64from io import BytesIO+from pathlib import Pathfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -235,29 +236,35 @@ async def test_multipart_upload_saves_file(aiohttp_client, mock_agent, tmp_path)@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")@pytest.mark.asyncio-async def test_multipart_multiple_files(aiohttp_client, mock_agent, tmp_path) -> None:+async def test_multipart_multiple_files(aiohttp_client, mock_agent, tmp_path, monkeypatch) -> None:"""Multipart upload with multiple files saves all and passes paths."""- import os- original_cwd = os.getcwd()- os.chdir(tmp_path)+ import aiohttp- try:- app = create_app(mock_agent, model_name="m", api_key=API_KEY)- client = await aiohttp_client(app)+ media_dir = tmp_path / "media"+ media_dir.mkdir()+ monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: media_dir)+ app = create_app(mock_agent, model_name="m", api_key=API_KEY)+ client = await aiohttp_client(app)- # Note: aiohttp test client has limited multipart support- # This test verifies the basic flow- file_data = b"test content"- data = BytesIO(file_data)+ files = [("first.txt", b"first file content"), ("second.bin", b"\x00second file\xff")]+ data = aiohttp.FormData()+ data.add_field("message", "analyze both files")+ for filename, payload in files:+ data.add_field("files", payload, filename=filename, content_type="application/octet-stream")- resp = await client.post(- "/v1/chat/completions",- headers=AUTH_HEADERS,- data={"message": "analyze", "files": data},- )- assert resp.status == 200- finally:- os.chdir(original_cwd)+ resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)++ assert resp.status == 200+ mock_agent.process_direct.assert_called_once()+ mock_agent.process_direct.assert_awaited_once()+ call_kwargs = mock_agent.process_direct.call_args.kwargs+ assert call_kwargs["content"] == "analyze both files"+ saved_paths = [Path(path) for path in call_kwargs["media"]]+ assert len(saved_paths) == 2+ assert saved_paths[0] != saved_paths[1]+ for path, (_, payload) in zip(saved_paths, files, strict=True):+ assert path.parent == media_dir+ assert path.read_bytes() == payload@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")diff --git a/tests/test_api_stream.py b/tests/test_api_stream.pyindex 3e267b764..a02e4ed24 100644--- a/tests/test_api_stream.py+++ b/tests/test_api_stream.py@@ -243,35 +243,6 @@ async def test_stream_sse_chunk_ids_are_consistent(aiohttp_client) -> None:assert chunk_ids.pop().startswith("chatcmpl-")[email protected](not HAS_AIOHTTP, reason="aiohttp not installed")-async def test_stream_passes_on_stream_callbacks(aiohttp_client) -> None:- """process_direct should be called with on_stream and on_stream_end when streaming."""- captured_kwargs: dict = {}-- async def fake_process_direct(**kwargs):- captured_kwargs.update(kwargs)- if kwargs.get("on_stream_end"):- await kwargs["on_stream_end"]()- return "done"-- agent = MagicMock()- agent.process_direct = fake_process_direct- agent.aclose = AsyncMock()-- app = create_app(agent, model_name="m", api_key=API_KEY)- client = await aiohttp_client(app)-- resp = await client.post(- "/v1/chat/completions",- headers=AUTH_HEADERS,- json={"messages": [{"role": "user", "content": "hi"}], "stream": True},- )- assert resp.status == 200- assert captured_kwargs.get("on_stream") is not None- assert captured_kwargs.get("on_stream_end") is not None--@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")@pytest.mark.asyncioasync def test_stream_segment_end_does_not_close_sse(aiohttp_client) -> None:diff --git a/tests/test_docker.sh b/tests/test_docker.shindex 1e5513383..6262d7910 100644--- a/tests/test_docker.sh+++ b/tests/test_docker.sh@@ -2,21 +2,39 @@set -euo pipefailcd "$(dirname "$0")/.." || exit 1-IMAGE_NAME="nanobot-test"+RUN_ID="$$-${RANDOM}"+IMAGE_NAME="nanobot-test-${RUN_ID}"+CONTAINER_NAME="nanobot-test-run-${RUN_ID}"+ONBOARDED_IMAGE="nanobot-test-onboarded-${RUN_ID}"++cleanup() {+ result=$?+ trap - EXIT+ echo ""+ echo "=== Cleanup ==="+ docker rm -f "$CONTAINER_NAME" > /dev/null 2>&1 || true+ docker rmi -f "$ONBOARDED_IMAGE" "$IMAGE_NAME" > /dev/null 2>&1 || true+ exit "$result"+}+trap cleanup EXITecho "=== Building Docker image ==="docker build -t "$IMAGE_NAME" .echo ""echo "=== Running 'nanobot onboard' ==="-docker run --name nanobot-test-run "$IMAGE_NAME" onboard+docker run --name "$CONTAINER_NAME" "$IMAGE_NAME" onboardecho ""echo "=== Running 'nanobot status' ==="-STATUS_OUTPUT=$(docker commit nanobot-test-run nanobot-test-onboarded > /dev/null && \- docker run --rm nanobot-test-onboarded status 2>&1) || true--echo "$STATUS_OUTPUT"+docker commit "$CONTAINER_NAME" "$ONBOARDED_IMAGE" > /dev/null+if STATUS_OUTPUT=$(docker run --rm "$ONBOARDED_IMAGE" status 2>&1); then+ echo "$STATUS_OUTPUT"+else+ result=$?+ echo "$STATUS_OUTPUT"+ exit "$result"+fiecho ""echo "=== Validating output ==="@@ -47,10 +65,4 @@ elseexit 1fi-# Cleanup-echo ""-echo "=== Cleanup ==="-docker rm -f nanobot-test-run 2>/dev/null || true-docker rmi -f nanobot-test-onboarded 2>/dev/null || true-docker rmi -f "$IMAGE_NAME" 2>/dev/null || trueecho "Done."diff --git a/tests/test_docker_smoke.py b/tests/test_docker_smoke.pynew file mode 100644index 000000000..848103ce5--- /dev/null+++ b/tests/test_docker_smoke.py@@ -0,0 +1,99 @@+"""Exercise the Docker smoke script's failure and resource-ownership contract."""++from __future__ import annotations++import json+import os+import shutil+import subprocess+import sys+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest++pytestmark = pytest.mark.skipif(+ sys.platform == "win32" or shutil.which("bash") is None,+ reason="the Docker smoke script runs under Unix Bash",+)+SCRIPT = Path(__file__).with_name("test_docker.sh")+++def docker_boundary(tmp_path):+ executable = tmp_path / "bin" / "docker"+ executable.parent.mkdir()+ executable.write_text(+ f"#!{sys.executable}\n"+ "import json, os, sys\n"+ "args = sys.argv[1:]\n"+ "with open(os.environ['DOCKER_CALLS'], 'a') as log:\n"+ " log.write(json.dumps(args) + '\\n')\n"+ "stage = args[0]\n"+ "if stage == 'run': stage = args[-1]\n"+ "if stage == 'status':\n"+ " print('nanobot Status\\nConfig: configured\\nWorkspace: ready\\nModel: test\\n'\n"+ " 'OpenRouter API: unset\\nAnthropic API: unset\\nOpenAI API: unset')\n"+ "if stage == os.environ.get('DOCKER_FAIL_STAGE'): sys.exit(23)\n",+ encoding="utf-8",+ )+ executable.chmod(0o755)++ def run(name, *, fail_stage=""):+ log = tmp_path / f"{name}.jsonl"+ result = subprocess.run(+ ["bash", str(SCRIPT)],+ env={+ **os.environ,+ "PATH": f"{executable.parent}{os.pathsep}{os.environ.get('PATH', '')}",+ "DOCKER_CALLS": str(log),+ "DOCKER_FAIL_STAGE": fail_stage,+ },+ capture_output=True,+ text=True,+ timeout=20,+ check=False,+ )+ calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]+ return result, calls++ return run+++def _assert_owned_cleanup(calls):+ image = calls[0][2]+ suffix = image.removeprefix("nanobot-test-")+ assert suffix and suffix != image+ container = f"nanobot-test-run-{suffix}"+ onboarded = f"nanobot-test-onboarded-{suffix}"+ assert calls[-2:] == [["rm", "-f", container], ["rmi", "-f", onboarded, image]]+ for call in calls:+ if call[0] == "run" and call[-1] == "onboard":+ assert call == ["run", "--name", container, image, "onboard"]+ elif call[0] == "commit":+ assert call == ["commit", container, onboarded]+ elif call[0] == "run" and call[-1] == "status":+ assert call == ["run", "--rm", onboarded, "status"]+ return {image, container, onboarded}++[email protected]("stage", ["build", "onboard", "commit", "status"])+def test_smoke_failure_preserves_exit_and_cleans_only_owned_resources(docker_boundary, stage):+ result, calls = docker_boundary(stage, fail_stage=stage)+ assert result.returncode == 23, result.stdout + result.stderr+ assert "All checks passed" not in result.stdout+ _assert_owned_cleanup(calls)+ if stage == "status":+ # Valid-looking output must never turn a failed status process green.+ assert "nanobot Status" in result.stdout+++def test_concurrent_smoke_runs_use_distinct_resources_and_cleanup(docker_boundary):+ with ThreadPoolExecutor(max_workers=2) as executor:+ runs = list(executor.map(docker_boundary, ["first", "second"]))+ resources = []+ for result, calls in runs:+ assert result.returncode == 0, result.stdout + result.stderr+ assert "All checks passed" in result.stdout+ resources.append(_assert_owned_cleanup(calls))+ assert resources[0].isdisjoint(resources[1])diff --git a/tests/test_openai_api.py b/tests/test_openai_api.pyindex 48cc41490..1b5647545 100644--- a/tests/test_openai_api.py+++ b/tests/test_openai_api.py@@ -240,19 +240,6 @@ async def test_no_user_message_returns_400(aiohttp_client, app) -> None:assert resp.status == 400[email protected](not HAS_AIOHTTP, reason="aiohttp not installed")-async def test_stream_true_returns_sse(aiohttp_client, app) -> None:- client = await aiohttp_client(app)- resp = await client.post(- "/v1/chat/completions",- headers=AUTH_HEADERS,- json={"messages": [{"role": "user", "content": "hello"}], "stream": True},- )- assert resp.status == 200- assert resp.content_type == "text/event-stream"--@pytest.mark.asyncioasync def test_model_mismatch_returns_400() -> None:request = MagicMock()diff --git a/tests/test_truncate_text_shadowing.py b/tests/test_truncate_text_shadowing.pydeleted file mode 100644index deabaf80f..000000000--- a/tests/test_truncate_text_shadowing.py+++ /dev/null@@ -1,12 +0,0 @@-from types import SimpleNamespace---def test_sanitize_persisted_blocks_preserves_tool_text() -> None:- from nanobot.agent.loop import AgentLoop-- dummy = SimpleNamespace()- content = [{"type": "text", "text": "0123456789"}]-- out = AgentLoop._sanitize_persisted_blocks(dummy, content)- assert out == content-diff --git a/tests/tools/test_apply_patch_tool.py b/tests/tools/test_apply_patch_tool.pyindex d2f11e9cd..18ccbd30a 100644--- a/tests/tools/test_apply_patch_tool.py+++ b/tests/tools/test_apply_patch_tool.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+from pathlib import Pathimport pytest@@ -415,7 +416,7 @@ def test_apply_patch_edits_reports_invalid_edit_shapes(tmp_path):assert "each edit must be an object" in non_object-def test_apply_patch_edits_rolls_back_when_late_operation_fails(tmp_path):+def test_apply_patch_preflight_rejects_missing_later_file_without_partial_write(tmp_path):first = tmp_path / "first.txt"first.write_text("before\n")tool = ApplyPatchTool(workspace=tmp_path)@@ -441,3 +442,51 @@ def test_apply_patch_edits_rolls_back_when_late_operation_fails(tmp_path):assert "file to update does not exist: missing.txt" in resultassert first.read_text() == "before\n"++[email protected]("first_exists", [True, False], ids=["existing-file", "added-file"])+def test_apply_patch_edits_rolls_back_when_later_write_fails(tmp_path, monkeypatch, first_exists):+ first = tmp_path / "first.txt"+ first_original = b"before\r\nfirst tail"+ if first_exists:+ first.write_bytes(first_original)+ second = tmp_path / "second.txt"+ second_original = b"before\r\nsecond tail"+ second.write_bytes(second_original)+ tool = ApplyPatchTool(workspace=tmp_path)+ write_text = Path.write_text+ failed = False++ def _fail_second_write(path, *args, **kwargs):+ nonlocal failed+ written = write_text(path, *args, **kwargs)+ if path == second and not failed:+ failed = True+ # A persistence error can occur after the file has already changed.+ raise OSError("injected second write failure")+ return written++ monkeypatch.setattr(Path, "write_text", _fail_second_write)++ result = asyncio.run(+ tool.execute(+ edits=[+ {"path": "first.txt", "action": "add", "new_text": "after"},+ {+ "path": "second.txt",+ "action": "replace",+ "old_text": "before",+ "new_text": "after",+ },+ ]+ )+ )++ assert failed+ assert getattr(result, "is_error", False)+ assert "Error applying patch: injected second write failure" in result+ if first_exists:+ assert first.read_bytes() == first_original+ else:+ assert not first.exists()+ assert second.read_bytes() == second_originaldiff --git a/tests/tools/test_edit_enhancements.py b/tests/tools/test_edit_enhancements.pyindex 4b2ebcf29..2710dad9e 100644--- a/tests/tools/test_edit_enhancements.py+++ b/tests/tools/test_edit_enhancements.py@@ -136,7 +136,7 @@ class TestEditIpynbFiles:new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',)assert "Patch applied:" in result- assert '"source": "hi"' in f.read_text(encoding="utf-8")+ assert f.read_text(encoding="utf-8") == '{"cells": [{"cell_type": "markdown", "source": "hi"}]}'# ---------------------------------------------------------------------------diff --git a/tests/tools/test_exec_env.py b/tests/tools/test_exec_env.pyindex 9bacb1a01..f623faad8 100644--- a/tests/tools/test_exec_env.py+++ b/tests/tools/test_exec_env.py@@ -1,22 +1,61 @@"""Tests for exec tool environment isolation."""+import json+import shleximport sysimport pytest+from nanobot.agent.tools.exec_session import ExecSessionManagerfrom nanobot.agent.tools.shell import ExecTool_UNIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="Unix shell commands")-@_UNIX_ONLY@pytest.mark.asyncio-async def test_exec_does_not_leak_parent_env(monkeypatch):- """Env vars from the parent process must not be visible to commands."""+ "allowed_env_keys, expected_allowed",+ [+ pytest.param(None, None, id="default-filtering"),+ pytest.param(+ ["MY_CUSTOM_VAR", "NONEXISTENT_VAR_12345"],+ "hello-from-config",+ id="configured-passthrough",+ ),+ ],+)+ "command_mode", [pytest.param("shell", marks=_UNIX_ONLY), "argv"],+)+async def test_exec_child_receives_filtered_env(monkeypatch, allowed_env_keys, expected_allowed, command_mode):+ """A successful child receives allowed values, but not secrets or unset keys."""+ monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")monkeypatch.setenv("NANOBOT_SECRET_TOKEN", "super-secret-value")- tool = ExecTool()- result = await tool.execute(command="printenv NANOBOT_SECRET_TOKEN")- assert "super-secret-value" not in result+ monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)+ marker = "ENV_PROBE_COMPLETE "+ script = (+ "import json, os; "+ "keys = ['MY_CUSTOM_VAR', 'NANOBOT_SECRET_TOKEN', 'NONEXISTENT_VAR_12345']; "+ f"print({marker!r} + json.dumps({{key: os.environ.get(key) for key in keys}}))"+ )+ argv = [sys.executable, "-c", script]+ command = shlex.join(argv) if command_mode == "shell" else argv+ manager = ExecSessionManager()+ tool = ExecTool(allowed_env_keys=allowed_env_keys, session_manager=manager)+ try:+ result = await tool.execute(command=command)+ finally:+ await manager.close_all()++ assert not getattr(result, "is_error", False), result+ assert "Exit code: 0" in result+ completed = [line.removeprefix(marker) for line in result.splitlines() if line.startswith(marker)]+ assert len(completed) == 1, result+ assert json.loads(completed[0]) == {+ "MY_CUSTOM_VAR": expected_allowed,+ "NANOBOT_SECRET_TOKEN": None,+ "NONEXISTENT_VAR_12345": None,+ }@pytest.mark.asyncio@@ -67,37 +106,6 @@ async def test_exec_path_prepend_takes_lookup_precedence(tmp_path):assert "fallback" not in result-@_UNIX_ONLY-async def test_exec_allowed_env_keys_passthrough(monkeypatch):- """Env vars listed in allowed_env_keys should be visible to commands."""- monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")- tool = ExecTool(allowed_env_keys=["MY_CUSTOM_VAR"])- result = await tool.execute(command="printenv MY_CUSTOM_VAR")- assert "hello-from-config" in result---@_UNIX_ONLY-async def test_exec_allowed_env_keys_does_not_leak_others(monkeypatch):- """Env vars NOT in allowed_env_keys should still be blocked."""- monkeypatch.setenv("MY_CUSTOM_VAR", "hello-from-config")- monkeypatch.setenv("MY_SECRET_VAR", "secret-value")- tool = ExecTool(allowed_env_keys=["MY_CUSTOM_VAR"])- result = await tool.execute(command="printenv MY_SECRET_VAR")- assert "secret-value" not in result---@_UNIX_ONLY-async def test_exec_allowed_env_keys_missing_var_ignored(monkeypatch):- """If an allowed key is not set in the parent process, it should be silently skipped."""- monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)- tool = ExecTool(allowed_env_keys=["NONEXISTENT_VAR_12345"])- result = await tool.execute(command="printenv NONEXISTENT_VAR_12345")- assert "Exit code: 1" in result--# --- path_append injection prevention ------------------------------------diff --git a/tests/tools/test_exec_session_tools.py b/tests/tools/test_exec_session_tools.pyindex b7f154a05..29069c708 100644--- a/tests/tools/test_exec_session_tools.py+++ b/tests/tools/test_exec_session_tools.py@@ -149,22 +149,37 @@ def test_exec_returns_completed_session_output_when_yield_time_ms_is_used(tmp_padef test_exec_session_yield_returns_when_process_finishes_early(tmp_path):- async def run() -> tuple[str, str, float]:+ async def run() -> str:manager = ExecSessionManager()- tool = ExecTool(working_dir=str(tmp_path), timeout=5, session_manager=manager)- stdin_tool = ExecSessionTool(manager=manager)- command = _python_command("import time; time.sleep(0.1); print('done')")- started = time.monotonic()- initial = await tool.execute(command=command, yield_time_ms=1200)- result, final = await _poll_if_running(initial, stdin_tool)- return result, final, time.monotonic() - started+ tool = ExecTool(working_dir=str(tmp_path), timeout=20, session_manager=manager)+ ready, release = tmp_path / "ready", tmp_path / "release"+ command = _python_command(+ "from pathlib import Path\nimport time\n"+ "Path('ready').write_text('ready')\n"+ "while not Path('release').exists(): time.sleep(0.01)\n"+ "print('done')"+ )+ pending = asyncio.create_task(tool.execute(command=command, yield_time_ms=15000))+ try:+ async with asyncio.timeout(10):+ while not ready.exists():+ if pending.done():+ pytest.fail(f"child exited before readiness: {await pending}")+ await asyncio.sleep(0.01)+ # Measure responsiveness only after the actual child is ready to exit.+ release.touch()+ return await asyncio.wait_for(pending, timeout=3)+ finally:+ release.touch()+ pending.cancel()+ await asyncio.gather(pending, return_exceptions=True)+ await manager.close_all()- result, final, elapsed = asyncio.run(run())+ result = asyncio.run(run())assert "done" in result- assert "Exit code: 0" in final- assert "session_id:" not in final- assert elapsed < 4.0+ assert "Exit code: 0" in result+ assert "session_id:" not in resultdef test_bounded_output_buffer_keeps_head_tail_and_exact_drop_count():diff --git a/tests/tools/test_file_edit_coding_enhancements.py b/tests/tools/test_file_edit_coding_enhancements.pyindex c9d69f905..5fc453459 100644--- a/tests/tools/test_file_edit_coding_enhancements.py+++ b/tests/tools/test_file_edit_coding_enhancements.py@@ -122,21 +122,6 @@ def test_edit_file_line_hint_can_cover_multiline_match(tmp_path):assert target.read_text() == "before\nstart\nchanged\nend\nafter\n"-def test_edit_file_can_edit_ipynb_as_json(tmp_path):- target = tmp_path / "analysis.ipynb"- target.write_text('{"cells": []}')- tool = EditFileTool(workspace=tmp_path)-- result = asyncio.run(tool.execute(- path=str(target),- old_text='"cells": []',- new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',- ))-- assert "Patch applied:" in result- assert '"source": "hi"' in target.read_text()--def test_edit_file_multiple_match_hint_mentions_occurrence(tmp_path):target = tmp_path / "duplicate.txt"target.write_text("same\nsame\n")diff --git a/tests/tools/test_mcp_probe.py b/tests/tools/test_mcp_probe.pyindex 3ec012596..d97bd48c1 100644--- a/tests/tools/test_mcp_probe.py+++ b/tests/tools/test_mcp_probe.py@@ -50,14 +50,17 @@ async def test_probe_returns_true_for_open_port(tmp_path):@pytest.mark.asyncio-async def test_probe_returns_false_for_closed_port():- """Port 19999 is almost certainly not listening."""- assert await _probe_http_url("http://127.0.0.1:19999/mcp") is False---async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch):- """When no port is present, probe the validated address on port 80."""+ "url, expected_port",+ [+ ("http://unreachable-host.test/mcp", 80),+ ("http://unreachable-host.test:19999/mcp", 19999),+ ],+)+async def test_probe_returns_false_when_validated_target_refuses_connection(+ monkeypatch: pytest.MonkeyPatch, url: str, expected_port: int,+):+ """Connection refusal on a validated address must fail on the selected port."""attempts: list[tuple[str, int]] = []monkeypatch.setattr(@@ -71,8 +74,8 @@ async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch)monkeypatch.setattr("nanobot.agent.tools.mcp.asyncio.open_connection", _open_connection)- assert await _probe_http_url("http://unreachable-host.test/mcp") is False- assert attempts == [("93.184.216.34", 80)]+ assert await _probe_http_url(url) is False+ assert attempts == [("93.184.216.34", expected_port)]@pytest.mark.asyncio@@ -80,8 +83,12 @@ async def test_probe_rejects_public_name_resolving_to_loopback():def _resolver(hostname, port, family=0, type_=0):return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 0))]- with patch("nanobot.security.network.socket.getaddrinfo", _resolver):+ with (+ patch("nanobot.security.network.socket.getaddrinfo", _resolver),+ patch("nanobot.agent.tools.mcp.asyncio.open_connection") as open_connection,+ ):assert await _probe_http_url("http://example.com:8765/mcp") is False+ open_connection.assert_not_called()@pytest.mark.asynciodiff --git a/tests/webui/fixtures/runtime-config-keys.json b/tests/webui/fixtures/runtime-config-keys.jsonnew file mode 100644index 000000000..750fb55fd--- /dev/null+++ b/tests/webui/fixtures/runtime-config-keys.json@@ -0,0 +1,41 @@+[+ "agents.defaults.timezone",+ "agents.defaults.timezone_mode",+ "agents.defaults.unified_session",+ "agents.defaults.max_tool_iterations",+ "agents.defaults.max_concurrent_subagents",+ "agents.defaults.max_tool_result_chars",+ "agents.defaults.provider_retry_mode",+ "agents.defaults.tool_hint_max_length",+ "agents.defaults.dream.enabled",+ "gateway.host",+ "gateway.port",+ "gateway.restart_mode",+ "tools.exec.enable",+ "tools.exec.timeout",+ "tools.exec.path_prepend",+ "tools.exec.path_append",+ "tools.exec.sandbox",+ "tools.exec.sandbox_ro_binds",+ "tools.exec.sandbox_rw_binds",+ "tools.exec.allowed_env_keys",+ "tools.exec.allow_patterns",+ "tools.exec.deny_patterns",+ "tools.file.enable",+ "tools.my.enable",+ "tools.my.allow_set",+ "tools.cli_apps.enable",+ "tools.cli_apps.install_timeout",+ "tools.cli_apps.run_timeout",+ "tools.cli_apps.catalog_ttl_seconds",+ "tools.restrict_to_workspace",+ "tools.ssrf_whitelist",+ "tools.max_session_messages_per_minute",+ "tools.webui_allow_remote_package_install",+ "tools.web.enable",+ "tools.web.proxy",+ "tools.web.user_agent",+ "tools.image_generation.save_dir",+ "api.host",+ "api.timeout"+]diff --git a/tests/webui/test_build.py b/tests/webui/test_build.pyindex 692552d22..ab2f5fdaa 100644--- a/tests/webui/test_build.py+++ b/tests/webui/test_build.py@@ -1,7 +1,6 @@from __future__ import annotationsimport os-import tomllibfrom pathlib import Pathfrom nanobot.webui.build import (@@ -88,13 +87,6 @@ def test_shared_notifications_make_existing_bundle_stale(tmp_path: Path) -> Noneassert 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"))-- assert "nanobot/channels/*/webui/**/*" in pyproject["tool"]["hatch"]["build"]["include"]--def test_inspect_webui_bundle_accepts_fresh_dist(tmp_path: Path) -> None:source = tmp_path / "webui"dist = tmp_path / "nanobot" / "web" / "dist"diff --git a/tests/webui/test_mcp_presets.py b/tests/webui/test_mcp_presets.pyindex 04607fbbe..f697fd7e5 100644--- a/tests/webui/test_mcp_presets.py+++ b/tests/webui/test_mcp_presets.py@@ -61,7 +61,7 @@ def test_json_presets_reject_invalid_configuration(preset_data: dict, invalid_pa@pytest.mark.parametrize("target", ["wheel", "sdist"])-def test_distributions_bundle_mcp_preset_resource(tmp_path: Path, target: str) -> None:+def test_distributions_bundle_webui_and_channel_resources(tmp_path: Path, target: str) -> None:repository = Path(__file__).resolve().parents[2]for name in ("pyproject.toml", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md"):shutil.copyfile(repository / name, tmp_path / name)@@ -70,8 +70,15 @@ def test_distributions_bundle_mcp_preset_resource(tmp_path: Path, target: str) -(tmp_path / "nanobot/__init__.py").write_text("", encoding="utf-8")(package / "__init__.py").write_text("", encoding="utf-8")resource = "nanobot/webui/mcp_presets.json"- expected = (repository / resource).read_bytes()- (tmp_path / resource).write_bytes(expected)+ resources = {+ resource: (repository / resource).read_bytes(),+ "nanobot/channels/example/webui/index.tsx": b"export const channel = 'example';\n",+ "nanobot/channels/example/webui/assets/icon.svg": b'<svg id="channel-icon"/>\n',+ }+ for name, content in resources.items():+ destination = tmp_path / name+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.write_bytes(content)result = subprocess.run([sys.executable, "-c", f"import hatchling.build; hatchling.build.build_{target}('dist')"],@@ -85,11 +92,14 @@ def test_distributions_bundle_mcp_preset_resource(tmp_path: Path, target: str) -if target == "wheel":with ZipFile(next((tmp_path / "dist").glob("*.whl"))) as wheel:- assert wheel.read(resource) == expected+ for name, content in resources.items():+ assert wheel.read(name) == contentelse:with tarfile.open(next((tmp_path / "dist").glob("*.tar.gz"))) as sdist:- member = next(name for name in sdist.getnames() if name.endswith(f"/{resource}"))- bundled = sdist.extractfile(member)- assert bundled is not None- with bundled:- assert bundled.read() == expected+ for name, content in resources.items():+ member = next((member for member in sdist.getnames() if member.endswith(f"/{name}")), None)+ assert member is not None, f"Missing bundled resource: {name}"+ bundled = sdist.extractfile(member)+ assert bundled is not None+ with bundled:+ assert bundled.read() == contentdiff --git a/tests/webui/test_session_list_index.py b/tests/webui/test_session_list_index.pyindex 0f54a18d9..97b4f38ff 100644--- a/tests/webui/test_session_list_index.py+++ b/tests/webui/test_session_list_index.py@@ -237,16 +237,26 @@ def test_webui_session_list_surfaces_pending_recovery_state(tmp_path: Path) -> Ndef test_webui_session_index_uses_unique_temp_file(tmp_path: Path) -> None:+ key = "websocket:unique-index-temp"+ transcript = tmp_path / "webui" / f"{SessionManager.safe_key(key)}.jsonl"+ transcript.write_text(+ '{"event":"user","chat_id":"unique-index-temp","text":"hello"}\n',+ encoding="utf-8",+ )manager = SessionManager(tmp_path)- session = manager.get_or_create("websocket:unique-index-temp")- session.add_message("user", "hello")- manager.save(session)stale_shared_tmp = manager.sessions_dir / ".webui_session_index.json.tmp"- stale_shared_tmp.write_text("stale", encoding="utf-8")+ stale_bytes = b"pre-existing shared temp\x00\xff"+ stale_shared_tmp.write_bytes(stale_bytes)- assert list_webui_sessions(manager)[0]["preview"] == "hello"+ row, = list_webui_sessions(manager)- assert stale_shared_tmp.read_text(encoding="utf-8") == "stale"+ assert row["key"] == key+ assert row["preview"] == "hello"+ cache = json.loads((manager.sessions_dir / ".webui_session_index.json").read_text(encoding="utf-8"))+ cached_row, = cache["sessions"]+ assert cached_row["key"] == key+ assert cached_row["preview"] == "hello"+ assert stale_shared_tmp.read_bytes() == stale_bytesassert not list(manager.sessions_dir.glob(".webui_session_index.json.*.tmp"))diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.pyindex e690412e6..9cf5353f7 100644--- a/tests/webui/test_settings_api.py+++ b/tests/webui/test_settings_api.py@@ -2725,15 +2725,6 @@ def test_create_model_configuration_accepts_azure_openai_aad_mode(assert saved.model_presets["azure-aad"].model == "my-deployment"-def test_azure_openai_spec_no_longer_requires_api_key() -> None:- """Contract guard: api_key is optional for azure_openai (AAD fallback)."""- from nanobot.webui.settings_api import _provider_requires_api_key-- spec = find_by_name("azure_openai")- assert spec is not None- assert _provider_requires_api_key(spec) is False--@pytest.mark.parametrize("protocol", ["chat_completions", "responses", "anthropic_messages"])def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypatch, protocol):config_path = tmp_path / "config.json"diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.pyindex d30d6d588..cfad6842d 100644--- a/tests/webui/test_settings_routes.py+++ b/tests/webui/test_settings_routes.py@@ -649,13 +649,35 @@ async def test_reverting_runtime_switch_clears_restart_but_preserves_other_changasync def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path):router = _router(config_path=tmp_path / "config.json")- original = router.settings.config.load().tools.web.fetch.use_jina_reader+ config = router.settings.config.load()+ original_reader = config.tools.web.fetch.use_jina_reader+ original_timeout = config.api.timeoutpath = "/api/settings/web-search/update"- first = await router.dispatch(None, _mutation_request(path, {"provider": "duckduckgo", "use_jina_reader": not original}), path)+ first = await router.dispatch(None, _mutation_request(path, {+ "provider": "duckduckgo", "use_jina_reader": not original_reader,+ }), path)+ assert first.status_code == 200assert json.loads(first.body)["restart_required_sections"] == ["browser"]- router._restart_sections.add("runtime")- restored = await router.dispatch(None, _mutation_request(path, {"provider": "duckduckgo", "use_jina_reader": original}), path)++ runtime_path = "/api/settings/runtime-config/update"+ changed = await router.dispatch(None, _mutation_request(runtime_path, {+ "values": {"api.timeout": original_timeout + 1},+ }), runtime_path)+ assert changed.status_code == 200+ assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"}++ restored = await router.dispatch(None, _mutation_request(path, {+ "provider": "duckduckgo", "use_jina_reader": original_reader,+ }), path)+ assert restored.status_code == 200assert json.loads(restored.body)["restart_required_sections"] == ["runtime"]+ refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")+ assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]+ reverted = await router.dispatch(None, _mutation_request(runtime_path, {+ "values": {"api.timeout": original_timeout},+ }), runtime_path)+ assert reverted.status_code == 200+ assert json.loads(reverted.body)["restart_required_sections"] == []@pytest.mark.parametrize("enabled", [False, True])diff --git a/tests/webui/test_settings_runtime.py b/tests/webui/test_settings_runtime.pyindex cdc163e4c..fe3a6c9af 100644--- a/tests/webui/test_settings_runtime.py+++ b/tests/webui/test_settings_runtime.py@@ -1,7 +1,6 @@from __future__ import annotationsimport json-import refrom pathlib import Pathimport pytest@@ -11,7 +10,6 @@ from nanobot.config.schema import Configfrom nanobot.webui.settings_api import update_runtime_config_settingsfrom nanobot.webui.settings_contracts import WebUISettingsErrorfrom nanobot.webui.settings_runtime import (- RUNTIME_CONFIG_PATHS,runtime_config_payload,update_runtime_config,)@@ -166,13 +164,11 @@ def test_api_changes_require_explicit_restart(tmp_path):assert payload["requires_restart"]-def test_every_exposed_runtime_setting_has_a_frontend_use():- fields = Path(__file__).parents[2] / "webui/src/components/settings/system/runtime-config-fields.ts"- paths = re.findall(r'group: "[^"]+", path: "([^"]+)"', fields.read_text(encoding="utf-8"))+def test_runtime_payload_matches_shared_catalogue_contract():+ fixture = Path(__file__).with_name("fixtures") / "runtime-config-keys.json"+ paths = json.loads(fixture.read_text(encoding="utf-8"))assert len(paths) == len(set(paths))- # The CLI enable flag controls visibility of its advanced fields, without an editor.- visibility_only = {"tools.cli_apps.enable"}- assert set(paths) | visibility_only == set(RUNTIME_CONFIG_PATHS)+ assert set(runtime_config_payload(Config())) == set(paths)def test_disabling_memory_consolidation_preserves_other_memory_settings():diff --git a/tui/src/app/layout.test.ts b/tui/src/app/layout.test.tsindex 237f97545..33fbb6935 100644--- a/tui/src/app/layout.test.ts+++ b/tui/src/app/layout.test.ts@@ -809,8 +809,6 @@ describe("NanobotTui layout and themes", () => {const ui = app as unknown as {composer: TextareaRenderablestatus: TextRenderable- shimmerFrame: number- renderActiveStatus(): void}expect(ui.composer.textColor.intent).toBe("default")expect(ui.composer.backgroundColor.intent).toBe("default")@@ -832,8 +830,7 @@ describe("NanobotTui layout and themes", () => {.slice(0, "Thinking".length).map((chunk) => chunk.attributes ?? 0)const firstFrame = terminalFrame()- ui.shimmerFrame += 1- ui.renderActiveStatus()+ await waitUntil(() => JSON.stringify(terminalFrame()) !== JSON.stringify(firstFrame), 2_000)const secondFrame = terminalFrame()expect(firstFrame).toContain(TextAttributes.BOLD)expect(secondFrame).not.toEqual(firstFrame)diff --git a/tui/src/app/transcript.test.ts b/tui/src/app/transcript.test.tsindex bc44b75d8..3ea442279 100644--- a/tui/src/app/transcript.test.ts+++ b/tui/src/app/transcript.test.ts@@ -189,11 +189,10 @@ describe("NanobotTui transcript", () => {setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")app.accept({ event: "attached", chat_id: "chat" })app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })- await Bun.sleep(130)- await setup.renderOnce()+ await setup.flush()let frame = setup.captureCharFrame()- expect(frame).toMatch(/Thinking\s+0s/u)+ expect(frame).toMatch(/Thinking\s+\d+s/u)expect(frame).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)expect(frame).not.toContain("hidden reasoning")const ui = app as unknown as {@@ -205,7 +204,12 @@ describe("NanobotTui transcript", () => {composerFrame: BoxRenderable}const status = ui.status- expect(status.plainText).toMatch(/^Thinking\s+0s/u)+ const statusColors = () => status.content.chunks+ .slice(0, "Thinking".length)+ .map((chunk) => chunk.fg?.toInts().join(","))+ const firstFrame = JSON.stringify(statusColors())+ await waitUntil(() => JSON.stringify(statusColors()) !== firstFrame, 2_000)+ expect(status.plainText).toMatch(/^Thinking\s+\d+s/u)expect(ui.composer.placeholder).toBe("Enter send now Tab send next")expect(ui.composerFrame.height).toBe(3)const shimmerColors = new Set(@@ -223,11 +227,11 @@ describe("NanobotTui transcript", () => {kind: "tool_hint",tool_events: [{ phase: "start", name: "exec", arguments: { cmd: "pwd" } }],})- await Bun.sleep(130)- await setup.renderOnce()+ await waitUntil(() => /^Working\s+\d+s/u.test(status.plainText), 2_000)+ await setup.flush()frame = setup.captureCharFrame()- expect(frame).toMatch(/Working\s+0s/u)+ expect(frame).toMatch(/Working\s+\d+s/u)expect(frame).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)expect(frame).toContain("› Running pwd")expect(occurrences(frame, "pwd")).toBe(1)@@ -235,6 +239,10 @@ describe("NanobotTui transcript", () => {app.accept({ event: "turn_end", chat_id: "chat" })await setup.flush()expect(ui.composer.placeholder).toBe("Ask nanobot anything")+ expect(status.plainText).toMatch(/^Ready/u)+ const stopped = status.content+ await Bun.sleep(200)+ expect(status.content).toBe(stopped)})test("updates retry state in place and ends failed turns explicitly", async () => {diff --git a/tui/src/client/client.test.ts b/tui/src/client/client.test.tsindex 2f5da1f6b..d5baa0219 100644--- a/tui/src/client/client.test.ts+++ b/tui/src/client/client.test.ts@@ -478,8 +478,21 @@ describe("gateway protocol", () => {client.close()})- test("represents lifecycle frames without browser state", () => {- const events: InboundEvent[] = [+ test("delivers lifecycle frames with media metadata through the gateway socket", () => {+ const original = globalThis.WebSocket+ let socket: FakeSocket | undefined+ Object.defineProperty(globalThis, "WebSocket", {+ configurable: true,+ value: class extends FakeSocket {+ constructor() {+ super()+ socket = this+ }+ },+ })+ const frames: InboundEvent[] = [+ { event: "ready", chat_id: "", client_id: "client" },+ { event: "attached", chat_id: "one" },{event: "user_message",chat_id: "one",@@ -493,12 +506,26 @@ describe("gateway protocol", () => {{ event: "stream_end", chat_id: "one", resuming: false },{ event: "turn_end", chat_id: "one", latency_ms: 12 },]- expect(events.map((event) => event.event)).toEqual([- "user_message",- "delta",- "stream_end",- "turn_end",- ])+ const delivered: InboundEvent[] = []+ const client = new NanobotClient({+ url: "ws://nanobot.test/ws",+ chatId: "one",+ onEvent: (event) => delivered.push(event),+ onStatus: () => undefined,+ })++ try {+ client.connect()+ if (!socket) throw new Error("socket was not created")+ socket.emit("open")+ for (const frame of frames) {+ socket.emit("message", { data: JSON.stringify(frame) })+ }+ expect(delivered).toEqual(frames)+ } finally {+ client.close()+ Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original })+ }})test("attaches and sends turns through the gateway envelope", () => {diff --git a/webui/.gitignore b/webui/.gitignoreindex cd8c35d5a..f4f833c7d 100644--- a/webui/.gitignore+++ b/webui/.gitignore@@ -6,3 +6,5 @@ coverage/.env.env.*!.env.example+test-results/+playwright-report/diff --git a/webui/README.md b/webui/README.mdindex 84abbbedf..01f0a956a 100644--- a/webui/README.md+++ b/webui/README.md@@ -114,10 +114,12 @@ The gateway picks up the new bundle on the next restart.cd webuibun run lintbun run test+bun x playwright install chromium+bun run test:browserbun run build```-`lint` runs ESLint; `test` runs Vitest, including channel-owned frontend tests; `build` runs TypeScript checking and produces the production bundle. Keep tests near the changed behavior and exercise settings save/reload in the browser. Browser-only preferences stay in the frontend; persistent configuration and security policy belong to the Python gateway. When changing that boundary, also run the relevant Python tests from [CONTRIBUTING.md](../CONTRIBUTING.md).+`lint` runs ESLint; `test` runs Vitest, including channel-owned frontend tests; `test:browser` uses Chromium with the real components and stylesheet to check tall-dialog reachability and completed-history motion without a gateway; `build` runs TypeScript checking and produces the production bundle. Keep tests near the changed behavior and exercise settings save/reload in the browser. Browser-only preferences stay in the frontend; persistent configuration and security policy belong to the Python gateway. When changing that boundary, also run the relevant Python tests from [CONTRIBUTING.md](../CONTRIBUTING.md).## Acknowledgementsdiff --git a/webui/browser/fixture.html b/webui/browser/fixture.htmlnew file mode 100644index 000000000..22d3c1829--- /dev/null+++ b/webui/browser/fixture.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Browser regression fixtures</title></head>+ <body><div id="root"></div><script type="module" src="/browser/fixture.tsx"></script></body>+</html>diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsxnew file mode 100644index 000000000..58af3ab41--- /dev/null+++ b/webui/browser/fixture.tsx@@ -0,0 +1,54 @@+import { useState } from "react";+import { createRoot } from "react-dom/client";+import { MessageBubble } from "@/components/MessageBubble";+import { ThreadMessages } from "@/components/thread/ThreadMessages";+import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog";+import { TooltipProvider } from "@/components/ui/tooltip";+import { initializeI18n } from "@/i18n";+import type { UIMessage } from "@/lib/types";+import "../src/globals.css";++const history: UIMessage[] = [+ { id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },+ { id: "answer", role: "assistant", content: "Earlier answer", createdAt: 1_700_000_001_000 },+];+const trace: UIMessage = {+ id: "trace", role: "tool", kind: "trace", content: "Earlier tool call", createdAt: 1_700_000_002_000,+};++function HistoryFixture() {+ const [open, setOpen] = useState(false);+ return <main>+ <button onClick={() => setOpen(!open)}>{open ? "Close history" : "Reopen history"}</button>+ <section aria-label="Persisted history">+ {open && <>+ <ThreadMessages messages={history} isStreaming={false} />+ <MessageBubble message={trace} />+ </>}+ </section>+ </main>;+}++function TallDialogFixture({ placement }: { placement: "center" | "bottom" }) {+ return <main aria-label="Background content" style={{ height: 240, overflowY: "auto" }}>+ <div style={{ minHeight: 1800 }}><Dialog>+ <DialogTrigger asChild><button>Open tall dialog</button></DialogTrigger>+ <DialogContent placement={placement}>+ <DialogTitle>Tall dialog</DialogTitle>+ <DialogDescription>All controls must remain reachable in a short viewport.</DialogDescription>+ {Array.from({ length: 30 }, (_, index) => <label key={index}>+ Field {index + 1}<input aria-label={`Field ${index + 1}`} style={{ display: "block", height: 40 }} />+ </label>)}+ <DialogClose asChild><button>Save tall dialog</button></DialogClose>+ </DialogContent>+ </Dialog></div>+ </main>;+}++const parameters = new URLSearchParams(location.search);+await initializeI18n();+createRoot(document.getElementById("root")!).render(<TooltipProvider>+ {parameters.get("case") === "history"+ ? <HistoryFixture />+ : <TallDialogFixture placement={parameters.get("placement") === "bottom" ? "bottom" : "center"} />}+</TooltipProvider>);diff --git a/webui/browser/layout.spec.ts b/webui/browser/layout.spec.tsnew file mode 100644index 000000000..d9307449f--- /dev/null+++ b/webui/browser/layout.spec.ts@@ -0,0 +1,77 @@+import { expect, test } from "@playwright/test";++for (const placement of ["center", "bottom"]) {+ test(`oversized ${placement} dialog keeps both ends keyboard-reachable`, async ({ page }) => {+ await page.setViewportSize({ width: 640, height: 320 });+ await page.goto(`/browser/fixture.html?placement=${placement}`);+ const background = page.getByRole("main", { name: "Background content", includeHidden: true });+ const trigger = page.getByRole("button", { name: "Open tall dialog" });+ await trigger.click();+ const dialog = page.getByRole("dialog", { name: "Tall dialog" });+ const close = dialog.getByRole("button", { name: "Close", exact: true });+ const lastAction = dialog.getByRole("button", { name: "Save tall dialog" });+ await expect(dialog.getByRole("heading", { name: "Tall dialog" })).toBeInViewport({ ratio: 1 });+ await expect(close).toBeInViewport({ ratio: 1 });+ expect(await dialog.evaluate((element) => element.scrollHeight)).toBeGreaterThan(320);+ await expect(page.locator("body")).toHaveAttribute("data-scroll-locked", "1");++ await close.focus();+ await page.keyboard.press("Shift+Tab");+ await expect(lastAction).toBeFocused();+ await expect(lastAction).toBeInViewport({ ratio: 1 });+ expect(await background.evaluate((element) => element.scrollTop)).toBe(0);+ await lastAction.press("Enter");+ await expect(dialog).not.toBeVisible();+ await expect(trigger).toBeFocused();+ await expect(page.locator("body")).not.toHaveAttribute("data-scroll-locked");+ await background.hover({ position: { x: 300, y: 180 } });+ await page.mouse.wheel(0, 400);+ await expect.poll(() => background.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);+ });+}++test("reopened completed history is readable without subtree entrance motion", async ({ page }) => {+ await page.goto("/browser/fixture.html?case=history");+ const history = page.getByRole("region", { name: "Persisted history" });+ for (let reopen = 0; reopen < 2; reopen++) {+ const observation = await history.evaluateHandle((element) => {+ const names = new Set<string>();+ let frames = 0;+ let frame = 0;+ const onAnimation = (event: Event) => names.add((event as AnimationEvent).animationName);+ element.addEventListener("animationstart", onAnimation);+ const sample = () => {+ for (const animation of element.getAnimations({ subtree: true })) {+ names.add(animation.constructor.name);+ }+ frames++;+ frame = requestAnimationFrame(sample);+ };+ frame = requestAnimationFrame(sample);+ return {+ get frames() { return frames; },+ stop() {+ cancelAnimationFrame(frame);+ element.removeEventListener("animationstart", onAnimation);+ return [...names];+ },+ };+ });+ try {+ await page.getByRole("button", { name: "Reopen history" }).click();+ await expect(history.getByText("Earlier question", { exact: true })).toBeVisible();+ await expect(history.getByText("Earlier answer", { exact: true })).toBeVisible();+ await expect(history.getByRole("button", { name: "Using a tool", exact: true })).toBeVisible();+ await expect.poll(() => observation.evaluate((record) => record.frames)).toBeGreaterThan(12);+ expect(await observation.evaluate((record) => record.stop())).toEqual([]);+ } finally {+ await observation.evaluate((record) => record.stop());+ await observation.dispose();+ }+ const disclosure = history.getByRole("button", { name: "Using a tool", exact: true });+ await disclosure.click();+ await expect(history.getByText("Earlier tool call", { exact: true })).toBeVisible();+ await page.getByRole("button", { name: "Close history" }).click();+ await expect(history.getByText("Earlier question", { exact: true })).not.toBeVisible();+ }+});diff --git a/webui/bun.lock b/webui/bun.lockindex 7f4af13f1..a3cd87572 100644--- a/webui/bun.lock+++ b/webui/bun.lock@@ -37,6 +37,7 @@},"devDependencies": {"@eslint/js": "^10.0.1",+ "@playwright/test": "1.64.1","@tailwindcss/typography": "^0.5.19","@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0",@@ -231,6 +232,8 @@"@pkgjs/parseargs": ["@pkgjs/[email protected]", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],+ "@playwright/test": ["@playwright/[email protected]", "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", { "dependencies": { "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg=="],+"@radix-ui/number": ["@radix-ui/[email protected]", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],"@radix-ui/primitive": ["@radix-ui/[email protected]", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],@@ -1109,6 +1112,10 @@"pirates": ["[email protected]", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="],+ "playwright": ["[email protected]", "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", { "dependencies": { "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA=="],++ "playwright-core": ["[email protected]", "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],+"pngjs": ["[email protected]", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],"points-on-curve": ["[email protected]", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="],diff --git a/webui/eslint.config.js b/webui/eslint.config.jsindex 31221d5f2..3119fa98b 100644--- a/webui/eslint.config.js+++ b/webui/eslint.config.js@@ -21,6 +21,7 @@ export default tseslint.config({files: ["webui/src/**/*.{ts,tsx}",+ "webui/browser/**/*.{ts,tsx}","nanobot/channels/*/webui/**/*.{ts,tsx}","nanobot/channels/*/tests/webui/**/*.{ts,tsx}",],diff --git a/webui/package-lock.json b/webui/package-lock.jsonindex 38099fab3..77e173adc 100644--- a/webui/package-lock.json+++ b/webui/package-lock.json@@ -40,6 +40,7 @@},"devDependencies": {"@eslint/js": "^10.0.1",+ "@playwright/test": "1.64.1","@tailwindcss/typography": "^0.5.19","@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0",@@ -1227,6 +1228,22 @@"node": ">=14"}},+ "node_modules/@playwright/test": {+ "version": "1.64.1",+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz",+ "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright": "1.64.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/@radix-ui/number": {"version": "1.1.1","resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",@@ -7284,6 +7301,35 @@"node": ">= 6"}},+ "node_modules/playwright": {+ "version": "1.64.1",+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz",+ "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "playwright-core": "1.64.1"+ },+ "bin": {+ "playwright": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/playwright-core": {+ "version": "1.64.1",+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz",+ "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "playwright-core": "cli.js"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/pngjs": {"version": "5.0.0","resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",diff --git a/webui/package.json b/webui/package.jsonindex 09ddbe585..94c3641f3 100644--- a/webui/package.json+++ b/webui/package.json@@ -11,9 +11,10 @@"test": "vitest run","test:coverage": "vitest run --coverage","test:watch": "vitest",+ "test:browser": "tsc -p tsconfig.browser.json && playwright test","check:imports": "bun ../scripts/check_client_import_boundaries.mjs --project webui","test:imports": "bun test ../scripts/check_client_import_boundaries.test.mjs",- "lint": "cd .. && eslint --config webui/eslint.config.js webui/src \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" \"scripts/check_client_import_boundaries*.mjs\" --max-warnings 0"+ "lint": "cd .. && eslint --config webui/eslint.config.js webui/src webui/browser \"nanobot/channels/*/webui/**/*.{ts,tsx}\" \"nanobot/channels/*/tests/webui/**/*.{ts,tsx}\" \"scripts/check_client_import_boundaries*.mjs\" --max-warnings 0"},"dependencies": {"@radix-ui/react-alert-dialog": "^1.1.4",@@ -48,6 +49,7 @@},"devDependencies": {"@eslint/js": "^10.0.1",+ "@playwright/test": "1.64.1","@tailwindcss/typography": "^0.5.19","@testing-library/jest-dom": "^6.6.3","@testing-library/react": "^16.1.0",diff --git a/webui/playwright.config.ts b/webui/playwright.config.tsnew file mode 100644index 000000000..7e2a27f9c--- /dev/null+++ b/webui/playwright.config.ts@@ -0,0 +1,27 @@+import { defineConfig, devices } from "@playwright/test";++const port = Number(process.env.NANOBOT_BROWSER_TEST_PORT ?? 4178);++export default defineConfig({+ testDir: "./browser",+ fullyParallel: false,+ workers: 1,+ retries: 0,+ timeout: 30_000,+ reporter: "list",+ outputDir: "test-results/browser",+ use: {+ ...devices["Desktop Chrome"],+ baseURL: `http://127.0.0.1:${port}`,+ reducedMotion: "no-preference",+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ screenshot: "only-on-failure",+ },+ webServer: {+ command: `node node_modules/vite/bin/vite.js --host 127.0.0.1 --port ${port} --strictPort`,+ url: `http://127.0.0.1:${port}/browser/fixture.html`,+ reuseExistingServer: false,+ },+});diff --git a/webui/src/tests/channel-logo.test.tsx b/webui/src/tests/channel-logo.test.tsxindex eddca0efb..d7f198b79 100644--- a/webui/src/tests/channel-logo.test.tsx+++ b/webui/src/tests/channel-logo.test.tsx@@ -55,7 +55,9 @@ describe("channel logos", () => {expectFootprint(icon);expect(fallback).toHaveClass("opacity-0");expect(image).toHaveClass("opacity-100");- expect(image).not.toHaveClass("invert", "grayscale", "object-cover");+ for (const className of ["invert", "grayscale", "object-cover"]) {+ expect(image).not.toHaveClass(className);+ }expect(icon).toHaveClass(presentation.logoLayout === "tile" ? "bg-transparent" : "bg-white");expect(image).toHaveClass(...(presentation.logoLayout === "tile" ? ["h-8", "w-8"] : ["h-6", "w-6"]));});diff --git a/webui/src/tests/channel-ui-registry.test.ts b/webui/src/tests/channel-ui-registry.test.tsindex fc83dfc58..573be47e4 100644--- a/webui/src/tests/channel-ui-registry.test.ts+++ b/webui/src/tests/channel-ui-registry.test.ts@@ -1,7 +1,9 @@-import { readFileSync } from "node:fs";import { resolve } from "node:path";-import { describe, expect, it } from "vitest";+import postcss from "postcss";+import tailwindcss from "tailwindcss";+import loadConfig from "tailwindcss/loadConfig";+import { describe, expect, it, vi } from "vitest";import {channelUiContribution,@@ -34,9 +36,22 @@ describe("channel UI contributions", () => {expect(channelUiOwner("wechat")).toBe("weixin");});- it("includes channel-owned UI in Tailwind's production scan", () => {- const source = readFileSync(resolve(process.cwd(), "tailwind.config.js"), "utf8");+ it("includes channel-owned UI in Tailwind's production scan", async () => {+ vi.stubEnv("NODE_ENV", "production");+ try {+ const config = loadConfig(resolve(process.cwd(), "tailwind.config.js"));+ const result = await postcss([tailwindcss(config)]).process("@tailwind utilities;", { from: undefined });- expect(source).toContain("../nanobot/channels/*/webui/**/*.{ts,tsx}");+ // Linear's connecting indicator uses a channel-only arbitrary color.+ let backgroundColor: string | undefined;+ result.root.walkRules(".bg-\\[\\#5E6AD2\\]", (rule) => {+ rule.walkDecls("background-color", (declaration) => {+ backgroundColor = declaration.value;+ });+ });+ expect(backgroundColor?.trim()).toBeTruthy();+ } finally {+ vi.unstubAllEnvs();+ }});});diff --git a/webui/src/tests/form-controls.test.tsx b/webui/src/tests/form-controls.test.tsxindex 4d482d116..cc32dd65a 100644--- a/webui/src/tests/form-controls.test.tsx+++ b/webui/src/tests/form-controls.test.tsx@@ -17,10 +17,12 @@ describe("form control focus styles", () => {"focus-visible:ring-inset","focus-visible:ring-ring/50",);- expect(element).not.toHaveClass(+ for (const className of ["ring-offset-background","focus-visible:ring-ring","focus-visible:ring-offset-2",- );+ ]) {+ expect(element).not.toHaveClass(className);+ }});});diff --git a/webui/src/tests/i18n.test.tsx b/webui/src/tests/i18n.test.tsxindex 44b0904e5..e67c072ea 100644--- a/webui/src/tests/i18n.test.tsx+++ b/webui/src/tests/i18n.test.tsx@@ -1,6 +1,6 @@import { readFileSync } from "node:fs";import { resolve } from "node:path";-import { runInNewContext } from "node:vm";+import { Window } from "happy-dom";import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";@@ -339,43 +339,24 @@ const ACCIDENTALLY_SPANISH_SETTINGS_KEYS = ["settings.oauth.signInHelp",];const INDEX_HTML = readFileSync(resolve(process.cwd(), "index.html"), "utf8");-const PREBOOT_SCRIPT = INDEX_HTML.match(- /<script>\s*(\(function \(\) \{\s*var localeKey = "nanobot\.locale";[\s\S]*?\}\)\(\);)\s*<\/script>/,-)?.[1];-const BOOT_COPY_MARKUP = '<span data-boot-copy>Loading nanobot…</span>';--function runPrebootLocale(storedLocale: string) {- if (!PREBOOT_SCRIPT) throw new Error("Could not find the preboot locale script in index.html");-- const documentElement = { lang: "" };- const meta = {- content: "",- setAttribute(name: string, value: string) {- if (name === "content") this.content = value;- },- };- const boot = { textContent: "" };-- runInNewContext(PREBOOT_SCRIPT, {- localStorage: {- getItem: (key: string) => key === LOCALE_STORAGE_KEY ? storedLocale : null,- },- navigator: { languages: [], language: "en" },- document: {- documentElement,- querySelector: (selector: string) => {- if (selector === '[data-i18n-meta="description"]') return meta;- if (selector === "[data-boot-copy]") return boot;- return null;- },- },+async function runPrebootLocale(storedLocale: string) {+ const preboot = new Window({+ url: "http://preboot.test",+ settings: { disableJavaScriptFileLoading: true, disableCSSFileLoading: true },});-- return {- lang: documentElement.lang,- boot: boot.textContent,- description: meta.content,- };+ try {+ preboot.localStorage.setItem(LOCALE_STORAGE_KEY, storedLocale);+ // Parse the shipped document and execute inline scripts in parser order.+ // External/module loading stays disabled: React must not repair the splash.+ preboot.document.write(INDEX_HTML);+ return {+ lang: preboot.document.documentElement.lang,+ boot: preboot.document.querySelector('[role="status"]')?.textContent.trim(),+ description: preboot.document.querySelector('meta[name="description"]')?.getAttribute("content"),+ };+ } finally {+ await preboot.happyDOM.close();+ }}function isRecord(value: unknown): value is Record<string, unknown> {@@ -406,13 +387,6 @@ function interpolationKeys(value: unknown): string[] {}describe("webui i18n", () => {- it("runs preboot localization after the splash copy exists", () => {- expect(INDEX_HTML.indexOf(BOOT_COPY_MARKUP)).toBeGreaterThan(-1);- expect(INDEX_HTML.indexOf(PREBOOT_SCRIPT ?? "")).toBeGreaterThan(- INDEX_HTML.indexOf(BOOT_COPY_MARKUP),- );- });-it.each(supportedLocales)("localizes compaction states in $code", async ({ code }) => {await setAppLanguage(code);const copy = resources[code].common.thread.compaction;@@ -437,9 +411,9 @@ describe("webui i18n", () => {}});- it("keeps preboot copy aligned with every registered locale", () => {+ it("localizes the parsed splash in document order for every registered locale", async () => {for (const { code } of supportedLocales) {- const result = runPrebootLocale(code);+ const result = await runPrebootLocale(code);const expected = resources[code].common.app;expect({ code, ...result }).toEqual({@@ -451,11 +425,11 @@ describe("webui i18n", () => {}});- it("normalizes Portuguese locales before the app bundle loads", () => {+ it("normalizes Portuguese locales before the app bundle loads", async () => {const expected = resources["pt-BR"].common.app;for (const locale of ["pt", "pt-PT"]) {- expect(runPrebootLocale(locale)).toEqual({+ expect(await runPrebootLocale(locale)).toEqual({lang: "pt-BR",boot: expected.loading.boot,description: expected.meta.description,diff --git a/webui/src/tests/image-gallery.test.tsx b/webui/src/tests/image-gallery.test.tsxindex 90f02e3b5..151f6058b 100644--- a/webui/src/tests/image-gallery.test.tsx+++ b/webui/src/tests/image-gallery.test.tsx@@ -97,7 +97,9 @@ describe("file quick look", () => {const quickLook = screen.getByTestId("file-image-quick-look");expect(quickLook.textContent).toBe("");expect(quickLook).toHaveClass("w-max");- expect(quickLook).not.toHaveClass("h-36", "w-full");+ for (const className of ["h-36", "w-full"]) {+ expect(quickLook).not.toHaveClass(className);+ }expect(quickLook.querySelector("img")).toHaveClass("rounded-mark", "object-contain");expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");diff --git a/webui/src/tests/linear-avatar.test.tsx b/webui/src/tests/linear-avatar.test.tsxindex fbb986289..7afea2cb8 100644--- a/webui/src/tests/linear-avatar.test.tsx+++ b/webui/src/tests/linear-avatar.test.tsx@@ -12,7 +12,9 @@ describe("Linear workspace logo", () => {expect(image).toHaveAttribute("height", "28");expect(image).toHaveAttribute("referrerpolicy", "no-referrer");expect(image.parentElement).toHaveClass("h-7", "w-7");- expect(image.parentElement).not.toHaveClass("overflow-hidden", "bg-muted");+ for (const className of ["overflow-hidden", "bg-muted"]) {+ expect(image.parentElement).not.toHaveClass(className);+ }expect(image).toHaveClass("object-contain");expect(view.container.querySelector("svg")).toBeNull();fireEvent.error(image);diff --git a/webui/src/tests/main-pwa-registration-unavailable.test.tsx b/webui/src/tests/main-pwa-registration-unavailable.test.tsxindex d49c90999..8d3d5490d 100644--- a/webui/src/tests/main-pwa-registration-unavailable.test.tsx+++ b/webui/src/tests/main-pwa-registration-unavailable.test.tsx@@ -1,3 +1,4 @@+import { waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const render = vi.fn();@@ -12,28 +13,28 @@ vi.mock("@/App", () => ({}));describe("service worker registration when unsupported", () => {- const register = vi.fn(() => Promise.resolve());-beforeEach(() => {vi.resetModules();createRoot.mockClear();render.mockClear();- register.mockClear();document.body.innerHTML = '<div id="root"></div>';- // happy-dom's Navigator has no serviceWorker member, so this file runs- // without defining one — the entry's `"serviceWorker" in navigator` guard- // must keep registration from being attempted.+ Reflect.deleteProperty(navigator, "serviceWorker");});afterEach(() => {document.body.innerHTML = "";- delete (navigator as Navigator & { serviceWorker?: unknown }).serviceWorker;+ Reflect.deleteProperty(navigator, "serviceWorker");});- it("does not attempt registration when the service worker API is missing", async () => {+ it("renders the app when the service worker API is missing", async () => {+ expect("serviceWorker" in navigator).toBe(false);+await import("../main");window.dispatchEvent(new Event("load"));- expect(register).not.toHaveBeenCalled();+ await waitFor(() => {+ expect(createRoot).toHaveBeenCalledWith(document.getElementById("root"));+ expect(render).toHaveBeenCalledTimes(1);+ });});});diff --git a/webui/src/tests/markdown-text.test.tsx b/webui/src/tests/markdown-text.test.tsxindex e18e81e51..ded1295ac 100644--- a/webui/src/tests/markdown-text.test.tsx+++ b/webui/src/tests/markdown-text.test.tsx@@ -142,30 +142,4 @@ describe("MarkdownText", () => {"true",);});-- it("defers syntax highlighting until the final render", async () => {- rendererSpy.mockClear();- const largeCode = `\`\`\`ts\n${"const value = 1;\n".repeat(1_100)}\`\`\``;-- const { rerender } = render(- <MarkdownText streaming>{largeCode}</MarkdownText>,- );-- await act(async () => {- await Promise.resolve();- await Promise.resolve();- });-- expect(screen.getByTestId("markdown-renderer")).toHaveAttribute(- "data-highlight-code",- "false",- );-- rerender(<MarkdownText>{largeCode}</MarkdownText>);-- expect(screen.getByTestId("markdown-renderer")).toHaveAttribute(- "data-highlight-code",- "true",- );- });});diff --git a/webui/src/tests/message-bubble.test.tsx b/webui/src/tests/message-bubble.test.tsxindex d77b079a7..3d46beecf 100644--- a/webui/src/tests/message-bubble.test.tsx+++ b/webui/src/tests/message-bubble.test.tsx@@ -274,31 +274,37 @@ describe("MessageBubble", () => {expect(bubble).toHaveClass("bg-secondary/70");});- it("does not replay an entrance animation when persisted messages mount", () => {+ it("renders completed message branches with static wrapper classes", async () => {const messages: UIMessage[] = [{id: "u-persisted",role: "user",content: "Earlier question",- createdAt: Date.now(),+ createdAt: 1_700_000_000_000,},{id: "a-persisted",role: "assistant",content: "Earlier answer",- createdAt: Date.now(),+ createdAt: 1_700_000_001_000,},{id: "t-persisted",role: "tool",kind: "trace",content: "Earlier tool call",- createdAt: Date.now(),+ createdAt: 1_700_000_002_000,},];for (const message of messages) {const { container, unmount } = render(<MessageBubble message={message} />);+ if (message.kind === "trace") {+ const disclosure = screen.getByRole("button", { expanded: false });+ fireEvent.click(disclosure);+ expect(disclosure).toHaveAttribute("aria-expanded", "true");+ }+ expect(await screen.findByText(message.content)).toBeVisible();for (const className of ["animate-in", "fade-in-0", "slide-in-from-bottom-1"]) {expect(container.firstElementChild).not.toHaveClass(className);}diff --git a/webui/src/tests/provider-icon.test.tsx b/webui/src/tests/provider-icon.test.tsxindex 1d8e07499..cbdb3515c 100644--- a/webui/src/tests/provider-icon.test.tsx+++ b/webui/src/tests/provider-icon.test.tsx@@ -40,7 +40,9 @@ describe("settings provider icons", () => {expect(icon).not.toHaveAttribute("style");expect(fallback).toHaveClass("opacity-0");expect(image).toHaveClass("opacity-100");- expect(image).not.toHaveClass("invert", "grayscale");+ for (const className of ["invert", "grayscale"]) {+ expect(image).not.toHaveClass(className);+ }},);@@ -60,7 +62,9 @@ describe("settings provider icons", () => {fireEvent.load(image);expect(image).toHaveClass("opacity-100");expect(icon).toHaveClass("bg-transparent");- expect(icon).not.toHaveClass("bg-white", "bg-muted");+ for (const className of ["bg-white", "bg-muted"]) {+ expect(icon).not.toHaveClass(className);+ }fireEvent.error(image);expect(image).toHaveAttribute("src", providerBrand(provider)!.logoUrls[1]);diff --git a/webui/src/tests/settings-runtime-config.test.tsx b/webui/src/tests/settings-runtime-config.test.tsxindex d1b3af04e..c9739bf03 100644--- a/webui/src/tests/settings-runtime-config.test.tsx+++ b/webui/src/tests/settings-runtime-config.test.tsx@@ -2,6 +2,8 @@ import { fireEvent, render, screen, waitFor, within } from "@testing-library/reaimport userEvent from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";+import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS } from "@/components/settings/system/runtime-config-fields";+import runtimeConfigKeys from "../../../tests/webui/fixtures/runtime-config-keys.json";import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/ModelsSettings";import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";@@ -29,6 +31,15 @@ function runtimeSettings() {describe("Runtime configuration settings", () => {installSettingsViewTestHooks();+ it("covers the shared runtime wire-key catalogue without duplicate editors", () => {+ const paths = RUNTIME_CONFIG_FIELDS.map((field) => field.path);+ expect(new Set(paths).size).toBe(paths.length);+ // This key gates the CLI group rather than having a separate editor.+ const visibilityOnly = "tools.cli_apps.enable";+ expect(RUNTIME_CONFIG_GROUPS.find((group) => group.id === "cli")?.enabledBy).toBe(visibilityOnly);+ expect([...paths, visibilityOnly].sort()).toEqual([...runtimeConfigKeys].sort());+ });+it("keeps local service controls available when tool families are disabled", () => {const payload = runtimeSettings();renderSettingsView({ initialSection: "advanced", initialSettings: {diff --git a/webui/src/tests/settings-system.test.tsx b/webui/src/tests/settings-system.test.tsxindex ca2aed5c8..210b2b1f1 100644--- a/webui/src/tests/settings-system.test.tsx+++ b/webui/src/tests/settings-system.test.tsx@@ -203,7 +203,9 @@ describe("Settings system domains", () => {expect(title.parentElement).toHaveClass("settings-section-heading");expect(title.nextElementSibling).toHaveTextContent("1");expect(title.nextElementSibling).toHaveClass("tabular-nums");- expect(title.nextElementSibling).not.toHaveClass("rounded-full", "bg-muted");+ for (const className of ["rounded-full", "bg-muted"]) {+ expect(title.nextElementSibling).not.toHaveClass(className);+ }fireEvent.click(screen.getByRole("button", { name: "MCP", exact: true }));const mcpTitle = screen.getByRole("heading", { name: "MCP tools" });@@ -267,7 +269,9 @@ describe("Settings system domains", () => {for (const name of ["Custom", "Built-in", "Other"]) {const title = screen.getByRole("heading", { name, exact: true });expect(title).toHaveClass("text-[13px]", "font-medium", "leading-5");- expect(title).not.toHaveClass("uppercase", "tracking-[0.08em]");+ for (const className of ["uppercase", "tracking-[0.08em]"]) {+ expect(title).not.toHaveClass(className);+ }expect(title.nextElementSibling).toHaveTextContent("1");expect(title.nextElementSibling).toHaveClass("leading-5");}diff --git a/webui/src/tests/sw.test.ts b/webui/src/tests/sw.test.tsindex 2759c4715..53e4645a6 100644--- a/webui/src/tests/sw.test.ts+++ b/webui/src/tests/sw.test.ts@@ -139,10 +139,10 @@ function indexHtml(assetPaths: string[]): Response {return new Response(`<!doctype html><html><head>${refs}</head></html>`);}-function fetchEvent(url: string) {+function fetchEvent(url: string, init?: RequestInit) {const respondWith = vi.fn();const event = {- request: new Request(url, { method: "GET" }),+ request: new Request(url, init),respondWith,};return { event, respondWith };@@ -223,8 +223,8 @@ describe("service worker", () => {];for (const path of paths) {- const { respondWith } = fetchEvent(`${ORIGIN}${path}`);- await sw.fire("fetch", { request: new Request(`${ORIGIN}${path}`) });+ const { event, respondWith } = fetchEvent(`${ORIGIN}${path}`);+ await sw.fire("fetch", event);expect(respondWith, path).not.toHaveBeenCalled();}expect(sw.fetchMock).not.toHaveBeenCalled();@@ -233,16 +233,14 @@ describe("service worker", () => {it("does not intercept non-GET or unrelated cross-origin requests", async () => {const sw = loadSw();- const { respondWith: post } = fetchEvent(`${ORIGIN}/api/v1/models`);- await sw.fire("fetch", {- request: new Request(`${ORIGIN}/api/v1/models`, { method: "POST" }),- });+ const { event: postEvent, respondWith: post } = fetchEvent(+ `${ORIGIN}/assets/app.js`, { method: "POST" },+ );+ await sw.fire("fetch", postEvent);expect(post).not.toHaveBeenCalled();- const { respondWith: cross } = fetchEvent("https://other.test/assets/app.js");- await sw.fire("fetch", {- request: new Request("https://other.test/assets/app.js"),- });+ const { event: crossEvent, respondWith: cross } = fetchEvent("https://other.test/assets/app.js");+ await sw.fire("fetch", crossEvent);expect(cross).not.toHaveBeenCalled();expect(sw.fetchMock).not.toHaveBeenCalled();});diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsxindex 18e43f903..f5b2f3d9b 100644--- a/webui/src/tests/thread-composer.test.tsx+++ b/webui/src/tests/thread-composer.test.tsx@@ -816,7 +816,9 @@ describe("ThreadComposer", () => {expect(modelPill).not.toHaveClass("font-semibold");const providerLogo = screen.getByTestId("composer-model-logo-openai");expect(providerLogo).toBeInTheDocument();- expect(providerLogo).not.toHaveClass("border", "bg-background");+ for (const className of ["border", "bg-background"]) {+ expect(providerLogo).not.toHaveClass(className);+ }const input = screen.getByPlaceholderText("Type your message...");expect(input.className).toContain("min-h-[50px]");expect(input.className).toContain("text-[16px]");diff --git a/webui/src/tests/thread-messages.test.tsx b/webui/src/tests/thread-messages.test.tsxindex 87deb5983..4845cd5a6 100644--- a/webui/src/tests/thread-messages.test.tsx+++ b/webui/src/tests/thread-messages.test.tsx@@ -731,7 +731,9 @@ describe("ThreadMessages", () => {const rows = Array.from(container.firstElementChild?.children ?? []);expect(rows).toHaveLength(2);- expect(rows[0]).not.toHaveClass("mt-2", "mt-4", "mt-5");+ for (const className of ["mt-2", "mt-4", "mt-5"]) {+ expect(rows[0]).not.toHaveClass(className);+ }expect(rows[1]).not.toHaveClass("mt-4");const answerRow = screen.getByText("final answer").closest<HTMLElement>("[data-thread-display-unit]")!;@@ -772,7 +774,9 @@ describe("ThreadMessages", () => {expect(disclosure.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();expect(menu).toHaveClass("w-max", "max-w-64", "bg-popover", "rounded-floating", "overflow-y-auto");- expect(menu).not.toHaveClass("min-w-[8.5rem]", "bg-popover/95", "rounded-xl");+ for (const className of ["min-w-[8.5rem]", "bg-popover/95", "rounded-xl"]) {+ expect(menu).not.toHaveClass(className);+ }const menuButtons = Array.from(menu.querySelectorAll("button"));expect(menuButtons.length).toBeGreaterThan(1);for (const button of menuButtons) {diff --git a/webui/src/tests/ui-shape-system.test.tsx b/webui/src/tests/ui-shape-system.test.tsxindex a16c285d8..36e4ad8e7 100644--- a/webui/src/tests/ui-shape-system.test.tsx+++ b/webui/src/tests/ui-shape-system.test.tsx@@ -24,7 +24,7 @@ import { Input } from "@/components/ui/input";import { Textarea } from "@/components/ui/textarea";describe("UI shape system", () => {- it.each(["center", "bottom"] as const)("keeps an oversized %s dialog scrollable from its start", (placement) => {+ it.each(["center", "bottom"] as const)("declares a scroll owner inside the %s modal boundary", (placement) => {render(<Dialog open><DialogContent placement={placement}><DialogTitle>Long dialog</DialogTitle><DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>@@ -32,7 +32,7 @@ describe("UI shape system", () => {const dialog = screen.getByRole("dialog");expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");// The scroll owner stays inside Radix's overlay/scroll-lock boundary.- expect(dialog.parentElement?.parentElement).toHaveClass("backdrop-blur-[8px]", "duration-200");+ expect(dialog.parentElement?.parentElement).toHaveAttribute("data-state", "open");expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");});diff --git a/webui/src/tests/vite-config.test.ts b/webui/src/tests/vite-config.test.tsindex 10c46fecf..72ccfcc4c 100644--- a/webui/src/tests/vite-config.test.ts+++ b/webui/src/tests/vite-config.test.ts@@ -1,14 +1,14 @@-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { gunzipSync } from "node:zlib";import { describe, expect, it } from "vitest";+import { rollup } from "rollup";import webuiConfig, {entryLazyFeatureImports,gzipWebuiAssets,webuiManualChunk,- writeCompressedWebuiAssets,} from "../../vite.config";describe("development overlay dependencies", () => {@@ -20,24 +20,37 @@ describe("development overlay dependencies", () => {});describe("gzipWebuiAssets", () => {- it("compresses finalized files after Rollup writes the bundle", () => {+ it("compresses finalized files after Rollup writes the bundle", async () => {const plugin = gzipWebuiAssets();expect(plugin.generateBundle).toBeUndefined();- expect(plugin.writeBundle).toBeTypeOf("function");-const outputDir = mkdtempSync(path.join(tmpdir(), "nanobot-vite-gzip-"));+ const assetPath = path.join(outputDir, "assets", "index-final.js");+ const finalized = Buffer.from(+ "const __vite__mapDeps = ['assets/lazy-feature.js'];\n".repeat(200),+ );+ const build = await rollup({+ input: "virtual-entry",+ plugins: [+ {+ name: "fixture-entry",+ resolveId: (id) => id === "virtual-entry" ? id : null,+ load: (id) => id === "virtual-entry" ? 'console.log("stale in-memory bytes");' : null,+ },+ {+ name: "finalize-on-disk",+ writeBundle: {+ sequential: true,+ handler() { writeFileSync(assetPath, finalized); },+ },+ },+ plugin,+ ],+ });try {- const assetPath = path.join(outputDir, "assets", "index-final.js");- mkdirSync(path.dirname(assetPath), { recursive: true });- const finalized = Buffer.from(- "const __vite__mapDeps = ['assets/lazy-feature.js'];\n".repeat(200),- );- writeFileSync(assetPath, finalized);-- writeCompressedWebuiAssets(outputDir, ["assets/index-final.js"]);-+ await build.write({ dir: outputDir, format: "es", entryFileNames: "assets/index-final.js" });expect(gunzipSync(readFileSync(`${assetPath}.gz`))).toEqual(finalized);} finally {+ await build.close();rmSync(outputDir, { recursive: true, force: true });}});diff --git a/webui/src/tests/webui-thread-cache.test.ts b/webui/src/tests/webui-thread-cache.test.tsindex 0139a9a7c..3a8e448db 100644--- a/webui/src/tests/webui-thread-cache.test.ts+++ b/webui/src/tests/webui-thread-cache.test.ts@@ -7,7 +7,8 @@ function payload(id: string): WebuiThreadPersistedPayload {return {schemaVersion: 3,revision: `rev-${id}`,- messages: [{ id, role: "assistant", content: id, createdAt: 1 }],+ projection: "events",+ events: [{ event: "message", chat_id: id, text: id }],};}diff --git a/webui/tsconfig.browser.json b/webui/tsconfig.browser.jsonnew file mode 100644index 000000000..cd674a09c--- /dev/null+++ b/webui/tsconfig.browser.json@@ -0,0 +1,5 @@+{+ "extends": "./tsconfig.build.json",+ "include": ["browser", "playwright.config.ts"],+ "exclude": []+}diff --git a/webui/tsconfig.json b/webui/tsconfig.jsonindex 5d964a164..0904e4761 100644--- a/webui/tsconfig.json+++ b/webui/tsconfig.json@@ -26,6 +26,7 @@"baseUrl": ".","paths": {"@/*": ["./src/*"],+ "vitest": ["./node_modules/vitest"],"lucide-react": ["./node_modules/lucide-react"],"react": ["./node_modules/@types/react/index.d.ts"],"react/*": ["./node_modules/@types/react/*"],