源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Creator App Tests / PR Spam Gate (push) Skipped
Frontend Tests / PR Spam Gate (push) Skipped
NPM Format (website & console) / PR Spam Gate (push) Skipped
Pre-commit Checks / PR Spam Gate (push) Skipped
QwenPaw Creator Plugin Release / check-version (push) Canceled after 0s
QwenPaw Creator Plugin Release / upload-oss (push) Canceled after 0s
Tests / PR Spam Gate (push) Skipped
CodeQL / CodeQL (python) (push) Canceled after 0s
CodeQL / CodeQL (typescript) (push) Canceled after 0s
Creator App Tests / Creator Backend Tests (push) Canceled after 0s
Creator App Tests / Creator UI Build & Tests (push) Canceled after 0s
E2E Smoke Tests / Playwright UI Smoke (push) Canceled after 0s
Frontend Tests / Detect console changes (push) Canceled after 0s
NPM Format (website & console) / website format check (push) Canceled after 0s
NPM Format (website & console) / console format check (push) Canceled after 0s
Pre-commit Checks / Pre-commit (push) Canceled after 0s
QwenPaw Data Plugin Release / check-version (push) Canceled after 0s
Tests / Detect code changes (push) Canceled after 0s
Frontend Tests / Vitest Unit Tests (push) Canceled after 0s
Frontend Tests / Frontend Summary (push) Canceled after 0s
QwenPaw Data Plugin Release / upload-oss (push) Canceled after 0s
Tests / Maintainer Approval (push) Canceled after 0s
Tests / Unit Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - fallback (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p2 (push) Canceled after 0s
Tests / Coverage Report (push) Canceled after 0s
Tests / Test Summary (push) Canceled after 0s

This commit is contained in:
agent-radar committed 2026-09-01 20:01:50 +08:00
commit 1a3a4ccde1
4652 files changed
+1891610

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""Unit tests for the plugins subpackage."""
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
"""Make the in-repo Computer Use plugin importable for its tests.
The plugin ships as a directory under ``plugins/`` rather than as an installed
package, so its own modules are not on ``sys.path``. The tests live here, under
``tests/unit``, so the standard suite collects them without any CI workflow
needing to name a second path.
"""
from __future__ import annotations
import os
import sys
_PLUGIN_DIR = os.path.join(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.abspath(__file__)),
),
),
),
),
"plugins",
"bundle",
"computer-use",
)
if _PLUGIN_DIR not in sys.path:
sys.path.insert(0, _PLUGIN_DIR)
@@ -0,0 +1,150 @@
# -*- coding: utf-8 -*-
"""Recovering after the native helper goes away.
The capability names a pipe or socket the helper is listening on. It used to be
cached for the life of the process with no way to retire it, so a helper that
crashed left the client reconnecting to a name that answered nothing -- for
every request thereafter, until the backend restarted. The desktop host notices
the dead child and will issue a new capability, but only if asked.
"""
from __future__ import annotations
import pytest
from qwenpaw.app.computer_use import runtime as runtime_module
from qwenpaw.app.computer_use.runtime import (
HostRuntimeProvider,
RuntimeCapability,
)
def _capability(pipe: str) -> RuntimeCapability:
return RuntimeCapability(
_pipe_name=pipe,
_secret="secret",
protocol_version=runtime_module.COMPUTER_USE_PROTOCOL_VERSION,
)
@pytest.fixture(autouse=True)
def _clean_provider(monkeypatch: pytest.MonkeyPatch):
"""Start from a provider that holds nothing and sees no environment."""
monkeypatch.setattr(HostRuntimeProvider, "_capability", None)
monkeypatch.setattr(HostRuntimeProvider, "_environment_spent", False)
for name in (
"QWENPAW_COMPUTER_USE_PIPE",
"QWENPAW_COMPUTER_USE_CAPABILITY",
"QWENPAW_COMPUTER_USE_PROTOCOL",
):
monkeypatch.delenv(name, raising=False)
yield
monkeypatch.setattr(HostRuntimeProvider, "_capability", None)
monkeypatch.setattr(HostRuntimeProvider, "_environment_spent", False)
def test_a_dead_endpoint_is_replaced_by_asking_the_host_again(
monkeypatch: pytest.MonkeyPatch,
) -> None:
issued = iter([_capability("pipe-first"), _capability("pipe-second")])
monkeypatch.setattr(
runtime_module,
"_control_endpoint",
object,
)
monkeypatch.setattr(
runtime_module,
"_request_capability",
lambda _control: next(issued),
)
first = HostRuntimeProvider.acquire_capability()
assert first is not None
assert first.names_same_endpoint(_capability("pipe-first"))
# Cached, so the host is not troubled again while it works.
assert HostRuntimeProvider.acquire_capability() is first
HostRuntimeProvider.invalidate_capability(first)
second = HostRuntimeProvider.acquire_capability()
assert second is not None
assert second.names_same_endpoint(_capability("pipe-second"))
def test_invalidating_an_endpoint_already_replaced_keeps_the_new_one(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Two clients can fail over the same dead helper at once.
The second one must not discard the replacement the first already obtained,
or they would take turns invalidating each other's capability.
"""
monkeypatch.setattr(runtime_module, "_control_endpoint", object)
monkeypatch.setattr(
runtime_module,
"_request_capability",
lambda _control: _capability("pipe-new"),
)
HostRuntimeProvider.acquire_capability()
HostRuntimeProvider.invalidate_capability(_capability("pipe-old"))
held = HostRuntimeProvider.get_capability()
assert held is not None
assert held.names_same_endpoint(_capability("pipe-new"))
def test_a_spent_environment_capability_stops_being_returned(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The environment value is a bootstrap, not a permanent answer.
It is handed over when the backend is spawned. Once its endpoint is gone,
returning it again would loop forever, since clearing the cached capability
cannot clear an environment variable.
"""
monkeypatch.setenv("QWENPAW_COMPUTER_USE_PIPE", "pipe-from-env")
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CAPABILITY", "secret")
monkeypatch.setenv(
"QWENPAW_COMPUTER_USE_PROTOCOL",
str(runtime_module.COMPUTER_USE_PROTOCOL_VERSION),
)
injected = HostRuntimeProvider.get_capability()
assert injected is not None
assert injected.names_same_endpoint(_capability("pipe-from-env"))
HostRuntimeProvider.invalidate_capability(injected)
assert HostRuntimeProvider.get_capability() is None
# And the next acquire goes to the host rather than back to the
# environment.
monkeypatch.setattr(runtime_module, "_control_endpoint", object)
monkeypatch.setattr(
runtime_module,
"_request_capability",
lambda _control: _capability("pipe-fresh"),
)
replacement = HostRuntimeProvider.acquire_capability()
assert replacement is not None
assert replacement.names_same_endpoint(_capability("pipe-fresh"))
def test_an_incompatible_desktop_capability_is_not_exposed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("QWENPAW_COMPUTER_USE_PIPE", "pipe-old")
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CAPABILITY", "secret")
monkeypatch.setenv(
"QWENPAW_COMPUTER_USE_PROTOCOL",
str(runtime_module.COMPUTER_USE_PROTOCOL_VERSION + 1),
)
assert HostRuntimeProvider.get_capability() is None
def test_no_host_and_no_environment_means_no_capability(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(runtime_module, "_control_endpoint", lambda: None)
assert HostRuntimeProvider.acquire_capability() is None
@@ -0,0 +1,753 @@
# -*- coding: utf-8 -*-
"""Tests for the thin Computer Use protocol adapter."""
# Tests reach into module internals to pin the protocol contract, and their
# fakes deliberately accept arguments they ignore to match real signatures.
# pylint: disable=protected-access, unused-argument, unnecessary-lambda
# pylint: disable=useless-return, use-implicit-booleaness-not-comparison
from __future__ import annotations
from collections.abc import Iterator, Mapping
import json
import socket
import threading
from typing import Any
import pytest
from agentscope.message import ToolResultState
from agentscope.tool import FunctionTool, ToolChunk
import computer_use.client as client_module
import computer_use.dispatch as dispatch_module
from computer_use.client import ComputerUseClient
from computer_use.dispatch import (
_element_line,
_error,
_native_request,
_response,
_with_compact_elements,
computer_use,
)
from computer_use.protocol import ComputerUseProtocolError
from computer_use.transport.base import (
ComputerUseTransport,
ReverseRequestHandler,
)
from qwenpaw.app.computer_use import (
HostRuntimeProvider,
set_current_computer_use_turn_id,
)
from qwenpaw.app.computer_use import runtime as runtime_module
@pytest.fixture(autouse=True)
def _reset_host_runtime(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
for name in (
"QWENPAW_COMPUTER_USE_PIPE",
"QWENPAW_COMPUTER_USE_CAPABILITY",
"QWENPAW_COMPUTER_USE_PROTOCOL",
"QWENPAW_COMPUTER_USE_CONTROL_HOST",
"QWENPAW_COMPUTER_USE_CONTROL_PORT",
"QWENPAW_COMPUTER_USE_CONTROL_TOKEN",
):
monkeypatch.delenv(name, raising=False)
HostRuntimeProvider._capability = None
yield
HostRuntimeProvider._capability = None
def test_host_runtime_requests_a_capability_only_when_needed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(runtime_module.sys, "platform", "darwin")
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.bind(("127.0.0.1", 0))
listener.listen(1)
port = listener.getsockname()[1]
token = "test-token"
received: dict[str, object] = {}
def _serve_once() -> None:
with listener:
connection, _ = listener.accept()
with connection, connection.makefile("rwb") as stream:
received.update(json.loads(stream.readline()))
stream.write(
b'{"ok":true,"pipe_name":"pipe-1",'
b'"capability":"secret-1"}\n',
)
stream.flush()
server = threading.Thread(target=_serve_once)
server.start()
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CONTROL_HOST", "127.0.0.1")
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CONTROL_PORT", str(port))
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CONTROL_TOKEN", token)
assert HostRuntimeProvider.is_available() is True
assert received == {}
capability = HostRuntimeProvider.acquire_capability()
server.join(timeout=1)
assert capability == runtime_module.RuntimeCapability(
"pipe-1",
"secret-1",
runtime_module.COMPUTER_USE_PROTOCOL_VERSION,
)
assert received == {
"token": token,
"action": "acquire",
}
def test_coordinate_input_leaves_observation_context_to_client() -> None:
method, params, include_images = _native_request(
"click",
screenshot_id="screenshot-7",
x=40,
y=60,
button="left",
count=1,
)
assert method == "click"
assert include_images is False
assert params == {
"screenshot_id": "screenshot-7",
"x": 40,
"y": 60,
"button": "left",
"count": 1,
}
def test_observe_window_requests_current_visual_and_semantic_state() -> None:
method, params, include_images = _native_request(
"observe_window",
window_id="42",
)
assert method == "observe_window"
assert params == {"window_id": "42"}
assert include_images is True
def test_coordinate_input_requires_a_current_screenshot() -> None:
with pytest.raises(ValueError):
_native_request("click", x=40, y=60, button="left", count=1)
def test_close_window_maps_to_the_native_method() -> None:
"""Closing acts through the observation and returns no screenshot."""
method, params, include_images = _native_request("close_window")
assert method == "close_window"
assert params == {}
assert include_images is False
def test_sequence_maps_a_bounded_keyboard_batch() -> None:
steps = [
{"action": "type", "text": "INV-001"},
{"action": "press_key", "key": "TAB"},
]
method, params, include_images = _native_request("sequence", steps=steps)
assert method == "sequence"
assert params == {"steps": steps}
assert include_images is False
def test_sequence_accepts_a_json_encoded_batch() -> None:
steps = json.dumps(
[
{"action": "type", "text": "INV-001"},
{"action": "press_key", "key": "TAB"},
],
)
method, params, include_images = _native_request("sequence", steps=steps)
assert method == "sequence"
assert params["steps"][0]["text"] == "INV-001"
assert include_images is False
def test_sequence_tool_schema_accepts_array_or_json_string() -> None:
import jsonschema
schema = FunctionTool(computer_use).input_schema
steps = [{"action": "type", "text": "INV-001"}]
jsonschema.validate({"action": "sequence", "steps": steps}, schema)
jsonschema.validate(
{"action": "sequence", "steps": json.dumps(steps)},
schema,
)
@pytest.mark.parametrize(
"steps",
[
[],
"not-json",
[{"action": "click", "x": 1, "y": 1}],
[{"action": "type", "text": "x", "extra": True}],
[{"action": "press_key", "key": " "}],
[{"action": "type", "text": "x"}] * 21,
[{"action": "type", "text": "x" * 513}],
],
)
def test_sequence_rejects_inputs_outside_its_contract(steps: Any) -> None:
with pytest.raises(ValueError):
_native_request("sequence", steps=steps)
def test_client_injects_its_private_observation() -> None:
client = ComputerUseClient("session-1")
client._observation_id = "observation-1"
params = client._native_params("close_window", {})
assert params == {"observation_id": "observation-1"}
def test_partial_sequence_result_advances_the_private_observation() -> None:
client = ComputerUseClient("session-1")
client._observation_id = "observation-1"
result = client._accept_result(
"sequence",
{
"observation_id": "observation-2",
"completed_steps": 1,
"error": {"code": "input_failed"},
},
)
assert client._observation_id == "observation-2"
assert "observation_id" not in result
assert result["completed_steps"] == 1
def test_client_rejects_action_before_observe() -> None:
client = ComputerUseClient("session-1")
with pytest.raises(ComputerUseProtocolError) as refusal:
client._native_params("click", {"x": 40, "y": 60})
assert refusal.value.code == "observation_required"
def test_screenshot_data_uses_base64_source_and_stays_out_of_text() -> None:
"""Inline screenshots use the standard media representation once."""
data_url = "data:image/jpeg;base64," + "A" * 4096
payload = {
"ok": True,
"screenshots": [
{
"id": "screenshot-1",
"url": data_url,
"width": 800,
"height": 600,
},
],
}
response = _response(payload, include_images=True)
image_blocks = [
block for block in response.content if block.type == "data"
]
text_blocks = [block for block in response.content if block.type == "text"]
assert len(image_blocks) == 1
assert image_blocks[0].source.type == "base64"
assert image_blocks[0].source.media_type == "image/jpeg"
assert image_blocks[0].source.data == "A" * 4096
assert len(text_blocks) == 1
assert data_url not in text_blocks[0].text
assert "screenshot-1" in text_blocks[0].text
def test_native_error_marks_the_tool_call_as_failed() -> None:
response = _error("stale_observation", "Observe the window again.")
assert isinstance(response, ToolChunk)
assert response.state == ToolResultState.ERROR
assert '"ok":false' in response.content[-1].text
assert '"requires_observe":true' in response.content[-1].text
assert '"next_action":"observe_window"' in response.content[-1].text
def test_sequence_steps_count_against_the_action_rate_limit(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(dispatch_module, "_action_times", [])
monkeypatch.setattr(dispatch_module, "_MAX_ACTIONS_PER_MINUTE", 3)
dispatch_module._check_rate_limit(3)
with pytest.raises(ComputerUseProtocolError) as refusal:
dispatch_module._check_rate_limit()
assert refusal.value.code == "rate_limited"
@pytest.mark.asyncio
async def test_partial_sequence_is_an_error_with_a_fresh_observation(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class _Enabled:
@staticmethod
def is_enabled() -> bool:
return True
class _PartialClient:
@staticmethod
async def execute(*_args: Any, **_kwargs: Any) -> dict[str, Any]:
return {
"completed_steps": 1,
"error": {"code": "input_failed", "step_index": 1},
"screenshots": [],
}
monkeypatch.setattr(dispatch_module, "_check_rate_limit", lambda *_: None)
monkeypatch.setattr(
dispatch_module,
"get_computer_use_feature_state",
lambda: _Enabled(),
)
monkeypatch.setattr(
dispatch_module,
"get_computer_use_client",
lambda: _PartialClient(),
)
response = await computer_use(
action="sequence",
steps=[
{"action": "type", "text": "A"},
{"action": "press_key", "key": "TAB"},
],
)
assert response.state == ToolResultState.ERROR
assert '"ok":false' in response.content[-1].text
assert '"completed_steps":1' in response.content[-1].text
@pytest.mark.asyncio
async def test_function_tool_preserves_intervention_error_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The AgentScope boundary must not turn protocol errors into success."""
class _Enabled:
@staticmethod
def is_enabled() -> bool:
return True
class _IntervenedClient:
@staticmethod
async def execute(*_args: Any, **_kwargs: Any) -> dict[str, Any]:
raise ComputerUseProtocolError(
"user_intervention",
"Recent user input was detected; observe again.",
)
monkeypatch.setattr(dispatch_module, "_check_rate_limit", lambda: None)
monkeypatch.setattr(
dispatch_module,
"get_computer_use_feature_state",
lambda: _Enabled(),
)
monkeypatch.setattr(
dispatch_module,
"get_computer_use_client",
lambda: _IntervenedClient(),
)
response = await FunctionTool(computer_use)(action="list_apps")
assert isinstance(response, ToolChunk)
assert response.is_last is True
assert response.state == ToolResultState.ERROR
assert '"code":"user_intervention"' in response.content[-1].text
assert '"requires_observe":true' in response.content[-1].text
def test_semantic_actions_leave_observation_to_client() -> None:
method, params, _ = _native_request(
"invoke",
element_id="uia-7",
)
assert method == "invoke_element"
assert params == {"element_id": "uia-7"}
method, params, _ = _native_request(
"begin_text_edit",
element_id="uia-8",
)
assert method == "invoke_element"
assert params == {
"element_id": "uia-8",
"expects_text_input": True,
}
class _FakeTransport(ComputerUseTransport):
def __init__(self) -> None:
self.messages: list[dict[str, Any]] = []
self.handler: ReverseRequestHandler | None = None
self.closed = False
async def connect(self) -> None:
return None
async def request(self, message: Mapping[str, Any]) -> dict[str, Any]:
payload = dict(message)
self.messages.append(payload)
if payload["method"] == "hello":
protocol_version = runtime_module.COMPUTER_USE_PROTOCOL_VERSION
return {
"request_id": payload["request_id"],
"ok": True,
"result": {
"protocol_version": protocol_version,
},
}
result = {}
if payload["method"] in client_module._OBSERVED_METHODS:
result["observation_id"] = "observation-next"
return {
"request_id": payload["request_id"],
"ok": True,
"result": result,
}
async def close(self) -> None:
self.closed = True
def set_reverse_request_handler(
self,
handler: ReverseRequestHandler,
) -> None:
self.handler = handler
@pytest.mark.asyncio
async def test_failed_action_invalidates_the_private_observation() -> None:
class _ActionFailureTransport(_FakeTransport):
async def request(self, message: Mapping[str, Any]) -> dict[str, Any]:
if message["method"] == "hello":
return await super().request(message)
return {
"request_id": message["request_id"],
"ok": False,
"error": {
"code": "target_not_at_point",
"message": "Observe again.",
},
}
client = ComputerUseClient("session-1", lambda: _ActionFailureTransport())
client._observation_id = "observation-1"
set_current_computer_use_turn_id("turn-1")
try:
with pytest.raises(ComputerUseProtocolError):
await client.execute("click", {})
finally:
set_current_computer_use_turn_id(None)
assert client._observation_id is None
@pytest.mark.asyncio
async def test_client_binds_session_and_turn_to_native_request() -> None:
transport = _FakeTransport()
client = ComputerUseClient("session-1", lambda: transport)
set_current_computer_use_turn_id("turn-1")
try:
await client.execute("list_windows", {})
finally:
set_current_computer_use_turn_id(None)
request = transport.messages[-1]
assert request["method"] == "list_windows"
assert request["meta"] == {
"session_id": "session-1",
"turn_id": "turn-1",
"deadline_ms": 10000,
}
@pytest.mark.asyncio
async def test_acquire_capability_retries_cold_start_misses(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A transient acquire miss must be retried before giving up."""
attempts: list[int] = []
capability = runtime_module.RuntimeCapability(
"pipe-1",
"secret-1",
runtime_module.COMPUTER_USE_PROTOCOL_VERSION,
)
def _flaky_acquire():
attempts.append(len(attempts))
return None if len(attempts) < 3 else capability
monkeypatch.setattr(
client_module.HostRuntimeProvider,
"acquire_capability",
_flaky_acquire,
)
monkeypatch.setattr(client_module, "_ACQUIRE_RETRY_DELAY_SECONDS", 0.0)
acquired = await ComputerUseClient._acquire_capability()
assert acquired == capability
assert len(attempts) == 3
@pytest.mark.asyncio
async def test_acquire_capability_rejects_an_incompatible_desktop(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
client_module.HostRuntimeProvider,
"acquire_capability",
lambda: runtime_module.RuntimeCapability(
"pipe-1",
"secret-1",
runtime_module.COMPUTER_USE_PROTOCOL_VERSION + 1,
),
)
with pytest.raises(ComputerUseProtocolError) as refusal:
await ComputerUseClient._acquire_capability()
assert refusal.value.code == "protocol_mismatch"
@pytest.mark.asyncio
async def test_acquire_capability_gives_up_after_bounded_attempts(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Persistent failures must surface instead of retrying forever."""
attempts: list[int] = []
def _never_acquire():
attempts.append(len(attempts))
return None
monkeypatch.setattr(
client_module.HostRuntimeProvider,
"acquire_capability",
_never_acquire,
)
monkeypatch.setattr(client_module, "_ACQUIRE_RETRY_DELAY_SECONDS", 0.0)
acquired = await ComputerUseClient._acquire_capability()
assert acquired is None
assert len(attempts) == client_module._ACQUIRE_ATTEMPTS
@pytest.mark.asyncio
async def test_no_action_ever_carries_a_post_approval_exemption() -> None:
"""The client never sends after_approval, on any path.
The exemption is gone: the recency guard has no bypass, so an action right
after an approval is refused as retryable user_intervention rather than
waved through by a client-held flag. The client therefore has no mechanism
left to attach the flag, and this pins that it is absent.
"""
transport = _FakeTransport()
client = ComputerUseClient("session-a", lambda: transport)
client._observation_id = "observation-1"
set_current_computer_use_turn_id("turn-1")
try:
await client.execute(
"type_text",
{"text": "x"},
)
assert "after_approval" not in transport.messages[-1]["params"]
await client.execute("click", {})
assert "after_approval" not in transport.messages[-1]["params"]
finally:
set_current_computer_use_turn_id(None)
def test_the_approval_coordinator_holds_no_exemption_state() -> None:
"""Nothing to arm, so nothing to leak across turns or apps."""
assert not hasattr(
client_module.ComputerUseApprovalCoordinator(),
"intervention_bypass_pending",
)
def test_element_line_omits_windows_screen_bounds() -> None:
"""Desktop UIA bounds do not map to screenshot coordinates."""
line = _element_line(
{
"id": "uia-1",
"control_type_name": "Edit",
"name": "text editor",
"bounds": [100, 200, 300, 400],
"enabled": True,
"offscreen": False,
},
)
assert line == 'uia-1 Edit "text editor"'
def test_element_line_uses_value_on_macos() -> None:
"""macOS elements carry a value instead of bounds."""
line = _element_line(
{
"id": "ax-2",
"role": "AXTextArea",
"control_type_name": "Edit",
"name": "note",
"value": "hello",
},
)
assert line == 'ax-2 Edit "note" =hello'
def test_element_line_preserves_accessibility_depth() -> None:
"""Native hierarchy remains visible in the compact model contract."""
line = _element_line(
{
"id": "uia-2",
"control_type_name": "ListItem",
"name": "餐饮",
"depth": 3,
},
)
assert line == ' uia-2 ListItem "餐饮"'
def test_element_line_preserves_application_identifier() -> None:
"""Stable command identities disambiguate localized menu labels."""
line = _element_line(
{
"id": "ax-3",
"control_type_name": "MenuItem",
"name": "复制",
"identifier": "cmdDuplicate:",
},
)
assert line == 'ax-3 MenuItem "复制" [identifier=cmdDuplicate:]'
def test_element_line_normalizes_windows_semantic_capabilities() -> None:
"""Windows UIA metadata uses the same compact contract as macOS AX."""
line = _element_line(
{
"id": "uia-4",
"control_type_name": "Button",
"name": "Continue",
"automation_id": "continue-button",
"actions": ["Invoke"],
},
)
assert line == (
'uia-4 Button "Continue" [identifier=continue-button] '
"[actions=Invoke]"
)
def test_element_line_keeps_disabled_and_offscreen_visible() -> None:
"""Both states stay in the listing: they inform the next decision."""
line = _element_line(
{
"id": "uia-9",
"control_type_name": "Button",
"name": "Save",
"bounds": [0, 0, 10, 10],
"enabled": False,
"offscreen": True,
},
)
assert line == 'uia-9 Button "Save" [disabled] [offscreen]'
def test_compact_elements_preserves_protocol_fields() -> None:
"""Only the element listing changes; binding fields stay untouched."""
payload = {
"ok": True,
"action": "observe_window",
"observation_id": "observation-1",
"window": {"id": "42", "title": "Editor"},
"accessibility": {
"available": True,
"elements": [
{
"id": "uia-0",
"control_type_name": "Window",
"name": "Editor",
"bounds": [0, 0, 100, 100],
},
{
"id": "uia-1",
"control_type_name": "Button",
"name": "OK",
"depth": 1,
"bounds": [10, 10, 30, 30],
},
],
},
}
result = _with_compact_elements(payload)
assert result["observation_id"] == "observation-1"
assert result["window"] == {"id": "42", "title": "Editor"}
assert result["accessibility"]["available"] is True
assert result["accessibility"]["elements"] == (
'uia-0 Window "Editor"\n' ' uia-1 Button "OK"'
)
# The original payload must not be mutated.
accessibility = payload["accessibility"]
assert isinstance(accessibility, Mapping)
assert isinstance(accessibility["elements"], list)
def test_compact_elements_ignores_payloads_without_accessibility() -> None:
"""Input actions return no accessibility block and pass through."""
payload = {"ok": True, "action": "click", "applied": True}
assert _with_compact_elements(payload) == payload
def test_response_text_is_compact_and_carries_summary_fields() -> None:
"""The model-facing text drops indentation and keeps summary fields."""
payload = {
"ok": True,
"action": "observe_window",
"accessibility": {
"available": True,
"focused_element": 'uia-1 Edit "text editor"',
"document_text": "hello world",
"elements": [
{
"id": "uia-1",
"control_type_name": "Edit",
"name": "text editor",
"bounds": [100, 200, 300, 400],
},
],
},
}
text = _response(payload).content[-1].text
assert "\n " not in text
decoded = json.loads(text)
accessibility = decoded["accessibility"]
assert accessibility["focused_element"] == 'uia-1 Edit "text editor"'
assert accessibility["document_text"] == "hello world"
assert accessibility["elements"] == 'uia-1 Edit "text editor"'
@@ -0,0 +1,343 @@
# -*- coding: utf-8 -*-
"""Tests for the Computer Use plugin status route."""
# Fixtures are requested for their side effects, so some are never read.
# pylint: disable=unused-argument, use-implicit-booleaness-not-comparison
from __future__ import annotations
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from computer_use import router as router_module
from computer_use.access import (
ComputerUseAccessStore,
PersistentAppAccess,
)
from computer_use.feature_state import ComputerUseFeatureState
from computer_use.router import (
FeatureToggleRequest,
PendingDecisionRequest,
PersistentAccessRequest,
build_router,
)
from qwenpaw.app.computer_use import HostRuntimeProvider
from qwenpaw.app.computer_use import runtime as runtime_module
from qwenpaw.security.tool_guard.approval import ApprovalDecision
def test_status_route_does_not_acquire_native_runtime(monkeypatch) -> None:
monkeypatch.setattr(runtime_module.sys, "platform", "darwin")
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CONTROL_HOST", "127.0.0.1")
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CONTROL_PORT", "8080")
monkeypatch.setenv("QWENPAW_COMPUTER_USE_CONTROL_TOKEN", "test-token")
route = next(
route for route in build_router().routes if route.path == "/status"
)
payload = route.endpoint()
assert payload["runtime_available"] is True
assert payload["connection_active"] is False
assert HostRuntimeProvider.get_capability() is None
@pytest.mark.asyncio
async def test_session_route_reads_access_without_acquiring_runtime(
monkeypatch: pytest.MonkeyPatch,
) -> None:
route = next(
route for route in build_router().routes if route.path == "/session"
)
payload = await route.endpoint("session-1")
assert payload["automation_active"] is False
assert HostRuntimeProvider.get_capability() is None
def test_revoke_persistent_access(
monkeypatch: pytest.MonkeyPatch,
tmp_path,
) -> None:
store = ComputerUseAccessStore(tmp_path / "app_access.json")
store.record_persistent("win32:contoso.editor", "Contoso Editor")
monkeypatch.setattr(
router_module,
"get_computer_use_access_store",
lambda: store,
)
route = next(
route
for route in build_router().routes
if route.path == "/access" and "DELETE" in route.methods
)
response = route.endpoint(
PersistentAccessRequest(canonical_app_id="win32:contoso.editor"),
)
assert response == {"revoked": True}
assert store.list_persistent() == []
class _ApprovalService:
def __init__(self, pending: object) -> None:
self.pending = pending
self.decisions: list[tuple[str, ApprovalDecision]] = []
async def get_request(self, request_id: str):
if getattr(self.pending, "request_id", None) == request_id:
return self.pending
return None
async def resolve_request(
self,
request_id: str,
decision: ApprovalDecision,
) -> object | None:
self.decisions.append((request_id, decision))
return self.pending
@pytest.mark.asyncio
async def test_pending_decision_only_resolves_computer_use_access(
monkeypatch: pytest.MonkeyPatch,
) -> None:
pending = SimpleNamespace(
request_id="request-1",
session_id="session-1",
extra={"source_type": "computer_use_app_access"},
)
service = _ApprovalService(pending)
monkeypatch.setattr(
router_module,
"get_approval_service",
lambda: service,
)
route = next(
route
for route in build_router().routes
if route.path == "/session/pending/decision"
)
response = await route.endpoint(
PendingDecisionRequest(
session_id="session-1",
request_id="request-1",
decision="session",
),
)
assert response == {"resolved": True, "decision": "session"}
assert service.decisions == [("request-1", ApprovalDecision.APPROVED)]
@pytest.mark.asyncio
async def test_pending_decision_rejects_non_computer_use_approval(
monkeypatch: pytest.MonkeyPatch,
) -> None:
pending = SimpleNamespace(
request_id="request-1",
session_id="session-1",
extra={"source_type": "tool_guard"},
)
service = _ApprovalService(pending)
monkeypatch.setattr(
router_module,
"get_approval_service",
lambda: service,
)
route = next(
route
for route in build_router().routes
if route.path == "/session/pending/decision"
)
with pytest.raises(HTTPException, match="Pending approval not found"):
await route.endpoint(
PendingDecisionRequest(
session_id="session-1",
request_id="request-1",
decision="session",
),
)
assert service.decisions == []
@pytest.mark.asyncio
async def test_pending_always_decision_records_persistent_access(
monkeypatch: pytest.MonkeyPatch,
tmp_path,
) -> None:
pending = SimpleNamespace(
request_id="request-1",
session_id="session-1",
extra={
"source_type": "computer_use_app_access",
"computer_use_app": {
"canonical_app_id": "win32:contoso.editor",
"display_name": "Contoso Editor",
},
},
)
service = _ApprovalService(pending)
store = ComputerUseAccessStore(tmp_path / "app_access.json")
monkeypatch.setattr(
router_module,
"get_approval_service",
lambda: service,
)
monkeypatch.setattr(
router_module,
"get_computer_use_access_store",
lambda: store,
)
route = next(
route
for route in build_router().routes
if route.path == "/session/pending/decision"
)
response = await route.endpoint(
PendingDecisionRequest(
session_id="session-1",
request_id="request-1",
decision="always",
),
)
assert response == {"resolved": True, "decision": "always"}
assert store.list_persistent() == [
PersistentAppAccess(
canonical_app_id="win32:contoso.editor",
display_name="Contoso Editor",
),
]
def test_status_route_reports_feature_enabled_by_default(
monkeypatch: pytest.MonkeyPatch,
tmp_path,
) -> None:
state = ComputerUseFeatureState(tmp_path / "feature_state.json")
monkeypatch.setattr(
router_module,
"get_computer_use_feature_state",
lambda: state,
)
route = next(
route for route in build_router().routes if route.path == "/status"
)
assert route.endpoint()["enabled"] is True
class _PendingApprovalService:
def __init__(self, pending: list[object]) -> None:
self.pending = pending
self.decisions: list[tuple[str, ApprovalDecision]] = []
async def list_pending_by_session(self, session_id: str):
return [
item
for item in self.pending
if getattr(item, "session_id", None) == session_id
]
async def resolve_request(
self,
request_id: str,
decision: ApprovalDecision,
) -> object | None:
self.decisions.append((request_id, decision))
return next(
(
item
for item in self.pending
if getattr(item, "request_id", None) == request_id
),
None,
)
@pytest.mark.asyncio
async def test_feature_disable_stops_turns_and_denies_pending(
monkeypatch: pytest.MonkeyPatch,
tmp_path,
) -> None:
state = ComputerUseFeatureState(tmp_path / "feature_state.json")
monkeypatch.setattr(
router_module,
"get_computer_use_feature_state",
lambda: state,
)
async def _stop_all() -> int:
return 2
monkeypatch.setattr(
router_module,
"stop_all_computer_use_turns",
_stop_all,
)
pending = SimpleNamespace(
request_id="request-1",
session_id="session-1",
extra={"source_type": "computer_use_app_access"},
)
service = _PendingApprovalService([pending])
monkeypatch.setattr(
router_module,
"get_approval_service",
lambda: service,
)
route = next(
route for route in build_router().routes if route.path == "/feature"
)
response = await route.endpoint(
FeatureToggleRequest(enabled=False, session_id="session-1"),
)
assert response == {"enabled": False, "stopped": 2, "denied": 1}
assert state.is_enabled() is False
assert service.decisions == [("request-1", ApprovalDecision.DENIED)]
# The decision must survive a reload from disk.
reloaded = ComputerUseFeatureState(tmp_path / "feature_state.json")
assert reloaded.is_enabled() is False
@pytest.mark.asyncio
async def test_feature_enable_skips_stop_and_persists(
monkeypatch: pytest.MonkeyPatch,
tmp_path,
) -> None:
state = ComputerUseFeatureState(tmp_path / "feature_state.json")
state.set_enabled(False)
monkeypatch.setattr(
router_module,
"get_computer_use_feature_state",
lambda: state,
)
async def _stop_all() -> int:
raise AssertionError("enable must not stop turns")
monkeypatch.setattr(
router_module,
"stop_all_computer_use_turns",
_stop_all,
)
route = next(
route for route in build_router().routes if route.path == "/feature"
)
response = await route.endpoint(FeatureToggleRequest(enabled=True))
assert response == {"enabled": True}
assert state.is_enabled() is True
reloaded = ComputerUseFeatureState(tmp_path / "feature_state.json")
assert reloaded.is_enabled() is True
@@ -0,0 +1,253 @@
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Waiting for another session's turn at the desktop.
The helper refuses immediately when another session holds the desktop rather
than queueing the request, so the waiting happens on this side. That placement
is the point: a thread parked inside the helper is not reading its connection,
so a stop could not reach it, and it would wake later to act on a desktop the
user had already withdrawn.
"""
from __future__ import annotations
import asyncio
from typing import Any
import pytest
from computer_use import client as client_module
from computer_use.client import ComputerUseClient
from computer_use.protocol import ComputerUseProtocolError
class _Transport:
"""A transport that reports the desktop busy a fixed number of times."""
def __init__(self, busy_replies: int) -> None:
self.busy_replies = busy_replies
self.attempts = 0
self.closed = False
def set_reverse_request_handler(self, _handler: Any) -> None:
return None
async def connect(self) -> None:
return None
async def close(self) -> None:
self.closed = True
async def request(self, message: dict[str, Any]) -> dict[str, Any]:
self.attempts += 1
if self.attempts <= self.busy_replies:
raise ComputerUseProtocolError(
"desktop_busy",
"Another Computer Use session is using the desktop.",
)
return {
"protocol_version": message["protocol_version"],
"request_id": message["request_id"],
"ok": True,
"result": {"done": True},
}
@pytest.fixture(autouse=True)
def _fast_retries(monkeypatch: pytest.MonkeyPatch):
"""Keep the backoff from making the suite wait for real seconds."""
monkeypatch.setattr(client_module, "_DESKTOP_BUSY_DELAY_SECONDS", 0.001)
yield
@pytest.mark.asyncio
async def test_a_busy_desktop_is_retried_until_it_frees_up(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
client_module,
"get_current_computer_use_turn_id",
lambda: "turn-1",
)
transport = _Transport(busy_replies=2)
client = ComputerUseClient(
"session-1",
transport_factory=lambda: transport,
)
client._observation_id = "observation-1"
result = await client.execute("click", {})
assert result == {"done": True}
assert transport.attempts == 3, "should have retried past both refusals"
@pytest.mark.asyncio
async def test_a_desktop_busy_for_too_long_is_reported(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The model is told, rather than left waiting indefinitely."""
monkeypatch.setattr(
client_module,
"get_current_computer_use_turn_id",
lambda: "turn-1",
)
transport = _Transport(busy_replies=99)
client = ComputerUseClient(
"session-1",
transport_factory=lambda: transport,
)
client._observation_id = "observation-1"
with pytest.raises(ComputerUseProtocolError) as refusal:
await client.execute("click", {})
assert refusal.value.code == "desktop_busy"
assert transport.attempts == client_module._DESKTOP_BUSY_ATTEMPTS
@pytest.mark.asyncio
async def test_a_stop_ends_the_retrying(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The reason the waiting belongs on this side.
A stop arriving while the desktop is busy must end the attempts. Inside the
helper the same wait could not be interrupted, and the queued input would
land after the user had already stopped it.
"""
monkeypatch.setattr(
client_module,
"get_current_computer_use_turn_id",
lambda: "turn-1",
)
transport = _Transport(busy_replies=99)
client = ComputerUseClient(
"session-1",
transport_factory=lambda: transport,
)
client._observation_id = "observation-1"
async def _stop_once_contended() -> None:
while transport.attempts < 1:
await asyncio.sleep(0)
client._stopped_turn = "turn-1"
stopper = asyncio.create_task(_stop_once_contended())
with pytest.raises(ComputerUseProtocolError) as refusal:
await client.execute("click", {})
await stopper
assert refusal.value.code == "turn_stopped"
assert (
transport.attempts < client_module._DESKTOP_BUSY_ATTEMPTS
), "the retrying should have stopped early rather than using every attempt"
@pytest.mark.asyncio
async def test_other_failures_are_not_retried(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Only this refusal is safe to repeat.
It is raised before the helper touches anything. A timeout is not: the
action may already have happened, and repeating it would click twice.
"""
monkeypatch.setattr(
client_module,
"get_current_computer_use_turn_id",
lambda: "turn-1",
)
class _Timeout(_Transport):
async def request(self, message: dict[str, Any]) -> dict[str, Any]:
self.attempts += 1
raise ComputerUseProtocolError("request_timeout", "too slow")
transport = _Timeout(busy_replies=0)
client = ComputerUseClient(
"session-1",
transport_factory=lambda: transport,
)
client._observation_id = "observation-1"
with pytest.raises(ComputerUseProtocolError) as failure:
await client.execute("click", {})
assert failure.value.code == "request_timeout"
assert transport.attempts == 1, "a timeout must be reported, not repeated"
@pytest.mark.asyncio
async def test_user_intervention_is_a_retryable_soft_refusal(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The recency guard's refusal must not tear down the connection.
Removing the post-approval exemption means an action right after an
approval can be refused as ``user_intervention``. The design relies on that
being recoverable: the caller observes again and reissues once the grace
has passed. So it has to surface as a plain action-level error on a live
connection -- not discard the transport the way a broken pipe would, or the
retry would pay for a fresh connect every time.
"""
monkeypatch.setattr(
client_module,
"get_current_computer_use_turn_id",
lambda: "turn-1",
)
class _Intervene(_Transport):
def __init__(self) -> None:
super().__init__(busy_replies=0)
self.methods: list[str] = []
async def request(self, message: dict[str, Any]) -> dict[str, Any]:
self.attempts += 1
self.methods.append(message["method"])
if self.attempts == 1:
raise ComputerUseProtocolError(
"user_intervention",
"Recent user input was detected; observe again.",
)
if message["method"] == "observe_window":
return {
"protocol_version": message["protocol_version"],
"request_id": message["request_id"],
"ok": True,
"result": {"observation_id": "observation-2"},
}
assert message["params"]["observation_id"] == "observation-2"
return {
"protocol_version": message["protocol_version"],
"request_id": message["request_id"],
"ok": True,
"result": {"done": True},
}
transport = _Intervene()
client = ComputerUseClient(
"session-1",
transport_factory=lambda: transport,
)
client._observation_id = "observation-1"
with pytest.raises(ComputerUseProtocolError) as refusal:
await client.execute("click", {})
assert refusal.value.code == "user_intervention"
# The connection is intact: not closed, and not retried behind the caller's
# back -- a soft refusal, not a transport failure.
assert transport.closed is False
assert transport.attempts == 1
# The caller observes again and reissues with the fresh observation on the
# same connection; it works.
observed = await client.execute(
"observe_window",
{"window_id": "window-1"},
)
result = await client.execute("click", {})
assert observed == {}
assert result == {"done": True}
assert transport.methods == ["click", "observe_window", "click"]
assert transport.attempts == 3
@@ -0,0 +1,129 @@
# -*- coding: utf-8 -*-
"""How the feature switch reads a state file it cannot trust.
The switch decides whether desktop automation is allowed at all. Its default
applies to an installation that has never chosen -- not to one whose recorded
choice has become unreadable, where reading it as on would restore access the
user may have deliberately withdrawn.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
import pytest
import computer_use.dispatch as dispatch_module
from computer_use.dispatch import computer_use
from computer_use.feature_state import ComputerUseFeatureState
def test_a_fresh_installation_starts_from_the_default(tmp_path: Path) -> None:
state = ComputerUseFeatureState(tmp_path / "absent.json")
assert state.is_enabled() is True
def test_a_recorded_choice_is_honoured(tmp_path: Path) -> None:
path = tmp_path / "state.json"
path.write_text(json.dumps({"enabled": False}), encoding="utf-8")
assert ComputerUseFeatureState(path).is_enabled() is False
path.write_text(json.dumps({"enabled": True}), encoding="utf-8")
assert ComputerUseFeatureState(path).is_enabled() is True
def test_an_unparseable_file_is_not_read_as_enabled(
tmp_path: Path,
caplog: pytest.LogCaptureFixture,
) -> None:
"""The case that matters: a file exists, so a choice was made.
Which choice cannot be recovered, and the one that must not be invented is
the permissive one.
"""
path = tmp_path / "state.json"
path.write_text("{ this is not json", encoding="utf-8")
with caplog.at_level(logging.WARNING):
assert ComputerUseFeatureState(path).is_enabled() is False
assert "unreadable" in caplog.text
def test_a_file_without_the_flag_is_not_read_as_enabled(
tmp_path: Path,
) -> None:
path = tmp_path / "state.json"
path.write_text(json.dumps({"something_else": 1}), encoding="utf-8")
assert ComputerUseFeatureState(path).is_enabled() is False
def test_a_non_boolean_flag_is_not_coerced(tmp_path: Path) -> None:
"""``bool("false")`` is True, which is the wrong way to be wrong."""
path = tmp_path / "state.json"
path.write_text(json.dumps({"enabled": "false"}), encoding="utf-8")
assert ComputerUseFeatureState(path).is_enabled() is False
def test_turning_it_off_survives_a_reload(tmp_path: Path) -> None:
path = tmp_path / "state.json"
ComputerUseFeatureState(path).set_enabled(False)
assert ComputerUseFeatureState(path).is_enabled() is False
# And back on again, so the round trip is covered in both directions.
ComputerUseFeatureState(path).set_enabled(True)
assert ComputerUseFeatureState(path).is_enabled() is True
def _first_text_block(response) -> dict:
for block in response.content:
if getattr(block, "type", None) == "text":
return json.loads(block.text)
raise AssertionError("tool response has no text block")
@pytest.mark.asyncio
async def test_dispatch_blocks_actions_while_disabled(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
state = ComputerUseFeatureState(tmp_path / "feature_state.json")
state.set_enabled(False)
monkeypatch.setattr(
dispatch_module,
"get_computer_use_feature_state",
lambda: state,
)
def _unexpected_client():
raise AssertionError("disabled feature must not touch the client")
monkeypatch.setattr(
dispatch_module,
"get_computer_use_client",
_unexpected_client,
)
payload = _first_text_block(await computer_use(action="list_apps"))
assert payload["ok"] is False
assert payload["error"]["code"] == "feature_disabled"
@pytest.mark.asyncio
async def test_dispatch_allows_wait_while_enabled(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
state = ComputerUseFeatureState(tmp_path / "feature_state.json")
monkeypatch.setattr(
dispatch_module,
"get_computer_use_feature_state",
lambda: state,
)
payload = _first_text_block(await computer_use(action="wait", wait_ms=0))
assert payload["ok"] is True
assert payload["action"] == "wait"
@@ -0,0 +1,181 @@
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Turning the feature off has to reach every session, not just one.
Off is the global kill switch. A session left waiting on an approval would be
granted access later and act on a desktop the user had already switched the
feature off for -- so the switch has to refuse all of them, including sessions
the person flipping it was never looking at.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import pytest
from computer_use import client as client_module
from computer_use import router as router_module
@dataclass
class _Pending:
request_id: str
session_id: str
@dataclass
class _ApprovalService:
"""Stands in for the host's approval service, per session."""
pending: dict[str, list[_Pending]]
resolved: list[str] = field(default_factory=list)
async def list_pending_by_session(
self,
session_id: str,
include_subagents: bool = True, # pylint: disable=unused-argument
) -> list[_Pending]:
return list(self.pending.get(session_id, ()))
async def resolve_request(self, request_id: str, _decision) -> object:
self.resolved.append(request_id)
for items in self.pending.values():
items[:] = [
item for item in items if item.request_id != request_id
]
return object()
@pytest.mark.asyncio
async def test_switching_off_refuses_every_waiting_session(
monkeypatch: pytest.MonkeyPatch,
) -> None:
service = _ApprovalService(
pending={
"session-a": [_Pending("approval-a", "session-a")],
"session-b": [_Pending("approval-b", "session-b")],
},
)
monkeypatch.setattr(router_module, "get_approval_service", lambda: service)
monkeypatch.setattr(
router_module,
"_is_computer_use_pending",
lambda _item: True,
)
# Both sessions hold a client, which is how a pending approval reaches
# here.
monkeypatch.setattr(
router_module,
"known_computer_use_sessions",
lambda: ["session-a", "session-b"],
)
stopped: list[bool] = []
async def _stop_all() -> int:
# Recorded to pin the order: the release has to be signalled before
# anything waits on the actions it is releasing.
stopped.append(bool(service.resolved))
return 2
monkeypatch.setattr(
router_module,
"stop_all_computer_use_turns",
_stop_all,
)
feature = _FeatureState()
monkeypatch.setattr(
router_module,
"get_computer_use_feature_state",
lambda: feature,
)
result = await _call_feature_off(session_id="session-a")
assert result["enabled"] is False
# Both, not only the session named in the request.
assert sorted(service.resolved) == ["approval-a", "approval-b"]
assert stopped == [
True,
], "approvals must be denied before turns are reaped"
@pytest.mark.asyncio
async def test_switching_off_covers_a_session_with_no_client_yet(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The caller's own session counts even if it holds no client."""
service = _ApprovalService(
pending={"session-new": [_Pending("approval-new", "session-new")]},
)
monkeypatch.setattr(router_module, "get_approval_service", lambda: service)
monkeypatch.setattr(
router_module,
"_is_computer_use_pending",
lambda _item: True,
)
monkeypatch.setattr(
router_module,
"known_computer_use_sessions",
lambda: [],
)
async def _stop_all() -> int:
return 0
monkeypatch.setattr(
router_module,
"stop_all_computer_use_turns",
_stop_all,
)
feature = _FeatureState()
monkeypatch.setattr(
router_module,
"get_computer_use_feature_state",
lambda: feature,
)
await _call_feature_off(session_id="session-new")
assert service.resolved == ["approval-new"]
def test_the_session_list_comes_from_the_client_cache(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(
client_module,
"_clients",
{"one": object(), "two": object()},
)
assert sorted(client_module.known_computer_use_sessions()) == [
"one",
"two",
]
class _FeatureState:
def __init__(self) -> None:
self.enabled = True
def set_enabled(self, value: bool) -> None:
self.enabled = value
def is_enabled(self) -> bool:
return self.enabled
async def _call_feature_off(session_id: str | None) -> dict:
"""Invoke the /feature route function directly, off the HTTP stack."""
router = router_module.build_router()
route = next(
item
for item in router.routes
if getattr(item, "path", "") == "/feature"
)
request = router_module.FeatureToggleRequest(
enabled=False,
session_id=session_id,
)
return await route.endpoint(request)
@@ -0,0 +1,40 @@
# -*- coding: utf-8 -*-
"""Tests for the plugin manifest's declared QwenPaw compatibility range."""
import json
from pathlib import Path
from qwenpaw._version_compat import check_plugin_version_compat
from qwenpaw.plugins.architecture import PluginManifest
_MANIFEST = (
Path(__file__).resolve().parents[4]
/ "plugins"
/ "bundle"
/ "computer-use"
/ "plugin.json"
)
_FRONTEND_BUNDLE = _MANIFEST.parent / "dist" / "index.js"
def _manifest() -> PluginManifest:
# The real manifest is the subject: a test fixture would pass while the
# shipped file stays wrong.
return PluginManifest(**json.loads(_MANIFEST.read_text(encoding="utf-8")))
def test_built_frontend_embeds_the_manifest_version():
version = json.loads(_MANIFEST.read_text(encoding="utf-8"))["version"]
bundle = _FRONTEND_BUNDLE.read_text(encoding="utf-8")
assert f'"{version}"' in bundle, (
f"frontend bundle does not embed manifest version {version}; "
"rebuild it with `npm run build`"
)
def test_the_running_qwenpaw_is_inside_the_declared_range():
# The loader disables a plugin whose range excludes the running version, so
# this failing means the plugin ships dead on the current tree.
compatible, message = check_plugin_version_compat(_manifest())
assert compatible, message
@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
"""Tests for plugin-local Computer Use application access decisions."""
from computer_use import access
def _request(
*,
session_id: str = "session-1",
app_id: str = "win32:contoso.editor",
):
return access.AppApprovalRequest(
request_id="native-request-1",
session_id=session_id,
canonical_app_id=app_id,
display_name="Contoso Editor",
identity_evidence={"path": "C:/Editor.exe"},
)
def test_session_decision_is_scoped_to_session_and_application():
access_store = access.ComputerUseAccessStore()
request = _request()
assert access_store.resolve(request) is None
access_store.record_session(request, allowed=True)
assert access_store.resolve(request) == access.AppAccessDecision(
True,
"session",
)
assert access_store.resolve(_request(session_id="session-2")) is None
assert access_store.resolve(_request(app_id="win32:other")) is None
def test_persistent_allow_survives_a_new_plugin_store(tmp_path):
path = tmp_path / "app_access.json"
request = _request()
access_store = access.ComputerUseAccessStore(path)
access_store.record_persistent(
request.canonical_app_id,
request.display_name,
)
reloaded_store = access.ComputerUseAccessStore(path)
assert reloaded_store.resolve(
_request(session_id="session-2"),
) == access.AppAccessDecision(True, "persistent")
assert reloaded_store.list_persistent() == [
access.PersistentAppAccess(
canonical_app_id=request.canonical_app_id,
display_name=request.display_name,
),
]
assert reloaded_store.revoke_persistent(request.canonical_app_id)
assert access.ComputerUseAccessStore(path).resolve(request) is None
def test_process_app_id_spellings_share_one_decision():
# launch_app reports an extended-length path, while window discovery
# reports a plain lowercase drive path. Both denote one application and
# must resolve to a single approval instead of prompting twice.
access_store = access.ComputerUseAccessStore()
launched = _request(
app_id=r"process:\\?\C:\Windows\System32\notepad.exe",
)
discovered = _request(
app_id=r"process:c:\windows\system32\notepad.exe",
)
access_store.record_session(launched, allowed=True)
assert access_store.resolve(discovered) == access.AppAccessDecision(
True,
"session",
)
@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-
"""Tests for how the plugin seeds its tool into agent configurations."""
# The seeding helper is module-private on purpose; exercising it directly is
# the point of these tests.
# pylint: disable=protected-access
from types import SimpleNamespace
import plugin
def _agent_config(tools=None):
return SimpleNamespace(tools=tools)
def test_a_missing_entry_is_seeded_enabled():
agent_config = _agent_config()
assert plugin._seed_tool_config(agent_config) is True
tool_config = agent_config.tools.builtin_tools["computer_use"]
assert tool_config.enabled is True
def test_an_explicitly_disabled_entry_is_respected():
# The user turned the tool off for this agent; a plugin restart must
# not silently turn it back on.
agent_config = _agent_config()
plugin._seed_tool_config(agent_config)
agent_config.tools.builtin_tools["computer_use"].enabled = False
assert plugin._seed_tool_config(agent_config) is False
assert agent_config.tools.builtin_tools["computer_use"].enabled is False
def test_an_enabled_entry_is_not_rewritten():
agent_config = _agent_config()
plugin._seed_tool_config(agent_config)
assert plugin._seed_tool_config(agent_config) is False
assert agent_config.tools.builtin_tools["computer_use"].enabled is True
@@ -0,0 +1,168 @@
# -*- coding: utf-8 -*-
"""The method vocabulary has to mean the same thing on both sides of the wire.
The adapter and the native helper are written in different languages and share
no build step, so their agreement rests on two lists of strings staying in
step.
Nothing catches a drift: a method only one side knows fails at run time as an
unsupported operation, on whichever machine happens to try it.
Both sides state their vocabulary as a single declaration that the code
enforces rather than describes, and this compares the two. Reading a
declaration matters: an earlier version of this file parsed the helper's
dispatch, and reported a method as unhandled the first time two match arms were
grouped -- the code was right and the test was wrong, which is how a suite
teaches people to ignore it.
"""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from computer_use.protocol import (
NATIVE_METHODS,
PROTOCOL_VERSION,
ComputerUseProtocolError,
NativeRequest,
)
from qwenpaw.app.computer_use import COMPUTER_USE_PROTOCOL_VERSION
_SERVER = (
Path(__file__).resolve().parents[4]
/ "console"
/ "src-tauri"
/ "src"
/ "computer_use_server"
)
_DISPATCH = _SERVER / "dispatch.rs"
_PROTOCOL = _SERVER.parent / "computer_use_protocol.rs"
_PLUGIN_PROTOCOL = (
Path(__file__).resolve().parents[4]
/ "plugins"
/ "bundle"
/ "computer-use"
/ "computer_use"
/ "protocol.py"
)
# A method the helper answers but the adapter never sends. Listed rather than
# ignored, so unused protocol surface stays visible instead of accumulating.
_HELPER_ONLY: frozenset[str] = frozenset()
def _rust_string_array(name: str) -> set[str]:
"""Read a `const NAME: &[&str] = [...]` declaration from the helper.
Bounded to the literal's own brackets, so nothing after it is picked up.
"""
source = _DISPATCH.read_text(encoding="utf-8")
match = re.search(
rf"const {name}: &\[&str\] = &\[(.*?)\];",
source,
re.S,
)
assert match, f"{name} should be declared in dispatch.rs"
return set(re.findall(r'"([a-z_]+)"', match.group(1)))
def _methods_the_helper_serves() -> set[str]:
"""The helper's declared vocabulary, which its dispatch admits against."""
served = _rust_string_array("SERVED_METHODS")
assert served, "the helper should declare the methods it serves"
return served
def test_the_helper_serves_every_method_the_adapter_sends() -> None:
served = _methods_the_helper_serves()
missing = sorted(NATIVE_METHODS - served)
assert not missing, (
f"the adapter sends {missing}, which the helper does not serve; they "
"would fail as unsupported operations"
)
def test_the_helper_serves_nothing_the_adapter_has_forgotten() -> None:
"""The other direction: surface the helper answers but nobody asks for.
Not a failure in itself, but it has to be deliberate. Anything unexpected
here is either a method the adapter stopped sending -- dead protocol -- or
one it should be sending and does not.
"""
unused = sorted(
_methods_the_helper_serves() - NATIVE_METHODS - _HELPER_ONLY,
)
assert not unused, (
f"the helper serves {unused}, which nothing sends; either wire it up "
"or remove it"
)
def test_the_guarded_set_is_a_subset_of_the_vocabulary() -> None:
"""Every guarded method must be a method that actually exists."""
source = _DISPATCH.read_text(encoding="utf-8")
after = source.split("fn changes_window_state")[1]
# Stop at the function's closing brace, or the file's own tests below would
# be read as part of the predicate.
body = after.split("\n}")[0]
guarded = set(re.findall(r'"([a-z_]+)"', body))
assert guarded, "the predicate should list the guarded methods"
assert guarded <= NATIVE_METHODS, sorted(guarded - NATIVE_METHODS)
def test_all_components_speak_the_same_protocol_version() -> None:
"""The independently installed components must reject contract drift.
A mismatch is caught at run time as a refused handshake, so it cannot go
unnoticed -- but it would be noticed by whoever is holding the machine,
after a build and an install. Cheaper to notice here.
"""
source = _PROTOCOL.read_text(encoding="utf-8")
match = re.search(r"const VERSION: u64 = (\d+);", source)
assert match, "the helper should declare its protocol version"
plugin_source = _PLUGIN_PROTOCOL.read_text(encoding="utf-8")
plugin_match = re.search(
r"^PROTOCOL_VERSION = (\d+)$",
plugin_source,
re.M,
)
assert plugin_match, "the plugin should own its expected protocol version"
assert {
int(match.group(1)),
int(plugin_match.group(1)),
COMPUTER_USE_PROTOCOL_VERSION,
} == {PROTOCOL_VERSION}
def test_a_method_outside_the_vocabulary_never_reaches_the_wire() -> None:
"""The vocabulary is enforced where requests are serialized.
Otherwise the constant would be documentation, and a typo would travel to
the helper and come back as an unsupported operation.
"""
request = NativeRequest(
method="press_keys",
params={},
session_id="session",
turn_id="turn",
deadline_ms=1000,
)
with pytest.raises(ComputerUseProtocolError) as refusal:
request.to_message()
assert refusal.value.code == "invalid_request"
def test_every_declared_method_serializes() -> None:
# The handshake is written directly by the transports rather than built as
# a NativeRequest, but it is part of the same vocabulary.
for method in sorted(NATIVE_METHODS):
message = NativeRequest(
method=method,
params={},
session_id="session",
turn_id="turn",
deadline_ms=1000,
).to_message()
assert message["method"] == method
@@ -0,0 +1,72 @@
# -*- coding: utf-8 -*-
"""Whether Computer Use reports itself usable, and on what grounds.
The desktop shell offers a control endpoint on every platform it runs on, but
the native helper is built only for Windows and macOS. Treating the endpoint as
the whole answer registered the tool on Linux, where every call could do
nothing
but report the runtime unavailable.
"""
from __future__ import annotations
import pytest
from qwenpaw.app.computer_use import runtime as runtime_module
from qwenpaw.app.computer_use.runtime import HostRuntimeProvider, RuntimeStatus
_CONTROL_ENV = {
"QWENPAW_COMPUTER_USE_CONTROL_HOST": "127.0.0.1",
"QWENPAW_COMPUTER_USE_CONTROL_PORT": "51234",
"QWENPAW_COMPUTER_USE_CONTROL_TOKEN": "token",
}
@pytest.fixture(autouse=True)
def _reachable_host(monkeypatch: pytest.MonkeyPatch):
"""Present a reachable desktop host, so only the platform varies."""
for name, value in _CONTROL_ENV.items():
monkeypatch.setenv(name, value)
monkeypatch.setattr(HostRuntimeProvider, "_capability", None)
yield
monkeypatch.setattr(HostRuntimeProvider, "_capability", None)
@pytest.mark.parametrize("platform", ["win32", "darwin"])
def test_a_platform_with_a_helper_is_available(
monkeypatch: pytest.MonkeyPatch,
platform: str,
) -> None:
monkeypatch.setattr(runtime_module.sys, "platform", platform)
status = HostRuntimeProvider.status()
assert status == RuntimeStatus(
supported_platform=True,
host_reachable=True,
)
assert HostRuntimeProvider.is_available() is True
@pytest.mark.parametrize("platform", ["linux", "freebsd"])
def test_a_platform_without_a_helper_is_not_available(
monkeypatch: pytest.MonkeyPatch,
platform: str,
) -> None:
monkeypatch.setattr(runtime_module.sys, "platform", platform)
status = HostRuntimeProvider.status()
# The host is reachable, and that used to be the entire test.
assert status.host_reachable is True
assert status.supported_platform is False
assert HostRuntimeProvider.is_available() is False
def test_a_supported_platform_without_a_host_is_not_available(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Reported apart, so a caller can say which precondition is missing."""
monkeypatch.setattr(runtime_module.sys, "platform", "win32")
for name in _CONTROL_ENV:
monkeypatch.delenv(name, raising=False)
status = HostRuntimeProvider.status()
assert status.supported_platform is True
assert status.host_reachable is False
assert HostRuntimeProvider.is_available() is False
@@ -0,0 +1,100 @@
# -*- coding: utf-8 -*-
"""Tests for the guards that keep shared tool state from being corrupted."""
# Both guards are module-private on purpose; exercising them directly is the
# point of these tests.
# pylint: disable=protected-access
import threading
from computer_use import access as access_module
from computer_use import client as client_module
from computer_use import dispatch
from computer_use.protocol import ComputerUseProtocolError
def test_the_rate_limit_cap_holds_under_concurrent_callers():
# The host runs one event loop per workspace, each on its own thread, so
# the limiter is reached from several threads at once. This pins the
# invariant -- the cap is never exceeded -- rather than the mechanism:
# under the GIL the unguarded read-modify-write is narrow enough that it
# cannot be made to overshoot here, but that is a property of the current
# interpreter, not of the code, and a free-threaded build removes it.
dispatch._action_times.clear()
refused = []
barrier = threading.Barrier(8)
def call() -> None:
barrier.wait()
for _ in range(20):
try:
dispatch._check_rate_limit()
except ComputerUseProtocolError as error:
refused.append(error)
return
threads = [threading.Thread(target=call) for _ in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert len(dispatch._action_times) == dispatch._MAX_ACTIONS_PER_MINUTE
assert refused
def test_the_client_cache_evicts_idle_sessions_when_full(monkeypatch):
class _Idle:
has_active_turn = False
class _Busy:
has_active_turn = True
cache = {
f"idle-{index}": _Idle()
for index in range(
client_module._MAX_CACHED_CLIENTS - 1,
)
}
cache["busy"] = _Busy()
monkeypatch.setattr(client_module, "_clients", cache)
client_module._evict_idle_clients()
# The cache was at capacity, so idle sessions are dropped until it is not.
assert len(cache) < client_module._MAX_CACHED_CLIENTS
# A session with a turn in flight is never evicted: its client owns the
# turn id needed to end that turn.
assert "busy" in cache
def test_the_client_cache_leaves_room_untouched_below_capacity(monkeypatch):
class _Idle:
has_active_turn = False
cache = {"one": _Idle(), "two": _Idle()}
monkeypatch.setattr(client_module, "_clients", cache)
client_module._evict_idle_clients()
assert set(cache) == {"one", "two"}
def test_the_access_store_is_a_single_shared_instance(monkeypatch):
# Concurrent first-callers on different threads must all receive the same
# store; without the double-checked lock two could each build one and half
# the callers would read from an instance the other half never writes to.
monkeypatch.setattr(access_module, "_access_store", None)
seen = []
barrier = threading.Barrier(8)
def acquire() -> None:
barrier.wait()
seen.append(access_module.get_computer_use_access_store())
threads = [threading.Thread(target=acquire) for _ in range(8)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert len({id(store) for store in seen}) == 1
@@ -0,0 +1,259 @@
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Per-turn Computer Use stopping without terminating the shared helper."""
from __future__ import annotations
import asyncio
import threading
from collections.abc import Mapping
from typing import Any
import pytest
from computer_use.client import ComputerUseClient
from computer_use.protocol import ComputerUseProtocolError
from computer_use.transport import (
ComputerUseTransport,
ReverseRequestHandler,
)
from qwenpaw.app.computer_use import set_current_computer_use_turn_id
class _ControlledTransport(ComputerUseTransport):
"""Hold ordinary requests until the test chooses their native outcome."""
def __init__(self) -> None:
self.closed = False
self.requests: list[dict[str, Any]] = []
self._pending: list[
tuple[dict[str, Any], asyncio.Future[dict[str, Any]]]
] = []
async def connect(self) -> None:
return None
async def request(self, message: Mapping[str, Any]) -> dict[str, Any]:
payload = dict(message)
self.requests.append(payload)
if payload["method"] == "end_turn":
return self._response(payload, {})
future: asyncio.Future[
dict[str, Any]
] = asyncio.get_running_loop().create_future()
self._pending.append((payload, future))
return await future
async def close(self) -> None:
self.closed = True
for _, future in self._pending:
if not future.done():
future.set_exception(
ComputerUseProtocolError(
"runtime_disconnected",
"Computer Use connection closed.",
),
)
self._pending.clear()
def set_reverse_request_handler(
self,
handler: ReverseRequestHandler,
) -> None:
return None
@property
def pending_count(self) -> int:
return len(self._pending)
def complete_next(self, result: dict[str, Any] | None = None) -> None:
payload, future = self._pending.pop(0)
future.set_result(self._response(payload, result or {}))
@staticmethod
def _response(
request: Mapping[str, Any],
result: Mapping[str, Any],
) -> dict[str, Any]:
return {
"protocol_version": request["protocol_version"],
"request_id": request["request_id"],
"ok": True,
"result": dict(result),
}
@pytest.mark.asyncio
async def test_stop_marks_before_waiting_for_the_current_action() -> None:
transport = _ControlledTransport()
client = ComputerUseClient("session-stop", lambda: transport)
set_current_computer_use_turn_id("turn-stop")
try:
action = asyncio.create_task(client.execute("observe_window", {}))
await wait_for_pending(transport)
stopping = asyncio.create_task(client.stop_turn())
await asyncio.sleep(0)
assert client._stopped_turn == "turn-stop"
assert (
not stopping.done()
), "stop should let the dispatched action settle"
transport.complete_next()
with pytest.raises(ComputerUseProtocolError) as failure:
await action
assert failure.value.code == "turn_stopped"
assert await stopping is True
assert transport.closed is False
assert [request["method"] for request in transport.requests] == [
"observe_window",
"end_turn",
]
finally:
set_current_computer_use_turn_id(None)
@pytest.mark.asyncio
async def test_a_request_queued_before_stop_cannot_cross_the_lock() -> None:
transport = _ControlledTransport()
client = ComputerUseClient("session-queued", lambda: transport)
set_current_computer_use_turn_id("turn-queued")
try:
current = asyncio.create_task(client.execute("observe_window", {}))
await wait_for_pending(transport)
queued = asyncio.create_task(client.execute("list_windows", {}))
stopping = asyncio.create_task(client.stop_turn())
await asyncio.sleep(0)
transport.complete_next()
for task in (current, queued):
with pytest.raises(ComputerUseProtocolError) as failure:
await task
assert failure.value.code == "turn_stopped"
assert await stopping is True
assert [request["method"] for request in transport.requests] == [
"observe_window",
"end_turn",
]
finally:
set_current_computer_use_turn_id(None)
@pytest.mark.asyncio
async def test_stopping_one_client_does_not_close_another_connection() -> None:
first_transport = _ControlledTransport()
second_transport = _ControlledTransport()
first = ComputerUseClient("session-a", lambda: first_transport)
second = ComputerUseClient("session-b", lambda: second_transport)
set_current_computer_use_turn_id("turn-shared")
try:
first_action = asyncio.create_task(first.execute("observe_window", {}))
second_action = asyncio.create_task(
second.execute("observe_window", {}),
)
await wait_for_pending(first_transport)
await wait_for_pending(second_transport)
stopping = asyncio.create_task(first.stop_turn())
first_transport.complete_next()
with pytest.raises(ComputerUseProtocolError):
await first_action
assert await stopping is True
second_transport.complete_next({"observation_id": "observation-b"})
assert await second_action == {}
assert first_transport.closed is False
assert second_transport.closed is False
finally:
set_current_computer_use_turn_id(None)
@pytest.mark.asyncio
async def test_a_later_turn_is_not_refused_by_an_earlier_stop() -> None:
transport = _ControlledTransport()
client = ComputerUseClient("session-later", lambda: transport)
set_current_computer_use_turn_id("turn-a")
try:
action = asyncio.create_task(client.execute("observe_window", {}))
await wait_for_pending(transport)
stopping = asyncio.create_task(client.stop_turn())
transport.complete_next()
with pytest.raises(ComputerUseProtocolError):
await action
assert await stopping is True
set_current_computer_use_turn_id("turn-b")
following = asyncio.create_task(client.execute("observe_window", {}))
await wait_for_pending(transport)
transport.complete_next({"observation_id": "observation-b"})
assert await following == {}
finally:
set_current_computer_use_turn_id(None)
def test_stop_arriving_on_another_event_loop_is_handed_back() -> None:
owner_loop = asyncio.new_event_loop()
ready = threading.Event()
def run_owner() -> None:
asyncio.set_event_loop(owner_loop)
ready.set()
owner_loop.run_forever()
thread = threading.Thread(target=run_owner, name="owner-loop", daemon=True)
thread.start()
ready.wait(timeout=5)
transport = _ControlledTransport()
client = ComputerUseClient("session-cross", lambda: transport)
async def start_action() -> asyncio.Task[Any]:
set_current_computer_use_turn_id("turn-cross")
return asyncio.create_task(client.execute("observe_window", {}))
action = asyncio.run_coroutine_threadsafe(
start_action(),
owner_loop,
).result(5)
asyncio.run_coroutine_threadsafe(
wait_for_pending(transport),
owner_loop,
).result(5)
caller_loop = asyncio.new_event_loop()
released = threading.Event()
def release_after_stop_mark() -> None:
for _ in range(5_000):
if client._stopped_turn == "turn-cross":
owner_loop.call_soon_threadsafe(transport.complete_next)
released.set()
return
threading.Event().wait(0.001)
releaser = threading.Thread(target=release_after_stop_mark, daemon=True)
releaser.start()
try:
stopped = caller_loop.run_until_complete(
asyncio.wait_for(client.stop_turn(), timeout=5),
)
assert stopped is True
assert released.wait(timeout=5)
with pytest.raises(ComputerUseProtocolError):
action.result()
assert transport.closed is False
finally:
releaser.join(timeout=5)
owner_loop.call_soon_threadsafe(owner_loop.stop)
thread.join(timeout=5)
caller_loop.close()
owner_loop.close()
set_current_computer_use_turn_id(None)
async def wait_for_pending(transport: _ControlledTransport) -> None:
for _ in range(1_000):
if transport.pending_count:
return
await asyncio.sleep(0)
raise AssertionError("transport did not receive a request")
@@ -0,0 +1,169 @@
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Retiring a turn, and the cache bound that depends on it.
The host mints a turn id per request and nothing retired it, so a session that
used the tool once kept its turn, its connection and the helper's per-turn
state
indefinitely. That also made the cache bound unreachable, because a client
holding a turn is never evicted. These tests hold both halves.
"""
from __future__ import annotations
import asyncio
from collections.abc import Mapping
from typing import Any
import pytest
from computer_use import client as client_module
from computer_use.client import (
ComputerUseClient,
end_computer_use_turn,
get_computer_use_client,
)
from computer_use.protocol import ComputerUseProtocolError
from computer_use.transport import (
ComputerUseTransport,
ReverseRequestHandler,
)
from qwenpaw.app import agent_context
from qwenpaw.app.computer_use import set_current_computer_use_turn_id
class _RecordingTransport(ComputerUseTransport):
def __init__(self) -> None:
self.methods: list[str] = []
self.closed = False
async def connect(self) -> None:
return None
async def request(self, message: Mapping[str, Any]) -> dict[str, Any]:
payload = dict(message)
self.methods.append(str(payload["method"]))
return {"request_id": payload["request_id"], "ok": True, "result": {}}
async def close(self) -> None:
self.closed = True
def set_reverse_request_handler(
self,
_handler: ReverseRequestHandler,
) -> None:
return None
@pytest.mark.asyncio
async def test_ending_a_turn_tells_the_helper_and_frees_the_client() -> None:
transport = _RecordingTransport()
client = ComputerUseClient("session-turn", lambda: transport)
set_current_computer_use_turn_id("turn-1")
try:
await client.execute("observe_window", {})
assert client.has_active_turn is True
assert await client.end_turn() is True
# The helper is told, so it can drop that turn's screenshots and
# accessibility handles rather than hold them for a turn nobody will
# mention again.
assert "end_turn" in transport.methods
# And the client no longer claims a turn, which is what lets the cache
# ever evict it.
assert client.has_active_turn is False
# The connection stays: the next turn will want it.
assert transport.closed is False
finally:
set_current_computer_use_turn_id(None)
@pytest.mark.asyncio
async def test_ending_a_turn_is_harmless_when_there_is_none() -> None:
# The hook runs on every request, including those that never touched the
# tool, so a session with no client or no turn must be a quiet no-op.
assert await end_computer_use_turn("session-never-used") is False
transport = _RecordingTransport()
client = ComputerUseClient("session-idle", lambda: transport)
assert await client.end_turn() is False
@pytest.mark.asyncio
async def test_the_cache_refuses_rather_than_growing_past_its_bound(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A bound that a busy session can walk past is not a bound.
Eviction only drops clients with no turn in flight, so before turns were
retired every cached client counted as busy and the cache grew without
limit, each entry holding a connection.
"""
monkeypatch.setattr(client_module, "_clients", {})
monkeypatch.setattr(client_module, "_MAX_CACHED_CLIENTS", 3)
busy = []
for index in range(3):
session = f"busy-{index}"
transport = _RecordingTransport()
held = ComputerUseClient(session, lambda t=transport: t)
set_current_computer_use_turn_id(f"turn-{index}")
await held.execute("observe_window", {})
client_module._clients[session] = held
busy.append(held)
assert all(held.has_active_turn for held in busy)
monkeypatch.setattr(
agent_context,
"get_current_session_id",
lambda: "newcomer",
)
monkeypatch.setattr(client_module, "get_tool_session_id", lambda: "")
try:
with pytest.raises(ComputerUseProtocolError) as refusal:
get_computer_use_client()
assert refusal.value.code == "too_many_sessions"
assert len(client_module._clients) == 3
# Retiring one turn makes room, the way finishing a request does.
await busy[0].end_turn()
admitted = get_computer_use_client()
assert admitted is client_module._clients["newcomer"]
finally:
set_current_computer_use_turn_id(None)
@pytest.mark.asyncio
async def test_an_evicted_client_has_its_connection_closed(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Dropping the reference alone would leave the pipe or socket open."""
monkeypatch.setattr(client_module, "_clients", {})
monkeypatch.setattr(client_module, "_MAX_CACHED_CLIENTS", 1)
transport = _RecordingTransport()
idle = ComputerUseClient("idle-session", lambda: transport)
set_current_computer_use_turn_id("turn-idle")
try:
await idle.execute("observe_window", {})
await idle.end_turn()
client_module._clients["idle-session"] = idle
monkeypatch.setattr(
agent_context,
"get_current_session_id",
lambda: "next",
)
monkeypatch.setattr(client_module, "get_tool_session_id", lambda: "")
get_computer_use_client()
assert "idle-session" not in client_module._clients
# Closing is handed to the loop that owns the transport rather than
# awaited under the cache lock, so it lands a little later.
for _ in range(100):
if transport.closed:
break
await asyncio.sleep(0.01)
assert transport.closed is True
finally:
set_current_computer_use_turn_id(None)
@@ -0,0 +1,375 @@
# -*- coding: utf-8 -*-
"""Regression tests for the overlapped Windows pipe transport.
Every test here deadlocks or hangs forever with the pre-fix synchronous pipe
handle, so they guard the overlapped I/O rework directly.
"""
# Nested helpers shadow the fixture name on purpose, and the fake handlers
# accept the arguments of the real signature without reading them all.
# pylint: disable=redefined-outer-name, unused-argument
from __future__ import annotations
import asyncio
import contextvars
import ctypes
import json
import os
import struct
import threading
import time
import uuid
from ctypes import wintypes
from typing import Any
import pytest
from computer_use.protocol import ComputerUseProtocolError
from computer_use.transport.windows_pipe import (
WindowsPipeTransport,
_kernel32,
)
from qwenpaw.app.computer_use.runtime import (
COMPUTER_USE_PROTOCOL_VERSION,
RuntimeCapability,
)
pytestmark = pytest.mark.skipif(
os.name != "nt",
reason="Windows named pipes only",
)
_PIPE_ACCESS_DUPLEX = 0x00000003
_PIPE_TYPE_BYTE = 0x00000000
_PIPE_WAIT = 0x00000000
class _MockHelper:
"""Minimal in-process stand-in for the native computer-use helper."""
def __init__(self) -> None:
suffix = uuid.uuid4().hex[:8]
self.pipe_name = f"qwenpaw-cu-test-{os.getpid()}-{suffix}"
self.secret = "test-secret"
self.stop_reading = threading.Event()
self._ready = threading.Event()
def start(self) -> None:
thread = threading.Thread(
target=self._serve,
name="mock-helper",
daemon=True,
)
thread.start()
assert self._ready.wait(5), "mock helper pipe did not appear"
def _serve(self) -> None:
kernel32 = _kernel32()
kernel32.CreateNamedPipeW.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.DWORD,
wintypes.DWORD,
wintypes.DWORD,
wintypes.DWORD,
wintypes.DWORD,
wintypes.LPVOID,
]
kernel32.CreateNamedPipeW.restype = wintypes.HANDLE
kernel32.ConnectNamedPipe.argtypes = [wintypes.HANDLE, wintypes.LPVOID]
kernel32.ConnectNamedPipe.restype = wintypes.BOOL
kernel32.DisconnectNamedPipe.argtypes = [wintypes.HANDLE]
kernel32.DisconnectNamedPipe.restype = wintypes.BOOL
path = f"\\\\.\\pipe\\{self.pipe_name}"
while True:
hpipe = kernel32.CreateNamedPipeW(
path,
_PIPE_ACCESS_DUPLEX,
_PIPE_TYPE_BYTE | _PIPE_WAIT,
1,
65536,
4096,
0,
None,
)
self._ready.set()
kernel32.ConnectNamedPipe(hpipe, None)
try:
self._serve_connection(kernel32, hpipe)
finally:
kernel32.DisconnectNamedPipe(hpipe)
kernel32.CloseHandle(hpipe)
def _serve_connection(self, kernel32, hpipe) -> None:
while True:
header = self._read_fully(kernel32, hpipe, 4)
if header is None:
return
size = struct.unpack("<I", header)[0]
body = self._read_fully(kernel32, hpipe, size)
if body is None:
return
message = json.loads(body.decode("utf-8"))
method = message.get("method")
request_id = message.get("request_id")
result: dict[str, Any]
if method == "hello":
result = {"protocol_version": COMPUTER_USE_PROTOCOL_VERSION}
elif method == "list_apps":
result = {"apps": []}
elif method == "delayed":
time.sleep(0.1)
result = {"done": True}
elif method == "no_reply":
continue
elif method == "needs_approval":
reverse = {
"request_id": f"approval-{request_id}",
"method": "request_app_approval",
"params": {
"canonical_app_id": "process:test.exe",
"display_name": "Test App",
"identity_evidence": {},
"risk": "low",
"warning": "",
},
"meta": message.get("meta"),
"protocol_version": COMPUTER_USE_PROTOCOL_VERSION,
}
self._write_frame(kernel32, hpipe, reverse)
reply = self._read_message(kernel32, hpipe)
if reply is None:
return
decision = (reply.get("result") or {}).get("decision")
result = {"approved": decision == "allow"}
elif method == "stop_reading":
self._reply(kernel32, hpipe, request_id, {"stopped": True})
self.stop_reading.set()
while self.stop_reading.is_set():
time.sleep(0.05)
return # client is gone by now
else:
continue
self._reply(kernel32, hpipe, request_id, result)
def _read_message(self, kernel32, hpipe) -> dict | None:
header = self._read_fully(kernel32, hpipe, 4)
if header is None:
return None
body = self._read_fully(
kernel32,
hpipe,
struct.unpack("<I", header)[0],
)
if body is None:
return None
return json.loads(body.decode("utf-8"))
@staticmethod
def _read_fully(kernel32, hpipe, size: int) -> bytes | None:
chunks: list[bytes] = []
remaining = size
while remaining:
buffer = ctypes.create_string_buffer(remaining)
read = wintypes.DWORD(0)
ok = kernel32.ReadFile(
hpipe,
buffer,
remaining,
ctypes.byref(read),
None,
)
if not ok or not read.value:
return None
chunks.append(buffer.raw[: read.value])
remaining -= read.value
return b"".join(chunks)
def _reply(self, kernel32, hpipe, request_id, result: dict) -> None:
self._write_frame(
kernel32,
hpipe,
{"request_id": request_id, "ok": True, "result": result},
)
@staticmethod
def _write_frame(kernel32, hpipe, message: dict) -> None:
payload = json.dumps(message, separators=(",", ":")).encode("utf-8")
data = struct.pack("<I", len(payload)) + payload
written = wintypes.DWORD(0)
kernel32.WriteFile(hpipe, data, len(data), ctypes.byref(written), None)
@pytest.fixture()
def mock_helper():
helper = _MockHelper()
helper.start()
yield helper
helper.stop_reading.clear()
def _request(
method: str,
params: dict | None = None,
deadline: int = 10000,
) -> dict:
return {
"request_id": uuid.uuid4().hex,
"method": method,
"params": params or {},
"meta": {
"session_id": "test",
"turn_id": "test",
"deadline_ms": deadline,
},
"protocol_version": COMPUTER_USE_PROTOCOL_VERSION,
}
def _transport(helper: _MockHelper) -> WindowsPipeTransport:
capability = RuntimeCapability(
helper.pipe_name,
helper.secret,
COMPUTER_USE_PROTOCOL_VERSION,
)
return WindowsPipeTransport(capability)
_session_var: contextvars.ContextVar[str] = contextvars.ContextVar(
"cu_test_session",
default="",
)
def test_reverse_request_inherits_request_context(
mock_helper: _MockHelper,
) -> None:
"""The approval coroutine must see the requesting task's contextvars.
Before the fix, run_coroutine_threadsafe copied the reader thread's
bare context, so session contextvars were lost and every reverse
approval was denied with source=session_mismatch.
"""
seen: list[str] = []
async def handler(message: dict) -> dict:
seen.append(_session_var.get())
return {"allowed": True, "source": "session"}
async def run() -> None:
transport = _transport(mock_helper)
transport.set_reverse_request_handler(handler)
await asyncio.wait_for(transport.connect(), 5)
_session_var.set("session-ctx")
response = await transport.request(_request("needs_approval"))
assert response.get("ok")
assert response.get("result", {}).get("approved") is True
await transport.close()
asyncio.run(run())
assert seen == ["session-ctx"]
def test_slow_approval_pauses_request_deadline(
mock_helper: _MockHelper,
) -> None:
"""Waiting for the user's approval must not consume the deadline.
The helper blocks serving the request until the approval reply, so
a user slower than deadline_ms used to fail it with request_timeout
before the approval could ever be granted.
"""
async def handler(message: dict) -> dict:
await asyncio.sleep(2.0) # user is slower than the 1s deadline
return {"allowed": True, "source": "session"}
async def run() -> None:
transport = _transport(mock_helper)
transport.set_reverse_request_handler(handler)
await asyncio.wait_for(transport.connect(), 5)
response = await transport.request(
_request("needs_approval", deadline=1000),
)
assert response.get("ok")
assert response.get("result", {}).get("approved") is True
await transport.close()
asyncio.run(run())
def test_connect_handshake_does_not_deadlock(mock_helper: _MockHelper) -> None:
async def run() -> None:
transport = _transport(mock_helper)
await asyncio.wait_for(transport.connect(), 5)
response = await transport.request(_request("list_apps"))
assert response.get("ok")
await transport.close()
asyncio.run(run())
def test_concurrent_requests_while_reader_parked(
mock_helper: _MockHelper,
) -> None:
async def run() -> None:
transport = _transport(mock_helper)
await asyncio.wait_for(transport.connect(), 5)
requests = [transport.request(_request("delayed")) for _ in range(5)]
responses = await asyncio.gather(*requests)
assert all(response.get("ok") for response in responses)
await transport.close()
asyncio.run(run())
def test_response_timeout_keeps_connection(mock_helper: _MockHelper) -> None:
async def run() -> None:
transport = _transport(mock_helper)
await asyncio.wait_for(transport.connect(), 5)
with pytest.raises(ComputerUseProtocolError, match="timed out"):
await transport.request(_request("no_reply", deadline=1000))
response = await transport.request(_request("list_apps"))
assert response.get("ok")
await transport.close()
asyncio.run(run())
def test_close_cancels_parked_reader(mock_helper: _MockHelper) -> None:
async def run() -> None:
transport = _transport(mock_helper)
await asyncio.wait_for(transport.connect(), 5)
# The reader thread is parked in ReadFile; close must stay fast.
start = time.monotonic()
await transport.close()
assert time.monotonic() - start < 2
with pytest.raises(ComputerUseProtocolError):
await transport.request(_request("list_apps"))
asyncio.run(run())
def test_write_timeout_closes_connection(mock_helper: _MockHelper) -> None:
async def run() -> None:
transport = _transport(mock_helper)
await asyncio.wait_for(transport.connect(), 5)
response = await transport.request(_request("stop_reading"))
assert response.get("ok")
# The helper never drains the pipe, so this frame exceeds the
# buffer and the write stalls until _WRITE_TIMEOUT_MS kicks in.
big = _request(
"list_apps",
params={"blob": "x" * 1_000_000},
deadline=30000,
)
start = time.monotonic()
with pytest.raises(ComputerUseProtocolError, match="timed out"):
await transport.request(big)
assert time.monotonic() - start < 20
# A partial frame may be on the wire: the connection must be poisoned.
with pytest.raises(ComputerUseProtocolError):
await transport.request(_request("list_apps"))
asyncio.run(run())
@@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
"""Tests for the CloudPaw mission prompt patch."""
import importlib.util
import sys
import types
from pathlib import Path
def _load_mission_prompts(monkeypatch):
"""Load mission prompts without importing the full qwenpaw package."""
for package_name in (
"qwenpaw",
"qwenpaw.modes",
"qwenpaw.modes.mission",
):
package = types.ModuleType(package_name)
package.__path__ = []
monkeypatch.setitem(sys.modules, package_name, package)
prompts_path = (
Path(__file__).parents[3]
/ "src"
/ "qwenpaw"
/ "modes"
/ "mission"
/ "prompts.py"
)
spec = importlib.util.spec_from_file_location(
"qwenpaw.modes.mission.prompts",
prompts_path,
)
assert spec is not None
assert spec.loader is not None
mission_prompts = importlib.util.module_from_spec(spec)
monkeypatch.setitem(
sys.modules,
"qwenpaw.modes.mission.prompts",
mission_prompts,
)
spec.loader.exec_module(mission_prompts)
mission_handler = types.ModuleType("qwenpaw.modes.mission.handler")
mission_handler.build_master_prompt = mission_prompts.build_master_prompt
monkeypatch.setitem(
sys.modules,
"qwenpaw.modes.mission.handler",
mission_handler,
)
return mission_prompts, mission_handler
def test_mission_patch_accepts_upstream_prompt_kwargs(monkeypatch):
"""Both patched prompt paths accept the upstream mission kwargs."""
mission_prompts, mission_handler = _load_mission_prompts(monkeypatch)
from plugins.bundle.cloudpaw.hooks import _patch_mission_master_prompt
_patch_mission_master_prompt()
prompt_kwargs = {
"loop_dir": "/tmp/mission-loop",
"verification_instructions": "Check the regression scenario.",
"max_retries_per_story": 7,
}
default_prompt = mission_prompts.build_master_prompt(
agent_id="default",
**prompt_kwargs,
)
cloudpaw_prompt = mission_handler.build_master_prompt(
agent_id="cloud-orchestrator",
**prompt_kwargs,
)
assert "Check the regression scenario." in default_prompt
assert "Max 7 retries per story" in default_prompt
assert "Check the regression scenario." in cloudpaw_prompt
assert cloudpaw_prompt
+130
View File
@@ -0,0 +1,130 @@
# -*- coding: utf-8 -*-
"""Unit tests for src/qwenpaw/plugins/download_catalog.py."""
from __future__ import annotations
from qwenpaw.plugins.download_catalog import _is_entry_compatible
def test_entry_with_qwenpaw_version_compatible() -> None:
entry = {
"id": "demo",
"version": "1.0.0",
# Exclusive upper bound: current 2.1.0b1 is treated as 2.1.0.
"qwenpaw_version": {"min": "1.1.6", "max": "2.2.0"},
}
assert _is_entry_compatible(entry) is True
def test_entry_with_qwenpaw_version_max_ignored() -> None:
"""Declared max must not exclude a newer running QwenPaw."""
entry = {
"id": "demo",
"version": "1.0.0",
"qwenpaw_version": {"min": "0.1.0", "max": "1.1.0"},
}
assert _is_entry_compatible(entry) is True
def test_entry_with_only_min_compatible() -> None:
entry = {
"id": "demo",
"version": "1.0.0",
# Derived exclusive max is 2.2.0 for min 2.1.0.
"qwenpaw_version": {"min": "2.1.0"},
}
assert _is_entry_compatible(entry) is True
def test_entry_with_only_min_incompatible() -> None:
entry = {
"id": "demo",
"version": "1.0.0",
"qwenpaw_version": {"min": "3.0.0"},
}
assert _is_entry_compatible(entry) is False
def test_entry_without_version_constraints_is_compatible() -> None:
entry = {
"id": "demo",
"version": "1.0.0",
}
assert _is_entry_compatible(entry) is True
def test_entry_with_malformed_qwenpaw_version_falls_to_legacy() -> None:
"""Non-dict qwenpaw_version falls back to min_version/max_version."""
entry = {
"id": "demo",
"version": "1.0.0",
"qwenpaw_version": "not-a-dict",
"min_version": "1.0.0",
"max_version": "2.2.0",
}
assert _is_entry_compatible(entry) is True
def test_entry_with_malformed_qwenpaw_version_no_legacy() -> None:
"""Non-dict qwenpaw_version with no legacy fields is compatible."""
entry = {
"id": "demo",
"version": "1.0.0",
"qwenpaw_version": "not-a-dict",
}
assert _is_entry_compatible(entry) is True
def test_legacy_min_version_compatible() -> None:
"""Legacy min_version within range is compatible."""
entry = {
"id": "demo",
"version": "1.0.0",
"min_version": "2.1.0",
}
assert _is_entry_compatible(entry) is True
def test_legacy_min_version_incompatible() -> None:
"""Legacy min_version above current QwenPaw is incompatible."""
entry = {
"id": "demo",
"version": "1.0.0",
"min_version": "3.0.0",
}
assert _is_entry_compatible(entry) is False
def test_legacy_min_max_version_compatible() -> None:
"""Legacy min+max still loads when min is satisfied (max ignored)."""
entry = {
"id": "demo",
"version": "1.0.0",
"min_version": "1.0.0",
"max_version": "2.2.0",
}
assert _is_entry_compatible(entry) is True
def test_legacy_max_version_ignored() -> None:
"""Legacy max_version alone must not make an entry incompatible."""
entry = {
"id": "demo",
"version": "1.0.0",
"min_version": "0.1.0",
"max_version": "1.0.0",
}
assert _is_entry_compatible(entry) is True
def test_entry_with_empty_dict_qwenpaw_version() -> None:
"""Empty dict qwenpaw_version triggers compat check with defaults."""
entry = {
"id": "demo",
"version": "1.0.0",
"qwenpaw_version": {},
}
# Empty dict is isinstance(dict) but has no min/max, should
# still pass through PluginManifest validation or fallback gracefully
result = _is_entry_compatible(entry)
assert isinstance(result, bool)
@@ -0,0 +1,293 @@
# -*- coding: utf-8 -*-
# pylint: disable=wrong-import-position
"""Unit tests for scripts/pack/generate_plugin_metadata.py."""
from __future__ import annotations
import json
import sys
import zipfile
from pathlib import Path
import pytest
# Add scripts/pack to the path so we can import the module
sys.path.insert(
0,
str(
Path(__file__).resolve().parent.parent.parent.parent
/ "scripts"
/ "pack",
),
)
from generate_plugin_metadata import ( # noqa: E402
_iter_tree_relpaths,
_normalize_pack_exclude,
_validate_declared_entries,
_zip_plugin,
get_version,
)
def test_structured_qwenpaw_version_passthrough() -> None:
manifest = {"qwenpaw_version": {"min": "1.1.6", "max": "2.1.0"}}
assert get_version(manifest) == {"min": "1.1.6", "max": "2.1.0"}
def test_structured_qwenpaw_version_only_min() -> None:
manifest = {"qwenpaw_version": {"min": "2.0.0"}}
assert get_version(manifest) == {"min": "2.0.0"}
def test_structured_qwenpaw_version_strips_leading_v() -> None:
manifest = {"qwenpaw_version": {"min": "v1.0.0", "max": "v2.0.0"}}
assert get_version(manifest) == {"min": "1.0.0", "max": "2.0.0"}
def test_structured_qwenpaw_version_strips_whitespace() -> None:
manifest = {"qwenpaw_version": {"min": " 1.0.0 ", "max": " 2.0.0\t"}}
assert get_version(manifest) == {"min": "1.0.0", "max": "2.0.0"}
def test_legacy_min_and_max() -> None:
manifest = {"min_version": "1.1.0", "max_version": "2.0.0"}
assert get_version(manifest) == {"min": "1.1.0", "max": "2.0.0"}
def test_legacy_only_min() -> None:
manifest = {"min_version": "1.1.0"}
assert get_version(manifest) == {"min": "1.1.0"}
def test_legacy_only_max() -> None:
manifest = {"max_version": "2.0.0"}
assert get_version(manifest) == {"max": "2.0.0"}
def test_legacy_strips_leading_v() -> None:
manifest = {"min_version": "v1.0.0", "max_version": "V2.0.0"}
assert get_version(manifest) == {"min": "1.0.0", "max": "2.0.0"}
def test_legacy_strips_whitespace() -> None:
manifest = {"min_version": " 1.0.0 ", "max_version": "\t2.0.0 "}
assert get_version(manifest) == {"min": "1.0.0", "max": "2.0.0"}
def test_no_constraints_returns_none() -> None:
manifest = {"id": "demo", "version": "1.0.0"}
assert get_version(manifest) is None
def test_non_dict_qwenpaw_version_falls_to_legacy() -> None:
"""Non-dict qwenpaw_version is ignored; falls back to min/max."""
manifest = {
"qwenpaw_version": "invalid",
"min_version": "1.0.0",
}
assert get_version(manifest) == {"min": "1.0.0"}
def test_non_dict_qwenpaw_version_no_legacy_returns_none() -> None:
manifest = {"qwenpaw_version": "invalid"}
assert get_version(manifest) is None
def test_prerelease_version_string_in_legacy() -> None:
"""Pre-release suffix like '1.0.0-rc1' passes through as-is."""
manifest = {"min_version": "1.0.0-rc1", "max_version": "2.0.0-beta"}
assert get_version(manifest) == {
"min": "1.0.0-rc1",
"max": "2.0.0-beta",
}
def test_extra_keys_in_qwenpaw_version_ignored() -> None:
"""Only 'min' and 'max' keys are retained."""
manifest = {
"qwenpaw_version": {
"min": "1.0.0",
"max": "2.0.0",
"note": "should be ignored",
},
}
assert get_version(manifest) == {"min": "1.0.0", "max": "2.0.0"}
# --- pack_exclude ---------------------------------------------------------
def _make_plugin_tree(root: Path) -> Path:
"""Create a plugin dir with runtime files and dev-only files."""
plugin_dir = root / "demo-plugin"
files = [
"plugin.json",
"requirements.txt",
"backend/main.py",
"backend/api/router.py",
"backend/tests/test_api.py",
"backend/pytest.ini",
"e2e/test_shell.py",
"ui/dist/index.js",
"ui/src/App.tsx",
"ui/package.json",
]
for rel in files:
path = plugin_dir / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("x", encoding="utf-8")
return plugin_dir
def _demo_manifest() -> dict:
return {
"id": "demo-plugin",
"version": "1.0.0",
"entry": {
"backend": "backend/main.py",
"frontend": "ui/dist/index.js",
},
"pack_exclude": [
"backend/tests",
"backend/pytest.ini",
"e2e",
"ui/src",
"ui/package.json",
],
}
def test_normalize_pack_exclude_missing_returns_empty() -> None:
assert not _normalize_pack_exclude({})
def test_normalize_pack_exclude_non_list_ignored() -> None:
assert not _normalize_pack_exclude({"pack_exclude": "backend/tests"})
def test_normalize_pack_exclude_strips_slashes_and_backslashes() -> None:
manifest = {"pack_exclude": ["e2e/", "ui\\src", "/scripts"]}
assert _normalize_pack_exclude(manifest) == [
"e2e",
"ui/src",
"scripts",
]
def test_normalize_pack_exclude_drops_traversal_and_empty() -> None:
manifest = {"pack_exclude": ["../secrets", "a/../../b", "", "."]}
assert not _normalize_pack_exclude(manifest)
def test_iter_tree_relpaths_prunes_pack_exclude(tmp_path: Path) -> None:
plugin_dir = _make_plugin_tree(tmp_path)
rels = _iter_tree_relpaths(plugin_dir, _demo_manifest())
assert "backend/main.py" in rels
assert "backend/api/router.py" in rels
assert "ui/dist/index.js" in rels
assert "plugin.json" in rels
assert "backend/tests/test_api.py" not in rels
assert "backend/pytest.ini" not in rels
assert "e2e/test_shell.py" not in rels
assert "ui/src/App.tsx" not in rels
assert "ui/package.json" not in rels
def test_pack_exclude_never_drops_manifest_or_entries(
tmp_path: Path,
) -> None:
"""plugin.json and entry files survive even a hostile pack_exclude."""
plugin_dir = _make_plugin_tree(tmp_path)
manifest = _demo_manifest()
manifest["pack_exclude"] = [
"plugin.json",
"backend/main.py",
"ui/dist/index.js",
]
rels = _iter_tree_relpaths(plugin_dir, manifest)
assert "plugin.json" in rels
assert "backend/main.py" in rels
assert "ui/dist/index.js" in rels
def test_iter_tree_relpaths_are_posix_on_every_platform(
tmp_path: Path,
) -> None:
"""Relpaths never carry a native separator (Windows regression guard)."""
plugin_dir = _make_plugin_tree(tmp_path)
rels = _iter_tree_relpaths(plugin_dir, _demo_manifest())
assert rels
assert not any("\\" in rel for rel in rels)
def test_pack_exclude_exact_prefix_no_sibling_bleed(tmp_path: Path) -> None:
"""'e2e' must not exclude a sibling like 'e2e-extra/'."""
plugin_dir = _make_plugin_tree(tmp_path)
extra = plugin_dir / "e2e-extra" / "keep.py"
extra.parent.mkdir(parents=True)
extra.write_text("x", encoding="utf-8")
rels = _iter_tree_relpaths(plugin_dir, _demo_manifest())
assert "e2e-extra/keep.py" in rels
assert "e2e/test_shell.py" not in rels
def test_zip_plugin_applies_pack_exclude(tmp_path: Path) -> None:
plugin_dir = _make_plugin_tree(tmp_path)
manifest = _demo_manifest()
(plugin_dir / "plugin.json").write_text(
json.dumps(manifest),
encoding="utf-8",
)
out_zip = tmp_path / "out" / "demo-plugin-1.0.0.zip"
_zip_plugin(plugin_dir, out_zip, manifest)
with zipfile.ZipFile(out_zip) as zf:
names = set(zf.namelist())
assert "demo-plugin/backend/main.py" in names
assert "demo-plugin/ui/dist/index.js" in names
assert "demo-plugin/plugin.json" in names
assert not any("backend/tests" in n for n in names)
assert not any("/e2e/" in n for n in names)
assert not any("ui/src" in n for n in names)
def test_validate_declared_entries_rejects_missing_frontend(
tmp_path: Path,
) -> None:
plugin_dir = _make_plugin_tree(tmp_path)
manifest = _demo_manifest()
(plugin_dir / "ui/dist/index.js").unlink()
with pytest.raises(
FileNotFoundError,
match=(
r"cannot package demo-plugin: declared entry file\(s\) "
r"missing: ui/dist/index.js"
),
):
_validate_declared_entries(plugin_dir, manifest)
def test_zip_plugin_missing_entry_leaves_no_artifact(tmp_path: Path) -> None:
plugin_dir = _make_plugin_tree(tmp_path)
manifest = _demo_manifest()
(plugin_dir / "ui/dist/index.js").unlink()
out_zip = tmp_path / "out" / "demo-plugin-1.0.0.zip"
with pytest.raises(FileNotFoundError, match="ui/dist/index.js"):
_zip_plugin(plugin_dir, out_zip, manifest)
assert not out_zip.exists()
def test_zip_plugin_without_manifest_packs_everything(
tmp_path: Path,
) -> None:
"""Backwards compatibility: no manifest arg means no pack_exclude."""
plugin_dir = _make_plugin_tree(tmp_path)
out_zip = tmp_path / "out" / "demo-plugin-1.0.0.zip"
_zip_plugin(plugin_dir, out_zip)
with zipfile.ZipFile(out_zip) as zf:
names = set(zf.namelist())
assert "demo-plugin/backend/tests/test_api.py" in names
assert "demo-plugin/ui/src/App.tsx" in names
+141
View File
@@ -0,0 +1,141 @@
# -*- coding: utf-8 -*-
# pylint: disable=protected-access,redefined-outer-name,unnecessary-lambda,unused-argument # noqa: E501
"""Unit tests for plugins/loader.py helper functions.
Coverage-driven backfill (batch 4, coverage-first per the 2026-08-24
instruction: upstream PRs are only considered after backend_unit coverage
rises by at least 5 percentage points). Target: the plugin loader path /
runtime-dir helpers which previously sat at ~53% coverage.
"""
from __future__ import annotations
import sys
from pathlib import Path
import pytest
import qwenpaw.plugins.loader as pl
@pytest.fixture()
def working_dir(tmp_path, monkeypatch):
wd = tmp_path / "wd"
wd.mkdir()
monkeypatch.setattr("qwenpaw.constant.WORKING_DIR", wd)
return wd
class TestIsFrozen:
def test_not_frozen(self):
assert pl._is_frozen() is False
def test_frozen_flag(self, monkeypatch):
monkeypatch.setattr(sys, "frozen", True, raising=False)
assert pl._is_frozen() is True
class TestDesktopPython:
def test_unset_returns_none(self, monkeypatch):
monkeypatch.delenv("QWENPAW_DESKTOP_PY_RUNTIME", raising=False)
assert pl._desktop_python() is None
def test_blank_returns_none(self, monkeypatch):
monkeypatch.setenv("QWENPAW_DESKTOP_PY_RUNTIME", " ")
assert pl._desktop_python() is None
def test_missing_file_returns_none(self, monkeypatch):
monkeypatch.setenv("QWENPAW_DESKTOP_PY_RUNTIME", "/no/such/python")
assert pl._desktop_python() is None
def test_existing_file_returned(self, tmp_path, monkeypatch):
py = tmp_path / "python"
py.write_text("")
monkeypatch.setenv("QWENPAW_DESKTOP_PY_RUNTIME", str(py))
assert pl._desktop_python() == str(py)
class TestPluginRuntimeDirs:
def test_runtime_dir_under_working_dir(self, working_dir):
assert pl._plugin_runtime_dir() == working_dir / "plugin_runtime"
def test_site_dir_bucketed_and_created(self, working_dir):
site = pl._plugin_site_dir()
assert site.is_dir()
assert site.name == "site"
assert f"py{sys.version_info.major}.{sys.version_info.minor}" in (
str(site)
)
def test_install_lock_path_sanitised(self, working_dir):
lock = pl._install_lock_path("my plugin/id")
assert lock.name == "my_plugin_id.lock"
assert lock.parent == working_dir / "plugin_runtime" / "install-locks"
def test_install_lock_path_simple(self, working_dir):
lock = pl._install_lock_path("demo-1.0")
assert lock.name == "demo-1.0.lock"
class TestNormRealpath:
def test_normalises(self, tmp_path):
assert pl._norm_realpath(tmp_path) == pl._norm_realpath(str(tmp_path))
class TestResolvedPluginManifestPath:
def test_returns_manifest(self, tmp_path):
(tmp_path / "plugin.json").write_text("{}")
result = pl.resolved_plugin_manifest_path(tmp_path)
assert result.name == "plugin.json"
def test_missing_dir_raises(self, tmp_path):
with pytest.raises(FileNotFoundError):
pl.resolved_plugin_manifest_path(tmp_path / "nope")
def test_missing_manifest_raises(self, tmp_path):
with pytest.raises(FileNotFoundError):
pl.resolved_plugin_manifest_path(tmp_path)
def test_symlink_escape_rejected(self, tmp_path):
src = tmp_path / "src"
src.mkdir()
outside = tmp_path / "outside" / "plugin.json"
outside.parent.mkdir()
outside.write_text("{}")
(src / "plugin.json").symlink_to(outside)
with pytest.raises(ValueError, match="escapes"):
pl.resolved_plugin_manifest_path(src)
class TestIsDisabledPluginDir:
def test_hidden_dir_disabled(self):
assert pl._is_disabled_plugin_dir(Path("/x/.git")) is True
def test_disabled_suffix(self):
assert pl._is_disabled_plugin_dir(Path("/x/remote.disabled")) is True
def test_normal_dir_enabled(self):
assert pl._is_disabled_plugin_dir(Path("/x/remote")) is False
class TestEnsurePluginSiteOnPath:
def test_noop_when_not_frozen(self, monkeypatch):
monkeypatch.setattr(pl, "_is_frozen", lambda: False)
pl._ensure_plugin_site_on_path() # must not raise or modify path
def test_adds_site_when_frozen(self, working_dir, monkeypatch):
monkeypatch.setattr(pl, "_is_frozen", lambda: True)
site_dir = pl._plugin_site_dir()
# clean the dir from sys.path so the insertion path is exercised
monkeypatch.setattr(
pl.sys,
"path",
[p for p in pl.sys.path if p != str(site_dir)],
)
import site as _site
adds = []
monkeypatch.setattr(_site, "addsitedir", lambda d: adds.append(d))
pl._ensure_plugin_site_on_path()
assert str(site_dir) in pl.sys.path
assert pl.os.environ.get("QWENPAW_PLUGIN_SITE") == str(site_dir)
@@ -0,0 +1,76 @@
# -*- coding: utf-8 -*-
"""OMP loop UI i18n catalog and CommandSpec metadata wiring."""
from __future__ import annotations
import importlib.util
import sys
from functools import lru_cache
from pathlib import Path
import pytest
_REPO = Path(__file__).resolve().parents[3]
_I18N_PATH = (
_REPO
/ "plugins"
/ "bundle"
/ "omp_workflows"
/ "shared"
/ "loop_ui_i18n.py"
)
@lru_cache(maxsize=1)
def _omp_loop_ui_i18n():
spec = importlib.util.spec_from_file_location(
"omp_loop_ui_i18n",
_I18N_PATH,
)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize(
"mode_key",
["ultrawork", "ralph", "autopilot", "ultraqa", "team"],
)
def test_loop_ui_has_en_and_zh_description(mode_key: str):
mod = _omp_loop_ui_i18n()
ui = mod.loop_ui(mode_key)
assert ui["description"]["en"]
assert ui["description"]["zh-CN"]
assert ui["name"]["en"]
assert mod.loop_help_text(mode_key).startswith("**")
def test_loop_command_metadata_exposes_i18n_maps():
meta = _omp_loop_ui_i18n().loop_command_metadata("ultrawork")
assert meta["loop_name"] == "Ultrawork"
assert "zh-CN" in meta["description_i18n"]
assert "en" in meta["name_i18n"]
def test_as_str_dict_and_catalog_fields():
from qwenpaw.app.routers.loops import LoopModeInfo, _as_str_dict
assert _as_str_dict({"en": "Hi", "zh-CN": "你好"}) == {
"en": "Hi",
"zh-CN": "你好",
}
assert not _as_str_dict("nope")
info = LoopModeInfo(
id="plugin:ultrawork",
name="Ultrawork",
slash_command="ultrawork",
description="help",
source="plugin",
name_i18n={"en": "Ultrawork"},
description_i18n={"zh-CN": "**Ultrawork** — 并行"},
)
desc_i18n = info.description_i18n or {}
assert desc_i18n["zh-CN"].startswith("**Ultrawork**")
@@ -0,0 +1,780 @@
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name,protected-access,import-outside-toplevel
"""Unit tests for plugin API extensions: #8, #10, #16.
Tests cover:
- #8: register_uninstall_hook and its execution during unload_plugin
- #10: Plugin validator uses submodule_search_locations for relative imports
- #16: register_skill_provider API contract
"""
import importlib.util
import sys
import tempfile
import types
from pathlib import Path
from typing import Any, Dict
from unittest.mock import MagicMock
import pytest
# ---------------------------------------------------------------------------
# Stub missing agentscope 2.0 modules so MultiAgentManager can be imported
# in environments where agentscope 2.0 is not installed.
# ---------------------------------------------------------------------------
_AGENTSCOPE_STUBS = [
"agentscope.state",
]
for _mod_name in _AGENTSCOPE_STUBS:
if _mod_name not in sys.modules:
_stub = types.ModuleType(_mod_name)
# Provide placeholder attributes that downstream imports expect.
# type: ignore[attr-defined]
_stub.AgentState = type("AgentState", (), {})
sys.modules[_mod_name] = _stub
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture()
def fresh_registry():
"""Create a fresh PluginRegistry (bypass singleton for test isolation).
.. warning::
This fixture is NOT safe for parallel test execution (e.g.
``pytest-xdist``). It mutates the class-level ``_instance``
attribute without locking. Only use with sequential test runs.
"""
from qwenpaw.plugins.registry import PluginRegistry
# Force a new instance by clearing the singleton
old_instance = PluginRegistry._instance
PluginRegistry._instance = None
registry = PluginRegistry()
yield registry
# Restore
PluginRegistry._instance = old_instance
@pytest.fixture()
def plugin_api(fresh_registry):
"""Create a PluginApi instance with a fresh registry."""
from qwenpaw.plugins.api import PluginApi
api = PluginApi("test-plugin", config={}, manifest={"id": "test-plugin"})
api.set_registry(fresh_registry)
return api
# ---------------------------------------------------------------------------
# #8: register_uninstall_hook
# ---------------------------------------------------------------------------
class TestUninstallHook:
"""Tests for register_uninstall_hook (requirement #8)."""
def test_register_uninstall_hook_stores_in_registry(
self,
plugin_api,
fresh_registry,
):
"""Uninstall hooks are stored in registry after registration."""
callback = MagicMock()
plugin_api.register_uninstall_hook(
hook_name="test_cleanup",
callback=callback,
priority=50,
)
hooks = fresh_registry.get_uninstall_hooks()
assert len(hooks) == 1
assert hooks[0].plugin_id == "test-plugin"
assert hooks[0].hook_name == "test_cleanup"
assert hooks[0].callback is callback
assert hooks[0].priority == 50
def test_uninstall_hooks_sorted_by_priority(
self,
plugin_api,
fresh_registry,
):
"""Multiple uninstall hooks are sorted by priority."""
plugin_api.register_uninstall_hook(
hook_name="low_priority",
callback=MagicMock(),
priority=200,
)
plugin_api.register_uninstall_hook(
hook_name="high_priority",
callback=MagicMock(),
priority=10,
)
hooks = fresh_registry.get_uninstall_hooks()
assert hooks[0].hook_name == "high_priority"
assert hooks[1].hook_name == "low_priority"
def test_uninstall_hooks_cleaned_on_unregister(
self,
plugin_api,
fresh_registry,
):
"""Uninstall hooks are removed when plugin is unregistered."""
plugin_api.register_uninstall_hook(
hook_name="cleanup",
callback=MagicMock(),
)
assert len(fresh_registry.get_uninstall_hooks()) == 1
fresh_registry.unregister_plugin("test-plugin")
assert len(fresh_registry.get_uninstall_hooks()) == 0
@pytest.mark.asyncio
async def test_unload_plugin_calls_uninstall_hooks(self, fresh_registry):
"""PluginLoader.unload_plugin executes uninstall hooks."""
from qwenpaw.plugins.loader import PluginLoader
from qwenpaw.plugins.architecture import (
PluginManifest,
PluginRecord,
PluginEntryPoints,
)
loader = PluginLoader(plugin_dirs=[])
loader.registry = fresh_registry
# Create a fake loaded plugin record
manifest = PluginManifest(
id="test-plugin",
name="Test",
version="1.0.0",
entry=PluginEntryPoints(backend="plugin.py"),
)
record = PluginRecord(
manifest=manifest,
source_path=Path("/fake"),
enabled=True,
instance=None,
)
loader._loaded_plugins["test-plugin"] = record
# Register an uninstall hook
hook_called_with: Dict[str, Any] = {}
def uninstall_callback(plugin_id: str, delete_files: bool):
hook_called_with["plugin_id"] = plugin_id
hook_called_with["delete_files"] = delete_files
fresh_registry.register_uninstall_hook(
plugin_id="test-plugin",
hook_name="test_cleanup",
callback=uninstall_callback,
)
await loader.unload_plugin("test-plugin", delete_files=True)
assert hook_called_with["plugin_id"] == "test-plugin"
assert hook_called_with["delete_files"] is True
@pytest.mark.asyncio
async def test_uninstall_hook_async_callback(self, fresh_registry):
"""Async uninstall hook callbacks are properly awaited."""
from qwenpaw.plugins.loader import PluginLoader
from qwenpaw.plugins.architecture import (
PluginManifest,
PluginRecord,
PluginEntryPoints,
)
loader = PluginLoader(plugin_dirs=[])
loader.registry = fresh_registry
manifest = PluginManifest(
id="async-plugin",
name="Async",
version="1.0.0",
entry=PluginEntryPoints(backend="plugin.py"),
)
record = PluginRecord(
manifest=manifest,
source_path=Path("/fake"),
enabled=True,
instance=None,
)
loader._loaded_plugins["async-plugin"] = record
async_called = []
async def async_cleanup(plugin_id: str, **_kwargs):
async_called.append(plugin_id)
fresh_registry.register_uninstall_hook(
plugin_id="async-plugin",
hook_name="async_cleanup",
callback=async_cleanup,
)
await loader.unload_plugin("async-plugin")
assert "async-plugin" in async_called
@pytest.mark.asyncio
async def test_uninstall_hook_error_isolated(self, fresh_registry):
"""Errors in uninstall hooks don't crash the unload flow."""
from qwenpaw.plugins.loader import PluginLoader
from qwenpaw.plugins.architecture import (
PluginManifest,
PluginRecord,
PluginEntryPoints,
)
loader = PluginLoader(plugin_dirs=[])
loader.registry = fresh_registry
manifest = PluginManifest(
id="err-plugin",
name="Err",
version="1.0.0",
entry=PluginEntryPoints(backend="plugin.py"),
)
record = PluginRecord(
manifest=manifest,
source_path=Path("/fake"),
enabled=True,
instance=None,
)
loader._loaded_plugins["err-plugin"] = record
def bad_hook(**_kwargs):
raise RuntimeError("hook failed")
fresh_registry.register_uninstall_hook(
plugin_id="err-plugin",
hook_name="bad_hook",
callback=bad_hook,
)
# Should not raise
await loader.unload_plugin("err-plugin")
assert "err-plugin" not in loader._loaded_plugins
# ---------------------------------------------------------------------------
# #10: Plugin validator relative import fix
# ---------------------------------------------------------------------------
class TestPluginValidatorImports:
"""Tests for plugin validator import resolution (requirement #10)."""
def test_validator_sets_submodule_search_locations(self):
"""CLI install validator uses submodule_search_locations."""
# Create a temp plugin with relative import
with tempfile.TemporaryDirectory() as tmpdir:
plugin_dir = Path(tmpdir)
# Create plugin.json
import json
manifest = {
"id": "import-test",
"name": "Import Test",
"version": "1.0.0",
"entry": {"backend": "plugin.py"},
}
(plugin_dir / "plugin.json").write_text(
json.dumps(manifest),
encoding="utf-8",
)
# Create a helper module
(plugin_dir / "constants.py").write_text(
"PLUGIN_NAME = 'import-test'\n",
encoding="utf-8",
)
# Create plugin.py that uses relative import
(plugin_dir / "plugin.py").write_text(
"from .constants import PLUGIN_NAME\n"
"\n"
"class Plugin:\n"
" pass\n"
"\n"
"plugin = Plugin()\n",
encoding="utf-8",
)
# Simulate validation with correct submodule_search_locations
backend_path = plugin_dir / "plugin.py"
module_name = "_plugin_validation_import_test"
plugin_dir_str = str(plugin_dir)
spec = importlib.util.spec_from_file_location(
module_name,
backend_path,
submodule_search_locations=[plugin_dir_str],
)
assert spec is not None
assert spec.loader is not None
module = importlib.util.module_from_spec(spec)
module.__package__ = module_name
module.__path__ = [plugin_dir_str]
# Register sub-module mapping so relative imports resolve
sys.modules[module_name] = module
# Also register the constants sub-module path
constants_spec = importlib.util.spec_from_file_location(
f"{module_name}.constants",
plugin_dir / "constants.py",
)
constants_module = importlib.util.module_from_spec(constants_spec)
sys.modules[f"{module_name}.constants"] = constants_module
constants_spec.loader.exec_module(constants_module)
try:
spec.loader.exec_module(module)
assert hasattr(module, "plugin")
assert hasattr(module, "PLUGIN_NAME")
finally:
sys.modules.pop(module_name, None)
sys.modules.pop(f"{module_name}.constants", None)
def test_validator_without_search_locations_fails(self):
"""Without submodule_search_locations, relative imports fail."""
with tempfile.TemporaryDirectory() as tmpdir:
plugin_dir = Path(tmpdir)
(plugin_dir / "constants.py").write_text(
"PLUGIN_NAME = 'test'\n",
encoding="utf-8",
)
(plugin_dir / "plugin.py").write_text(
"from .constants import PLUGIN_NAME\n",
encoding="utf-8",
)
backend_path = plugin_dir / "plugin.py"
module_name = "_plugin_validation_no_locations"
# Without submodule_search_locations — should fail
spec = importlib.util.spec_from_file_location(
module_name,
backend_path,
)
module = importlib.util.module_from_spec(spec)
# Don't set __package__ or __path__
sys.modules[module_name] = module
try:
with pytest.raises(ImportError):
spec.loader.exec_module(module)
finally:
sys.modules.pop(module_name, None)
def test_cli_validate_path_with_relative_import(self):
"""Exercise the actual CLI validation code path.
Calls validate_plugin_module (the real implementation used by
both 'install' and 'validate' commands) to prove that relative
imports work end-to-end, including sys.modules registration
before exec_module, cleanup in finally, and sanitized module
name from plugin_id with hyphens.
"""
from qwenpaw.plugins.validation import validate_plugin_module
with tempfile.TemporaryDirectory() as tmpdir:
plugin_dir = Path(tmpdir) / "my-datapaw"
plugin_dir.mkdir()
(plugin_dir / "helpers.py").write_text(
"HELPER_VALUE = 42\n",
encoding="utf-8",
)
(plugin_dir / "plugin.py").write_text(
"from .helpers import HELPER_VALUE\n"
"\n"
"class Plugin:\n"
" pass\n"
"\n"
"plugin = Plugin()\n",
encoding="utf-8",
)
# Should succeed without raising
validate_plugin_module("my-datapaw", plugin_dir, "plugin.py")
# Verify sys.modules was cleaned up (no leaking)
leaked = [
k
for k in sys.modules
if k.startswith("_plugin_validation_my_datapaw")
]
assert leaked == [], f"Leaked modules: {leaked}"
def test_cli_validate_cleans_sys_modules_on_error(self):
"""sys.modules cleanup happens even when validation fails."""
from qwenpaw.plugins.validation import validate_plugin_module
with tempfile.TemporaryDirectory() as tmpdir:
plugin_dir = Path(tmpdir) / "bad-plugin"
plugin_dir.mkdir()
# Plugin that imports a non-existent module
(plugin_dir / "plugin.py").write_text(
"from .nonexistent import MISSING\n",
encoding="utf-8",
)
with pytest.raises(ImportError):
validate_plugin_module(
"bad-plugin",
plugin_dir,
"plugin.py",
)
# Verify cleanup still happened
leaked = [
k
for k in sys.modules
if k.startswith("_plugin_validation_bad_plugin")
]
assert leaked == [], f"Leaked modules: {leaked}"
# ---------------------------------------------------------------------------
# #16: register_skill_provider
# ---------------------------------------------------------------------------
class TestRegisterSkillProvider:
"""Tests for register_skill_provider API (requirement #16)."""
def test_register_skill_provider_registers_hooks(
self,
plugin_api,
fresh_registry,
):
"""register_skill_provider registers startup and uninstall hooks."""
with tempfile.TemporaryDirectory() as tmpdir:
skills_dir = Path(tmpdir)
# Create a fake skill
skill_dir = skills_dir / "my-skill"
skill_dir.mkdir()
(skill_dir / "SKILL.md").write_text(
"---\nname: My Skill\n---\nDo something.",
encoding="utf-8",
)
plugin_api.register_skill_provider(
skills_dir=skills_dir,
enabled_by_default=True,
channels=["all"],
)
# Check startup hook registered
startup_hooks = fresh_registry.get_startup_hooks()
startup_names = [h.hook_name for h in startup_hooks]
assert "install_skills_test-plugin" in startup_names
# Check uninstall hook registered
uninstall_hooks = fresh_registry.get_uninstall_hooks()
uninstall_names = [h.hook_name for h in uninstall_hooks]
assert "uninstall_skills_test-plugin" in uninstall_names
def test_register_skill_provider_default_channels(
self,
plugin_api,
fresh_registry,
):
"""Default channels is ['all'] when not specified."""
with tempfile.TemporaryDirectory() as tmpdir:
skills_dir = Path(tmpdir)
skill_dir = skills_dir / "default-skill"
skill_dir.mkdir()
(skill_dir / "SKILL.md").write_text(
"---\nname: Default\n---\nHello.",
encoding="utf-8",
)
plugin_api.register_skill_provider(skills_dir=skills_dir)
# Verify startup hook is registered (integration correctness)
hooks = fresh_registry.get_startup_hooks()
assert any(h.hook_name == "install_skills_test-plugin" for h in hooks)
def test_register_skill_provider_source_tag(self, plugin_api):
"""Source tag follows 'plugin:{id}' convention."""
# Verify internal source_tag format
expected_tag = "plugin:test-plugin"
assert expected_tag == f"plugin:{plugin_api.plugin_id}"
def test_register_skill_provider_registers_workspace_created_hook(
self,
plugin_api,
fresh_registry,
):
"""register_skill_provider also registers a workspace_created hook."""
with tempfile.TemporaryDirectory() as tmpdir:
skills_dir = Path(tmpdir)
skill_dir = skills_dir / "auto-skill"
skill_dir.mkdir()
(skill_dir / "SKILL.md").write_text(
"---\nname: Auto Skill\n---\nAuto.",
encoding="utf-8",
)
plugin_api.register_skill_provider(
skills_dir=skills_dir,
enabled_by_default=True,
channels=["all"],
)
hooks = fresh_registry.get_workspace_created_hooks()
hook_names = [h.hook_name for h in hooks]
assert "provision_skills_test-plugin" in hook_names
# ---------------------------------------------------------------------------
# workspace_created hook infrastructure
# ---------------------------------------------------------------------------
class TestWorkspaceCreatedHook:
"""Tests for workspace_created hook registration and dispatch."""
def test_register_workspace_created_hook_stores_in_registry(
self,
plugin_api,
fresh_registry,
):
"""workspace_created hooks are stored in registry."""
callback = MagicMock()
plugin_api.register_workspace_created_hook(
hook_name="on_ws_created",
callback=callback,
priority=50,
)
hooks = fresh_registry.get_workspace_created_hooks()
assert len(hooks) == 1
assert hooks[0].plugin_id == "test-plugin"
assert hooks[0].hook_name == "on_ws_created"
assert hooks[0].callback is callback
assert hooks[0].priority == 50
# ---------------------------------------------------------------------------
# _fire_workspace_created_hooks: sync / async dispatch
# ---------------------------------------------------------------------------
class TestFireWorkspaceCreatedHooks:
"""Tests for async _fire_workspace_created_hooks dispatch logic."""
@pytest.mark.asyncio
async def test_sync_callback_offloaded_to_thread(
self,
plugin_api,
):
"""Sync callbacks are executed via asyncio.to_thread (non-blocking)."""
invoked_with = {}
def sync_hook(workspace_info: dict) -> None:
invoked_with.update(workspace_info)
plugin_api.register_workspace_created_hook(
hook_name="sync_hook",
callback=sync_hook,
)
from qwenpaw.app.multi_agent_manager import MultiAgentManager
await MultiAgentManager._fire_workspace_created_hooks(
{"agent_id": "a1", "workspace_dir": "/tmp/ws"},
)
assert invoked_with == {
"agent_id": "a1",
"workspace_dir": "/tmp/ws",
}
@pytest.mark.asyncio
async def test_async_callback_awaited(
self,
plugin_api,
):
"""Async callbacks are directly awaited."""
invoked_with = {}
async def async_hook(workspace_info: dict) -> None:
invoked_with.update(workspace_info)
plugin_api.register_workspace_created_hook(
hook_name="async_hook",
callback=async_hook,
)
from qwenpaw.app.multi_agent_manager import MultiAgentManager
await MultiAgentManager._fire_workspace_created_hooks(
{"agent_id": "a2", "workspace_dir": "/tmp/ws2"},
)
assert invoked_with == {
"agent_id": "a2",
"workspace_dir": "/tmp/ws2",
}
@pytest.mark.asyncio
async def test_hook_error_does_not_block_subsequent_hooks(
self,
plugin_api,
):
"""A failing hook does not prevent later hooks from running."""
results = []
def failing_hook(_info: dict) -> None:
raise RuntimeError("boom")
def good_hook(_info: dict) -> None:
results.append("ok")
plugin_api.register_workspace_created_hook(
hook_name="fail_first",
callback=failing_hook,
priority=10,
)
plugin_api.register_workspace_created_hook(
hook_name="succeed_second",
callback=good_hook,
priority=20,
)
from qwenpaw.app.multi_agent_manager import MultiAgentManager
await MultiAgentManager._fire_workspace_created_hooks(
{"agent_id": "a3", "workspace_dir": "/tmp/ws3"},
)
assert results == ["ok"]
def test_workspace_created_hooks_sorted_by_priority(
self,
plugin_api,
fresh_registry,
):
"""Multiple workspace_created hooks are sorted by priority."""
plugin_api.register_workspace_created_hook(
hook_name="low_prio",
callback=MagicMock(),
priority=200,
)
plugin_api.register_workspace_created_hook(
hook_name="high_prio",
callback=MagicMock(),
priority=10,
)
hooks = fresh_registry.get_workspace_created_hooks()
assert hooks[0].hook_name == "high_prio"
assert hooks[1].hook_name == "low_prio"
def test_workspace_created_hooks_cleaned_on_unregister(
self,
plugin_api,
fresh_registry,
):
"""workspace_created hooks are removed when plugin is unregistered."""
plugin_api.register_workspace_created_hook(
hook_name="provision",
callback=MagicMock(),
)
assert len(fresh_registry.get_workspace_created_hooks()) == 1
fresh_registry.unregister_plugin("test-plugin")
assert len(fresh_registry.get_workspace_created_hooks()) == 0
@pytest.mark.asyncio
async def test_fire_workspace_created_hooks_calls_callbacks(
self,
fresh_registry,
):
"""_fire_workspace_created_hooks invokes registered callbacks."""
from qwenpaw.plugins.api import PluginApi
from qwenpaw.app.multi_agent_manager import MultiAgentManager
api = PluginApi(
"hook-plugin",
config={},
manifest={"id": "hook-plugin"},
)
api.set_registry(fresh_registry)
received_info: Dict[str, Any] = {}
def on_created(workspace_info):
received_info.update(workspace_info)
api.register_workspace_created_hook(
hook_name="test_hook",
callback=on_created,
)
workspace_info = {
"agent_id": "agent-42",
"workspace_dir": "/tmp/ws/agent-42",
}
await MultiAgentManager._fire_workspace_created_hooks(workspace_info)
assert received_info["agent_id"] == "agent-42"
assert received_info["workspace_dir"] == "/tmp/ws/agent-42"
@pytest.mark.asyncio
async def test_fire_workspace_created_hooks_error_isolation(
self,
fresh_registry,
):
"""Errors in one hook don't prevent subsequent hooks from running."""
from qwenpaw.plugins.api import PluginApi
from qwenpaw.app.multi_agent_manager import MultiAgentManager
api = PluginApi(
"err-plugin",
config={},
manifest={"id": "err-plugin"},
)
api.set_registry(fresh_registry)
second_called = []
def bad_hook(workspace_info):
raise RuntimeError("boom")
def good_hook(workspace_info):
second_called.append(workspace_info["agent_id"])
api.register_workspace_created_hook(
hook_name="bad",
callback=bad_hook,
priority=10,
)
api.register_workspace_created_hook(
hook_name="good",
callback=good_hook,
priority=20,
)
# Should not raise
await MultiAgentManager._fire_workspace_created_hooks(
{
"agent_id": "ws-1",
"workspace_dir": "/tmp/ws-1",
},
)
assert "ws-1" in second_called
@@ -0,0 +1,361 @@
# -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""Per-plugin lifecycle lock serializes load/unload/reinstall."""
from __future__ import annotations
import asyncio
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from qwenpaw.app.routers.plugins import (
_finish_plugin_install_after_load,
_tool_names_from_meta,
)
from qwenpaw.governance.tool_registry import (
DEFAULT_REGISTRY,
register_tool_governance,
)
from qwenpaw.plugins.api import (
_TOOL_PLUGIN_OWNERS,
release_tool_ownership_for_plugin,
)
from qwenpaw.plugins.architecture import (
PluginEntryPoints,
PluginManifest,
PluginRecord,
)
from qwenpaw.plugins.loader import (
PluginLoader,
_norm_realpath,
resolved_plugin_manifest_path,
)
from qwenpaw.plugins.registry import PluginRegistry
def test_tool_names_from_meta_supports_legacy_and_multi():
assert _tool_names_from_meta({"tool_name": "a"}) == ["a"]
assert _tool_names_from_meta(
{"tools": [{"name": "b"}, {"name": "c"}, {"other": 1}]},
) == ["b", "c"]
assert _tool_names_from_meta(
{"tool_name": "a", "tools": [{"name": "b"}]},
) == ["a", "b"]
def test_tool_names_from_meta_tolerates_malformed_tools():
"""``meta.tools`` must never raise — install runs this post-load."""
for bad_tools in (None, "not-a-list", {"name": "x"}):
names = _tool_names_from_meta({"tools": bad_tools})
assert isinstance(names, list)
assert not names
assert _tool_names_from_meta(
{
"tool_name": " legacy ",
"tools": [
{"name": "a"},
None,
"skip",
{"name": 123},
{"name": " a "},
{"name": "b"},
{"name": ""},
{"name": " "},
],
},
) == ["legacy", "a", "b"]
def test_force_reinstall_removed_tools_are_old_minus_new():
"""Only tools dropped by the new manifest should be cleaned up."""
old_tools = set(
_tool_names_from_meta(
{"tools": [{"name": "old_tool"}, {"name": "shared"}]},
),
)
new_tools = set(
_tool_names_from_meta(
{"tools": [{"name": "shared"}, {"name": "new_tool"}]},
),
)
assert sorted(old_tools - new_tools) == ["old_tool"]
@pytest.mark.asyncio
async def test_force_reinstall_removes_obsolete_tools_before_reload():
"""Agent reload must not run before obsolete tool configs are deleted."""
order: list[str] = []
async def _fake_post_load(_request, _plugin_id):
order.append("post_load_setup")
def _fake_remove(plugin_id, tool_names):
del plugin_id
order.append(f"remove:{','.join(tool_names)}")
async def _fake_reload(_request):
order.append("schedule_reload")
record = MagicMock()
record.manifest.id = "plug"
record.manifest.meta = {
"tools": [{"name": "shared"}, {"name": "new_tool"}],
}
with (
patch(
"qwenpaw.app.routers.plugins._post_load_setup",
new=AsyncMock(side_effect=_fake_post_load),
),
patch(
"qwenpaw.app.routers.plugins._remove_named_tools_from_agents",
side_effect=_fake_remove,
),
patch(
"qwenpaw.app.routers.plugins._schedule_all_agents_reload",
new=AsyncMock(side_effect=_fake_reload),
),
patch(
"qwenpaw.app.routers.plugins.asyncio.to_thread",
new=AsyncMock(
side_effect=lambda fn, *args: fn(*args),
),
),
):
await _finish_plugin_install_after_load(
MagicMock(),
record,
force=True,
old_tools={"old_tool", "shared"},
)
assert order == [
"post_load_setup",
"remove:old_tool",
"schedule_reload",
]
def test_norm_realpath_applies_normcase(tmp_path: Path):
"""Hot-reload path identity must use realpath + normcase."""
import os
target = tmp_path / "PluginDir"
target.mkdir()
assert _norm_realpath(target) == os.path.normcase(
os.path.realpath(str(target)),
)
def test_resolved_plugin_manifest_path_accepts_normal_dir(tmp_path: Path):
manifest = tmp_path / "plugin.json"
manifest.write_text('{"id": "demo"}', encoding="utf-8")
resolved = resolved_plugin_manifest_path(tmp_path)
assert resolved.is_file()
assert resolved.name == "plugin.json"
assert resolved.parent == tmp_path.resolve()
def test_resolved_plugin_manifest_path_rejects_missing(tmp_path: Path):
with pytest.raises(FileNotFoundError):
resolved_plugin_manifest_path(tmp_path)
@pytest.mark.asyncio
async def test_plugin_lifecycle_serializes_same_id():
"""Same plugin_id critical sections must not interleave."""
loader = PluginLoader(plugin_dirs=[])
order: list[str] = []
async def hold(tag: str) -> None:
async with loader.plugin_lifecycle("p1"):
order.append(f"{tag}-enter")
await asyncio.sleep(0.05)
order.append(f"{tag}-exit")
await asyncio.gather(hold("a"), hold("b"))
assert order in (
["a-enter", "a-exit", "b-enter", "b-exit"],
["b-enter", "b-exit", "a-enter", "a-exit"],
)
@pytest.mark.asyncio
async def test_plugin_lifecycle_allows_different_ids_concurrently():
"""Unrelated plugins may enter lifecycle sections together."""
loader = PluginLoader(plugin_dirs=[])
in_critical = 0
max_in_critical = 0
lock = asyncio.Lock()
async def hold(plugin_id: str) -> None:
nonlocal in_critical, max_in_critical
async with loader.plugin_lifecycle(plugin_id):
async with lock:
in_critical += 1
max_in_critical = max(max_in_critical, in_critical)
await asyncio.sleep(0.05)
async with lock:
in_critical -= 1
await asyncio.gather(hold("p-a"), hold("p-b"))
assert max_in_critical == 2
@pytest.mark.asyncio
async def test_child_task_cannot_bypass_lifecycle_lock():
"""create_task children must not inherit re-entrancy and skip the lock."""
loader = PluginLoader(plugin_dirs=[])
child_entered = asyncio.Event()
async def child_body() -> None:
async with loader.plugin_lifecycle("p1"):
child_entered.set()
async with loader.plugin_lifecycle("p1"):
child_task = asyncio.create_task(child_body())
await asyncio.sleep(0.05)
assert not child_entered.is_set()
assert not child_task.done()
await child_task
assert child_entered.is_set()
@pytest.mark.asyncio
async def test_uninstall_waits_for_full_install_transaction():
"""Uninstall waits until install post-load releases the lock."""
loader = PluginLoader(plugin_dirs=[])
plugin_id = "p-tx"
install_holding = asyncio.Event()
uninstall_started = asyncio.Event()
release_install = asyncio.Event()
order: list[str] = []
async def install_transaction() -> None:
# Mimic router: hold lifecycle across load + post-load setup.
async with loader.plugin_lifecycle(plugin_id):
order.append("install-enter")
install_holding.set()
await uninstall_started.wait()
await asyncio.sleep(0)
order.append("install-post-load")
await release_install.wait()
order.append("install-exit")
async def uninstall_transaction() -> None:
await install_holding.wait()
uninstall_started.set()
async with loader.plugin_lifecycle(plugin_id):
order.append("uninstall-enter")
order.append("uninstall-exit")
install_task = asyncio.create_task(install_transaction())
uninstall_task = asyncio.create_task(uninstall_transaction())
await asyncio.sleep(0.05)
assert not uninstall_task.done()
assert "uninstall-enter" not in order
release_install.set()
await asyncio.gather(install_task, uninstall_task)
assert order == [
"install-enter",
"install-post-load",
"install-exit",
"uninstall-enter",
"uninstall-exit",
]
@pytest.mark.asyncio
async def test_stale_unload_cannot_delete_tools_from_concurrent_reload():
"""Unload must not race a force-reinstall and wipe the new tools."""
plugin_id = "__ut_lifecycle_race__"
tool_name = "__ut_lifecycle_race_tool__"
release_tool_ownership_for_plugin(plugin_id)
DEFAULT_REGISTRY.unregister_python_tool(tool_name)
old = PluginRegistry._instance
PluginRegistry._instance = None
try:
preg = PluginRegistry()
loader = PluginLoader(plugin_dirs=[])
loader.registry = preg
manifest = PluginManifest(
id=plugin_id,
name="Race",
version="1.0.0",
entry=PluginEntryPoints(backend="plugin.py"),
meta={"tool_name": tool_name},
)
loader._loaded_plugins[plugin_id] = PluginRecord(
manifest=manifest,
source_path=Path("/fake-lifecycle-race"),
enabled=True,
instance=None,
)
register_tool_governance(
DEFAULT_REGISTRY,
python_name=tool_name,
tool_type="network",
owner=plugin_id,
)
_TOOL_PLUGIN_OWNERS[tool_name] = plugin_id
reinstall_entered = asyncio.Event()
unload_started = asyncio.Event()
release_reinstall = asyncio.Event()
async def force_reinstall() -> None:
async with loader.plugin_lifecycle(plugin_id):
reinstall_entered.set()
await unload_started.wait()
# Yield so a racy unload would proceed without the lock.
await asyncio.sleep(0)
await loader.unload_plugin(plugin_id)
# Simulate reload re-claiming the same tool identity.
register_tool_governance(
DEFAULT_REGISTRY,
python_name=tool_name,
tool_type="shell",
target_param="command",
owner=plugin_id,
)
_TOOL_PLUGIN_OWNERS[tool_name] = plugin_id
loader._loaded_plugins[plugin_id] = PluginRecord(
manifest=manifest,
source_path=Path("/fake-lifecycle-race-v2"),
enabled=True,
instance=None,
)
await release_reinstall.wait()
async def stale_unload() -> None:
await reinstall_entered.wait()
unload_started.set()
await loader.unload_plugin(plugin_id)
reinstall_task = asyncio.create_task(force_reinstall())
unload_task = asyncio.create_task(stale_unload())
# Stale unload must block while reinstall holds the lifecycle lock.
await asyncio.sleep(0.05)
assert not unload_task.done()
assert _TOOL_PLUGIN_OWNERS.get(tool_name) == plugin_id
assert DEFAULT_REGISTRY.get_owner(tool_name) == plugin_id
release_reinstall.set()
await reinstall_task
await unload_task
# Stale unload ran only after reinstall finished, so it removed
# the post-reload registration cleanly (no torn mid-reload state).
assert tool_name not in _TOOL_PLUGIN_OWNERS
assert plugin_id not in loader._loaded_plugins
finally:
release_tool_ownership_for_plugin(plugin_id)
DEFAULT_REGISTRY.unregister_python_tool(tool_name)
PluginRegistry._instance = old
@@ -0,0 +1,453 @@
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name,protected-access
"""Tests for plugin load-failure isolation.
Verifies that when ``_load_backend_module`` fails at any stage
(exec_module, missing ``plugin`` attribute, ``register()`` exception),
the framework cleans up:
- ``sys.modules`` (main module, sub-modules, bare-imported modules)
- ``sys.path``
- ``PluginRegistry`` (manifest, hooks, providers, middleware, etc.)
"""
import json
import os
import sys
import types
from pathlib import Path
from typing import Dict
import pytest
# ---------------------------------------------------------------------------
# Stub missing agentscope 2.0 modules (same pattern as sibling test file)
# ---------------------------------------------------------------------------
_AGENTSCOPE_STUBS = [
"agentscope.state",
]
for _mod_name in _AGENTSCOPE_STUBS:
if _mod_name not in sys.modules:
_stub = types.ModuleType(_mod_name)
_stub.AgentState = type(
"AgentState",
(),
{},
) # type: ignore[attr-defined]
sys.modules[_mod_name] = _stub
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture()
def fresh_registry():
"""Create a fresh PluginRegistry (bypass singleton)."""
from qwenpaw.plugins.registry import PluginRegistry
old_instance = PluginRegistry._instance
PluginRegistry._instance = None
registry = PluginRegistry()
yield registry
PluginRegistry._instance = old_instance
@pytest.fixture()
def loader(fresh_registry, tmp_path):
"""Create a PluginLoader wired to the fresh registry."""
from qwenpaw.plugins.loader import PluginLoader
ldr = PluginLoader(plugin_dirs=[tmp_path])
ldr.registry = fresh_registry
return ldr
def _write_plugin(plugin_dir: Path, plugin_py_code: str) -> Dict:
"""Write a minimal plugin directory and return the manifest dict."""
plugin_dir.mkdir(parents=True, exist_ok=True)
manifest = {
"id": plugin_dir.name,
"name": plugin_dir.name,
"version": "1.0.0",
"entry": {"backend": "plugin.py"},
"qwenpaw_version": {"min": "0.1.0", "max": "99.0.0"},
}
(plugin_dir / "plugin.json").write_text(
json.dumps(manifest),
encoding="utf-8",
)
(plugin_dir / "plugin.py").write_text(plugin_py_code, encoding="utf-8")
return manifest
# ---------------------------------------------------------------------------
# Tests: sys.modules cleanup
# ---------------------------------------------------------------------------
class TestSysModulesCleanup:
"""sys.modules must not retain entries from a failed load."""
@pytest.mark.asyncio
async def test_exec_module_failure_cleans_sys_modules(
self,
loader,
tmp_path,
):
"""If exec_module raises, the module is removed from sys.modules."""
plugin_dir = tmp_path / "bad-syntax"
_write_plugin(plugin_dir, "raise SyntaxError('intentional')\n")
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
module_name = f"plugin_{manifest.id.replace('-', '_')}"
with pytest.raises(SyntaxError):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert module_name not in sys.modules
@pytest.mark.asyncio
async def test_missing_plugin_attr_cleans_sys_modules(
self,
loader,
tmp_path,
):
"""If the module lacks a 'plugin' attribute, sys.modules is cleaned."""
plugin_dir = tmp_path / "no-attr"
_write_plugin(plugin_dir, "x = 42\n")
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
module_name = f"plugin_{manifest.id.replace('-', '_')}"
with pytest.raises(AttributeError, match="plugin"):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert module_name not in sys.modules
@pytest.mark.asyncio
async def test_register_failure_cleans_submodules(
self,
loader,
tmp_path,
):
"""Sub-modules written by exec_module are cleaned on failure."""
plugin_dir = tmp_path / "sub-mod"
(plugin_dir).mkdir()
(plugin_dir / "helper.py").write_text(
"VALUE = 99\n",
encoding="utf-8",
)
_write_plugin(
plugin_dir,
"from .helper import VALUE\n"
"\n"
"class P:\n"
" def register(self, api):\n"
" raise RuntimeError('register boom')\n"
"\n"
"plugin = P()\n",
)
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
module_name = f"plugin_{manifest.id.replace('-', '_')}"
sub_name = f"{module_name}.helper"
with pytest.raises(RuntimeError, match="register boom"):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert module_name not in sys.modules
assert sub_name not in sys.modules
@pytest.mark.asyncio
async def test_bare_import_cleaned_by_file_path(
self,
loader,
tmp_path,
):
"""Modules that land in the global top-level namespace (e.g. via
``importlib.import_module``, which bypasses the plugin-namespace
``__import__`` redirection) are cleaned via __file__ scanning."""
plugin_dir = tmp_path / "bare-imp"
(plugin_dir).mkdir()
# A helper that the plugin will import via bare name
(plugin_dir / "bare_helper_xyzzy.py").write_text(
"MAGIC = 123\n",
encoding="utf-8",
)
_write_plugin(
plugin_dir,
"import sys, os, importlib\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"bare_helper_xyzzy = importlib.import_module(\n"
" 'bare_helper_xyzzy',\n"
")\n"
"assert 'bare_helper_xyzzy' in sys.modules\n"
"\n"
"class P:\n"
" def register(self, api):\n"
" raise RuntimeError('fail after bare import')\n"
"\n"
"plugin = P()\n",
)
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
with pytest.raises(RuntimeError, match="fail after bare import"):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert "bare_helper_xyzzy" not in sys.modules
# ---------------------------------------------------------------------------
# Tests: sys.path cleanup
# ---------------------------------------------------------------------------
class TestSysPathCleanup:
@pytest.mark.asyncio
async def test_sys_path_cleaned_on_failure(self, loader, tmp_path):
"""Plugin directory inserted into sys.path is removed on failure."""
plugin_dir = tmp_path / "path-pol"
_write_plugin(
plugin_dir,
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"\n"
"class P:\n"
" def register(self, api):\n"
" raise RuntimeError('path pollution test')\n"
"\n"
"plugin = P()\n",
)
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
plugin_dir_real = os.path.realpath(str(plugin_dir))
assert plugin_dir_real not in [os.path.realpath(p) for p in sys.path]
with pytest.raises(RuntimeError, match="path pollution test"):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert plugin_dir_real not in [os.path.realpath(p) for p in sys.path]
# ---------------------------------------------------------------------------
# Tests: PluginRegistry cleanup
# ---------------------------------------------------------------------------
class TestRegistryCleanup:
@pytest.mark.asyncio
async def test_manifest_cleaned_on_register_failure(
self,
loader,
fresh_registry,
tmp_path,
):
"""Manifest pre-registered before register() is cleaned on failure."""
plugin_dir = tmp_path / "reg-fail"
_write_plugin(
plugin_dir,
"class P:\n"
" def register(self, api):\n"
" raise ValueError('register failed')\n"
"\n"
"plugin = P()\n",
)
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
with pytest.raises(ValueError, match="register failed"):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert fresh_registry.get_plugin_manifest(manifest.id) is None
@pytest.mark.asyncio
async def test_partial_registrations_cleaned_on_failure(
self,
loader,
fresh_registry,
tmp_path,
):
"""Hooks/middleware registered before the exception are cleaned."""
plugin_dir = tmp_path / "partial-reg"
_write_plugin(
plugin_dir,
"class P:\n"
" def register(self, api):\n"
" api.register_startup_hook(\n"
" hook_name='orphan_hook',\n"
" callback=lambda: None,\n"
" )\n"
" api.register_middleware(\n"
" middleware_factory=lambda ctx, cfg: None,\n"
" )\n"
" raise RuntimeError('partial failure')\n"
"\n"
"plugin = P()\n",
)
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads(
(plugin_dir / "plugin.json").read_text(encoding="utf-8"),
),
)
with pytest.raises(RuntimeError, match="partial failure"):
await loader._load_backend_module(
manifest.id,
plugin_dir / "plugin.py",
plugin_dir,
None,
manifest,
)
assert len(fresh_registry.get_startup_hooks()) == 0
assert len(fresh_registry.get_middleware_factories()) == 0
assert fresh_registry.get_plugin_manifest(manifest.id) is None
# ---------------------------------------------------------------------------
# Tests: load_all_plugins integration
# ---------------------------------------------------------------------------
class TestLoadAllPluginsIsolation:
@pytest.mark.asyncio
async def test_bad_plugin_does_not_block_good_plugin(
self,
loader,
fresh_registry,
tmp_path,
):
"""A failing plugin does not prevent subsequent plugins from loading,
and leaves no residue in the registry.
The directory names (aaa-bad, zzz-good) do NOT imply a required
load order — Path.iterdir() order is filesystem-dependent. The
assertions only check presence/absence in the loaded dict and
registry, which are order-independent.
"""
# Plugin that fails during register()
bad_dir = tmp_path / "aaa-bad"
_write_plugin(
bad_dir,
"class P:\n"
" def register(self, api):\n"
" api.register_startup_hook(\n"
" hook_name='orphan',\n"
" callback=lambda: None,\n"
" )\n"
" raise RuntimeError('bad plugin')\n"
"\n"
"plugin = P()\n",
)
# Plugin that loads successfully
good_dir = tmp_path / "zzz-good"
_write_plugin(
good_dir,
"class P:\n"
" def register(self, api):\n"
" api.register_startup_hook(\n"
" hook_name='good_hook',\n"
" callback=lambda: None,\n"
" )\n"
"\n"
"plugin = P()\n",
)
loaded = await loader.load_all_plugins()
# Good plugin loaded successfully
assert "zzz-good" in loaded
assert loaded["zzz-good"].enabled is True
# Bad plugin is NOT in loaded dict
assert "aaa-bad" not in loaded
# Registry contains only the good plugin's hook, not the bad one
hooks = fresh_registry.get_startup_hooks()
hook_names = [h.hook_name for h in hooks]
assert "good_hook" in hook_names
assert "orphan" not in hook_names
# No manifest residue from bad plugin
assert fresh_registry.get_plugin_manifest("aaa-bad") is None
assert fresh_registry.get_plugin_manifest("zzz-good") is not None
@@ -0,0 +1,954 @@
# -*- coding: utf-8 -*-
# pylint: disable=redefined-outer-name,protected-access
"""Tests for per-plugin bare-import namespace isolation (#6683).
Two plugins shipping the same top-level module name (``utils``) must not
collide: bare absolute imports (``import utils`` / ``from utils.env
import x``) are redirected into each plugin's private ``plugin_<id>``
namespace, including nested and lazy (function-level) imports, while
stdlib / third-party imports fall through untouched.
"""
import json
import sys
import types
from pathlib import Path
from typing import Dict
import pytest
# ---------------------------------------------------------------------------
# Stub missing agentscope 2.0 modules (same pattern as sibling test file)
# ---------------------------------------------------------------------------
_AGENTSCOPE_STUBS = [
"agentscope.state",
]
for _mod_name in _AGENTSCOPE_STUBS:
if _mod_name not in sys.modules:
_stub = types.ModuleType(_mod_name)
_stub.AgentState = type(
"AgentState",
(),
{},
) # type: ignore[attr-defined]
sys.modules[_mod_name] = _stub
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture()
def fresh_registry():
"""Create a fresh PluginRegistry (bypass singleton)."""
from qwenpaw.plugins.registry import PluginRegistry
old_instance = PluginRegistry._instance
PluginRegistry._instance = None
registry = PluginRegistry()
yield registry
PluginRegistry._instance = old_instance
@pytest.fixture()
def loader(fresh_registry, tmp_path):
"""Create a PluginLoader wired to the fresh registry."""
from qwenpaw.plugins.loader import PluginLoader
ldr = PluginLoader(plugin_dirs=[tmp_path])
ldr.registry = fresh_registry
return ldr
@pytest.fixture(autouse=True)
def _cleanup_test_modules(tmp_path):
"""Remove modules loaded from tmp_path and its sys.path entries."""
yield
tmp_str = str(tmp_path)
for key, mod in list(sys.modules.items()):
mod_file = getattr(mod, "__file__", None)
if mod_file is not None and mod_file.startswith(tmp_str):
sys.modules.pop(key, None)
elif mod_file is None:
# Namespace packages have no __file__; match by __path__.
# Accessing __path__ recomputes _NamespacePath, which looks
# up the parent in sys.modules — if we already popped the
# parent above, the child is an orphan: pop it too.
try:
paths = list(getattr(mod, "__path__", None) or [])
except KeyError:
sys.modules.pop(key, None)
continue
if any(str(p).startswith(tmp_str) for p in paths):
sys.modules.pop(key, None)
sys.path[:] = [p for p in sys.path if not str(p).startswith(tmp_str)]
def _write_manifest(
plugin_dir: Path,
backend_entry: str = "plugin.py",
) -> Dict:
plugin_dir.mkdir(parents=True, exist_ok=True)
manifest = {
"id": plugin_dir.name,
"name": plugin_dir.name,
"version": "1.0.0",
"entry": {"backend": backend_entry},
"qwenpaw_version": {"min": "0.1.0", "max": "99.0.0"},
}
(plugin_dir / "plugin.json").write_text(
json.dumps(manifest),
encoding="utf-8",
)
return manifest
async def _load(loader, plugin_dir: Path, backend_entry: str = "plugin.py"):
from qwenpaw.plugins.architecture import PluginManifest
manifest = PluginManifest.from_dict(
json.loads((plugin_dir / "plugin.json").read_text(encoding="utf-8")),
)
return await loader._load_backend_module(
manifest.id,
plugin_dir / backend_entry,
plugin_dir,
None,
manifest,
)
_REGISTER_OK = (
"\n"
"class P:\n"
" def register(self, api):\n"
" pass\n"
"\n"
"plugin = P()\n"
)
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestBareImportNamespaceIsolation:
@pytest.mark.asyncio
async def test_conflicting_utils_module_and_package(
self,
loader,
tmp_path,
):
"""The #6683 repro: plugin A ships ``utils.py`` (a plain module),
plugin B ships ``utils/`` (a package). Both must load and see
their own ``utils`` regardless of load order."""
dir_a = tmp_path / "plug-a"
dir_a.mkdir()
(dir_a / "utils.py").write_text("WHO = 'A'\n", encoding="utf-8")
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import utils\n"
"WHO = utils.WHO\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "plug-b"
(dir_b / "utils").mkdir(parents=True)
(dir_b / "utils" / "__init__.py").write_text("", encoding="utf-8")
(dir_b / "utils" / "env.py").write_text(
"WHO = 'B'\n",
encoding="utf-8",
)
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"from utils.env import WHO\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
# Before the fix this raised: No module named 'utils.env';
# 'utils' is not a package.
await _load(loader, dir_b)
assert sys.modules["plugin_plug_a"].WHO == "A"
assert sys.modules["plugin_plug_b"].WHO == "B"
assert "plugin_plug_a.utils" in sys.modules
assert "plugin_plug_b.utils" in sys.modules
@pytest.mark.asyncio
async def test_nested_bare_import_stays_namespaced(
self,
loader,
tmp_path,
):
"""Bare imports *inside* plugin submodules resolve to the plugin's
own files, not to another plugin's same-named module."""
dir_a = tmp_path / "aaa-first"
dir_a.mkdir()
(dir_a / "helper.py").write_text("TAG = 'first'\n", encoding="utf-8")
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import helper\n"
"TAG = helper.TAG\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "bbb-second"
(dir_b / "pkg").mkdir(parents=True)
(dir_b / "pkg" / "__init__.py").write_text("", encoding="utf-8")
# pkg.core reaches a sibling top-level module via a bare import.
(dir_b / "pkg" / "core.py").write_text(
"from helper import TAG\n",
encoding="utf-8",
)
(dir_b / "helper.py").write_text("TAG = 'second'\n", encoding="utf-8")
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"from pkg.core import TAG\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
await _load(loader, dir_b)
assert sys.modules["plugin_aaa_first"].TAG == "first"
assert sys.modules["plugin_bbb_second"].TAG == "second"
@pytest.mark.asyncio
async def test_lazy_function_level_import(self, loader, tmp_path):
"""A bare import executed at call time (after other plugins have
loaded) still resolves inside the calling plugin."""
dir_a = tmp_path / "lazy-a"
dir_a.mkdir()
(dir_a / "shared_name.py").write_text(
"OWNER = 'lazy-a'\n",
encoding="utf-8",
)
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"def whoami():\n"
" from shared_name import OWNER\n"
" return OWNER\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "lazy-b"
dir_b.mkdir()
(dir_b / "shared_name.py").write_text(
"OWNER = 'lazy-b'\n",
encoding="utf-8",
)
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import shared_name\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
await _load(loader, dir_b)
# Called only now — after lazy-b claimed ``shared_name`` too.
assert sys.modules["plugin_lazy_a"].whoami() == "lazy-a"
@pytest.mark.asyncio
async def test_stdlib_imports_fall_through(self, loader, tmp_path):
"""Names not shipped by the plugin resolve via the regular
machinery and are not captured into the plugin namespace."""
plugin_dir = tmp_path / "std-plug"
plugin_dir.mkdir()
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import json\n"
"JSON_MOD = json\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
assert sys.modules["plugin_std_plug"].JSON_MOD is sys.modules["json"]
assert "plugin_std_plug.json" not in sys.modules
@pytest.mark.asyncio
async def test_nested_entry_dir_imports(self, loader, tmp_path):
"""The qwenpaw-creator layout: entry at ``backend/main.py`` with
bare imports resolving against ``backend/``."""
plugin_dir = tmp_path / "nested-entry"
backend = plugin_dir / "backend"
(backend / "utils").mkdir(parents=True)
(backend / "utils" / "__init__.py").write_text("", encoding="utf-8")
(backend / "utils" / "env.py").write_text(
"VALUE = 'nested'\n",
encoding="utf-8",
)
_write_manifest(plugin_dir, backend_entry="backend/main.py")
(backend / "main.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"from utils.env import VALUE\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir, backend_entry="backend/main.py")
assert sys.modules["plugin_nested_entry"].VALUE == "nested"
@pytest.mark.asyncio
async def test_nested_entry_dir_precedes_plugin_root(
self,
loader,
tmp_path,
):
"""When the plugin root and the entry directory both ship the same
bare module name, the entry directory wins — matching the
``sys.path.insert(0, dirname(__file__))`` semantics nested-entry
plugins rely on."""
plugin_dir = tmp_path / "nested-priority"
backend = plugin_dir / "backend"
backend.mkdir(parents=True)
(plugin_dir / "helper.py").write_text(
"VALUE = 'plugin-root'\n",
encoding="utf-8",
)
(backend / "helper.py").write_text(
"VALUE = 'entry-dir'\n",
encoding="utf-8",
)
_write_manifest(plugin_dir, backend_entry="backend/main.py")
(backend / "main.py").write_text(
"import os, sys\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"from helper import VALUE\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir, backend_entry="backend/main.py")
assert sys.modules["plugin_nested_priority"].VALUE == "entry-dir"
@pytest.mark.asyncio
async def test_pep420_namespace_packages_stay_isolated(
self,
loader,
tmp_path,
):
"""Packages without __init__.py (PEP 420 namespace packages) are
still plugin-local: two plugins shipping the same namespace
package name must not share modules."""
code = (
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"from helpers.value import VALUE\n" + _REGISTER_OK
)
for name, val in (("pep-a", "A"), ("pep-b", "B")):
plugin_dir = tmp_path / name
(plugin_dir / "helpers").mkdir(parents=True)
# No __init__.py on purpose — a PEP 420 namespace package.
(plugin_dir / "helpers" / "value.py").write_text(
f"VALUE = '{val}'\n",
encoding="utf-8",
)
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(code, encoding="utf-8")
await _load(loader, plugin_dir)
assert sys.modules["plugin_pep_a"].VALUE == "A"
assert sys.modules["plugin_pep_b"].VALUE == "B"
@pytest.mark.asyncio
async def test_pep420_package_without_sys_path_insert(
self,
loader,
tmp_path,
):
"""A PEP 420 package imports fine (and stays isolated) even when
the plugin never touches sys.path — same as a regular package."""
for name, val in (("noins-a", "A"), ("noins-b", "B")):
plugin_dir = tmp_path / name
(plugin_dir / "helpers").mkdir(parents=True)
(plugin_dir / "helpers" / "value.py").write_text(
f"VALUE = '{val}'\n",
encoding="utf-8",
)
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"from helpers.value import VALUE\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
assert sys.modules["plugin_noins_a"].VALUE == "A"
assert sys.modules["plugin_noins_b"].VALUE == "B"
@pytest.mark.asyncio
async def test_regular_package_then_pep420_package(
self,
loader,
tmp_path,
):
"""A regular package left on sys.path by an earlier plugin must
not pull a later plugin's same-named PEP 420 package out of its
namespace."""
code = (
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"from helpers.value import VALUE\n" + _REGISTER_OK
)
dir_a = tmp_path / "reg-a"
(dir_a / "helpers").mkdir(parents=True)
(dir_a / "helpers" / "__init__.py").write_text("", encoding="utf-8")
(dir_a / "helpers" / "value.py").write_text(
"VALUE = 'A'\n",
encoding="utf-8",
)
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(code, encoding="utf-8")
dir_b = tmp_path / "pep-late-b"
(dir_b / "helpers").mkdir(parents=True)
# No __init__.py on purpose — a PEP 420 namespace package.
(dir_b / "helpers" / "value.py").write_text(
"VALUE = 'B'\n",
encoding="utf-8",
)
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(code, encoding="utf-8")
await _load(loader, dir_a)
await _load(loader, dir_b)
assert sys.modules["plugin_reg_a"].VALUE == "A"
assert sys.modules["plugin_pep_late_b"].VALUE == "B"
assert "plugin_pep_late_b.helpers.value" in sys.modules
@pytest.mark.asyncio
async def test_data_directory_does_not_shadow_stdlib(
self,
loader,
tmp_path,
):
"""A bare data directory (no __init__.py, no code) must not be
treated as a plugin-local module: ``import wave`` with a
``wave/`` assets dir present still resolves to the stdlib."""
plugin_dir = tmp_path / "data-dir"
(plugin_dir / "wave").mkdir(parents=True)
(plugin_dir / "wave" / "sample.bin").write_bytes(b"\x00")
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import wave\n"
"WAVE = wave\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
import wave as real_wave
assert sys.modules["plugin_data_dir"].WAVE is real_wave
assert "plugin_data_dir.wave" not in sys.modules
@pytest.mark.asyncio
async def test_loader_forwards_resource_access(
self,
loader,
tmp_path,
):
"""importlib.resources works on namespaced plugin packages: the
wrapping loader must forward get_resource_reader etc."""
import importlib.resources
plugin_dir = tmp_path / "res-plug"
pkg = plugin_dir / "assets_pkg"
pkg.mkdir(parents=True)
(pkg / "__init__.py").write_text("", encoding="utf-8")
(pkg / "data.txt").write_text("hello-resource", encoding="utf-8")
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import assets_pkg\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
mod = sys.modules["plugin_res_plug.assets_pkg"]
text = importlib.resources.files(mod).joinpath("data.txt").read_text()
assert text == "hello-resource"
@pytest.mark.asyncio
async def test_bare_import_of_entry_aliases_running_module(
self,
loader,
tmp_path,
):
"""A submodule bare-importing the entry file gets the running
entry module, not a second freshly-executed copy."""
plugin_dir = tmp_path / "self-imp"
plugin_dir.mkdir()
(plugin_dir / "helper.py").write_text(
"import plugin\nplugin.X.append(1)\n",
encoding="utf-8",
)
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"X = []\n"
"import helper\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
assert sys.modules["plugin_self_imp"].X == [1]
assert "plugin_self_imp.plugin" not in sys.modules
@pytest.mark.asyncio
async def test_dotted_import_as_binding(self, loader, tmp_path):
"""``import a.b as c`` binds the submodule under the alias."""
plugin_dir = tmp_path / "dotted-as"
pkg = plugin_dir / "a"
pkg.mkdir(parents=True)
(pkg / "__init__.py").write_text("", encoding="utf-8")
(pkg / "b.py").write_text("V = 7\n", encoding="utf-8")
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import a.b as c\n"
"VAL = c.V\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
assert sys.modules["plugin_dotted_as"].VAL == 7
@pytest.mark.asyncio
async def test_cleanup_keeps_relative_sys_path_entries(
self,
loader,
tmp_path,
):
"""Failed-load cleanup must not strip relative sys.path entries
('' — the CWD) even when the CWD is inside the plugin dir."""
import os as os_mod
plugin_dir = tmp_path / "cwd-plug"
(plugin_dir / "sub").mkdir(parents=True)
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"raise RuntimeError('boom')\n",
encoding="utf-8",
)
old_cwd = os_mod.getcwd()
had_empty = "" in sys.path
if not had_empty:
sys.path.insert(0, "")
os_mod.chdir(plugin_dir / "sub")
try:
with pytest.raises(RuntimeError, match="boom"):
await _load(loader, plugin_dir)
# The plugin's own absolute entry is swept …
plugin_real = os_mod.path.realpath(str(plugin_dir))
assert plugin_real not in [
os_mod.path.realpath(p) for p in sys.path if p
]
# … but the relative CWD entry survives.
assert "" in sys.path
finally:
os_mod.chdir(old_cwd)
if not had_empty and "" in sys.path:
sys.path.remove("")
@pytest.mark.asyncio
async def test_entry_alias_with_fromlist_imports_sibling(
self,
loader,
tmp_path,
):
"""``from <entry> import <sibling_module>`` imports the sibling
as a namespaced submodule without re-executing the entry."""
plugin_dir = tmp_path / "fromlist-plug"
plugin_dir.mkdir()
(plugin_dir / "sib.py").write_text("S = 'sib'\n", encoding="utf-8")
(plugin_dir / "helper.py").write_text(
"from plugin import sib\nS = sib.S\n",
encoding="utf-8",
)
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"RUNS = globals().get('RUNS', 0) + 1\n"
"import helper\n"
"S = helper.S\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
mod = sys.modules["plugin_fromlist_plug"]
assert mod.S == "sib"
assert mod.RUNS == 1
assert "plugin_fromlist_plug.sib" in sys.modules
assert "plugin_fromlist_plug.plugin" not in sys.modules
@pytest.mark.asyncio
async def test_non_importable_nested_code_stays_data(
self,
loader,
tmp_path,
):
"""Code reachable only through non-identifier path components
(e.g. ``wave/en-US/tool.py``) does not make a data directory
shadow the stdlib."""
plugin_dir = tmp_path / "l10n-plug"
(plugin_dir / "wave" / "en-US").mkdir(parents=True)
(plugin_dir / "wave" / "en-US" / "tool.py").write_text(
"X = 1\n",
encoding="utf-8",
)
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import wave\n" "WAVE = wave\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
import wave as real_wave
assert sys.modules["plugin_l10n_plug"].WAVE is real_wave
assert "plugin_l10n_plug.wave" not in sys.modules
@pytest.mark.asyncio
async def test_stale_bytecode_does_not_make_data_dir_a_package(
self,
loader,
tmp_path,
):
"""Leftover bytecode (``__pycache__`` contents or a stray legacy
``.pyc``) is not importable source — a data directory holding
only bytecode must still fall through to the stdlib. The
``__pycache__/x.py`` file locks the cache-dir pruning: nothing
under ``__pycache__`` counts, whatever its suffix."""
plugin_dir = tmp_path / "pyc-plug"
(plugin_dir / "wave" / "__pycache__").mkdir(parents=True)
(plugin_dir / "wave" / "sample.bin").write_bytes(b"\x00")
(plugin_dir / "wave" / "__pycache__" / "x.py").write_text(
"X = 1\n",
encoding="utf-8",
)
(
plugin_dir / "wave" / "__pycache__" / "x.cpython-312.pyc"
).write_bytes(
b"\x00",
)
(plugin_dir / "wave" / "legacy.pyc").write_bytes(b"\x00")
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import wave\n"
"WAVE = wave\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, plugin_dir)
import wave as real_wave
assert sys.modules["plugin_pyc_plug"].WAVE is real_wave
assert "plugin_pyc_plug.wave" not in sys.modules
@pytest.mark.asyncio
async def test_failed_load_unregisters_namespace(
self,
loader,
tmp_path,
):
"""A failed load must remove the plugin's import redirection."""
from qwenpaw.plugins.module_isolation import get_namespace_finder
plugin_dir = tmp_path / "fail-ns"
plugin_dir.mkdir()
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"raise RuntimeError('boom')\n",
encoding="utf-8",
)
with pytest.raises(RuntimeError, match="boom"):
await _load(loader, plugin_dir)
assert not get_namespace_finder().is_registered("plugin_fail_ns")
class TestFallthroughIsolation:
"""Non-local fallthrough imports must not resolve into other loaded
plugins' source trees left on sys.path (PR #6688 review)."""
@pytest.mark.asyncio
async def test_data_dir_fallthrough_skips_other_plugin(
self,
loader,
tmp_path,
):
"""Blocking-1: a data-directory fallthrough must not resolve into
an earlier plugin's source tree left on sys.path."""
dir_a = tmp_path / "res-a"
(dir_a / "helpers_qq").mkdir(parents=True)
(dir_a / "helpers_qq" / "__init__.py").write_text(
"WHO = 'A'\n",
encoding="utf-8",
)
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import helpers_qq\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "res-b"
(dir_b / "helpers_qq").mkdir(parents=True)
(dir_b / "helpers_qq" / "readme.bin").write_bytes(b"\x00")
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import helpers_qq\n"
"H = helpers_qq\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
await _load(loader, dir_b)
# B must not receive A's module; at most its own (empty)
# namespace portion — never a path from A's tree.
imported = sys.modules["plugin_res_b"].H
assert not hasattr(imported, "WHO")
assert list(imported.__path__) == [str(dir_b / "helpers_qq")]
@pytest.mark.asyncio
async def test_uncached_stdlib_name_not_polluted_by_plugin(
self,
loader,
tmp_path,
):
"""Blocking-2: with the stdlib name not pre-cached, a later
data-dir fallthrough must load the real stdlib module — not an
earlier plugin's same-named file — and must not leave a wrong
binding in sys.modules for the host."""
dir_a = tmp_path / "fake-a"
dir_a.mkdir()
(dir_a / "wave.py").write_text("FAKE = True\n", encoding="utf-8")
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import wave\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "data-b"
(dir_b / "wave").mkdir(parents=True)
(dir_b / "wave" / "sample.bin").write_bytes(b"\x00")
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import wave\n"
"WAVE = wave\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
# A's own import was namespaced, so the global name is normally
# absent already; pop defensively in case an earlier test (or
# the host) imported the real module and cached it.
sys.modules.pop("wave", None)
await _load(loader, dir_b)
assert not hasattr(sys.modules["plugin_data_b"].WAVE, "FAKE")
assert hasattr(sys.modules["plugin_data_b"].WAVE, "open")
host_wave = sys.modules["wave"]
assert not str(host_wave.__file__).startswith(str(tmp_path))
@pytest.mark.asyncio
async def test_no_local_name_fallthrough_skips_other_plugin(
self,
loader,
tmp_path,
):
"""Blocking-3: a bare import with no plugin-local candidate at
all must not resolve into another plugin's source tree."""
dir_a = tmp_path / "owner-a"
dir_a.mkdir()
(dir_a / "only_a_owns_this.py").write_text(
"WHO = 'A'\n",
encoding="utf-8",
)
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import only_a_owns_this\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "bare-b"
dir_b.mkdir()
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import only_a_owns_this\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
with pytest.raises(ModuleNotFoundError):
await _load(loader, dir_b)
assert "only_a_owns_this" not in sys.modules
@pytest.mark.asyncio
async def test_load_end_sweep_skips_unchanged_module_locations(
self,
loader,
tmp_path,
monkeypatch,
):
"""Load-end cleanup must not normalize every preloaded module."""
from qwenpaw.plugins import module_isolation
plugin_dir = tmp_path / "incremental-sweep"
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
_REGISTER_OK,
encoding="utf-8",
)
stable_name = "_qwenpaw_unchanged_module_probe"
stable_module = types.ModuleType(stable_name)
stable_path = str(tmp_path.parent / "stable_module.py")
stable_module.__file__ = stable_path
sys.modules[stable_name] = stable_module
normalized = []
real_norm = module_isolation._norm
def _record_norm(path):
normalized.append(str(path))
return real_norm(path)
monkeypatch.setattr(module_isolation, "_norm", _record_norm)
try:
await _load(loader, plugin_dir)
finally:
sys.modules.pop(stable_name, None)
assert stable_path not in normalized
def test_incremental_sweep_restores_replaced_binding(self, tmp_path):
"""A plugin-local replacement must not erase an older binding."""
from qwenpaw.plugins.module_isolation import sweep_bare_tree_modules
plugin_dir = tmp_path / "restore-binding"
plugin_dir.mkdir()
module_name = "_qwenpaw_replaced_module_probe"
previous = types.ModuleType(module_name)
replacement = types.ModuleType(module_name)
replacement.__file__ = str(plugin_dir / "replacement.py")
sys.modules[module_name] = previous
modules_before = dict(sys.modules)
sys.modules[module_name] = replacement
try:
sweep_bare_tree_modules(plugin_dir, modules_before)
assert sys.modules[module_name] is previous
finally:
sys.modules.pop(module_name, None)
@pytest.mark.asyncio
async def test_bare_namespace_residue_swept_at_load_end(
self,
loader,
tmp_path,
):
"""A bare namespace package cached from a plugin's own data dir
during load must not outlive the load: sys.modules is the other
residue channel besides sys.path."""
dir_a = tmp_path / "nsres-a"
(dir_a / "resq_pkg").mkdir(parents=True)
(dir_a / "resq_pkg" / "x.bin").write_bytes(b"\x00")
_write_manifest(dir_a)
(dir_a / "plugin.py").write_text(
"import sys, os\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"import resq_pkg\n" + _REGISTER_OK,
encoding="utf-8",
)
dir_b = tmp_path / "nsres-b"
dir_b.mkdir()
_write_manifest(dir_b)
(dir_b / "plugin.py").write_text(
"import resq_pkg\n" + _REGISTER_OK,
encoding="utf-8",
)
await _load(loader, dir_a)
assert "resq_pkg" not in sys.modules
with pytest.raises(ModuleNotFoundError):
await _load(loader, dir_b)
@pytest.mark.asyncio
async def test_failed_load_sweeps_namespace_residue(
self,
loader,
tmp_path,
):
"""Bare namespace-package residue from a FAILED load is swept
too (by the load-end sweep, which runs on every exit path) —
such packages have no __file__, so a file-based sweep alone
would miss them."""
plugin_dir = tmp_path / "nsfail"
(plugin_dir / "nsp_dir").mkdir(parents=True)
(plugin_dir / "nsp_dir" / "d.bin").write_bytes(b"\x00")
_write_manifest(plugin_dir)
(plugin_dir / "plugin.py").write_text(
"import sys, os, importlib\n"
"sys.path.insert(0, os.path.dirname(__file__))\n"
"nsp_dir = importlib.import_module('nsp_dir')\n"
"assert 'nsp_dir' in sys.modules\n"
"raise RuntimeError('post-import boom')\n",
encoding="utf-8",
)
with pytest.raises(RuntimeError, match="post-import boom"):
await _load(loader, plugin_dir)
assert "nsp_dir" not in sys.modules