test: replace false-green checks with behavioral coverage (#6282)
* test: replace false-green checks with behavioral coverage * test: complete behavior-focused audit coverage
This commit is contained in:
1 parent
c7ab7aa6da
commit
74942bd190
91 files changed
+1891
-1391
No files matched your search
@@ -316,6 +316,14 @@ jobs:
|
|||||||
working-directory: webui
|
working-directory: webui
|
||||||
run: bun run test:coverage
|
run: 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 WebUI
|
- name: Build WebUI
|
||||||
working-directory: webui
|
working-directory: webui
|
||||||
run: bun run build
|
run: bun run build
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
"""Tests for Feishu/Lark domain configuration."""
|
"""Tests for Feishu/Lark domain configuration."""
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import ANY, AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig
|
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig
|
||||||
@@ -44,3 +46,46 @@ class TestFeishuConfigDomain:
|
|||||||
def test_channel_persists_feishu_domain_from_config(self):
|
def test_channel_persists_feishu_domain_from_config(self):
|
||||||
ch = _make_channel(domain="feishu")
|
ch = _make_channel(domain="feishu")
|
||||||
assert ch.config.domain == "feishu"
|
assert ch.config.domain == "feishu"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
@pytest.mark.parametrize("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()
|
||||||
@@ -9,7 +9,7 @@ import pytest
|
|||||||
pytest.importorskip("lark_oapi")
|
pytest.importorskip("lark_oapi")
|
||||||
|
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig, _FeishuStreamBuf
|
from nanobot.channels.feishu.runtime import FeishuChannel, FeishuConfig
|
||||||
|
|
||||||
|
|
||||||
def _make_channel() -> FeishuChannel:
|
def _make_channel() -> FeishuChannel:
|
||||||
@@ -187,12 +187,7 @@ class TestStreamEndReactionCleanup:
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_removes_reaction_on_stream_end(self):
|
async def test_removes_reaction_on_stream_end(self):
|
||||||
ch = _make_channel()
|
ch = _make_channel()
|
||||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})
|
||||||
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._remove_reaction = AsyncMock()
|
ch._remove_reaction = AsyncMock()
|
||||||
|
|
||||||
await ch.send_delta(
|
await ch.send_delta(
|
||||||
@@ -201,33 +196,23 @@ class TestStreamEndReactionCleanup:
|
|||||||
stream_end=True,
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_no_removal_when_message_id_missing(self):
|
async def test_no_removal_when_message_id_missing(self):
|
||||||
ch = _make_channel()
|
ch = _make_channel()
|
||||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
ch._reaction_ids["om_001"] = "rx_42"
|
||||||
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()
|
ch._remove_reaction = AsyncMock()
|
||||||
|
|
||||||
await ch.send_delta(
|
await ch.send_delta("oc_chat1", "", stream_end=True)
|
||||||
"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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_no_removal_when_reaction_id_missing(self):
|
async def test_no_removal_when_reaction_id_missing(self):
|
||||||
ch = _make_channel()
|
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()
|
ch._remove_reaction = AsyncMock()
|
||||||
|
|
||||||
await ch.send_delta(
|
await ch.send_delta(
|
||||||
@@ -241,26 +226,29 @@ class TestStreamEndReactionCleanup:
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_no_removal_when_not_stream_end(self):
|
async def test_no_removal_when_not_stream_end(self):
|
||||||
ch = _make_channel()
|
ch = _make_channel()
|
||||||
|
ch._reaction_ids["om_001"] = "rx_42"
|
||||||
|
ch._create_streaming_card_sync = MagicMock(return_value=None)
|
||||||
ch._remove_reaction = AsyncMock()
|
ch._remove_reaction = AsyncMock()
|
||||||
|
ch._add_reaction = AsyncMock()
|
||||||
|
ch.config.done_emoji = "DONE"
|
||||||
|
|
||||||
await ch.send_delta(
|
await ch.send_delta(
|
||||||
"oc_chat1", "more text",
|
"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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_no_removal_when_resuming(self):
|
async def test_no_removal_when_resuming(self):
|
||||||
"""resuming=True means more tool-call rounds follow; reaction must persist."""
|
"""resuming=True means more tool-call rounds follow; reaction must persist."""
|
||||||
ch = _make_channel()
|
ch = _make_channel()
|
||||||
ch.config.done_emoji = "DONE"
|
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._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._remove_reaction = AsyncMock()
|
||||||
ch._add_reaction = AsyncMock()
|
ch._add_reaction = AsyncMock()
|
||||||
|
|
||||||
@@ -281,12 +269,7 @@ class TestStreamEndReactionCleanup:
|
|||||||
"""Across resuming rounds, done_emoji is added only on the final round."""
|
"""Across resuming rounds, done_emoji is added only on the final round."""
|
||||||
ch = _make_channel()
|
ch = _make_channel()
|
||||||
ch.config.done_emoji = "DONE"
|
ch.config.done_emoji = "DONE"
|
||||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
ch._reaction_ids.update({"om_001": "rx_42", "om_other": "rx_other"})
|
||||||
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._remove_reaction = AsyncMock()
|
ch._remove_reaction = AsyncMock()
|
||||||
ch._add_reaction = AsyncMock()
|
ch._add_reaction = AsyncMock()
|
||||||
|
|
||||||
@@ -300,10 +283,8 @@ class TestStreamEndReactionCleanup:
|
|||||||
ch._remove_reaction.assert_not_called()
|
ch._remove_reaction.assert_not_called()
|
||||||
ch._add_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).
|
assert ch._reaction_ids == {"om_001": "rx_42", "om_other": "rx_other"}
|
||||||
ch._stream_bufs["oc_chat1"] = _FeishuStreamBuf(
|
|
||||||
text="t", card_id="card_1", sequence=5, last_edit=0.0,
|
|
||||||
)
|
|
||||||
# Final stream end (resuming=False): OnIt removed, done_emoji added.
|
# Final stream end (resuming=False): OnIt removed, done_emoji added.
|
||||||
await ch.send_delta(
|
await ch.send_delta(
|
||||||
"oc_chat1", "",
|
"oc_chat1", "",
|
||||||
@@ -311,5 +292,6 @@ class TestStreamEndReactionCleanup:
|
|||||||
stream_end=True,
|
stream_end=True,
|
||||||
resuming=False,
|
resuming=False,
|
||||||
)
|
)
|
||||||
ch._remove_reaction.assert_called_once_with("om_001", "rx_42")
|
ch._remove_reaction.assert_awaited_once_with("om_001", "rx_42")
|
||||||
ch._add_reaction.assert_called_once_with("om_001", "DONE")
|
ch._add_reaction.assert_awaited_once_with("om_001", "DONE")
|
||||||
|
assert ch._reaction_ids == {"om_other": "rx_other"}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { vi } from "vitest";
|
||||||
|
|
||||||
import { channelUiContribution } from "@/channel-plugins/registry";
|
import { channelUiContribution } from "@/channel-plugins/registry";
|
||||||
import { NanobotClient } from "@/lib/nanobot-client";
|
import { NanobotClient } from "@/lib/nanobot-client";
|
||||||
import type { ConnectionStatus } from "@/lib/types";
|
import type { ConnectionStatus } from "@/lib/types";
|
||||||
@@ -253,16 +255,21 @@ describe("Linear channel UI", () => {
|
|||||||
requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));
|
requestMutationMock.mockRejectedValueOnce(new Error("Unable to save settings"));
|
||||||
renderSettingsView({ initialSection: "channels" });
|
renderSettingsView({ initialSection: "channels" });
|
||||||
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
|
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
|
||||||
fireEvent.change(await screen.findByRole("textbox", { name: "OAuth client ID" }), {
|
const input = await screen.findByRole("textbox", { name: "OAuth client ID" });
|
||||||
target: { value: "replacement-client" },
|
vi.useFakeTimers();
|
||||||
});
|
try {
|
||||||
fireEvent.blur(screen.getByRole("textbox", { name: "OAuth client ID" }));
|
fireEvent.change(input, { target: { value: "replacement-client" } });
|
||||||
expect(await screen.findByText("Unable to save settings")).toBeVisible();
|
fireEvent.blur(input);
|
||||||
expect(screen.getByRole("textbox", { name: "OAuth client ID" })).toHaveValue("replacement-client");
|
await act(async () => { await vi.advanceTimersByTimeAsync(750); });
|
||||||
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
|
expect(screen.getByText("Unable to save settings")).toBeVisible();
|
||||||
await new Promise((resolve) => setTimeout(resolve, 750));
|
expect(input).toHaveValue("replacement-client");
|
||||||
expect(actionCalls()).toHaveLength(1);
|
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeDisabled();
|
||||||
expect(actionCalls()[0][1]).not.toHaveProperty("enable");
|
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 () => {
|
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" }));
|
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
|
||||||
const input = screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });
|
const input = screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" });
|
||||||
expect(input).toHaveFocus();
|
expect(input).toHaveFocus();
|
||||||
fireEvent.change(input, { target: { value: "replacement-secret" } });
|
vi.useFakeTimers();
|
||||||
fireEvent.blur(input);
|
try {
|
||||||
await new Promise((resolve) => setTimeout(resolve, 750));
|
fireEvent.change(input, { target: { value: "replacement-secret" } });
|
||||||
expect(actionCalls()).toHaveLength(0);
|
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 }));
|
fireEvent.click(screen.getByRole("button", { name: "Save", exact: true }));
|
||||||
await waitFor(() => expect(actionCalls()).toHaveLength(1));
|
await waitFor(() => expect(actionCalls()).toHaveLength(1));
|
||||||
const params = actionCalls()[0][1] as { values: Record<string, unknown> };
|
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" }));
|
fireEvent.click(await screen.findByRole("button", { name: "View Linear settings" }));
|
||||||
await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
|
await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
|
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
|
||||||
fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {
|
vi.useFakeTimers();
|
||||||
target: { value: "discarded-draft" },
|
try {
|
||||||
});
|
fireEvent.change(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" }), {
|
||||||
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
|
target: { value: "discarded-draft" },
|
||||||
expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);
|
});
|
||||||
expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled();
|
fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
|
||||||
await new Promise(resolve => setTimeout(resolve, 750));
|
expect(screen.getAllByText("Saved", { exact: true })).toHaveLength(2);
|
||||||
expect(actionCalls()).toHaveLength(0);
|
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" }));
|
fireEvent.click(screen.getByRole("button", { name: "Replace OAuth client secret" }));
|
||||||
expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("");
|
expect(screen.getByLabelText("OAuth client secret", { exact: true, selector: "input" })).toHaveValue("");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -951,14 +951,30 @@ async def test_typing_keepalive_refreshes_periodically(monkeypatch) -> None:
|
|||||||
channel._running = True
|
channel._running = True
|
||||||
|
|
||||||
monkeypatch.setattr(matrix_module, "TYPING_KEEPALIVE_INTERVAL_MS", 10)
|
monkeypatch.setattr(matrix_module, "TYPING_KEEPALIVE_INTERVAL_MS", 10)
|
||||||
|
refreshed = asyncio.Event()
|
||||||
|
room_typing = client.room_typing
|
||||||
|
|
||||||
await channel._start_typing_keepalive("!room:matrix.org")
|
async def record_typing(**kwargs):
|
||||||
await asyncio.sleep(0.03)
|
response = await room_typing(**kwargs)
|
||||||
await channel._stop_typing_keepalive("!room:matrix.org", clear_typing=True)
|
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]
|
true_updates = [call for call in client.typing_calls if call[1] is True]
|
||||||
assert len(true_updates) >= 2
|
assert len(true_updates) >= 2
|
||||||
assert client.typing_calls[-1] == ("!room:matrix.org", False, TYPING_NOTICE_TIMEOUT_MS)
|
assert 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
|
@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)
|
monkeypatch.setattr("nanobot.channels.matrix.runtime.get_data_dir", lambda: tmp_path)
|
||||||
|
|
||||||
channel = MatrixChannel(_make_config(), MessageBus())
|
channel = MatrixChannel(_make_config(), MessageBus())
|
||||||
client = _FakeAsyncClient("", "", "", None)
|
channel.client = _FakeAsyncClient("", "", "", None)
|
||||||
client.download_bytes = b"image"
|
downloads: list[tuple[str, int]] = []
|
||||||
channel.client = client
|
|
||||||
|
|
||||||
|
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]] = []
|
handled: list[dict[str, object]] = []
|
||||||
|
|
||||||
async def _fake_handle_message(**kwargs) -> None:
|
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)
|
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
|
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"]
|
metadata = handled[0]["metadata"]
|
||||||
|
assert metadata["attachments"][0]["path"] == media_paths[0]
|
||||||
assert metadata["thread_root_event_id"] == "$root1"
|
assert metadata["thread_root_event_id"] == "$root1"
|
||||||
assert metadata["thread_reply_to_event_id"] == "$event1"
|
assert metadata["thread_reply_to_event_id"] == "$event1"
|
||||||
assert metadata["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
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_send_room_content_returns_room_send_response():
|
async def test_send_room_content_returns_room_send_response():
|
||||||
"""Test that _send_room_content returns the response from client.room_send."""
|
"""Test that _send_room_content returns the response from client.room_send."""
|
||||||
|
|||||||
@@ -105,8 +105,11 @@ def test_guess_send_file_type_file() -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_guess_send_file_type_by_mime() -> None:
|
def test_guess_send_file_type_by_mime() -> None:
|
||||||
# A filename with no known extension but whose mime type is image/*
|
filename = "photo.xyz_image_test"
|
||||||
assert _guess_send_file_type("photo.xyz_image_test") == QQ_FILE_TYPE_FILE
|
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 ───────────────────────────────────────
|
# ── send() exception handling ───────────────────────────────────────
|
||||||
|
|||||||
@@ -90,10 +90,12 @@ def test_markdown_style_mapping(markdown, expected_plain, styled_text, style):
|
|||||||
|
|
||||||
def test_code_block():
|
def test_code_block():
|
||||||
plain, styles = _markdown_to_signal("```\nprint('hi')\n```")
|
plain, styles = _markdown_to_signal("```\nprint('hi')\n```")
|
||||||
assert "print('hi')" in plain
|
assert plain.rstrip("\n") == "print('hi')"
|
||||||
assert styles_for(plain, styles).get("print('hi')\n") == ["MONOSPACE"] or "MONOSPACE" in str(
|
assert {
|
||||||
styles_for(plain, styles)
|
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():
|
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)."""
|
"""Header becomes BOLD; code inside becomes MONOSPACE (not double-BOLD)."""
|
||||||
plain, styles = _markdown_to_signal("# Use `grep`")
|
plain, styles = _markdown_to_signal("# Use `grep`")
|
||||||
assert plain == "Use grep"
|
assert plain == "Use grep"
|
||||||
sd = styles_for(plain, styles)
|
assert utf16_styles_for(plain, styles) == {
|
||||||
assert "BOLD" in sd.get("Use ", []) or "BOLD" in str(styles)
|
"Use ": ["BOLD"], "grep": ["MONOSPACE"],
|
||||||
assert "MONOSPACE" in sd.get("grep", [])
|
}
|
||||||
|
assert_within_utf16_bounds(plain, styles)
|
||||||
|
|
||||||
|
|
||||||
def test_multiline_mixed():
|
def test_multiline_mixed():
|
||||||
@@ -435,20 +438,16 @@ def test_inline_code_inside_blockquote():
|
|||||||
assert sd.get("grep") == ["MONOSPACE"]
|
assert sd.get("grep") == ["MONOSPACE"]
|
||||||
|
|
||||||
|
|
||||||
def test_header_with_inner_bold_produces_contiguous_bold_ranges():
|
def test_header_with_inner_bold_covers_whole_header():
|
||||||
"""`# **wrap** me` — header forces BOLD over the whole line; the inner `**`
|
"""Header text is bold regardless of equivalent adjacent range fragmentation."""
|
||||||
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.
|
|
||||||
"""
|
|
||||||
plain, styles = _markdown_to_signal("# **wrap** me")
|
plain, styles = _markdown_to_signal("# **wrap** me")
|
||||||
assert plain == "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")]
|
bold_ranges = [s for s in styles if s.endswith(":BOLD")]
|
||||||
assert len(bold_ranges) == 2
|
|
||||||
covered = set()
|
covered = set()
|
||||||
for entry in bold_ranges:
|
for entry in bold_ranges:
|
||||||
start, length, _ = entry.split(":", 2)
|
start, length, _ = entry.split(":", 2)
|
||||||
for i in range(int(start), int(start) + int(length)):
|
for i in range(int(start), int(start) + int(length)):
|
||||||
covered.add(i)
|
covered.add(i)
|
||||||
assert covered == set(range(len(plain)))
|
assert covered == set(range(_utf16_len(plain)))
|
||||||
@@ -773,9 +773,12 @@ async def test_running_message_handler_reorders_same_session_updates() -> None:
|
|||||||
MessageBus(),
|
MessageBus(),
|
||||||
)
|
)
|
||||||
seen: list[int] = []
|
seen: list[int] = []
|
||||||
|
processed = asyncio.Event()
|
||||||
|
|
||||||
async def fake_process(update, context) -> None:
|
async def fake_process(update, context) -> None:
|
||||||
seen.append(update.message.message_id)
|
seen.append(update.message.message_id)
|
||||||
|
if len(seen) == 2:
|
||||||
|
processed.set()
|
||||||
|
|
||||||
channel._process_message_update = fake_process
|
channel._process_message_update = fake_process
|
||||||
channel._running = True
|
channel._running = True
|
||||||
@@ -787,12 +790,20 @@ async def test_running_message_handler_reorders_same_session_updates() -> None:
|
|||||||
second.update_id = 101
|
second.update_id = 101
|
||||||
second.message.message_id = 2
|
second.message.message_id = 2
|
||||||
|
|
||||||
await channel._on_message(second, None)
|
workers: set[asyncio.Task[None]] = set()
|
||||||
await channel._on_message(first, None)
|
try:
|
||||||
await asyncio.sleep(0.3)
|
await channel._on_message(second, None)
|
||||||
channel._running = False
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ from .ws_test_client import http_get as _http_get
|
|||||||
|
|
||||||
# -- Shared helpers (aligned with test_websocket_integration.py) ---------------
|
# -- Shared helpers (aligned with test_websocket_integration.py) ---------------
|
||||||
|
|
||||||
_PORT = 29876
|
_PORT = 0
|
||||||
|
|
||||||
|
|
||||||
async def _register_running_turn(
|
async def _register_running_turn(
|
||||||
@@ -180,12 +180,36 @@ def _basic_handler(bus: Any, **kw: Any) -> GatewayServices:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _connect_when_ready(url: str) -> Any:
|
@pytest.fixture
|
||||||
while True:
|
async def start_listener():
|
||||||
try:
|
"""Start test-owned ephemeral listeners and join them even if setup/assertions fail."""
|
||||||
return await websockets.connect(url)
|
listeners = []
|
||||||
except OSError:
|
|
||||||
await asyncio.sleep(0.02)
|
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(
|
async def _wait_for_connection_cleanup(
|
||||||
@@ -875,8 +899,8 @@ def test_issue_route_secret_matches_empty_secret() -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock) -> None:
|
async def test_token_issue_route_requires_secret_when_static_token_configured(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29882
|
port = 0
|
||||||
channel = _ch(
|
channel = _ch(
|
||||||
bus,
|
bus,
|
||||||
port=port,
|
port=port,
|
||||||
@@ -885,8 +909,7 @@ async def test_token_issue_route_requires_secret_when_static_token_configured(bu
|
|||||||
websocketRequiresToken=True,
|
websocketRequiresToken=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
denied = await _http_get(f"http://127.0.0.1:{port}/custom-token")
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock) -> None:
|
async def test_end_to_end_client_receives_ready_and_agent_sees_inbound(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29876
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
client = await asyncio.wait_for(
|
client = await websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=tester")
|
||||||
_connect_when_ready(f"ws://127.0.0.1:{port}/ws?client_id=tester"),
|
|
||||||
timeout=5,
|
|
||||||
)
|
|
||||||
async with client:
|
async with client:
|
||||||
ready_raw = await client.recv()
|
ready_raw = await client.recv()
|
||||||
ready = json.loads(ready_raw)
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_token_rejects_handshake_when_mismatch(bus: MagicMock) -> None:
|
async def test_token_rejects_handshake_when_mismatch(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29877
|
port = 0
|
||||||
channel = _ch(bus, port=port, path="/", token="secret")
|
channel = _ch(bus, port=port, path="/", token="secret")
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_wrong_path_returns_404(bus: MagicMock) -> None:
|
async def test_wrong_path_returns_404(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29878
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
|
with pytest.raises(websockets.exceptions.InvalidStatus) as excinfo:
|
||||||
@@ -4237,8 +4255,8 @@ def test_registry_discovers_websocket_channel() -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock) -> None:
|
async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29879
|
port = 0
|
||||||
channel = _ch(
|
channel = _ch(
|
||||||
bus, port=port,
|
bus, port=port,
|
||||||
tokenIssuePath="/auth/token",
|
tokenIssuePath="/auth/token",
|
||||||
@@ -4246,8 +4264,7 @@ async def test_http_route_issues_token_then_websocket_requires_it(bus: MagicMock
|
|||||||
websocketRequiresToken=True,
|
websocketRequiresToken=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
deny = await _http_get(f"http://127.0.0.1:{port}/auth/token")
|
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,
|
bus: MagicMock,
|
||||||
monkeypatch,
|
monkeypatch,
|
||||||
tmp_path,
|
tmp_path,
|
||||||
|
start_listener,
|
||||||
) -> None:
|
) -> None:
|
||||||
port = 29891
|
port = 0
|
||||||
config_path = tmp_path / "config.json"
|
config_path = tmp_path / "config.json"
|
||||||
config = Config()
|
config = Config()
|
||||||
config.agents.defaults.model = "openai/gpt-4o"
|
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 = _ch(bus, port=port, image_generation_reload=image_reload)
|
||||||
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
webui_client = None
|
webui_client = None
|
||||||
try:
|
try:
|
||||||
@@ -4700,6 +4717,7 @@ async def test_image_settings_hot_reload_without_restart(
|
|||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
provider_name: str,
|
provider_name: str,
|
||||||
|
start_listener,
|
||||||
) -> None:
|
) -> None:
|
||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
from nanobot.agent.tools.image_generation import (
|
from nanobot.agent.tools.image_generation import (
|
||||||
@@ -4707,7 +4725,7 @@ async def test_image_settings_hot_reload_without_restart(
|
|||||||
reload_image_generation_tool,
|
reload_image_generation_tool,
|
||||||
)
|
)
|
||||||
|
|
||||||
port = 29935
|
port = 0
|
||||||
config_path = tmp_path / "config.json"
|
config_path = tmp_path / "config.json"
|
||||||
config = Config.model_validate({"providers": {"SenseNova": {
|
config = Config.model_validate({"providers": {"SenseNova": {
|
||||||
"apiKey": "named-image-key", "apiBase": "https://images.test/v1",
|
"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 = _ch(runtime_bus, port=port, image_generation_reload=image_reload)
|
||||||
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
webui_client = None
|
webui_client = None
|
||||||
try:
|
try:
|
||||||
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
|
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,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
runtime_available: bool,
|
runtime_available: bool,
|
||||||
|
start_listener,
|
||||||
) -> None:
|
) -> None:
|
||||||
port = 29936
|
port = 0
|
||||||
config_path = tmp_path / "config.json"
|
config_path = tmp_path / "config.json"
|
||||||
config = Config()
|
config = Config()
|
||||||
config.providers.openrouter.api_key = "image-key"
|
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 = _ch(bus, port=port, image_generation_reload=image_reload if runtime_available else None)
|
||||||
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
webui_client = None
|
webui_client = None
|
||||||
try:
|
try:
|
||||||
webui_token = channel.gateway.tokens.issue_token(300, audience="webui")
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_commands_api_returns_slash_command_metadata(bus: MagicMock) -> None:
|
async def test_commands_api_returns_slash_command_metadata(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29892
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
channel.gateway.tokens.api_tokens["tok"] = time.monotonic() + 300
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
denied = await _http_get(f"http://127.0.0.1:{port}/api/commands")
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:
|
async def test_bootstrap_exposes_native_surface(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29893
|
port = 0
|
||||||
channel = WebSocketChannel(
|
channel = WebSocketChannel(
|
||||||
{
|
{
|
||||||
"enabled": True,
|
"enabled": True,
|
||||||
@@ -4883,8 +4899,7 @@ async def test_bootstrap_exposes_native_surface(bus: MagicMock) -> None:
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = await _http_get(
|
response = await _http_get(
|
||||||
@@ -4990,12 +5005,11 @@ def test_update_provider_settings_ignores_api_type_for_non_openai(monkeypatch, t
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock) -> None:
|
async def test_end_to_end_server_pushes_streaming_deltas_to_client(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29880
|
port = 0
|
||||||
channel = _ch(bus, port=port, streaming=True)
|
channel = _ch(bus, port=port, streaming=True)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=stream-tester") as client:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_token_issue_rejects_when_at_capacity(bus: MagicMock) -> None:
|
async def test_token_issue_rejects_when_at_capacity(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29881
|
port = 0
|
||||||
channel = _ch(bus, port=port, tokenIssuePath="/auth/token", tokenIssueSecret="s")
|
channel = _ch(bus, port=port, tokenIssuePath="/auth/token", tokenIssueSecret="s")
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Fill issued tokens to capacity
|
# Fill issued tokens to capacity
|
||||||
@@ -5071,12 +5084,11 @@ async def test_token_issue_rejects_when_at_capacity(bus: MagicMock) -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock) -> None:
|
async def test_allow_from_rejects_unauthorized_client_id(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29882
|
port = 0
|
||||||
channel = _ch(bus, port=port, allowFrom=["alice", "bob"])
|
channel = _ch(bus, port=port, allowFrom=["alice", "bob"])
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_client_id_truncation(bus: MagicMock) -> None:
|
async def test_client_id_truncation(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29883
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
long_id = "x" * 200
|
long_id = "x" * 200
|
||||||
@@ -5330,12 +5341,11 @@ async def test_client_id_truncation(bus: MagicMock) -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_non_utf8_binary_frame_ignored(bus: MagicMock) -> None:
|
async def test_non_utf8_binary_frame_ignored(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29884
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bin-test") as client:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) -> None:
|
async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29885
|
port = 0
|
||||||
channel = _ch(
|
channel = _ch(
|
||||||
bus, port=port,
|
bus, port=port,
|
||||||
token="static-secret",
|
token="static-secret",
|
||||||
@@ -5360,8 +5370,7 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) ->
|
|||||||
tokenIssueSecret="route-secret",
|
tokenIssueSecret="route-secret",
|
||||||
)
|
)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Get an issued token
|
# Get an issued token
|
||||||
@@ -5382,12 +5391,11 @@ async def test_static_token_accepts_issued_token_as_fallback(bus: MagicMock) ->
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_allow_from_empty_list_denies_all(bus: MagicMock) -> None:
|
async def test_allow_from_empty_list_denies_all(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29886
|
port = 0
|
||||||
channel = _ch(bus, port=port, allowFrom=[])
|
channel = _ch(bus, port=port, allowFrom=[])
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with pytest.raises(websockets.exceptions.InvalidStatus) as exc_info:
|
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
|
@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."""
|
"""When websocket_requires_token is True but no token or issue path configured, all connections are rejected."""
|
||||||
port = 29887
|
port = 0
|
||||||
channel = _ch(bus, port=port, websocketRequiresToken=True)
|
channel = _ch(bus, port=port, websocketRequiresToken=True)
|
||||||
|
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# No token at all → 401
|
# No token at all → 401
|
||||||
@@ -5433,11 +5440,10 @@ async def test_websocket_requires_token_without_issue_path(bus: MagicMock) -> No
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_multiplex_legacy_still_works(bus: MagicMock) -> None:
|
async def test_multiplex_legacy_still_works(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29930
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=legacy") as client:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_multiplex_new_chat_roundtrip(bus: MagicMock) -> None:
|
async def test_multiplex_new_chat_roundtrip(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29931
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=mp") as client:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_multiplex_two_chats_isolated(bus: MagicMock) -> None:
|
async def test_multiplex_two_chats_isolated(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29932
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=two") as client:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_multiplex_invalid_frames_return_error(bus: MagicMock) -> None:
|
async def test_multiplex_invalid_frames_return_error(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29933
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=bad") as client:
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_multiplex_cleanup_on_disconnect(bus: MagicMock) -> None:
|
async def test_multiplex_cleanup_on_disconnect(bus: MagicMock, start_listener) -> None:
|
||||||
port = 29934
|
port = 0
|
||||||
channel = _ch(bus, port=port)
|
channel = _ch(bus, port=port)
|
||||||
server_task = asyncio.create_task(channel.start())
|
port, server_task = await start_listener(channel)
|
||||||
await asyncio.sleep(0.3)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=dc") as client:
|
async with websockets.connect(f"ws://127.0.0.1:{port}/ws?client_id=dc") as client:
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ def test_sanitize_filename_empty_or_dots_fallback() -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@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."""
|
"""Successful download writes file and returns sanitized path."""
|
||||||
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
|
channel = WecomChannel(WecomConfig(bot_id="b", secret="s", allow_from=["*"]), MessageBus())
|
||||||
client = _FakeWeComClient()
|
client = _FakeWeComClient()
|
||||||
@@ -110,14 +110,12 @@ async def test_download_and_save_success() -> None:
|
|||||||
fake_data = b"\x89PNG\r\nfake image"
|
fake_data = b"\x89PNG\r\nfake image"
|
||||||
client.download_file.return_value = (fake_data, "raw_photo.png")
|
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")
|
path = await channel._download_and_save_media("https://example.com/img.png", "aes_key", "image", "photo.png")
|
||||||
|
|
||||||
assert path is not None
|
assert path is not None
|
||||||
assert os.path.isfile(path)
|
assert Path(path) == tmp_path / "photo.png"
|
||||||
assert os.path.basename(path) == "photo.png"
|
assert Path(path).read_bytes() == fake_data
|
||||||
# Cleanup
|
|
||||||
os.unlink(path)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -253,7 +253,10 @@ async def test_qr_fetch_does_not_retry_invalid_request_without_local_tokens(tmp_
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_lifecycle_notifications_are_best_effort() -> None:
|
async def test_lifecycle_notifications_are_best_effort() -> None:
|
||||||
channel = _ready_channel()
|
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("start")
|
||||||
await channel._notify_lifecycle("stop")
|
await channel._notify_lifecycle("stop")
|
||||||
|
|||||||
@@ -507,26 +507,17 @@ class TestArchiveDelegates:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_no_summary_when_compact_returns_empty(self):
|
async def test_no_summary_when_compact_returns_empty(self):
|
||||||
ac = _make_autocompact()
|
|
||||||
mock_sm = _mock_sessions()
|
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="")
|
ac.consolidator.compact_idle_session = AsyncMock(return_value="")
|
||||||
|
|
||||||
await ac._archive("cli:test", runtime=_runtime())
|
await ac._archive("cli:test", runtime=_runtime())
|
||||||
|
|
||||||
assert "cli:test" not in ac._summaries
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_exception_still_removes_from_archiving(self):
|
async def test_exception_still_removes_from_archiving(self):
|
||||||
ac = _make_autocompact()
|
ac = _make_autocompact()
|
||||||
|
|||||||
@@ -1,21 +1,36 @@
|
|||||||
from __future__ import annotations
|
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):
|
def __init__(self):
|
||||||
self.last_ctx = None
|
self.last_ctx = None
|
||||||
|
|
||||||
def set_context(self, ctx: RequestContext) -> None:
|
def set_context(self, ctx: RequestContext) -> None:
|
||||||
self.last_ctx = ctx
|
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()
|
tool = _ContextTool()
|
||||||
|
registry = ToolRegistry()
|
||||||
|
registry.register(tool)
|
||||||
ctx = RequestContext(channel="test", chat_id="123", session_key="test:123")
|
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 ctx
|
||||||
|
|
||||||
|
|
||||||
def test_context_tool_is_instance_of_context_aware():
|
def test_context_tool_is_instance_of_context_aware():
|
||||||
|
|||||||
@@ -281,16 +281,13 @@ class TestBuildUserContent:
|
|||||||
|
|
||||||
|
|
||||||
class TestBuildSystemPrompt:
|
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):
|
def test_includes_identity_section(self, tmp_path):
|
||||||
builder = _builder(tmp_path)
|
builder = _builder(tmp_path)
|
||||||
result = builder.build_system_prompt()
|
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 result
|
||||||
|
|
||||||
def test_default_identity_uses_relative_agent_paths(self, tmp_path):
|
def test_default_identity_uses_relative_agent_paths(self, tmp_path):
|
||||||
result = ContextBuilder(tmp_path)._get_identity()
|
result = ContextBuilder(tmp_path)._get_identity()
|
||||||
|
|||||||
@@ -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():
|
def test_composite_finalize_content_none_passthrough():
|
||||||
hook = CompositeHook([AgentHook()])
|
hook = CompositeHook([AgentHook()])
|
||||||
assert hook.finalize_content(_ctx(), None) is None
|
assert hook.finalize_content(_ctx(), None) is None
|
||||||
|
|||||||
@@ -64,8 +64,8 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
|
|||||||
release = threading.Event()
|
release = threading.Event()
|
||||||
captured = []
|
captured = []
|
||||||
finalized = []
|
finalized = []
|
||||||
ticks = []
|
heartbeat_requested = asyncio.Event()
|
||||||
ticking = True
|
heartbeat_progress = asyncio.Event()
|
||||||
|
|
||||||
class Lifecycle(AgentHook):
|
class Lifecycle(AgentHook):
|
||||||
async def on_finally(self, context):
|
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"
|
context.messages[0]["content"] = "hook-only"
|
||||||
|
|
||||||
async def heartbeat():
|
async def heartbeat():
|
||||||
while ticking:
|
while True:
|
||||||
ticks.append(runtime_loop.time())
|
await heartbeat_requested.wait()
|
||||||
await asyncio.sleep(0.01)
|
heartbeat_requested.clear()
|
||||||
|
heartbeat_progress.set()
|
||||||
|
|
||||||
def blocked(operation, *args, **kwargs):
|
def blocked(operation, *args, **kwargs):
|
||||||
captured.append((current_request_context(), current_workspace_scope(), threading.get_ident()))
|
captured.append((current_request_context(), current_workspace_scope(), threading.get_ident()))
|
||||||
runtime_loop.call_soon_threadsafe(entered.set)
|
runtime_loop.call_soon_threadsafe(entered.set)
|
||||||
try:
|
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)
|
return operation(*args, **kwargs)
|
||||||
finally:
|
finally:
|
||||||
runtime_loop.call_soon_threadsafe(finished.set)
|
runtime_loop.call_soon_threadsafe(finished.set)
|
||||||
@@ -127,11 +128,11 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
|
|||||||
tasks = [task, pulse]
|
tasks = [task, pulse]
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(entered.wait(), timeout=5)
|
await asyncio.wait_for(entered.wait(), timeout=5)
|
||||||
before = len(ticks)
|
status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 5)
|
||||||
status = await asyncio.wait_for(loop.process_direct("/status", session_key="cli:status"), 0.5)
|
|
||||||
assert status is not None and "test-model" in status.content
|
assert status is not None and "test-model" in status.content
|
||||||
await asyncio.sleep(0.04)
|
heartbeat_requested.set()
|
||||||
assert len(ticks) >= before + 2
|
await asyncio.wait_for(heartbeat_progress.wait(), 5)
|
||||||
|
assert not release.is_set()
|
||||||
assert not finished.is_set()
|
assert not finished.is_set()
|
||||||
assert captured[0][2] != threading.get_ident()
|
assert captured[0][2] != threading.get_ident()
|
||||||
if phase != "history":
|
if phase != "history":
|
||||||
@@ -145,7 +146,7 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
|
|||||||
if cancel:
|
if cancel:
|
||||||
task.cancel()
|
task.cancel()
|
||||||
with pytest.raises(asyncio.CancelledError):
|
with pytest.raises(asyncio.CancelledError):
|
||||||
await asyncio.wait_for(task, 0.5)
|
await asyncio.wait_for(task, 5)
|
||||||
assert not finished.is_set()
|
assert not finished.is_set()
|
||||||
if phase != "history":
|
if phase != "history":
|
||||||
assert len(finalized) == 1
|
assert len(finalized) == 1
|
||||||
@@ -155,15 +156,32 @@ async def test_preparation_allows_status_heartbeat_and_cancellation(
|
|||||||
assert final_loop is runtime_loop
|
assert final_loop is runtime_loop
|
||||||
if phase != "prompt":
|
if phase != "prompt":
|
||||||
assert snapshot
|
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"))
|
waiting = asyncio.create_task(loop.process_direct("Queued", session_key="cli:waiting"))
|
||||||
tasks.append(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_requests
|
assert len(provider.requests) == expected_requests
|
||||||
assert not waiting.done()
|
assert not waiting.done()
|
||||||
waiting.cancel()
|
waiting.cancel()
|
||||||
with pytest.raises(asyncio.CancelledError):
|
with pytest.raises(asyncio.CancelledError):
|
||||||
await asyncio.wait_for(waiting, 0.5)
|
await asyncio.wait_for(waiting, 5)
|
||||||
elif phase == "history":
|
elif phase == "history":
|
||||||
# The live nested payload may change after capture; the worker owns its copy.
|
# The live nested payload may change after capture; the worker owns its copy.
|
||||||
live.messages[0]["content"][0]["text"] = "Changed after capture"
|
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 None
|
assert current_request_context() is None
|
||||||
assert current_workspace_scope() is None
|
assert current_workspace_scope() is None
|
||||||
finally:
|
finally:
|
||||||
ticking = False
|
|
||||||
release.set()
|
release.set()
|
||||||
for pending in tasks:
|
for pending in tasks:
|
||||||
if not pending.done():
|
if not pending.done():
|
||||||
|
|||||||
@@ -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
|
# 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)
|
# upstream: messages.content.N.tool_use.name: Input should be a valid string)
|
||||||
|
|||||||
@@ -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"
|
assert result.tool_events and result.tool_events[0]["status"] == "error"
|
||||||
# v2: detail keeps the breadcrumb but the runner did not raise.
|
# v2: detail keeps the breadcrumb but the runner did not raise.
|
||||||
assert "workspace_violation" in result.tool_events[0]["detail"]
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -147,6 +147,7 @@ class TestInspectPathNavigation:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_inspect_config_subfield(self):
|
async def test_inspect_config_subfield(self):
|
||||||
|
"""Positive control for sensitive-field blocking: ordinary config stays inspectable."""
|
||||||
loop = _make_mock_loop()
|
loop = _make_mock_loop()
|
||||||
tool = _make_tool(loop=loop)
|
tool = _make_tool(loop=loop)
|
||||||
result = await tool.execute(action="check", key="web_config.enable")
|
result = await tool.execute(action="check", key="web_config.enable")
|
||||||
@@ -649,60 +650,6 @@ class TestSubagentHookStatus:
|
|||||||
assert context.iteration == 1
|
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)
|
# 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")
|
result = await tool.execute(action="set", key="some_config.password", value="evil")
|
||||||
assert "not accessible" in result
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_modify_sensitive_top_level_blocked(self):
|
async def test_modify_sensitive_top_level_blocked(self):
|
||||||
"""Top-level key matching sensitive name must be blocked for set."""
|
"""Top-level key matching sensitive name must be blocked for set."""
|
||||||
|
|||||||
@@ -110,19 +110,13 @@ async def test_subagent_exec_tool_receives_allowed_env_keys(tmp_path):
|
|||||||
)
|
)
|
||||||
mgr._announce_result = AsyncMock()
|
mgr._announce_result = AsyncMock()
|
||||||
|
|
||||||
async def fake_run(spec):
|
mgr.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||||
exec_tool = spec.tools.get("exec")
|
messages=[],
|
||||||
assert exec_tool is not None
|
stop_reason="done",
|
||||||
assert exec_tool.allowed_env_keys == ["GOPATH", "JAVA_HOME"]
|
final_content="done",
|
||||||
return AgentRunResult(
|
error=None,
|
||||||
messages=[],
|
tool_events=[],
|
||||||
stop_reason="done",
|
))
|
||||||
final_content="done",
|
|
||||||
error=None,
|
|
||||||
tool_events=[],
|
|
||||||
)
|
|
||||||
|
|
||||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
|
||||||
|
|
||||||
await mgr.spawn(
|
await mgr.spawn(
|
||||||
task="do task",
|
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)
|
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||||
|
|
||||||
mgr.runner.run.assert_awaited_once()
|
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
|
@pytest.mark.asyncio
|
||||||
@@ -154,17 +153,13 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
|
|||||||
)
|
)
|
||||||
mgr._announce_result = AsyncMock()
|
mgr._announce_result = AsyncMock()
|
||||||
|
|
||||||
async def fake_run(spec):
|
mgr.runner.run = AsyncMock(return_value=AgentRunResult(
|
||||||
assert spec.max_iterations == 37
|
messages=[],
|
||||||
return AgentRunResult(
|
stop_reason="done",
|
||||||
messages=[],
|
final_content="done",
|
||||||
stop_reason="done",
|
error=None,
|
||||||
final_content="done",
|
tool_events=[],
|
||||||
error=None,
|
))
|
||||||
tool_events=[],
|
|
||||||
)
|
|
||||||
|
|
||||||
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
|
||||||
|
|
||||||
await mgr.spawn(
|
await mgr.spawn(
|
||||||
task="do task",
|
task="do task",
|
||||||
@@ -176,6 +171,55 @@ async def test_subagent_uses_configured_max_iterations(tmp_path):
|
|||||||
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||||
|
|
||||||
mgr.runner.run.assert_awaited_once()
|
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"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
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):
|
||||||
|
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",
|
||||||
|
final_content="done",
|
||||||
|
error=None,
|
||||||
|
tool_events=[],
|
||||||
|
)
|
||||||
|
|
||||||
|
mgr.runner.run = AsyncMock(side_effect=fake_run)
|
||||||
|
|
||||||
|
await mgr.spawn(task="do task", session_key="test:c1", runtime=_runtime(MagicMock()))
|
||||||
|
await asyncio.gather(*mgr._running_tasks.values(), return_exceptions=True)
|
||||||
|
|
||||||
|
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.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import subprocess
|
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -53,59 +52,6 @@ def test_subprocess_env_excludes_api_keys_on_windows(monkeypatch, tmp_path) -> N
|
|||||||
assert all(isinstance(value, str) for value in env.values())
|
assert 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("operation", ["run", "management"])
|
||||||
@pytest.mark.parametrize("runtime_dir", ["/run/user/1000", None])
|
@pytest.mark.parametrize("runtime_dir", ["/run/user/1000", None])
|
||||||
def test_child_process_receives_runtime_dir_without_api_keys(
|
def test_child_process_receives_runtime_dir_without_api_keys(
|
||||||
|
|||||||
@@ -3,10 +3,12 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from contextlib import suppress
|
||||||
from unittest.mock import AsyncMock
|
from unittest.mock import AsyncMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.bus.events import OutboundMessage
|
||||||
from nanobot.bus.outbound_events import (
|
from nanobot.bus.outbound_events import (
|
||||||
ContextCompactionEvent,
|
ContextCompactionEvent,
|
||||||
ProgressEvent,
|
ProgressEvent,
|
||||||
@@ -33,84 +35,77 @@ class _MockChannel(BaseChannel):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
async def send(self, msg):
|
async def send(self, msg):
|
||||||
if isinstance(msg.event, ContextCompactionEvent) and not (
|
|
||||||
msg.event.notify or self.show_compaction_notices
|
|
||||||
):
|
|
||||||
return
|
|
||||||
return await self._send_mock(msg)
|
return await self._send_mock(msg)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def manager() -> ChannelManager:
|
def manager(tmp_path) -> ChannelManager:
|
||||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
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)
|
mgr.channels["mock"] = _MockChannel({}, mgr.bus)
|
||||||
return mgr
|
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
|
@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,
|
manager: ChannelManager,
|
||||||
) -> None:
|
) -> None:
|
||||||
manager.channels["mock"].send_progress = False
|
channel = manager.channels["mock"]
|
||||||
for event in (
|
channel.send_progress = False
|
||||||
ProgressEvent(content="ordinary progress"),
|
channel.show_compaction_notices = False
|
||||||
|
events = [
|
||||||
ContextCompactionEvent(compaction_id="auto", phase="started"),
|
ContextCompactionEvent(compaction_id="auto", phase="started"),
|
||||||
ContextCompactionEvent(compaction_id="auto", phase="succeeded"),
|
ContextCompactionEvent(compaction_id="auto", phase="succeeded"),
|
||||||
ContextCompactionEvent(compaction_id="auto-failed", phase="failed"),
|
ContextCompactionEvent(compaction_id="auto-failed", phase="failed"),
|
||||||
ContextCompactionEvent(compaction_id="auto-cancelled", phase="cancelled"),
|
ContextCompactionEvent(compaction_id="auto-cancelled", phase="cancelled"),
|
||||||
ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),
|
ContextCompactionEvent(compaction_id="c1", phase="started", notify=True),
|
||||||
ContextCompactionEvent(compaction_id="c1", phase="succeeded", notify=True),
|
ContextCompactionEvent(compaction_id="c1", phase="succeeded", notify=True),
|
||||||
):
|
]
|
||||||
await manager.bus.publish_outbound(
|
await manager.bus.publish_outbound(outbound_message_for_event(
|
||||||
outbound_message_for_event(channel="mock", chat_id="chat", event=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()
|
||||||
|
|
||||||
await _dispatch_until(manager, 2)
|
def record_send(msg):
|
||||||
|
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat", "Final", None):
|
||||||
|
delivered.set()
|
||||||
|
|
||||||
contents = _sent_contents(manager)
|
channel._send_mock.side_effect = record_send
|
||||||
assert "ordinary progress" not in contents
|
task = asyncio.create_task(manager._dispatch_outbound())
|
||||||
assert contents == ["Compressing context…", "Context compacted."]
|
try:
|
||||||
|
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||||
|
finally:
|
||||||
|
task.cancel()
|
||||||
|
with suppress(asyncio.CancelledError):
|
||||||
|
await asyncio.wait_for(task, timeout=2)
|
||||||
|
|
||||||
|
# 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("global_value", [False, True])
|
||||||
@pytest.mark.parametrize("override", [None, False, True])
|
@pytest.mark.parametrize("override", [None, False, True])
|
||||||
@pytest.mark.parametrize("key", ["show_compaction_notices", "showCompactionNotices"])
|
@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_value
|
manager.config.channels.show_compaction_notices = global_value
|
||||||
section = {} if override is None else {key: override}
|
section = {} if override is None else {key: override}
|
||||||
channel = manager._build_channel("mock", _MockChannel, section)
|
channel = manager._build_channel("mock", _MockChannel, section)
|
||||||
assert channel.show_compaction_notices is (global_value if override is None else override)
|
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):
|
def test_global_notice_config_round_trip_and_rebuild(manager):
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"""Tests for ChannelManager delta coalescing to reduce streaming latency."""
|
"""Tests for ChannelManager delta coalescing to reduce streaming latency."""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from contextlib import suppress
|
||||||
from unittest.mock import AsyncMock
|
from unittest.mock import AsyncMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -74,8 +75,8 @@ def bus():
|
|||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def manager(config, bus):
|
def manager(config, bus, tmp_path):
|
||||||
manager = ChannelManager(config, bus)
|
manager = ChannelManager(config, bus, config_path=tmp_path / "config.json")
|
||||||
manager.channels["mock"] = manager._build_channel("mock", MockChannel, {})
|
manager.channels["mock"] = manager._build_channel("mock", MockChannel, {})
|
||||||
return manager
|
return manager
|
||||||
|
|
||||||
@@ -121,43 +122,6 @@ class TestDeltaCoalescing:
|
|||||||
assert merged.metadata == first.metadata
|
assert merged.metadata == first.metadata
|
||||||
assert pending == [second]
|
assert 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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_multiple_deltas_coalesced(self, manager, bus):
|
async def test_multiple_deltas_coalesced(self, manager, bus):
|
||||||
for text in ["Hello", " ", "world", "!"]:
|
for text in ["Hello", " ", "world", "!"]:
|
||||||
@@ -270,38 +234,49 @@ class TestDispatchOutboundWithCoalescing:
|
|||||||
"""Tests for the full _dispatch_outbound flow with coalescing."""
|
"""Tests for the full _dispatch_outbound flow with coalescing."""
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_dispatch_coalesces_and_processes_pending(self, manager, bus):
|
@pytest.mark.parametrize("end_stream", [False, True])
|
||||||
await bus.publish_outbound(_delta("A"))
|
async def test_dispatch_coalesces_and_delivers_final(self, manager, bus, end_stream):
|
||||||
await bus.publish_outbound(_delta("B"))
|
await bus.publish_outbound(_delta("A", stream_id="seg-1"))
|
||||||
await bus.publish_outbound(OutboundMessage(
|
await bus.publish_outbound(_delta("B", stream_id="seg-1"))
|
||||||
channel="mock",
|
if end_stream:
|
||||||
chat_id="chat1",
|
await bus.publish_outbound(_end(
|
||||||
content="Final",
|
"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 = []
|
||||||
|
|
||||||
pending = []
|
def record_delta(chat_id, delta, metadata, **flags):
|
||||||
processed = []
|
received.append(("delta", chat_id, delta, metadata, flags))
|
||||||
|
|
||||||
msg = pending.pop(0) if pending else await bus.consume_outbound()
|
def record_send(msg):
|
||||||
event = msg.event
|
received.append(("send", msg.channel, msg.chat_id, msg.content, msg.event))
|
||||||
if isinstance(event, StreamDeltaEvent):
|
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "chat1", "Final", None):
|
||||||
msg, extra_pending = manager._coalesce_stream_deltas(msg)
|
delivered.set()
|
||||||
pending.extend(extra_pending)
|
|
||||||
|
|
||||||
channel = manager.channels.get(msg.channel)
|
channel = manager.channels["mock"]
|
||||||
event = msg.event
|
channel._send_delta_mock.side_effect = record_delta
|
||||||
if channel and isinstance(event, StreamDeltaEvent):
|
channel._send_mock.side_effect = record_send
|
||||||
await channel.send_delta(
|
task = asyncio.create_task(manager._dispatch_outbound())
|
||||||
msg.chat_id,
|
try:
|
||||||
msg.content,
|
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||||
msg.metadata,
|
finally:
|
||||||
stream_id=event.stream_id,
|
task.cancel()
|
||||||
)
|
with suppress(asyncio.CancelledError):
|
||||||
processed.append(("delta", msg.content))
|
await asyncio.wait_for(task, timeout=2)
|
||||||
|
|
||||||
assert processed == [("delta", "AB")]
|
assert received == [
|
||||||
assert len(pending) == 1
|
("delta", "chat1", "ABC" if end_stream else "AB", {}, {
|
||||||
assert pending[0].content == "Final"
|
"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_tails
|
||||||
|
|
||||||
|
|
||||||
class TestProgressFiltering:
|
class TestProgressFiltering:
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ plugins only implement the streaming primitives.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from contextlib import suppress
|
||||||
from unittest.mock import AsyncMock
|
from unittest.mock import AsyncMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -41,6 +42,7 @@ class _MockChannel(BaseChannel):
|
|||||||
self._delta_mock = AsyncMock()
|
self._delta_mock = AsyncMock()
|
||||||
self._end_mock = AsyncMock()
|
self._end_mock = AsyncMock()
|
||||||
self._file_edit_mock = AsyncMock()
|
self._file_edit_mock = AsyncMock()
|
||||||
|
self.received = []
|
||||||
|
|
||||||
async def start(self): # pragma: no cover - not exercised
|
async def start(self): # pragma: no cover - not exercised
|
||||||
pass
|
pass
|
||||||
@@ -49,27 +51,31 @@ class _MockChannel(BaseChannel):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
async def send(self, msg):
|
async 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):
|
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):
|
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):
|
async def send_file_edit_events(self, chat_id, edits, metadata=None):
|
||||||
return await self._file_edit_mock(chat_id, edits, metadata)
|
return await self._file_edit_mock(chat_id, edits, metadata)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def manager() -> ChannelManager:
|
def manager(tmp_path) -> ChannelManager:
|
||||||
config = Config.model_validate({"channels": {"websocket": {"enabled": False}}})
|
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)
|
mgr.channels["mock"] = _MockChannel({}, mgr.bus)
|
||||||
return mgr
|
return mgr
|
||||||
|
|
||||||
|
|
||||||
def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monkeypatch):
|
def test_websocket_gateway_uses_configured_workspace_restriction(tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"nanobot.webui.workspaces.read_webui_default_access_mode",
|
"nanobot.webui.workspaces.read_webui_default_access_mode",
|
||||||
lambda: "default",
|
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"]
|
channel = mgr.channels["websocket"]
|
||||||
|
|
||||||
scope = channel.gateway.workspaces.default_scope()
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_dispatch_drops_reasoning_when_channel_opts_out(manager):
|
@pytest.mark.parametrize("show_reasoning", [False, True])
|
||||||
|
@pytest.mark.parametrize("send_progress", [False, True])
|
||||||
|
async def test_dispatch_reasoning_visibility_is_independent_of_progress(
|
||||||
|
manager, show_reasoning, send_progress,
|
||||||
|
):
|
||||||
channel = manager.channels["mock"]
|
channel = manager.channels["mock"]
|
||||||
channel.show_reasoning = False
|
channel.show_reasoning = show_reasoning
|
||||||
msg = outbound_message_for_event(
|
channel.send_progress = send_progress
|
||||||
channel="mock",
|
events = [
|
||||||
chat_id="c1",
|
ProgressEvent(content="first ", reasoning_delta=True, stream_id="r1"),
|
||||||
event=ProgressEvent(content="hidden thinking", reasoning_delta=True),
|
ProgressEvent(content="second", reasoning_delta=True, stream_id="r1"),
|
||||||
)
|
ProgressEvent(reasoning_end=True, stream_id="r1"),
|
||||||
await manager.bus.publish_outbound(msg)
|
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)
|
||||||
|
|
||||||
await _pump_one(manager)
|
final = await _dispatch_through_final(manager)
|
||||||
|
|
||||||
channel._delta_mock.assert_not_awaited()
|
expected = []
|
||||||
channel._end_mock.assert_not_awaited()
|
if show_reasoning:
|
||||||
channel._send_mock.assert_not_awaited()
|
expected.extend([
|
||||||
|
("delta", "c1", "first ", messages[0].metadata, "r1"),
|
||||||
|
("delta", "c1", "second", messages[1].metadata, "r1"),
|
||||||
@pytest.mark.asyncio
|
("end", "c1", messages[2].metadata, "r1"),
|
||||||
async def test_dispatch_delivers_reasoning_when_channel_opts_in(manager):
|
("delta", "c1", "one-shot reasoning", messages[3].metadata, "r2"),
|
||||||
channel = manager.channels["mock"]
|
("end", "c1", messages[3].metadata, "r2"),
|
||||||
channel.show_reasoning = True
|
])
|
||||||
for chunk in ("first ", "second"):
|
if send_progress:
|
||||||
await manager.bus.publish_outbound(outbound_message_for_event(
|
expected.append(("send", messages[-1]))
|
||||||
channel="mock",
|
assert channel.received == [*expected, ("send", final)]
|
||||||
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()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_dispatch_silently_drops_reasoning_for_unknown_channel(manager):
|
async 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",
|
channel="ghost",
|
||||||
chat_id="c1",
|
chat_id="c1",
|
||||||
event=ProgressEvent(content="nobody home", reasoning_delta=True),
|
event=ProgressEvent(content="nobody home", reasoning_delta=True, stream_id="ghost-r1"),
|
||||||
)
|
))
|
||||||
await manager.bus.publish_outbound(msg)
|
|
||||||
|
|
||||||
await _pump_one(manager)
|
final = await _dispatch_through_final(manager)
|
||||||
|
|
||||||
manager.channels["mock"]._delta_mock.assert_not_awaited()
|
channel = manager.channels["mock"]
|
||||||
manager.channels["mock"]._send_mock.assert_not_awaited()
|
assert channel.received == [("send", final)]
|
||||||
|
channel._delta_mock.assert_not_awaited()
|
||||||
|
channel._end_mock.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@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
|
assert await channel.send_file_edit_events("c", [{"path": "a.py"}]) is None
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
async def _dispatch_through_final(manager: ChannelManager) -> OutboundMessage:
|
||||||
async def test_reasoning_routing_does_not_consult_send_progress(manager):
|
"""A same-destination send acknowledges completion of earlier callbacks."""
|
||||||
"""`show_reasoning` is orthogonal to `send_progress` — turning off
|
final = OutboundMessage(channel="mock", chat_id="c1", content="Final")
|
||||||
progress streaming must not silence reasoning."""
|
delivered = asyncio.Event()
|
||||||
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)
|
def record_send(msg):
|
||||||
|
if (msg.channel, msg.chat_id, msg.content, msg.event) == ("mock", "c1", "Final", None):
|
||||||
|
delivered.set()
|
||||||
|
|
||||||
channel._delta_mock.assert_awaited_once()
|
manager.channels["mock"]._send_mock.side_effect = record_send
|
||||||
|
await manager.bus.publish_outbound(final)
|
||||||
|
task = asyncio.create_task(manager._dispatch_outbound())
|
||||||
async def _pump_one(manager: ChannelManager) -> None:
|
try:
|
||||||
"""Process currently queued messages through the reasoning dispatch branch."""
|
await asyncio.wait_for(delivered.wait(), timeout=2)
|
||||||
|
finally:
|
||||||
async def dispatch_one(msg: OutboundMessage) -> None:
|
task.cancel()
|
||||||
event = msg.event
|
with suppress(asyncio.CancelledError):
|
||||||
if isinstance(event, ProgressEvent) and (
|
await asyncio.wait_for(task, timeout=2)
|
||||||
event.reasoning_delta
|
assert not manager._outbound_tasks
|
||||||
or event.reasoning_end
|
assert not manager._outbound_tails
|
||||||
or event.reasoning
|
return final
|
||||||
):
|
|
||||||
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
|
|
||||||
@@ -1,67 +1,150 @@
|
|||||||
"""Executable architecture constraints for the WebSocket transport adapter."""
|
"""Behavioral delegation and executable ownership boundaries for WebSocket."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ast
|
import ast
|
||||||
|
import asyncio
|
||||||
from pathlib import Path
|
from 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 MessageBus
|
||||||
from nanobot.channels.websocket import runtime
|
from nanobot.channels.websocket import runtime
|
||||||
|
from nanobot.webui.gateway_services import build_gateway_services
|
||||||
|
|
||||||
_REPOSITORY_ROOT = Path(__file__).resolve().parents[2]
|
_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"
|
_SESSION_IDENTITY_PATH = _REPOSITORY_ROOT / "nanobot" / "webui" / "session_identity.py"
|
||||||
|
|
||||||
|
|
||||||
def _channel_method(name: str) -> ast.AsyncFunctionDef:
|
@pytest.fixture
|
||||||
tree = ast.parse(_RUNTIME_PATH.read_text(encoding="utf-8"))
|
async def channel(tmp_path, monkeypatch):
|
||||||
channel = next(
|
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
|
||||||
node
|
config = runtime.WebSocketConfig(allow_from=["client-1"], websocket_requires_token=False)
|
||||||
for node in tree.body
|
bus = MessageBus()
|
||||||
if isinstance(node, ast.ClassDef) and node.name == "WebSocketChannel"
|
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(
|
channel = runtime.WebSocketChannel(config, bus, gateway=gateway)
|
||||||
node
|
try:
|
||||||
for node in channel.body
|
yield channel
|
||||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == name
|
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)
|
||||||
|
|
||||||
def _statements_without_docstring(node: ast.AsyncFunctionDef) -> list[ast.stmt]:
|
send.assert_awaited_once_with(msg)
|
||||||
body = list(node.body)
|
hydrate.assert_not_awaited()
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def test_business_entrypoints_are_thin_transport_delegations() -> None:
|
async def test_subscribe_hydration_delegates_the_requested_chat(channel, monkeypatch):
|
||||||
for method_name in ("_dispatch_envelope", "_hydrate_after_subscribe", "send"):
|
hydrate = AsyncMock()
|
||||||
statements = _statements_without_docstring(_channel_method(method_name))
|
send = AsyncMock()
|
||||||
assert len(statements) == 1, method_name
|
monkeypatch.setattr(channel._outbound, "hydrate", hydrate)
|
||||||
assert isinstance(statements[0], ast.Expr), method_name
|
monkeypatch.setattr(channel._outbound, "send", send)
|
||||||
assert isinstance(statements[0].value, ast.Await), method_name
|
|
||||||
|
|
||||||
statements = _statements_without_docstring(_channel_method("_dispatch_http"))
|
await channel._hydrate_after_subscribe("chat-2")
|
||||||
assert len(statements) == 1
|
|
||||||
assert isinstance(statements[0], ast.Return)
|
hydrate.assert_awaited_once_with("chat-2")
|
||||||
assert isinstance(statements[0].value, ast.Await)
|
send.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
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"}
|
||||||
|
|
||||||
|
await channel._dispatch_envelope(connection, "client-1", envelope)
|
||||||
|
|
||||||
|
dispatch.assert_awaited_once_with(connection, "client-1", envelope)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("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:
|
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"):
|
for path in (_REPOSITORY_ROOT / "nanobot").rglob("*.py"):
|
||||||
if "tests" in path.parts or path == _SESSION_IDENTITY_PATH:
|
if "tests" in path.parts:
|
||||||
continue
|
continue
|
||||||
if "websocket:" in path.read_text(encoding="utf-8"):
|
lines = _session_namespace_literal_lines(path.read_text(encoding="utf-8"))
|
||||||
owners.append(path.relative_to(_REPOSITORY_ROOT).as_posix())
|
if lines:
|
||||||
assert owners == []
|
owners[path.relative_to(_REPOSITORY_ROOT).as_posix()] = lines
|
||||||
assert 'WEBUI_SESSION_STORAGE_PREFIX = "websocket:"' in _SESSION_IDENTITY_PATH.read_text(
|
assert set(owners) == {_SESSION_IDENTITY_PATH.relative_to(_REPOSITORY_ROOT).as_posix()}, owners
|
||||||
encoding="utf-8"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_runtime_exports_compatibility_protocol_helpers() -> None:
|
def test_runtime_exports_compatibility_protocol_helpers() -> None:
|
||||||
|
|||||||
@@ -2593,7 +2593,7 @@ def test_webui_missing_runtime_env_fails_before_starting_gateway(
|
|||||||
assert result.exit_code == 1
|
assert result.exit_code == 1
|
||||||
assert missing_env in result.stdout
|
assert missing_env in result.stdout
|
||||||
assert "nanobot status --config" in result.stdout
|
assert "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.stdout
|
assert "Traceback" not in result.stdout
|
||||||
assert f"${{{missing_env}}}" in config_file.read_text(encoding="utf-8")
|
assert f"${{{missing_env}}}" in config_file.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
|||||||
@@ -12,11 +12,6 @@ def test_commands_keeps_safe_file_history_import_compatible() -> None:
|
|||||||
|
|
||||||
|
|
||||||
class TestSanitizeSurrogates:
|
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):
|
def test_lone_surrogates_replaced(self):
|
||||||
result = _sanitize_surrogates("hello \udce9 world")
|
result = _sanitize_surrogates("hello \udce9 world")
|
||||||
assert "\udce9" not in result
|
assert "\udce9" not in result
|
||||||
@@ -56,11 +51,15 @@ class TestSafeFileHistory:
|
|||||||
entries = list(hist.load_history_strings())
|
entries = list(hist.load_history_strings())
|
||||||
assert entries[0] == "normal ascii text"
|
assert entries[0] == "normal ascii text"
|
||||||
|
|
||||||
def test_emoji_preserved(self, tmp_path):
|
def test_windows_surrogate_pair_round_trips_as_emoji(self, tmp_path):
|
||||||
hist = SafeFileHistory(str(tmp_path / "history"))
|
"""Raw UTF-16 console input must survive a UTF-8 history write and reload."""
|
||||||
hist.store_string("hello 🐈 nanobot")
|
history_path = tmp_path / "history"
|
||||||
entries = list(hist.load_history_strings())
|
hist = SafeFileHistory(str(history_path))
|
||||||
assert entries[0] == "hello 🐈 nanobot"
|
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):
|
def test_mixed_unicode_preserved(self, tmp_path):
|
||||||
"""CJK + emoji + latin should all pass through cleanly."""
|
"""CJK + emoji + latin should all pass through cleanly."""
|
||||||
|
|||||||
@@ -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))
|
store = _FakeStore(_FakeGit(initialized=False), dream_prompt_result=("dream prompt", 123))
|
||||||
bus = _FakeBus()
|
bus = _FakeBus()
|
||||||
calls = []
|
calls = []
|
||||||
|
progress_sentinel = "private Dream progress sentinel"
|
||||||
|
|
||||||
async def process_direct(*args, **kwargs):
|
async def process_direct(*args, **kwargs):
|
||||||
calls.append((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(
|
return OutboundMessage(
|
||||||
channel="cli",
|
channel="cli",
|
||||||
chat_id="direct",
|
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)
|
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 len(calls) == 1
|
||||||
assert callable(calls[0][1]["on_progress"])
|
|
||||||
assert calls[0][1]["runtime"] is dream_runtime
|
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.content
|
||||||
|
|
||||||
|
|
||||||
def _build_runnable_dream(
|
def _build_runnable_dream(
|
||||||
|
|||||||
@@ -92,6 +92,7 @@ async def test_model_command_lists_current_and_available_presets(tmp_path) -> No
|
|||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_model_command_switches_preset(tmp_path) -> None:
|
async def test_model_command_switches_preset(tmp_path) -> None:
|
||||||
loop = _make_loop(tmp_path)
|
loop = _make_loop(tmp_path)
|
||||||
|
assert loop.tools_config.my.allow_set is False
|
||||||
|
|
||||||
out = await cmd_model(_ctx(loop, "/model fast", args="fast"))
|
out = 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
|
assert "No API key configured for provider 'openai'." in status.content
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_model_command_registered_as_exact_and_prefix(tmp_path) -> None:
|
async def test_model_command_registered_as_exact_and_prefix(tmp_path) -> None:
|
||||||
router = CommandRouter()
|
router = CommandRouter()
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
"""Test Azure OpenAI provider (Responses API via OpenAI SDK)."""
|
"""Test Azure OpenAI provider (Responses API via OpenAI SDK)."""
|
||||||
|
|
||||||
|
import json
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import AsyncMock, MagicMock, patch
|
from unittest.mock import AsyncMock, MagicMock, call, patch
|
||||||
|
|
||||||
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
from openai import AsyncOpenAI
|
||||||
|
|
||||||
from nanobot.providers.azure_openai_provider import (
|
from nanobot.providers.azure_openai_provider import (
|
||||||
AzureOpenAIProvider,
|
AzureOpenAIProvider,
|
||||||
@@ -79,79 +82,100 @@ def _install_fake_azure_identity(monkeypatch, credential_factory):
|
|||||||
monkeypatch.setitem(sys.modules, "azure.identity.aio", aio_mod)
|
monkeypatch.setitem(sys.modules, "azure.identity.aio", aio_mod)
|
||||||
|
|
||||||
|
|
||||||
def test_init_missing_key_uses_aad_token_provider(monkeypatch):
|
@pytest.fixture
|
||||||
"""Empty api_key falls back to DefaultAzureCredential via _AzureTokenProvider."""
|
async def azure_wire_requests(monkeypatch):
|
||||||
credential_instance = MagicMock()
|
"""Inject only the HTTP transport; keep the SDK's request/auth path real."""
|
||||||
credential_factory = MagicMock(return_value=credential_instance)
|
requests: list[httpx.Request] = []
|
||||||
_install_fake_azure_identity(monkeypatch, credential_factory)
|
|
||||||
|
|
||||||
provider = AzureOpenAIProvider(
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
api_key="", api_base="https://res.openai.azure.com",
|
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
|
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http_client:
|
||||||
assert isinstance(provider._token_provider, _AzureTokenProvider)
|
def create_client(**kwargs):
|
||||||
# DefaultAzureCredential must have been instantiated exactly once
|
return AsyncOpenAI(http_client=http_client, **kwargs)
|
||||||
credential_factory.assert_called_once_with()
|
|
||||||
assert provider._token_provider._credential is credential_instance
|
monkeypatch.setattr("nanobot.providers.azure_openai_provider.AsyncOpenAI", create_client)
|
||||||
# The token provider must be wired into the OpenAI SDK as its
|
yield requests
|
||||||
# ``_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 == ""
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_aad_token_provider_wires_into_sdk_auth_headers(monkeypatch):
|
async def test_aad_token_provider_sends_rotating_bearer_tokens_on_chat_requests(
|
||||||
"""Regression guard: the token provider must be wired into the
|
monkeypatch, azure_wire_requests,
|
||||||
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)
|
|
||||||
credential_instance = MagicMock()
|
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)
|
credential_factory = MagicMock(return_value=credential_instance)
|
||||||
_install_fake_azure_identity(monkeypatch, credential_factory)
|
_install_fake_azure_identity(monkeypatch, credential_factory)
|
||||||
|
|
||||||
provider = AzureOpenAIProvider(
|
provider = AzureOpenAIProvider(
|
||||||
api_key="", api_base="https://res.openai.azure.com",
|
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 provider._client.api_key == ""
|
assert [response.content for response in responses] == ["reply 1", "reply 2"]
|
||||||
assert provider._client.auth_headers == {}
|
assert all(response.finish_reason == "stop" for response in responses)
|
||||||
|
assert len(azure_wire_requests) == 2
|
||||||
await provider._client._refresh_api_key()
|
assert [request.headers.get("Authorization") for request in azure_wire_requests] == [
|
||||||
|
"Bearer token-A", "Bearer token-B",
|
||||||
assert provider._client.api_key == "token-A"
|
]
|
||||||
assert provider._client.auth_headers == {"Authorization": "Bearer token-A"}
|
assert all(request.method == "POST" for request in azure_wire_requests)
|
||||||
credential_instance.get_token.assert_awaited_with(
|
assert all(
|
||||||
"https://cognitiveservices.azure.com/.default"
|
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]
|
||||||
# Rotated token on second refresh proves per-request delegation (no client-side caching).
|
assert [body["model"] for body in bodies] == ["gpt-4o-deployment", "gpt-4o-deployment"]
|
||||||
credential_instance.get_token = AsyncMock(
|
assert [body["input"][0]["content"][0]["text"] for body in bodies] == ["turn 1", "turn 2"]
|
||||||
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"}
|
|
||||||
credential_factory.assert_called_once_with()
|
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):
|
@pytest.mark.asyncio
|
||||||
"""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(
|
credential_factory = MagicMock(side_effect=AssertionError(
|
||||||
"DefaultAzureCredential must not be constructed when api_key is set"
|
"DefaultAzureCredential must not be constructed when api_key is set"
|
||||||
))
|
))
|
||||||
_install_fake_azure_identity(monkeypatch, credential_factory)
|
_install_fake_azure_identity(monkeypatch, credential_factory)
|
||||||
|
|
||||||
provider = AzureOpenAIProvider(
|
provider = AzureOpenAIProvider(
|
||||||
api_key="real-key", api_base="https://res.openai.azure.com",
|
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()
|
credential_factory.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -168,22 +168,6 @@ class TestBuildKwargsExtraBody:
|
|||||||
assert body.get("custom_param") == "value"
|
assert body.get("custom_param") == "value"
|
||||||
assert body["thinking"] == {"type": "enabled"}
|
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:
|
def test_guided_json_injection(self) -> None:
|
||||||
"""Real-world use case: vLLM guided decoding."""
|
"""Real-world use case: vLLM guided decoding."""
|
||||||
schema = {"type": "object", "properties": {"name": {"type": "string"}}}
|
schema = {"type": "object", "properties": {"name": {"type": "string"}}}
|
||||||
|
|||||||
@@ -12,11 +12,13 @@ from nanobot.providers import github_copilot_provider as gc
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_concurrent_token_refresh_fetches_once(monkeypatch):
|
async def test_concurrent_token_refresh_fetches_once(monkeypatch):
|
||||||
"""Two concurrent _get_copilot_access_token calls should trigger only one
|
"""A competing caller waits for the in-flight exchange and reuses its token."""
|
||||||
HTTP fetch when the token is expired, not two."""
|
|
||||||
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
|
monkeypatch.setattr(gc, "_load_github_token", lambda: SimpleNamespace(access="github-token"))
|
||||||
|
|
||||||
fetch_count = 0
|
fetch_count = 0
|
||||||
|
entered = asyncio.Event()
|
||||||
|
release = asyncio.Event()
|
||||||
|
competing_started = asyncio.Event()
|
||||||
|
|
||||||
class FakeResponse:
|
class FakeResponse:
|
||||||
def raise_for_status(self):
|
def raise_for_status(self):
|
||||||
@@ -38,82 +40,37 @@ async def test_concurrent_token_refresh_fetches_once(monkeypatch):
|
|||||||
async def get(self, url, *, headers):
|
async def get(self, url, *, headers):
|
||||||
nonlocal fetch_count
|
nonlocal fetch_count
|
||||||
fetch_count += 1
|
fetch_count += 1
|
||||||
# Simulate network latency so both coroutines overlap before the
|
entered.set()
|
||||||
# lock serializes them.
|
await release.wait()
|
||||||
await asyncio.sleep(0.05)
|
|
||||||
return FakeResponse()
|
return FakeResponse()
|
||||||
|
|
||||||
monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)
|
monkeypatch.setattr(gc.httpx, "AsyncClient", FakeAsyncClient)
|
||||||
|
|
||||||
provider = gc.GitHubCopilotProvider()
|
provider = gc.GitHubCopilotProvider()
|
||||||
# Force token expiry.
|
|
||||||
provider._copilot_access_token = None
|
|
||||||
provider._copilot_expires_at = 0.0
|
|
||||||
|
|
||||||
token_a, token_b = await asyncio.gather(
|
async def competing_call():
|
||||||
provider._get_copilot_access_token(),
|
# No suspension between this signal and entering the token path.
|
||||||
provider._get_copilot_access_token(),
|
competing_started.set()
|
||||||
)
|
return await 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}"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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 __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())
|
task_a = asyncio.create_task(provider._get_copilot_access_token())
|
||||||
await asyncio.sleep(0.02) # task A is now inside the lock, mid-fetch
|
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
|
||||||
|
|
||||||
# Task B starts while A is still in flight.
|
release.set()
|
||||||
token_b = await provider._get_copilot_access_token()
|
tokens = await asyncio.wait_for(asyncio.gather(*tasks), timeout=5)
|
||||||
token_a = await task_a
|
assert tokens == ["copilot-token", "copilot-token"]
|
||||||
|
assert fetch_count == 1
|
||||||
assert token_a == "cached-token"
|
finally:
|
||||||
assert token_b == "cached-token"
|
release.set()
|
||||||
assert fetch_count == 1
|
for task in tasks:
|
||||||
|
if not task.done():
|
||||||
|
task.cancel()
|
||||||
@pytest.mark.asyncio
|
await asyncio.gather(*tasks, return_exceptions=True)
|
||||||
async def test_copilot_token_lock_exists():
|
await provider.aclose()
|
||||||
"""Provider should have an asyncio.Lock for token refresh."""
|
|
||||||
provider = gc.GitHubCopilotProvider()
|
|
||||||
assert isinstance(provider._copilot_token_lock, asyncio.Lock)
|
|
||||||
@@ -1,8 +1,12 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
import threading
|
import threading
|
||||||
from collections.abc import Callable, Iterator
|
from collections.abc import Callable, Iterator
|
||||||
|
from contextlib import closing
|
||||||
|
from dataclasses import asdict
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -127,18 +131,30 @@ async def test_observer_receives_every_retry_attempt(stream: bool) -> None:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_observer_estimates_missing_success_usage_without_storing_content() -> None:
|
async 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] = []
|
events: list[LLMCallRecord] = []
|
||||||
provider.set_llm_call_observer(events.append)
|
provider.set_llm_call_observer(events.append)
|
||||||
|
|
||||||
response = await provider.chat_with_retry(
|
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 None
|
assert response.usage is not None
|
||||||
assert response.usage.source == "estimated"
|
assert 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 > 0
|
||||||
assert events[0].usage == response.usage
|
assert 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
|
@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(
|
async def test_gateway_usage_observer_records_missing_usage_and_retry(
|
||||||
monkeypatch, tmp_path, stream: bool,
|
monkeypatch, tmp_path, stream: bool,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
prompt = "gateway-prompt-canary-f6d5a4"
|
||||||
|
reply = "gateway-response-canary-27be91"
|
||||||
|
error = "gateway-error-canary-64a8cd"
|
||||||
store = LLMUsageStore(tmp_path / "usage.sqlite3")
|
store = LLMUsageStore(tmp_path / "usage.sqlite3")
|
||||||
monkeypatch.setattr("nanobot.llm_usage.service.get_llm_usage_store", lambda: store)
|
monkeypatch.setattr("nanobot.llm_usage.service.get_llm_usage_store", lambda: store)
|
||||||
provider = _SequenceProvider(iter([
|
provider = _SequenceProvider(iter([
|
||||||
LLMResponse(content="temporary failure", finish_reason="error", error_kind="timeout"),
|
LLMResponse(content=error, finish_reason="error", error_kind="timeout"),
|
||||||
LLMResponse(content="hello"),
|
LLMResponse(content=reply),
|
||||||
]))
|
]))
|
||||||
provider.set_llm_call_observer(record_llm_call)
|
provider.set_llm_call_observer(record_llm_call)
|
||||||
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
|
call = provider.chat_stream_with_retry if stream else provider.chat_with_retry
|
||||||
try:
|
try:
|
||||||
with llm_usage_source("api"):
|
with llm_usage_source("api"):
|
||||||
response = await call(messages=[{"role": "user", "content": "hello"}])
|
response = await call(messages=[{"role": "user", "content": prompt}])
|
||||||
assert response.content == "hello"
|
assert response.content == reply
|
||||||
assert response.usage is not None and response.usage.source == "estimated"
|
assert 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 > 0
|
||||||
assert provider.calls == 2
|
assert 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) == 2
|
||||||
assert [record["finish_reason"] for record in records] == ["error", "stop"]
|
assert [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["source"] == "api" for record in records)
|
||||||
assert all(record["stream"] == int(stream) for record in records)
|
assert all(record["stream"] == int(stream) for record in records)
|
||||||
assert records[0]["total_tokens"] is None
|
assert records[0]["total_tokens"] is None
|
||||||
assert records[1]["total_tokens"] == response.usage.total_tokens
|
assert 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 serialized
|
||||||
finally:
|
finally:
|
||||||
store.close()
|
store.close()
|
||||||
|
|
||||||
|
|||||||
@@ -88,33 +88,19 @@ async def test_codex_provider_reuses_tls_context_for_concurrent_requests(monkeyp
|
|||||||
assert request_contexts == [context, context, context]
|
assert request_contexts == [context, context, context]
|
||||||
|
|
||||||
|
|
||||||
class _WarningCaptureLogger:
|
@pytest.fixture
|
||||||
def __init__(self) -> None:
|
def codex_warning_log(monkeypatch):
|
||||||
self.calls: list[tuple[str, tuple[Any, ...]]] = []
|
monkeypatch.delenv("LANGFUSE_SECRET_KEY", raising=False)
|
||||||
|
sink = io.StringIO()
|
||||||
def warning(self, *args: Any, **kwargs: Any) -> None:
|
logger.enable("nanobot")
|
||||||
self.calls.append((args[0], args[1:]))
|
handler_id = logger.add(
|
||||||
|
sink, format="{message}", level="WARNING",
|
||||||
def exception(self, message: str, *args: Any, **kwargs: Any) -> None:
|
filter="nanobot.providers.openai_codex_provider", backtrace=True, diagnose=True,
|
||||||
raise AssertionError("Codex diagnostics must not log exception tracebacks")
|
)
|
||||||
|
try:
|
||||||
|
yield sink
|
||||||
def _capture_codex_warnings(monkeypatch: pytest.MonkeyPatch) -> _WarningCaptureLogger:
|
finally:
|
||||||
capture = _WarningCaptureLogger()
|
logger.remove(handler_id)
|
||||||
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 test_codex_http_friendly_error_omits_raw_body() -> None:
|
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.asyncio
|
||||||
@pytest.mark.parametrize("failed_stage", ["codex_compaction", "codex_request"])
|
@pytest.mark.parametrize("failed_stage", ["codex_compaction", "codex_request"])
|
||||||
async def test_codex_diagnostics_distinguish_compaction_from_following_request(
|
async def test_codex_diagnostics_distinguish_compaction_from_following_request(
|
||||||
monkeypatch, failed_stage,
|
monkeypatch, codex_warning_log, failed_stage,
|
||||||
) -> None:
|
) -> None:
|
||||||
_mock_codex_token(monkeypatch)
|
_mock_codex_token(monkeypatch)
|
||||||
capture = _capture_codex_warnings(monkeypatch)
|
|
||||||
state_provider = "openai_codex:https://chatgpt.com/backend-api/codex/responses"
|
state_provider = "openai_codex:https://chatgpt.com/backend-api/codex/responses"
|
||||||
state = build_responses_state(
|
state = build_responses_state(
|
||||||
provider=state_provider, model="gpt-5.6-sol",
|
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"
|
assert response.finish_reason == "error"
|
||||||
template, args = capture.calls[-1]
|
logs = codex_warning_log.getvalue().splitlines()
|
||||||
log = template.format(*args)
|
assert len(logs) == 1
|
||||||
|
log = logs[0]
|
||||||
assert f"stage={failed_stage}" in log
|
assert f"stage={failed_stage}" in log
|
||||||
assert f"compaction_applied={failed_stage == 'codex_request'}" in log
|
assert f"compaction_applied={failed_stage == 'codex_request'}" in log
|
||||||
assert "replayed=True" in log
|
assert "replayed=True" in log
|
||||||
assert "reasoning_effort=low" in log
|
assert "reasoning_effort=low" in log
|
||||||
assert "error_param=input[1].type" in log
|
assert "error_param=input[1].type" in log
|
||||||
|
assert "request_id=req-compaction-test" in log
|
||||||
assert "PRIVATE STATE" not in log
|
assert "PRIVATE STATE" not in log
|
||||||
|
assert "Traceback" not in log
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -623,47 +611,38 @@ async def test_codex_provider_passes_proxy_to_oauth_and_response_request(monkeyp
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch) -> None:
|
async def test_codex_timeout_error_writes_diagnostic_log(monkeypatch, codex_warning_log) -> None:
|
||||||
log_capture = _capture_codex_warnings(monkeypatch)
|
|
||||||
_mock_codex_token(monkeypatch)
|
_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"] == prompt
|
||||||
raise httpx.ReadTimeout("")
|
raise httpx.ReadTimeout("")
|
||||||
|
|
||||||
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
|
monkeypatch.setattr("nanobot.providers.openai_codex_provider._request_codex", fake_request)
|
||||||
|
|
||||||
provider = OpenAICodexProvider()
|
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 == (
|
assert response.content == (
|
||||||
"Error calling Codex (ReadTimeout): timed out waiting for response"
|
"Error calling Codex (ReadTimeout): timed out waiting for response"
|
||||||
)
|
)
|
||||||
assert log_capture.calls == [
|
logs = codex_warning_log.getvalue().splitlines()
|
||||||
(
|
assert len(logs) == 1
|
||||||
"Codex API request failed: stage={} type={} kind={} retryable={} status={} "
|
log = logs[0]
|
||||||
"error_type={} error_code={} retry_after={} summary={} "
|
for field in (
|
||||||
"model={} reasoning_effort={} replayed={} compaction_applied={} "
|
"Codex API request failed", "stage=codex_request", "type=ReadTimeout",
|
||||||
"error_param={} error_message={} request_id={}",
|
"kind=timeout", "retryable=True", "status=None", "error_type=None",
|
||||||
(
|
"error_code=None", "retry_after=None", "summary=ReadTimeout timeout",
|
||||||
"codex_request",
|
"model=gpt-5.6-sol", "reasoning_effort=high", "replayed=False",
|
||||||
"ReadTimeout",
|
"compaction_applied=False", "error_param=None", "error_message=None", "request_id=None",
|
||||||
"timeout",
|
):
|
||||||
True,
|
assert field in log
|
||||||
None,
|
assert prompt not in log
|
||||||
None,
|
assert "Traceback" not in log
|
||||||
None,
|
|
||||||
None,
|
|
||||||
"ReadTimeout timeout",
|
|
||||||
"gpt-5.6-sol",
|
|
||||||
None,
|
|
||||||
False,
|
|
||||||
False,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -751,50 +730,60 @@ async def test_codex_http_error_preserves_status_and_retry_after(monkeypatch) ->
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch) -> None:
|
async def test_codex_http_diagnostic_log_omits_raw_body(monkeypatch, codex_warning_log) -> None:
|
||||||
log_capture = _capture_codex_warnings(monkeypatch)
|
|
||||||
_mock_codex_token(monkeypatch)
|
_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):
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
raise _CodexHTTPError(
|
requests.append(request)
|
||||||
_friendly_error(500, "raw upstream body with PRIVATE PROMPT MUST NOT APPEAR"),
|
assert prompt.encode() in request.content
|
||||||
status_code=500,
|
return httpx.Response(500, headers={
|
||||||
error_type="server_error",
|
"retry-after": "2.5", "x-request-id": "req-http-diagnostic",
|
||||||
error_code="overloaded",
|
}, 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()
|
provider = OpenAICodexProvider()
|
||||||
response = await provider.chat([{"role": "user", "content": "hello"}])
|
try:
|
||||||
|
response = await provider.chat(
|
||||||
assert response.content == "Error calling Codex (CodexHTTPError): HTTP 500: Codex API request failed"
|
[{"role": "user", "content": prompt}],
|
||||||
assert log_capture.calls == [
|
model="openai-codex/gpt-5.6-sol", reasoning_effort="high",
|
||||||
(
|
|
||||||
"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,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
]
|
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 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.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -62,17 +62,18 @@ class TestSanitizeSurrogatesDeep:
|
|||||||
"role": "user",
|
"role": "user",
|
||||||
"content": [
|
"content": [
|
||||||
{"type": "text", "text": "hello \ud83e world"},
|
{"type": "text", "text": "hello \ud83e world"},
|
||||||
{"type": "text", "text": "normal"},
|
{"type": "text", "text": "normal 🤖"},
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
cleaned = sanitize_surrogates_deep(dirty)
|
cleaned = sanitize_surrogates_deep(dirty)
|
||||||
assert cleaned is not dirty # rebuilt
|
assert cleaned is not dirty # rebuilt
|
||||||
first = cleaned["content"][0]["text"]
|
first = cleaned["content"][0]["text"]
|
||||||
assert "\ud83e" not in first
|
assert "\ud83e" not in first
|
||||||
|
assert cleaned["content"][1]["text"] == "normal 🤖"
|
||||||
# Full payload must be UTF-8 encodable.
|
# Full payload must be UTF-8 encodable.
|
||||||
import json
|
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):
|
def test_paired_surrogates_in_list_collapse_to_emoji(self):
|
||||||
dirty = ["a", "b \ud83e\udd16", "c"]
|
dirty = ["a", "b \ud83e\udd16", "c"]
|
||||||
@@ -150,13 +151,16 @@ class TestProviderSanitizeEmptyContent:
|
|||||||
{
|
{
|
||||||
"role": "assistant",
|
"role": "assistant",
|
||||||
"content": [
|
"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)
|
cleaned = LLMProvider._sanitize_empty_content(messages)
|
||||||
# This is the operation that previously raised UnicodeEncodeError.
|
# 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:
|
class TestBackwardCompatReExport:
|
||||||
|
|||||||
@@ -418,38 +418,6 @@ def test_resolver_keeps_enabled_and_limits_on_effective_config() -> None:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_openai_does_not_retry_on_auth_error(audio_file: Path) -> None:
|
async 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."""
|
"""401 is the user's misconfiguration — retrying wastes time and rate-limit quota."""
|
||||||
|
|||||||
@@ -22,6 +22,15 @@ from nanobot.webui import session_list_index, transcript
|
|||||||
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
|
from nanobot.webui.recovery import RecoveryActionError, RecoveryCoordinator
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(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:
|
def _persist(manager: SessionManager, session: Session) -> None:
|
||||||
session.metadata["webui"] = True
|
session.metadata["webui"] = True
|
||||||
manager.save(session)
|
manager.save(session)
|
||||||
@@ -732,26 +741,59 @@ async def test_scan_failure_is_visible_instead_of_aborting_other_sessions(
|
|||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
) -> None:
|
||||||
coordinator, bus, sessions = _coordinator(tmp_path)
|
coordinator, bus, sessions = _coordinator(tmp_path)
|
||||||
session = sessions.get_or_create("websocket:chat")
|
keys = {"websocket:first", "websocket:second"}
|
||||||
session.metadata[PENDING_USER_TURN_KEY] = True
|
for key in sorted(keys):
|
||||||
_persist(sessions, session)
|
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(*_args: object, **_kwargs: object) -> None:
|
async def fail_first(self, session: Session, chat_id: str) -> None:
|
||||||
raise RuntimeError("boom")
|
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)
|
monkeypatch.setattr(RecoveryCoordinator, "_recover_session", fail_first)
|
||||||
await coordinator.scan()
|
try:
|
||||||
|
await coordinator.scan()
|
||||||
|
|
||||||
state = sessions.get_or_create("websocket:chat").metadata[RECOVERY_METADATA_KEY]
|
assert len(attempted) == 2
|
||||||
assert state["status"] == "failed"
|
assert {key for key, _ in attempted} == keys
|
||||||
assert state["can_continue"] is False
|
failed_key, failed_chat = attempted[0]
|
||||||
assert isinstance(bus.outbound.get_nowait().event, RecoveryStateEvent)
|
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"):
|
with pytest.raises(RecoveryActionError, match="context is unavailable"):
|
||||||
await coordinator.handle_action(
|
await coordinator.handle_action(
|
||||||
"continue",
|
"continue",
|
||||||
{"chat_id": "chat", "recovery_id": state["recovery_id"]},
|
{"chat_id": failed_chat, "recovery_id": state["recovery_id"]},
|
||||||
)
|
)
|
||||||
|
finally:
|
||||||
|
await sessions.state.aclose()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -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):
|
async def test_checkpoint_does_not_rewrite_messages(tmp_path):
|
||||||
manager = SessionManager(tmp_path)
|
manager = SessionManager(tmp_path)
|
||||||
state = manager.state
|
state = manager.state
|
||||||
draft = await state.get("chat:a")
|
try:
|
||||||
draft.add_message("user", "hello")
|
draft = await state.import_messages("chat:a", [
|
||||||
await state.prepare_input(draft)
|
{"role": "user", "content": "earlier question"},
|
||||||
path = manager.sessions_dir / "sessions.sqlite3"
|
{"role": "assistant", "content": "earlier answer"},
|
||||||
with sqlite3.connect(path) as db:
|
])
|
||||||
db.execute("CREATE TRIGGER prohibit_rewrite BEFORE UPDATE ON messages BEGIN SELECT RAISE(ABORT, 'rewritten'); END")
|
draft.add_message("user", "hello")
|
||||||
await state.checkpoint_view(draft, {"step": 1})
|
await state.prepare_input(draft)
|
||||||
assert (await state.get(draft.key)).metadata["runtime_checkpoint"] == {"step": 1}
|
accepted = manager.read_session_snapshot(draft.key).messages
|
||||||
await state.aclose()
|
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):
|
async def test_database_lock_does_not_block_event_loop(tmp_path):
|
||||||
|
|||||||
@@ -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():
|
def test_save_skip_unchanged_for_standalone_current_message():
|
||||||
# [system, history user, current user] with the current user already saved.
|
# [system, history user, current user] with the current user already saved.
|
||||||
assert _save_skip_for_turn(
|
assert _save_skip_for_turn(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
|
from pathlib import Path
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
import pytest
|
import 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.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||||
@pytest.mark.asyncio
|
@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."""
|
"""Multipart upload with multiple files saves all and passes paths."""
|
||||||
import os
|
import aiohttp
|
||||||
original_cwd = os.getcwd()
|
|
||||||
os.chdir(tmp_path)
|
|
||||||
|
|
||||||
try:
|
media_dir = tmp_path / "media"
|
||||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
media_dir.mkdir()
|
||||||
client = await aiohttp_client(app)
|
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
|
files = [("first.txt", b"first file content"), ("second.bin", b"\x00second file\xff")]
|
||||||
# This test verifies the basic flow
|
data = aiohttp.FormData()
|
||||||
file_data = b"test content"
|
data.add_field("message", "analyze both files")
|
||||||
data = BytesIO(file_data)
|
for filename, payload in files:
|
||||||
|
data.add_field("files", payload, filename=filename, content_type="application/octet-stream")
|
||||||
|
|
||||||
resp = await client.post(
|
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)
|
||||||
"/v1/chat/completions",
|
|
||||||
headers=AUTH_HEADERS,
|
assert resp.status == 200
|
||||||
data={"message": "analyze", "files": data},
|
mock_agent.process_direct.assert_called_once()
|
||||||
)
|
mock_agent.process_direct.assert_awaited_once()
|
||||||
assert resp.status == 200
|
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||||
finally:
|
assert call_kwargs["content"] == "analyze both files"
|
||||||
os.chdir(original_cwd)
|
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")
|
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||||
|
|||||||
@@ -243,35 +243,6 @@ async def test_stream_sse_chunk_ids_are_consistent(aiohttp_client) -> None:
|
|||||||
assert chunk_ids.pop().startswith("chatcmpl-")
|
assert chunk_ids.pop().startswith("chatcmpl-")
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_stream_segment_end_does_not_close_sse(aiohttp_client) -> None:
|
async def test_stream_segment_end_does_not_close_sse(aiohttp_client) -> None:
|
||||||
|
|||||||
+24
-12
@@ -2,21 +2,39 @@
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "$(dirname "$0")/.." || exit 1
|
cd "$(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 EXIT
|
||||||
|
|
||||||
echo "=== Building Docker image ==="
|
echo "=== Building Docker image ==="
|
||||||
docker build -t "$IMAGE_NAME" .
|
docker build -t "$IMAGE_NAME" .
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Running 'nanobot onboard' ==="
|
echo "=== Running 'nanobot onboard' ==="
|
||||||
docker run --name nanobot-test-run "$IMAGE_NAME" onboard
|
docker run --name "$CONTAINER_NAME" "$IMAGE_NAME" onboard
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Running 'nanobot status' ==="
|
echo "=== Running 'nanobot status' ==="
|
||||||
STATUS_OUTPUT=$(docker commit nanobot-test-run nanobot-test-onboarded > /dev/null && \
|
docker commit "$CONTAINER_NAME" "$ONBOARDED_IMAGE" > /dev/null
|
||||||
docker run --rm nanobot-test-onboarded status 2>&1) || true
|
if STATUS_OUTPUT=$(docker run --rm "$ONBOARDED_IMAGE" status 2>&1); then
|
||||||
|
echo "$STATUS_OUTPUT"
|
||||||
echo "$STATUS_OUTPUT"
|
else
|
||||||
|
result=$?
|
||||||
|
echo "$STATUS_OUTPUT"
|
||||||
|
exit "$result"
|
||||||
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Validating output ==="
|
echo "=== Validating output ==="
|
||||||
@@ -47,10 +65,4 @@ else
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 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 || true
|
|
||||||
echo "Done."
|
echo "Done."
|
||||||
@@ -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")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
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}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("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])
|
||||||
@@ -240,19 +240,6 @@ async def test_no_user_message_returns_400(aiohttp_client, app) -> None:
|
|||||||
assert resp.status == 400
|
assert resp.status == 400
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_model_mismatch_returns_400() -> None:
|
async def test_model_mismatch_returns_400() -> None:
|
||||||
request = MagicMock()
|
request = MagicMock()
|
||||||
|
|||||||
@@ -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
|
|
||||||
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import 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
|
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 = tmp_path / "first.txt"
|
||||||
first.write_text("before\n")
|
first.write_text("before\n")
|
||||||
tool = ApplyPatchTool(workspace=tmp_path)
|
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 result
|
assert "file to update does not exist: missing.txt" in result
|
||||||
assert first.read_text() == "before\n"
|
assert first.read_text() == "before\n"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("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_original
|
||||||
@@ -136,7 +136,7 @@ class TestEditIpynbFiles:
|
|||||||
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
|
new_text='"cells": [{"cell_type": "markdown", "source": "hi"}]',
|
||||||
)
|
)
|
||||||
assert "Patch applied:" in result
|
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"}]}'
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -1,22 +1,61 @@
|
|||||||
"""Tests for exec tool environment isolation."""
|
"""Tests for exec tool environment isolation."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import shlex
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from nanobot.agent.tools.exec_session import ExecSessionManager
|
||||||
from nanobot.agent.tools.shell import ExecTool
|
from nanobot.agent.tools.shell import ExecTool
|
||||||
|
|
||||||
_UNIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="Unix shell commands")
|
_UNIX_ONLY = pytest.mark.skipif(sys.platform == "win32", reason="Unix shell commands")
|
||||||
|
|
||||||
|
|
||||||
@_UNIX_ONLY
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_exec_does_not_leak_parent_env(monkeypatch):
|
@pytest.mark.parametrize(
|
||||||
"""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",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"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")
|
monkeypatch.setenv("NANOBOT_SECRET_TOKEN", "super-secret-value")
|
||||||
tool = ExecTool()
|
monkeypatch.delenv("NONEXISTENT_VAR_12345", raising=False)
|
||||||
result = await tool.execute(command="printenv NANOBOT_SECRET_TOKEN")
|
marker = "ENV_PROBE_COMPLETE "
|
||||||
assert "super-secret-value" not in result
|
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
|
@pytest.mark.asyncio
|
||||||
@@ -67,37 +106,6 @@ async def test_exec_path_prepend_takes_lookup_precedence(tmp_path):
|
|||||||
assert "fallback" not in result
|
assert "fallback" not in result
|
||||||
|
|
||||||
|
|
||||||
@_UNIX_ONLY
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
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 ------------------------------------
|
# --- path_append injection prevention ------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -149,22 +149,37 @@ def test_exec_returns_completed_session_output_when_yield_time_ms_is_used(tmp_pa
|
|||||||
|
|
||||||
|
|
||||||
def test_exec_session_yield_returns_when_process_finishes_early(tmp_path):
|
def test_exec_session_yield_returns_when_process_finishes_early(tmp_path):
|
||||||
async def run() -> tuple[str, str, float]:
|
async def run() -> str:
|
||||||
manager = ExecSessionManager()
|
manager = ExecSessionManager()
|
||||||
tool = ExecTool(working_dir=str(tmp_path), timeout=5, session_manager=manager)
|
tool = ExecTool(working_dir=str(tmp_path), timeout=20, session_manager=manager)
|
||||||
stdin_tool = ExecSessionTool(manager=manager)
|
ready, release = tmp_path / "ready", tmp_path / "release"
|
||||||
command = _python_command("import time; time.sleep(0.1); print('done')")
|
command = _python_command(
|
||||||
started = time.monotonic()
|
"from pathlib import Path\nimport time\n"
|
||||||
initial = await tool.execute(command=command, yield_time_ms=1200)
|
"Path('ready').write_text('ready')\n"
|
||||||
result, final = await _poll_if_running(initial, stdin_tool)
|
"while not Path('release').exists(): time.sleep(0.01)\n"
|
||||||
return result, final, time.monotonic() - started
|
"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 "done" in result
|
||||||
assert "Exit code: 0" in final
|
assert "Exit code: 0" in result
|
||||||
assert "session_id:" not in final
|
assert "session_id:" not in result
|
||||||
assert elapsed < 4.0
|
|
||||||
|
|
||||||
|
|
||||||
def test_bounded_output_buffer_keeps_head_tail_and_exact_drop_count():
|
def test_bounded_output_buffer_keeps_head_tail_and_exact_drop_count():
|
||||||
|
|||||||
@@ -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"
|
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):
|
def test_edit_file_multiple_match_hint_mentions_occurrence(tmp_path):
|
||||||
target = tmp_path / "duplicate.txt"
|
target = tmp_path / "duplicate.txt"
|
||||||
target.write_text("same\nsame\n")
|
target.write_text("same\nsame\n")
|
||||||
|
|||||||
@@ -50,14 +50,17 @@ async def test_probe_returns_true_for_open_port(tmp_path):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_probe_returns_false_for_closed_port():
|
@pytest.mark.parametrize(
|
||||||
"""Port 19999 is almost certainly not listening."""
|
"url, expected_port",
|
||||||
assert await _probe_http_url("http://127.0.0.1:19999/mcp") is False
|
[
|
||||||
|
("http://unreachable-host.test/mcp", 80),
|
||||||
|
("http://unreachable-host.test:19999/mcp", 19999),
|
||||||
@pytest.mark.asyncio
|
],
|
||||||
async def test_probe_uses_default_port_for_http(monkeypatch: pytest.MonkeyPatch):
|
)
|
||||||
"""When no port is present, probe the validated address on port 80."""
|
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]] = []
|
attempts: list[tuple[str, int]] = []
|
||||||
|
|
||||||
monkeypatch.setattr(
|
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)
|
monkeypatch.setattr("nanobot.agent.tools.mcp.asyncio.open_connection", _open_connection)
|
||||||
|
|
||||||
assert await _probe_http_url("http://unreachable-host.test/mcp") is False
|
assert await _probe_http_url(url) is False
|
||||||
assert attempts == [("93.184.216.34", 80)]
|
assert attempts == [("93.184.216.34", expected_port)]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@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):
|
def _resolver(hostname, port, family=0, type_=0):
|
||||||
return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("127.0.0.1", 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
|
assert await _probe_http_url("http://example.com:8765/mcp") is False
|
||||||
|
open_connection.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -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"
|
||||||
|
]
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import tomllib
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from nanobot.webui.build import (
|
from nanobot.webui.build import (
|
||||||
@@ -88,13 +87,6 @@ def test_shared_notifications_make_existing_bundle_stale(tmp_path: Path) -> None
|
|||||||
assert status.newest_source == shared
|
assert status.newest_source == shared
|
||||||
|
|
||||||
|
|
||||||
def test_channel_owned_ui_sources_are_included_in_distributions() -> None:
|
|
||||||
project_root = Path(__file__).resolve().parents[2]
|
|
||||||
pyproject = tomllib.loads((project_root / "pyproject.toml").read_text(encoding="utf-8"))
|
|
||||||
|
|
||||||
assert "nanobot/channels/*/webui/**/*" in pyproject["tool"]["hatch"]["build"]["include"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_inspect_webui_bundle_accepts_fresh_dist(tmp_path: Path) -> None:
|
def test_inspect_webui_bundle_accepts_fresh_dist(tmp_path: Path) -> None:
|
||||||
source = tmp_path / "webui"
|
source = tmp_path / "webui"
|
||||||
dist = tmp_path / "nanobot" / "web" / "dist"
|
dist = tmp_path / "nanobot" / "web" / "dist"
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ def test_json_presets_reject_invalid_configuration(preset_data: dict, invalid_pa
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("target", ["wheel", "sdist"])
|
@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]
|
repository = Path(__file__).resolve().parents[2]
|
||||||
for name in ("pyproject.toml", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md"):
|
for name in ("pyproject.toml", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md"):
|
||||||
shutil.copyfile(repository / name, tmp_path / name)
|
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")
|
(tmp_path / "nanobot/__init__.py").write_text("", encoding="utf-8")
|
||||||
(package / "__init__.py").write_text("", encoding="utf-8")
|
(package / "__init__.py").write_text("", encoding="utf-8")
|
||||||
resource = "nanobot/webui/mcp_presets.json"
|
resource = "nanobot/webui/mcp_presets.json"
|
||||||
expected = (repository / resource).read_bytes()
|
resources = {
|
||||||
(tmp_path / resource).write_bytes(expected)
|
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(
|
result = subprocess.run(
|
||||||
[sys.executable, "-c", f"import hatchling.build; hatchling.build.build_{target}('dist')"],
|
[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":
|
if target == "wheel":
|
||||||
with ZipFile(next((tmp_path / "dist").glob("*.whl"))) as 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) == content
|
||||||
else:
|
else:
|
||||||
with tarfile.open(next((tmp_path / "dist").glob("*.tar.gz"))) as sdist:
|
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}"))
|
for name, content in resources.items():
|
||||||
bundled = sdist.extractfile(member)
|
member = next((member for member in sdist.getnames() if member.endswith(f"/{name}")), None)
|
||||||
assert bundled is not None
|
assert member is not None, f"Missing bundled resource: {name}"
|
||||||
with bundled:
|
bundled = sdist.extractfile(member)
|
||||||
assert bundled.read() == expected
|
assert bundled is not None
|
||||||
|
with bundled:
|
||||||
|
assert bundled.read() == content
|
||||||
@@ -237,16 +237,26 @@ def test_webui_session_list_surfaces_pending_recovery_state(tmp_path: Path) -> N
|
|||||||
|
|
||||||
|
|
||||||
def test_webui_session_index_uses_unique_temp_file(tmp_path: Path) -> None:
|
def 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)
|
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 = 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_bytes
|
||||||
assert not list(manager.sessions_dir.glob(".webui_session_index.json.*.tmp"))
|
assert not list(manager.sessions_dir.glob(".webui_session_index.json.*.tmp"))
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2725,15 +2725,6 @@ def test_create_model_configuration_accepts_azure_openai_aad_mode(
|
|||||||
assert saved.model_presets["azure-aad"].model == "my-deployment"
|
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"])
|
@pytest.mark.parametrize("protocol", ["chat_completions", "responses", "anthropic_messages"])
|
||||||
def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypatch, protocol):
|
def test_custom_connection_api_create_edit_and_preset_ceiling(tmp_path, monkeypatch, protocol):
|
||||||
config_path = tmp_path / "config.json"
|
config_path = tmp_path / "config.json"
|
||||||
|
|||||||
@@ -649,13 +649,35 @@ async def test_reverting_runtime_switch_clears_restart_but_preserves_other_chang
|
|||||||
|
|
||||||
async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path):
|
async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path):
|
||||||
router = _router(config_path=tmp_path / "config.json")
|
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.timeout
|
||||||
path = "/api/settings/web-search/update"
|
path = "/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 == 200
|
||||||
assert json.loads(first.body)["restart_required_sections"] == ["browser"]
|
assert 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 == 200
|
||||||
assert json.loads(restored.body)["restart_required_sections"] == ["runtime"]
|
assert 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])
|
@pytest.mark.parametrize("enabled", [False, True])
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import re
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -11,7 +10,6 @@ from nanobot.config.schema import Config
|
|||||||
from nanobot.webui.settings_api import update_runtime_config_settings
|
from nanobot.webui.settings_api import update_runtime_config_settings
|
||||||
from nanobot.webui.settings_contracts import WebUISettingsError
|
from nanobot.webui.settings_contracts import WebUISettingsError
|
||||||
from nanobot.webui.settings_runtime import (
|
from nanobot.webui.settings_runtime import (
|
||||||
RUNTIME_CONFIG_PATHS,
|
|
||||||
runtime_config_payload,
|
runtime_config_payload,
|
||||||
update_runtime_config,
|
update_runtime_config,
|
||||||
)
|
)
|
||||||
@@ -166,13 +164,11 @@ def test_api_changes_require_explicit_restart(tmp_path):
|
|||||||
assert payload["requires_restart"]
|
assert payload["requires_restart"]
|
||||||
|
|
||||||
|
|
||||||
def test_every_exposed_runtime_setting_has_a_frontend_use():
|
def test_runtime_payload_matches_shared_catalogue_contract():
|
||||||
fields = Path(__file__).parents[2] / "webui/src/components/settings/system/runtime-config-fields.ts"
|
fixture = Path(__file__).with_name("fixtures") / "runtime-config-keys.json"
|
||||||
paths = re.findall(r'group: "[^"]+", path: "([^"]+)"', fields.read_text(encoding="utf-8"))
|
paths = json.loads(fixture.read_text(encoding="utf-8"))
|
||||||
assert len(paths) == len(set(paths))
|
assert len(paths) == len(set(paths))
|
||||||
# The CLI enable flag controls visibility of its advanced fields, without an editor.
|
assert set(runtime_config_payload(Config())) == set(paths)
|
||||||
visibility_only = {"tools.cli_apps.enable"}
|
|
||||||
assert set(paths) | visibility_only == set(RUNTIME_CONFIG_PATHS)
|
|
||||||
|
|
||||||
|
|
||||||
def test_disabling_memory_consolidation_preserves_other_memory_settings():
|
def test_disabling_memory_consolidation_preserves_other_memory_settings():
|
||||||
|
|||||||
@@ -809,8 +809,6 @@ describe("NanobotTui layout and themes", () => {
|
|||||||
const ui = app as unknown as {
|
const ui = app as unknown as {
|
||||||
composer: TextareaRenderable
|
composer: TextareaRenderable
|
||||||
status: TextRenderable
|
status: TextRenderable
|
||||||
shimmerFrame: number
|
|
||||||
renderActiveStatus(): void
|
|
||||||
}
|
}
|
||||||
expect(ui.composer.textColor.intent).toBe("default")
|
expect(ui.composer.textColor.intent).toBe("default")
|
||||||
expect(ui.composer.backgroundColor.intent).toBe("default")
|
expect(ui.composer.backgroundColor.intent).toBe("default")
|
||||||
@@ -832,8 +830,7 @@ describe("NanobotTui layout and themes", () => {
|
|||||||
.slice(0, "Thinking".length)
|
.slice(0, "Thinking".length)
|
||||||
.map((chunk) => chunk.attributes ?? 0)
|
.map((chunk) => chunk.attributes ?? 0)
|
||||||
const firstFrame = terminalFrame()
|
const firstFrame = terminalFrame()
|
||||||
ui.shimmerFrame += 1
|
await waitUntil(() => JSON.stringify(terminalFrame()) !== JSON.stringify(firstFrame), 2_000)
|
||||||
ui.renderActiveStatus()
|
|
||||||
const secondFrame = terminalFrame()
|
const secondFrame = terminalFrame()
|
||||||
expect(firstFrame).toContain(TextAttributes.BOLD)
|
expect(firstFrame).toContain(TextAttributes.BOLD)
|
||||||
expect(secondFrame).not.toEqual(firstFrame)
|
expect(secondFrame).not.toEqual(firstFrame)
|
||||||
|
|||||||
@@ -189,11 +189,10 @@ describe("NanobotTui transcript", () => {
|
|||||||
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
|
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
|
||||||
app.accept({ event: "attached", chat_id: "chat" })
|
app.accept({ event: "attached", chat_id: "chat" })
|
||||||
app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })
|
app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })
|
||||||
await Bun.sleep(130)
|
await setup.flush()
|
||||||
await setup.renderOnce()
|
|
||||||
let frame = setup.captureCharFrame()
|
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.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)
|
||||||
expect(frame).not.toContain("hidden reasoning")
|
expect(frame).not.toContain("hidden reasoning")
|
||||||
const ui = app as unknown as {
|
const ui = app as unknown as {
|
||||||
@@ -205,7 +204,12 @@ describe("NanobotTui transcript", () => {
|
|||||||
composerFrame: BoxRenderable
|
composerFrame: BoxRenderable
|
||||||
}
|
}
|
||||||
const status = ui.status
|
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.composer.placeholder).toBe("Enter send now Tab send next")
|
||||||
expect(ui.composerFrame.height).toBe(3)
|
expect(ui.composerFrame.height).toBe(3)
|
||||||
const shimmerColors = new Set(
|
const shimmerColors = new Set(
|
||||||
@@ -223,11 +227,11 @@ describe("NanobotTui transcript", () => {
|
|||||||
kind: "tool_hint",
|
kind: "tool_hint",
|
||||||
tool_events: [{ phase: "start", name: "exec", arguments: { cmd: "pwd" } }],
|
tool_events: [{ phase: "start", name: "exec", arguments: { cmd: "pwd" } }],
|
||||||
})
|
})
|
||||||
await Bun.sleep(130)
|
await waitUntil(() => /^Working\s+\d+s/u.test(status.plainText), 2_000)
|
||||||
await setup.renderOnce()
|
await setup.flush()
|
||||||
frame = setup.captureCharFrame()
|
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).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)
|
||||||
expect(frame).toContain("› Running pwd")
|
expect(frame).toContain("› Running pwd")
|
||||||
expect(occurrences(frame, "pwd")).toBe(1)
|
expect(occurrences(frame, "pwd")).toBe(1)
|
||||||
@@ -235,6 +239,10 @@ describe("NanobotTui transcript", () => {
|
|||||||
app.accept({ event: "turn_end", chat_id: "chat" })
|
app.accept({ event: "turn_end", chat_id: "chat" })
|
||||||
await setup.flush()
|
await setup.flush()
|
||||||
expect(ui.composer.placeholder).toBe("Ask nanobot anything")
|
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 () => {
|
test("updates retry state in place and ends failed turns explicitly", async () => {
|
||||||
|
|||||||
@@ -478,8 +478,21 @@ describe("gateway protocol", () => {
|
|||||||
client.close()
|
client.close()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("represents lifecycle frames without browser state", () => {
|
test("delivers lifecycle frames with media metadata through the gateway socket", () => {
|
||||||
const events: InboundEvent[] = [
|
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",
|
event: "user_message",
|
||||||
chat_id: "one",
|
chat_id: "one",
|
||||||
@@ -493,12 +506,26 @@ describe("gateway protocol", () => {
|
|||||||
{ event: "stream_end", chat_id: "one", resuming: false },
|
{ event: "stream_end", chat_id: "one", resuming: false },
|
||||||
{ event: "turn_end", chat_id: "one", latency_ms: 12 },
|
{ event: "turn_end", chat_id: "one", latency_ms: 12 },
|
||||||
]
|
]
|
||||||
expect(events.map((event) => event.event)).toEqual([
|
const delivered: InboundEvent[] = []
|
||||||
"user_message",
|
const client = new NanobotClient({
|
||||||
"delta",
|
url: "ws://nanobot.test/ws",
|
||||||
"stream_end",
|
chatId: "one",
|
||||||
"turn_end",
|
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", () => {
|
test("attaches and sends turns through the gateway envelope", () => {
|
||||||
|
|||||||
@@ -6,3 +6,5 @@ coverage/
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
|
test-results/
|
||||||
|
playwright-report/
|
||||||
+3
-1
@@ -114,10 +114,12 @@ The gateway picks up the new bundle on the next restart.
|
|||||||
cd webui
|
cd webui
|
||||||
bun run lint
|
bun run lint
|
||||||
bun run test
|
bun run test
|
||||||
|
bun x playwright install chromium
|
||||||
|
bun run test:browser
|
||||||
bun run build
|
bun 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).
|
||||||
|
|
||||||
## Acknowledgements
|
## Acknowledgements
|
||||||
|
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -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>);
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -37,6 +37,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@playwright/test": "1.64.1",
|
||||||
"@tailwindcss/typography": "^0.5.19",
|
"@tailwindcss/typography": "^0.5.19",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.1.0",
|
"@testing-library/react": "^16.1.0",
|
||||||
@@ -231,6 +232,8 @@
|
|||||||
|
|
||||||
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
|
"@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
|
||||||
|
|
||||||
|
"@playwright/test": ["@playwright/test@1.64.1", "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/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],
|
"@radix-ui/number": ["@radix-ui/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],
|
||||||
|
|
||||||
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
|
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
|
||||||
@@ -1109,6 +1112,10 @@
|
|||||||
|
|
||||||
"pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="],
|
"pirates": ["pirates@4.0.7", "", {}, "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA=="],
|
||||||
|
|
||||||
|
"playwright": ["playwright@1.64.1", "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": ["playwright-core@1.64.1", "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],
|
||||||
|
|
||||||
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
|
"pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="],
|
||||||
|
|
||||||
"points-on-curve": ["points-on-curve@0.2.0", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="],
|
"points-on-curve": ["points-on-curve@0.2.0", "", {}, "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="],
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export default tseslint.config(
|
|||||||
{
|
{
|
||||||
files: [
|
files: [
|
||||||
"webui/src/**/*.{ts,tsx}",
|
"webui/src/**/*.{ts,tsx}",
|
||||||
|
"webui/browser/**/*.{ts,tsx}",
|
||||||
"nanobot/channels/*/webui/**/*.{ts,tsx}",
|
"nanobot/channels/*/webui/**/*.{ts,tsx}",
|
||||||
"nanobot/channels/*/tests/webui/**/*.{ts,tsx}",
|
"nanobot/channels/*/tests/webui/**/*.{ts,tsx}",
|
||||||
],
|
],
|
||||||
|
|||||||
Generated
+46
@@ -40,6 +40,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@playwright/test": "1.64.1",
|
||||||
"@tailwindcss/typography": "^0.5.19",
|
"@tailwindcss/typography": "^0.5.19",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.1.0",
|
"@testing-library/react": "^16.1.0",
|
||||||
@@ -1227,6 +1228,22 @@
|
|||||||
"node": ">=14"
|
"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": {
|
"node_modules/@radix-ui/number": {
|
||||||
"version": "1.1.1",
|
"version": "1.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
|
||||||
@@ -7284,6 +7301,35 @@
|
|||||||
"node": ">= 6"
|
"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": {
|
"node_modules/pngjs": {
|
||||||
"version": "5.0.0",
|
"version": "5.0.0",
|
||||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||||
|
|||||||
+3
-1
@@ -11,9 +11,10 @@
|
|||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:coverage": "vitest run --coverage",
|
"test:coverage": "vitest run --coverage",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
|
"test:browser": "tsc -p tsconfig.browser.json && playwright test",
|
||||||
"check:imports": "bun ../scripts/check_client_import_boundaries.mjs --project webui",
|
"check:imports": "bun ../scripts/check_client_import_boundaries.mjs --project webui",
|
||||||
"test:imports": "bun test ../scripts/check_client_import_boundaries.test.mjs",
|
"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": {
|
"dependencies": {
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.4",
|
"@radix-ui/react-alert-dialog": "^1.1.4",
|
||||||
@@ -48,6 +49,7 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@playwright/test": "1.64.1",
|
||||||
"@tailwindcss/typography": "^0.5.19",
|
"@tailwindcss/typography": "^0.5.19",
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
"@testing-library/react": "^16.1.0",
|
"@testing-library/react": "^16.1.0",
|
||||||
|
|||||||
@@ -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,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -55,7 +55,9 @@ describe("channel logos", () => {
|
|||||||
expectFootprint(icon);
|
expectFootprint(icon);
|
||||||
expect(fallback).toHaveClass("opacity-0");
|
expect(fallback).toHaveClass("opacity-0");
|
||||||
expect(image).toHaveClass("opacity-100");
|
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(icon).toHaveClass(presentation.logoLayout === "tile" ? "bg-transparent" : "bg-white");
|
||||||
expect(image).toHaveClass(...(presentation.logoLayout === "tile" ? ["h-8", "w-8"] : ["h-6", "w-6"]));
|
expect(image).toHaveClass(...(presentation.logoLayout === "tile" ? ["h-8", "w-8"] : ["h-6", "w-6"]));
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import { readFileSync } from "node:fs";
|
|
||||||
import { resolve } from "node:path";
|
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 {
|
import {
|
||||||
channelUiContribution,
|
channelUiContribution,
|
||||||
@@ -34,9 +36,22 @@ describe("channel UI contributions", () => {
|
|||||||
expect(channelUiOwner("wechat")).toBe("weixin");
|
expect(channelUiOwner("wechat")).toBe("weixin");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("includes channel-owned UI in Tailwind's production scan", () => {
|
it("includes channel-owned UI in Tailwind's production scan", async () => {
|
||||||
const source = readFileSync(resolve(process.cwd(), "tailwind.config.js"), "utf8");
|
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();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -17,10 +17,12 @@ describe("form control focus styles", () => {
|
|||||||
"focus-visible:ring-inset",
|
"focus-visible:ring-inset",
|
||||||
"focus-visible:ring-ring/50",
|
"focus-visible:ring-ring/50",
|
||||||
);
|
);
|
||||||
expect(element).not.toHaveClass(
|
for (const className of [
|
||||||
"ring-offset-background",
|
"ring-offset-background",
|
||||||
"focus-visible:ring-ring",
|
"focus-visible:ring-ring",
|
||||||
"focus-visible:ring-offset-2",
|
"focus-visible:ring-offset-2",
|
||||||
);
|
]) {
|
||||||
|
expect(element).not.toHaveClass(className);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { resolve } from "node:path";
|
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 { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
@@ -339,43 +339,24 @@ const ACCIDENTALLY_SPANISH_SETTINGS_KEYS = [
|
|||||||
"settings.oauth.signInHelp",
|
"settings.oauth.signInHelp",
|
||||||
];
|
];
|
||||||
const INDEX_HTML = readFileSync(resolve(process.cwd(), "index.html"), "utf8");
|
const INDEX_HTML = readFileSync(resolve(process.cwd(), "index.html"), "utf8");
|
||||||
const PREBOOT_SCRIPT = INDEX_HTML.match(
|
async function runPrebootLocale(storedLocale: string) {
|
||||||
/<script>\s*(\(function \(\) \{\s*var localeKey = "nanobot\.locale";[\s\S]*?\}\)\(\);)\s*<\/script>/,
|
const preboot = new Window({
|
||||||
)?.[1];
|
url: "http://preboot.test",
|
||||||
const BOOT_COPY_MARKUP = '<span data-boot-copy>Loading nanobot…</span>';
|
settings: { disableJavaScriptFileLoading: true, disableCSSFileLoading: true },
|
||||||
|
|
||||||
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;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
try {
|
||||||
return {
|
preboot.localStorage.setItem(LOCALE_STORAGE_KEY, storedLocale);
|
||||||
lang: documentElement.lang,
|
// Parse the shipped document and execute inline scripts in parser order.
|
||||||
boot: boot.textContent,
|
// External/module loading stays disabled: React must not repair the splash.
|
||||||
description: meta.content,
|
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> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
@@ -406,13 +387,6 @@ function interpolationKeys(value: unknown): string[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("webui i18n", () => {
|
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 }) => {
|
it.each(supportedLocales)("localizes compaction states in $code", async ({ code }) => {
|
||||||
await setAppLanguage(code);
|
await setAppLanguage(code);
|
||||||
const copy = resources[code].common.thread.compaction;
|
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) {
|
for (const { code } of supportedLocales) {
|
||||||
const result = runPrebootLocale(code);
|
const result = await runPrebootLocale(code);
|
||||||
const expected = resources[code].common.app;
|
const expected = resources[code].common.app;
|
||||||
|
|
||||||
expect({ code, ...result }).toEqual({
|
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;
|
const expected = resources["pt-BR"].common.app;
|
||||||
|
|
||||||
for (const locale of ["pt", "pt-PT"]) {
|
for (const locale of ["pt", "pt-PT"]) {
|
||||||
expect(runPrebootLocale(locale)).toEqual({
|
expect(await runPrebootLocale(locale)).toEqual({
|
||||||
lang: "pt-BR",
|
lang: "pt-BR",
|
||||||
boot: expected.loading.boot,
|
boot: expected.loading.boot,
|
||||||
description: expected.meta.description,
|
description: expected.meta.description,
|
||||||
|
|||||||
@@ -97,7 +97,9 @@ describe("file quick look", () => {
|
|||||||
const quickLook = screen.getByTestId("file-image-quick-look");
|
const quickLook = screen.getByTestId("file-image-quick-look");
|
||||||
expect(quickLook.textContent).toBe("");
|
expect(quickLook.textContent).toBe("");
|
||||||
expect(quickLook).toHaveClass("w-max");
|
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("rounded-mark", "object-contain");
|
||||||
expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");
|
expect(quickLook.querySelector("img")).toHaveClass("h-auto", "w-auto", "max-h-36");
|
||||||
expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");
|
expect(screen.getByRole("tooltip")).toHaveTextContent("File preview");
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ describe("Linear workspace logo", () => {
|
|||||||
expect(image).toHaveAttribute("height", "28");
|
expect(image).toHaveAttribute("height", "28");
|
||||||
expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
|
expect(image).toHaveAttribute("referrerpolicy", "no-referrer");
|
||||||
expect(image.parentElement).toHaveClass("h-7", "w-7");
|
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(image).toHaveClass("object-contain");
|
||||||
expect(view.container.querySelector("svg")).toBeNull();
|
expect(view.container.querySelector("svg")).toBeNull();
|
||||||
fireEvent.error(image);
|
fireEvent.error(image);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { waitFor } from "@testing-library/react";
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
const render = vi.fn();
|
const render = vi.fn();
|
||||||
@@ -12,28 +13,28 @@ vi.mock("@/App", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
describe("service worker registration when unsupported", () => {
|
describe("service worker registration when unsupported", () => {
|
||||||
const register = vi.fn(() => Promise.resolve());
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.resetModules();
|
vi.resetModules();
|
||||||
createRoot.mockClear();
|
createRoot.mockClear();
|
||||||
render.mockClear();
|
render.mockClear();
|
||||||
register.mockClear();
|
|
||||||
document.body.innerHTML = '<div id="root"></div>';
|
document.body.innerHTML = '<div id="root"></div>';
|
||||||
// happy-dom's Navigator has no serviceWorker member, so this file runs
|
Reflect.deleteProperty(navigator, "serviceWorker");
|
||||||
// without defining one — the entry's `"serviceWorker" in navigator` guard
|
|
||||||
// must keep registration from being attempted.
|
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
document.body.innerHTML = "";
|
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");
|
await import("../main");
|
||||||
window.dispatchEvent(new Event("load"));
|
window.dispatchEvent(new Event("load"));
|
||||||
|
|
||||||
expect(register).not.toHaveBeenCalled();
|
await waitFor(() => {
|
||||||
|
expect(createRoot).toHaveBeenCalledWith(document.getElementById("root"));
|
||||||
|
expect(render).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -142,30 +142,4 @@ describe("MarkdownText", () => {
|
|||||||
"true",
|
"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",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
@@ -274,31 +274,37 @@ describe("MessageBubble", () => {
|
|||||||
expect(bubble).toHaveClass("bg-secondary/70");
|
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[] = [
|
const messages: UIMessage[] = [
|
||||||
{
|
{
|
||||||
id: "u-persisted",
|
id: "u-persisted",
|
||||||
role: "user",
|
role: "user",
|
||||||
content: "Earlier question",
|
content: "Earlier question",
|
||||||
createdAt: Date.now(),
|
createdAt: 1_700_000_000_000,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "a-persisted",
|
id: "a-persisted",
|
||||||
role: "assistant",
|
role: "assistant",
|
||||||
content: "Earlier answer",
|
content: "Earlier answer",
|
||||||
createdAt: Date.now(),
|
createdAt: 1_700_000_001_000,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "t-persisted",
|
id: "t-persisted",
|
||||||
role: "tool",
|
role: "tool",
|
||||||
kind: "trace",
|
kind: "trace",
|
||||||
content: "Earlier tool call",
|
content: "Earlier tool call",
|
||||||
createdAt: Date.now(),
|
createdAt: 1_700_000_002_000,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const message of messages) {
|
for (const message of messages) {
|
||||||
const { container, unmount } = render(<MessageBubble message={message} />);
|
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"]) {
|
for (const className of ["animate-in", "fade-in-0", "slide-in-from-bottom-1"]) {
|
||||||
expect(container.firstElementChild).not.toHaveClass(className);
|
expect(container.firstElementChild).not.toHaveClass(className);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ describe("settings provider icons", () => {
|
|||||||
expect(icon).not.toHaveAttribute("style");
|
expect(icon).not.toHaveAttribute("style");
|
||||||
expect(fallback).toHaveClass("opacity-0");
|
expect(fallback).toHaveClass("opacity-0");
|
||||||
expect(image).toHaveClass("opacity-100");
|
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);
|
fireEvent.load(image);
|
||||||
expect(image).toHaveClass("opacity-100");
|
expect(image).toHaveClass("opacity-100");
|
||||||
expect(icon).toHaveClass("bg-transparent");
|
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);
|
fireEvent.error(image);
|
||||||
expect(image).toHaveAttribute("src", providerBrand(provider)!.logoUrls[1]);
|
expect(image).toHaveAttribute("src", providerBrand(provider)!.logoUrls[1]);
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { fireEvent, render, screen, waitFor, within } from "@testing-library/rea
|
|||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
|
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 { TimezonePicker } from "@/components/settings/shared/TimezonePicker";
|
||||||
import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/ModelsSettings";
|
import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/ModelsSettings";
|
||||||
import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
|
import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
|
||||||
@@ -29,6 +31,15 @@ function runtimeSettings() {
|
|||||||
describe("Runtime configuration settings", () => {
|
describe("Runtime configuration settings", () => {
|
||||||
installSettingsViewTestHooks();
|
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", () => {
|
it("keeps local service controls available when tool families are disabled", () => {
|
||||||
const payload = runtimeSettings();
|
const payload = runtimeSettings();
|
||||||
renderSettingsView({ initialSection: "advanced", initialSettings: {
|
renderSettingsView({ initialSection: "advanced", initialSettings: {
|
||||||
|
|||||||
@@ -203,7 +203,9 @@ describe("Settings system domains", () => {
|
|||||||
expect(title.parentElement).toHaveClass("settings-section-heading");
|
expect(title.parentElement).toHaveClass("settings-section-heading");
|
||||||
expect(title.nextElementSibling).toHaveTextContent("1");
|
expect(title.nextElementSibling).toHaveTextContent("1");
|
||||||
expect(title.nextElementSibling).toHaveClass("tabular-nums");
|
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 }));
|
fireEvent.click(screen.getByRole("button", { name: "MCP", exact: true }));
|
||||||
const mcpTitle = screen.getByRole("heading", { name: "MCP tools" });
|
const mcpTitle = screen.getByRole("heading", { name: "MCP tools" });
|
||||||
@@ -267,7 +269,9 @@ describe("Settings system domains", () => {
|
|||||||
for (const name of ["Custom", "Built-in", "Other"]) {
|
for (const name of ["Custom", "Built-in", "Other"]) {
|
||||||
const title = screen.getByRole("heading", { name, exact: true });
|
const title = screen.getByRole("heading", { name, exact: true });
|
||||||
expect(title).toHaveClass("text-[13px]", "font-medium", "leading-5");
|
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).toHaveTextContent("1");
|
||||||
expect(title.nextElementSibling).toHaveClass("leading-5");
|
expect(title.nextElementSibling).toHaveClass("leading-5");
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-12
@@ -139,10 +139,10 @@ function indexHtml(assetPaths: string[]): Response {
|
|||||||
return new Response(`<!doctype html><html><head>${refs}</head></html>`);
|
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 respondWith = vi.fn();
|
||||||
const event = {
|
const event = {
|
||||||
request: new Request(url, { method: "GET" }),
|
request: new Request(url, init),
|
||||||
respondWith,
|
respondWith,
|
||||||
};
|
};
|
||||||
return { event, respondWith };
|
return { event, respondWith };
|
||||||
@@ -223,8 +223,8 @@ describe("service worker", () => {
|
|||||||
];
|
];
|
||||||
|
|
||||||
for (const path of paths) {
|
for (const path of paths) {
|
||||||
const { respondWith } = fetchEvent(`${ORIGIN}${path}`);
|
const { event, respondWith } = fetchEvent(`${ORIGIN}${path}`);
|
||||||
await sw.fire("fetch", { request: new Request(`${ORIGIN}${path}`) });
|
await sw.fire("fetch", event);
|
||||||
expect(respondWith, path).not.toHaveBeenCalled();
|
expect(respondWith, path).not.toHaveBeenCalled();
|
||||||
}
|
}
|
||||||
expect(sw.fetchMock).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 () => {
|
it("does not intercept non-GET or unrelated cross-origin requests", async () => {
|
||||||
const sw = loadSw();
|
const sw = loadSw();
|
||||||
|
|
||||||
const { respondWith: post } = fetchEvent(`${ORIGIN}/api/v1/models`);
|
const { event: postEvent, respondWith: post } = fetchEvent(
|
||||||
await sw.fire("fetch", {
|
`${ORIGIN}/assets/app.js`, { method: "POST" },
|
||||||
request: new Request(`${ORIGIN}/api/v1/models`, { method: "POST" }),
|
);
|
||||||
});
|
await sw.fire("fetch", postEvent);
|
||||||
expect(post).not.toHaveBeenCalled();
|
expect(post).not.toHaveBeenCalled();
|
||||||
|
|
||||||
const { respondWith: cross } = fetchEvent("https://other.test/assets/app.js");
|
const { event: crossEvent, respondWith: cross } = fetchEvent("https://other.test/assets/app.js");
|
||||||
await sw.fire("fetch", {
|
await sw.fire("fetch", crossEvent);
|
||||||
request: new Request("https://other.test/assets/app.js"),
|
|
||||||
});
|
|
||||||
expect(cross).not.toHaveBeenCalled();
|
expect(cross).not.toHaveBeenCalled();
|
||||||
expect(sw.fetchMock).not.toHaveBeenCalled();
|
expect(sw.fetchMock).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -816,7 +816,9 @@ describe("ThreadComposer", () => {
|
|||||||
expect(modelPill).not.toHaveClass("font-semibold");
|
expect(modelPill).not.toHaveClass("font-semibold");
|
||||||
const providerLogo = screen.getByTestId("composer-model-logo-openai");
|
const providerLogo = screen.getByTestId("composer-model-logo-openai");
|
||||||
expect(providerLogo).toBeInTheDocument();
|
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...");
|
const input = screen.getByPlaceholderText("Type your message...");
|
||||||
expect(input.className).toContain("min-h-[50px]");
|
expect(input.className).toContain("min-h-[50px]");
|
||||||
expect(input.className).toContain("text-[16px]");
|
expect(input.className).toContain("text-[16px]");
|
||||||
|
|||||||
@@ -731,7 +731,9 @@ describe("ThreadMessages", () => {
|
|||||||
const rows = Array.from(container.firstElementChild?.children ?? []);
|
const rows = Array.from(container.firstElementChild?.children ?? []);
|
||||||
|
|
||||||
expect(rows).toHaveLength(2);
|
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");
|
expect(rows[1]).not.toHaveClass("mt-4");
|
||||||
const answerRow = screen.getByText("final answer")
|
const answerRow = screen.getByText("final answer")
|
||||||
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
.closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||||
@@ -772,7 +774,9 @@ describe("ThreadMessages", () => {
|
|||||||
expect(disclosure.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING)
|
expect(disclosure.compareDocumentPosition(timestamp) & Node.DOCUMENT_POSITION_FOLLOWING)
|
||||||
.toBeTruthy();
|
.toBeTruthy();
|
||||||
expect(menu).toHaveClass("w-max", "max-w-64", "bg-popover", "rounded-floating", "overflow-y-auto");
|
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"));
|
const menuButtons = Array.from(menu.querySelectorAll("button"));
|
||||||
expect(menuButtons.length).toBeGreaterThan(1);
|
expect(menuButtons.length).toBeGreaterThan(1);
|
||||||
for (const button of menuButtons) {
|
for (const button of menuButtons) {
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ import { Input } from "@/components/ui/input";
|
|||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
|
||||||
describe("UI shape system", () => {
|
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}>
|
render(<Dialog open><DialogContent placement={placement}>
|
||||||
<DialogTitle>Long dialog</DialogTitle>
|
<DialogTitle>Long dialog</DialogTitle>
|
||||||
<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>
|
<DialogDescription>Content that can outgrow a keyboard-fitted frame.</DialogDescription>
|
||||||
@@ -32,7 +32,7 @@ describe("UI shape system", () => {
|
|||||||
const dialog = screen.getByRole("dialog");
|
const dialog = screen.getByRole("dialog");
|
||||||
expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");
|
expect(dialog.parentElement).toHaveClass("items-start", "overflow-y-auto");
|
||||||
// The scroll owner stays inside Radix's overlay/scroll-lock boundary.
|
// 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");
|
expect(dialog).toHaveClass(placement === "bottom" ? "mt-auto" : "my-auto");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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 { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { gunzipSync } from "node:zlib";
|
import { gunzipSync } from "node:zlib";
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { rollup } from "rollup";
|
||||||
|
|
||||||
import webuiConfig, {
|
import webuiConfig, {
|
||||||
entryLazyFeatureImports,
|
entryLazyFeatureImports,
|
||||||
gzipWebuiAssets,
|
gzipWebuiAssets,
|
||||||
webuiManualChunk,
|
webuiManualChunk,
|
||||||
writeCompressedWebuiAssets,
|
|
||||||
} from "../../vite.config";
|
} from "../../vite.config";
|
||||||
|
|
||||||
describe("development overlay dependencies", () => {
|
describe("development overlay dependencies", () => {
|
||||||
@@ -20,24 +20,37 @@ describe("development overlay dependencies", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("gzipWebuiAssets", () => {
|
describe("gzipWebuiAssets", () => {
|
||||||
it("compresses finalized files after Rollup writes the bundle", () => {
|
it("compresses finalized files after Rollup writes the bundle", async () => {
|
||||||
const plugin = gzipWebuiAssets();
|
const plugin = gzipWebuiAssets();
|
||||||
expect(plugin.generateBundle).toBeUndefined();
|
expect(plugin.generateBundle).toBeUndefined();
|
||||||
expect(plugin.writeBundle).toBeTypeOf("function");
|
|
||||||
|
|
||||||
const outputDir = mkdtempSync(path.join(tmpdir(), "nanobot-vite-gzip-"));
|
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 {
|
try {
|
||||||
const assetPath = path.join(outputDir, "assets", "index-final.js");
|
await build.write({ dir: outputDir, format: "es", entryFileNames: "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"]);
|
|
||||||
|
|
||||||
expect(gunzipSync(readFileSync(`${assetPath}.gz`))).toEqual(finalized);
|
expect(gunzipSync(readFileSync(`${assetPath}.gz`))).toEqual(finalized);
|
||||||
} finally {
|
} finally {
|
||||||
|
await build.close();
|
||||||
rmSync(outputDir, { recursive: true, force: true });
|
rmSync(outputDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ function payload(id: string): WebuiThreadPersistedPayload {
|
|||||||
return {
|
return {
|
||||||
schemaVersion: 3,
|
schemaVersion: 3,
|
||||||
revision: `rev-${id}`,
|
revision: `rev-${id}`,
|
||||||
messages: [{ id, role: "assistant", content: id, createdAt: 1 }],
|
projection: "events",
|
||||||
|
events: [{ event: "message", chat_id: id, text: id }],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.build.json",
|
||||||
|
"include": ["browser", "playwright.config.ts"],
|
||||||
|
"exclude": []
|
||||||
|
}
|
||||||
@@ -26,6 +26,7 @@
|
|||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["./src/*"],
|
"@/*": ["./src/*"],
|
||||||
|
"vitest": ["./node_modules/vitest"],
|
||||||
"lucide-react": ["./node_modules/lucide-react"],
|
"lucide-react": ["./node_modules/lucide-react"],
|
||||||
"react": ["./node_modules/@types/react/index.d.ts"],
|
"react": ["./node_modules/@types/react/index.d.ts"],
|
||||||
"react/*": ["./node_modules/@types/react/*"],
|
"react/*": ["./node_modules/@types/react/*"],
|
||||||
|
|||||||
Reference in new issue
Block a user