From c474ca037191de76629796454a01e3bc07af68e1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 00:18:28 -0800 Subject: [PATCH 1/9] feat(task_step): arming the clock refuses a multi env's computer that can't follow it A computer whose card offers no clock/v1, one booted from a disk or a VM bundle or on a base without agent-env's clock, was skipped as a server without a clock: arming succeeded and its session stayed on real time. sync_env_clock now refuses it, naming the computer and what to deploy instead. Its apps, which run on the computer's clock, are still skipped. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/sync_env_clock.py | 15 ++++-- tst/unit/task_step/sync_env_clock_test.py | 48 +++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 8f574b058..685845b24 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -4,8 +4,10 @@ stored env card declares clock/v1, then invokes sync_time on each backing server, MCP server or website, the env card lists (``legacy_protocol.backing_servers``) whose own card advertises it, at the route that card gives. An env whose card offers no set_time has no gateway clock to arm, as a computer deployed alone, and is refused -saying to deploy it in a multi env; a record that kept no card is refused saying so. -Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. Place right +saying to deploy it in a multi env; a record that kept no card is refused saying so. A multi env's computer whose card +offers no clock/v1, one booted from a disk or a VM bundle or on a base without agent-env's clock, is refused too: its +session would stay on real time. Other non-advertisers are skipped when tolerate_missing_sync_time (default True), and +websites always. Place right before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start it with set_env_clock_rate right before prompt_agent. """ @@ -20,6 +22,7 @@ import httpx import tzdata # noqa: F401 from agentenv_protocol import client as protocol_v1 +from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.env.env import EnvCapabilityUnsupported from agent_env.env.gateway.constants import EXT_CLOCK_URI @@ -180,7 +183,7 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time tolerate: Optional[bool] = None, server: Optional[BackingServer] = None) -> dict: """Invoke sync_time on one server, an MCP server or with ``mcp=False`` a website, if its card advertises clock/v1; skip a server with no card or no clock/v1 when ``tolerate`` (tolerate_missing_sync_time by default), - else raise. ``execute`` tolerates every website, so one that doesn't follow the clock never fails the step; one + else raise. A multi env's computer with no clock/v1 is always refused, since it can't follow the universe. ``execute`` tolerates every website, so one that doesn't follow the clock never fails the step; one that follows it but can't take the task's timezone does, as an MCP server does. ``server`` is the server as the env's card lists it (``legacy_protocol.server_card``); without it, the card is ``service``'s on ``deployed``'s stored card, or read live at its gateway path.""" @@ -196,6 +199,12 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time return {"synced": False, "reason": "no_env_card"} raise RuntimeError(f"{service} has no env card: it serves none, its card isn't named {service!r}, or the deploy couldn't read it") if protocol_v1.find_extension(card, EXT_CLOCK_URI) is None: + if server is not None and server.record is not None and protocol_v1.find_extension(card, COMPUTER_EXEC): + raise StepContextError( + f"computer {service!r} can't follow the universe clock: it offers no {EXT_CLOCK_URI} sync_time, " + "as a computer booted from a disk or a VM bundle, or on a base without agent-env's clock, doesn't, " + "so its session would stay on real time. Deploy it in a container form of a base that follows the " + "clock, or leave the clock unarmed") if tolerate: logger.info(f"sync_env_clock: {service} does not advertise {EXT_CLOCK_URI}; skipping") return {"synced": False, "reason": "not_advertised"} diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index a615101bc..a225b42ff 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -1,8 +1,11 @@ """Unit tests for SyncEnvClockTaskStep — round-trip + the per-server sync_time fan-out (mocked).""" +import dataclasses import json from types import SimpleNamespace +from unittest.mock import patch import pytest +from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH @@ -504,3 +507,48 @@ async def test_a_record_that_kept_no_card_is_refused_saying_so_not_told_to_deplo def test_a_padded_zone_is_stored_and_sent_stripped(): s = _zoned(timezone=" America/New_York ") assert s.timezone == "America/New_York" and s.to_dict()["timezone"] == "America/New_York" + + +_EXEC_EXT = {"uri": COMPUTER_EXEC, "params": {"endpoint": "/agentenv/ext/computer-exec", "methods": {"run": {"method": "POST"}}}} + + +def _with_computer(record: DeployedEnv, card: dict) -> DeployedEnv: + """``record``, a multi env's, with the computer ``desktop`` on a sandbox of its own whose card is ``card``.""" + computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", + environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", environment_card=card) + return dataclasses.replace(record, control_token="gateway-token", child_envs={"desktop": dataclasses.asdict(computer)}) + + +@pytest.mark.asyncio +async def test_arming_a_multi_env_whose_computer_offers_no_clock_is_refused_naming_it_and_what_to_deploy(monkeypatch): + """As a computer booted from its disk is: its session would stay on real time while the universe moves.""" + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), + {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_EXEC_EXT]}}) + env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) + + with patch("agent_env.env.env.Env.get", return_value=env), pytest.raises( + StepContextError, match="computer 'desktop' can't follow the universe clock") as refused: + await _step().execute(TaskStepContext(deployed_envs=[record])) + + assert "container form of a base that follows the clock" in str(refused.value) + assert not [request for request in sent if request.url.host == "desk.example"] + + +@pytest.mark.asyncio +async def test_an_app_on_a_multi_envs_computer_that_offers_no_clock_is_skipped_since_it_runs_on_the_computers( + monkeypatch): + _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + card = {"name": "desktop", "url": "/agentenv", + "capabilities": {"operations": ["data/get"], "extensions": [_CLOCK_EXT, _EXEC_EXT]}, + "children_environments": [{"name": "notes", "url": "/apps/notes/agentenv", + "capabilities": {"extensions": []}}]} + record = _with_computer(_carded(await _composed_card({"desktop": [_CLOCK_EXT, _EXEC_EXT]})), card) + context = TaskStepContext(deployed_envs=[record]) + + with patch("agent_env.env.env.Env.get", return_value=SimpleNamespace(mcp_server_envs=[], website_envs=[])): + await _step().execute(context) + + configured = context.metadata["clock_configurations"][0] + assert [entry["service"] for entry in configured["synced"]] == ["desktop"] + assert [(entry["service"], entry["reason"]) for entry in configured["skipped"]] == [("notes", "not_advertised")] From d6b6799bf103a6654df7929115fb15630d4ab68a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 00:18:30 -0800 Subject: [PATCH 2/9] test(computers): a by-hand check of a computer's clock on a remote sandbox provider It takes the local clock test's steps, plus a minute and a half idle and the disk form's refusal, on modal_vm and modal, for the desktop and a browser computer, reading the gateway's universe and the session's time inside the computer. Co-Authored-By: Claude Opus 5.5 --- tst/manual/remote_computer_clock_check.py | 279 ++++++++++++++++++++++ 1 file changed, 279 insertions(+) create mode 100644 tst/manual/remote_computer_clock_check.py diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py new file mode 100644 index 000000000..566f17028 --- /dev/null +++ b/tst/manual/remote_computer_clock_check.py @@ -0,0 +1,279 @@ +"""Run explicitly with ``pytest -s tst/manual/remote_computer_clock_check.py``: a computer's universe clock on a remote +sandbox provider, through the steps ``tst/integration/computer/computer_clock_test.py`` takes on the local one. Armed, a day and a week on, a month back, a rate of 10, frozen, running again, a minute and a half with no +change, the follower killed, and a reset: the session is within ``MAX_SKEW_S`` of the gateway's universe after each, and +runs at its rate. A browser computer's pages show it too. A provider whose sandbox is the computer's container itself, +as ``modal``'s is, can't reset it in place, which core refuses; the check takes that refusal as the reset's outcome. On +a provider that boots the desktop from its disk form, whose guest follows no clock yet, arming the clock is refused. + +It needs a config whose image and object stores the provider reaches, the provider's credentials, and two multi envs +written there. ``AGENTENV_CLOCK_CHECK_OFFICE`` names one whose computer ``desktop`` is the ubuntu-24.04 desktop, and +``AGENTENV_CLOCK_CHECK_BROWSING`` one whose computer ``browser`` is a browser computer; either left out skips its check. +Each multi env deploys on ``AGENTENV_CLOCK_CHECK_GATEWAY_SANDBOX`` (``modal_vm``), its computer on each of +``AGENTENV_CLOCK_CHECK_SANDBOXES`` (``modal_vm,modal``). + +Every reading is taken inside the computer: the gateway's universe, read at the address the computer reaches the gateway +at, as its follower does, and the session's own, each between two readings of real time on the computer's clock. So +neither this machine's distance from the provider nor its clock is in them.""" + +import asyncio +import json +import os +import time +import urllib.parse +from datetime import datetime, timedelta, timezone + +import pytest +from agentenv_protocol.computer.clock import FOLLOWER, FOLLOWER_USER + +from agent_env.env.env import DeployedEnv +from agent_env.env.envs.computer.utils import inside +from agent_env.env.envs.computer.utils.sites import RootChannel +from agent_env.env.gateway.constants import EXT_CLOCK_URI +from agent_env.providers import build_sandbox_provider +from agent_env.task.teardown import teardown_run +from agent_env.task_step.context import StepContextError, TaskStepContext +from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep +from agent_env.task_step.task_steps.reset_env import ResetEnvTaskStep +from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep +from tst.integration.computer.browser_computer_test import _browser_op + +OFFICE = os.environ.get("AGENTENV_CLOCK_CHECK_OFFICE") +BROWSING = os.environ.get("AGENTENV_CLOCK_CHECK_BROWSING") +GATEWAY_SANDBOX = os.environ.get("AGENTENV_CLOCK_CHECK_GATEWAY_SANDBOX", "modal_vm") +SANDBOXES = os.environ.get("AGENTENV_CLOCK_CHECK_SANDBOXES", "modal_vm,modal").split(",") +RATE = 10 +#: How far the session's clock may be from the gateway's: room for reading the two, as on the local provider. +MAX_SKEW_S = 1.0 +#: How far, in universe seconds, half a reading's bracket of real time may leave it. +READING_S = 0.25 +#: How long a minute and a half with no clock change is: past the gateway's 25 s hold on a watch more than three times, +#: so a provider's tunnel that drops an idle long poll shows as a follower that misses the next change. +IDLE_S = 90 +#: How soon a killed follower may be back: supervisord's second, and a remote sandbox's slower start. +FOLLOWER_BACK_S = 10 +TTL_S = 2400 +#: What core says when a computer's provider runs it as the sandbox itself, which a reset can't replace in place. +IN_PLACE = "can't be reset in place" +#: Inside the computer, on real time: the gateway's universe as the computer reaches it, between two readings of real +#: time, then the session's own (``date``, without the real-time marker), between two more; each pair taken again, +#: up to ten times, until both brackets are narrower than argv[2]. +READ = """ +import json, os, subprocess, sys, time, urllib.request +url, widest = sys.argv[1], float(sys.argv[2]) +session = {k: v for k, v in os.environ.items() if k != "AGENTENV_REAL_TIME"} +for _ in range(10): + a = time.time() + gateway = json.load(urllib.request.urlopen(url, timeout=10))["virtual_time"] + b = time.time() + universe = float(subprocess.run(["date", "+%s.%N"], env=session, capture_output=True, text=True, check=True).stdout) + c = time.time() + if b - a < widest and c - b < widest: + break +print(json.dumps({"gateway_at": (a + b) / 2, "gateway": gateway, "session_at": (b + c) / 2, "session": universe, + "widths": [round(b - a, 4), round(c - b, 4)]})) +""" +#: A page that names its own Date.now(), in milliseconds, in its title, five times a second. +CLOCK_PAGE = "data:text/html," + urllib.parse.quote( + "") + + +def _iso(moment: datetime) -> str: + return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _at(text: str) -> float: + return datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp() + + +def _widest(rate: float) -> float: + return 2 * READING_S / max(rate, 1) + + +async def _write(deployed, method: str, **params) -> float: + """A clock write that waits up to 15 s for every computer to show it; the seconds it took.""" + started = time.monotonic() + await deployed.invoke(EXT_CLOCK_URI, method, {**params, "wait_followers_s": 15}, timeout=30) + return round(time.monotonic() - started, 2) + + +async def _now(deployed) -> datetime: + state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30) + return datetime.fromtimestamp(_at(state["virtual_time"]), timezone.utc) + + +async def _reading(computer, time_url: str, rate: float) -> dict: + ran = await inside.run(computer, ["env", "AGENTENV_REAL_TIME=1", "python3", "-c", READ, time_url, + str(_widest(rate))], timeout_s=120) + assert ran["exit_code"] == 0, ran + return json.loads(ran["stdout"]) + + +async def _skew(computer, time_url: str, rate: float) -> float: + """How far the session's clock is from the gateway's, in universe seconds, both read inside the computer.""" + read = await _reading(computer, time_url, rate) + return round(read["session"] - (_at(read["gateway"]) + rate * (read["session_at"] - read["gateway_at"])), 3) + + +async def _rate(computer, time_url: str, rate: float, over_s: float = 3.0) -> float: + first = await _reading(computer, time_url, rate) + await asyncio.sleep(over_s) + then = await _reading(computer, time_url, rate) + return round((then["session"] - first["session"]) / (then["session_at"] - first["session_at"]), 3) + + +async def _followers(computer) -> list[str]: + channel = RootChannel(await build_sandbox_provider(computer.sandbox_type).get_sandbox(computer.sandbox_id)) + return (await channel.run(["sh", "-c", f"pgrep -u {FOLLOWER_USER} -f {FOLLOWER} || true"])).split() + + +async def _kill_follower(computer) -> tuple[list[str], list[str], float]: + """The computer's follower killed with SIGKILL through the root channel: its pids, those back, and how long that + took, timed from here.""" + channel = RootChannel(await build_sandbox_provider(computer.sandbox_type).get_sandbox(computer.sandbox_id)) + killed = await _followers(computer) + await channel.run(["kill", "-9", *killed]) + started = time.monotonic() + while time.monotonic() - started < 60: + back = await _followers(computer) + if back and set(back) != set(killed): + return killed, back, round(time.monotonic() - started, 1) + await asyncio.sleep(0.5) + return killed, [], 60.0 + + +async def _page_now(browser: DeployedEnv) -> float: + """What a fresh page in ``browser`` takes for now, in seconds, from its Date.now().""" + opened = await _browser_op(browser, "tabs/open", {"url": CLOCK_PAGE}) + deadline, tabs = time.monotonic() + 60, [] + while time.monotonic() < deadline: + tabs = (await _browser_op(browser, "tabs/list", {}))["tabs"] + tab = next((tab for tab in tabs if tab["id"] == opened["tab"]), None) + if tab and (tab.get("title") or "").startswith("now "): + await _browser_op(browser, "tabs/close", {"tab": tab["id"]}) + return int(tab["title"].split()[1]) / 1000 + await asyncio.sleep(0.25) + raise AssertionError(f"the clock page named no time within 60 s: {tabs}") + + +async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: bool = False) -> dict: + """The clock test's steps on ``env_id``'s computer ``child`` deployed on ``sandbox``: what each showed.""" + results: dict = {"sandbox": sandbox} + context = TaskStepContext() + try: + started = time.monotonic() + [deployed] = (await DeployEnvTaskStep( + id="office", version=None, env_id=env_id, sandbox_type=GATEWAY_SANDBOX, ttl_seconds=TTL_S, + child_envs={child: {"sandbox_type": sandbox, "env_params": {"form": "container"}}}).execute(context) + ).deployed_envs + results["deployed in s"] = round(time.monotonic() - started) + own = DeployedEnv.from_dict(deployed.child_envs[child]) + kept = own.metadata["computer"]["clock"] + results["follows"] = {"name": kept["name"], "watch_url": kept["watch_url"].split("://")[0] + "://…", + "sandbox_type": own.sandbox_type} + time_url = kept["watch_url"].removesuffix("/clock/watch") + "/clock/time" + + universe = datetime.now(timezone.utc) - timedelta(days=182) + await SyncEnvClockTaskStep(id="clock", version=None, env_id=env_id, + virtual_time=_iso(universe)).execute(context) + results["synced"] = [(entry["service"], entry["result"]["follower"]["armed"]) + for entry in context.metadata["clock_configurations"][-1]["synced"] + if "follower" in (entry.get("result") or {})] + skews, writes, rates = {}, {}, {} + results.update(skews=skews, rates=rates, writes=writes) + skews["armed"] = await _skew(own, time_url, 1) + if browser: + results["page minus universe s"] = round(await _page_now(own) - _at( + (await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30))["virtual_time"]), 1) + for name, by in (("a day on", timedelta(days=1)), ("a week on", timedelta(weeks=1))): + writes[name] = await _write(deployed, "advance", virtual_time=_iso(await _now(deployed) + by)) + skews[name] = await _skew(own, time_url, 1) + writes["a month back"] = await _write(deployed, "set_time", virtual_time=_iso( + await _now(deployed) - timedelta(days=30)), virtual_seconds_per_real_second=1) + skews["a month back"] = await _skew(own, time_url, 1) + writes[f"rate {RATE}"] = await _write(deployed, "set_rate", virtual_seconds_per_real_second=RATE) + rates[RATE] = await _rate(own, time_url, RATE) + skews[f"at a rate of {RATE}"] = await _skew(own, time_url, RATE) + writes["frozen"] = await _write(deployed, "set_rate", virtual_seconds_per_real_second=0) + rates["frozen"], skews["frozen"] = await _rate(own, time_url, 0), await _skew(own, time_url, 0) + writes["running again"] = await _write(deployed, "set_rate", virtual_seconds_per_real_second=1) + skews["running again"] = await _skew(own, time_url, 1) + + await asyncio.sleep(IDLE_S) + writes[f"after {IDLE_S} s idle"] = await _write(deployed, "advance", virtual_time=_iso( + await _now(deployed) + timedelta(hours=1))) + skews[f"after {IDLE_S} s idle"] = await _skew(own, time_url, 1) + + killed, back, results["follower back in s"] = await _kill_follower(own) + results["follower killed, back"] = (bool(killed), bool(back)) + writes["after the follower's kill"] = await _write(deployed, "advance", virtual_time=_iso( + await _now(deployed) + timedelta(hours=8))) + skews["after the follower's kill"] = await _skew(own, time_url, 1) + + try: + await ResetEnvTaskStep(id="reset", version=None, env_id=env_id, fail_task_on_error=True).execute(context) + except RuntimeError as error: + if IN_PLACE not in str(error): + raise + results["reset"] = f"refused: {IN_PLACE}" + return results + own = DeployedEnv.from_dict(context.deployed_envs[0].child_envs[child]) + skews["after a reset"] = await _skew(own, time_url, 1) + if browser: + results["page minus universe s after a reset"] = round(await _page_now(own) - _at( + (await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30))["virtual_time"]), 1) + state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30) + results["shown after a reset"] = state["followers"][kept["name"]]["version"] == state["version"] + results["reset"] = "done" + finally: + report = await teardown_run(context) + results["torn down"] = not report.failed + print("CLOCK CHECK", json.dumps(results, indent=1, default=str), flush=True) + return results + + +def _assert(results: dict) -> None: + assert results["synced"] and all(armed for _, armed in results["synced"]), results + assert all(abs(skew) < MAX_SKEW_S for skew in results["skews"].values()), results + assert abs(results["rates"][RATE] / RATE - 1) < 0.05 and abs(results["rates"]["frozen"]) < 0.01, results + assert results["follower killed, back"] == (True, True) and results["follower back in s"] < FOLLOWER_BACK_S, results + assert results["reset"] == f"refused: {IN_PLACE}" or results["shown after a reset"], results + assert results["torn down"], results + + +@pytest.mark.skipif(not OFFICE, reason="AGENTENV_CLOCK_CHECK_OFFICE names no multi env") +@pytest.mark.parametrize("sandbox", SANDBOXES) +@pytest.mark.asyncio +async def test_a_remote_desktop_keeps_to_its_gateways_clock_through_jumps_rates_an_idle_spell_a_kill_and_a_reset( + sandbox): + _assert(await _through_the_steps(OFFICE, "desktop", sandbox)) + + +@pytest.mark.skipif(not BROWSING, reason="AGENTENV_CLOCK_CHECK_BROWSING names no multi env") +@pytest.mark.parametrize("sandbox", SANDBOXES) +@pytest.mark.asyncio +async def test_a_remote_browser_computer_and_its_pages_keep_to_its_gateways_clock(sandbox): + results = await _through_the_steps(BROWSING, "browser", sandbox, browser=True) + _assert(results) + assert abs(results["page minus universe s"]) < 3, results + assert results["reset"] != "done" or abs(results["page minus universe s after a reset"]) < 3, results + + +@pytest.mark.skipif(not OFFICE, reason="AGENTENV_CLOCK_CHECK_OFFICE names no multi env") +@pytest.mark.parametrize("sandbox", [sandbox for sandbox in SANDBOXES + if build_sandbox_provider(sandbox).disk_image_platforms()]) +@pytest.mark.asyncio +async def test_arming_the_clock_of_a_remote_desktop_booted_from_its_disk_is_refused_naming_it(sandbox): + context, refused = TaskStepContext(), None + try: + await DeployEnvTaskStep(id="office", version=None, env_id=OFFICE, sandbox_type=GATEWAY_SANDBOX, + ttl_seconds=TTL_S, child_envs={"desktop": {"sandbox_type": sandbox, + "env_params": {"form": "disk"}}} + ).execute(context) + with pytest.raises(StepContextError) as refused: + await SyncEnvClockTaskStep(id="clock", version=None, env_id=OFFICE, virtual_time=_iso( + datetime.now(timezone.utc) - timedelta(days=182))).execute(context) + finally: + report = await teardown_run(context) + print("CLOCK CHECK", json.dumps({"sandbox": sandbox, "refused": refused and str(refused.value)}), flush=True) + + assert "computer 'desktop' can't follow the universe clock" in str(refused.value) and not report.failed From 4514779f9440e178030403d8875412da8c021fcc Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 00:23:47 -0800 Subject: [PATCH 3/9] test(computers): the remote clock check fails a reading it couldn't take narrowly, instead of using it Ten readings each slower than the bracket allows used to leave the last one to be measured, so a slow request could fail a healthy clock. The reading now says whether one was narrow enough, and the check fails naming the widths when none was. Co-Authored-By: Claude Opus 5.5 --- tst/manual/remote_computer_clock_check.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index 566f17028..31eb61dc5 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -1,6 +1,7 @@ """Run explicitly with ``pytest -s tst/manual/remote_computer_clock_check.py``: a computer's universe clock on a remote -sandbox provider, through the steps ``tst/integration/computer/computer_clock_test.py`` takes on the local one. Armed, a day and a week on, a month back, a rate of 10, frozen, running again, a minute and a half with no -change, the follower killed, and a reset: the session is within ``MAX_SKEW_S`` of the gateway's universe after each, and +sandbox provider, through the steps ``tst/integration/computer/computer_clock_test.py`` takes on the local one. Armed, +a day and a week on, a month back, a rate of 10, frozen, running again, a minute and a half with no change, the +follower killed, and a reset: the session is within ``MAX_SKEW_S`` of the gateway's universe after each, and runs at its rate. A browser computer's pages show it too. A provider whose sandbox is the computer's container itself, as ``modal``'s is, can't reset it in place, which core refuses; the check takes that refusal as the reset's outcome. On a provider that boots the desktop from its disk form, whose guest follows no clock yet, arming the clock is refused. @@ -56,7 +57,7 @@ IN_PLACE = "can't be reset in place" #: Inside the computer, on real time: the gateway's universe as the computer reaches it, between two readings of real #: time, then the session's own (``date``, without the real-time marker), between two more; each pair taken again, -#: up to ten times, until both brackets are narrower than argv[2]. +#: up to ten times, until both brackets are narrower than argv[2], and ``within`` says whether one was. READ = """ import json, os, subprocess, sys, time, urllib.request url, widest = sys.argv[1], float(sys.argv[2]) @@ -70,7 +71,7 @@ if b - a < widest and c - b < widest: break print(json.dumps({"gateway_at": (a + b) / 2, "gateway": gateway, "session_at": (b + c) / 2, "session": universe, - "widths": [round(b - a, 4), round(c - b, 4)]})) + "widths": [round(b - a, 4), round(c - b, 4)], "within": b - a < widest and c - b < widest})) """ #: A page that names its own Date.now(), in milliseconds, in its title, five times a second. CLOCK_PAGE = "data:text/html," + urllib.parse.quote( @@ -105,7 +106,10 @@ async def _reading(computer, time_url: str, rate: float) -> dict: ran = await inside.run(computer, ["env", "AGENTENV_REAL_TIME=1", "python3", "-c", READ, time_url, str(_widest(rate))], timeout_s=120) assert ran["exit_code"] == 0, ran - return json.loads(ran["stdout"]) + read = json.loads(ran["stdout"]) + assert read["within"], (f"the computer's readings took over {_widest(rate):.3f} s each of ten times, so none is " + f"close enough to tell its skew: the last took {read['widths']}") + return read async def _skew(computer, time_url: str, rate: float) -> float: From ce81ebbc2e17fe7631c1bf594210831efd837ad8 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 00:27:50 -0800 Subject: [PATCH 4/9] test(computers): the remote clock check gives each skew the uncertainty of its own reading At a rate of 10, each 0.1 s of the computer's round trip to the gateway is a second of universe, more than the skew allowed; a slow link failed a healthy clock. Each reading keeps the narrowest of its ten tries and reports how far it may be off, the skew passes when it's within the limit give or take that, and the rate is read from the session's own readings alone. Co-Authored-By: Claude Opus 5.5 --- tst/manual/remote_computer_clock_check.py | 70 +++++++++++------------ 1 file changed, 34 insertions(+), 36 deletions(-) diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index 31eb61dc5..38e38b9e2 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -1,10 +1,12 @@ """Run explicitly with ``pytest -s tst/manual/remote_computer_clock_check.py``: a computer's universe clock on a remote sandbox provider, through the steps ``tst/integration/computer/computer_clock_test.py`` takes on the local one. Armed, a day and a week on, a month back, a rate of 10, frozen, running again, a minute and a half with no change, the -follower killed, and a reset: the session is within ``MAX_SKEW_S`` of the gateway's universe after each, and -runs at its rate. A browser computer's pages show it too. A provider whose sandbox is the computer's container itself, -as ``modal``'s is, can't reset it in place, which core refuses; the check takes that refusal as the reset's outcome. On -a provider that boots the desktop from its disk form, whose guest follows no clock yet, arming the clock is refused. +follower killed, and a reset: after each, the session is within ``MAX_SKEW_S`` of the gateway's universe, give or take +how far the reading itself may be off, and it runs at the clock's rate. A browser computer's pages show it too. + +A provider whose sandbox is the computer's container itself, as ``modal``'s is, can't reset it in place, which core +refuses; the check takes that refusal as the reset's outcome. On a provider that boots the desktop from its disk form, +whose guest follows no clock yet, arming the clock is refused. It needs a config whose image and object stores the provider reaches, the provider's credentials, and two multi envs written there. ``AGENTENV_CLOCK_CHECK_OFFICE`` names one whose computer ``desktop`` is the ubuntu-24.04 desktop, and @@ -45,8 +47,6 @@ RATE = 10 #: How far the session's clock may be from the gateway's: room for reading the two, as on the local provider. MAX_SKEW_S = 1.0 -#: How far, in universe seconds, half a reading's bracket of real time may leave it. -READING_S = 0.25 #: How long a minute and a half with no clock change is: past the gateway's 25 s hold on a watch more than three times, #: so a provider's tunnel that drops an idle long poll shows as a follower that misses the next change. IDLE_S = 90 @@ -55,23 +55,26 @@ TTL_S = 2400 #: What core says when a computer's provider runs it as the sandbox itself, which a reset can't replace in place. IN_PLACE = "can't be reset in place" -#: Inside the computer, on real time: the gateway's universe as the computer reaches it, between two readings of real -#: time, then the session's own (``date``, without the real-time marker), between two more; each pair taken again, -#: up to ten times, until both brackets are narrower than argv[2], and ``within`` says whether one was. +#: Inside the computer, on real time: the gateway's universe as the computer reaches it at argv[1], between two +#: readings of real time, then the session's own (``date``, without the real-time marker), between two more, taken up +#: to ten times, keeping the narrowest; argv[1] "-" reads the session alone. Each bracket's width is printed, so the +#: caller can say how far the reading may be from the truth. READ = """ import json, os, subprocess, sys, time, urllib.request -url, widest = sys.argv[1], float(sys.argv[2]) +url = sys.argv[1] session = {k: v for k, v in os.environ.items() if k != "AGENTENV_REAL_TIME"} +best = None for _ in range(10): a = time.time() - gateway = json.load(urllib.request.urlopen(url, timeout=10))["virtual_time"] + gateway = json.load(urllib.request.urlopen(url, timeout=10))["virtual_time"] if url != "-" else None b = time.time() universe = float(subprocess.run(["date", "+%s.%N"], env=session, capture_output=True, text=True, check=True).stdout) c = time.time() - if b - a < widest and c - b < widest: - break -print(json.dumps({"gateway_at": (a + b) / 2, "gateway": gateway, "session_at": (b + c) / 2, "session": universe, - "widths": [round(b - a, 4), round(c - b, 4)], "within": b - a < widest and c - b < widest})) + read = {"gateway_at": (a + b) / 2, "gateway": gateway, "session_at": (b + c) / 2, "session": universe, + "widths": [round(b - a, 4), round(c - b, 4)]} + if best is None or max(read["widths"]) < max(best["widths"]): + best = read +print(json.dumps(best)) """ #: A page that names its own Date.now(), in milliseconds, in its title, five times a second. CLOCK_PAGE = "data:text/html," + urllib.parse.quote( @@ -86,10 +89,6 @@ def _at(text: str) -> float: return datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp() -def _widest(rate: float) -> float: - return 2 * READING_S / max(rate, 1) - - async def _write(deployed, method: str, **params) -> float: """A clock write that waits up to 15 s for every computer to show it; the seconds it took.""" started = time.monotonic() @@ -102,26 +101,25 @@ async def _now(deployed) -> datetime: return datetime.fromtimestamp(_at(state["virtual_time"]), timezone.utc) -async def _reading(computer, time_url: str, rate: float) -> dict: - ran = await inside.run(computer, ["env", "AGENTENV_REAL_TIME=1", "python3", "-c", READ, time_url, - str(_widest(rate))], timeout_s=120) +async def _reading(computer, time_url: str) -> dict: + ran = await inside.run(computer, ["env", "AGENTENV_REAL_TIME=1", "python3", "-c", READ, time_url], timeout_s=120) assert ran["exit_code"] == 0, ran - read = json.loads(ran["stdout"]) - assert read["within"], (f"the computer's readings took over {_widest(rate):.3f} s each of ten times, so none is " - f"close enough to tell its skew: the last took {read['widths']}") - return read + return json.loads(ran["stdout"]) -async def _skew(computer, time_url: str, rate: float) -> float: - """How far the session's clock is from the gateway's, in universe seconds, both read inside the computer.""" - read = await _reading(computer, time_url, rate) - return round(read["session"] - (_at(read["gateway"]) + rate * (read["session_at"] - read["gateway_at"])), 3) +async def _skew(computer, time_url: str, rate: float) -> tuple[float, float]: + """How far the session's clock is from the gateway's, in universe seconds, both read inside the computer, and how + far that may be from the truth: half of each reading's bracket of real time, at the clock's rate.""" + read = await _reading(computer, time_url) + skew = read["session"] - (_at(read["gateway"]) + rate * (read["session_at"] - read["gateway_at"])) + return round(skew, 3), round(rate * sum(read["widths"]) / 2, 3) -async def _rate(computer, time_url: str, rate: float, over_s: float = 3.0) -> float: - first = await _reading(computer, time_url, rate) +async def _rate(computer, over_s: float = 3.0) -> float: + """The session clock's rate, from two of its own readings ``over_s`` apart: no gateway read is in it.""" + first = await _reading(computer, "-") await asyncio.sleep(over_s) - then = await _reading(computer, time_url, rate) + then = await _reading(computer, "-") return round((then["session"] - first["session"]) / (then["session_at"] - first["session_at"]), 3) @@ -195,10 +193,10 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo await _now(deployed) - timedelta(days=30)), virtual_seconds_per_real_second=1) skews["a month back"] = await _skew(own, time_url, 1) writes[f"rate {RATE}"] = await _write(deployed, "set_rate", virtual_seconds_per_real_second=RATE) - rates[RATE] = await _rate(own, time_url, RATE) + rates[RATE] = await _rate(own) skews[f"at a rate of {RATE}"] = await _skew(own, time_url, RATE) writes["frozen"] = await _write(deployed, "set_rate", virtual_seconds_per_real_second=0) - rates["frozen"], skews["frozen"] = await _rate(own, time_url, 0), await _skew(own, time_url, 0) + rates["frozen"], skews["frozen"] = await _rate(own), await _skew(own, time_url, 0) writes["running again"] = await _write(deployed, "set_rate", virtual_seconds_per_real_second=1) skews["running again"] = await _skew(own, time_url, 1) @@ -237,7 +235,7 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo def _assert(results: dict) -> None: assert results["synced"] and all(armed for _, armed in results["synced"]), results - assert all(abs(skew) < MAX_SKEW_S for skew in results["skews"].values()), results + assert all(abs(skew) - error < MAX_SKEW_S for skew, error in results["skews"].values()), results assert abs(results["rates"][RATE] / RATE - 1) < 0.05 and abs(results["rates"]["frozen"]) < 0.01, results assert results["follower killed, back"] == (True, True) and results["follower back in s"] < FOLLOWER_BACK_S, results assert results["reset"] == f"refused: {IN_PLACE}" or results["shown after a reset"], results From fd76a94bdcbeefea9bd275810e87582b8fc227f9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 08:22:56 -0800 Subject: [PATCH 5/9] test(computers): the remote clock check's limits are named where it starts The waits, timeouts, attempt counts, tolerances and the arming offset its helpers held inline are named constants beside the others, and the reading script inside the computer takes its attempts and gateway timeout as arguments. Co-Authored-By: Claude Opus 5.5 --- tst/manual/remote_computer_clock_check.py | 78 +++++++++++++++-------- 1 file changed, 52 insertions(+), 26 deletions(-) diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index 38e38b9e2..56767f149 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -53,20 +53,42 @@ #: How soon a killed follower may be back: supervisord's second, and a remote sandbox's slower start. FOLLOWER_BACK_S = 10 TTL_S = 2400 +#: How far back of now the universe is armed: half a year, as the local clock test arms it. +ARMED_BACK = timedelta(days=182) +#: How long a clock write waits for every computer to show it, and how long a call to the gateway may take. +FOLLOWERS_WAIT_S = 15 +CALL_TIMEOUT_S = 30 +#: How long the reading script inside the computer may run, how many times it reads, keeping the narrowest, and how +#: long its read of the gateway may take. +READ_TIMEOUT_S = 120 +READ_ATTEMPTS = 10 +GATEWAY_READ_TIMEOUT_S = 10 +#: How far apart the two readings a rate is measured from are, and how far that rate may be from the clock's: a +#: fraction of it, or outright when frozen. +RATE_OVER_S = 3.0 +RATE_TOLERANCE = 0.05 +FROZEN_TOLERANCE = 0.01 +#: How long a killed follower, and a page's time, are waited for, and how often each is looked for. +FOLLOWER_WAIT_S = 60 +FOLLOWER_POLL_S = 0.5 +PAGE_WAIT_S = 60 +PAGE_POLL_S = 0.25 +#: How far a page's Date.now() may be from the gateway's universe: room for its title's refresh and the reads from here. +MAX_PAGE_SKEW_S = 3 #: What core says when a computer's provider runs it as the sandbox itself, which a reset can't replace in place. IN_PLACE = "can't be reset in place" -#: Inside the computer, on real time: the gateway's universe as the computer reaches it at argv[1], between two -#: readings of real time, then the session's own (``date``, without the real-time marker), between two more, taken up -#: to ten times, keeping the narrowest; argv[1] "-" reads the session alone. Each bracket's width is printed, so the -#: caller can say how far the reading may be from the truth. +#: Inside the computer, on real time: the gateway's universe as the computer reaches it at argv[1], read within +#: argv[3] seconds, between two readings of real time, then the session's own (``date``, without the real-time marker), +#: between two more, taken argv[2] times, keeping the narrowest; argv[1] "-" reads the session alone. Each bracket's +#: width is printed, so the caller can say how far the reading may be from the truth. READ = """ import json, os, subprocess, sys, time, urllib.request -url = sys.argv[1] +url, attempts, timeout = sys.argv[1], int(sys.argv[2]), float(sys.argv[3]) session = {k: v for k, v in os.environ.items() if k != "AGENTENV_REAL_TIME"} best = None -for _ in range(10): +for _ in range(attempts): a = time.time() - gateway = json.load(urllib.request.urlopen(url, timeout=10))["virtual_time"] if url != "-" else None + gateway = json.load(urllib.request.urlopen(url, timeout=timeout))["virtual_time"] if url != "-" else None b = time.time() universe = float(subprocess.run(["date", "+%s.%N"], env=session, capture_output=True, text=True, check=True).stdout) c = time.time() @@ -90,19 +112,22 @@ def _at(text: str) -> float: async def _write(deployed, method: str, **params) -> float: - """A clock write that waits up to 15 s for every computer to show it; the seconds it took.""" + """A clock write that waits up to ``FOLLOWERS_WAIT_S`` for every computer to show it; the seconds it took.""" started = time.monotonic() - await deployed.invoke(EXT_CLOCK_URI, method, {**params, "wait_followers_s": 15}, timeout=30) + await deployed.invoke(EXT_CLOCK_URI, method, {**params, "wait_followers_s": FOLLOWERS_WAIT_S}, + timeout=CALL_TIMEOUT_S) return round(time.monotonic() - started, 2) async def _now(deployed) -> datetime: - state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30) + state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=CALL_TIMEOUT_S) return datetime.fromtimestamp(_at(state["virtual_time"]), timezone.utc) async def _reading(computer, time_url: str) -> dict: - ran = await inside.run(computer, ["env", "AGENTENV_REAL_TIME=1", "python3", "-c", READ, time_url], timeout_s=120) + argv = ["env", "AGENTENV_REAL_TIME=1", "python3", "-c", READ, time_url, str(READ_ATTEMPTS), + str(GATEWAY_READ_TIMEOUT_S)] + ran = await inside.run(computer, argv, timeout_s=READ_TIMEOUT_S) assert ran["exit_code"] == 0, ran return json.loads(ran["stdout"]) @@ -115,7 +140,7 @@ async def _skew(computer, time_url: str, rate: float) -> tuple[float, float]: return round(skew, 3), round(rate * sum(read["widths"]) / 2, 3) -async def _rate(computer, over_s: float = 3.0) -> float: +async def _rate(computer, over_s: float = RATE_OVER_S) -> float: """The session clock's rate, from two of its own readings ``over_s`` apart: no gateway read is in it.""" first = await _reading(computer, "-") await asyncio.sleep(over_s) @@ -135,26 +160,26 @@ async def _kill_follower(computer) -> tuple[list[str], list[str], float]: killed = await _followers(computer) await channel.run(["kill", "-9", *killed]) started = time.monotonic() - while time.monotonic() - started < 60: + while time.monotonic() - started < FOLLOWER_WAIT_S: back = await _followers(computer) if back and set(back) != set(killed): return killed, back, round(time.monotonic() - started, 1) - await asyncio.sleep(0.5) - return killed, [], 60.0 + await asyncio.sleep(FOLLOWER_POLL_S) + return killed, [], float(FOLLOWER_WAIT_S) async def _page_now(browser: DeployedEnv) -> float: """What a fresh page in ``browser`` takes for now, in seconds, from its Date.now().""" opened = await _browser_op(browser, "tabs/open", {"url": CLOCK_PAGE}) - deadline, tabs = time.monotonic() + 60, [] + deadline, tabs = time.monotonic() + PAGE_WAIT_S, [] while time.monotonic() < deadline: tabs = (await _browser_op(browser, "tabs/list", {}))["tabs"] tab = next((tab for tab in tabs if tab["id"] == opened["tab"]), None) if tab and (tab.get("title") or "").startswith("now "): await _browser_op(browser, "tabs/close", {"tab": tab["id"]}) return int(tab["title"].split()[1]) / 1000 - await asyncio.sleep(0.25) - raise AssertionError(f"the clock page named no time within 60 s: {tabs}") + await asyncio.sleep(PAGE_POLL_S) + raise AssertionError(f"the clock page named no time within {PAGE_WAIT_S} s: {tabs}") async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: bool = False) -> dict: @@ -174,7 +199,7 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo "sandbox_type": own.sandbox_type} time_url = kept["watch_url"].removesuffix("/clock/watch") + "/clock/time" - universe = datetime.now(timezone.utc) - timedelta(days=182) + universe = datetime.now(timezone.utc) - ARMED_BACK await SyncEnvClockTaskStep(id="clock", version=None, env_id=env_id, virtual_time=_iso(universe)).execute(context) results["synced"] = [(entry["service"], entry["result"]["follower"]["armed"]) @@ -185,7 +210,7 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo skews["armed"] = await _skew(own, time_url, 1) if browser: results["page minus universe s"] = round(await _page_now(own) - _at( - (await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30))["virtual_time"]), 1) + (await deployed.invoke(EXT_CLOCK_URI, "state", timeout=CALL_TIMEOUT_S))["virtual_time"]), 1) for name, by in (("a day on", timedelta(days=1)), ("a week on", timedelta(weeks=1))): writes[name] = await _write(deployed, "advance", virtual_time=_iso(await _now(deployed) + by)) skews[name] = await _skew(own, time_url, 1) @@ -222,8 +247,8 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo skews["after a reset"] = await _skew(own, time_url, 1) if browser: results["page minus universe s after a reset"] = round(await _page_now(own) - _at( - (await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30))["virtual_time"]), 1) - state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30) + (await deployed.invoke(EXT_CLOCK_URI, "state", timeout=CALL_TIMEOUT_S))["virtual_time"]), 1) + state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=CALL_TIMEOUT_S) results["shown after a reset"] = state["followers"][kept["name"]]["version"] == state["version"] results["reset"] = "done" finally: @@ -236,7 +261,8 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo def _assert(results: dict) -> None: assert results["synced"] and all(armed for _, armed in results["synced"]), results assert all(abs(skew) - error < MAX_SKEW_S for skew, error in results["skews"].values()), results - assert abs(results["rates"][RATE] / RATE - 1) < 0.05 and abs(results["rates"]["frozen"]) < 0.01, results + assert abs(results["rates"][RATE] / RATE - 1) < RATE_TOLERANCE, results + assert abs(results["rates"]["frozen"]) < FROZEN_TOLERANCE, results assert results["follower killed, back"] == (True, True) and results["follower back in s"] < FOLLOWER_BACK_S, results assert results["reset"] == f"refused: {IN_PLACE}" or results["shown after a reset"], results assert results["torn down"], results @@ -256,8 +282,8 @@ async def test_a_remote_desktop_keeps_to_its_gateways_clock_through_jumps_rates_ async def test_a_remote_browser_computer_and_its_pages_keep_to_its_gateways_clock(sandbox): results = await _through_the_steps(BROWSING, "browser", sandbox, browser=True) _assert(results) - assert abs(results["page minus universe s"]) < 3, results - assert results["reset"] != "done" or abs(results["page minus universe s after a reset"]) < 3, results + assert abs(results["page minus universe s"]) < MAX_PAGE_SKEW_S, results + assert results["reset"] != "done" or abs(results["page minus universe s after a reset"]) < MAX_PAGE_SKEW_S, results @pytest.mark.skipif(not OFFICE, reason="AGENTENV_CLOCK_CHECK_OFFICE names no multi env") @@ -273,7 +299,7 @@ async def test_arming_the_clock_of_a_remote_desktop_booted_from_its_disk_is_refu ).execute(context) with pytest.raises(StepContextError) as refused: await SyncEnvClockTaskStep(id="clock", version=None, env_id=OFFICE, virtual_time=_iso( - datetime.now(timezone.utc) - timedelta(days=182))).execute(context) + datetime.now(timezone.utc) - ARMED_BACK)).execute(context) finally: report = await teardown_run(context) print("CLOCK CHECK", json.dumps({"sandbox": sandbox, "refused": refused and str(refused.value)}), flush=True) From cced98526f10a0a2b726237f20d1d41636d154ff Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 09:34:42 -0800 Subject: [PATCH 6/9] feat(task_step): tolerate_missing_sync_time covers a multi env's computer too A computer that offers no clock/v1 is skipped when the step tolerates servers without sync_time, as it is by default, and stays on real time; a strict arm refuses it, naming it and what to deploy instead, rather than refusing it whatever the step says. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/sync_env_clock.py | 25 ++++++------- tst/manual/remote_computer_clock_check.py | 20 +++++++---- tst/unit/task_step/sync_env_clock_test.py | 36 ++++++++++++++++--- 3 files changed, 57 insertions(+), 24 deletions(-) diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 685845b24..cdc87d10f 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -4,12 +4,12 @@ stored env card declares clock/v1, then invokes sync_time on each backing server, MCP server or website, the env card lists (``legacy_protocol.backing_servers``) whose own card advertises it, at the route that card gives. An env whose card offers no set_time has no gateway clock to arm, as a computer deployed alone, and is refused -saying to deploy it in a multi env; a record that kept no card is refused saying so. A multi env's computer whose card -offers no clock/v1, one booted from a disk or a VM bundle or on a base without agent-env's clock, is refused too: its -session would stay on real time. Other non-advertisers are skipped when tolerate_missing_sync_time (default True), and -websites always. Place right -before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 -and start it with set_env_clock_rate right before prompt_agent. +saying to deploy it in a multi env; a record that kept no card is refused saying so. +Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. A multi env's computer +whose card offers no clock/v1 (one booted from a disk or a VM bundle, or on a base without agent-env's clock) is one +too: tolerated, it's skipped and stays on real time; otherwise it's refused, naming it. Place right before +prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start +it with set_env_clock_rate right before prompt_agent. """ from __future__ import annotations @@ -183,8 +183,9 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time tolerate: Optional[bool] = None, server: Optional[BackingServer] = None) -> dict: """Invoke sync_time on one server, an MCP server or with ``mcp=False`` a website, if its card advertises clock/v1; skip a server with no card or no clock/v1 when ``tolerate`` (tolerate_missing_sync_time by default), - else raise. A multi env's computer with no clock/v1 is always refused, since it can't follow the universe. ``execute`` tolerates every website, so one that doesn't follow the clock never fails the step; one - that follows it but can't take the task's timezone does, as an MCP server does. ``server`` is the server as the + else raise, a multi env's computer saying it can't follow the universe. ``execute`` tolerates every website, so + one that doesn't follow the clock never fails the step; one that follows it but can't take the task's timezone + does, as an MCP server does. ``server`` is the server as the env's card lists it (``legacy_protocol.server_card``); without it, the card is ``service``'s on ``deployed``'s stored card, or read live at its gateway path.""" tolerate = self.tolerate_missing_sync_time if tolerate is None else tolerate @@ -199,15 +200,15 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time return {"synced": False, "reason": "no_env_card"} raise RuntimeError(f"{service} has no env card: it serves none, its card isn't named {service!r}, or the deploy couldn't read it") if protocol_v1.find_extension(card, EXT_CLOCK_URI) is None: + if tolerate: + logger.info(f"sync_env_clock: {service} does not advertise {EXT_CLOCK_URI}; skipping") + return {"synced": False, "reason": "not_advertised"} if server is not None and server.record is not None and protocol_v1.find_extension(card, COMPUTER_EXEC): raise StepContextError( f"computer {service!r} can't follow the universe clock: it offers no {EXT_CLOCK_URI} sync_time, " "as a computer booted from a disk or a VM bundle, or on a base without agent-env's clock, doesn't, " "so its session would stay on real time. Deploy it in a container form of a base that follows the " - "clock, or leave the clock unarmed") - if tolerate: - logger.info(f"sync_env_clock: {service} does not advertise {EXT_CLOCK_URI}; skipping") - return {"synced": False, "reason": "not_advertised"} + "clock, leave the clock unarmed, or set tolerate_missing_sync_time to leave it on real time") raise StepContextError(f"{service} does not advertise {EXT_CLOCK_URI}") if not env_get_time_url: raise RuntimeError(f"gateway did not expose env_get_time_url; cannot sync {service}") diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index 56767f149..1d712f6e5 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -6,7 +6,7 @@ A provider whose sandbox is the computer's container itself, as ``modal``'s is, can't reset it in place, which core refuses; the check takes that refusal as the reset's outcome. On a provider that boots the desktop from its disk form, -whose guest follows no clock yet, arming the clock is refused. +whose guest follows no clock yet, arming the clock skips it, as tolerated by default, and a strict arm refuses it. It needs a config whose image and object stores the provider reaches, the provider's credentials, and two multi envs written there. ``AGENTENV_CLOCK_CHECK_OFFICE`` names one whose computer ``desktop`` is the ubuntu-24.04 desktop, and @@ -290,18 +290,24 @@ async def test_a_remote_browser_computer_and_its_pages_keep_to_its_gateways_cloc @pytest.mark.parametrize("sandbox", [sandbox for sandbox in SANDBOXES if build_sandbox_provider(sandbox).disk_image_platforms()]) @pytest.mark.asyncio -async def test_arming_the_clock_of_a_remote_desktop_booted_from_its_disk_is_refused_naming_it(sandbox): - context, refused = TaskStepContext(), None +async def test_a_remote_desktop_booted_from_its_disk_is_skipped_when_tolerated_and_refused_by_a_strict_arm(sandbox): + context, results, refused = TaskStepContext(), {"sandbox": sandbox}, None try: await DeployEnvTaskStep(id="office", version=None, env_id=OFFICE, sandbox_type=GATEWAY_SANDBOX, ttl_seconds=TTL_S, child_envs={"desktop": {"sandbox_type": sandbox, "env_params": {"form": "disk"}}} ).execute(context) + universe = _iso(datetime.now(timezone.utc) - ARMED_BACK) + await SyncEnvClockTaskStep(id="clock", version=None, env_id=OFFICE, virtual_time=universe).execute(context) + results["tolerated"] = [(entry["service"], entry.get("reason")) + for entry in context.metadata["clock_configurations"][-1]["skipped"]] with pytest.raises(StepContextError) as refused: - await SyncEnvClockTaskStep(id="clock", version=None, env_id=OFFICE, virtual_time=_iso( - datetime.now(timezone.utc) - ARMED_BACK)).execute(context) + await SyncEnvClockTaskStep(id="strict", version=None, env_id=OFFICE, virtual_time=universe, + tolerate_missing_sync_time=False).execute(context) + results["refused"] = str(refused.value) finally: report = await teardown_run(context) - print("CLOCK CHECK", json.dumps({"sandbox": sandbox, "refused": refused and str(refused.value)}), flush=True) + print("CLOCK CHECK", json.dumps(results), flush=True) - assert "computer 'desktop' can't follow the universe clock" in str(refused.value) and not report.failed + assert ("desktop", "not_advertised") in results["tolerated"], results + assert "computer 'desktop' can't follow the universe clock" in results["refused"] and not report.failed diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index a225b42ff..96fe68fb4 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -509,29 +509,55 @@ def test_a_padded_zone_is_stored_and_sent_stripped(): assert s.timezone == "America/New_York" and s.to_dict()["timezone"] == "America/New_York" -_EXEC_EXT = {"uri": COMPUTER_EXEC, "params": {"endpoint": "/agentenv/ext/computer-exec", "methods": {"run": {"method": "POST"}}}} +_EXEC_EXT = {"uri": COMPUTER_EXEC, + "params": {"endpoint": "/agentenv/ext/computer-exec", "methods": {"run": {"method": "POST"}}}} def _with_computer(record: DeployedEnv, card: dict) -> DeployedEnv: """``record``, a multi env's, with the computer ``desktop`` on a sandbox of its own whose card is ``card``.""" computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", environment_card=card) - return dataclasses.replace(record, control_token="gateway-token", child_envs={"desktop": dataclasses.asdict(computer)}) + return dataclasses.replace(record, control_token="gateway-token", + child_envs={"desktop": dataclasses.asdict(computer)}) + + +def _office_without_a_computer_clock(card_children: dict) -> dict: + """The card of a multi env's computer ``desktop`` that offers computer-exec but no clock, as a disk guest's does.""" + return {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_EXEC_EXT]}, **card_children} @pytest.mark.asyncio -async def test_arming_a_multi_env_whose_computer_offers_no_clock_is_refused_naming_it_and_what_to_deploy(monkeypatch): +async def test_a_multi_envs_computer_that_offers_no_clock_is_skipped_as_tolerated_and_stays_on_real_time(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), + _office_without_a_computer_clock({})) + env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) + context = TaskStepContext(deployed_envs=[record]) + + with patch("agent_env.env.env.Env.get", return_value=env): + await _step().execute(context) + + configured = context.metadata["clock_configurations"][0] + assert [entry["service"] for entry in configured["synced"]] == ["email"] + assert [(entry["service"], entry["reason"]) for entry in configured["skipped"]] == [("desktop", "not_advertised")] + assert not [request for request in sent if request.url.host == "desk.example"] + + +@pytest.mark.asyncio +async def test_a_strict_arm_of_a_multi_env_whose_computer_offers_no_clock_is_refused_naming_it_and_what_to_deploy( + monkeypatch): """As a computer booted from its disk is: its session would stay on real time while the universe moves.""" sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), - {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_EXEC_EXT]}}) + _office_without_a_computer_clock({})) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) with patch("agent_env.env.env.Env.get", return_value=env), pytest.raises( StepContextError, match="computer 'desktop' can't follow the universe clock") as refused: - await _step().execute(TaskStepContext(deployed_envs=[record])) + await _step(tolerate_missing_sync_time=False).execute(TaskStepContext(deployed_envs=[record])) assert "container form of a base that follows the clock" in str(refused.value) + assert "tolerate_missing_sync_time" in str(refused.value) assert not [request for request in sent if request.url.host == "desk.example"] From 78841376485494051ee8965b57fe3f868b700243 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 10:11:53 -0800 Subject: [PATCH 7/9] refactor(task_step): a backing server says whether it's a multi env's computer, and the clock check reads as core does - BackingServer.is_computer names the rule sync_env_clock used inline (a server on a computer's own sandbox whose card offers computer-exec/v1), beside the code that lists those servers, with a test of its own. - sync_env_clock's tests share one helper for a multi env with a computer, and the module's imports are at its top. - The remote clock check expects a reset to be refused where core refuses it, on a sandbox that isn't a VM, rather than by the refusal's wording, and its docstring says how to write the envs it needs. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/legacy_protocol.py | 7 ++ .../task_step/task_steps/sync_env_clock.py | 8 +-- tst/manual/remote_computer_clock_check.py | 32 ++++++--- tst/unit/env/test_legacy_protocol.py | 15 ++++ tst/unit/task_step/sync_env_clock_test.py | 68 ++++++------------- 5 files changed, 67 insertions(+), 63 deletions(-) diff --git a/src/agent_env/env/legacy_protocol.py b/src/agent_env/env/legacy_protocol.py index 18d78e234..2316bc810 100644 --- a/src/agent_env/env/legacy_protocol.py +++ b/src/agent_env/env/legacy_protocol.py @@ -15,6 +15,7 @@ import httpx from agentenv_protocol import METHOD_GET, DataPart, client as protocol_v1 +from agentenv_protocol.computer import COMPUTER_EXEC from mcp import ClientSession from mcp.types import CallToolResult from mcp.client.streamable_http import streamable_http_client @@ -61,6 +62,12 @@ def card(self) -> Optional[dict]: """The server's card as the env's card lists it, or None.""" return self.child.card if self.child is not None else None + @property + def is_computer(self) -> bool: + """Whether the server is a multi env's computer itself, on a sandbox of its own: its card offers + computer-exec/v1, which the apps it fronts don't.""" + return self.record is not None and protocol_v1.find_extension(self.card or {}, COMPUTER_EXEC) is not None + def owner(self, deployed: DeployedEnv) -> DeployedEnv: """The record whose control token a call to the server takes: its own ``record``, a multi env's computer's or one of its apps', else ``deployed``, the record of the env it was listed for.""" diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index cdc87d10f..0d0f3e08a 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -22,7 +22,6 @@ import httpx import tzdata # noqa: F401 from agentenv_protocol import client as protocol_v1 -from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.env.env import EnvCapabilityUnsupported from agent_env.env.gateway.constants import EXT_CLOCK_URI @@ -185,9 +184,8 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time clock/v1; skip a server with no card or no clock/v1 when ``tolerate`` (tolerate_missing_sync_time by default), else raise, a multi env's computer saying it can't follow the universe. ``execute`` tolerates every website, so one that doesn't follow the clock never fails the step; one that follows it but can't take the task's timezone - does, as an MCP server does. ``server`` is the server as the - env's card lists it (``legacy_protocol.server_card``); without it, the card is ``service``'s on ``deployed``'s - stored card, or read live at its gateway path.""" + does, as an MCP server does. ``server`` is the server as the env's card lists it (``legacy_protocol.server_card``); + without it, the card is ``service``'s on ``deployed``'s stored card, or read live at its gateway path.""" tolerate = self.tolerate_missing_sync_time if tolerate is None else tolerate from agent_env.env import legacy_protocol @@ -203,7 +201,7 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time if tolerate: logger.info(f"sync_env_clock: {service} does not advertise {EXT_CLOCK_URI}; skipping") return {"synced": False, "reason": "not_advertised"} - if server is not None and server.record is not None and protocol_v1.find_extension(card, COMPUTER_EXEC): + if server is not None and server.is_computer: raise StepContextError( f"computer {service!r} can't follow the universe clock: it offers no {EXT_CLOCK_URI} sync_time, " "as a computer booted from a disk or a VM bundle, or on a base without agent-env's clock, doesn't, " diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index 1d712f6e5..fabdd9b41 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -14,6 +14,18 @@ Each multi env deploys on ``AGENTENV_CLOCK_CHECK_GATEWAY_SANDBOX`` (``modal_vm``), its computer on each of ``AGENTENV_CLOCK_CHECK_SANDBOXES`` (``modal_vm,modal``). +To write them, register a bundle into those stores with ``agent-env bundle register --sandbox ``, +which composes its computers on the provider. Its envs: +- ``desktop``: ``type = "computer"``, ``computer = "ubuntu-24.04"``, ``driver = "reference"``. +- ``browser``: ``type = "computer"``, ``computer = "ubuntu-24.04-browser"``, ``driver = "page"``, + ``apps = ["chromium"]``. +- ``office``: ``type = "multi"``, ``computer_envs = ["desktop"]``. +- ``browsing``: ``type = "multi"``, ``computer_envs = ["browser"]``. +- Copies of those bases, drivers and app, since registration refuses entities of installed bundles. +Registration builds each image it writes on this machine, for amd64. The stores need the gateway's and the service-db's +infra envs too (``agent-env env gateway put --id default``, ``agent-env env service-db put --id default-db``); a VM +sandbox builds an image from its context when it isn't published or was built for another platform. + Every reading is taken inside the computer: the gateway's universe, read at the address the computer reaches the gateway at, as its follower does, and the session's own, each between two readings of real time on the computer's clock. So neither this machine's distance from the provider nor its clock is in them.""" @@ -33,6 +45,7 @@ from agent_env.env.envs.computer.utils.sites import RootChannel from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.providers import build_sandbox_provider +from agent_env.providers.sandbox_providers.sandbox import VmSandbox from agent_env.task.teardown import teardown_run from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_steps.deploy_env import DeployEnvTaskStep @@ -75,8 +88,8 @@ PAGE_POLL_S = 0.25 #: How far a page's Date.now() may be from the gateway's universe: room for its title's refresh and the reads from here. MAX_PAGE_SKEW_S = 3 -#: What core says when a computer's provider runs it as the sandbox itself, which a reset can't replace in place. -IN_PLACE = "can't be reset in place" +#: The reset's outcome on a provider whose sandbox is the computer's container itself, which core can't replace. +REFUSED_IN_PLACE = "refused: its sandbox is the container itself" #: Inside the computer, on real time: the gateway's universe as the computer reaches it at argv[1], read within #: argv[3] seconds, between two readings of real time, then the session's own (``date``, without the real-time marker), #: between two more, taken argv[2] times, keeping the narrowest; argv[1] "-" reads the session alone. Each bracket's @@ -236,13 +249,14 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo await _now(deployed) + timedelta(hours=8))) skews["after the follower's kill"] = await _skew(own, time_url, 1) - try: - await ResetEnvTaskStep(id="reset", version=None, env_id=env_id, fail_task_on_error=True).execute(context) - except RuntimeError as error: - if IN_PLACE not in str(error): - raise - results["reset"] = f"refused: {IN_PLACE}" + if not isinstance(await build_sandbox_provider(own.sandbox_type).get_sandbox(own.sandbox_id), VmSandbox): + # Only a VM's Docker can replace the computer's container in place (SandboxProvider.reset_container). + with pytest.raises(RuntimeError): + await ResetEnvTaskStep(id="reset", version=None, env_id=env_id, + fail_task_on_error=True).execute(context) + results["reset"] = REFUSED_IN_PLACE return results + await ResetEnvTaskStep(id="reset", version=None, env_id=env_id, fail_task_on_error=True).execute(context) own = DeployedEnv.from_dict(context.deployed_envs[0].child_envs[child]) skews["after a reset"] = await _skew(own, time_url, 1) if browser: @@ -264,7 +278,7 @@ def _assert(results: dict) -> None: assert abs(results["rates"][RATE] / RATE - 1) < RATE_TOLERANCE, results assert abs(results["rates"]["frozen"]) < FROZEN_TOLERANCE, results assert results["follower killed, back"] == (True, True) and results["follower back in s"] < FOLLOWER_BACK_S, results - assert results["reset"] == f"refused: {IN_PLACE}" or results["shown after a reset"], results + assert results["reset"] == REFUSED_IN_PLACE or results["shown after a reset"], results assert results["torn down"], results diff --git a/tst/unit/env/test_legacy_protocol.py b/tst/unit/env/test_legacy_protocol.py index d426e3259..685ec0179 100644 --- a/tst/unit/env/test_legacy_protocol.py +++ b/tst/unit/env/test_legacy_protocol.py @@ -2,12 +2,14 @@ from __future__ import annotations +import dataclasses from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from agentenv_protocol import RPC_PATH, WELL_KNOWN_PATH, DataPart, uploaded_file_part from agentenv_protocol.client import GetDataResponse +from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.env import legacy_protocol from agent_env.env.env import DeployedSandboxEnv @@ -226,6 +228,19 @@ def test_card_servers_of_a_leaf_card_is_the_env_itself_and_a_composed_card_servi assert [s.environment_name for s in legacy_protocol.card_servers(driver, "https://d")] == ["desktop", "slack", "slack", "docs"] + +def test_a_computer_is_the_server_on_a_sandbox_of_its_own_offering_computer_exec_not_an_app_it_fronts(): + driver = {"name": "desktop", "url": RPC_PATH, + "capabilities": {"operations": ["data/get"], "extensions": [{"uri": COMPUTER_EXEC}]}, + "children_environments": [{"name": "notes", "url": "/apps/notes/agentenv", + "capabilities": {"extensions": []}}]} + record = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk") + listed = legacy_protocol.card_servers(driver, "https://d") + + assert [(s.environment_name, dataclasses.replace(s, record=record).is_computer) for s in listed] == [ + ("desktop", True), ("notes", False)] + assert not any(s.is_computer for s in listed) + def _record(card: dict | None, card_url: str | None = "https://env.example/.well-known/agent-env.json"): from agent_env.env.env import DeployedGatewayEnv diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 96fe68fb4..67c0c5cd2 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -121,9 +121,6 @@ async def test_execute_keeps_the_arm_failure_message(monkeypatch): @pytest.mark.asyncio async def test_execute_syncs_a_multi_envs_websites_alongside_its_mcp_servers(monkeypatch): - from types import SimpleNamespace - from unittest.mock import patch - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="shop"), SimpleNamespace(environment_name="blog")]) @@ -142,8 +139,6 @@ async def test_execute_syncs_a_multi_envs_websites_alongside_its_mcp_servers(mon @pytest.mark.asyncio async def test_execute_syncs_a_single_website_env(monkeypatch): - from unittest.mock import patch - from agent_env.env.envs.website import WebsiteEnv sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) @@ -172,8 +167,6 @@ async def fake_card(base_url, **kw): @pytest.mark.asyncio async def test_execute_syncs_a_website_sharing_an_mcp_servers_name_at_its_own_route(monkeypatch): """The card lists the two as children at distinct urls, so each is synced by its own card, with no card read.""" - from unittest.mock import patch - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="email")]) @@ -193,7 +186,6 @@ async def test_execute_syncs_a_website_sharing_an_mcp_servers_name_at_its_own_ro async def test_execute_without_a_card_url_syncs_the_servers_the_definition_names_read_live(monkeypatch): """An older record kept no card URL, so its servers come from its env definition and each card is read live at its gateway path.""" - from unittest.mock import patch import httpx @@ -232,9 +224,6 @@ async def invoke(uri, method, params=None, **kw): @pytest.mark.asyncio async def test_strict_execute_skips_websites_but_not_mcp_servers_that_do_not_follow_the_clock(monkeypatch): - from types import SimpleNamespace - from unittest.mock import patch - _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="shop"), SimpleNamespace(environment_name="legacy")]) @@ -283,8 +272,6 @@ def _cardless() -> DeployedEnv: def _carded(card: dict) -> DeployedEnv: - from agent_env.env.gateway.constants import WELL_KNOWN_PATH - return DeployedGatewayEnv(env_id="e1", env_version=1, gateway_url="http://gw", mcp_url="http://gw/mcp", db_web_url=None, sandbox_id="sb-1", environment_card_url=f"{_CARD}{WELL_KNOWN_PATH}", environment_card=card) @@ -305,6 +292,20 @@ def handle(request: httpx.Request) -> httpx.Response: return sent +_EXEC_EXT = {"uri": COMPUTER_EXEC, + "params": {"endpoint": "/agentenv/ext/computer-exec", "methods": {"run": {"method": "POST"}}}} +#: A multi env's computer ``desktop`` that offers computer-exec but no clock, as a disk guest's driver does. +_COMPUTER_WITHOUT_CLOCK = {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_EXEC_EXT]}} + + +def _with_computer(record: DeployedEnv, card: dict) -> DeployedEnv: + """``record``, a multi env's, with the computer ``desktop`` on a sandbox of its own whose card is ``card``.""" + computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", + environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", environment_card=card) + return dataclasses.replace(record, control_token="gateway-token", + child_envs={"desktop": dataclasses.asdict(computer)}) + + def _zoned(virtual_time="2026-01-01T12:00:00", timezone="America/New_York", **kw): return SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time=virtual_time, timezone=timezone, depends_on=[], **kw) @@ -415,8 +416,6 @@ async def test_a_server_that_does_not_advertise_clock_is_still_skipped_when_a_zo async def test_a_zoned_step_tells_a_website_that_takes_the_zone_and_fails_on_one_that_cannot(monkeypatch): """A website is tolerated for not following the clock, but one that follows it without taking the zone fails the step, as an MCP server does.""" - from types import SimpleNamespace - from unittest.mock import patch env = SimpleNamespace(mcp_server_envs=[], website_envs=[SimpleNamespace(environment_name="shop")]) sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) @@ -434,9 +433,6 @@ async def test_a_zoned_step_tells_a_website_that_takes_the_zone_and_fails_on_one @pytest.mark.asyncio async def test_a_website_sharing_an_mcp_servers_name_is_synced_with_the_envs_control_headers(monkeypatch): - import dataclasses - from unittest.mock import patch - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="email")]) @@ -455,19 +451,10 @@ async def test_a_website_sharing_an_mcp_servers_name_is_synced_with_the_envs_con @pytest.mark.asyncio async def test_a_multi_envs_computer_is_synced_at_its_own_address_with_its_own_control_token(monkeypatch): """Not through the gateway's /svc/desktop/, which carries the gateway's token, not the computer's.""" - import dataclasses - from unittest.mock import patch - - from agent_env.env.env import DeployedSandboxEnv - from agent_env.env.gateway.constants import WELL_KNOWN_PATH - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) - computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", - environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", - environment_card={"name": "desktop", "url": "/agentenv", - "capabilities": {"extensions": [_CLOCK_EXT]}}) - record = dataclasses.replace(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_CLOCK_EXT]})), - control_token="gateway-token", child_envs={"desktop": dataclasses.asdict(computer)}) + record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_CLOCK_EXT]})), + {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_CLOCK_EXT]}}) + computer = DeployedEnv.from_dict(record.child_envs["desktop"]) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) with patch("agent_env.env.env.Env.get", return_value=env): @@ -509,28 +496,11 @@ def test_a_padded_zone_is_stored_and_sent_stripped(): assert s.timezone == "America/New_York" and s.to_dict()["timezone"] == "America/New_York" -_EXEC_EXT = {"uri": COMPUTER_EXEC, - "params": {"endpoint": "/agentenv/ext/computer-exec", "methods": {"run": {"method": "POST"}}}} - - -def _with_computer(record: DeployedEnv, card: dict) -> DeployedEnv: - """``record``, a multi env's, with the computer ``desktop`` on a sandbox of its own whose card is ``card``.""" - computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", - environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", environment_card=card) - return dataclasses.replace(record, control_token="gateway-token", - child_envs={"desktop": dataclasses.asdict(computer)}) - - -def _office_without_a_computer_clock(card_children: dict) -> dict: - """The card of a multi env's computer ``desktop`` that offers computer-exec but no clock, as a disk guest's does.""" - return {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_EXEC_EXT]}, **card_children} - - @pytest.mark.asyncio async def test_a_multi_envs_computer_that_offers_no_clock_is_skipped_as_tolerated_and_stays_on_real_time(monkeypatch): sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), - _office_without_a_computer_clock({})) + _COMPUTER_WITHOUT_CLOCK) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) context = TaskStepContext(deployed_envs=[record]) @@ -549,7 +519,7 @@ async def test_a_strict_arm_of_a_multi_env_whose_computer_offers_no_clock_is_ref """As a computer booted from its disk is: its session would stay on real time while the universe moves.""" sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), - _office_without_a_computer_clock({})) + _COMPUTER_WITHOUT_CLOCK) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) with patch("agent_env.env.env.Env.get", return_value=env), pytest.raises( From 38151bc972b7d14fdd6c505c076b701ab27b7a2e Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 10:19:49 -0800 Subject: [PATCH 8/9] test(computers): the remote clock check takes only core's refusal of an in-place reset as the reset's outcome On a sandbox that isn't a VM, any RuntimeError from the reset passed as the refusal, though the multi env wraps every child's failure in one. The check now also requires core's refusal for that provider, which names it. Co-Authored-By: Claude Opus 5.5 --- tst/manual/remote_computer_clock_check.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index fabdd9b41..110865fe4 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -33,6 +33,7 @@ import asyncio import json import os +import re import time import urllib.parse from datetime import datetime, timedelta, timezone @@ -249,9 +250,11 @@ async def _through_the_steps(env_id: str, child: str, sandbox: str, browser: boo await _now(deployed) + timedelta(hours=8))) skews["after the follower's kill"] = await _skew(own, time_url, 1) - if not isinstance(await build_sandbox_provider(own.sandbox_type).get_sandbox(own.sandbox_id), VmSandbox): - # Only a VM's Docker can replace the computer's container in place (SandboxProvider.reset_container). - with pytest.raises(RuntimeError): + provider = build_sandbox_provider(own.sandbox_type) + if not isinstance(await provider.get_sandbox(own.sandbox_id), VmSandbox): + # Only a VM's Docker can replace the computer's container in place (SandboxProvider.reset_container), and + # core's refusal names the provider; any other failure of the reset fails the check. + with pytest.raises(RuntimeError, match=re.escape(f"can't be reset on {type(provider).__name__}")): await ResetEnvTaskStep(id="reset", version=None, env_id=env_id, fail_task_on_error=True).execute(context) results["reset"] = REFUSED_IN_PLACE From 060675feed4c22464d978384d0a7888db5b998b7 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 17 Nov 2026 19:36:40 -0800 Subject: [PATCH 9/9] revert(task_step): a multi env's computer takes sync_env_clock's path as any server does With tolerate_missing_sync_time covering computers, the computer-specific branch only reworded a strict arm's refusal. A computer whose card offers no clock/v1 is skipped when tolerated and refused, as not advertising clock/v1, when not, from its card like any server; sync_env_clock, legacy_protocol and their tests are as on main again. The remote check's disk case expects that refusal. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/legacy_protocol.py | 7 -- .../task_step/task_steps/sync_env_clock.py | 22 ++-- tst/manual/remote_computer_clock_check.py | 2 +- tst/unit/env/test_legacy_protocol.py | 15 --- tst/unit/task_step/sync_env_clock_test.py | 104 +++++------------- 5 files changed, 38 insertions(+), 112 deletions(-) diff --git a/src/agent_env/env/legacy_protocol.py b/src/agent_env/env/legacy_protocol.py index 2316bc810..18d78e234 100644 --- a/src/agent_env/env/legacy_protocol.py +++ b/src/agent_env/env/legacy_protocol.py @@ -15,7 +15,6 @@ import httpx from agentenv_protocol import METHOD_GET, DataPart, client as protocol_v1 -from agentenv_protocol.computer import COMPUTER_EXEC from mcp import ClientSession from mcp.types import CallToolResult from mcp.client.streamable_http import streamable_http_client @@ -62,12 +61,6 @@ def card(self) -> Optional[dict]: """The server's card as the env's card lists it, or None.""" return self.child.card if self.child is not None else None - @property - def is_computer(self) -> bool: - """Whether the server is a multi env's computer itself, on a sandbox of its own: its card offers - computer-exec/v1, which the apps it fronts don't.""" - return self.record is not None and protocol_v1.find_extension(self.card or {}, COMPUTER_EXEC) is not None - def owner(self, deployed: DeployedEnv) -> DeployedEnv: """The record whose control token a call to the server takes: its own ``record``, a multi env's computer's or one of its apps', else ``deployed``, the record of the env it was listed for.""" diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 0d0f3e08a..8f574b058 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -5,11 +5,9 @@ env card lists (``legacy_protocol.backing_servers``) whose own card advertises it, at the route that card gives. An env whose card offers no set_time has no gateway clock to arm, as a computer deployed alone, and is refused saying to deploy it in a multi env; a record that kept no card is refused saying so. -Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. A multi env's computer -whose card offers no clock/v1 (one booted from a disk or a VM bundle, or on a base without agent-env's clock) is one -too: tolerated, it's skipped and stays on real time; otherwise it's refused, naming it. Place right before -prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 and start -it with set_env_clock_rate right before prompt_agent. +Non-advertisers are skipped when tolerate_missing_sync_time (default True), and websites always. Place right +before prompt_agent so the virtual timeline starts at agent-start; when setup needs the clock armed, arm it at rate 0 +and start it with set_env_clock_rate right before prompt_agent. """ from __future__ import annotations @@ -182,10 +180,10 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time tolerate: Optional[bool] = None, server: Optional[BackingServer] = None) -> dict: """Invoke sync_time on one server, an MCP server or with ``mcp=False`` a website, if its card advertises clock/v1; skip a server with no card or no clock/v1 when ``tolerate`` (tolerate_missing_sync_time by default), - else raise, a multi env's computer saying it can't follow the universe. ``execute`` tolerates every website, so - one that doesn't follow the clock never fails the step; one that follows it but can't take the task's timezone - does, as an MCP server does. ``server`` is the server as the env's card lists it (``legacy_protocol.server_card``); - without it, the card is ``service``'s on ``deployed``'s stored card, or read live at its gateway path.""" + else raise. ``execute`` tolerates every website, so one that doesn't follow the clock never fails the step; one + that follows it but can't take the task's timezone does, as an MCP server does. ``server`` is the server as the + env's card lists it (``legacy_protocol.server_card``); without it, the card is ``service``'s on ``deployed``'s + stored card, or read live at its gateway path.""" tolerate = self.tolerate_missing_sync_time if tolerate is None else tolerate from agent_env.env import legacy_protocol @@ -201,12 +199,6 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time if tolerate: logger.info(f"sync_env_clock: {service} does not advertise {EXT_CLOCK_URI}; skipping") return {"synced": False, "reason": "not_advertised"} - if server is not None and server.is_computer: - raise StepContextError( - f"computer {service!r} can't follow the universe clock: it offers no {EXT_CLOCK_URI} sync_time, " - "as a computer booted from a disk or a VM bundle, or on a base without agent-env's clock, doesn't, " - "so its session would stay on real time. Deploy it in a container form of a base that follows the " - "clock, leave the clock unarmed, or set tolerate_missing_sync_time to leave it on real time") raise StepContextError(f"{service} does not advertise {EXT_CLOCK_URI}") if not env_get_time_url: raise RuntimeError(f"gateway did not expose env_get_time_url; cannot sync {service}") diff --git a/tst/manual/remote_computer_clock_check.py b/tst/manual/remote_computer_clock_check.py index 110865fe4..869895389 100644 --- a/tst/manual/remote_computer_clock_check.py +++ b/tst/manual/remote_computer_clock_check.py @@ -327,4 +327,4 @@ async def test_a_remote_desktop_booted_from_its_disk_is_skipped_when_tolerated_a print("CLOCK CHECK", json.dumps(results), flush=True) assert ("desktop", "not_advertised") in results["tolerated"], results - assert "computer 'desktop' can't follow the universe clock" in results["refused"] and not report.failed + assert f"desktop does not advertise {EXT_CLOCK_URI}" in results["refused"] and not report.failed diff --git a/tst/unit/env/test_legacy_protocol.py b/tst/unit/env/test_legacy_protocol.py index 685ec0179..d426e3259 100644 --- a/tst/unit/env/test_legacy_protocol.py +++ b/tst/unit/env/test_legacy_protocol.py @@ -2,14 +2,12 @@ from __future__ import annotations -import dataclasses from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest from agentenv_protocol import RPC_PATH, WELL_KNOWN_PATH, DataPart, uploaded_file_part from agentenv_protocol.client import GetDataResponse -from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.env import legacy_protocol from agent_env.env.env import DeployedSandboxEnv @@ -228,19 +226,6 @@ def test_card_servers_of_a_leaf_card_is_the_env_itself_and_a_composed_card_servi assert [s.environment_name for s in legacy_protocol.card_servers(driver, "https://d")] == ["desktop", "slack", "slack", "docs"] - -def test_a_computer_is_the_server_on_a_sandbox_of_its_own_offering_computer_exec_not_an_app_it_fronts(): - driver = {"name": "desktop", "url": RPC_PATH, - "capabilities": {"operations": ["data/get"], "extensions": [{"uri": COMPUTER_EXEC}]}, - "children_environments": [{"name": "notes", "url": "/apps/notes/agentenv", - "capabilities": {"extensions": []}}]} - record = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk") - listed = legacy_protocol.card_servers(driver, "https://d") - - assert [(s.environment_name, dataclasses.replace(s, record=record).is_computer) for s in listed] == [ - ("desktop", True), ("notes", False)] - assert not any(s.is_computer for s in listed) - def _record(card: dict | None, card_url: str | None = "https://env.example/.well-known/agent-env.json"): from agent_env.env.env import DeployedGatewayEnv diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 67c0c5cd2..a615101bc 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -1,11 +1,8 @@ """Unit tests for SyncEnvClockTaskStep — round-trip + the per-server sync_time fan-out (mocked).""" -import dataclasses import json from types import SimpleNamespace -from unittest.mock import patch import pytest -from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH @@ -121,6 +118,9 @@ async def test_execute_keeps_the_arm_failure_message(monkeypatch): @pytest.mark.asyncio async def test_execute_syncs_a_multi_envs_websites_alongside_its_mcp_servers(monkeypatch): + from types import SimpleNamespace + from unittest.mock import patch + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="shop"), SimpleNamespace(environment_name="blog")]) @@ -139,6 +139,8 @@ async def test_execute_syncs_a_multi_envs_websites_alongside_its_mcp_servers(mon @pytest.mark.asyncio async def test_execute_syncs_a_single_website_env(monkeypatch): + from unittest.mock import patch + from agent_env.env.envs.website import WebsiteEnv sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) @@ -167,6 +169,8 @@ async def fake_card(base_url, **kw): @pytest.mark.asyncio async def test_execute_syncs_a_website_sharing_an_mcp_servers_name_at_its_own_route(monkeypatch): """The card lists the two as children at distinct urls, so each is synced by its own card, with no card read.""" + from unittest.mock import patch + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="email")]) @@ -186,6 +190,7 @@ async def test_execute_syncs_a_website_sharing_an_mcp_servers_name_at_its_own_ro async def test_execute_without_a_card_url_syncs_the_servers_the_definition_names_read_live(monkeypatch): """An older record kept no card URL, so its servers come from its env definition and each card is read live at its gateway path.""" + from unittest.mock import patch import httpx @@ -224,6 +229,9 @@ async def invoke(uri, method, params=None, **kw): @pytest.mark.asyncio async def test_strict_execute_skips_websites_but_not_mcp_servers_that_do_not_follow_the_clock(monkeypatch): + from types import SimpleNamespace + from unittest.mock import patch + _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="shop"), SimpleNamespace(environment_name="legacy")]) @@ -272,6 +280,8 @@ def _cardless() -> DeployedEnv: def _carded(card: dict) -> DeployedEnv: + from agent_env.env.gateway.constants import WELL_KNOWN_PATH + return DeployedGatewayEnv(env_id="e1", env_version=1, gateway_url="http://gw", mcp_url="http://gw/mcp", db_web_url=None, sandbox_id="sb-1", environment_card_url=f"{_CARD}{WELL_KNOWN_PATH}", environment_card=card) @@ -292,20 +302,6 @@ def handle(request: httpx.Request) -> httpx.Response: return sent -_EXEC_EXT = {"uri": COMPUTER_EXEC, - "params": {"endpoint": "/agentenv/ext/computer-exec", "methods": {"run": {"method": "POST"}}}} -#: A multi env's computer ``desktop`` that offers computer-exec but no clock, as a disk guest's driver does. -_COMPUTER_WITHOUT_CLOCK = {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_EXEC_EXT]}} - - -def _with_computer(record: DeployedEnv, card: dict) -> DeployedEnv: - """``record``, a multi env's, with the computer ``desktop`` on a sandbox of its own whose card is ``card``.""" - computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", - environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", environment_card=card) - return dataclasses.replace(record, control_token="gateway-token", - child_envs={"desktop": dataclasses.asdict(computer)}) - - def _zoned(virtual_time="2026-01-01T12:00:00", timezone="America/New_York", **kw): return SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time=virtual_time, timezone=timezone, depends_on=[], **kw) @@ -416,6 +412,8 @@ async def test_a_server_that_does_not_advertise_clock_is_still_skipped_when_a_zo async def test_a_zoned_step_tells_a_website_that_takes_the_zone_and_fails_on_one_that_cannot(monkeypatch): """A website is tolerated for not following the clock, but one that follows it without taking the zone fails the step, as an MCP server does.""" + from types import SimpleNamespace + from unittest.mock import patch env = SimpleNamespace(mcp_server_envs=[], website_envs=[SimpleNamespace(environment_name="shop")]) sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) @@ -433,6 +431,9 @@ async def test_a_zoned_step_tells_a_website_that_takes_the_zone_and_fails_on_one @pytest.mark.asyncio async def test_a_website_sharing_an_mcp_servers_name_is_synced_with_the_envs_control_headers(monkeypatch): + import dataclasses + from unittest.mock import patch + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[SimpleNamespace(environment_name="email")]) @@ -451,10 +452,19 @@ async def test_a_website_sharing_an_mcp_servers_name_is_synced_with_the_envs_con @pytest.mark.asyncio async def test_a_multi_envs_computer_is_synced_at_its_own_address_with_its_own_control_token(monkeypatch): """Not through the gateway's /svc/desktop/, which carries the gateway's token, not the computer's.""" + import dataclasses + from unittest.mock import patch + + from agent_env.env.env import DeployedSandboxEnv + from agent_env.env.gateway.constants import WELL_KNOWN_PATH + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) - record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_CLOCK_EXT]})), - {"name": "desktop", "url": "/agentenv", "capabilities": {"extensions": [_CLOCK_EXT]}}) - computer = DeployedEnv.from_dict(record.child_envs["desktop"]) + computer = DeployedSandboxEnv(env_id="desk", env_version=1, sandbox_id="sb-desk", control_token="desk-token", + environment_card_url=f"https://desk.example{WELL_KNOWN_PATH}", + environment_card={"name": "desktop", "url": "/agentenv", + "capabilities": {"extensions": [_CLOCK_EXT]}}) + record = dataclasses.replace(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_CLOCK_EXT]})), + control_token="gateway-token", child_envs={"desktop": dataclasses.asdict(computer)}) env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) with patch("agent_env.env.env.Env.get", return_value=env): @@ -494,57 +504,3 @@ async def test_a_record_that_kept_no_card_is_refused_saying_so_not_told_to_deplo def test_a_padded_zone_is_stored_and_sent_stripped(): s = _zoned(timezone=" America/New_York ") assert s.timezone == "America/New_York" and s.to_dict()["timezone"] == "America/New_York" - - -@pytest.mark.asyncio -async def test_a_multi_envs_computer_that_offers_no_clock_is_skipped_as_tolerated_and_stays_on_real_time(monkeypatch): - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) - record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), - _COMPUTER_WITHOUT_CLOCK) - env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) - context = TaskStepContext(deployed_envs=[record]) - - with patch("agent_env.env.env.Env.get", return_value=env): - await _step().execute(context) - - configured = context.metadata["clock_configurations"][0] - assert [entry["service"] for entry in configured["synced"]] == ["email"] - assert [(entry["service"], entry["reason"]) for entry in configured["skipped"]] == [("desktop", "not_advertised")] - assert not [request for request in sent if request.url.host == "desk.example"] - - -@pytest.mark.asyncio -async def test_a_strict_arm_of_a_multi_env_whose_computer_offers_no_clock_is_refused_naming_it_and_what_to_deploy( - monkeypatch): - """As a computer booted from its disk is: its session would stay on real time while the universe moves.""" - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) - record = _with_computer(_carded(await _composed_card({"mcp-email": [_CLOCK_EXT], "desktop": [_EXEC_EXT]})), - _COMPUTER_WITHOUT_CLOCK) - env = SimpleNamespace(mcp_server_envs=[SimpleNamespace(environment_name="email")], website_envs=[]) - - with patch("agent_env.env.env.Env.get", return_value=env), pytest.raises( - StepContextError, match="computer 'desktop' can't follow the universe clock") as refused: - await _step(tolerate_missing_sync_time=False).execute(TaskStepContext(deployed_envs=[record])) - - assert "container form of a base that follows the clock" in str(refused.value) - assert "tolerate_missing_sync_time" in str(refused.value) - assert not [request for request in sent if request.url.host == "desk.example"] - - -@pytest.mark.asyncio -async def test_an_app_on_a_multi_envs_computer_that_offers_no_clock_is_skipped_since_it_runs_on_the_computers( - monkeypatch): - _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) - card = {"name": "desktop", "url": "/agentenv", - "capabilities": {"operations": ["data/get"], "extensions": [_CLOCK_EXT, _EXEC_EXT]}, - "children_environments": [{"name": "notes", "url": "/apps/notes/agentenv", - "capabilities": {"extensions": []}}]} - record = _with_computer(_carded(await _composed_card({"desktop": [_CLOCK_EXT, _EXEC_EXT]})), card) - context = TaskStepContext(deployed_envs=[record]) - - with patch("agent_env.env.env.Env.get", return_value=SimpleNamespace(mcp_server_envs=[], website_envs=[])): - await _step().execute(context) - - configured = context.metadata["clock_configurations"][0] - assert [entry["service"] for entry in configured["synced"]] == ["desktop"] - assert [(entry["service"], entry["reason"]) for entry in configured["skipped"]] == [("notes", "not_advertised")]