From 31517898cd1a721b8cf73b82d531c656f5c258f1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 8 Nov 2026 22:54:42 -0800 Subject: [PATCH 1/4] feat(browser): browser_sign_in, and browser steps reach a multi env's computers (FD-4944) browser_sign_in {site, user} signs an env's website browser in to a site as a user: the site's website/v1 session gives the cookies and local storage, each cookie is set for every name the site is reached by (an exact name by its URL, a *. name as a domain cookie), and the browser's data/add loads them, which opens its start tabs again while no agent has acted. The site is a website env deployed in the run on its own or in a multi env, by its env id. A task runs the step after the load that seeds the site and again after reset_env. Every browser step now reaches a browser app inside a multi env's computer, through the computer's own record and control token kept in the multi env's record, since the gateway lists a computer but not its apps. browser_connect_cdp refuses one for now: its agents reach it through the gateway, whose address it doesn't hand out yet. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/browsers/README.md | 9 +- src/agent_env/task/episode/rules.py | 2 +- src/agent_env/task_step/registry.py | 2 + .../task_step/task_steps/browser/base.py | 41 +++-- .../task_steps/browser/connect_cdp.py | 4 + .../task_step/task_steps/browser/sign_in.py | 137 ++++++++++++++ tst/data/session_website/Dockerfile | 12 ++ tst/data/session_website/server.py | 12 ++ .../computer/website_browser_test.py | 79 ++++++++- tst/unit/task_step/test_browser_sign_in.py | 167 ++++++++++++++++++ 10 files changed, 448 insertions(+), 17 deletions(-) create mode 100644 src/agent_env/task_step/task_steps/browser/sign_in.py create mode 100644 tst/data/session_website/Dockerfile create mode 100644 tst/data/session_website/server.py create mode 100644 tst/unit/task_step/test_browser_sign_in.py diff --git a/src/agent_env/browsers/README.md b/src/agent_env/browsers/README.md index 8da52800a..ac480a816 100644 --- a/src/agent_env/browsers/README.md +++ b/src/agent_env/browsers/README.md @@ -26,6 +26,13 @@ values, the origin's other keys left as they are; `browser_clear_local_storage { `browser_open_tab {url, background?}`, in front, or with `background` behind the active tab, which stays active; and `browser_close_tab {url}` and `browser_activate_tab {url}`, on the one open tab at that URL as the browser shows it (scheme and host lowercase, no default port, `/` for an empty path), none or several failing the step with the tabs -open listed. Preflight refuses a step on an env with no browser, none of the name given, or several and none named. +open listed. `browser_sign_in {site, user}` signs the browser in to `site`, a website env deployed in the run on its +own or in a multi env, by its env id: the site's `website/v1` `session {user}` gives the cookies and local storage, +each cookie is set for every name the site is reached by (an exact name by its URL, a `*.` name as a domain cookie), +and the browser's `data/add` loads them, which opens the start tabs again while no agent has acted. A task runs it +after the load that seeds the site and again after `reset_env`, which starts the browser afresh. Preflight refuses a +step on an env with no browser, none of the name given, or several and none named. On a multi env, the steps reach +the browser apps of its computers, each through the computer's own record and control token; `browser_connect_cdp` +doesn't reach those yet. `browser_connect_cdp` hands an agent a CDP address to the same browser. A whole state, Playwright's `storageState` included, loads through `load_artifact` or `data/add` instead. diff --git a/src/agent_env/task/episode/rules.py b/src/agent_env/task/episode/rules.py index a2e9efc50..0bfb1d51d 100644 --- a/src/agent_env/task/episode/rules.py +++ b/src/agent_env/task/episode/rules.py @@ -150,7 +150,7 @@ def _rubrics_verifier(step: RubricsVerifierTaskStep, outside: Outside) -> list[s UNAFFECTED = frozenset({ # They name no agent. "aggregate_verifiers", "apply_server_config", "browser_activate_tab", "browser_clear_local_storage", - "browser_close_tab", "browser_delete_cookies", "browser_open_tab", "browser_set_cookies", + "browser_close_tab", "browser_delete_cookies", "browser_open_tab", "browser_set_cookies", "browser_sign_in", "browser_set_local_storage", "build_mcp_cli", "combine_universe_verdicts", "configure_scheduled_checks", "deploy_env", "deploy_sandbox", "end_computer_recording", "start_computer_recording", "env_outcome_verifier", "modify_env_tool_access", "reset_env", "review", diff --git a/src/agent_env/task_step/registry.py b/src/agent_env/task_step/registry.py index 1b9a3f298..d428aeb41 100644 --- a/src/agent_env/task_step/registry.py +++ b/src/agent_env/task_step/registry.py @@ -29,6 +29,7 @@ def get_task_step_registry() -> dict[str, type["TaskStep"]]: def _builtin_registry() -> dict[str, type["TaskStep"]]: from agent_env.task_step.task_steps.browser.connect_cdp import BrowserConnectCdpTaskStep from agent_env.task_step.task_steps.browser.cookies import BrowserDeleteCookiesTaskStep, BrowserSetCookiesTaskStep + from agent_env.task_step.task_steps.browser.sign_in import BrowserSignInTaskStep from agent_env.task_step.task_steps.browser.local_storage import ( BrowserClearLocalStorageTaskStep, BrowserSetLocalStorageTaskStep, @@ -100,6 +101,7 @@ def _builtin_registry() -> dict[str, type["TaskStep"]]: _get_type(BuildMcpCliTaskStep): BuildMcpCliTaskStep, _get_type(BrowserConnectCdpTaskStep): BrowserConnectCdpTaskStep, _get_type(BrowserSetCookiesTaskStep): BrowserSetCookiesTaskStep, + _get_type(BrowserSignInTaskStep): BrowserSignInTaskStep, _get_type(BrowserDeleteCookiesTaskStep): BrowserDeleteCookiesTaskStep, _get_type(BrowserSetLocalStorageTaskStep): BrowserSetLocalStorageTaskStep, _get_type(BrowserClearLocalStorageTaskStep): BrowserClearLocalStorageTaskStep, diff --git a/src/agent_env/task_step/task_steps/browser/base.py b/src/agent_env/task_step/task_steps/browser/base.py index 7b25f21be..87f982ab0 100644 --- a/src/agent_env/task_step/task_steps/browser/base.py +++ b/src/agent_env/task_step/task_steps/browser/base.py @@ -1,5 +1,6 @@ -"""BrowserStep: a task step on the website browser in a deployed env, found among the env's children by its card, and -called through browser/v1 with the env's control token.""" +"""BrowserStep: a task step on the website browser in a deployed env, found among the env's children by its card, or +among those of a multi env's computers by each computer's own record, and called through browser/v1 with the control +token of the record that serves it.""" from __future__ import annotations @@ -10,6 +11,7 @@ from agent_env.env.env import DeployedEnv, Env from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.envs.multi_env import MultiEnv from agent_env.task_step.context import TaskStepContext from agent_env.task_step.preflight import stored_env from agent_env.task_step.task_step import TaskStep, TaskStepDependency @@ -65,9 +67,9 @@ def _browser_from_dict(cls, data: dict) -> dict: return {**cls._base_from_dict(data), "env_id": data["env_id"], "browser": data.get("browser")} def _find(self, context: TaskStepContext) -> tuple[DeployedEnv, Optional[str], dict]: - """The deployed env, and its browser's name, None for the env itself, and card.""" - deployed = deployed_env(context, self.env_id) - return (deployed, *find_browser(deployed, self.browser)) + """The record that serves the browser, the deployed env's or a multi env's computer's, and the browser's name, + None for that record's env itself, and card.""" + return find_browser(deployed_env(context, self.env_id), self.browser) async def _call(self, context: TaskStepContext, op: str, params: dict, timeout_s: float = CALL_TIMEOUT_S) -> Any: @@ -86,7 +88,9 @@ def _record(self, context: TaskStepContext, **fields: Any) -> None: def stored_browsers(env: Env) -> list[str]: """The names of the website browsers a stored env deploys: a computer env's browser apps, the app itself for one - deployed alone; none for any other env.""" + deployed alone, a multi env's computers' browser apps; none for any other env.""" + if isinstance(env, MultiEnv): + return [name for computer in env.computer_envs for name in stored_browsers(computer)] if not isinstance(env, ComputerEnv): return [] return [app.environment_name for app in env.composed_apps() if app.declaration.browser] @@ -99,15 +103,16 @@ def deployed_env(context: TaskStepContext, env_id: str) -> DeployedEnv: return deployed -def find_browser(deployed: DeployedEnv, named: Optional[str]) -> tuple[Optional[str], dict]: - """The website browser in ``deployed``, the one ``named`` else its only one: its name among the env's children, - or None for the env itself, and its card.""" - card = deployed.environment_card or {} - browsers = [(None, card)] if find_extension(card, BROWSER) else [] - browsers += [(child.get("name"), child) for child in card.get("children_environments") or [] - if find_extension(child, BROWSER)] +def find_browser(deployed: DeployedEnv, named: Optional[str]) -> tuple[DeployedEnv, Optional[str], dict]: + """The website browser in ``deployed``, the one ``named`` else its only one: the record that serves it, its name + among that record's children, or None for the record's env itself, and its card. A multi env's gateway lists its + computers but not their apps, so a browser in one is found by the computer's own record, kept in the multi env's + (``DeployedGatewayEnv.child_envs``), whose control token reaches it.""" + browsers = _browsers(deployed) + for data in (getattr(deployed, "child_envs", None) or {}).values(): + browsers += _browsers(DeployedEnv.from_dict(data)) if named is not None: - found = next((browser for browser in browsers if browser[0] == named), None) + found = next((browser for browser in browsers if browser[1] == named), None) if found is None: raise RuntimeError(f"env {deployed.env_id!r} has no website browser named {named!r}") return found @@ -115,3 +120,11 @@ def find_browser(deployed: DeployedEnv, named: Optional[str]) -> tuple[Optional[ raise RuntimeError(f"env {deployed.env_id!r} has {len(browsers) or 'no'} website browsers" + (": name one as browser" if browsers else "")) return browsers[0] + + +def _browsers(record: DeployedEnv) -> list[tuple[DeployedEnv, Optional[str], dict]]: + """The website browsers ``record``'s card offers: its env itself, and each of its children that is one.""" + card = record.environment_card or {} + found = [(record, None, card)] if find_extension(card, BROWSER) else [] + return found + [(record, child.get("name"), child) for child in card.get("children_environments") or [] + if find_extension(child, BROWSER)] diff --git a/src/agent_env/task_step/task_steps/browser/connect_cdp.py b/src/agent_env/task_step/task_steps/browser/connect_cdp.py index 423323053..4b88310a0 100644 --- a/src/agent_env/task_step/task_steps/browser/connect_cdp.py +++ b/src/agent_env/task_step/task_steps/browser/connect_cdp.py @@ -75,6 +75,10 @@ def from_dict(cls, data: dict) -> BrowserConnectCdpTaskStep: async def execute(self, context: TaskStepContext) -> TaskStepContext: deployed, browser, _ = self._find(context) + if deployed.env_id != self.env_id: + raise RuntimeError(f"the website browser {browser!r} is in a computer of the multi env {self.env_id!r}, whose " + "agents reach it through the multi env's gateway; browser_connect_cdp doesn't hand out " + "that address yet") agent = _deployed_agent(context, self.agent_name) cdp_config = A2AAgent.find_extension(agent.a2a_card or {}, A2AAgent.EXT_CDP_CONFIG) if cdp_config is None or not agent.a2a_url: diff --git a/src/agent_env/task_step/task_steps/browser/sign_in.py b/src/agent_env/task_step/task_steps/browser/sign_in.py new file mode 100644 index 000000000..11dd7dd27 --- /dev/null +++ b/src/agent_env/task_step/task_steps/browser/sign_in.py @@ -0,0 +1,137 @@ +"""browser_sign_in: an env's website browser signed in to a site as a user, with the cookies and local storage the +site's website/v1 session gives, scoped to the site's names and loaded through the browser's data/add.""" + +from __future__ import annotations + +import logging +from typing import ClassVar, Optional + +from agentenv_protocol import METHOD_ADD, DataPart, client as protocol_v1 +from agentenv_protocol.website import WEBSITE_EXTENSION_URI + +from agent_env.entity.refs import EntityRef +from agent_env.env.env import DeployedEnv, Env +from agent_env.env.envs.computer.utils import sites +from agent_env.env.envs.website import WebsiteEnv +from agent_env.store.base import NotFoundError +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.preflight import stored_env +from agent_env.task_step.task_step import TaskStepDependency +from agent_env.task_step.task_steps.browser.base import BrowserStep + +logger = logging.getLogger(__name__) + +#: How long a site may take to answer for a session, and the browser to load it. +SESSION_TIMEOUT_S = 30 +ADD_TIMEOUT_S = 120 + + +class BrowserSignInTaskStep(BrowserStep): + """Sign the browser in to the website env ``site``, deployed in the run on its own or in a multi env, as ``user``: + the site's ``session {user}`` gives the cookies and local storage, each cookie is set for every name the site is + reached by, and the browser's ``data/add`` loads them, which opens its start tabs again while no agent has acted. + A task runs it after the load that seeds the site, and again after a reset, which starts the browser afresh.""" + + type: ClassVar[str] = "browser_sign_in" + entity_refs = (EntityRef.env("env_id"), EntityRef.env("site")) + + def __init__(self, id: str, version: Optional[int], env_id: str, site: str, user: str, + browser: Optional[str] = None, depends_on: Optional[list[TaskStepDependency]] = None, + fail_task_on_error: bool = True): + super().__init__(id, version, env_id, browser, depends_on=depends_on, fail_task_on_error=fail_task_on_error) + self.site = site + self.user = user + + def config_problems(self) -> list[str]: + problems = super().config_problems() + if not isinstance(self.site, str) or not self.site: + problems.append(f"step {self.id!r}: site must be a website env's id") + if not isinstance(self.user, str) or not self.user: + problems.append(f"step {self.id!r}: user must be a non-empty string; browser_delete_cookies signs out") + return problems + + def preflight(self) -> list[str]: + problems = super().preflight() + if not isinstance(self.site, str) or not self.site: + return problems + site = stored_env(self.site) + if site is not None and not isinstance(site, WebsiteEnv): + problems.append(f"step {self.id!r}: site {self.site!r} is a {type(site).__name__}, not a website env") + return problems + + def to_dict(self) -> dict: + return {**super().to_dict(), "site": self.site, "user": self.user} + + @classmethod + def from_dict(cls, data: dict) -> BrowserSignInTaskStep: + return cls(**cls._browser_from_dict(data), site=data.get("site"), user=data.get("user")) + + async def execute(self, context: TaskStepContext) -> TaskStepContext: + record, child, names = await self._site(context) + if protocol_v1.find_extension_method(child.card, WEBSITE_EXTENSION_URI, "session") is None: + raise RuntimeError(f"site {self.site!r} serves no website/v1 session, so it can't sign a browser in") + session = await record.invoke(WEBSITE_EXTENSION_URI, "session", {"user": self.user}, child=child, + timeout=SESSION_TIMEOUT_S) + cookies = scoped(session.get("cookies") or [], names) + owner, browser, card = self._find(context) + if protocol_v1.serves(card, METHOD_ADD) is False: + raise RuntimeError(f"the website browser {browser or owner.env_id!r} serves no data/add: rebuild it on a " + "newer agentenv-framework-protocol") + state = {"cookies": cookies, "local_storage": session.get("local_storage") or []} + await protocol_v1.add_data(_data_plane(owner, browser), [DataPart(data=state)], timeout=ADD_TIMEOUT_S, + headers=owner.control_headers) + self._record(context, site=self.site, user=self.user, + cookies=sorted({cookie["name"] for cookie in cookies}), names=names) + logger.info(f"{self.id}: signed {browser or owner.env_id!r} in to {self.site!r} as {self.user!r} " + f"({len(cookies)} cookie(s) on {', '.join(names)})") + return context + + async def _site(self, context: TaskStepContext) -> tuple[DeployedEnv, protocol_v1.ChildEnv, list[str]]: + """The record that serves the site, the site among its children, and the names a browser reaches it by: a + website env deployed on its own, or one of a deployed multi env's websites.""" + for record in context.deployed_envs: + try: + env = Env.get(record.env_id, record.env_version) + except NotFoundError: + continue + website = env if record.env_id == self.site else next( + (site for site in getattr(env, "website_envs", None) or [] if site.id == self.site), None) + if not isinstance(website, WebsiteEnv): + continue + child = record.child_env(website.environment_name, mcp=False) + if child is None: + raise RuntimeError(f"env {record.env_id!r}'s card lists no website {website.environment_name!r}") + found = await sites.deployed_sites([record], services=[website.environment_name]) + names = list(dict.fromkeys(name for site in found for name in site["domains"])) + if not names: + raise RuntimeError(f"site {self.site!r} has no names a browser reaches it by") + return record, child, names + raise RuntimeError(f"site {self.site!r} isn't deployed in this run: no env in context.deployed_envs is it or " + "has it among its websites") + + +def scoped(cookies: list[dict], names: list[str]) -> list[dict]: + """Each of ``cookies``, which ``session`` leaves unplaced, set for each of the site's ``names``: an exact name by + its URL, so the cookie is the name's alone, over HTTPS, a ``.localhost`` one over HTTP; a ``*.`` name as a domain + cookie on the name it ends in.""" + placed = [] + for cookie in cookies: + unplaced = {key: value for key, value in cookie.items() if key not in ("url", "domain")} + for name in names: + if name.startswith("*."): + placed.append({**unplaced, "domain": f".{name[2:]}", "path": unplaced.get("path") or "/"}) + else: + scheme = "http" if name == "localhost" or name.endswith(".localhost") else "https" + placed.append({**{key: value for key, value in unplaced.items() if key != "path"}, + "url": f"{scheme}://{name}{unplaced.get('path') or '/'}"}) + return placed + + +def _data_plane(owner: DeployedEnv, browser: Optional[str]) -> str: + """Where the browser's data plane is: its child's in ``owner``'s card, or ``owner``'s own for a browser alone.""" + if browser is None: + return owner.environment_url + child = owner.child_env(browser) + if child is None: + raise RuntimeError(f"env {owner.env_id!r}'s card lists no {browser!r}") + return child.base_url(owner.environment_url) diff --git a/tst/data/session_website/Dockerfile b/tst/data/session_website/Dockerfile new file mode 100644 index 000000000..03bc00aca --- /dev/null +++ b/tst/data/session_website/Dockerfile @@ -0,0 +1,12 @@ +FROM mirror.gcr.io/library/python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf + +WORKDIR /app +RUN pip install --no-cache-dir starlette uvicorn pydantic httpx +COPY agentenv_protocol /app/agentenv_protocol +COPY server.py /app/server.py +ENV PYTHONPATH=/app +ENV PORT=8000 +EXPOSE 8000 +RUN useradd --create-home --uid 10001 appuser +USER appuser +CMD ["python", "server.py"] diff --git a/tst/data/session_website/server.py b/tst/data/session_website/server.py new file mode 100644 index 000000000..be7a98217 --- /dev/null +++ b/tst/data/session_website/server.py @@ -0,0 +1,12 @@ +"""A website on WebsiteEnvironment with no pages of its own, named shop.test, for integration-testing browser_sign_in: +website/v1's session signs a browser in, and /api/session says who a request's cookie signs in.""" +from agentenv_protocol.website import WebsiteEnvironment, website + + +@website(domains=["shop.test"]) +class Shop(WebsiteEnvironment): + pass + + +if __name__ == "__main__": + Shop().serve() diff --git a/tst/integration/computer/website_browser_test.py b/tst/integration/computer/website_browser_test.py index edd6b68ee..53ef1da36 100644 --- a/tst/integration/computer/website_browser_test.py +++ b/tst/integration/computer/website_browser_test.py @@ -5,12 +5,16 @@ first start tab sees the deploy's time zone, and a page on loopback loads; its card declares browser/v1; a data/reset relaunches it on its profile template, on a new pipe its ready check answers over; and reset_env, a reboot, brings the template back too. Its computer's /dev/shm is Docker's -64 MiB, so it keeps its shared memory in files. Needs Docker and the local registry on localhost:5000.""" +64 MiB, so it keeps its shared memory in files. In a multi env beside a site that offers website/v1's session, +browser_sign_in signs it in, and again after reset_env starts it afresh. Needs Docker and the local registry on +localhost:5000.""" import asyncio import json import platform import re +import uuid +from typing import Optional import httpx import pytest @@ -22,12 +26,23 @@ from agentenv_protocol.types import WELL_KNOWN_PATH from agentenv_protocol.website_browser import BROWSER +from agent_env.config import get_config, website_browser_env_id from agent_env.env import Env +from agent_env.env.env import DeployedEnv from agent_env.env.envs.computer.utils import inside +from agent_env.env.envs.mcp_server import MCPServerEnv +from agent_env.env.envs.multi_env import MultiEnv +from agent_env.env.envs.playwright_mcp import PLAYWRIGHT_MCP_ENVIRONMENT_NAME +from agent_env.env.envs.website import WebsiteEnv from agent_env.store.routing import namespace_routing from agent_env.task.teardown import teardown_run from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.task_steps.browser.base import find_browser +from agent_env.task_step.task_steps.browser.sign_in import BrowserSignInTaskStep +from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep from agent_env.task_step.task_steps.reset_env import ResetEnvTaskStep +from tst.integration.computer.multi_env_computers_test import CONTAINER, _image +from tst.integration.store.local_parallel_deploy_test import _seed_bootstrap_envs pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] @@ -211,3 +226,65 @@ async def _ready(deployed, card: dict, app: str = "browser") -> dict: return readiness await asyncio.sleep(1) return readiness + + +# Who a request carrying the cookie signs in, as the site says, asked inside the computer through its site proxy. +WHO_IS_SIGNED_IN = """import json, sys, urllib.request +request = urllib.request.Request("https://shop.test/api/session", headers={"Cookie": sys.argv[1]}) +print(json.load(urllib.request.urlopen(request, timeout=20))["user"]) +""" + + +@pytest.fixture(scope="module") +def session_site(website_browser_desktop): + """The gateway's and service-db's envs, a small stand-in for the website browser's MCP server a gateway in front of + websites runs, and a WebsiteEnvironment site named shop.test that offers session, under a local id as the + desktop's.""" + uid = uuid.uuid4().hex[:8] + with namespace_routing(): + _seed_bootstrap_envs() + MCPServerEnv.put(id=website_browser_env_id(get_config()), environment_name=PLAYWRIGHT_MCP_ENVIRONMENT_NAME, + docker_image_artifact=_image("cardless_mcp", f"signin-browser-{uid}")) + return WebsiteEnv.put(id=f"@local/~/signin-{uid}/shop", environment_name="shop", domains=["shop.test"], + server_docker_image_artifact=_image("session_website", f"signin-shop-{uid}")) + + +async def _signed_in(computer: DeployedEnv) -> Optional[str]: + """Who the browser's cookies for shop.test sign in, as the site says inside the computer; None with none.""" + owner, _, card = find_browser(computer, None) + cookies = (await protocol_v1.invoke_extension(owner.environment_url, card, BROWSER, {"urls": ["https://shop.test/"]}, + 30, method="cookies/get", headers=owner.control_headers))["cookies"] + if not cookies: + return None + header = "; ".join(f"{cookie['name']}={cookie['value']}" for cookie in cookies) + answer = await inside.run(computer, ["python3", "-c", WHO_IS_SIGNED_IN, header], timeout_s=40) + return answer["stdout"].strip() or answer.get("stderr", "")[-300:] + + +@pytest.mark.asyncio +async def test_browser_sign_in_signs_a_multi_envs_browser_in_to_its_site_and_again_after_a_reset( + website_browser_desktop, session_site): + with namespace_routing(): + office = MultiEnv.put(id=f"{session_site.id.rsplit('/', 1)[0]}/office", website_envs=[session_site], + computer_envs=[Env.get(website_browser_desktop.id)], name="office") + sign_in = BrowserSignInTaskStep(id="in", version=None, env_id=office.id, site=session_site.id, user="alex") + context = TaskStepContext() + try: + [deployed] = (await DeployEnvTaskStep( + id="office", version=None, env_id=office.id, sandbox_type="local", ttl_seconds=900, + child_envs={"desktop": {**CONTAINER, "env_params": {"form": "container", "site_routing": True}}}, + ).execute(context)).deployed_envs + computer = DeployedEnv.from_dict(deployed.child_envs["desktop"]) + before = await _signed_in(computer) + await sign_in.execute(context) + signed = await _signed_in(computer) + await ResetEnvTaskStep(id="reset", version=None, env_id=office.id, fail_task_on_error=True).execute(context) + after_reset = await _signed_in(computer) + await sign_in.execute(context) + again = await _signed_in(computer) + finally: + report = await teardown_run(context) + + assert not report.failed + assert (before, signed, after_reset, again) == (None, "alex", None, "alex") + assert context.metadata["browser_steps"]["in"]["names"] == ["shop.test"] diff --git a/tst/unit/task_step/test_browser_sign_in.py b/tst/unit/task_step/test_browser_sign_in.py new file mode 100644 index 000000000..4d44426ee --- /dev/null +++ b/tst/unit/task_step/test_browser_sign_in.py @@ -0,0 +1,167 @@ +"""browser_sign_in, and every browser step's reach into a multi env's computers: the site's session is asked through the +record that serves it, its cookies are set for each of the site's names, and the browser in the computer gets them +through data/add with the computer's own control token, the multi env's gateway listing the computer but not its apps. +Only the HTTP boundary and the store are faked.""" + +from __future__ import annotations + +import dataclasses +import json +from types import SimpleNamespace +from unittest.mock import MagicMock + +import httpx +import pytest + +from agent_env.env.env import DeployedGatewayEnv, DeployedSandboxEnv, Env +from agent_env.env.envs.computer.app_env import ComputerAppEnv +from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.envs.multi_env import MultiEnv +from agent_env.env.envs.website import WebsiteEnv +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.registry import get_task_step_registry +from agent_env.task_step.task_steps.browser import sign_in +from agent_env.task_step.task_steps.browser.base import stored_browsers +from agent_env.task_step.task_steps.browser.connect_cdp import BrowserConnectCdpTaskStep +from agent_env.task_step.task_steps.browser.cookies import BrowserSetCookiesTaskStep +from agent_env.task_step.task_steps.browser.sign_in import BrowserSignInTaskStep, scoped + +_GATEWAY = "http://localhost:42000" +_DESKTOP = "http://localhost:42100" +_SESSION = {"name": "agentenv_session_shop", "value": "signed.alex", "path": "/", "max_age": 3600, "httpOnly": True, + "sameSite": "Lax"} + + +def _website() -> WebsiteEnv: + return WebsiteEnv(id="shop-site", version=1, server_docker_image_artifact=MagicMock(), environment_name="shop", + domains=["shop.test", "*.shop.test"]) + + +def _browser_card(ops=("cookies/set", "cdp")) -> dict: + prefix = "/svc/chromium/agentenv/ext/browser" + return {"name": "chromium", "url": "/svc/chromium/agentenv", + "capabilities": {"operations": ["data/reset", "data/add", "data/get"], "extensions": [ + {"uri": "urn:agentenv:browser/v1", "params": {"endpoint": prefix, "methods": { + op: {"endpoint": f"{prefix}/{op}"} for op in ops}}}]}} + + +def _office(*, session: bool = True) -> DeployedGatewayEnv: + """A multi env's record: the shop website among its card's children, and the desktop computer, whose card lists + chromium, kept whole in its child_envs, as the gateway's card lists the computer without its apps.""" + website = {"uri": "urn:agentenv:website/v1", "params": { + "endpoint": "/svc/shop/agentenv/ext/website", "domains": ["shop.test", "*.shop.test"], + "browse_url": "/website/shop/", + "methods": {"session": {"endpoint": "/svc/shop/agentenv/ext/website/session"}} if session else {}}} + desktop = DeployedSandboxEnv( + env_id="desktop-computer", env_version=1, sandbox_id="sb-desktop", sandbox_type="local", + control_token="desktop-token", environment_card_url=f"{_DESKTOP}/.well-known/agent-env.json", + environment_card={"name": "desktop", "children_environments": [_browser_card()]}) + return DeployedGatewayEnv( + env_id="office", env_version=1, sandbox_id="gw", sandbox_type="local", gateway_url=_GATEWAY, + control_token="gateway-token", environment_card_url=f"{_GATEWAY}/.well-known/agent-env.json", + environment_card={"name": "office", "children_environments": [ + {"name": "shop", "url": "/svc/shop/agentenv", "capabilities": {"extensions": [website]}}, + {"name": "desktop", "url": "/svc/desktop/agentenv", "capabilities": {"extensions": []}}]}, + child_envs={"desktop": dataclasses.asdict(desktop)}) + + +@pytest.fixture +def served(monkeypatch) -> list[httpx.Request]: + """The store holds the office multi env with its shop website; the site answers a session, the browser takes + what it's sent. The requests, in order.""" + sent, real = [], httpx.AsyncClient + office = SimpleNamespace(website_envs=[_website()], computer_envs=[]) + monkeypatch.setattr(Env, "get", classmethod(lambda cls, id, version=None: office)) + + def handle(request: httpx.Request) -> httpx.Response: + sent.append(request) + if request.url.path.endswith("/website/session"): + return httpx.Response(200, json={"cookies": [_SESSION], "local_storage": []}) + if request.url.path.endswith("/agentenv"): + return httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}}) + return httpx.Response(200, json={}) + + monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: real(transport=httpx.MockTransport(handle))) + return sent + + +@pytest.mark.asyncio +async def test_a_browser_in_a_multi_envs_computer_is_signed_in_with_the_sites_session_for_each_of_its_names(served): + context = TaskStepContext(deployed_envs=[_office()], metadata={}) + + await BrowserSignInTaskStep(id="in", version=None, env_id="office", site="shop-site", user="alex").execute(context) + + session, add = served + assert str(session.url) == f"{_GATEWAY}/svc/shop/agentenv/ext/website/session" + assert (json.loads(session.content), session.headers["authorization"]) == ({"user": "alex"}, "Bearer gateway-token") + assert (str(add.url), add.headers["authorization"]) == (f"{_DESKTOP}/svc/chromium/agentenv", "Bearer desktop-token") + body = json.loads(add.content) + unplaced = {key: value for key, value in _SESSION.items() if key != "path"} + assert body["method"] == "data/add" and body["params"]["parts"] == [{"kind": "data", "data": { + "cookies": [{**unplaced, "url": "https://shop.test/"}, {**unplaced, "path": "/", "domain": ".shop.test"}], + "local_storage": []}}] + assert context.metadata["browser_steps"]["in"] == { + "env_id": "office", "browser": None, "site": "shop-site", "user": "alex", "cookies": ["agentenv_session_shop"], + "names": ["shop.test", "*.shop.test"]} + + +@pytest.mark.asyncio +async def test_any_browser_step_reaches_a_browser_in_a_multi_envs_computer_with_the_computers_token(served): + cookie = {"name": "theme", "value": "dark", "url": "https://shop.test/"} + + await BrowserSetCookiesTaskStep(id="c", version=None, env_id="office", cookies=[cookie]).execute( + TaskStepContext(deployed_envs=[_office()], metadata={})) + + (request,) = served + assert str(request.url) == f"{_DESKTOP}/svc/chromium/agentenv/ext/browser/cookies/set" + assert request.headers["authorization"] == "Bearer desktop-token" + + +@pytest.mark.asyncio +async def test_a_cdp_address_to_a_browser_in_a_multi_envs_computer_is_refused_for_now(served): + with pytest.raises(RuntimeError, match="is in a computer of the multi env 'office'"): + await BrowserConnectCdpTaskStep(id="cdp", version=None, env_id="office", agent_name="agent").execute( + TaskStepContext(deployed_envs=[_office()], metadata={})) + assert served == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("office", "site", "problem"), [ + (_office(session=False), "shop-site", "site 'shop-site' serves no website/v1 session"), + (_office(), "blog-site", "site 'blog-site' isn't deployed in this run"), +], ids=["no-session", "not-deployed"]) +async def test_a_site_that_cant_sign_in_fails_the_step_before_the_browser_is_touched(served, office, site, problem): + with pytest.raises(RuntimeError, match=problem): + await BrowserSignInTaskStep(id="in", version=None, env_id="office", site=site, user="alex").execute( + TaskStepContext(deployed_envs=[office], metadata={})) + assert served == [] + + +def test_each_cookie_is_placed_on_each_name_the_site_is_reached_by(): + cookie = {"name": "s", "value": "v", "path": "/app", "max_age": 60, "domain": "ignored"} + assert scoped([cookie], ["shop.test", "*.shop.test", "notes.localhost"]) == [ + {"name": "s", "value": "v", "max_age": 60, "url": "https://shop.test/app"}, + {"name": "s", "value": "v", "path": "/app", "max_age": 60, "domain": ".shop.test"}, + {"name": "s", "value": "v", "max_age": 60, "url": "http://notes.localhost/app"}] + + +def test_the_step_round_trips_and_checks_its_fields(monkeypatch): + step = BrowserSignInTaskStep(id="in", version=None, env_id="office", site="shop-site", user="alex", browser="chromium") + data = step.to_dict() + assert get_task_step_registry()["browser_sign_in"].from_dict(data).to_dict() == data + assert BrowserSignInTaskStep(id="in", version=None, env_id="office", site="", user="").config_problems() == [ + "step 'in': site must be a website env's id", + "step 'in': user must be a non-empty string; browser_delete_cookies signs out"] + monkeypatch.setattr(sign_in, "stored_env", lambda id: ComputerEnv.__new__(ComputerEnv)) + monkeypatch.setattr("agent_env.task_step.task_steps.browser.base.stored_env", lambda id: None) + assert "site 'shop-site' is a ComputerEnv, not a website env" in step.preflight()[-1] + + +def test_a_multi_env_deploys_its_computers_browsers(): + app = ComputerAppEnv.__new__(ComputerAppEnv) + app.environment_name, app.declaration = "chromium", SimpleNamespace(browser=True) + computer = ComputerEnv.__new__(ComputerEnv) + computer.composed_apps = lambda: [app] + office = MultiEnv.__new__(MultiEnv) + office._computers = SimpleNamespace(envs=[computer]) + assert stored_browsers(office) == ["chromium"] From 5b62f4a7a39bd0e56eb83612fb58a65d425308e3 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 8 Nov 2026 23:04:12 -0800 Subject: [PATCH 2/4] fix(browser): browser_sign_in finds the site by the name it's served as, not its card's name A website's card name needn't be its environment_name (a card named Notes served as notes), so look the site up by its /svc// route, as deployed_sites does; sites.served_as is public for that. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/envs/computer/utils/sites.py | 4 ++-- .../task_step/task_steps/browser/sign_in.py | 16 +++++++++++++--- tst/unit/task_step/test_browser_sign_in.py | 15 +++++++++------ 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/agent_env/env/envs/computer/utils/sites.py b/src/agent_env/env/envs/computer/utils/sites.py index 3820c476b..04be8c40e 100644 --- a/src/agent_env/env/envs/computer/utils/sites.py +++ b/src/agent_env/env/envs/computer/utils/sites.py @@ -509,7 +509,7 @@ async def deployed_sites(deployed_envs: list[DeployedEnv], only: Optional[list[s for child in children: params = protocol_v1.extension_params(child.card, WEBSITE_EXTENSION_URI) browse = params.get(WEBSITE_BROWSE_URL_PARAM) - service = _served_as(child) + service = served_as(child) if services is not None and service not in services: named.add(service) continue @@ -589,7 +589,7 @@ def _env_qualified(found: list[tuple[str, dict]]) -> list[dict]: if len(envs[site["name"]]) > 1 else site for env_id, site in found] -def _served_as(child) -> str: +def served_as(child) -> str: """The gateway service a child env is served as: the ```` of the ``/svc//`` route its url is at, which ``website_frontend_urls`` keys it by, else its card's name.""" parts = urlsplit(child.url or "").path.strip("/").split("/") diff --git a/src/agent_env/task_step/task_steps/browser/sign_in.py b/src/agent_env/task_step/task_steps/browser/sign_in.py index 11dd7dd27..d8b723cef 100644 --- a/src/agent_env/task_step/task_steps/browser/sign_in.py +++ b/src/agent_env/task_step/task_steps/browser/sign_in.py @@ -10,7 +10,7 @@ from agentenv_protocol.website import WEBSITE_EXTENSION_URI from agent_env.entity.refs import EntityRef -from agent_env.env.env import DeployedEnv, Env +from agent_env.env.env import DeployedEnv, Env, website_child from agent_env.env.envs.computer.utils import sites from agent_env.env.envs.website import WebsiteEnv from agent_env.store.base import NotFoundError @@ -98,9 +98,9 @@ async def _site(self, context: TaskStepContext) -> tuple[DeployedEnv, protocol_v (site for site in getattr(env, "website_envs", None) or [] if site.id == self.site), None) if not isinstance(website, WebsiteEnv): continue - child = record.child_env(website.environment_name, mcp=False) + child = _served(record, website.environment_name) if child is None: - raise RuntimeError(f"env {record.env_id!r}'s card lists no website {website.environment_name!r}") + raise RuntimeError(f"env {record.env_id!r}'s card serves no website as {website.environment_name!r}") found = await sites.deployed_sites([record], services=[website.environment_name]) names = list(dict.fromkeys(name for site in found for name in site["domains"])) if not names: @@ -110,6 +110,16 @@ async def _site(self, context: TaskStepContext) -> tuple[DeployedEnv, protocol_v "has it among its websites") +def _served(record: DeployedEnv, service: str) -> Optional[protocol_v1.ChildEnv]: + """The website ``record``'s card serves as ``service``, the name of the route it's at, which its card's name + needn't be (``sites.served_as``); a leaf card, a website's deployed alone, is its own.""" + card = record.environment_card or {} + if not isinstance(card.get("children_environments"), list): + return protocol_v1.ChildEnv(name=card.get("name"), url=card.get("url"), card=card) if card else None + return next((child for child in protocol_v1.children(card) + if website_child(child) and sites.served_as(child) == service), None) + + def scoped(cookies: list[dict], names: list[str]) -> list[dict]: """Each of ``cookies``, which ``session`` leaves unplaced, set for each of the site's ``names``: an exact name by its URL, so the cookie is the name's alone, over HTTPS, a ``.localhost`` one over HTTP; a ``*.`` name as a domain diff --git a/tst/unit/task_step/test_browser_sign_in.py b/tst/unit/task_step/test_browser_sign_in.py index 4d44426ee..1257ac77f 100644 --- a/tst/unit/task_step/test_browser_sign_in.py +++ b/tst/unit/task_step/test_browser_sign_in.py @@ -45,9 +45,10 @@ def _browser_card(ops=("cookies/set", "cdp")) -> dict: op: {"endpoint": f"{prefix}/{op}"} for op in ops}}}]}} -def _office(*, session: bool = True) -> DeployedGatewayEnv: - """A multi env's record: the shop website among its card's children, and the desktop computer, whose card lists - chromium, kept whole in its child_envs, as the gateway's card lists the computer without its apps.""" +def _office(*, session: bool = True, card_name: str = "shop") -> DeployedGatewayEnv: + """A multi env's record: the shop website among its card's children, served as shop whatever its card names it, + and the desktop computer, whose card lists chromium, kept whole in its child_envs, as the gateway's card lists the + computer without its apps.""" website = {"uri": "urn:agentenv:website/v1", "params": { "endpoint": "/svc/shop/agentenv/ext/website", "domains": ["shop.test", "*.shop.test"], "browse_url": "/website/shop/", @@ -60,7 +61,7 @@ def _office(*, session: bool = True) -> DeployedGatewayEnv: env_id="office", env_version=1, sandbox_id="gw", sandbox_type="local", gateway_url=_GATEWAY, control_token="gateway-token", environment_card_url=f"{_GATEWAY}/.well-known/agent-env.json", environment_card={"name": "office", "children_environments": [ - {"name": "shop", "url": "/svc/shop/agentenv", "capabilities": {"extensions": [website]}}, + {"name": card_name, "url": "/svc/shop/agentenv", "capabilities": {"extensions": [website]}}, {"name": "desktop", "url": "/svc/desktop/agentenv", "capabilities": {"extensions": []}}]}, child_envs={"desktop": dataclasses.asdict(desktop)}) @@ -86,8 +87,10 @@ def handle(request: httpx.Request) -> httpx.Response: @pytest.mark.asyncio -async def test_a_browser_in_a_multi_envs_computer_is_signed_in_with_the_sites_session_for_each_of_its_names(served): - context = TaskStepContext(deployed_envs=[_office()], metadata={}) +@pytest.mark.parametrize("card_name", ["shop", "Shop"], ids=["card-named-as-served", "card-named-otherwise"]) +async def test_a_browser_in_a_multi_envs_computer_is_signed_in_with_the_sites_session_for_each_of_its_names( + served, card_name): + context = TaskStepContext(deployed_envs=[_office(card_name=card_name)], metadata={}) await BrowserSignInTaskStep(id="in", version=None, env_id="office", site="shop-site", user="alex").execute(context) From f469be6539106265e722f3ab865cf580803fb81a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 8 Nov 2026 23:20:28 -0800 Subject: [PATCH 3/4] test(browser): the sign-in e2e puts its multi env with no MCP servers, and its site image keeps curl for the health check Co-Authored-By: Claude Opus 5.5 --- tst/data/session_website/Dockerfile | 2 +- tst/integration/computer/website_browser_test.py | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tst/data/session_website/Dockerfile b/tst/data/session_website/Dockerfile index 03bc00aca..7080524ee 100644 --- a/tst/data/session_website/Dockerfile +++ b/tst/data/session_website/Dockerfile @@ -1,5 +1,5 @@ FROM mirror.gcr.io/library/python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf - +RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/* WORKDIR /app RUN pip install --no-cache-dir starlette uvicorn pydantic httpx COPY agentenv_protocol /app/agentenv_protocol diff --git a/tst/integration/computer/website_browser_test.py b/tst/integration/computer/website_browser_test.py index 53ef1da36..3076977b5 100644 --- a/tst/integration/computer/website_browser_test.py +++ b/tst/integration/computer/website_browser_test.py @@ -265,8 +265,9 @@ async def _signed_in(computer: DeployedEnv) -> Optional[str]: async def test_browser_sign_in_signs_a_multi_envs_browser_in_to_its_site_and_again_after_a_reset( website_browser_desktop, session_site): with namespace_routing(): - office = MultiEnv.put(id=f"{session_site.id.rsplit('/', 1)[0]}/office", website_envs=[session_site], - computer_envs=[Env.get(website_browser_desktop.id)], name="office") + office = MultiEnv.put(id=f"{session_site.id.rsplit('/', 1)[0]}/office", mcp_server_envs=[], + website_envs=[session_site], computer_envs=[Env.get(website_browser_desktop.id)], + name="office") sign_in = BrowserSignInTaskStep(id="in", version=None, env_id=office.id, site=session_site.id, user="alex") context = TaskStepContext() try: From c8678d3384cc5bb52150b6285fd5e4e81ccfa440 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 9 Nov 2026 10:09:50 -0800 Subject: [PATCH 4/4] fix(browser): a website deployed alone is signed in by the names it stores, else those its card declares deployed_sites routes a website by a composed card's child or a frontend, so a website a plugin deploys alone, with a card of its own and no frontend, had no names and the sign-in failed before asking for a session. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/browser/sign_in.py | 10 ++++- tst/unit/task_step/test_browser_sign_in.py | 37 ++++++++++++++++++- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/src/agent_env/task_step/task_steps/browser/sign_in.py b/src/agent_env/task_step/task_steps/browser/sign_in.py index d8b723cef..97586cb66 100644 --- a/src/agent_env/task_step/task_steps/browser/sign_in.py +++ b/src/agent_env/task_step/task_steps/browser/sign_in.py @@ -102,7 +102,7 @@ async def _site(self, context: TaskStepContext) -> tuple[DeployedEnv, protocol_v if child is None: raise RuntimeError(f"env {record.env_id!r}'s card serves no website as {website.environment_name!r}") found = await sites.deployed_sites([record], services=[website.environment_name]) - names = list(dict.fromkeys(name for site in found for name in site["domains"])) + names = list(dict.fromkeys(name for site in found for name in site["domains"])) or _own_names(website, child) if not names: raise RuntimeError(f"site {self.site!r} has no names a browser reaches it by") return record, child, names @@ -120,6 +120,14 @@ def _served(record: DeployedEnv, service: str) -> Optional[protocol_v1.ChildEnv] if website_child(child) and sites.served_as(child) == service), None) +def _own_names(website: WebsiteEnv, child: protocol_v1.ChildEnv) -> list[str]: + """The names ``website`` stores, else those its card's ``website/v1`` declares, for a site ``deployed_sites`` + doesn't route: one a plugin deploys alone, with a card of its own and no frontend.""" + declared = protocol_v1.extension_params(child.card, WEBSITE_EXTENSION_URI).get("domains") + names = website.domains or (declared if isinstance(declared, list) else []) + return list(dict.fromkeys(name for name in names if isinstance(name, str) and name)) + + def scoped(cookies: list[dict], names: list[str]) -> list[dict]: """Each of ``cookies``, which ``session`` leaves unplaced, set for each of the site's ``names``: an exact name by its URL, so the cookie is the name's alone, over HTTPS, a ``.localhost`` one over HTTP; a ``*.`` name as a domain diff --git a/tst/unit/task_step/test_browser_sign_in.py b/tst/unit/task_step/test_browser_sign_in.py index 1257ac77f..da24cb79f 100644 --- a/tst/unit/task_step/test_browser_sign_in.py +++ b/tst/unit/task_step/test_browser_sign_in.py @@ -13,7 +13,7 @@ import httpx import pytest -from agent_env.env.env import DeployedGatewayEnv, DeployedSandboxEnv, Env +from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv, Env from agent_env.env.envs.computer.app_env import ComputerAppEnv from agent_env.env.envs.computer.env import ComputerEnv from agent_env.env.envs.multi_env import MultiEnv @@ -28,6 +28,7 @@ _GATEWAY = "http://localhost:42000" _DESKTOP = "http://localhost:42100" +_SITE = "http://localhost:42200" _SESSION = {"name": "agentenv_session_shop", "value": "signed.alex", "path": "/", "max_age": 3600, "httpOnly": True, "sameSite": "Lax"} @@ -108,6 +109,40 @@ async def test_a_browser_in_a_multi_envs_computer_is_signed_in_with_the_sites_se "names": ["shop.test", "*.shop.test"]} +@pytest.mark.asyncio +@pytest.mark.parametrize(("stored", "names"), [(["shop.test"], ["shop.test"]), ([], ["shop.example"])], + ids=["the-names-it-stores", "the-names-its-card-declares"]) +async def test_a_website_a_plugin_deployed_alone_is_signed_in_by_the_names_it_stores_else_those_its_card_declares( + served, monkeypatch, stored, names): + """A website deployed alone, its card its own and no frontend, which deployed_sites doesn't route, beside the + desktop deployed alone.""" + website = {"uri": "urn:agentenv:website/v1", "params": { + "endpoint": "/agentenv/ext/website", "domains": ["shop.example"], + "methods": {"session": {"endpoint": "/agentenv/ext/website/session"}}}} + site = DeployedEnv(env_id="shop-site", env_version=1, env_provider_type="plugin", instance_id="inst-shop", + environment_card_url=f"{_SITE}/.well-known/agent-env.json", + environment_card={"name": "shop", "url": "/agentenv", "capabilities": {"extensions": [website]}}) + desktop = DeployedSandboxEnv( + env_id="desktop-computer", env_version=1, sandbox_id="sb-desktop", sandbox_type="local", + control_token="desktop-token", environment_card_url=f"{_DESKTOP}/.well-known/agent-env.json", + environment_card={"name": "desktop", "children_environments": [_browser_card()]}) + envs = {"shop-site": WebsiteEnv(id="shop-site", version=1, server_docker_image_artifact=MagicMock(), + environment_name="shop", domains=stored), + "desktop-computer": SimpleNamespace(website_envs=[])} + monkeypatch.setattr(Env, "get", classmethod(lambda cls, id, version=None: envs[id])) + context = TaskStepContext(deployed_envs=[desktop, site], metadata={}) + + await BrowserSignInTaskStep(id="in", version=None, env_id="desktop-computer", site="shop-site", + user="alex").execute(context) + + session, add = served + assert str(session.url) == f"{_SITE}/agentenv/ext/website/session" + assert (str(add.url), add.headers["authorization"]) == (f"{_DESKTOP}/svc/chromium/agentenv", "Bearer desktop-token") + [cookie] = json.loads(add.content)["params"]["parts"][0]["data"]["cookies"] + assert cookie["url"] == f"https://{names[0]}/" + assert context.metadata["browser_steps"]["in"]["names"] == names + + @pytest.mark.asyncio async def test_any_browser_step_reaches_a_browser_in_a_multi_envs_computer_with_the_computers_token(served): cookie = {"name": "theme", "value": "dark", "url": "https://shop.test/"}