Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions modules/tool-computer-use/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,42 @@ transport remain local mechanisms. Fresh, bounded qualification is checked throu
`tests/fixtures/neutral-qualification.json` and its expected package bindings.
Retained historical evidence does not qualify neutral v1; expired or mismatched
current evidence fails the release consumer.

### macOS Edge media test fixtures

The local test launcher can call
`ComputerTool.bind_edge_media_fixture(process, profile, url)` in an already
active, disclosed control episode. Supply the launcher’s original Edge
`Popen`, private test profile directory, and exact loopback fixture URL. Bind
once while the dedicated browser has a single window. The returned run accepts
`press("mute")`, `press("unmute")`, `press("play")`, `press("pause")`,
`press("fullscreen")`, `press("exit_fullscreen")`, `press("volume_up")` and
`press("volume_down")` when Edge exposes the corresponding native control.

Each step waits up to 60 seconds for five seconds of quiet with the original
window in front. Activity postpones the step. The launcher retains responsibility
for the episode heartbeat and checking the resulting media state. Stop closes the
episode. An uncertain native acknowledgement retires the fixture binding.
For the visibility check, start with two fixture tabs in that same window and
pass the companion tab’s title as `companion_tab_title`. The run supports
`background_tab` and `restore_tab` only if Edge exposes both original tabs as
distinct accessibility elements. Browser keyboard zoom is unsupported by this
receiver. The media harness must report it as unrun.

A remote media test launcher can serve the same fixture on the regular runner
transport. In the target process that already owns the disposable Edge browser,
call `remote_agent.main(["--read-only=false"], edge_media_launcher=fixture)`.
The one-shot `fixture()` returns the launcher's original `process`, `profile`,
`url`, an optional `companion_tab_title` and a `check_binding` callback that
raises if the local test run has stopped. The caller keeps its existing Stop
and heartbeat handling active. No process, URL or window selector travels with
a media action.

On the sponsoring computer, await `ComputerTool.remote_edge_media_step("mute")`
in the active Mac episode. The caller checks the current write policy and the
target verifies the same episode and original fixture at each attempt. It
waits again only on a correlated reply that explicitly reports zero input.
A lost reply ends the step. An ordinary SSH worker with no fixture launcher
cannot adopt an existing browser window.

For the installed SSH runner, set `edge_media_url` to the loopback URL served by the Mac test harness. The runner opens a separate Edge profile without requesting activation when the first admitted step finds the Mac idle. The target pins the window and document. Discovery and read-only connections start no browser.
Original file line number Diff line number Diff line change
Expand Up @@ -2151,6 +2151,106 @@ def release():
# by actual calls. Hosts call the capability's heartbeat explicitly.
return result

def bind_edge_media_fixture(
self, process, profile, url, *, companion_tab_title=None
):
"""Bind native media controls for a local, already sponsored test launcher."""
from .edge_media import EdgeMediaRun, FixtureUnavailable, MacEdgeFixture

binding = self._binding
episode = self._episode
identity = self._episode_identity
if (
not self._episode_enabled
or episode is None
or identity is None
or binding.backend.name != "macos"
or binding.is_remote
or self._observed_control is not None
or binding.coexistence_guard is None
or binding.coexistence_guard.operator_presence_override is not None
):
raise FixtureUnavailable("fixture requires a local guarded Mac episode")

def check_binding():
if (
binding is not self._binding
or not binding.announced
or binding.announce_refused is not None
or binding.read_only
or binding.gate_writes
or self._cleanup_started
or self._episode_fenced_status is not None
or self._episode is not episode
or self._episode_identity != identity
or self._mouse_pending
or (binding.ledger is not None and binding.ledger.held_tokens)
):
raise FixtureUnavailable("fixture does not have an admitted write")
binding.coexistence_guard.check_sponsored_halt()
binding.coexistence_guard.pause.check()

check_binding()
fixture = MacEdgeFixture(process, profile, url, binding.backend)
if companion_tab_title is not None:
fixture.bind_companion_tab(companion_tab_title)
return EdgeMediaRun(episode, identity, check_binding, fixture)

async def remote_edge_media_step(self, control):
"""Dispatch a bounded step to the fixture owned by the target's launcher."""
from .edge_media import MEDIA_CONTROLS

if not isinstance(control, str) or control not in MEDIA_CONTROLS:
raise BackendError("unsupported window-bound Edge control")
binding = self._binding
identity = self._episode_identity
if (
not binding.is_remote
or binding.backend.presence_platform != "macos"
or not self._episode_enabled
or identity is None
or self._episode is not binding.backend
or self._observed_control is not None
or binding.coexistence_guard is None
):
raise BackendError("no sponsored remote Mac fixture")
binding.coexistence_guard.check_sponsored_halt()
binding.coexistence_guard.pause.check()
await asyncio.to_thread(self._ensure_announced)
binding = self._disclosed_binding(binding)
approval = await self._approve_write(
{"action": "edge_media_step", "control": control}, binding, True
)

def dispatch():
current = self._disclosed_binding(binding)
if (
not current.announced
or current.announce_refused is not None
or (current.gate_writes and approval is not self._write_approval)
or self._mouse_pending
or (current.ledger is not None and current.ledger.held_tokens)
or self._cleanup_started
or self._episode_fenced_status is not None
):
raise BackendError("remote fixture interrupted")
with self._episode_admission(
"edge_media_step", binding, episode=binding.backend, identity=identity
):
guard = binding.coexistence_guard
self._sync_remote_announcement_state(guard)
guard.check_sponsored_halt()
guard.pause.check()
return binding.backend.edge_media_step(identity, control)

deadline = time.monotonic() + 60
while time.monotonic() < deadline:
if await asyncio.to_thread(dispatch):
return
# The target acknowledged zero input. Check both ends again.
await asyncio.sleep(0.1)
raise TimeoutError("the Edge test window did not become ready")

def episode_status(self) -> dict:
if self._episode is None:
return {"state": "idle", "release_confirmed": False, "workers": 0}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -336,17 +336,21 @@ def release_target(self) -> None:
self.binding.release()

# -- start permission (D5, \u00a77.6) - governs BEGINNING to drive only ------
def check_sponsored_halt(self) -> None:
"""Observe sticky halts during a read-only wait for fixture input."""
self._poll_durable_halt()
if self._halted:
assert self._halt_snapshot is not None
self.release_all("halted")
raise HaltedError(self._halt_snapshot)

def check_start_permission(self) -> None:
"""Call once, before the first write of a session. Raises
`HaltedError` if a human is already detected AND `drive_anyway` is
False. This is the ONLY method `drive_anyway` affects - it never
reaches `before_event()`'s halt check. The separate finite operator
policy (\u00a76.0a) applies to START and continuing live classifications."""
self._poll_durable_halt()
if self._halted:
assert self._halt_snapshot is not None
self.release_all("halted")
raise HaltedError(self._halt_snapshot)
self.check_sponsored_halt()
overridden = self._presence_override_active()
if self.presence.state is PresenceState.HUMAN_ACTIVE and not (
self.drive_anyway or overridden
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
"""Start a disposable Edge window without activating it on the user's desktop."""

from __future__ import annotations

import logging
import math
import os
import shutil
import tempfile
import time
from pathlib import Path
from urllib.parse import urlsplit

from .edge_media import DocumentNotReady, FixtureUnavailable, MacEdgeFixture


def fixture_url(value: str) -> str:
parts = urlsplit(value)
if (
parts.scheme not in {"https", "http"}
or parts.hostname not in {"localhost", "127.0.0.1", "::1"}
or parts.username is not None
or parts.password is not None
or any(ord(char) < 32 for char in value)
):
raise ValueError("the Edge fixture needs a loopback HTTP URL")
return value


class EdgeApplication:
"""Hold the application instance returned by Launch Services for this launch."""

def __init__(self, profile, url):
from AppKit import (
NSWorkspace,
NSWorkspaceLaunchConfigurationArguments,
NSWorkspaceLaunchNewInstance,
NSWorkspaceLaunchWithoutActivation,
)

workspace = NSWorkspace.sharedWorkspace()
executable = workspace.URLForApplicationWithBundleIdentifier_(
"com.microsoft.edgemac"
)
existing = {app.processIdentifier() for app in workspace.runningApplications()}
if executable is None:
raise FixtureUnavailable("Microsoft Edge is unavailable")
self.args = [
f"--user-data-dir={profile}",
"--no-first-run",
"--no-default-browser-check",
"--force-renderer-accessibility",
url,
"data:text/html,<title>Edge%20media%20companion</title>",
]
self.app, error = workspace.launchApplicationAtURL_options_configuration_error_(
executable,
NSWorkspaceLaunchNewInstance | NSWorkspaceLaunchWithoutActivation,
{NSWorkspaceLaunchConfigurationArguments: self.args},
None,
)
if error or self.app is None:
raise FixtureUnavailable(f"Edge launch failed: {error}")
self.pid = self.app.processIdentifier()
if (
self.pid in existing
or self.app.bundleIdentifier() != "com.microsoft.edgemac"
):
raise FixtureUnavailable("Edge did not return a dedicated instance")

def poll(self):
return 0 if self.app.isTerminated() else None


class EdgeLauncher:
"""A single launch per remote worker. Startup and polling send no test input."""

def __init__(self, url, backend):
self.url = fixture_url(url)
self.backend = backend
self.profile = None
self.process = None
self.window = None
self.fixture = None
self.owned_browser = False

def __call__(self):
from . import macos_accessibility as ax

self.backend._ensure_not_locked()
idle = self.backend.presence_idle_ms()
if not math.isfinite(idle) or idle < 0:
raise FixtureUnavailable("Mac input activity is unavailable")
if idle < 5000:
return None
if self.process is None:
if self.profile is not None:
raise FixtureUnavailable("the previous Edge launch was interrupted")
self.profile = tempfile.mkdtemp(prefix="amplifier-edge-media-")
self.process = EdgeApplication(self.profile, self.url)
if self.process.poll() is not None:
raise FixtureUnavailable("the original Edge instance exited")
# Chromium holds a symlink ending in the browser PID in its profile.
# Require both the Launch Services instance and its private profile.
if not self.owns_profile():
if self.owned_browser:
raise FixtureUnavailable(
"the original Edge profile is no longer in use"
)
return None
self.owned_browser = True
root = ax.AXUIElementCreateApplication(self.process.pid)
error, windows = ax.AXUIElementCopyAttributeValue(root, "AXWindows", None)
if error or not windows:
if self.window is not None:
raise FixtureUnavailable("the original Edge window disappeared")
return None
if len(windows) != 1 or (self.window is not None and windows[0] != self.window):
raise FixtureUnavailable("the original Edge window changed")
self.window = windows[0]
# Wait for the local document in this exact window. A different URL or
# a partially loaded accessibility tree cannot receive a media action.
try:
if self.fixture is None:
self.fixture = MacEdgeFixture(
self.process,
self.profile,
self.url,
self.backend,
expected_window=self.window,
)
except DocumentNotReady:
return None
if not self.fixture.foreground():
return None
return {
"process": self.process,
"profile": self.profile,
"url": self.url,
"check_binding": self.check,
"window": self.fixture,
"companion_tab_title": "Edge media companion",
}

def owns_profile(self):
try:
owner = os.readlink(Path(self.profile) / "SingletonLock")
except OSError:
return False
return owner.rpartition("-")[2] == str(self.process.pid)

def check(self):
if (
self.process is None
or self.process.poll() is not None
or not self.owns_profile()
):
raise FixtureUnavailable("the original Edge instance exited")

def close(self):
if self.process is not None and self.process.poll() is None:
if not self.owns_profile():
logging.getLogger(__name__).warning(
"Edge profile ownership unconfirmed; retaining %s", self.profile
)
return
self.process.app.terminate()
deadline = time.monotonic() + 3
while self.process.poll() is None and time.monotonic() < deadline:
time.sleep(0.05)
if self.process.poll() is None:
logging.getLogger(__name__).warning(
"Edge is still exiting; retaining %s", self.profile
)
return
if self.profile is not None:
shutil.rmtree(Path(self.profile))
self.profile = None
Loading