refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

-9
View File
@@ -7,7 +7,6 @@ from nanobot.config.schema import AgentDefaults, Config
def test_bot_name_and_icon_defaults_preserve_current_branding() -> None:
"""Default values keep the existing 'nanobot' name and cat icon."""
defaults = AgentDefaults()
assert defaults.bot_name == "nanobot"
@@ -15,7 +14,6 @@ def test_bot_name_and_icon_defaults_preserve_current_branding() -> None:
def test_bot_name_and_icon_can_be_overridden_via_config() -> None:
"""camelCase keys (as used in config.json) bind to the new fields."""
config = Config.model_validate(
{"agents": {"defaults": {"botName": "mybot", "botIcon": "🤖"}}}
)
@@ -25,7 +23,6 @@ def test_bot_name_and_icon_can_be_overridden_via_config() -> None:
def test_bot_icon_accepts_empty_string_to_omit() -> None:
"""Empty bot_icon is valid and lets users opt out of the leading icon."""
config = Config.model_validate(
{"agents": {"defaults": {"botIcon": ""}}}
)
@@ -34,7 +31,6 @@ def test_bot_icon_accepts_empty_string_to_omit() -> None:
def test_stream_renderer_propagates_bot_name_to_spinner_text(capsys) -> None:
"""ThinkingSpinner uses the configured bot_name in its status text."""
spinner = ThinkingSpinner(bot_name="mybot")
# rich.Status keeps the renderable on its internal _renderable attribute;
@@ -44,20 +40,15 @@ def test_stream_renderer_propagates_bot_name_to_spinner_text(capsys) -> None:
def test_stream_renderer_header_combines_icon_and_name() -> None:
"""When bot_icon is non-empty, the header is '<icon> <name>'."""
renderer = StreamRenderer(show_spinner=False, bot_name="mybot", bot_icon="🤖")
# The header is built inline in on_delta; verify the stored fields
# so we don't depend on Live console output.
assert renderer._bot_name == "mybot"
assert renderer._bot_icon == "🤖"
def test_stream_renderer_empty_icon_omits_leading_space() -> None:
"""An empty bot_icon yields a header that is just the bot name, no leading space."""
renderer = StreamRenderer(show_spinner=False, bot_name="mybot", bot_icon="")
# Replicate the header construction used in on_delta to assert the contract.
header = (
f"{renderer._bot_icon} {renderer._bot_name}"
if renderer._bot_icon
-2
View File
@@ -1,5 +1,3 @@
"""Credential-bearing browser URLs must not enter a macOS command line."""
import ctypes
import subprocess
from unittest.mock import MagicMock
-2
View File
@@ -1,5 +1,3 @@
"""Message tools preserve target identity through gateway delivery recording."""
from functools import partial
import pytest
+1 -29
View File
@@ -30,7 +30,6 @@ def mock_prompt_session():
@pytest.mark.asyncio
async def test_read_interactive_input_async_returns_input(mock_prompt_session):
"""Test that _read_interactive_input_async returns the user input from prompt_session."""
mock_prompt_session.prompt_async.return_value = "hello world"
result = await terminal._read_interactive_input_async()
@@ -38,12 +37,11 @@ async def test_read_interactive_input_async_returns_input(mock_prompt_session):
assert result == "hello world"
mock_prompt_session.prompt_async.assert_called_once()
args, _ = mock_prompt_session.prompt_async.call_args
assert isinstance(args[0], HTML) # Verify HTML prompt is used
assert isinstance(args[0], HTML)
@pytest.mark.asyncio
async def test_read_interactive_input_async_handles_eof(mock_prompt_session):
"""Test that EOFError converts to KeyboardInterrupt."""
mock_prompt_session.prompt_async.side_effect = EOFError()
with pytest.raises(KeyboardInterrupt):
@@ -51,8 +49,6 @@ async def test_read_interactive_input_async_handles_eof(mock_prompt_session):
def test_init_prompt_session_creates_session():
"""Test that _init_prompt_session initializes the global session."""
# Ensure global is None before test
terminal._prompt_session = None
with patch("nanobot.cli.terminal.PromptSession") as mock_session_cls, \
@@ -66,15 +62,12 @@ def test_init_prompt_session_creates_session():
assert terminal._prompt_session is not None
mock_session_cls.assert_called_once()
_, kwargs = mock_session_cls.call_args
# Buffer is multiline-capable so Alt+Enter can insert newlines;
# Enter-to-submit is restored via custom key bindings.
assert kwargs["multiline"] is True
assert kwargs["enable_open_in_editor"] is False
assert kwargs.get("key_bindings") is not None
def test_cli_key_bindings_enter_submits_and_alt_enter_newlines():
"""Enter submits the buffer; Alt+Enter inserts a newline."""
from prompt_toolkit.keys import Keys
kb = terminal._build_cli_key_bindings()
@@ -84,14 +77,12 @@ def test_cli_key_bindings_enter_submits_and_alt_enter_newlines():
bound = {_keys(b): b for b in kb.bindings}
# Enter -> submit
enter = bound[(Keys.Enter.value,)]
buf = MagicMock()
enter.call(MagicMock(current_buffer=buf))
buf.validate_and_handle.assert_called_once()
buf.insert_text.assert_not_called()
# Alt+Enter (escape, enter) -> newline
alt_enter = bound[(Keys.Escape.value, Keys.Enter.value)]
buf = MagicMock()
alt_enter.call(MagicMock(current_buffer=buf))
@@ -124,7 +115,6 @@ async def test_raw_lf_enter_still_submits_like_wsl_terminals():
@pytest.mark.asyncio
async def test_alt_enter_inserts_newline_on_lf_terminals():
"""LF-as-Enter terminals send Alt+Enter as ESC + LF, which needs its own binding."""
from prompt_toolkit.application import create_app_session
from prompt_toolkit.input import create_pipe_input
from prompt_toolkit.output import DummyOutput
@@ -143,7 +133,6 @@ async def test_alt_enter_inserts_newline_on_lf_terminals():
@pytest.mark.asyncio
async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
"""CSI-u Shift+Enter inserts a newline instead of raw escape bytes."""
from prompt_toolkit.application import create_app_session
from prompt_toolkit.input import create_pipe_input
from prompt_toolkit.output import DummyOutput
@@ -157,12 +146,10 @@ async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
session.prompt_async("> ", set_exception_handler=False), timeout=10,
)
# A newline is inserted and no raw escape bytes leak into the result.
assert result == "foo\nbar"
def test_thinking_spinner_pause_stops_and_restarts():
"""Pause should stop the active spinner and restart it afterward."""
spinner = MagicMock()
mock_console = MagicMock()
mock_console.status.return_value = spinner
@@ -181,7 +168,6 @@ def test_thinking_spinner_pause_stops_and_restarts():
def test_print_cli_progress_line_pauses_spinner_before_printing():
"""CLI progress output should pause spinner to avoid garbled lines."""
order: list[str] = []
spinner = MagicMock()
spinner.start.side_effect = lambda: order.append("start")
@@ -198,7 +184,6 @@ def test_print_cli_progress_line_pauses_spinner_before_printing():
def test_thinking_spinner_clears_status_line_when_paused():
"""Stopping the spinner should erase its transient line before output."""
stream = StringIO()
stream.isatty = lambda: True # type: ignore[method-assign]
mock_console = MagicMock()
@@ -215,7 +200,6 @@ def test_thinking_spinner_clears_status_line_when_paused():
def test_stream_renderer_stops_spinner_even_after_header_printed():
"""A later answer delta must stop the spinner even when header already exists."""
stream = StringIO()
stream.isatty = lambda: True # type: ignore[method-assign]
mock_console = MagicMock()
@@ -233,7 +217,6 @@ def test_stream_renderer_stops_spinner_even_after_header_printed():
def test_print_cli_progress_line_opens_renderer_header_before_trace():
"""Trace lines should appear under the assistant header, not under You."""
order: list[str] = []
renderer = MagicMock()
renderer.console.print.side_effect = lambda *_args, **_kwargs: order.append("print")
@@ -246,7 +229,6 @@ def test_print_cli_progress_line_opens_renderer_header_before_trace():
def test_print_cli_progress_line_stops_live_before_trace():
"""A trace line should not leak the current transient Live frame."""
mock_live = MagicMock()
renderer = stream_mod.StreamRenderer(show_spinner=False)
renderer._live = mock_live
@@ -259,7 +241,6 @@ def test_print_cli_progress_line_stops_live_before_trace():
@pytest.mark.asyncio
async def test_print_interactive_progress_line_pauses_spinner_before_printing():
"""Interactive progress output should also pause spinner cleanly."""
order: list[str] = []
spinner = MagicMock()
spinner.start.side_effect = lambda: order.append("start")
@@ -309,28 +290,22 @@ def test_response_renderable_without_metadata_keeps_markdown_path():
def test_stream_renderer_stop_for_input_stops_spinner():
"""stop_for_input should stop the active spinner to avoid prompt_toolkit conflicts."""
spinner = MagicMock()
mock_console = MagicMock()
mock_console.status.return_value = spinner
# Create renderer with mocked console
with patch.object(stream_mod, "_make_console", return_value=mock_console):
renderer = stream_mod.StreamRenderer(show_spinner=True)
# Verify spinner started
spinner.start.assert_called_once()
# Stop for input
renderer.stop_for_input()
# Verify spinner stopped
spinner.stop.assert_called_once()
@pytest.mark.asyncio
async def test_on_end_writes_final_content_to_stdout_after_stopping_live():
"""on_end should stop Live (transient erases it) then print final content to stdout."""
mock_live = MagicMock()
mock_console = MagicMock()
mock_console.capture.return_value.__enter__ = MagicMock(
@@ -356,7 +331,6 @@ async def test_on_end_writes_final_content_to_stdout_after_stopping_live():
@pytest.mark.asyncio
async def test_on_end_resuming_clears_buffer_and_restarts_spinner():
"""on_end(resuming=True) should reset state for the next iteration."""
spinner = MagicMock()
mock_console = MagicMock()
mock_console.status.return_value = spinner
@@ -372,12 +346,10 @@ async def test_on_end_resuming_clears_buffer_and_restarts_spinner():
await renderer.on_end(resuming=True)
assert renderer._buf == ""
# Spinner should have been restarted (start called twice: __init__ + resuming)
assert spinner.start.call_count == 2
def test_make_console_force_terminal_when_stdout_is_tty():
"""Console should set force_terminal=True when stdout is a TTY (rich output)."""
import sys
with patch.object(sys.stdout, "isatty", return_value=True):
console = stream_mod._make_console()
+1 -11
View File
@@ -376,7 +376,6 @@ def mock_paths():
def test_onboard_fresh_install(mock_paths):
"""No existing config — should create from scratch."""
config_file, workspace_dir, mock_ws = mock_paths
result = runner.invoke(app, ["onboard"])
@@ -393,7 +392,6 @@ def test_onboard_fresh_install(mock_paths):
def test_onboard_recommends_webui(mock_paths):
"""Default onboarding should recommend the guided WebUI launcher."""
result = runner.invoke(app, ["onboard"])
assert result.exit_code == 0
@@ -401,7 +399,6 @@ def test_onboard_recommends_webui(mock_paths):
def test_onboard_existing_config_refresh(mock_paths):
"""Config exists, user declines overwrite — should refresh (load-merge-save)."""
config_file, workspace_dir, _ = mock_paths
config_file.write_text('{"existing": true}')
@@ -415,7 +412,6 @@ def test_onboard_existing_config_refresh(mock_paths):
def test_onboard_existing_config_refresh_non_interactive(mock_paths):
"""Config exists, user specifies --refresh — should refresh non-interactively (no prompt)."""
config_file, workspace_dir, _ = mock_paths
config_file.write_text('{"existing": true}')
@@ -429,7 +425,6 @@ def test_onboard_existing_config_refresh_non_interactive(mock_paths):
def test_onboard_existing_config_overwrite(mock_paths):
"""Config exists, user confirms overwrite — should reset to defaults."""
config_file, workspace_dir, _ = mock_paths
config_file.write_text('{"existing": true}')
@@ -442,7 +437,6 @@ def test_onboard_existing_config_overwrite(mock_paths):
def test_onboard_existing_workspace_safe_create(mock_paths):
"""Workspace exists — should not recreate, but still add missing templates."""
config_file, workspace_dir, _ = mock_paths
workspace_dir.mkdir(parents=True)
config_file.write_text("{}")
@@ -1286,7 +1280,6 @@ def test_config_bare_nemotron_still_auto_routes_to_configured_ollama():
def test_config_cloud_nemotron_is_not_hijacked_by_configured_ollama():
"""An explicit cloud namespace takes precedence over local keywords."""
config = Config.model_validate(
{
"agents": {
@@ -1921,7 +1914,7 @@ def test_agent_workspace_override_wins_over_config_workspace(mock_agent_runtime,
[
("", False),
("# Title\n\n## Active Tasks\n", False),
("<!--\nmulti-line\ncomment\n-->\n", False), # block comment, not tasks
("<!--\nmulti-line\ncomment\n-->\n", False),
("<!-- single line -->\n", False),
("## Active Tasks\n\n- water the plants\n", True),
("## Active Tasks\n\n### Garden\n\n- water the plants\n", True),
@@ -2129,7 +2122,6 @@ def _patch_cli_command_runtime(
) -> None:
from importlib import import_module
# Load adapter contracts before replacing runtime factories for this invocation.
import_module("nanobot.session.webui_turns")
import_module("nanobot.channels.validation")
import_module("nanobot.channels.websocket.runtime")
@@ -3835,7 +3827,6 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
def test_migrate_cron_store_moves_legacy_file(tmp_path: Path) -> None:
"""Legacy global jobs.json is moved into the workspace on first run."""
from nanobot.cli.runtime_config import _migrate_cron_store
legacy_dir = tmp_path / "global" / "cron"
@@ -3856,7 +3847,6 @@ def test_migrate_cron_store_moves_legacy_file(tmp_path: Path) -> None:
def test_migrate_cron_store_skips_when_workspace_file_exists(tmp_path: Path) -> None:
"""Migration does not overwrite an existing workspace cron store."""
from nanobot.cli.runtime_config import _migrate_cron_store
legacy_dir = tmp_path / "global" / "cron"
+1 -2
View File
@@ -216,7 +216,7 @@ def test_absent_desktop_selects_current_python(monkeypatch, capsys) -> None:
("\x1b[B\r", "python"),
("\x1b[B\x1b[A\r", "desktop"),
("\x1b[A\r", "python"),
("2\r", "desktop"), # Numeric keys no longer move the highlight.
("2\r", "desktop"),
("\x1b[B1\r", "python"),
])
def test_target_picker_accepts_real_navigation_keys(keys, expected):
@@ -253,7 +253,6 @@ def test_target_picker_cancellation_exits_without_attachment(monkeypatch, capsys
with create_pipe_input() as pipe_input:
with create_app_session(input=pipe_input, output=DummyOutput()):
if cancel == "interrupt":
# Cancel even after moving the highlight to the Python option.
pipe_input.send_text("\x1b[B\x03")
else:
pipe_input.close()
@@ -1,5 +1,3 @@
"""The picker covers retained launchers without intercepting explicit commands."""
import pytest
from prompt_toolkit.application import create_app_session
from prompt_toolkit.input import create_pipe_input
@@ -19,7 +17,6 @@ def test_retained_launcher_attaches_without_starting_python(monkeypatch, args):
monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", dispatch)
monkeypatch.setattr(entry, "_run_agent", lambda *_a, **_kw: pytest.fail("agent started"))
# Callback exits before webui can inspect/load config or start its runtime.
monkeypatch.setattr(
"nanobot.cli.webui._resolve_webui_config_path",
lambda *_a, **_kw: pytest.fail("Python WebUI started"),
+2 -5
View File
@@ -1,5 +1,3 @@
"""Win32 boundary tests; native pipe integration additionally runs on Windows."""
import ctypes
import os
import threading
@@ -48,11 +46,10 @@ def test_windows_pipe_authenticates_before_io(monkeypatch, kernel):
def test_windows_pending_io_is_drained_before_buffers_are_freed(monkeypatch, kernel, failure):
lifecycle = []
kernel.WriteFile.return_value = False
kernel.WaitForSingleObject.return_value = 258 # WAIT_TIMEOUT
kernel.WaitForSingleObject.return_value = 258
if failure == "interrupt":
kernel.WaitForSingleObject.side_effect = KeyboardInterrupt
elif failure == "deadline":
# Whole request budget: wait-pipe, pre-transfer, then pending wait.
monkeypatch.setattr(
desktop_target, "_remaining_seconds",
MagicMock(side_effect=[1.0, 0.5, DesktopTargetError("timed out")]),
@@ -132,7 +129,7 @@ def test_native_windows_pipe_roundtrip():
handle = winapi.CreateNamedPipe(
rf"\\.\pipe\{address}",
winapi.PIPE_ACCESS_DUPLEX | winapi.FILE_FLAG_OVERLAPPED,
0, # PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT
0,
1, 8192, 8192, 1000, 0,
)
connected = winapi.ConnectNamedPipe(handle, overlapped=True)
-5
View File
@@ -1,5 +1,3 @@
"""The Dock shortcut never owns gateway execution, data, or credentials on disk."""
import asyncio
import os
import socket
@@ -161,7 +159,6 @@ def _server():
listener.listen()
clients = _Clients()
stopped = threading.Event()
# Keep startup serialized just like the launcher: first connect before release.
from filelock import FileLock
with FileLock(str(address.parent / "start.lock")):
thread = threading.Thread(target=_serve, args=(listener, address, clients, stopped.set))
@@ -279,8 +276,6 @@ async def test_background_presence_waits_for_activation_and_remembers_explicit_r
with pytest.raises(asyncio.CancelledError):
await watcher
assert closed.is_set()
# A new gateway generation, including a protected update restart, reads the
# same intent without rewriting configuration or learning an updater protocol.
entered.clear()
watcher = asyncio.create_task(dock.watch_gateway_icon(
"http://127.0.0.1:8765/", instance=instance, activated=activated,
+10 -10
View File
@@ -177,14 +177,14 @@ async def test_stubborn_task_does_not_block_past_wait_timeout() -> None:
)
elapsed = time.monotonic() - start
for _ in range(10):
await asyncio.sleep(0) # let the swallowed cancellation handler run
await asyncio.sleep(0)
assert "swallowed" in events # task was cancelled, then refused to die
assert task.done() # the timed-out task received a second cancellation
assert "swallowed" in events
assert task.done()
assert runtime_tasks.done()
assert agent.close_calls == 1 # resources still closed underneath it
assert agent.close_calls == 1
assert provider.close_calls == 1
assert elapsed < 1.0 # bounded, not held open by the stubborn task
assert elapsed < 1.0
async def test_hanging_close_is_bounded_and_does_not_raise() -> None:
@@ -220,7 +220,7 @@ async def test_failing_close_is_logged_but_shutdown_proceeds() -> None:
assert agent.close_calls == 1
assert provider.close_calls == 1
assert channels.stopped == 1 # teardown continued past the failure
assert channels.stopped == 1
async def test_duplicate_cleanup_is_idempotent() -> None:
@@ -232,7 +232,7 @@ async def test_duplicate_cleanup_is_idempotent() -> None:
await _close_gateway_runtime(agent, provider, channels, [task], None)
await _close_gateway_runtime(agent, provider, channels, [task], None)
assert agent.close_calls == 2 # second pass is a clean no-op
assert agent.close_calls == 2
assert provider.close_calls == 2
assert channels.stopped == 2
assert task.cancelled()
@@ -245,7 +245,7 @@ async def test_finished_runtime_tasks_gather_is_retrieved() -> None:
finished = asyncio.get_running_loop().create_future()
finished.set_result(None)
runtime_tasks = asyncio.gather(finished)
await asyncio.sleep(0) # let the gather observe the finished child
await asyncio.sleep(0)
await _close_gateway_runtime(agent, provider, channels, [], runtime_tasks)
@@ -263,8 +263,8 @@ async def test_cancelled_runtime_tasks_gather_does_not_raise() -> None:
await _close_gateway_runtime(agent, provider, channels, [], runtime_tasks)
with suppress(asyncio.CancelledError):
await runtime_tasks # settle the cancelled gather without raising
await runtime_tasks
assert runtime_tasks.done() # the cancelled gather was awaited without raising
assert runtime_tasks.done()
assert agent.close_calls == 1
assert provider.close_calls == 1
-4
View File
@@ -9,7 +9,6 @@ from nanobot.cli import terminal
@pytest.mark.asyncio
async def test_interactive_retry_wait_is_rendered_as_progress_even_when_progress_disabled():
"""Provider retry waits should not fall through as assistant responses."""
calls: list[tuple[str, object | None]] = []
thinking = None
channels_config = SimpleNamespace(send_progress=False, send_tool_hints=False)
@@ -61,7 +60,6 @@ async def test_reasoning_display_is_independent_of_send_progress(send_progress):
@pytest.mark.asyncio
async def test_reasoning_delta_displayed_when_show_reasoning_enabled():
"""Streamed reasoning delta frames should use the reasoning renderer."""
calls: list[str] = []
channels_config = SimpleNamespace(
send_progress=True, send_tool_hints=False, show_reasoning=True,
@@ -151,7 +149,6 @@ async def test_reasoning_end_flushes_buffered_delta():
@pytest.mark.asyncio
async def test_reasoning_hidden_when_show_reasoning_disabled():
"""Reasoning content should be suppressed when show_reasoning is False."""
channels_config = SimpleNamespace(
send_progress=True, send_tool_hints=False, show_reasoning=False,
)
@@ -170,7 +167,6 @@ async def test_reasoning_hidden_when_show_reasoning_disabled():
@pytest.mark.asyncio
async def test_non_reasoning_progress_not_affected_by_show_reasoning():
"""Regular progress lines should display regardless of show_reasoning."""
calls: list[str] = []
channels_config = SimpleNamespace(
send_progress=True, send_tool_hints=False, show_reasoning=False,
-2
View File
@@ -1,5 +1,3 @@
"""CLI model discovery exercises the same provider boundary as WebUI."""
from types import SimpleNamespace
import httpx
-2
View File
@@ -1,5 +1,3 @@
"""A regular cloud login can complete pairing without guessing a sudo command."""
import json
import subprocess
from pathlib import Path
-2
View File
@@ -1,5 +1,3 @@
"""Server pairing suggests a real login account, never blindly trusts SUDO_USER."""
import subprocess
from types import SimpleNamespace
from unittest.mock import Mock
-2
View File
@@ -1,5 +1,3 @@
"""Pairing knows whose public IP it needs, without querying arbitrary metadata."""
import http.client
from pathlib import Path
from unittest.mock import Mock
+4 -9
View File
@@ -1,5 +1,3 @@
"""Tests for /restart slash command."""
from __future__ import annotations
import asyncio
@@ -151,7 +149,6 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_restart_intercepted_in_run_loop(self):
"""Verify /restart is handled at the run-loop level, without starting a session worker."""
loop, bus = _make_loop()
loop.restart_mode = "exec"
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/restart")
@@ -193,7 +190,6 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_status_intercepted_in_run_loop(self):
"""Verify /status is handled at the run-loop level for immediate replies."""
loop, bus = _make_loop()
msg = InboundMessage(channel="telegram", sender_id="u1", chat_id="c1", content="/status")
@@ -215,7 +211,6 @@ class TestRestartCommand:
@pytest.mark.asyncio
async def test_run_propagates_external_cancellation(self):
"""External task cancellation should not be swallowed by the inbound wait loop."""
loop, _bus = _make_loop()
run_task = asyncio.create_task(loop.run())
@@ -359,7 +354,7 @@ class TestRestartCommand:
session.get_history.return_value = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
{"role": "tool", "content": "tool result"}, # should be filtered out
{"role": "tool", "content": "tool result"},
{"role": "user", "content": "How are you?"},
{"role": "assistant", "content": "I am doing well."},
]
@@ -371,7 +366,7 @@ class TestRestartCommand:
assert response is not None
assert "👤 You: Hello" in response.content
assert "🤖 Bot: Hi there!" in response.content
assert "tool result" not in response.content # tool messages filtered
assert "tool result" not in response.content
assert response.metadata == {"render_as": "text"}
@pytest.mark.asyncio
@@ -388,8 +383,8 @@ class TestRestartCommand:
assert response is not None
assert "Last 3 message(s)" in response.content
assert "message 19" in response.content # most recent
assert "message 0" not in response.content # too old
assert "message 19" in response.content
assert "message 0" not in response.content
@pytest.mark.asyncio
async def test_history_clamps_count_and_extracts_text_blocks(self):
+1 -4
View File
@@ -22,7 +22,6 @@ class TestSanitizeSurrogates:
assert _sanitize_surrogates("normal ascii text") == "normal ascii text"
def test_emoji_already_correct(self):
"""Properly encoded emoji should pass through unchanged."""
assert _sanitize_surrogates("hello 🐈 nanobot") == "hello 🐈 nanobot"
def test_mixed_unicode_preserved(self):
@@ -52,17 +51,15 @@ class TestSafeFileHistory:
assert entries[0] == "normal ascii text"
def test_windows_surrogate_pair_round_trips_as_emoji(self, tmp_path):
"""Raw UTF-16 console input must survive a UTF-8 history write and reload."""
history_path = tmp_path / "history"
hist = SafeFileHistory(str(history_path))
hist.store_string("hello \ud83d\udc08 nanobot")
history_path.read_bytes().decode("utf-8") # Strict decoding must not raise.
history_path.read_bytes().decode("utf-8")
reloaded = SafeFileHistory(str(history_path))
assert list(reloaded.load_history_strings()) == ["hello 🐈 nanobot"]
def test_mixed_unicode_preserved(self, tmp_path):
"""CJK + emoji + latin should all pass through cleanly."""
hist = SafeFileHistory(str(tmp_path / "history"))
hist.store_string("你好 hello こんにちは 🎉")
entries = list(hist.load_history_strings())
-2
View File
@@ -1,5 +1,3 @@
"""Keep shipped corresponding source and runtime materials complete and aligned."""
import importlib.util
import io
import json
+1 -6
View File
@@ -1,5 +1,3 @@
"""Release wheels carry a complete native bundle, with installable metadata."""
import csv
import hashlib
import io
@@ -258,7 +256,6 @@ def complete_candidate(tmp_path, candidate):
def test_complete_manifest_binds_wheels_sdist_and_fallback_archives(tmp_path, complete_candidate):
"""Real archive/RECORD checks, with synthetic binaries (not native execution)."""
root, commit, artifacts = complete_candidate
manifest = verify_candidate(root, artifacts, source_commit=commit)
assert len(manifest.artifacts) == 16
@@ -276,7 +273,7 @@ def test_complete_manifest_binds_wheels_sdist_and_fallback_archives(tmp_path, co
write_install_guide(root, artifacts, guide, source_commit=commit)
assert guide.read_bytes() == original_guide
assert commit.encode() in original_guide
assert len(list(artifacts.iterdir())) == 17 # 16 artifacts and the manifest, no guide.
assert len(list(artifacts.iterdir())) == 17
with pytest.raises(ValueError, match="outside"):
write_install_guide(root, artifacts, artifacts / "install.md", source_commit=commit)
guide.write_text("previous reviewed handoff\n")
@@ -341,8 +338,6 @@ def test_interrupted_retention_has_no_accepted_handoff(tmp_path, complete_candid
@pytest.mark.parametrize("mutation", ["wheel-code", "wheel-webui", "source-code", "source-missing", "source-extra"])
def test_complete_candidate_rejects_mixed_or_incomplete_application_payload(tmp_path, complete_candidate, mutation):
root, commit, artifacts = complete_candidate
# These are intact archives with valid versions/commit markers and RECORDs.
# A stale intermediate or a stray local file can still be packaged correctly.
if mutation.startswith("wheel-"):
wheel = next(artifacts.glob("*-macosx_13_0_arm64.whl"))
with zipfile.ZipFile(wheel) as archive:
+4 -6
View File
@@ -1,5 +1,3 @@
"""Windows redirect, secret transport and cleanup regressions."""
import base64
import ctypes
import io
@@ -405,8 +403,8 @@ def test_private_file_checks_precede_secret_write_and_failures_clean_up(tmp_path
with browser._private_redirect(b"synthetic-only") as path:
assert path.read_bytes() == b"synthetic-only"
assert events.index(("private", path, False)) < events.index(("write", path))
assert ("close", path, 0x40020080) in events # No live write handle for browser.
assert ("close", path.parent, 0x20080) not in events # Directory is pinned.
assert ("close", path, 0x40020080) in events
assert ("close", path.parent, 0x20080) not in events
assert not path.exists()
assert not list(tmp_path.glob("*/*.html"))
if failure in {"reparse", "filesystem", "root_acl", "file_acl"}:
@@ -453,7 +451,7 @@ def test_stale_cleanup_preserves_active_unsafe_and_unrelated_entries(tmp_path):
for path in paths:
path.write_text("synthetic")
os.utime(path, (0, 0))
paths[1].touch() # fresh / active
paths[1].touch()
(tmp_path / ("d" * 32 + ".html")).mkdir()
@contextmanager
@@ -481,7 +479,7 @@ def test_native_private_file_permissions_sharing_and_cleanup(tmp_path, monkeypat
with api.opened(path) as handle:
api.check_private(handle, directory=False)
with pytest.raises(PermissionError):
path.unlink() # A live handoff cannot be removed by stale cleanup.
path.unlink()
assert not path.exists()
-2
View File
@@ -1,5 +1,3 @@
"""Exercise the Windows file boundary used by the WSL browser handoff."""
import base64
import os
import shutil