Skip to content

Self-improving AI Employees for everyone

fix(browser): pass the task's claim token to the Browser node

trohitgc50ad6d4fa35
diff --git a/server/nodes/browser/_credentials.py b/server/nodes/browser/_credentials.py
index ad0379cc..f237e6f4 100644
--- a/server/nodes/browser/_credentials.py
+++ b/server/nodes/browser/_credentials.py
@@ -81,7 +81,7 @@ async def fill_credentials(ctx: Any, runtime: Any, call: Any, *, timeout: float)
from services.plugin.deps import get_database
controller = runtime.controller
- task_id = str(ctx.raw.get("_browser_task_id") or ctx.execution_id or "")
+ task_id = ctx.raw.get("_browser_task_id")
if controller.task_id is not None and controller.task_id != task_id:
return {"success": False, "error_type": "BrowserBusy", "error": "This profile belongs to another task."}
page = None
diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.py
index 42c17907..e76c1e26 100644
--- a/server/nodes/browser/browser/__init__.py
+++ b/server/nodes/browser/browser/__init__.py
@@ -375,6 +375,10 @@ class BrowserNode(ToolNode):
hide_output_handle = False
ui_hints = {"isBrowserPanel": True, "isConfigNode": False}
annotations = {"destructive": True, "readonly": False, "open_world": True}
+ # The task's claim token and frozen binding and settings
+ # (services/browser_owners.py); a call that has none belongs to no task.
+ context_keys = ("_browser_task_id", "_browser_owner", "parameter_snapshot",
+ "native_workspace_version", "browser_runtime_version", "browser_routing_version")
task_queue = TaskQueue.BROWSER
# A page can do anything its logins allow; while the owner asks first
# it only reads, and hands changes to them (request_user).
@@ -450,7 +454,7 @@ class BrowserNode(ToolNode):
runtime = get_browser_runtime()
profile = await _profile_for(ctx, cfg)
owner = ctx.user_id or "owner"
- task_id = str(ctx.raw.get("_browser_task_id") or ctx.execution_id or "")
+ task_id = ctx.raw.get("_browser_task_id")
from services.browser_owners import assert_owner, bind_profile, _persistent
from services.plugin.deps import get_database
if ctx.raw.get("_browser_owner") or _persistent(get_database()):
diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.py
index 428750bd..2c1d9fd1 100644
--- a/server/services/handlers/tools.py
+++ b/server/services/handlers/tools.py
@@ -250,6 +250,8 @@ async def _dispatch_tool(tool_name: str, tool_args: Dict[str, Any], config: Dict
if checked.tool_args is not None:
tool_args = checked.tool_args
+ # The scope this plugin reads itself (BaseNode.context_keys).
+ context.update({key: config[key] for key in plugin_cls.context_keys if key in config})
instance = plugin_cls()
ctx = NodeContext.from_legacy(
node_id=config.get("node_id", f"tool_{node_type}"),
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index f25ad613..3e6e289a 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -282,6 +282,12 @@ class BaseNode:
# context). Currently only :class:`AgentBuilderNode` opts in.
needs_canvas: ClassVar[bool] = False
+ # Server-owned execution scope this plugin reads from ``ctx.raw``, such
+ # as the Browser's claim token. Both tool adapters (``as_activity`` and
+ # the in-process ``_dispatch_tool``) copy these keys from the run's
+ # context; a model's arguments never supply them.
+ context_keys: ClassVar[Sequence[str]] = ()
+
# Wave 12 D5: LLM-visible name + description for plugins surfaced as
# AI tools (ToolNode subclasses, ActionNodes marked usable_as_tool=True,
# SpecializedAgentBase subclasses).
@@ -1292,6 +1298,8 @@ class BaseNode:
# what it shows goes (show_ui, services/chat/parts.py).
"chat_stream",
"chat_run_id",
+ # The scope this plugin reads itself (context_keys).
+ *cls.context_keys,
):
if key in context:
extras[key] = context[key]
diff --git a/server/tests/nodes/browser/test_browser_owners.py b/server/tests/nodes/browser/test_browser_owners.py
index f28e3575..d6043897 100644
--- a/server/tests/nodes/browser/test_browser_owners.py
+++ b/server/tests/nodes/browser/test_browser_owners.py
@@ -419,6 +419,32 @@ async def test_reset_of_browser_agent_without_exactly_one_browser_tool_is_a_noop
execution_id="2:execution:5", generation=5, graph=graph, database=db) == {"reset": False}
+async def test_the_browser_checks_its_claim_with_the_task_token_not_the_run_id(database):
+ from nodes.browser.browser import BrowserNode, BrowserParams
+ from services.plugin.context import NodeContext
+
+ db, controller = database
+ binding = await owners.bind_profile(db, "profile", "owner")
+ await owners.claim_browser_task(db, binding, "owner", "agent-workflow")
+
+ class PastOwnership(Exception):
+ pass
+
+ runtime = SimpleNamespace(controller_for=lambda _: controller, controller=lambda _: controller,
+ base_policy=Mock(side_effect=PastOwnership))
+
+ def call(**scope):
+ return NodeContext.from_legacy("browser", "browser", {"workflow_id": "wf", "user_id": "owner",
+ "execution_id": "wf:execution:3", "_browser_owner": binding, **scope})
+
+ with patch("services.plugin.deps.get_database", return_value=db), \
+ patch("nodes.browser._runtime.get_browser_runtime", return_value=runtime):
+ with pytest.raises(PastOwnership):
+ await BrowserNode().dispatch(call(_browser_task_id="agent-workflow"), BrowserParams(operation="snapshot"))
+ with pytest.raises(NodeUserError, match="BrowserBusy"):
+ await BrowserNode().dispatch(call(), BrowserParams(operation="snapshot"))
+
+
async def test_ambiguous_active_browser_bindings_fail_closed(database):
db, _ = database
db.get_node_parameters = AsyncMock(return_value={})
diff --git a/server/tests/nodes/browser/test_browser_task_scope.py b/server/tests/nodes/browser/test_browser_task_scope.py
new file mode 100644
index 00000000..e724220f
--- /dev/null
+++ b/server/tests/nodes/browser/test_browser_task_scope.py
@@ -0,0 +1,93 @@
+"""The browser task's claim token reaches the Browser node on both tool paths.
+
+An agent claims its browser profile with a token (its workflow id) and sends
+it with every browser call. ``BaseNode.as_activity`` and the in-process
+``_dispatch_tool`` hand a node the keys it declares in ``context_keys``;
+before they did, the node compared the claim with the run's execution id and
+refused its own task (BrowserBusy).
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from temporalio.testing import ActivityEnvironment
+
+import nodes # noqa: F401 -- populate plugin registry
+from services.node_registry import get_node_class
+
+pytestmark = pytest.mark.asyncio
+
+TOKEN = "AI_Employee_1-Task_Completed-task_1:terminal-agent-2:ai_employee:1-delegate-2:browser_agent:1-1-1-task_1"
+SCOPE = {
+ "_browser_task_id": TOKEN,
+ "_browser_owner": {"profile_id": "profile", "owner_id": "local", "profile_task_id": TOKEN},
+ "parameter_snapshot": {"wf:browser:1": {"interaction": "full"}},
+ "native_workspace_version": 1,
+ "browser_runtime_version": 1,
+ "browser_routing_version": 1,
+}
+SNAPSHOT = {"operation": "snapshot"}
+
+
+def service(monkeypatch):
+ import core.container as container_module
+ import services.status_broadcaster as status_broadcaster
+ from services.approvals import tool_calls
+
+ workflow_service = MagicMock()
+ workflow_service.execute_node = AsyncMock(return_value={"success": True, "result": {}})
+ monkeypatch.setattr(container_module, "container", SimpleNamespace(workflow_service=lambda: workflow_service))
+ monkeypatch.setattr(status_broadcaster, "get_status_broadcaster", lambda: AsyncMock())
+ # Ask first is covered elsewhere (tests/services/approvals): every call here runs as sent.
+ monkeypatch.setattr(tool_calls, "check",
+ AsyncMock(return_value=SimpleNamespace(result=None, node_data=None, tool_args=None, record=None)))
+ return workflow_service
+
+
+def call(node_id: str, args: dict, **scope) -> dict:
+ return {
+ "node_id": node_id,
+ "workflow_id": "wf",
+ "execution_id": "wf:execution:3",
+ "user_id": "owner",
+ "parent_node_id": "wf:browser_agent:1",
+ "tool_call_id": "call_1",
+ "node_data": dict(args),
+ "tool_args": dict(args),
+ **scope,
+ }
+
+
+async def test_the_activity_hands_the_browser_its_task_scope(service):
+ await ActivityEnvironment().run(get_node_class("browser").as_activity(), call("wf:browser:1", SNAPSHOT, **SCOPE))
+ extras = service.execute_node.await_args.kwargs["extras"]
+ assert {key: extras.get(key) for key in SCOPE} == SCOPE
+
+
+async def test_a_node_that_does_not_read_the_scope_is_not_handed_it(service):
+ add = {"operation": "add", "a": 1, "b": 2}
+ await ActivityEnvironment().run(get_node_class("calculatorTool").as_activity(), call("wf:calculatorTool:1", add, **SCOPE))
+ assert not set(SCOPE) & set(service.execute_node.await_args.kwargs["extras"])
+
+
+async def test_in_process_dispatch_hands_the_browser_its_task_scope(monkeypatch):
+ from services.approvals import tool_calls
+ from services.handlers import tools
+
+ seen: dict = {}
+
+ async def execute_as_tool(self, tool_args, node_params, ctx):
+ seen.update(ctx.raw)
+ return {"success": True}
+
+ monkeypatch.setattr(get_node_class("browser"), "execute_as_tool", execute_as_tool)
+ monkeypatch.setattr(tool_calls, "check_in_process",
+ AsyncMock(return_value=SimpleNamespace(result=None, node_data=None, tool_args=None)))
+ config = {"node_type": "browser", "node_id": "wf:browser:1", "parameters": {}, "workflow_id": "wf",
+ "execution_id": "wf:execution:3", "user_id": "owner", **SCOPE}
+ await tools._dispatch_tool("browser", dict(SNAPSHOT), config)
+ assert {key: seen.get(key) for key in SCOPE} == SCOPE
diff --git a/server/tests/services/test_agent_bindings.py b/server/tests/services/test_agent_bindings.py
index 5e15afc6..e6377a3f 100644
--- a/server/tests/services/test_agent_bindings.py
+++ b/server/tests/services/test_agent_bindings.py
@@ -161,6 +161,7 @@ async def test_native_tool_dispatch_preserves_server_execution_scope(monkeypatch
captured = {}
class Tool:
credentials = ()
+ context_keys = ()
async def execute_as_tool(self, args, params, context):
captured.update(context.raw)
return {"success": True}