Skip to content

Self-improving AI Employees for everyone

20.8 KB
Raw Blame
"""The Browser node (nodes/browser/browser): operations, policy and locked settings.

No Chrome and no CLI run here: a fake runtime hands the node a real
``ProfileController`` (so control and leases behave as in production) and a
fake CLI that records each script call.
"""

from __future__ import annotations

import asyncio
from types import SimpleNamespace
from typing import Any, Dict, List
from unittest.mock import AsyncMock, patch

import pytest

from nodes.browser._cli import CliResult
from nodes.browser._controls import ActionGuard
from services.netpolicy import NetPolicy
from nodes.browser._profiles import Profile
from nodes.browser._session import ControlState, ProfileController
from nodes.browser.browser import BrowserNode, BrowserToolInput
from services.plugin.context import NodeContext

PAGE = {"target_id": "T1", "url": "https://example.com/", "title": "Example"}


class FakeCli:
    def __init__(self, tmp_path) -> None:
        self.calls: List[tuple] = []
        self.results: List[CliResult] = []
        self.tmp = tmp_path

    async def run(self, op: str, args: Dict[str, Any], *, timeout: float) -> CliResult:
        self.calls.append((op, dict(args)))
        if self.results:
            return self.results.pop(0)
        return CliResult(ok=True, value={}, page=dict(PAGE))

    async def interrupt(self) -> None:
        return None

    def dirs(self):
        return {"tmp": self.tmp}

    def stop_daemon(self) -> None:
        return None


class FakeWebMcp:
    def __init__(self) -> None:
        self.invoked: List[tuple] = []

    def tools(self, target_id):
        return [{"name": "search", "read_only": True, "frame_id": "F", "main_frame": True}, {"name": "buy", "read_only": False, "frame_id": "F", "main_frame": True}]

    def count(self, target_id):
        return 2

    async def invoke(self, target_id, name, tool_input, *, frame_id=None, mode="read_only", timeout=60):
        if mode == "read_only" and name == "buy":
            from services.plugin.base import NodeUserError

            raise NodeUserError("read-only")
        self.invoked.append((name, tool_input, mode))
        return {"status": "completed", "output": "ok", "untrusted": True, "tool": name}


class FakeRuntime:
    def __init__(self, tmp_path) -> None:
        self.action_guard = ActionGuard()
        self.controller = ProfileController("bp_1", "Work")
        self.controller.active_target_id = "T1"
        self.controller.tabs["T1"] = dict(PAGE)
        self.cli = FakeCli(tmp_path)
        self.prt = SimpleNamespace(controller=self.controller, cli=self.cli, webmcp=FakeWebMcp())
        self.sessions: Dict[str, Any] = {}
        self.stopped: List[str] = []

    def base_policy(self, *, allow_private_network=False, allowed_domains=()):
        return NetPolicy(allow_private_network=allow_private_network, blocked_local_ports=frozenset({5678}), allowed_domains=allowed_domains)

    def register_session(self, session):
        self.sessions[session.session_id] = session
        return session

    async def open(self, profile, *, wait):
        return self.prt

    async def stop_profile(self, profile_id, *, reason=""):
        self.stopped.append(profile_id)

    def running(self, profile_id):
        return self.prt


@pytest.fixture
def runtime(tmp_path):
    fake = FakeRuntime(tmp_path)
    profile = Profile(id="bp_1", owner_id="owner", name="Work", kind="shared", workflow_id=None, chrome_major=None)
    # The Workspace's step log (services/workspace_steps.py): what each test recorded.
    fake.steps = AsyncMock()
    with (
        patch("nodes.browser._runtime.get_browser_runtime", return_value=fake),
        patch("nodes.browser.browser._profile_for", AsyncMock(return_value=profile)),
        patch("nodes.browser._events.dispatch_browser_updated", AsyncMock()),
        patch("services.employees.node_signals.node_state_changed", lambda *a, **k: None),
        patch("services.workspace_steps.record_step", fake.steps),
    ):
        yield fake


def _ctx(**raw) -> NodeContext:
    return NodeContext(node_id="n1", node_type="browser", workflow_id="wf1", execution_id="e1", user_id="owner", raw=dict(raw))


async def _run(params: Dict[str, Any], **raw) -> Dict[str, Any]:
    # Most contract tests are about ordering, not wall-clock pacing. Tests
    # for admission explicitly select the production timing below.
    return await BrowserNode().execute("n1", {"min_action_interval_ms": 0, **params}, _ctx(**raw))


async def test_navigate_runs_the_script_and_reports_the_page(runtime):
    result = await _run({"operation": "navigate", "url": "https://example.com"})
    assert result.get("success") is not False, result
    op, args = runtime.cli.calls[-1]
    assert op == "navigate" and args["url"] == "https://example.com" and args["_target_id"] == "T1"
    assert result["url"] == "https://example.com/" and result["title"] == "Example"
    assert runtime.controller.state == ControlState.IDLE  # the step released control
    # The Workspace's step log names the site it opened.
    assert runtime.steps.await_args.kwargs == {"workflow_id": "wf1", "surface": "browser", "text": "Opened example.com", "node_id": "n1"}


@pytest.mark.parametrize("url", ["http://localhost:3000", "http://127.0.0.1:3000", "http://[::1]:3000"])
@pytest.mark.parametrize("operation", ["navigate", "tabs"])
async def test_local_apps_open_without_enabling_private_network(runtime, url, operation):
    result = await _run({"operation": operation, "url": url, "tab_action": "new"})
    assert result.get("success") is not False, result
    op, args = runtime.cli.calls[-1]
    assert op == operation and args["url"] == url


@pytest.mark.parametrize("url", ["file:///etc/passwd", "http://192.168.1.10:3000", "http://127.0.0.1:5678", "http://169.254.169.254/", "javascript:alert(1)"])
async def test_refused_urls_never_reach_the_browser(runtime, url):
    result = await _run({"operation": "navigate", "url": url})
    assert result.get("success") is False
    assert runtime.cli.calls == []


async def test_snapshot_refs_stay_server_side_and_resolve_for_click(runtime):
    runtime.cli.results.append(CliResult(ok=True, value={"text": "[e1] link \"Learn more\"", "refs": {"e1": 42}, "truncated": False}, page=dict(PAGE)))
    snap = await _run({"operation": "snapshot"})
    assert "[e1] link" in snap["snapshot"] and "WebMCP" in snap["snapshot"]
    assert "42" not in snap["snapshot"]

    await _run({"operation": "click", "ref": "e1"})
    op, args = runtime.cli.calls[-1]
    assert op == "click" and args["backend_node_id"] == 42 and "selector" not in args

    # An old agent-browser "@e1" selector means the same ref.
    await _run({"operation": "click", "selector": "@e1"})
    assert runtime.cli.calls[-1][1]["backend_node_id"] == 42

    missing = await _run({"operation": "click", "ref": "e9"})
    assert missing.get("success") is False and "snapshot" in missing["error"]


async def test_read_only_browser_refuses_changes(runtime):
    for op in ("click", "type", "press", "select", "webmcp_call"):
        result = await _run({"operation": op, "interaction": "read_only", "ref": "e1", "webmcp_tool": "buy"})
        assert result.get("success") is False and "read-only" in result["error"], op
    ok = await _run({"operation": "page_text", "interaction": "read_only"})
    assert ok.get("success") is not False


async def test_a_retried_change_is_not_repeated(runtime):
    with patch("nodes.browser.browser._attempt", return_value=2):
        result = await _run({"operation": "click", "x": 10, "y": 10})
    assert result.get("success") is False and "snapshot" in result["error"]
    assert runtime.cli.calls == []


async def test_a_tool_call_cannot_change_the_operator_settings(runtime):
    saved = {"operation": "navigate", "interaction": "read_only", "allow_private_network": False, "webmcp_mode": "disabled"}
    database = SimpleNamespace(get_node_parameters=AsyncMock(return_value=saved))
    node = BrowserNode()
    with patch("services.plugin.deps.get_database", return_value=database):
        # On the Temporal path the model's arguments arrive merged over the saved ones.
        merged = {**saved, "operation": "click", "x": 5, "y": 5, "interaction": "full", "allow_private_network": True}
        result = await node.execute_as_tool({"operation": "click", "x": 5, "y": 5, "interaction": "full"}, merged, _ctx(tool_args={"operation": "click"}))
    assert "read-only" in (result.get("error") or "")
    assert runtime.cli.calls == []


@pytest.mark.parametrize("adapter", ["in_process", "temporal"])
async def test_trusted_ask_first_restriction_survives_saved_full_settings(runtime, adapter):
    saved = {"interaction": "full"}
    database = SimpleNamespace(get_node_parameters=AsyncMock(return_value=saved))
    raw = {"tool_args": {"operation": "click", "interaction": "full"}} if adapter == "temporal" else {}
    with patch("services.plugin.deps.get_database", return_value=database):
        result = await BrowserNode().execute_as_tool({"operation": "click", "x": 5, "y": 5, "interaction": "full"},
                                                     {"interaction": "read_only"}, _ctx(**raw))
    assert "read-only" in result["error"]
    assert runtime.cli.calls == []


async def test_task_lifetime_prevents_same_node_interleaving(runtime):
    runtime.controller.claim_task("another-task")
    result = await _run({"operation": "snapshot"})
    assert result.get("success") is False and result["error_type"] == "BrowserBusy"
    assert runtime.cli.calls == []


async def test_an_action_tells_the_live_view_where_it_happened(runtime):
    seen: List[tuple] = []

    async def listen(kind, payload):
        seen.append((kind, payload))

    runtime.controller.add_listener(listen)
    runtime.cli.results.append(CliResult(ok=True, value={"x": 40.0, "y": 60.0}, page=dict(PAGE), extra={"cursor": {"x": 40.0, "y": 60.0}}))
    clicked = await _run({"operation": "click", "x": 40, "y": 60})
    # The agent's result is the script's value, nothing added.
    assert clicked["data"] == {"x": 40.0, "y": 60.0} and "cursor" not in clicked
    assert ("agent_action", {"action": "click", "target_id": "T1", "x": 40.0, "y": 60.0}) in seen

    runtime.cli.results.append(CliResult(ok=True, value={"typed_chars": 2, "submitted": False}, page=dict(PAGE), extra={"cursor": {"box": [1, 2, 30, 10]}}))
    await _run({"operation": "type", "selector": "#q", "text": "hi"})
    assert ("agent_action", {"action": "type", "target_id": "T1", "box": [1.0, 2.0, 30.0, 10.0]}) in seen


@pytest.mark.parametrize("cursor", [{"x": "1", "y": 2}, {"x": float("nan"), "y": 2}, {"box": [1, 2, -3, 4]}, {"box": [1, 2, 3]}, "1,2"])
async def test_a_made_up_position_is_not_shown(runtime, cursor):
    seen: List[str] = []

    async def listen(kind, payload):
        seen.append(kind)

    runtime.controller.add_listener(listen)
    runtime.cli.results.append(CliResult(ok=True, value={}, page=dict(PAGE), extra={"cursor": cursor}))
    result = await _run({"operation": "click", "x": 1, "y": 2})
    assert result.get("success") is not False
    assert "agent_action" not in seen


async def test_sensitive_login_blocks_browser_observations(runtime):
    runtime.controller.sensitive_login = True
    for operation in ("snapshot", "screenshot", "page_text", "page_info", "tabs", "webmcp_list"):
        result = await _run({"operation": operation})
        assert result["error_type"] == "sensitive_login"
        assert result.get("url") is None and result.get("title") is None
    assert runtime.cli.calls == []


def test_the_model_schema_has_no_operator_settings_or_host_code():
    schema = BrowserToolInput.model_json_schema()
    props = set(schema["properties"])
    for locked in ("profile_id", "interaction", "webmcp_mode", "allowed_domains", "allow_private_network", "code", "expression", "op_timeout_s"):
        assert locked not in props
    ops = set(schema["properties"]["operation"]["enum"])
    assert not ops & {"evaluate", "run_python", "close"}
    assert BrowserNode.server_controlled_fields >= {"profile_id", "interaction", "allow_private_network", "code"}


async def test_webmcp_mode_decides_what_the_agent_may_call(runtime):
    listed = await _run({"operation": "webmcp_list", "webmcp_mode": "read_only"})
    callable_by_name = {t["name"]: t["callable"] for t in listed["webmcp_tools"]}
    assert callable_by_name == {"search": True, "buy": False}
    refused = await _run({"operation": "webmcp_call", "webmcp_tool": "buy", "webmcp_mode": "read_only"})
    assert refused.get("success") is False
    done = await _run({"operation": "webmcp_call", "webmcp_tool": "buy", "webmcp_input": '{"qty": 1}', "webmcp_mode": "all"})
    assert done["webmcp_result"]["status"] == "completed"
    assert runtime.prt.webmcp.invoked[-1] == ("buy", {"qty": 1}, "all")


async def test_request_user_waits_for_the_hand_back(runtime):
    task = asyncio.create_task(_run({"operation": "request_user", "reason": "login", "message": "Please sign in"}))
    for _ in range(50):
        await asyncio.sleep(0.01)
        if runtime.controller.state == ControlState.AWAITING_USER:
            break
    assert runtime.controller.state == ControlState.AWAITING_USER
    assert runtime.controller.pending.message == "Please sign in"
    granted, _ = await runtime.controller.take_over("viewer-1")
    assert granted and runtime.controller.state == ControlState.USER
    await runtime.controller.hand_back("viewer-1", note="signed in")
    result = await asyncio.wait_for(task, 5)
    assert result["handback"] == {"status": "handed_back", "note": "signed in"}
    assert runtime.controller.state == ControlState.IDLE


async def test_legacy_agent_browser_parameters_still_validate(runtime):
    result = await _run({"operation": "fill", "selector": "#q", "value": "hello", "session": "old", "headed": True, "timeout": 12})
    op, args = runtime.cli.calls[-1]
    assert op == "type" and args["text"] == "hello" and args["clear"] is True and args["selector"] == "#q"
    assert result.get("success") is not False


async def test_the_profile_dropdown_lists_the_callers_profiles_not_a_client_named_user():
    import nodes.browser  # noqa: F401 - registers the browserProfiles loader
    from services.ws_handler_registry import dispatch_load_options

    listed: List[str] = []

    class Store:
        def __init__(self, database) -> None:
            pass

        async def list(self, owner: str):
            listed.append(owner)
            return []

    with patch("nodes.browser._handlers.ProfileStore", Store), patch("nodes.browser._handlers.get_database", lambda: None):
        await dispatch_load_options("browserProfiles", {"user_id": "someone-else"}, principal="alice")
    assert listed == ["alice"]


async def test_success_keeps_the_flat_tool_contract(runtime):
    result = await _run({"operation": "page_info"})
    assert "success" not in result
    assert BrowserNode.interpret_result(result) == (True, result, None)


@pytest.mark.parametrize("params", [{"operation": "navigate", "url": "https://example.com"}, {"operation": "tabs", "tab_action": "new", "url": "https://example.com"}, {"operation": "tabs", "tab_action": "close", "tab_id": "T1"}])
async def test_navigation_and_tab_changes_are_not_replayed_by_temporal(runtime, params):
    with patch("nodes.browser.browser._attempt", return_value=2):
        result = await _run(params)
    assert result["success"] is False
    assert not runtime.cli.calls


@pytest.mark.parametrize("error_class", ["BrowserUnavailable", "BrowserStepOutcomeUnknown", "BrowserStepTimeout"])
async def test_uncertain_navigation_is_not_replayed_and_requires_observation(runtime, error_class):
    from nodes.browser import _cli

    runtime.cli.run = AsyncMock(side_effect=getattr(_cli, error_class)("lost reply"))
    result = await _run({"operation": "navigate", "url": "https://example.com"})
    assert result["error_type"] == "outcome_unknown"
    assert runtime.cli.run.await_count == 1
    denied = await _run({"operation": "click", "x": 4, "y": 4})
    assert denied["error_type"] == "outcome_unknown"
    assert runtime.cli.run.await_count == 1
    runtime.cli.run.side_effect = None
    runtime.cli.run.return_value = CliResult(ok=True, value={}, page=dict(PAGE))
    await _run({"operation": "snapshot"})
    assert not runtime.controller.needs_observation
    allowed = await _run({"operation": "click", "x": 4, "y": 4})
    assert allowed.get("success") is not False


async def test_site_rate_limit_does_not_block_observations(runtime):
    first = await _run({"operation": "navigate", "url": "https://example.com", "min_action_interval_ms": 60000})
    assert first.get("success") is not False
    denied = await _run({"operation": "click", "x": 2, "y": 2, "min_action_interval_ms": 60000})
    assert denied["error_type"] == "rate_limited" and denied["retry_after"] > 0
    assert len(runtime.cli.calls) == 1
    observed = await _run({"operation": "snapshot", "min_action_interval_ms": 60000})
    assert observed.get("success") is not False


async def test_irrelevant_fields_cannot_evade_repeat_limit(runtime):
    params = {"operation": "navigate", "url": "https://example.com", "max_repeat_actions": 1}
    await _run(params)
    denied = await _run({**params, "max_chars": 50000})
    assert denied["error_type"] == "repeat_limit"
    assert len(runtime.cli.calls) == 1


async def test_challenge_pauses_operations_until_explicit_owner_handback(runtime):
    runtime.cli.results.append(CliResult(ok=False, error_type="challenge_required", error="Please finish the site verification.", page=dict(PAGE)))
    result = await _run({"operation": "navigate", "url": "https://example.com"})
    assert result["error_type"] == "challenge_required" and result["next_action"] == "request_user"
    assert runtime.controller.state == ControlState.AWAITING_USER
    assert runtime.controller.pending.reason == "captcha"
    denied = await _run({"operation": "click", "x": 4, "y": 4})
    assert denied["error_type"] == "challenge_required" and len(runtime.cli.calls) == 1
    await runtime.controller.take_over("viewer")
    await runtime.controller.hand_back("viewer", outcome="control_lost")
    assert runtime.controller.challenge_required
    await runtime.controller.take_over("viewer")
    await runtime.controller.hand_back("viewer")
    assert not runtime.controller.challenge_required
    assert (await _run({"operation": "snapshot"})).get("success") is not False


async def test_webmcp_cannot_bypass_challenge_detection(runtime):
    runtime.cli.results.append(CliResult(ok=False, error_type="challenge_required", error="Please finish verification.", page=dict(PAGE)))
    result = await _run({"operation": "webmcp_call", "webmcp_tool": "search"})
    assert result["error_type"] == "challenge_required"
    assert not runtime.prt.webmcp.invoked


@pytest.mark.parametrize("config", [{"interaction": "read_only"}, {"webmcp_mode": "disabled"}])
async def test_webmcp_listing_matches_enforced_permissions(runtime, config):
    listed = await _run({"operation": "webmcp_list", **config})
    assert all(not tool["callable"] for tool in listed["webmcp_tools"])


async def test_tool_arguments_cannot_raise_saved_action_limits(runtime):
    saved = {"min_action_interval_ms": 0, "max_actions_per_minute": 1}
    database = SimpleNamespace(get_node_parameters=AsyncMock(return_value=saved))
    args = {"operation": "navigate", "url": "https://example.com", "max_actions_per_minute": 300}
    with patch("services.plugin.deps.get_database", return_value=database):
        first = await BrowserNode().execute_as_tool(args, {**saved, **args}, _ctx())
        second = await BrowserNode().execute_as_tool({**args, "url": "https://example.com/next"}, {**saved, **args}, _ctx())
    assert first.get("success") is not False
    assert second["error_type"] == "rate_limited"
    assert len(runtime.cli.calls) == 1


async def test_webmcp_unknown_outcome_requires_observation(runtime):
    from nodes.browser._webmcp import WebMcpOutcomeUnknown

    runtime.prt.webmcp.invoke = AsyncMock(side_effect=WebMcpOutcomeUnknown("The invocation reply was lost."))
    failed = await _run({"operation": "webmcp_call", "webmcp_tool": "search", "op_timeout_s": 7})
    assert failed["error_type"] == "outcome_unknown"
    assert runtime.controller.needs_observation
    assert runtime.prt.webmcp.invoke.call_args.kwargs["timeout"] <= 7
    blocked = await _run({"operation": "navigate", "url": "https://example.com/next"})
    assert blocked["error_type"] == "outcome_unknown"
    assert len(runtime.cli.calls) == 1  # only the preflight observation


@pytest.mark.parametrize("operation", ["navigate", "webmcp_call"])
async def test_cancelled_site_action_requires_observation(runtime, operation):
    if operation == "navigate":
        runtime.cli.run = AsyncMock(side_effect=asyncio.CancelledError)
    else:
        runtime.prt.webmcp.invoke = AsyncMock(side_effect=asyncio.CancelledError)
    with pytest.raises(asyncio.CancelledError):
        await _run({"operation": operation, "url": "https://example.com", "webmcp_tool": "search"})
    assert runtime.controller.needs_observation
    blocked = await _run({"operation": "click", "x": 4, "y": 4})
    assert blocked["error_type"] == "outcome_unknown"