diff --git a/agents/computer-operator.md b/agents/computer-operator.md index 257284b..6c81312 100644 --- a/agents/computer-operator.md +++ b/agents/computer-operator.md @@ -50,6 +50,12 @@ the capability is local-only. 3. **Look again.** Screenshot after anything that changes state, and confirm it did what you expected before continuing. 4. **Stop when the goal is met**, or when you are not sure — see Stop Conditions. +5. **Hand back control.** Where episode actions are supported, query + `desktop(action="episode_status")` and end that exact generation after the + bounded task, including an unsuccessful task. A trusted host wrapper may own + this boundary already. Do not call release confirmed while status is stopping, + interrupted, or release-unconfirmed; query an unknown reply without replaying + input. Do not begin a fresh episode to work around Stop or a retained halt. Coordinates are in the pixel space of the screenshot you were just given. They are scaled to the physical display for you; do not do your own scaling math. diff --git a/context/computer-use-awareness.md b/context/computer-use-awareness.md index 314aab8..1ef0d9d 100644 --- a/context/computer-use-awareness.md +++ b/context/computer-use-awareness.md @@ -18,6 +18,17 @@ when UI-use reports unavailable/unsupported controls, unstable observations, or needs recovery. If `ui_use` is absent, the ordinary computer operator remains the first-class path. Verify current state before recovery; never replay unknown input. +**Hand back control.** On supported Mac bindings the target activity panel stays +up across calls. End the bounded task with `desktop(action="episode_status")`, +then `desktop(action="end_episode", generation=)` unless +the host already owns that boundary. Report released only from confirmed release +status, separately from task success. Stopping, expiry, disconnect or helper loss +means pending/interrupted, never Done. A fresh explicit begin under current +authority requires zero workers, confirmed input release and settled indicator +custody; it never revives the old token, clears Stop/halts or retries input. +Do not auto-begin after interruption. Other platforms retain their disclosure behavior; +this episode is cooperative channel/agent ownership, not desktop-wide exclusion. + **Targeting.** `config.target` selects the mount target (unset is this machine; `ssh://user@host` is another). `desktop(action="retarget")` re-points an already-mounted session; `computer_use_unavailable(action="activate")` mounts tools when none are mounted. diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/__init__.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/__init__.py index 30a4819..6d1eb1c 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/__init__.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/__init__.py @@ -48,6 +48,13 @@ from .announce_macos import announce as macos_announce from .backend import Backend, BackendError, MonitorInfo from .coexistence_guard import CoexistenceGuard, HaltedError, OperatorPresenceOverride +from .episode import ( + Episode, + EpisodeError, + OverlayIndicator, + new_episode_generation, + settled_terminal, +) from .exclusion import Rect from .geometry import Display, ImageSpace, InvalidDisplayGeometryError, compute_display from .guard_diagnostics import ( @@ -100,9 +107,18 @@ _input_cancelled: contextvars.ContextVar[threading.Event | None] = ( contextvars.ContextVar("computer_input_cancelled", default=None) ) +_episode_cancelled = contextvars.ContextVar("computer_episode_cancelled", default=None) +_episode_scope = contextvars.ContextVar("computer_episode_scope", default=None) +_episode_registry_lock = threading.Lock() +_episode_registry: dict[str, Episode] = {} def _check_input_cancelled() -> None: + cancelled = _episode_cancelled.get() + if cancelled is not None and cancelled.is_set(): + raise BackendError( + "computer-use episode stopped; native outcome may be partial" + ) signal = _input_cancelled.get() if signal is not None and signal.is_set(): raise BackendError("request cancelled; no further input scheduled") @@ -435,6 +451,17 @@ def __init__(self, backend: Backend, config: dict[str, Any] | None = None) -> No # session previously wrote into together. See `execute()` and # `_prune_shots()`. self._session_id: str = uuid.uuid4().hex + self._episode_enabled = ( + False # enabled by the production builder, inert at mount + ) + self._episode_owner = self._session_id + self._episode = None + self._episode_identity = None + self._episode_lock = threading.RLock() + self._episode_heartbeat_stop = threading.Event() + self._episode_fenced_status = None + self._episode_worker_condition = threading.Condition() + self._episode_workers = 0 self._observed_control = None self._diagnostics = DiagnosticLog() # One-shot handoff to the hook's real tool:post call association. Only @@ -1290,6 +1317,7 @@ def _guard_write( guard.bind_target() guard.before_event(coord=coord) try: + _check_input_cancelled() if self._observed_control is not None: from .observed_control import check_observed_proof @@ -1610,6 +1638,18 @@ def retarget(self, target: str | None) -> ToolResult: target's remoteness, exactly like `__init__` does at mount. """ normalized = str(target).strip() if target else "" + if self._episode_enabled and self._episode_identity is not None: + result = self.end_episode() + if not settled_terminal(result) or self._episode_workers: + return ToolResult( + success=False, + error={ + "message": "retarget refused: old episode custody not settled", + "type": "RetargetRefused", + }, + ) + self._episode_identity = None + self._episode = None new_cfg = dict(self._cfg) if normalized and normalized != "local": new_cfg["target"] = normalized @@ -1925,6 +1965,12 @@ def retarget(self, target: str | None) -> ToolResult: remote_cancel_seen=False, ) old = self._binding + self._episode_enabled = ( + new_backend.name == "macos" + or getattr(new_backend, "presence_platform", None) == "macos" + or new_cfg.get("_indicator_factory") is not None + ) + self._episode_fenced_status = None # Step 7 (\u00a76.2): SWAP - the fix the review named: ONE atomic # reference assignment, never a field at a time. A reader can # only ever observe the OLD binding whole or the NEW binding @@ -1977,6 +2023,295 @@ def retarget(self, target: str | None) -> ToolResult: # this: it fires once, asks a human if needed, and builds the handle # this section re-raises/lowers. Nothing here can ask a human anything # or clear a sticky refusal. + def begin_episode(self, *, explicit=False) -> dict: + """Lazy task sponsorship. Owner is this mounted instance, never model input.""" + if not self._episode_enabled: + return { + "state": "unavailable", + "identity": None, + "reason": "platform_lifecycle_not_enabled", + "release_confirmed": False, + "indicator_settled": True, + "workers": 0, + } + with self._episode_lock: + scope = _episode_scope.get() + if scope is not None and scope[0] is self: + if ( + self._episode_identity is None + or scope[1] != self._episode_identity["generation"] + ): + raise BackendError("stale host episode scope") + if self._episode_fenced_status is not None: + raise BackendError("host episode scope fenced") + if self._cleanup_started: + raise BackendError("computer-use cleanup has started") + if self._episode_identity is not None: + status = self.episode_status() + if explicit and settled_terminal(status): + if ( + self._episode_workers + or self._mouse_pending + or ( + self._binding.ledger is not None + and self._binding.ledger.held_tokens + ) + ): + raise BackendError( + "prior episode still has controller input custody" + ) + if not self._binding.is_remote: + with _episode_registry_lock: + key = _channel_identity(self._binding.backend) + if _episode_registry.get(key) is self._episode: + del _episode_registry[key] + self._episode_identity = None + self._episode = None + self._episode_fenced_status = None + else: + if status["state"] not in {"viewing", "controlling"}: + raise BackendError( + "episode fenced; fresh explicit begin requires settled terminal custody" + ) + if self._binding.is_remote: + self._episode.heartbeat_episode(self._episode_identity) + else: + self._episode.heartbeat(self._episode_identity) + return status + binding = self._binding + identity = { + "owner": self._episode_owner, + "target": ( + binding.backend.episode_target + if binding.is_remote + else binding.diagnostic_id + ), + "generation": new_episode_generation(), + } + if binding.is_remote: + self._episode = binding.backend + self._episode_identity = identity + result = binding.backend.begin_episode(identity) + else: + key = _channel_identity(binding.backend) + with _episode_registry_lock: + existing = _episode_registry.get(key) + if existing is not None: + raise BackendError( + "another controller owns this channel episode" + ) + if binding.ledger is not None and binding.ledger.held_tokens: + raise BackendError( + "existing channel held-input custody must settle first" + ) + + def indicator(): + factory = self._cfg.get("_indicator_factory") + if factory: + return factory() + if binding.backend.name == "macos": + from .macos_indicator import MacOSIndicator + + return MacOSIndicator() + return OverlayIndicator(binding.announcement) + + def release(): + if binding.ledger is not None: + binding.ledger.release_all(reason="episode_end") + return not self._mouse_pending and not ( + binding.ledger is not None and binding.ledger.held_tokens + ) + + episode = Episode( + identity["target"], indicator, release, lease_seconds=120 + ) + _episode_registry[key] = episode + self._episode = episode + # Publish startup custody before a blocking helper start; + # cleanup/Stop must be able to fence this pending generation. + self._episode_identity = identity + try: + result = episode.begin(identity) + if self._cleanup_started: + episode.fence(identity, reason="cleanup_during_start") + raise BackendError("cleanup overtook episode startup") + except BaseException: + # Failed start stays fenced, with cleanup custody retained. + self._episode_identity = identity + raise + self._episode_identity = identity + # Renewal belongs to a live bounded sponsor, not a mounted process. + # Direct clients get a finite 120s reasoning-gap lease renewed only + # by actual calls. Hosts call the capability's heartbeat explicitly. + return result + + def episode_status(self) -> dict: + if self._episode is None: + return {"state": "idle", "release_confirmed": False, "workers": 0} + if self._binding.is_remote: + return self._own_episode_status( + self._episode.episode_status(self._episode_identity) + ) + return self._episode.status(self._episode_identity) + + def _own_episode_status(self, status: dict) -> dict: + if status.get("target_adopted") is False and ( + self._episode_workers or self._mouse_pending + ): + return { + **status, + "reason": "controller_input_custody_pending", + "controller_workers": self._episode_workers, + "release_confirmed": False, + } + return status + + def end_episode(self, generation: str | None = None, *, interrupted=False) -> dict: + # Fence BEFORE waiting for any sponsorship/status/native lock. Another + # call may hold _episode_lock while waiting for a remote status reply. + identity = self._episode_identity + if identity is not None: + if generation is not None and generation != identity["generation"]: + raise BackendError("stale episode generation") + self.fence_episode(identity["generation"], interrupted=interrupted) + with self._episode_lock: + if identity is None: + identity = self._episode_identity + if identity is None: + return self.episode_status() + self.fence_episode(identity["generation"], interrupted=interrupted) + if self._episode_identity != identity: + raise BackendError("stale episode generation") + if generation is not None and generation != identity["generation"]: + raise BackendError("stale episode generation") + self._episode_heartbeat_stop.set() + if self._binding.is_remote: + deadline = time.monotonic() + 5 + with self._episode_worker_condition: + while self._episode_workers: + remaining = deadline - time.monotonic() + if remaining <= 0: + return { + "identity": dict(identity), + "state": "stopping", + "reason": "controller_workers_pending", + "workers": self._episode_workers, + "admission_open": False, + "release_confirmed": False, + "indicator_settled": False, + } + self._episode_worker_condition.wait(remaining) + result = self._episode.end_episode(identity, interrupted=interrupted) + if result.get("target_adopted") is False: + # A target no-adoption receipt cannot erase an unrelated + # controller obligation or authorize a synthetic mouse-up. + result = self._own_episode_status(result) + self._episode_fenced_status = result + return result + if ( + result.get("identity") == identity + and result.get("release_confirmed") is True + and result.get("workers") == 0 + ): + # The target already emitted owned ups. Do not replay them + # through a now-fenced backend; retire only our own boxes. + for token in list(self._mouse_pending): + if self._binding.ledger is not None: + self._binding.ledger.acknowledge_release(token) + self._mouse_pending.pop(token, None) + self._episode_fenced_status = result + else: + self._episode.fence(identity, interrupted=interrupted) + result = self._episode.close(identity) + if settled_terminal(result) and not self._binding.is_remote: + with _episode_registry_lock: + key = _channel_identity(self._binding.backend) + if _episode_registry.get(key) is self._episode: + del _episode_registry[key] + # Keep terminal identity until a deliberate new begin. + return result + + def fence_episode(self, generation: str, *, interrupted=True) -> dict: + identity = self._episode_identity + if identity is None or generation != identity["generation"]: + raise BackendError("wrong or stale episode generation") + self._episode_heartbeat_stop.set() + if self._binding.is_remote: + # Close controller admission synchronously. Target custody notice + # does not wait for the response lock or a native worker. + self._episode.fence_episode_local(identity, interrupted=interrupted) + episode = self._episode + + def notify(): + try: + episode.revoke_episode(identity, interrupted=interrupted) + except Exception: + logger.warning( + "episode revoke reply unconfirmed; target lease remains fenced on expiry" + ) + + threading.Thread(target=notify, daemon=True).start() + self._episode_fenced_status = { + "identity": dict(identity), + "state": "interrupted" if interrupted else "stopping", + "release_confirmed": False, + "workers": None, + "admission_open": False, + } + return dict(self._episode_fenced_status) + self._episode.fence(identity, interrupted=interrupted) + self._episode_fenced_status = self._episode.status(identity) + return dict(self._episode_fenced_status) + + @contextmanager + def _episode_admission( + self, action: str, binding: _Binding, *, episode=None, identity=None + ): + if not self._episode_enabled: + yield + return + identity = identity if identity is not None else self._episode_identity + episode = episode if episode is not None else self._episode + if ( + identity is None + or identity != self._episode_identity + or episode is not self._episode + ): + raise BackendError("no sponsored computer-use episode") + scope = _episode_scope.get() + if ( + scope is not None + and scope[0] is self + and scope[1] != identity["generation"] + ): + raise BackendError("stale host episode scope") + try: + if binding.is_remote: + # Remote final admission is on the target; controller still + # owns the complete worker, including late custody registration + # after the target has replied to native input. + with self._episode_worker_condition: + binding.backend.check_episode(identity) + self._episode_workers += 1 + try: + yield + finally: + with self._episode_worker_condition: + self._episode_workers -= 1 + self._episode_worker_condition.notify_all() + else: + with episode.admit( + identity, + controlling=action in MUTATING or action in MUTATING_DESKTOP, + ) as cancelled: + token = _episode_cancelled.set(cancelled) + try: + yield + finally: + _episode_cancelled.reset(token) + except EpisodeError as exc: + raise BackendError(str(exc)) from exc + def _live_band_handle(self) -> Any | None: """This session's announcement handle, narrowed to one that supports live re-raise/lower (`show()`/`hide()`) - the Linux/Windows overlay. @@ -2070,6 +2405,8 @@ def _band_exit(self, token: tuple[Any, _ChannelBandState] | None) -> None: with state.lock: state.depth -= 1 depth_now = state.depth + if self._episode_enabled and self._episode_identity is not None: + return # Episode, not an empty queue, owns persistent indication. if depth_now != 0: return ledger = self._ledger @@ -2773,6 +3110,7 @@ async def _approve_write( async def execute(self, input: dict[str, Any]) -> ToolResult: """Run a flat canonical call or one fully prevalidated v1 batch.""" + invocation_episode = self._episode_identity if self._cleanup_started: return ToolResult( success=False, @@ -2828,6 +3166,15 @@ async def execute(self, input: dict[str, Any]) -> ToolResult: ) try: await asyncio.to_thread(self._ensure_announced) + pinned_episode, pinned_identity = None, None + if self._episode_enabled: + if ( + invocation_episode is not None + and invocation_episode != self._episode_identity + ): + raise BackendError("queued invocation belongs to a stale episode") + sponsored = await asyncio.to_thread(self.begin_episode) + pinned_episode, pinned_identity = self._episode, sponsored["identity"] except asyncio.CancelledError: if not batch: raise @@ -2850,6 +3197,10 @@ async def execute(self, input: dict[str, Any]) -> ToolResult: success=False, error={"message": str(exc), "type": "AnnouncementRefused"}, ) + except (BackendError, EpisodeError) as exc: + return ToolResult( + success=False, error={"message": str(exc), "type": type(exc).__name__} + ) try: binding = self._disclosed_binding(binding) except BackendError as exc: @@ -2896,6 +3247,8 @@ async def execute(self, input: dict[str, Any]) -> ToolResult: "running": False, "cleanup": None, "cancelled": threading.Event(), + "episode": pinned_episode, + "episode_identity": pinned_identity, } result = None captures: list = [] @@ -3047,6 +3400,7 @@ def _check_write( raise BackendError("computer-use session cleanup has started") if self._binding is not binding: raise BackendError("request stopped: target or policy changed") + _check_input_cancelled() if action in MUTATING or action in MUTATING_DESKTOP: if binding.read_only: raise BackendError("write blocked: computer-use is mounted read_only") @@ -3071,7 +3425,13 @@ def _run_owned_step( self._diagnostics, binding, self._diagnostics.identity ): _check_input_cancelled() - outcome = function(*args) + with self._episode_admission( + action, + binding, + episode=flight.get("episode"), + identity=flight.get("episode_identity"), + ): + outcome = function(*args) with flight["lock"]: flight["outcome"] = outcome return outcome @@ -3448,6 +3808,9 @@ def _persist_screenshot_result( # leave. "retarget", "diagnostic_snapshot", + "begin_episode", + "end_episode", + "episode_status", ] #: Clipboard *reads* travel to the model provider as tool output (see README Safety @@ -3561,6 +3924,9 @@ def description(self) -> str: f"session controls is fixed for the whole session, not chosen per call: {_TARGET_MODEL}" " Use `diagnostic_snapshot` for bounded cached, payload-free guard evidence; " "it never contacts the target, samples presence, or clears a halt." + " Computer use lazily begins an owner-bound episode which persists between " + "actions. Call end_episode when the bounded task ends; inspect episode_status " + "after an unknown reply, never replay input. Release is distinct from task success." ) @property @@ -3569,6 +3935,10 @@ def input_schema(self) -> dict[str, Any]: "type": "object", "properties": { "action": {"type": "string", "enum": DESKTOP_ACTIONS}, + "generation": { + "type": "string", + "description": "Exact episode generation for end_episode, from episode_status.", + }, "handle": { "type": "string", "description": "Window handle from list_windows (focus_window).", @@ -3601,6 +3971,32 @@ def input_schema(self) -> dict[str, Any]: } async def execute(self, input: dict[str, Any]) -> ToolResult: + invocation_episode = self._computer._episode_identity + if isinstance(input, dict) and input.get("action") in { + "end_episode", + "episode_status", + }: + try: + if input["action"] == "end_episode": + if set(input) - {"action", "generation"}: + raise ValueError("end_episode accepts only generation") + if not isinstance(input.get("generation"), str): + raise ValueError( + "end_episode requires exact generation from episode_status" + ) + result = await asyncio.to_thread( + self._computer.end_episode, input.get("generation") + ) + else: + if set(input) != {"action"}: + raise ValueError("episode_status accepts only action") + result = await asyncio.to_thread(self._computer.episode_status) + return ToolResult(success=True, output=result) + except Exception as exc: + return ToolResult( + success=False, + error={"message": str(exc), "type": type(exc).__name__}, + ) # Pure cached diagnostics are available even while halted or after # cleanup. Do not approve, disclose, poll, copy arbitrary input fields, # touch the backend, or wait for _announce_lock on this route. @@ -3631,6 +4027,10 @@ async def execute(self, input: dict[str, Any]) -> ToolResult: success=False, error={"message": f"unknown action {action!r}"} ) input["action"] = action + if action == "begin_episode" and not self._computer._episode_enabled: + return ToolResult( + success=True, output=self._computer.begin_episode(explicit=True) + ) binding = self._computer._binding try: if action == "focus_window" and ( @@ -3710,11 +4110,32 @@ async def execute(self, input: dict[str, Any]) -> ToolResult: # ones that happen to share `_run()` with `computer`. try: await asyncio.to_thread(self._computer._ensure_announced) + pinned_episode, pinned_identity = None, None + if self._computer._episode_enabled or action == "begin_episode": + if ( + action != "begin_episode" + and invocation_episode is not None + and (invocation_episode != self._computer._episode_identity) + ): + raise BackendError("queued invocation belongs to a stale episode") + sponsored = await asyncio.to_thread( + self._computer.begin_episode, explicit=action == "begin_episode" + ) + pinned_episode, pinned_identity = ( + self._computer._episode, + sponsored["identity"], + ) + if action == "begin_episode": + return ToolResult(success=True, output=sponsored) except AnnouncementRefused as exc: return ToolResult( success=False, error={"message": str(exc), "type": "AnnouncementRefused"}, ) + except (BackendError, EpisodeError) as exc: + return ToolResult( + success=False, error={"message": str(exc), "type": type(exc).__name__} + ) try: binding = self._computer._disclosed_binding(binding) except BackendError as exc: @@ -3728,19 +4149,43 @@ async def execute(self, input: dict[str, Any]) -> ToolResult: # action would, and is what closes F9 (desktop actions bypassing # the counter). try: - band_token = await asyncio.to_thread(self._computer._band_enter) + band_token = await self._computer._acquire_batch_band() except AnnouncementRefused as exc: return ToolResult( success=False, error={"message": str(exc), "type": "AnnouncementRefused"}, ) + flight = { + "lock": threading.Lock(), + "running": False, + "cleanup": None, + "cancelled": threading.Event(), + "episode": pinned_episode, + "episode_identity": pinned_identity, + } try: - return await self._execute_action(input, binding=binding, approved=approved) + return await self._execute_action( + input, binding=binding, approved=approved, flight=flight + ) finally: - await asyncio.to_thread(self._computer._band_exit, band_token) + with flight["lock"]: + deferred = flight["running"] + if deferred: + flight["cleanup"] = lambda: self._computer._band_exit(band_token) + if not deferred: + await asyncio.shield( + self._computer._submit_batch_thread( + self._computer._band_exit, band_token + ) + ) async def _execute_action( - self, input: dict[str, Any], *, binding: _Binding, approved: Callable | None + self, + input: dict[str, Any], + *, + binding: _Binding, + approved: Callable | None, + flight: dict, ) -> ToolResult: """The actual per-action dispatch, unchanged from before band- lifetime tracking existed - split out of `execute()` only so that @@ -3761,6 +4206,11 @@ async def _execute_action( ) backend = binding.backend + async def owned(function, *args): + return await self._computer._await_owned_step( + action, binding, flight, function, *args + ) + def checked_call(function, *args): # Direct desktop reads/monitor changes do not use _run_flat_step. # Check and invoke in one worker-held lock, like canonical actions. @@ -3786,7 +4236,7 @@ def checked_call(function, *args): "clipboard_read_policy=block" }, ) - output = await asyncio.to_thread(checked_call, backend.get_clipboard) + output = await owned(checked_call, backend.get_clipboard) digest = _text_digest(output) logger.info( "computer-use audit: op=get_clipboard policy=%s chars=%d sha256=%s", @@ -3818,7 +4268,7 @@ def set_clipboard(): with self._computer._guard_write(binding=binding): backend.set_clipboard(body) - await asyncio.to_thread(set_clipboard) + await owned(set_clipboard) # §3 audit hardening: digest, never plaintext - the same # discipline `type` uses, since clipboard content is exactly # the kind of thing that "frequently includes credentials." @@ -3829,9 +4279,7 @@ def set_clipboard(): ) return ToolResult(success=True, output="clipboard set") if action == "list_monitors": - monitors = await asyncio.to_thread( - checked_call, self._computer.list_monitors - ) + monitors = await owned(checked_call, self._computer.list_monitors) current = self._computer.current_monitor lines = [ f" [{m.id}] {m.width}x{m.height} at ({m.x},{m.y})" @@ -3848,9 +4296,7 @@ def set_clipboard(): target = str(input.get("monitor") or "").strip() if not target: raise ValueError("action 'select_monitor' requires 'monitor'") - disp = await asyncio.to_thread( - checked_call, self._computer.select_monitor, target - ) + disp = await owned(checked_call, self._computer.select_monitor, target) return ToolResult( success=True, output=( @@ -3860,7 +4306,7 @@ def set_clipboard(): f"{disp.model_width}x{disp.model_height}" ), ) - summary, _ = await asyncio.to_thread( + summary, _ = await owned( self._computer._run_flat_step, action, input, binding, approved ) return ToolResult(success=True, output=summary) @@ -5342,6 +5788,11 @@ def _select_and_build(cfg: dict[str, Any]) -> ComputerTool: backend = select_backend(cfg) try: computer = ComputerTool(backend, cfg) + computer._episode_enabled = ( + backend.name == "macos" + or getattr(backend, "presence_platform", None) == "macos" + or cfg.get("_indicator_factory") is not None + ) # D2: resolve display once, here, before the tool ever answers a provider # request - not lazily on the first `native_tool_spec` read. try: @@ -5364,7 +5815,7 @@ def _select_and_build(cfg: dict[str, Any]) -> ComputerTool: # (same population as before this feature existed: no coexistence # layer at all). Computed from the SAME backend `_build_coexistence_guard` # was just given, so `_channel_identity` returns the identical key. - if computer._coexistence_guard is not None: + if computer._coexistence_guard is not None or computer._episode_enabled: computer._channel_key = _channel_identity(backend) computer._ledger = _get_channel_ledger(computer._channel_key) computer._band_state = _get_channel_band_state(computer._channel_key) @@ -5394,6 +5845,92 @@ def _select_and_build(cfg: dict[str, Any]) -> ComputerTool: raise +class EpisodeController: + """Public cooperative host seam; callbacks carry exact captured generation. + + A host supplies a bounded task lifetime and calls heartbeat only while that + sponsor is live. No hook name or model-supplied owner establishes authority. + """ + + def __init__(self, computer): + self.computer = computer + + async def begin(self) -> dict: + if not self.computer._episode_enabled: + return { + "state": "unavailable", + "reason": "platform_lifecycle_not_enabled", + "release_confirmed": False, + "workers": 0, + "identity": None, + } + await asyncio.to_thread(self.computer._ensure_announced) + return await asyncio.to_thread(self.computer.begin_episode, explicit=True) + + def _identity(self, generation): + identity = self.computer._episode_identity + if identity is None or identity["generation"] != generation: + raise BackendError("wrong or stale episode generation") + return identity + + @contextmanager + def bind(self, generation: str): + """Bind all nested calls/worker contexts to this exact host generation.""" + self._identity(generation) + token = _episode_scope.set((self.computer, generation)) + try: + yield + finally: + _episode_scope.reset(token) + + def fence(self, generation: str, *, interrupted=True) -> dict: + self._identity(generation) + return self.computer.fence_episode(generation, interrupted=interrupted) + + async def heartbeat(self, generation: str) -> None: + identity = self._identity(generation) + episode = self.computer._episode + if self.computer._binding.is_remote: + await asyncio.to_thread(episode.heartbeat_episode, identity) + else: + episode.heartbeat(identity) + + async def end(self, generation: str, *, interrupted=False) -> dict: + self._identity(generation) + # Fence before moving any settlement offloop. Cancellation of the + # awaiting host does not reopen admission or imply native drain. + self.fence(generation, interrupted=interrupted) + return await asyncio.shield( + self.computer._submit_batch_thread( + lambda: self.computer.end_episode(generation, interrupted=interrupted) + ) + ) + + async def status(self, generation: str | None = None) -> dict: + if generation is not None: + self._identity(generation) + return await asyncio.to_thread(self.computer.episode_status) + + def cached_status(self) -> dict: + episode = self.computer._episode + if episode is not None and not self.computer._binding.is_remote: + return episode.status() + if self.computer._episode_fenced_status is not None: + return dict(self.computer._episode_fenced_status) + if episode is None: + return { + "state": "idle", + "identity": None, + "workers": 0, + "release_confirmed": False, + } + if self.computer._binding.is_remote: + return self.computer._own_episode_status( + copy.deepcopy(episode._episode_status_cache) + ) + return episode.status() + + class _MountResult(dict): """Keep direct-call metadata while satisfying Core's cleanup-callable contract. @@ -5423,11 +5960,47 @@ async def _mount_backend(coordinator: Any, cfg: dict[str, Any]) -> dict[str, Any (`mount()`) or a `ToolResult` (`_activate`). """ computer = await asyncio.to_thread(_select_and_build, cfg) + # Bind owner to coordinator runtime identity plus this mount; event payload + # session_id and model arguments cannot choose another owner. + runtime_owner = getattr(coordinator, "session_id", None) + if isinstance(runtime_owner, str): + computer._episode_owner = hashlib.sha256( + (runtime_owner + ":" + computer._session_id).encode() + ).hexdigest() + episodes = EpisodeController(computer) + register_capability = getattr(coordinator, "register_capability", None) + get_capability = getattr(coordinator, "get_capability", None) + previous_episodes = ( + get_capability("computer_use.episodes") if callable(get_capability) else None + ) + if callable(register_capability): + register_capability("computer_use.episodes", episodes) closed = False close_error: BaseException | None = None def close_current_binding() -> None: nonlocal closed, close_error + # Close startup admission before inspecting pending generation custody. + # Legacy non-episode cleanup keeps its existing held-input retry path. + if computer._episode_enabled: + computer._cleanup_started = True + identity = computer._episode_identity + if identity is not None: + computer.fence_episode(identity["generation"], interrupted=True) + # If cleanup overtook allocation, await that startup owner's + # finally before deciding whether any helper custody exists. + with computer._episode_lock: + pass + if computer._episode_identity is not None: + result = computer.end_episode(interrupted=True) + if ( + result["workers"] + or not result["release_confirmed"] + or result.get("indicator_settled") is not True + ): + raise RuntimeError( + "computer-use cleanup pending: episode release or indicator settlement unconfirmed" + ) with computer._announce_lock: if close_error is not None: raise close_error @@ -5470,6 +6043,12 @@ def close_current_binding() -> None: async def cleanup() -> None: await asyncio.to_thread(close_current_binding) + if ( + callable(register_capability) + and callable(get_capability) + and (get_capability("computer_use.episodes") is episodes) + ): + register_capability("computer_use.episodes", previous_episodes) if cfg.get("observed_control") is True: from .observed_control import ObservedControl diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/episode.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/episode.py new file mode 100644 index 0000000..ae2cb22 --- /dev/null +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/episode.py @@ -0,0 +1,410 @@ +"""Owner-bound activity custody, not a claim of desktop-wide exclusion. + +Admission and fencing use a lock never held across native work. A cancelled +awaiter is not a drained worker. Expiry and indicator failure are irreversible +interruptions; neither is a successful hand-back. Renderers only display state. +""" + +from __future__ import annotations + +import itertools +import re +import threading +import time +import uuid +from collections.abc import Callable +from contextlib import contextmanager +from typing import Any + + +class EpisodeError(RuntimeError): + pass + + +_generations = itertools.count(1) + + +def new_episode_generation() -> str: + """Opaque to hosts; ordered across mounts sharing this process's transport.""" + return f"{next(_generations):016x}-{uuid.uuid4().hex}" + + +def episode_order(generation: str) -> int: + if not isinstance(generation, str) or not re.fullmatch( + r"[0-9a-f]{16}-[0-9a-f]{32}", generation + ): + raise EpisodeError("invalid ordered episode generation") + return int(generation[:16], 16) + + +def settled_terminal(status: dict) -> bool: + """Fresh explicit work is allowed only after all prior custody is settled.""" + return ( + status.get("state") in {"released", "interrupted"} + and status.get("workers") == 0 + and status.get("admission_open") is False + and status.get("release_confirmed") is True + and status.get("indicator_settled") is True + ) + + +class Episode: + """One channel/agent's cooperative arbiter. No permission is conveyed here.""" + + def __init__( + self, + target: str, + indicator_factory: Callable, + release: Callable[[], bool], + *, + lease_seconds: float = 10.0, + clock: Callable = time.monotonic, + ): + self.target = target + self._factory = indicator_factory + self._release = release + self._lease = lease_seconds + self._clock = clock + self._condition = threading.Condition(threading.RLock()) + self._transition = threading.Lock() + self._render_lock = threading.Lock() + self._identity = None + self._indicator = None + self._state = "idle" + self._reason = None + self._deadline = 0.0 + self._workers = 0 + self._cancelled = threading.Event() + self._confirmed = False + self._release_failed = False + self._watch = None + self._closed = False + + def _match(self, identity): + if identity != self._identity or not isinstance(identity, dict): + raise EpisodeError("wrong or stale episode owner/target/generation") + + def begin(self, identity: dict, mode: str = "viewing") -> dict: + if ( + not isinstance(identity, dict) + or set(identity) != {"owner", "target", "generation"} + or identity["target"] != self.target + or any( + not isinstance(v, str) or not v or len(v) > 128 + for v in identity.values() + ) + or mode not in {"viewing", "controlling"} + ): + raise EpisodeError("invalid episode identity or mode") + with self._transition: + with self._condition: + if self._identity is not None: + self._match(identity) + if self._state not in {"viewing", "controlling"}: + raise EpisodeError( + "episode fenced; explicit new generation required" + ) + return self.status(identity) + self._identity = dict(identity) + self._state = "starting" + self._deadline = self._clock() + self._lease + try: + self._indicator = self._factory() + ready = self._indicator.start(state=mode) + if not all( + ready.get(k) is True for k in ("available", "ready", "healthy") + ): + raise EpisodeError("target activity indicator not ready") + with self._condition: + if self._state != "starting": + raise EpisodeError("episode revoked during indicator startup") + self._state = mode + self._watch = threading.Thread(target=self._watchdog, daemon=True) + self._watch.start() + except BaseException: + self.fence(identity, reason="indicator_unavailable") + raise + return self.status(identity) + + def heartbeat(self, identity) -> dict: + with self._condition: + self._match(identity) + self._check_locked() + self._deadline = self._clock() + self._lease + return self.status(identity) + + def _healthy(self): + try: + return self._indicator is not None and all( + self._indicator.status().get(k) is True + for k in ("available", "ready", "healthy") + ) + except Exception: + return False + + def _check_locked(self): + if self._state not in {"viewing", "controlling"}: + raise EpisodeError("episode is fenced") + if self._clock() >= self._deadline or not self._healthy(): + self._state = "interrupted" + self._reason = "expired_or_indicator_lost" + self._cancelled.set() + self._condition.notify_all() + raise EpisodeError("episode expired or target indicator lost") + + @contextmanager + def admit(self, identity, *, controlling: bool = False): + # Upgrade before admission, never after the input it discloses. + with self._transition: + with self._condition: + self._match(identity) + self._check_locked() + upgrade = controlling and self._state == "viewing" + if upgrade: + try: + result = self._indicator.update("controlling") + ready = all(result.get(k) is True for k in ("ready", "healthy")) + except Exception: + ready = False + if not ready: + self.fence(identity, reason="indicator_lost") + raise EpisodeError("target indicator update unconfirmed") + with self._condition: + self._check_locked() + if upgrade: + self._state = "controlling" + self._workers += 1 + try: + yield self._cancelled + finally: + with self._condition: + self._workers -= 1 + self._condition.notify_all() + + def fence(self, identity, *, reason: str = "stopping", interrupted: bool = True): + """Close admission immediately; never wait for a native worker here.""" + with self._condition: + if ( + self._identity is None + and isinstance(identity, dict) + and (identity.get("target") == self.target) + ): + # Cleanup/Stop can overtake the scheduled startup worker. + self._identity = dict(identity) + self._state = "interrupted" + self._match(identity) + if self._state == "released" or self._closed: + return + if self._state in {"viewing", "controlling"}: + try: + self._check_locked() + except EpisodeError: + interrupted = True + self._state = ( + "interrupted" + if interrupted or self._state == "interrupted" + else "stopping" + ) + self._reason = reason + self._cancelled.set() + self._condition.notify_all() + threading.Thread(target=self._display, args=(self._state,), daemon=True).start() + + def end(self, identity, *, timeout: float = 5.0) -> dict: + with self._condition: + self._match(identity) + if self._state == "released" or self._closed: + return self.status(identity) + interrupted = self._state == "interrupted" + self.fence(identity, interrupted=interrupted) + with self._transition: + with self._condition: + if self._closed: + return self.status(identity) + self._display("interrupted" if interrupted else "stopping") + deadline = time.monotonic() + timeout + with self._condition: + while self._workers: + remaining = deadline - time.monotonic() + if remaining <= 0: + self._reason = "native_workers_pending" + return self.status(identity) + self._condition.wait(remaining) + # No new worker can enter. Reconcile only this arbiter's custody. + try: + confirmed = self._release() is True + except Exception: + confirmed = False + with self._condition: + self._confirmed = confirmed + if not confirmed: + self._release_failed = True + self._state = "interrupted" + self._reason = "release_unconfirmed" + elif ( + not self._release_failed + and self._state != "interrupted" + and self._healthy() + ): + self._state = "released" + self._reason = None + else: + self._state = "interrupted" + self._reason = self._reason or "indicator_lost" + state = self._state + self._display(state) + return self.status(identity) + + def _display(self, state): + with self._render_lock: + with self._condition: + if state != self._state: + return # A delayed stopping update cannot overwrite released. + self._display_locked(state) + + def _display_locked(self, state): + if self._indicator is not None: + try: + result = self._indicator.update(state) + if result.get("healthy") is not True and state == "released": + with self._condition: + self._state = "interrupted" + self._reason = "terminal_ack_unconfirmed" + except Exception: + # Release may be physically confirmed, but the terminal display + # acknowledgement is unknown. Do not manufacture a released label. + with self._condition: + self._state = "interrupted" + self._reason = "indicator_update_unconfirmed" + + def status(self, identity=None) -> dict[str, Any]: + with self._condition: + if identity is not None: + self._match(identity) + if self._state in {"viewing", "controlling"}: + try: + self._check_locked() + except EpisodeError: + pass + return { + "identity": dict(self._identity) if self._identity else None, + "state": self._state, + "reason": self._reason, + "workers": self._workers, + "admission_open": self._state in {"viewing", "controlling"}, + "release_confirmed": self._confirmed, + "indicator_settled": self._closed, + "scope": "cooperative_channel_agent_not_desktop_wide", + } + + def close(self, identity) -> dict: + result = self.end(identity) + if result["workers"] or not result["release_confirmed"]: + return result + # Linearize custody retirement with every already-entered end/drain. + # An old waiter must observe _closed under this same transition before + # it can invoke the channel's release callback against a new owner. + with self._transition: + return self._settle_indicator(identity, result) + + def _settle_indicator(self, identity, result): + with self._render_lock: + if self._indicator is None: + self._closed = True # Start was fenced before allocating a helper. + if self._indicator is not None and not self._closed: + closed = self._indicator.close() + # Normal helper closure is intentionally unhealthy (no live + # surface), so use explicit absence/exit evidence, not liveness. + settled = ( + closed.get("closed") is True + and closed.get("surface_absent") is True + and closed.get("process_settled") is True + and closed.get("helper_exit") + == (0 if result["state"] == "released" else 2) + ) + fault_settled = ( + closed.get("fault_settled") is True + and closed.get("state") == "interrupted" + and closed.get("healthy") is False + and closed.get("process_settled") is True + and ( + ( + closed.get("settlement_basis") == "never_launched" + and closed.get("helper_exit") is None + ) + or ( + closed.get("settlement_basis") == "helper_reaped" + and type(closed.get("helper_exit")) is int + ) + ) + ) + if fault_settled: + # Dedicated renderer-resource custody only. Input release + # was checked above; retain failure, never relabel as Done + # or invent the native surface-absence acknowledgement. + with self._condition: + self._state = "interrupted" + self._reason = closed.get("reason") or "indicator_failed" + self._closed = True + elif not settled: + with self._condition: + self._state = "interrupted" + self._reason = "indicator_close_unconfirmed" + else: + self._closed = True + return self.status(identity) + + def _watchdog(self): + while True: + time.sleep(min(0.25, self._lease / 4)) + with self._condition: + if self._state not in {"viewing", "controlling"}: + interrupted = self._state == "interrupted" + break + try: + self._check_locked() + except EpisodeError: + interrupted = True + break + if interrupted: + # Independent custody path; a blocked native call cannot stop fencing. + # End may time out, but it must never label pending work released. + self.end(self._identity) + + +class OverlayIndicator: + """Legacy Linux/Windows ambient band; no terminal-label parity is claimed.""" + + def __init__(self, handle): + self.handle = handle + self.state = "viewing" + + def start(self, state="viewing"): + self.state = state + if self.handle is not None: + self.handle.show() + return self.status() + + def update(self, state): + self.state = state + return self.status() + + def status(self): + shown = self.handle is not None and getattr(self.handle, "shown", False) + return { + "available": shown, + "ready": shown, + "healthy": shown, + "state": self.state, + } + + def close(self): + if self.handle is not None: + self.handle.hide() + absent = not getattr(self.handle, "shown", True) + return { + "closed": absent, + "surface_absent": absent, + "process_settled": absent, + "helper_exit": 0 if self.state == "released" else 2, + } diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/ledger.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/ledger.py index 54a7628..7e79693 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/ledger.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/ledger.py @@ -78,30 +78,31 @@ def hold( token: str, release_fn: Callable[[], None], *, - retain_on_failure: bool = False, + retain_on_failure: bool = True, ) -> None: """Register `token` (e.g. a modifier name, a button name) as held. - `retain_on_failure` is for acknowledged safety-release callbacks: - preserve their obligation and suppress success notifications when an - attempt fails. It does not retry the original input operation. + Failed callbacks always retain custody and suppress success notifications. + `retain_on_failure` remains accepted for source compatibility; false no + longer discards an unconfirmed obligation. No original input is retried. """ with self._lock: + if token in self._held: + raise RuntimeError( + "held-input token already has an outstanding obligation" + ) if self._stopped: # A hold requested after shutdown must not silently vanish # from the ledger - release immediately rather than track a # phantom entry no trigger will ever see. - if retain_on_failure: - held = _Held( - token=token, - kind=kind, - release_fn=release_fn, - retain_on_failure=True, - ) - self._held[token] = held - self._release_locked(held) - else: - release_fn() + held = _Held( + token=token, + kind=kind, + release_fn=release_fn, + retain_on_failure=True, + ) + self._held[token] = held + self._release_locked(held) return self._held[token] = _Held( token=token, @@ -154,6 +155,18 @@ def stop(self) -> None: self._timer.cancel() self._timer = None + def acknowledge_release(self, token: str) -> None: + """Retire controller custody from owner-bound target release evidence. + + Emits no input. The caller must already have matching target generation, + native worker drain and successful ledger-release acknowledgement. + """ + with self._lock: + held = self._held.pop(token, None) + if held is not None: + held.released = True + self._reset_deadman_locked() + @property def held_tokens(self) -> list[str]: with self._lock: @@ -168,19 +181,13 @@ def _release_locked(self, held: _Held) -> bool: try: held.release_fn() except Exception: - if held.retain_on_failure: - held.released = False - logger.exception( - "held-input ledger: release for %r unconfirmed; retaining custody", - held.token, - ) - return False + held.released = False logger.exception( - "held-input ledger: release_fn for %r (%s) raised - the input " - "may still be physically held; this is logged, not swallowed", + "held-input ledger: release for %r (%s) unconfirmed; retaining custody", held.token, held.kind, ) + return False self._held.pop(held.token, None) if self._on_release is not None: try: diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/macos_indicator.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/macos_indicator.py new file mode 100644 index 0000000..1ff210b --- /dev/null +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/macos_indicator.py @@ -0,0 +1,391 @@ +"""Bounded synchronous target-side adapter for the private AppKit helper. + +Construction/import/status are inert. Call start/update/close off an async loop. +Only an explicit lifecycle-owner update('released') requests that label; neither +timeout, empty input ledger nor helper exit implies real control release. +""" + +from __future__ import annotations + +import os +import select +import subprocess +import sys +import threading +import time +import uuid +from pathlib import Path + +from .macos_indicator_helper import ( + HEARTBEAT_SECONDS, + MAX_FRAME, + STATES, + TERMINAL, + TERMINAL_DWELL_SECONDS, + WATCHDOG_SECONDS, + ProtocolError, + decode_frame, + encode_frame, + validate_reply, +) + +_ACTIONS = { + "cocoa_unavailable": "Install the tool package's Darwin Cocoa dependency in the target interpreter.", + "console_user_mismatch": "Run as the logged-in target console user.", + "console_unavailable": "Unlock a logged-in target console session.", + "gui_unavailable": "Use an available target graphical console session.", + "unsupported_platform": "The Mac activity panel requires macOS.", +} + + +class MacOSIndicator: + """Single-use generation. status() is a monitor-maintained nonblocking copy. + + ``fault_settled`` is resource custody, NOT healthy disclosure or release. + A completed wait on our dedicated helper proves its process-owned NSPanel + resources cannot remain live. It does not fabricate ``surface_absent`` + (the native metadata acknowledgement), pixels or physical input release. + """ + + def __init__(self): + self._generation = uuid.uuid4().hex + self._sequence = 0 + self._proc = None + self._buffer = b"" + self._lock = threading.Lock() + self._stop = threading.Event() + self._monitor = None + self._last_reply = 0.0 + self._last_loop = 0 + self._failed = False + self._failure_reason = None + self._snapshot = { + "available": False, + "ready": False, + "healthy": False, + "state": "interrupted", + "reason": "not_started", + "generation": self._generation, + "sequence": 0, + "terminal": False, + "own_window_confirmed": False, + "pixels_verified": False, + "closed": False, + "surface_absent": False, + "process_settled": False, + "helper_exit": None, + "fault_settled": False, + "settlement_basis": "not_settled", + } + + def status(self) -> dict: + result = dict(self._snapshot) + if result["healthy"] and ( + time.monotonic() - self._last_reply >= WATCHDOG_SECONDS + or (self._proc is not None and self._proc.poll() is not None) + ): + # Observation only: do not wait for a lock or invent release. + # Sticky loss even when a blocked monitor resumes later. + if self._failure_reason is None: + self._failure_reason = "connection_lost" + self._failed = True + self._stop.set() + if self._failed: + # Independent sticky loss wins even if a concurrent exchange just + # published an unhealthy/closed terminal snapshot after its last + # failure check. Preserve absence/settlement as separate observations. + result = { + **result, + "healthy": False, + "ready": False, + "state": "interrupted", + "reason": self._failure_reason or "connection_lost", + "terminal": False, + "own_window_confirmed": False, + "fault_settled": ( + result["process_settled"] + and result["settlement_basis"] + in ("never_launched", "helper_reaped") + ), + } + return result + + def _launch(self): + # A script path avoids importing the tool's package __init__ in the child. + helper = Path(__file__).with_name("macos_indicator_helper.py") + proc = subprocess.Popen( + [sys.executable, "-I", str(helper)], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + bufsize=0, + close_fds=True, + ) + # Retain custody immediately: pipe setup can fail after Popen succeeded. + # _reap must never mistake that failure for a never-launched helper. + self._proc = proc + os.set_blocking(proc.stdin.fileno(), False) + os.set_blocking(proc.stdout.fileno(), False) + return proc + + def start(self, state="viewing") -> dict: + if state not in ("viewing", "controlling"): + raise ValueError("invalid indicator start state") + with self._lock: + if self._proc is not None or self._failed or self._snapshot["closed"]: + return self.status() + if sys.platform != "darwin": + self._fail("unsupported_platform") + self._reap() + return self.status() + try: + self._proc = self._launch() + result = self._request("start", state, WATCHDOG_SECONDS - 0.5) + except OSError: + result = self._fail("helper_failed") + if result["healthy"]: + self._monitor = threading.Thread( + target=self._watch, name="mac-indicator-health", daemon=True + ) + self._monitor.start() + else: + self._reap() + return self.status() + + def update(self, state) -> dict: + if not isinstance(state, str) or state not in STATES: + raise ValueError("invalid indicator state") + with self._lock: + if not self.status()["healthy"] or self._failed: + return self._fail("connection_lost") + current = self._snapshot["state"] + if (current in TERMINAL and state != current) or ( + current == "stopping" and state not in ("stopping", *TERMINAL) + ): + raise ValueError("invalid indicator state transition") + return self._request("update", state) + + def _request(self, op, state=None, timeout=1.5): + try: + return self._exchange(op, state, timeout) + except TimeoutError: + return self._fail("reply_timeout") + except (OSError, ProtocolError): + return self._fail("connection_lost") + + def _exchange(self, op, state, timeout): + # Monitor/close callers must observe *prior* health without relying on + # a model/status poll. Never revive an expired generation with traffic. + prior = self.status() + if self._failed or (op != "start" and not prior["healthy"]): + return self.status() + lease_deadline = ( + self._last_reply + WATCHDOG_SECONDS if prior["healthy"] else None + ) + self._sequence += 1 + row = { + "v": 1, + "g": self._generation, + "s": self._sequence, + "op": op, + "state": state, + } + data = encode_frame(row) + deadline = time.monotonic() + timeout + proc = self._proc + if proc is None: + raise OSError("helper_failed") + _, writable, _ = select.select([], [proc.stdin], [], timeout) + now = time.monotonic() + if lease_deadline is not None and now >= lease_deadline: + return self._fail("connection_lost") + if now >= deadline: + raise TimeoutError + if not writable or os.write(proc.stdin.fileno(), data) != len(data): + raise TimeoutError + while time.monotonic() < deadline: + ready, _, _ = select.select( + [proc.stdout], [], [], max(0, deadline - time.monotonic()) + ) + if not ready: + break + chunk = os.read(proc.stdout.fileno(), MAX_FRAME + 1 - len(self._buffer)) + if not chunk: + raise OSError("connection_lost") + self._buffer += chunk + if len(self._buffer) > MAX_FRAME: + raise ProtocolError("protocol_error") + if b"\n" not in self._buffer: + continue + frame, self._buffer = self._buffer.split(b"\n", 1) + reply = decode_frame(frame + b"\n") + validate_reply(reply) + expected = ( + "ready" + if op == "start" + else "terminal" + if op in ("close", "abort") + else "ack" + ) + if ( + reply["g"] != self._generation + or reply["s"] != self._sequence + or reply["event"] not in (expected, "unavailable") + or ( + state is not None + and reply["state"] != state + and reply["reason"] == "ok" + ) + or (op == "status" and reply["state"] != self._snapshot["state"]) + or self._buffer + ): + raise ProtocolError("protocol_error") + if reply["reason"] != "ok" or reply["event"] == "unavailable": + return self._fail(reply["reason"]) + closed = expected == "terminal" + terminal_state = ( + "interrupted" + if op == "abort" or self._snapshot["state"] not in TERMINAL + else self._snapshot["state"] + ) + if ( + reply["loop"] <= self._last_loop + or reply["window"] == closed + or (closed and reply["state"] != terminal_state) + ): + raise ProtocolError("protocol_error") + if self._failed: + return self.status() + now = time.monotonic() + # A correlated reply can arrive after the old lease or request + # deadline, even if select returned readable. Check before renewal, + # including terminal acknowledgements; do not replay the mutation. + if lease_deadline is not None and now >= lease_deadline: + return self._fail("connection_lost") + if now >= deadline: + raise TimeoutError + self._last_reply = now + self._last_loop = reply["loop"] + self._snapshot = { + "available": True, + "ready": not closed, + "healthy": not closed, + "state": reply["state"], + "reason": "closed" if closed else "ok", + "generation": self._generation, + "sequence": self._sequence, + "terminal": reply["state"] in TERMINAL, + "own_window_confirmed": reply["window"], + "pixels_verified": False, + "closed": closed, + "surface_absent": closed, + "process_settled": False, + "helper_exit": None, + "fault_settled": False, + "settlement_basis": "not_settled", + } + return self.status() + raise TimeoutError + + def _fail(self, reason): + # A failure is sticky. The same generation can never become healthy again. + if self._failure_reason is None: + self._failure_reason = reason + self._failed = True + self._stop.set() + self._snapshot = { + **self._snapshot, + "ready": False, + "healthy": False, + "state": "interrupted", + "reason": reason, + "sequence": self._sequence, + "terminal": False, + "own_window_confirmed": False, + } + if reason in _ACTIONS: + self._snapshot["action"] = _ACTIONS[reason] + return self.status() + + def _watch(self): + try: + while not self._stop.wait(HEARTBEAT_SECONDS): + with self._lock: + if self._stop.is_set(): + return + if not self._request("status")["healthy"]: + return + finally: + if self._failed: + with self._lock: + # No retry of an unknown mutation; close pipe => interrupted. + self._reap() + + def _reap(self): + proc = self._proc + if proc is None: + self._record_settlement("never_launched", None) + return True + try: + if proc.stdin and not proc.stdin.closed: + proc.stdin.close() + try: + proc.wait(timeout=TERMINAL_DWELL_SECONDS + 0.5) + except subprocess.TimeoutExpired: + proc.terminate() + try: + proc.wait(timeout=0.5) + except subprocess.TimeoutExpired: + proc.kill() + try: + proc.wait(timeout=0.5) + except subprocess.TimeoutExpired: + return False + if proc.stdout and not proc.stdout.closed: + proc.stdout.close() + except OSError: + # Including a race during signal delivery: retain custody until a + # subsequent wait actually observes exit, never infer it from error. + return False + if type(proc.returncode) is not int: + return False # An attempted wait/kill is not a confirmed process exit. + self._record_settlement("helper_reaped", proc.returncode) + return True + + def _record_settlement(self, basis, helper_exit): + self._snapshot = { + **self._snapshot, + "process_settled": True, + "helper_exit": helper_exit, + "fault_settled": self._failed, + "settlement_basis": basis, + } + + def close(self) -> dict: + return self._finish("close") + + def abort(self) -> dict: + return self._finish("abort") + + def _finish(self, op): + self._stop.set() + with self._lock: + if self._snapshot["closed"] and self._snapshot["process_settled"]: + return self.status() + if self._proc is None: + self._reap() + self._snapshot = { + **self._snapshot, + "closed": True, + "process_settled": True, + } + return self.status() + if not self._failed and not self._snapshot["closed"]: + self._request(op, timeout=TERMINAL_DWELL_SECONDS + 1) + if not self._reap() or ( + self._snapshot["closed"] + and self._proc.returncode + != (0 if self._snapshot["state"] == "released" else 2) + ): + self._fail("helper_failed") + return self.status() diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/macos_indicator_helper.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/macos_indicator_helper.py new file mode 100644 index 0000000..3c117a1 --- /dev/null +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/macos_indicator_helper.py @@ -0,0 +1,588 @@ +"""Private, payload-free Mac activity panel process. + +Import and --self-test are inert: AppKit is imported only after a valid start. +The controller launches this file with its *own* prepared Python interpreter, +not the login shell's Python. No compiler, listener, daemon or permission prompt. +Window metadata acknowledges our surface, never visible pixels or input release. +""" + +from __future__ import annotations + +import json +import math +import os +import re +import select +import signal +import sys +import threading +import time + +VERSION = 1 +MAX_FRAME = 512 +HEARTBEAT_SECONDS = 0.5 +WATCHDOG_SECONDS = 4.0 +TERMINAL_DWELL_SECONDS = 3.0 +STATES = frozenset( + {"viewing", "controlling", "paused", "stopping", "released", "interrupted"} +) +TERMINAL = frozenset({"released", "interrupted"}) +LABELS = { + "viewing": "Amplifier viewing this Mac", + "controlling": "Amplifier controlling this Mac", + "paused": "Paused — viewing may continue", + "stopping": "Stopping — please wait", + "released": "Control released", + "interrupted": "Connection lost — state unconfirmed", +} +REASONS = frozenset( + { + "ok", + "unsupported_platform", + "console_user_mismatch", + "console_unavailable", + "cocoa_unavailable", + "gui_unavailable", + "surface_unconfirmed", + "protocol_error", + "connection_lost", + "helper_failed", + "reply_timeout", + "not_started", + "closed", + } +) + + +class ProtocolError(ValueError): + """Closed schema violation; never include received bytes in an error.""" + + +def _object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ProtocolError("protocol_error") + result[key] = value + return result + + +def decode_frame(data: bytes) -> dict: + if ( + not 1 < len(data) <= MAX_FRAME + or not data.endswith(b"\n") + or data.count(b"\n") != 1 + ): + raise ProtocolError("protocol_error") + try: + value = json.loads(data.decode("ascii"), object_pairs_hook=_object) + except (ValueError, UnicodeError, RecursionError) as exc: + raise ProtocolError("protocol_error") from exc + if not isinstance(value, dict): + raise ProtocolError("protocol_error") + return value + + +def encode_frame(value: dict) -> bytes: + data = json.dumps(value, ensure_ascii=True, separators=(",", ":")).encode() + b"\n" + if len(data) > MAX_FRAME: + raise ProtocolError("protocol_error") + return data + + +def _correlation(row: dict) -> None: + if ( + type(row.get("v")) is not int + or row["v"] != VERSION + or not isinstance(row.get("g"), str) + or re.fullmatch("[0-9a-f]{32}", row["g"]) is None + or type(row.get("s")) is not int + or not 1 <= row["s"] <= 2**53 + ): + raise ProtocolError("protocol_error") + + +def validate_command(row: dict) -> None: + if set(row) != {"v", "g", "s", "op", "state"}: + raise ProtocolError("protocol_error") + _correlation(row) + if not isinstance(row["op"], str): + raise ProtocolError("protocol_error") + if row["op"] in ("start", "update"): + if not isinstance(row["state"], str) or row["state"] not in STATES: + raise ProtocolError("protocol_error") + elif row["op"] not in ("status", "close", "abort") or row["state"] is not None: + raise ProtocolError("protocol_error") + + +def validate_reply(row: dict) -> None: + if set(row) != {"v", "g", "s", "event", "state", "reason", "window", "loop"}: + raise ProtocolError("protocol_error") + _correlation(row) + if ( + row["event"] not in ("ready", "ack", "terminal", "unavailable") + or not isinstance(row["state"], str) + or row["state"] not in STATES + or not isinstance(row["reason"], str) + or row["reason"] not in REASONS + or type(row["window"]) is not bool + or type(row["loop"]) is not int + or not 0 <= row["loop"] <= 2**53 + ): + raise ProtocolError("protocol_error") + + +class Protocol: + """One generation, contiguous sequence, irreversible terminal state.""" + + def __init__(self): + self.generation = None + self.sequence = 0 + self.state = "interrupted" + self.closing = False + + def accept(self, row: dict) -> str: + validate_command(row) + op, state = row["op"], row["state"] + if self.generation is None: + if ( + row["s"] != 1 + or op != "start" + or state not in ("viewing", "controlling") + ): + raise ProtocolError("protocol_error") + self.generation = row["g"] + elif ( + row["g"] != self.generation + or row["s"] != self.sequence + 1 + or op == "start" + or self.closing + ): + raise ProtocolError("protocol_error") + if op == "update": + if self.state in TERMINAL and state != self.state: + raise ProtocolError("protocol_error") + if self.state == "stopping" and state not in ( + "stopping", + "released", + "interrupted", + ): + raise ProtocolError("protocol_error") + self.sequence = row["s"] + if op in ("start", "update"): + self.state = state + elif op == "abort" or (op == "close" and self.state not in TERMINAL): + self.state = "interrupted" + if op in ("close", "abort"): + self.closing = True + return op + + def reply(self, event, reason="ok", window=False, loop=0): + return { + "v": VERSION, + "g": self.generation, + "s": self.sequence, + "event": event, + "state": self.state, + "reason": reason, + "window": window, + "loop": loop, + } + + +def console_reason() -> str: + if sys.platform != "darwin": + return "unsupported_platform" + try: + # No username, host identifiers or other users' metadata cross IPC. + uid = os.stat("/dev/console").st_uid + if uid == 0: + return "console_unavailable" + return "ok" if uid == os.geteuid() else "console_user_mismatch" + except OSError: + return "console_unavailable" + + +class PanelRuntime: + """Main-loop coordinator, also exercised with an inert surface in CI.""" + + def __init__(self, protocol, surface, emit, *, clock=time.monotonic): + self.protocol, self.surface, self.emit = protocol, surface, emit + self.clock = clock + self.last_command = self.last_tick = self.applied_at = clock() + self.parent_pid = os.getppid() + self.loops = 0 + self.pending = "ready" + self.reason = "ok" + self.finished = False + self.ever_confirmed = False + self.removing_at = None + self.interrupt_requested = False + self.surface.apply(protocol.state) + + def receive(self, data): + # Expiry is a precondition, not a timer side effect. A command arriving + # between loop ticks must not renew an already expired generation. + self._check_liveness(self.clock()) + if self.reason != "ok": + raise ProtocolError("connection_lost") + if self.pending is not None: + raise ProtocolError("protocol_error") + before = self.protocol.state + op = self.protocol.accept(decode_frame(data)) + now = self.clock() + self._check_liveness(now) + if self.interrupt_requested or self.reason != "ok": + self.interrupt() + else: + self.last_command = now + if before != self.protocol.state: + self.applied_at = now + self.surface.apply(self.protocol.state) + self.pending = "terminal" if op in ("close", "abort") else "ack" + + def request_interrupt(self): + # Signal-safe Python bookkeeping only. Never reenter AppKit or mutate + # Protocol.accept's in-progress transition from a Python signal handler. + self.interrupt_requested = True + + def interrupt(self, reason="connection_lost"): + # Lost connection overrides even a previously requested released label. + if self.reason == "ok": + self.reason = reason + self.protocol.state = "interrupted" + self.protocol.closing = True + self.applied_at = self.clock() + self.surface.apply("interrupted") + elif self.protocol.state != "interrupted": + self.protocol.state = "interrupted" + self.protocol.closing = True + self.surface.apply("interrupted") + + def _check_liveness(self, now): + if ( + self.interrupt_requested + or now - self.last_command >= WATCHDOG_SECONDS + or os.getppid() != self.parent_pid + ): + self.interrupt() + + def tick(self): + self.loops += 1 + self.last_tick = now = self.clock() + self._check_liveness(now) + confirmed = False if self.removing_at is not None else self.surface.confirmed() + if confirmed: + self.ever_confirmed = True + elif ( + not self.ever_confirmed + and self.reason == "ok" + and now - self.applied_at < 2.0 + ): + return # Allow bounded WindowServer registration before initial ready. + if not confirmed and self.removing_at is None: + self.interrupt("surface_unconfirmed") + closing = self.protocol.closing + if closing and now - self.applied_at >= TERMINAL_DWELL_SECONDS: + if self.removing_at is None: + self.removing_at = now + absent = self.surface.remove() + if not absent and now - self.removing_at < 0.5: + return + reason = self.reason if absent else "surface_unconfirmed" + if reason != "ok": + self.protocol.state = "interrupted" + self.reason = reason + if self.pending is not None: + self.emit(self.protocol.reply("terminal", reason, False, self.loops)) + self.pending = None + self.finished = True + return + if self.pending is not None and not closing: + event = self.pending if self.reason == "ok" else "unavailable" + self.emit(self.protocol.reply(event, self.reason, confirmed, self.loops)) + self.pending = None + elif self.pending is not None and self.reason != "ok": + # Report loss promptly; the native loop retains the interrupted badge. + self.emit( + self.protocol.reply("unavailable", self.reason, False, self.loops) + ) + self.pending = None + + +def _create_surface(appkit, quartz): + """Create only our fixed-size, click-through, never-key/main panel.""" + + class ActivityPanel(appkit.NSPanel): + def canBecomeKeyWindow(self): + return False + + def canBecomeMainWindow(self): + return False + + screen = appkit.NSScreen.mainScreen() + if screen is None: + raise RuntimeError("gui_unavailable") + visible = screen.visibleFrame() + values = ( + visible.origin.x, + visible.origin.y, + visible.size.width, + visible.size.height, + ) + if not all(math.isfinite(v) for v in values) or values[2] < 496 or values[3] < 80: + raise RuntimeError("gui_unavailable") + panel = ActivityPanel.alloc().initWithContentRect_styleMask_backing_defer_( + ((values[0] + 16, values[1] + values[3] - 80), (480, 64)), + appkit.NSWindowStyleMaskBorderless | appkit.NSWindowStyleMaskNonactivatingPanel, + appkit.NSBackingStoreBuffered, + False, + ) + panel.setReleasedWhenClosed_(False) + panel.setLevel_(appkit.NSStatusWindowLevel) + panel.setCollectionBehavior_( + appkit.NSWindowCollectionBehaviorCanJoinAllSpaces + | appkit.NSWindowCollectionBehaviorStationary + | appkit.NSWindowCollectionBehaviorFullScreenAuxiliary + ) + panel.setHidesOnDeactivate_(False) + panel.setBecomesKeyOnlyIfNeeded_(True) + panel.setIgnoresMouseEvents_(True) + panel.setMovable_(False) + panel.setHasShadow_(False) + panel.setOpaque_(True) + panel.setBackgroundColor_( + appkit.NSColor.colorWithCalibratedRed_green_blue_alpha_(1, 0.82, 0.25, 1) + ) + label = appkit.NSTextField.labelWithString_("") + label.setFrame_(((8, 8), (464, 48))) + label.setFont_(appkit.NSFont.boldSystemFontOfSize_(17)) + label.setTextColor_(appkit.NSColor.blackColor()) + label.setAlignment_(appkit.NSTextAlignmentCenter) + label.setMaximumNumberOfLines_(2) + label.setSelectable_(False) + panel.contentView().addSubview_(label) + panel.orderFront_(None) # No activate, makeKey, orderFrontRegardless or focus call. + + class Surface: + window_id = None + removed = False + + def apply(self, state): + label.setStringValue_(LABELS[state]) + panel.displayIfNeeded() + + def _onscreen(self): + if self.window_id is None: + number = panel.windowNumber() + if number <= 0: + return None + self.window_id = number + entries = quartz.CGWindowListCopyWindowInfo( + quartz.kCGWindowListOptionOnScreenOnly + | quartz.kCGWindowListExcludeDesktopElements, + quartz.kCGNullWindowID, + ) + if entries is None: + return None + # Inspect ONLY owner and window number, never titles or other payload. + return any( + entry.get(quartz.kCGWindowOwnerPID) == os.getpid() + and entry.get(quartz.kCGWindowNumber) == self.window_id + for entry in entries + ) + + def confirmed(self): + app = appkit.NSApplication.sharedApplication() + return bool( + app.activationPolicy() == appkit.NSApplicationActivationPolicyAccessory + and not app.isActive() + and panel.isVisible() + and not panel.canBecomeKeyWindow() + and not panel.canBecomeMainWindow() + and not panel.isKeyWindow() + and not panel.isMainWindow() + and panel.ignoresMouseEvents() + and self._onscreen() is True + and console_reason() == "ok" + ) + + def remove(self): + if not self.removed: + # Save the actual observed ID before close can invalidate it. + self._onscreen() + panel.orderOut_(None) + panel.close() + self.removed = True + return self.window_id is not None and self._onscreen() is False + + return Surface() + + +def _stop_application(app, appkit): + app.stop_(None) + # Wake only this helper's AppKit event queue. This application-defined event + # is not keyboard/mouse input and is never posted to the desktop. + event = appkit.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_( + appkit.NSEventTypeApplicationDefined, (0, 0), 0, 0, 0, None, 0, 0, 0 + ) + app.postEvent_atStart_(event, False) + + +def _emit(row): + # A <=512 byte frame fits PIPE_BUF; a full/closed pipe never blocks AppKit. + data = encode_frame(row) + try: + if os.write(1, data) != len(data): + os._exit(71) + except OSError: + os._exit(71) + + +def _read_start(): + buffer = b"" + deadline = time.monotonic() + WATCHDOG_SECONDS + while time.monotonic() < deadline: + ready, _, _ = select.select([0], [], [], max(0, deadline - time.monotonic())) + if not ready: + break + chunk = os.read(0, MAX_FRAME + 1 - len(buffer)) + if not chunk: + break + buffer += chunk + if len(buffer) > MAX_FRAME: + break + if buffer.endswith(b"\n"): + row = decode_frame(buffer) + protocol = Protocol() + protocol.accept(row) + return protocol + raise ProtocolError("protocol_error") + + +def _native_main(protocol): + reason = console_reason() + if reason != "ok": + _emit(protocol.reply("unavailable", reason)) + return 2 + try: + import AppKit + import Quartz + from Foundation import NSRunLoop, NSRunLoopCommonModes, NSTimer + except Exception: + _emit(protocol.reply("unavailable", "cocoa_unavailable")) + return 2 + try: + app = AppKit.NSApplication.sharedApplication() + if not app.setActivationPolicy_(AppKit.NSApplicationActivationPolicyAccessory): + raise RuntimeError("gui_unavailable") + surface = _create_surface(AppKit, Quartz) + runtime = PanelRuntime(protocol, surface, _emit) + except Exception: + _emit(protocol.reply("unavailable", "gui_unavailable")) + return 2 + buffer = b"" + stop = threading.Event() + + def watchdog(): + # Independent of main-loop/IPC locks. A stalled loop cannot stay healthy. + while not stop.wait(0.25): + if time.monotonic() - runtime.last_tick > WATCHDOG_SECONDS: + os._exit(70) + + threading.Thread( + target=watchdog, name="mac-indicator-watchdog", daemon=True + ).start() + + def interrupted(_signum, _frame): + runtime.request_interrupt() + + for number in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + signal.signal(number, interrupted) + + def tick(_timer): + nonlocal buffer + try: + try: + chunk = os.read(0, MAX_FRAME + 1 - len(buffer)) + except BlockingIOError: + chunk = None + if chunk == b"": + runtime.interrupt() + elif chunk: + buffer += chunk + if len(buffer) > MAX_FRAME: + raise ProtocolError("protocol_error") + if b"\n" in buffer: + frame, buffer = buffer.split(b"\n", 1) + runtime.receive(frame + b"\n") + except ProtocolError: + runtime.interrupt("protocol_error") + buffer = b"" + except Exception: + runtime.interrupt("helper_failed") + try: + runtime.tick() + if runtime.finished: + _stop_application(app, AppKit) + except Exception: + # A broken native surface cannot keep the helper resident indefinitely. + os._exit(72) + + timer = NSTimer.timerWithTimeInterval_repeats_block_(0.1, True, tick) + NSRunLoop.mainRunLoop().addTimer_forMode_(timer, NSRunLoopCommonModes) + try: + app.run() + finally: + timer.invalidate() + stop.set() + surface.remove() + return 0 if protocol.state == "released" and runtime.reason == "ok" else 2 + + +def self_test(): + """Exercise the real framing/state machine, without AppKit or a display.""" + protocol = Protocol() + for seq, op, state in ( + (1, "start", "viewing"), + (2, "status", None), + (3, "update", "controlling"), + (4, "update", "stopping"), + (5, "update", "released"), + (6, "close", None), + ): + protocol.accept( + decode_frame( + encode_frame( + {"v": 1, "g": "a" * 32, "s": seq, "op": op, "state": state} + ) + ) + ) + validate_reply(decode_frame(encode_frame(protocol.reply("ack")))) + try: + protocol.accept( + {"v": 1, "g": "a" * 32, "s": 6, "op": "update", "state": "controlling"} + ) + except ProtocolError: + return + raise AssertionError("stale terminal command accepted") + + +def main(): + if sys.argv[1:] == ["--self-test"]: + self_test() + print('{"protocol_self_test":"pass","native_ui_exercised":false}') + return 0 + if sys.argv[1:]: + return 2 + os.set_blocking(0, False) + os.set_blocking(1, False) + try: + return _native_main(_read_start()) + except Exception: + # No arbitrary error text, paths or caller data in stdout/stderr. + return 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/observed_control.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/observed_control.py index b51981e..d9ec571 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/observed_control.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/observed_control.py @@ -90,7 +90,8 @@ def capture(self, binding): ) if self.computer._binding is not binding: raise StaleObservation("Target changed") - _, encoded = self.computer._run("screenshot", {}, binding=binding) + with self.computer._episode_admission("screenshot", binding): + _, encoded = self.computer._run("screenshot", {}, binding=binding) raw = base64.b64decode(encoded) with Image.open(io.BytesIO(raw)) as img: fingerprint = hashlib.sha256(img.convert("RGB").tobytes()).hexdigest() @@ -242,6 +243,8 @@ async def execute(self, arguments): try: if arguments.get("action") == "observe": await asyncio.to_thread(self.computer._ensure_announced) + if self.computer._episode_enabled: + await asyncio.to_thread(self.computer.begin_episode) binding = self.computer._binding observed = await asyncio.to_thread(self.observe, binding) return ToolResult(success=True, output=observed) diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_agent.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_agent.py index 697baab..934d298 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_agent.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_agent.py @@ -43,10 +43,12 @@ import io import json import logging +import queue import signal import sys as _sys import threading import traceback +import uuid from collections.abc import Callable from typing import Any, ClassVar @@ -59,6 +61,13 @@ sweep_stale_agent_dirs, ) from .backend import Backend, BackendError +from .episode import ( + Episode, + EpisodeError, + OverlayIndicator, + episode_order, + settled_terminal, +) from .exclusion import ExclusionZone from .ledger import DEFAULT_DEADMAN_SECONDS, HeldInputLedger from .overlay_linux import LinuxOverlay @@ -69,7 +78,7 @@ target_clock_exchange, without_target_clock, ) -from .wire import PROTOCOL_VERSION, Request, Response, classify_op +from .wire import PROTOCOL_VERSION, EpisodeBeginRefused, Request, Response, classify_op logging.basicConfig( level=logging.INFO, @@ -169,6 +178,8 @@ def __init__( *, deadman_seconds: float = DEFAULT_DEADMAN_SECONDS, read_only: bool = True, + require_episode: bool = False, + indicator_factory: Callable | None = None, ) -> None: self.backend = backend self.read_only = read_only @@ -194,6 +205,146 @@ def __init__( self._exclusion = ExclusionZone() self._announce_paused = False self._announce_cancelled = False + # Production entry point requires owner-bound episodes. False supports + # old in-process handler harnesses only; run() always enables admission. + self._require_episode = require_episode + self._episode_target = uuid.uuid4().hex + self._episode = None + self._indicator_factory = indicator_factory + self._disconnected = threading.Event() + self._episode_control_lock = threading.RLock() + self._revoked_generations: set[tuple[str, str]] = set() + self._episode_highwater = 0 + + def _make_indicator(self): + if self._indicator_factory: + return self._indicator_factory() + if self.backend.name == "macos": + from .macos_indicator import MacOSIndicator + + return MacOSIndicator() + return OverlayIndicator(self._overlay) + + def _release_episode(self): + self._ledger.release_all(reason="episode_end") + return not self._ledger.held_tokens and not self._mouse_pending + + def _op_episode_begin(self, args): + identity = args["identity"] + if ( + not isinstance(identity, dict) + or set(identity) != {"owner", "target", "generation"} + or identity.get("target") != self._episode_target + or any( + not isinstance(v, str) or not v or len(v) > 128 + for v in identity.values() + ) + ): + raise EpisodeError("invalid episode identity") + order = episode_order(identity.get("generation")) + key = (identity.get("owner"), identity.get("generation")) + with self._episode_control_lock: + current = self._episode.status() if self._episode is not None else None + if current is not None and current["identity"] == identity: + # Idempotent query of an existing generation, never a restart. + if key in self._revoked_generations or not current["admission_open"]: + raise EpisodeError("episode is already fenced") + return self._episode.begin(identity) + if order <= self._episode_highwater: + raise EpisodeError("stale episode generation order") + revoked = key in self._revoked_generations + # Begin dispatch consumes its ordered slot even if previously + # revoked. Old begins can never be replayed after compacting fences. + self._episode_highwater = order + self._revoked_generations = { + entry + for entry in self._revoked_generations + if episode_order(entry[1]) > order + } + # Consume rejected ordered slots as well. A delayed duplicate can + # never acquire custody once the current owner has settled. + if revoked or (current is not None and not settled_terminal(current)): + raise EpisodeBeginRefused( + { + "version": 1, + "identity": dict(identity), + "adopted": False, + "reason": "revoked_before_begin" + if revoked + else "target_custody_owned", + } + ) + if current is not None: + self._episode = None + if self._episode is None: + self._episode = Episode( + self._episode_target, + self._make_indicator, + self._release_episode, + lease_seconds=120, + ) + episode = self._episode + self._require_episode = True + result = episode.begin(identity) + with self._episode_control_lock: + if key in self._revoked_generations: + episode.fence(identity, reason="revoked_during_begin") + raise EpisodeError("episode revoked during begin") + return result + + def _op_episode_status(self, args): + if self._episode is None: + return {"state": "idle", "workers": 0, "release_confirmed": False} + return self._episode.status(args["identity"]) + + def _op_episode_end(self, args): + if self._episode is None: + raise EpisodeError("no episode") + self._episode.fence( + args["identity"], interrupted=args.get("interrupted") is True + ) + return self._episode.close(args["identity"]) + + def _episode_notice(self, req): + # Sole stdin reader handles these notices while the native executor may + # be blocked. They never write a response or consume the reply framing. + if req.op not in {"episode_heartbeat", "episode_revoke"}: + return False + try: + identity = req.args["identity"] + if req.op == "episode_revoke": + if ( + not isinstance(identity, dict) + or identity.get("target") != self._episode_target + ): + raise EpisodeError("wrong episode target") + key = (identity.get("owner"), identity.get("generation")) + if any(not isinstance(v, str) or not v or len(v) > 128 for v in key): + raise EpisodeError("invalid episode generation") + order = episode_order(identity["generation"]) + with self._episode_control_lock: + # Only future, not-yet-dispatched generations need a slot. + # Retired begins are refused by the scalar high-water mark. + if ( + order > self._episode_highwater + and key not in self._revoked_generations + ): + if len(self._revoked_generations) >= 128: + self._disconnected.set() + else: + self._revoked_generations.add(key) + if self._episode is None: + raise EpisodeError("no episode") + if req.op == "episode_heartbeat": + self._episode.heartbeat(req.args["identity"]) + else: + self._episode.fence( + req.args["identity"], + interrupted=req.args.get("interrupted") is True, + ) + except Exception: + logger.warning("stale or invalid episode notice refused") + return True def _on_release(self, kind: str, token: str) -> None: # \u00a710.2/\u00a73.3: this exact line, `RELEASED:`, is the @@ -386,6 +537,7 @@ def handshake(self) -> dict[str, Any]: # from the agent's own reality instead of from prose that has to # be kept in sync by hand. "ops": sorted(self._HANDLERS), + "episode_target": self._episode_target, } def run(self, stdin: Any, stdout: Any) -> None: @@ -395,21 +547,45 @@ def run(self, stdin: Any, stdout: Any) -> None: handshake = self.handshake() stdout.write(json.dumps({"id": 0, "ok": True, "result": handshake}) + "\n") stdout.flush() - try: - for line in stdin: - line = line.strip() - if not line: - continue - try: - data = json.loads(line) - req = Request( - id=int(data["id"]), - op=str(data["op"]), - args=data.get("args") or {}, + requests = queue.Queue(maxsize=64) + + def read_requests(): + try: + for line in stdin: + try: + data = json.loads(line) + req = Request( + id=int(data["id"]), + op=str(data["op"]), + args=data.get("args") or {}, + ) + except Exception: + continue + if not self._episode_notice(req): + try: + requests.put_nowait(req) + except queue.Full: + # Do not let a full action queue prevent revocation. + if self._episode is not None: + self._episode.fence( + self._episode.status()["identity"], + reason="queue_overflow", + ) + break + finally: + self._disconnected.set() + if self._episode is not None: + self._episode.fence( + self._episode.status()["identity"], reason="disconnected" ) - except Exception as exc: # noqa: BLE001 - malformed line, not our bug - logger.warning("malformed request line: %s (%s)", line[:200], exc) - continue + requests.put(None) + + threading.Thread(target=read_requests, daemon=True).start() + try: + while True: + req = requests.get() + if req is None: + break resp = self._dispatch(req) stdout.write(resp.encode().decode("utf-8")) stdout.flush() @@ -424,12 +600,69 @@ def run(self, stdin: Any, stdout: Any) -> None: # drop that never runs another line of Python here would leave # both a held key AND a stranded overlay - one guarantee, one # call site, for both. - self._ledger.stop() - self._teardown_overlay() + try: + if self._episode is not None: + self._episode.close(self._episode.status()["identity"]) + finally: + try: + self._ledger.stop() + finally: + self._teardown_overlay() # -- dispatch --------------------------------------------------------------- def _dispatch(self, req: Request) -> Response: + # Native admission is independent of controller hooks and of the + # synchronous response path. No queued request can cross a revoke fence. + protected = req.op in { + "capture", + "capture_scaled", + "cursor_position", + "list_windows", + "get_clipboard", + "move", + "click", + "mouse_down", + "mouse_up", + "drag", + "scroll", + "key", + "hold_key", + "hold", + "type_text", + "focus_window", + "set_clipboard", + } + if getattr(self, "_require_episode", False) and protected: + try: + if self._episode is None: + raise EpisodeError("target requires an explicit sponsored episode") + with self._episode.admit( + req.args.get("_episode"), + controlling=classify_op(req.op) == "write", + ): + return RemoteAgent._dispatch_admitted(self, req) + except Exception as exc: + return Response( + id=req.id, + ok=False, + error_type=type(exc).__name__, + error_message=str(exc), + ) + return RemoteAgent._dispatch_admitted(self, req) + + def _dispatch_admitted(self, req: Request) -> Response: + if ( + getattr(self, "_require_episode", False) + and self._disconnected.is_set() + and req.op not in {"episode_end", "episode_status", "release_all", "bye"} + ): + return Response( + id=req.id, + ok=False, + error_type="EpisodeError", + error_message="controller disconnected", + ) try: op_class = classify_op(req.op) except ValueError as exc: @@ -475,6 +708,14 @@ def _dispatch(self, req: Request) -> Response: ) result = handler(self, args) return Response(id=req.id, ok=True, result=result) + except EpisodeBeginRefused as exc: + return Response( + id=req.id, + ok=False, + error_type="EpisodeBeginRefused", + error_message=str(exc), + error_data=exc.receipt, + ) except BackendError as exc: return Response( id=req.id, @@ -803,6 +1044,9 @@ def _op_bye(self, _args: dict[str, Any]) -> dict[str, Any]: "announce_raise": _op_announce_raise, "announcement_status": _op_announcement_status, "release_all": _op_release_all, + "episode_begin": _op_episode_begin, + "episode_status": _op_episode_status, + "episode_end": _op_episode_end, "bye": _op_bye, } @@ -947,6 +1191,7 @@ def main(argv: list[str] | None = None) -> int: backend, deadman_seconds=args.deadman_seconds, read_only=str(args.read_only).lower() != "false", + require_episode=backend.name == "macos", ) agent.install_signal_handlers() try: diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_backend.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_backend.py index 7337697..9a5e56c 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_backend.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/remote_backend.py @@ -9,8 +9,10 @@ from __future__ import annotations +import copy import itertools import logging +import threading import time from typing import Any @@ -22,9 +24,17 @@ WindowInfo, WindowList, ) +from .episode import settled_terminal from .ssh_transport import AgentStderrError, SshConnectError, SshTransport from .target_clock import CURRENT_TARGET_CLOCK, TargetClockFailure, guarded_target_call -from .wire import AgentBackendUnavailableError, Request, Response, classify_op +from .wire import ( + AgentBackendUnavailableError, + EpisodeBeginRefused, + Request, + Response, + classify_op, + validate_begin_refusal, +) logger = logging.getLogger(__name__) @@ -97,6 +107,144 @@ def __init__(self, config: dict[str, Any] | None = None) -> None: # session, long after this dict was built). self.handshake: dict[str, Any] | None = None self._connected_at: float | None = None + self._episode_identity = None + self._episode_fenced = False + self._episode_state_lock = threading.RLock() + self._episode_status_cache = { + "state": "idle", + "workers": 0, + "release_confirmed": False, + } + + @property + def episode_target(self): + return (self.handshake or {}).get("episode_target") + + def begin_episode(self, identity): + with self._episode_state_lock: + if identity != self._episode_identity: + if self._episode_identity is not None and ( + not self._settled_receipt(self._episode_identity) + ): + raise BackendError("prior remote generation custody is not settled") + self._episode_identity = dict(identity) + self._episode_fenced = False + self._episode_status_cache = { + "identity": dict(identity), + "state": "starting", + "workers": 0, + "admission_open": False, + "release_confirmed": False, + "indicator_settled": False, + } + elif self._episode_fenced: + raise BackendError("remote episode fenced") + try: + result = self._call("episode_begin", identity=identity) + except EpisodeBeginRefused as exc: + with self._episode_state_lock: + if identity == self._episode_identity: + self._episode_fenced = True + self._episode_status_cache = { + "identity": dict(identity), + "state": "interrupted", + "reason": exc.receipt["reason"], + "target_adopted": False, + "begin_refusal": copy.deepcopy(exc.receipt), + "workers": 0, + "admission_open": False, + # Scoped no-input/no-renderer custody, NOT physical + # release of another owner's held input or surface. + "release_confirmed": True, + "indicator_settled": True, + } + raise BackendError(f"remote episode begin refused: {exc}") from exc + except BaseException: + # A missing/malformed reply is not a no-effect receipt. Close local + # admission, retain unknown custody and never replay the request. + self.fence_episode_local(identity, interrupted=True) + raise + with self._episode_state_lock: + if self._episode_fenced or identity != self._episode_identity: + # Readiness reply is not authority to revoke a newer Stop. + raise BackendError("remote episode fenced during begin reply") + self._episode_status_cache = result + return result + + def check_episode(self, identity): + with self._episode_state_lock: + if self._episode_fenced or identity != self._episode_identity: + raise BackendError("remote episode fenced or stale") + + def fence_episode_local(self, identity, *, interrupted=False): + with self._episode_state_lock: + if identity != self._episode_identity: + raise BackendError("wrong episode owner") + if self._settled_receipt(identity): + return + self._episode_fenced = True + prior = self._episode_status_cache + self._episode_status_cache = { + **prior, + "identity": dict(identity), + "state": "interrupted" + if interrupted or prior.get("state") == "interrupted" + else "stopping", + "admission_open": False, + "release_confirmed": False, + } + + def _episode_notice(self, op, identity, **kwargs): + if self._transport is None: + raise BackendError("remote episode transport missing") + self._transport.notify( + Request( + id=next(self._ids), op=op, args={"identity": identity, **kwargs} + ).encode() + ) + + def heartbeat_episode(self, identity): + self.check_episode(identity) + self._episode_notice("episode_heartbeat", identity) + + def revoke_episode(self, identity, *, interrupted=False): + self.fence_episode_local(identity, interrupted=interrupted) + self._episode_notice("episode_revoke", identity, interrupted=interrupted) + + def end_episode(self, identity, *, interrupted=False): + with self._episode_state_lock: + if identity == self._episode_identity and self._settled_receipt(identity): + return copy.deepcopy(self._episode_status_cache) + result = self._call("episode_end", identity=identity, interrupted=interrupted) + with self._episode_state_lock: + if identity == self._episode_identity: + self._episode_status_cache = result + return result + + def _settled_receipt(self, identity): + return self._episode_status_cache.get( + "identity" + ) == identity and settled_terminal(self._episode_status_cache) + + def episode_status(self, identity): + with self._episode_state_lock: + if identity == self._episode_identity and self._settled_receipt(identity): + # Another transport reference may now own the target. Its + # current status cannot replace our immutable terminal receipt. + return copy.deepcopy(self._episode_status_cache) + result = self._call("episode_status", identity=identity) + with self._episode_state_lock: + if identity != self._episode_identity: + return result # Delayed old query cannot replace current custody. + if self._episode_fenced and result.get("admission_open"): + result = { + **result, + "target_state": result["state"], + "state": self._episode_status_cache.get("state", "interrupted"), + "admission_open": False, + } + self._episode_status_cache = result + return result @property def handshake_age_seconds(self) -> float | None: @@ -180,6 +328,22 @@ def _call(self, op: str, **args: Any) -> Any: if self._transport is None or not self._connected: raise BackendError(f"remote backend not connected (op={op!r})") op_class = classify_op(op) + if self._episode_identity is not None and op not in { + "episode_begin", + "episode_end", + "episode_status", + "release_all", + "bye", + "presence_idle", + "announcement_status", + "probe", + "screen_geometry", + "list_monitors", + "ping", + "announce_raise", + }: + self.check_episode(self._episode_identity) + args["_episode"] = self._episode_identity exchange = ( CURRENT_TARGET_CLOCK.get() if self.presence_platform == "windows-wsl2" and op_class == "write" @@ -208,6 +372,12 @@ def _call(self, op: str, **args: Any) -> Any: f"wire desync: sent id={req.id}, got id={resp.id} for op {op!r}" ) if not resp.ok: + if ( + op == "episode_begin" + and resp.error_type == "EpisodeBeginRefused" + and validate_begin_refusal(resp.error_data, args.get("identity")) + ): + raise EpisodeBeginRefused(resp.error_data) raise BackendError(f"{resp.error_type}: {resp.error_message}") if exchange is not None: envelope = resp.result diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/shared_transport.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/shared_transport.py index 7d5f7f6..032dae3 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/shared_transport.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/shared_transport.py @@ -196,6 +196,11 @@ def connect( def send(self, line: bytes, *, timeout: float = 30.0) -> bytes: return self._entry.send(line, timeout=timeout) + def notify(self, line: bytes) -> None: + if self._released or self._entry.broken: + raise self._entry._retired_error() + self._entry.transport.notify(line) + def close(self) -> None: if self._released: return diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/ssh_transport.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/ssh_transport.py index f6d6095..483dbb0 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/ssh_transport.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/ssh_transport.py @@ -53,6 +53,7 @@ "target_clock.py", "wire.py", "ledger.py", + "episode.py", "agent_scratch_lease.py", "remote_agent.py", # The session-start disclosure channel (docs/designs/coexistence.md @@ -65,6 +66,8 @@ # dependency) and is shipped for the same reason those two are. "exclusion.py", "announce_macos.py", + "macos_indicator.py", + "macos_indicator_helper.py", "overlay_linux.py", "overlay_windows.py", # NOT a Python module, and required anyway: `windows.py` resolves @@ -361,6 +364,7 @@ def __init__( self.port = port self._proc: subprocess.Popen[bytes] | None = None self._lock = threading.Lock() + self._write_lock = threading.Lock() self._sent_sha256: str | None = None self.handshake: dict[str, Any] | None = None @@ -388,6 +392,7 @@ def connect( extras = [ "pillow", 'pyobjc-framework-Quartz; sys_platform=="darwin"', + 'pyobjc-framework-Cocoa; sys_platform=="darwin"', 'python-xlib; sys_platform=="linux"', ] with_args = " ".join(f"--with {shlex.quote(e)}" for e in extras) @@ -457,8 +462,9 @@ def send(self, line: bytes, *, timeout: float = 30.0) -> bytes: raise SshConnectError("not connected") with self._lock: try: - proc.stdin.write(line) - proc.stdin.flush() + with self._write_lock: + proc.stdin.write(line) + proc.stdin.flush() except BrokenPipeError as exc: raise SshConnectError( f"connection to {self.user_host} lost while sending" @@ -482,6 +488,15 @@ def send(self, line: bytes, *, timeout: float = 30.0) -> bytes: self._drain_stderr_on_failure() return resp_line + def notify(self, line: bytes) -> None: + """One-way episode custody notice, never waits behind a native reply.""" + proc = self._proc + if proc is None or proc.stdin is None: + raise SshConnectError("not connected") + with self._write_lock: + proc.stdin.write(line) + proc.stdin.flush() + def _read_line_with_timeout(self, stream: Any, timeout: float) -> bytes | None: result: dict[str, bytes | None] = {"line": None} diff --git a/modules/tool-computer-use/amplifier_module_tool_computer_use/wire.py b/modules/tool-computer-use/amplifier_module_tool_computer_use/wire.py index a126f33..0515cb8 100644 --- a/modules/tool-computer-use/amplifier_module_tool_computer_use/wire.py +++ b/modules/tool-computer-use/amplifier_module_tool_computer_use/wire.py @@ -50,6 +50,7 @@ # target's own persistent overlay since the last read? A query, no # side effect - the same idempotency argument as `presence_idle`. "announcement_status", + "episode_status", } ) WRITE_OPS = frozenset( @@ -79,6 +80,10 @@ # implies. Session-lifecycle, not injected input - CONTROL, matching # the design doc's own classification, not WRITE. "announce_raise", + "episode_begin", + "episode_end", + "episode_heartbeat", + "episode_revoke", } ) @@ -89,6 +94,28 @@ class UnknownOpError(ValueError): """`classify_op` was asked about an op this protocol version does not know.""" +class EpisodeBeginRefused(RuntimeError): + """Correlated target proof of rejection BEFORE this generation was adopted.""" + + def __init__(self, receipt: dict[str, Any]) -> None: + self.receipt = receipt + super().__init__(receipt["reason"]) + + +def validate_begin_refusal(receipt: Any, identity: Any) -> bool: + """Closed schema; generic errors, timeouts and other identities prove nothing.""" + return ( + isinstance(receipt, dict) + and set(receipt) == {"version", "identity", "adopted", "reason"} + and type(receipt["version"]) is int + and receipt["version"] == 1 + and receipt["identity"] == identity + and receipt["adopted"] is False + and isinstance(receipt["reason"], str) + and receipt["reason"] in {"revoked_before_begin", "target_custody_owned"} + ) + + def classify_op(op: str) -> OpClass: """Return which retry-policy class `op` belongs to. Raises for an unknown op rather than guessing - an op this protocol doesn't know the class of must @@ -135,6 +162,7 @@ class Response: result: Any = None error_type: str | None = None error_message: str | None = None + error_data: dict[str, Any] | None = None @classmethod def decode(cls, line: bytes | str) -> Response: @@ -163,6 +191,7 @@ def decode(cls, line: bytes | str) -> Response: or not isinstance(err.get("type"), str) or not isinstance(err.get("message"), str) or "result" in data + or ("data" in err and not isinstance(err["data"], dict)) ): raise ValueError("malformed failed wire response") return cls( @@ -170,6 +199,7 @@ def decode(cls, line: bytes | str) -> Response: ok=False, error_type=err["type"], error_message=err["message"], + error_data=err.get("data"), ) def encode(self) -> bytes: @@ -185,6 +215,8 @@ def encode(self) -> bytes: "message": self.error_message or "", }, } + if self.error_data is not None: + payload["error"]["data"] = self.error_data return (json.dumps(payload) + "\n").encode("utf-8") diff --git a/modules/tool-computer-use/pyproject.toml b/modules/tool-computer-use/pyproject.toml index 26639c3..7582bca 100644 --- a/modules/tool-computer-use/pyproject.toml +++ b/modules/tool-computer-use/pyproject.toml @@ -9,6 +9,7 @@ dependencies = [ "pillow>=10.0", "python-xlib>=0.33; sys_platform == 'linux'", "pyobjc-framework-Quartz>=10.0; sys_platform == 'darwin'", + "pyobjc-framework-Cocoa>=10.0; sys_platform == 'darwin'", # Self-configuring fix: `ComputerUseUnavailableTool` action="persist" # (`_persist_target`) reads/writes the user's `~/.amplifier/settings.yaml`. "pyyaml>=6.0", diff --git a/tests/test_episode_lifecycle.py b/tests/test_episode_lifecycle.py new file mode 100644 index 0000000..0ecb19a --- /dev/null +++ b/tests/test_episode_lifecycle.py @@ -0,0 +1,1272 @@ +"""Production lifecycle functions against inert backends, not native qualification.""" + +from __future__ import annotations + +import asyncio +import io +import json +import queue +import threading +import time +from functools import wraps + +import amplifier_module_tool_computer_use as cu +import pytest +from amplifier_core.testing import MockCoordinator +from amplifier_module_tool_computer_use.episode import ( + Episode, + EpisodeError, + new_episode_generation, +) +from amplifier_module_tool_computer_use.ledger import HeldInputLedger +from amplifier_module_tool_computer_use.remote_agent import RemoteAgent +from amplifier_module_tool_computer_use.remote_backend import RemoteBackend +from amplifier_module_tool_computer_use.ssh_transport import SshTransport +from amplifier_module_tool_computer_use.wire import Request, Response +from test_neutral_computer import Backend, batch +from test_remote_agent import _FakeBackend + + +class Indicator: + def __init__(self): + self.states = [] + self.healthy = True + self.closed = False + + def start(self, state="viewing"): + return self.update(state) + + def update(self, state): + self.states.append(state) + return self.status() + + def status(self): + return {"available": True, "ready": True, "healthy": self.healthy} + + def close(self): + self.closed = True + return { + "healthy": False, + "closed": True, + "surface_absent": True, + "process_settled": True, + "helper_exit": 0 if self.states[-1] == "released" else 2, + } + + +def wait_for(predicate, timeout=2): + deadline = time.monotonic() + timeout + while not predicate(): + assert time.monotonic() < deadline, "condition not observed" + time.sleep(0.005) + + +def run_async(function): + # A private loop leaves legacy sync tests' current loop untouched. + @wraps(function) + def run(*args, **kwargs): + with asyncio.Runner(loop_factory=asyncio.new_event_loop) as runner: + return runner.run(function(*args, **kwargs)) + + return run + + +@pytest.fixture +def rig(monkeypatch, tmp_path): + monkeypatch.setattr(cu, "SHOT_DIR", tmp_path) + indicator = Indicator() + tool = cu.ComputerTool(Backend(), {"_indicator_factory": lambda: indicator}) + tool._episode_enabled = True + tool._announced = True + tool.resolve_display() + yield tool, indicator + if tool._episode_identity is not None: + tool.end_episode(interrupted=True) + with cu._episode_registry_lock: + cu._episode_registry.clear() + + +@run_async +async def test_capture_only_reasoning_gaps_batch_desktop_and_explicit_release(rig): + tool, indicator = rig + assert (await tool.execute({"action": "screenshot"})).success + generation = tool.episode_status()["identity"]["generation"] + assert indicator.states == ["viewing"] + await asyncio.sleep(0.02) # queue is empty, sponsor is still active + assert tool.episode_status()["state"] == "viewing" + assert not indicator.closed + assert ( + await tool.execute(batch({"action": "key", "text": "A"}, capture=False)) + ).success + assert "controlling" in indicator.states + tool._backend.get_clipboard = lambda: "inert" + assert (await cu.DesktopTool(tool).execute({"action": "get_clipboard"})).success + result = await cu.DesktopTool(tool).execute( + {"action": "end_episode", "generation": generation} + ) + assert result.output["state"] == "released" + assert result.output["release_confirmed"] + assert indicator.closed and indicator.states[-1] == "released" + assert not (await tool.execute({"action": "key", "text": "A"})).success + + +@pytest.mark.parametrize("action", ["get_clipboard", "set_clipboard", "focus_window"]) +@run_async +async def test_cancelled_desktop_worker_not_released_and_queued_call_refused( + rig, action +): + tool, indicator = rig + entered, proceed, settled = threading.Event(), threading.Event(), threading.Event() + + def blocked(*args): + entered.set() + assert proceed.wait(5) + settled.set() + return "inert" + + setattr(tool._backend, action, blocked) + desktop = cu.DesktopTool(tool) + task = asyncio.create_task( + desktop.execute({"action": action, "text": "x", "handle": "1"}) + ) + assert await asyncio.to_thread(entered.wait, 2) + generation = tool.episode_status()["identity"]["generation"] + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + controller = cu.EpisodeController(tool) + status = controller.fence(generation) + assert status["workers"] == 1 and not status["release_confirmed"] + assert "released" not in indicator.states + queued = await tool.execute({"action": "key", "text": "A"}) + assert not queued.success + proceed.set() + assert await asyncio.to_thread(settled.wait, 2) + result = await controller.end(generation, interrupted=True) + assert result["workers"] == 0 and result["state"] == "interrupted" + assert "released" not in indicator.states + + +def test_failed_release_keeps_custody_and_never_issues_success_notification(rig): + tool, indicator = rig + notifications = [] + ledger = HeldInputLedger( + deadman_seconds=100, on_release=lambda *args: notifications.append(args) + ) + tool._ledger = ledger + tool.begin_episode() + + def fail(): + raise RuntimeError("inert release failure") + + # Even legacy callers explicitly passing false must retain failed custody. + ledger.hold("key", "owned", fail, retain_on_failure=False) + assert ledger.release_all() == [] + assert ledger.held_tokens == ["owned"] and notifications == [] + first = tool.end_episode() + second = tool.end_episode() + assert first["state"] == second["state"] == "interrupted" + assert not first["release_confirmed"] and not second["release_confirmed"] + assert "released" not in indicator.states + ledger.stop() + + +@run_async +async def test_second_owner_and_stale_scope_cannot_touch_new_generation(rig): + tool, _ = rig + controller = cu.EpisodeController(tool) + first = await controller.begin() + old = first["identity"]["generation"] + sibling = cu.ComputerTool(tool._backend, {"_indicator_factory": Indicator}) + sibling._episode_enabled = True + sibling._announced = True + with pytest.raises(cu.BackendError, match="another controller"): + sibling.begin_episode() + with pytest.raises(cu.BackendError, match="stale"): + tool.end_episode("not-the-owner") + assert (await controller.end(old))["state"] == "released" + second = await controller.begin() + assert second["identity"]["generation"] != old + with pytest.raises(cu.BackendError, match="stale"): + controller.fence(old) + # Existing descendant context cannot silently attach to a new sponsor. + token = cu._episode_scope.set((tool, old)) + try: + result = await tool.execute({"action": "key", "text": "A"}) + assert not result.success and "stale" in result.error["message"] + finally: + cu._episode_scope.reset(token) + + +@pytest.mark.parametrize("loss", ["expiry", "helper"]) +def test_watchdog_fences_without_held_input_or_next_call(loss): + indicator = Indicator() + now = [1.0] + episode = Episode( + "target", + lambda: indicator, + lambda: True, + clock=lambda: now[0], + lease_seconds=0.1, + ) + identity = {"owner": "owner", "target": "target", "generation": "generation"} + episode.begin(identity) + if loss == "expiry": + now[0] = 2.0 + else: + indicator.healthy = False + wait_for(lambda: episode.status()["state"] == "interrupted") + with pytest.raises(EpisodeError): + episode.heartbeat(identity) + with pytest.raises(EpisodeError), episode.admit(identity): + pytest.fail("fenced episode admitted") + assert "released" not in indicator.states + + +def test_remote_revocation_not_queued_behind_native_dispatch_and_no_replay(): + backend, indicator = _FakeBackend(), Indicator() + agent = RemoteAgent( + backend, + read_only=False, + require_episode=True, + indicator_factory=lambda: indicator, + ) + identity = { + "owner": "owner", + "target": agent._episode_target, + "generation": new_episode_generation(), + } + assert agent._dispatch(Request(1, "episode_begin", {"identity": identity})).ok + entered, proceed = threading.Event(), threading.Event() + calls = [] + + def blocked(combo): + entered.set() + assert proceed.wait(3) + calls.append(combo) + + backend.key = blocked + worker = threading.Thread( + target=agent._dispatch, + args=(Request(2, "key", {"combo": "A", "_episode": identity}),), + ) + worker.start() + assert entered.wait(2) + # Exactly the reader-side production notice path, while dispatch is blocked. + assert agent._episode_notice(Request(3, "episode_revoke", {"identity": identity})) + assert not agent._dispatch( + Request(4, "key", {"combo": "B", "_episode": identity}) + ).ok + assert agent._episode.status()["workers"] == 1 + assert "released" not in indicator.states + proceed.set() + worker.join(2) + end = agent._dispatch(Request(5, "episode_end", {"identity": identity})) + assert end.ok and end.result["state"] == "released" + assert calls == ["A"] # no input retry after an unknown/lost reply + + +def test_remote_notify_uses_write_lock_not_response_lock(): + transport = SshTransport.__new__(SshTransport) + transport._lock = threading.Lock() + transport._write_lock = threading.Lock() + + class Process: + stdin = io.BytesIO() + + transport._proc = Process() + with transport._lock: + transport.notify(Request(1, "episode_revoke", {"identity": {}}).encode()) + assert json.loads(transport._proc.stdin.getvalue())["op"] == "episode_revoke" + + +@run_async +async def test_production_mount_exports_trusted_controller_and_cleanup( + rig, monkeypatch +): + tool, _ = rig + monkeypatch.setattr(cu, "_select_and_build", lambda cfg: tool) + coordinator = MockCoordinator() + mounted = await cu.mount(coordinator) + controller = coordinator.get_capability("computer_use.episodes") + status = await controller.begin() + generation = status["identity"]["generation"] + with controller.bind(generation): + assert (await tool.execute({"action": "screenshot"})).success + await mounted() + assert not tool.episode_status()["admission_open"] + assert coordinator.get_capability("computer_use.episodes") is None + + +@pytest.mark.parametrize("replacement", [False, True]) +@run_async +async def test_late_remote_begin_reply_cannot_clear_host_fence_with_notice_delayed( + replacement, +): + tool, agent, target = remote_rig() + if replacement: + tool.begin_episode() + assert tool.end_episode()["state"] == "released" + backend = tool._backend + transport = backend._transport + send = transport.send + target_ready, release_reply = threading.Event(), threading.Event() + notices = [] + + def delayed_send(line): + response = send(line) + if json.loads(line)["op"] == "episode_begin": + target_ready.set() + assert release_reply.wait(3) + return response + + transport.send = delayed_send + transport.notify = lambda line: notices.append(line) + keys = [] + target.key = keys.append + controller = cu.EpisodeController(tool) + beginning = asyncio.create_task(controller.begin()) + assert await asyncio.to_thread(target_ready.wait, 2) + generation = tool._episode_identity["generation"] + assert agent._episode.status()["admission_open"] + controller.fence(generation, interrupted=True) + release_reply.set() + with pytest.raises(cu.BackendError, match="fenced"): + await beginning + assert backend._episode_fenced + assert controller.cached_status()["state"] == "interrupted" + result = await tool.execute({"action": "key", "text": "A"}) + assert not result.success and keys == [] + for line in notices: + agent._episode_notice(Request(**json.loads(line))) + transport.notify = lambda line: agent._episode_notice(Request(**json.loads(line))) + await controller.end(generation, interrupted=True) + tool._ledger.stop() + + +def test_lost_begin_reply_reconciles_status_without_replaying_begin(): + backend = RemoteBackend() + identity = {"owner": "owner", "target": "target", "generation": "generation"} + calls = [] + + def call(op, **kwargs): + calls.append(op) + if op == "episode_begin": + raise cu.BackendError("lost reply") + return {"identity": identity, "state": "viewing", "workers": 0} + + backend._call = call + with pytest.raises(cu.BackendError): + backend.begin_episode(identity) + assert backend.episode_status(identity)["identity"] == identity + assert calls == ["episode_begin", "episode_status"] + + +@pytest.mark.parametrize("loss", ["expiry", "helper"]) +def test_end_and_cached_status_check_deadline_before_watchdog_tick(loss): + indicator = Indicator() + clock = [0.0] + episode = Episode("t", lambda: indicator, lambda: True, clock=lambda: clock[0]) + identity = {"owner": "o", "target": "t", "generation": "g"} + episode.begin(identity) + if loss == "expiry": + clock[0] = 10.01 + else: + indicator.healthy = False + result = episode.end(identity) + assert result["state"] == "interrupted" + assert "released" not in indicator.states + assert not episode.status()["admission_open"] + + +def test_indicator_upgrade_exception_is_sticky(): + indicator = Indicator() + update = indicator.update + + def fail(state): + if state == "controlling": + raise RuntimeError("unknown indicator acknowledgement") + return update(state) + + indicator.update = fail + episode = Episode("t", lambda: indicator, lambda: True) + identity = {"owner": "o", "target": "t", "generation": "g"} + episode.begin(identity) + with pytest.raises(EpisodeError), episode.admit(identity, controlling=True): + pytest.fail("admitted without indicator") + indicator.update = update + with pytest.raises(EpisodeError): + episode.heartbeat(identity) + assert episode.end(identity)["state"] == "interrupted" + + +@pytest.mark.parametrize("surface", ["computer", "desktop"]) +@run_async +async def test_call_queued_at_band_cannot_attach_replacement_generation( + rig, monkeypatch, surface +): + tool, _ = rig + entered, proceed = asyncio.Event(), asyncio.Event() + acquire = tool._acquire_batch_band + + async def gate(): + entered.set() + await proceed.wait() + return await acquire() + + monkeypatch.setattr(tool, "_acquire_batch_band", gate) + tool._backend.get_clipboard = lambda: "inert" + target = tool if surface == "computer" else cu.DesktopTool(tool) + payload = ( + {"action": "key", "text": "A"} + if surface == "computer" + else {"action": "get_clipboard"} + ) + queued = asyncio.create_task(target.execute(payload)) + await asyncio.wait_for(entered.wait(), 2) + old = tool.episode_status()["identity"]["generation"] + assert (await asyncio.to_thread(tool.end_episode, old))["state"] == "released" + tool.begin_episode(explicit=True) + proceed.set() + assert not (await queued).success + assert tool._backend.calls == [] + + +def test_reader_revoke_overtaking_queued_begin_remains_fenced(): + indicator = Indicator() + agent = RemoteAgent( + _FakeBackend(), require_episode=True, indicator_factory=lambda: indicator + ) + identity = { + "owner": "o", + "target": agent._episode_target, + "generation": new_episode_generation(), + } + lines = queue.Queue() + entered, proceed, revoked = threading.Event(), threading.Event(), threading.Event() + dispatch, notice = agent._dispatch, agent._episode_notice + + def gated(req): + if req.op == "episode_begin": + entered.set() + assert proceed.wait(3) + return dispatch(req) + + def observed(req): + result = notice(req) + if req.op == "episode_revoke": + revoked.set() + return result + + agent._dispatch, agent._episode_notice = gated, observed + + class Input: + def __iter__(self): + while (line := lines.get()) is not None: + yield line + + stdout = io.StringIO() + worker = threading.Thread(target=agent.run, args=(Input(), stdout)) + worker.start() + lines.put(Request(1, "episode_begin", {"identity": identity}).encode()) + assert entered.wait(2) + lines.put(Request(2, "episode_revoke", {"identity": identity}).encode()) + assert revoked.wait(2) + lines.put(Request(3, "key", {"combo": "A", "_episode": identity}).encode()) + proceed.set() + lines.put(Request(4, "bye").encode()) + lines.put(None) + worker.join(3) + assert not worker.is_alive() + replies = { + row["id"]: row for row in map(json.loads, stdout.getvalue().splitlines()) + } + assert replies[1]["ok"] is False and replies[3]["ok"] is False + assert 2 not in replies # one-way notice never disturbs response framing + + +def remote_rig(): + target = _FakeBackend() + agent = RemoteAgent( + target, read_only=False, require_episode=True, indicator_factory=Indicator + ) + + class Transport: + user_host = "inert" + port = None + + def send(self, line): + req = json.loads(line) + return agent._dispatch(Request(**req)).encode() + + def notify(self, line): + agent._episode_notice(Request(**json.loads(line))) + + backend = RemoteBackend({"_transport": Transport()}) + backend._transport.agent = agent + backend._connected = True + backend.handshake = {"episode_target": agent._episode_target} + tool = cu.ComputerTool(backend, {"read_only": False, "gate_writes": False}) + tool._episode_enabled = True + tool._announced = True + tool.resolve_display() + tool._ledger = HeldInputLedger(deadman_seconds=100) + return tool, agent, target + + +@run_async +async def test_remote_target_release_reconciles_controller_without_replaying_up(): + tool, agent, target = remote_rig() + assert ( + await tool.execute({"action": "left_mouse_down", "coordinate": [1, 1]}) + ).success + assert tool._mouse_pending + result = await asyncio.to_thread(tool.end_episode) + assert result["state"] == "released" + assert not tool._mouse_pending and tool._ledger.held_tokens == [] + assert not agent._ledger.held_tokens and len(target.mouse_ups) == 1 + tool._ledger.release_all() + assert len(target.mouse_ups) == 1 + tool._ledger.stop() + + +def test_public_end_fences_before_waiting_sponsor_status_lock(): + tool, agent, _ = remote_rig() + tool.begin_episode() + entered, proceed, ending = threading.Event(), threading.Event(), threading.Event() + status = tool._episode.episode_status + + def blocked(identity): + entered.set() + assert proceed.wait(3) + return status(identity) + + tool._episode.episode_status = blocked + begin_worker = threading.Thread(target=lambda: _ignore_error(tool.begin_episode)) + begin_worker.start() + assert entered.wait(2) + + def end(): + ending.set() + tool.end_episode() + + end_worker = threading.Thread(target=end) + end_worker.start() + assert ending.wait(1) + wait_for(lambda: tool._episode._episode_fenced) + wait_for(lambda: not agent._episode.status()["admission_open"]) + proceed.set() + begin_worker.join(3) + end_worker.join(3) + assert not end_worker.is_alive() + tool._ledger.stop() + + +def _ignore_error(function): + try: + function() + except Exception: + pass + + +@run_async +async def test_cleanup_owns_pending_start_and_no_active_publish_after_close( + rig, monkeypatch +): + tool, indicator = rig + entered, proceed = threading.Event(), threading.Event() + start = indicator.start + + def blocked(state="viewing"): + entered.set() + assert proceed.wait(3) + return start(state) + + indicator.start = blocked + backend_closes = [] + tool._backend.close = lambda: backend_closes.append(True) + monkeypatch.setattr(cu, "_select_and_build", lambda cfg: tool) + coordinator = MockCoordinator() + mounted = await cu.mount(coordinator) + controller = coordinator.get_capability("computer_use.episodes") + beginning = asyncio.create_task(controller.begin()) + assert await asyncio.to_thread(entered.wait, 2) + cleaning = asyncio.create_task(mounted()) + await asyncio.sleep(0.02) + assert not cleaning.done() and not backend_closes + assert controller.cached_status()["admission_open"] is False + proceed.set() + with pytest.raises((EpisodeError, cu.BackendError)): + await beginning + await cleaning + assert indicator.closed and backend_closes == [True] + assert not tool.episode_status()["admission_open"] + assert coordinator.get_capability("computer_use.episodes") is None + + +@run_async +async def test_cleanup_retains_capability_and_backend_until_indicator_settles( + rig, monkeypatch +): + tool, indicator = rig + backend_closes = [] + tool._backend.close = lambda: backend_closes.append(True) + real_close = indicator.close + indicator.close = lambda: { + "closed": False, + "surface_absent": False, + "process_settled": False, + "helper_exit": None, + } + monkeypatch.setattr(cu, "_select_and_build", lambda cfg: tool) + coordinator = MockCoordinator() + mounted = await cu.mount(coordinator) + controller = coordinator.get_capability("computer_use.episodes") + await controller.begin() + with pytest.raises(RuntimeError, match="indicator settlement"): + await mounted() + status = controller.cached_status() + assert status["release_confirmed"] is True + assert status["indicator_settled"] is False + assert status["state"] == "interrupted" + assert not backend_closes + assert coordinator.get_capability("computer_use.episodes") is controller + indicator.close = real_close + await mounted() + assert backend_closes == [True] + assert coordinator.get_capability("computer_use.episodes") is None + + +@run_async +async def test_remote_end_drains_controller_late_hold_registration(rig, monkeypatch): + tool, agent, target = remote_rig() + entered, proceed = threading.Event(), threading.Event() + register = tool._hold_mouse_button + + def delayed(*args, **kwargs): + entered.set() + assert proceed.wait(3) + return register(*args, **kwargs) + + monkeypatch.setattr(tool, "_hold_mouse_button", delayed) + down = asyncio.create_task( + tool.execute({"action": "left_mouse_down", "coordinate": [1, 1]}) + ) + assert await asyncio.to_thread(entered.wait, 2) + ending = asyncio.create_task(asyncio.to_thread(tool.end_episode)) + await asyncio.sleep(0.02) + assert not ending.done() + assert tool._episode_workers == 1 + assert len(target.mouse_downs) == 1 + proceed.set() + assert (await down).success + result = await ending + assert result["state"] == "released" + assert tool._episode_workers == 0 and not tool._mouse_pending + assert not tool._ledger.held_tokens and not agent._ledger.held_tokens + assert len(target.mouse_ups) == 1 + tool.begin_episode(explicit=True) + tool._ledger._on_deadman() + assert len(target.mouse_ups) == 1 # no stale cleanup can touch a new generation + tool.end_episode() + tool._ledger.stop() + + +@run_async +async def test_explicit_fresh_generation_after_settled_stop_not_old_token_revival(rig): + tool, _ = rig + controller = cu.EpisodeController(tool) + first = await controller.begin() + old = first["identity"]["generation"] + controller.fence(old, interrupted=True) + stopped = await controller.end(old, interrupted=True) + assert stopped["release_confirmed"] and stopped["indicator_settled"] + assert stopped["state"] == "interrupted" + assert not (await tool.execute({"action": "screenshot"})).success + # Host Resume supplies a fresh explicit begin, not a heartbeat/old binding. + resumed = await controller.begin() + assert resumed["identity"]["generation"] != old + with pytest.raises(cu.BackendError): + controller.fence(old) + with controller.bind(resumed["identity"]["generation"]): + assert (await tool.execute({"action": "screenshot"})).success + + +def test_remote_more_than_129_normal_generations_do_not_disconnect(): + tool, agent, _ = remote_rig() + for _ in range(132): + tool.begin_episode(explicit=True) + ended = tool.end_episode() + assert ended["state"] == "released" + assert not agent._disconnected.is_set() + tool._ledger.stop() + + +@pytest.mark.parametrize("remote", [False, True]) +@pytest.mark.parametrize("failure", ["stop", "expiry", "failed_start"]) +@run_async +async def test_fresh_explicit_recovery_after_terminal_failure(rig, remote, failure): + local, _ = rig + tool = remote_rig()[0] if remote else local + controller = cu.EpisodeController(tool) + original_factory = tool._cfg.get("_indicator_factory") + agent = None + if remote: + # Use the actual RemoteAgent owned by the in-memory transport. + agent = tool._backend._transport.agent + factories = [] + + def factory(): + indicator = Indicator() + if failure == "failed_start" and not factories: + indicator.healthy = False + factories.append(indicator) + return indicator + + if remote: + agent._indicator_factory = factory + else: + tool._cfg["_indicator_factory"] = factory + if failure == "failed_start": + with pytest.raises((cu.BackendError, EpisodeError)): + await controller.begin() + else: + await controller.begin() + old = tool._episode_identity["generation"] + if failure == "expiry": + episode = agent._episode if remote else tool._episode + episode._deadline = time.monotonic() - 1 + assert episode.status()["state"] == "interrupted" + else: + controller.fence(old, interrupted=True) + ended = await controller.end(old, interrupted=True) + assert ended["state"] == "interrupted" + assert ended["release_confirmed"] and ended["indicator_settled"] + assert not (await tool.execute({"action": "key", "text": "A"})).success + resumed = await controller.begin() + fresh = resumed["identity"]["generation"] + assert fresh != old + with pytest.raises((cu.BackendError, EpisodeError)): + await controller.heartbeat(old) + with controller.bind(fresh): + if remote: + assert ( + await cu.DesktopTool(tool).execute({"action": "get_clipboard"}) + ).success + else: + assert (await tool.execute({"action": "screenshot"})).success + await controller.end(fresh) + if remote: + tool._ledger.stop() + elif original_factory is not None: + tool._cfg["_indicator_factory"] = original_factory + + +@run_async +async def test_recovery_requires_settlement_and_preserves_durable_halt(rig): + tool, _ = rig + controller = cu.EpisodeController(tool) + old = (await controller.begin())["identity"]["generation"] + controller.fence(old) + with pytest.raises(cu.BackendError): + await controller.begin() # Terminal label alone isn't release evidence. + await controller.end(old, interrupted=True) + guard = object() + tool._coexistence_guard = guard + await controller.begin() + assert tool._coexistence_guard is guard # No guard replacement/halt reset. + + +def test_remote_highwater_refuses_retired_replays_and_late_wrong_owner_revokes(): + tool, agent, _ = remote_rig() + old = tool.begin_episode()["identity"] + tool.end_episode() + current = tool.begin_episode(explicit=True)["identity"] + # Current target remains active; stale begin never recaptures a new panel. + assert not agent._dispatch(Request(100, "episode_begin", {"identity": old})).ok + for identity in (old, {**current, "owner": "other"}): + agent._episode_notice(Request(101, "episode_revoke", {"identity": identity})) + assert agent._episode.status()["admission_open"] + assert not agent._dispatch(Request(102, "key", {"combo": "A", "_episode": old})).ok + assert agent._dispatch(Request(103, "key", {"combo": "A", "_episode": current})).ok + assert len(agent._revoked_generations) == 0 + tool.end_episode() + tool._ledger.stop() + + +def test_remote_run_finally_stops_ledger_even_if_indicator_close_raises(): + agent = RemoteAgent(_FakeBackend()) + released = [] + agent._ledger.hold("key", "owned", lambda: released.append(True)) + + class BrokenEpisode: + def status(self): + return {"identity": {}} + + def fence(self, *args, **kwargs): + pass + + def close(self, identity): + raise RuntimeError("inert renderer close failure") + + agent._episode = BrokenEpisode() + with pytest.raises(RuntimeError, match="renderer close"): + agent.run(io.StringIO(""), io.StringIO()) + assert released == [True] + assert not agent._ledger.held_tokens + + +def test_ordered_pending_revoke_compaction_preserves_late_begin_fence(): + tool, agent, _ = remote_rig() + identities = [] + for _ in range(132): + identity = { + "owner": "pending", + "target": agent._episode_target, + "generation": new_episode_generation(), + } + identities.append(identity) + agent._episode_notice(Request(1, "episode_revoke", {"identity": identity})) + assert not agent._dispatch( + Request(2, "episode_begin", {"identity": identity}) + ).ok + assert not agent._disconnected.is_set() + assert len(agent._revoked_generations) == 0 + for identity in (identities[0], identities[-1]): + assert not agent._dispatch( + Request(3, "episode_begin", {"identity": identity}) + ).ok + assert tool.begin_episode()["state"] == "viewing" + tool.end_episode() + tool._ledger.stop() + + +def test_normal_generations_across_shared_transport_owners_use_same_order_domain(): + first, agent, _ = remote_rig() + other_backend = RemoteBackend({"_transport": first._backend._transport}) + other_backend._connected = True + other_backend.handshake = first._backend.handshake + second = cu.ComputerTool(other_backend, {"read_only": False, "gate_writes": False}) + second._episode_enabled = True + second._announced = True + for index in range(132): + owner = first if index % 2 == 0 else second + assert owner.begin_episode(explicit=True)["state"] == "viewing" + assert owner.end_episode()["indicator_settled"] + assert not agent._disconnected.is_set() + first._ledger.stop() + + +@pytest.mark.parametrize("previous", [False, True]) +@pytest.mark.parametrize("refusal", ["revoked", "other_owner"]) +@pytest.mark.parametrize("disposition", ["recover", "cleanup"]) +@run_async +async def test_definitive_remote_begin_refusal_settles_only_rejected_owner( + monkeypatch, previous, refusal, disposition +): + tool, agent, target = remote_rig() + controller = cu.EpisodeController(tool) + if previous: + old = (await controller.begin())["identity"]["generation"] + await controller.end(old) + other = None + if refusal == "other_owner": + other = { + "owner": "other", + "target": agent._episode_target, + "generation": new_episode_generation(), + } + assert agent._dispatch(Request(1, "episode_begin", {"identity": other})).ok + assert agent._dispatch( + Request(2, "mouse_down", {"button": "left", "_episode": other}) + ).ok + held = list(agent._ledger.held_tokens) + ups = list(target.mouse_ups) + transport = tool._backend._transport + send = transport.send + calls = [] + + def refused_begin(line): + request = Request(**json.loads(line)) + calls.append(request.op) + if request.op == "episode_begin" and refusal == "revoked": + agent._episode_notice( + Request(99, "episode_revoke", {"identity": request.args["identity"]}) + ) + return send(line) + + monkeypatch.setattr(transport, "send", refused_begin) + closes = [] + monkeypatch.setattr(transport, "close", lambda: closes.append(True), raising=False) + try: + with pytest.raises(cu.BackendError): + await controller.begin() + identity = dict(tool._episode_identity) + # The refusal remains a failed task, not an invented Released badge. + status = await controller.status() + assert status["identity"] == identity and status["state"] == "interrupted" + assert status["target_adopted"] is False + assert status["release_confirmed"] and status["indicator_settled"] + assert not (await tool.execute({"action": "key", "text": "A"})).success + result = await controller.end(identity["generation"], interrupted=True) + assert result["release_confirmed"] and result["workers"] == 0 + assert calls.count("episode_begin") == 1 # Queries/end never replay begin. + assert agent._ledger.held_tokens == held and target.mouse_ups == ups + assert not agent._dispatch( + Request(100, "key", {"combo": "A", "_episode": identity}) + ).ok + assert not agent._dispatch( + Request(101, "episode_begin", {"identity": identity}) + ).ok + if disposition == "cleanup": + monkeypatch.setattr(cu, "_select_and_build", lambda cfg: tool) + mounted = await cu.mount(MockCoordinator()) + await mounted() + assert closes == [True] + assert agent._ledger.held_tokens == held and target.mouse_ups == ups + if other: + assert agent._episode.status(other)["admission_open"] + return + if other: + assert agent._episode.status(other)["admission_open"] + assert agent._dispatch(Request(102, "episode_end", {"identity": other})).ok + monkeypatch.setattr(transport, "send", send) + fresh = await controller.begin() + assert fresh["identity"] != identity + await controller.end(fresh["identity"]["generation"]) + finally: + if agent._episode: + agent._episode.close(agent._episode.status()["identity"]) + tool._ledger.stop() + + +@pytest.mark.parametrize( + "fault", + [ + "lost_refusal", + "lost_adopted", + "generic_error", + "wrong_id", + "wrong_identity", + "extra", + "adopted", + "bad_reason", + ], +) +@run_async +async def test_remote_begin_without_exact_refusal_proof_retains_unknown_custody( + monkeypatch, fault +): + tool, agent, target = remote_rig() + backend = tool._backend + transport = backend._transport + send = transport.send + calls = [] + + def corrupted(line): + request = Request(**json.loads(line)) + calls.append(request.op) + if request.op != "episode_begin": + return send(line) + if fault != "lost_adopted": + agent._episode_notice( + Request(99, "episode_revoke", {"identity": request.args["identity"]}) + ) + raw = json.loads(send(line)) + if fault.startswith("lost"): + raise cu.BackendError("inert missing reply") + if fault == "generic_error": + raw["error"].pop("data") + elif fault == "wrong_id": + raw["id"] += 100 + else: + data = raw["error"]["data"] + if fault == "wrong_identity": + data["identity"]["owner"] = "not-this-owner" + elif fault == "extra": + data["extra"] = True + elif fault == "adopted": + data["adopted"] = True + else: + data["reason"] = [] + return json.dumps(raw).encode() + + monkeypatch.setattr(transport, "send", corrupted) + try: + with pytest.raises((cu.BackendError, ValueError)): + await cu.EpisodeController(tool).begin() + assert backend._episode_fenced + status = cu.EpisodeController(tool).cached_status() + assert status["admission_open"] is False + assert not status["release_confirmed"] + assert not status["indicator_settled"] + with pytest.raises(cu.BackendError): + backend.key("A") + assert calls == ["episode_begin"] + if fault == "lost_adopted": + # Reconcile actual adoption by query/end, never a repeated begin. + result = tool.end_episode(interrupted=True) + assert result["release_confirmed"] + else: + with pytest.raises(cu.BackendError): + tool.end_episode(interrupted=True) + assert not backend._episode_status_cache["release_confirmed"] + finally: + if agent._episode: + agent._episode.close(agent._episode.status()["identity"]) + tool._ledger.stop() + + +@run_async +async def test_not_adopted_receipt_cannot_ack_controller_pending_input(monkeypatch): + tool, agent, _ = remote_rig() + transport = tool._backend._transport + send = transport.send + + def revoked(line): + request = Request(**json.loads(line)) + if request.op == "episode_begin": + agent._episode_notice( + Request(99, "episode_revoke", {"identity": request.args["identity"]}) + ) + return send(line) + + monkeypatch.setattr(transport, "send", revoked) + try: + with pytest.raises(cu.BackendError): + await cu.EpisodeController(tool).begin() + tool._mouse_pending["mouse:left"] = {} + releases = [] + tool._ledger.hold("mouse", "mouse:left", lambda: releases.append(True)) + assert not tool.episode_status()["release_confirmed"] + assert not cu.EpisodeController(tool).cached_status()["release_confirmed"] + assert not tool.end_episode()["release_confirmed"] + assert tool._ledger.held_tokens == ["mouse:left"] and releases == [] + finally: + tool._mouse_pending.clear() + tool._ledger.stop() + + +def test_begin_refusal_wire_roundtrip_and_adopted_or_invalid_have_no_proof(): + tool, agent, _ = remote_rig() + current = tool.begin_episode()["identity"] + try: + agent._episode.fence(current) + # Already-adopted/fenced generations must never get no-adoption proof. + adopted = agent._dispatch(Request(10, "episode_begin", {"identity": current})) + assert not adopted.ok and adopted.error_data is None + malformed = agent._dispatch( + Request(11, "episode_begin", {"identity": {**current, "target": "wrong"}}) + ) + assert not malformed.ok and malformed.error_data is None + rejected = {**current, "generation": new_episode_generation()} + response = agent._dispatch(Request(12, "episode_begin", {"identity": rejected})) + assert not response.ok and response.error_type == "EpisodeBeginRefused" + decoded = Response.decode(response.encode()) + assert decoded == response + assert decoded.error_data["identity"] == rejected + assert decoded.error_data["adopted"] is False + replay = agent._dispatch(Request(13, "episode_begin", {"identity": rejected})) + assert not replay.ok and replay.error_data is None + finally: + tool.end_episode(interrupted=True) + tool._ledger.stop() + + +@run_async +async def test_public_episode_begin_unsupported_does_not_allocate_or_break_cleanup( + monkeypatch, +): + tool = cu.ComputerTool(Backend()) + + def no_disclosure(): + pytest.fail("unsupported lifecycle must not allocate a disclosure surface") + + monkeypatch.setattr(tool, "_ensure_announced", no_disclosure) + result = await cu.DesktopTool(tool).execute({"action": "begin_episode"}) + assert result.output["state"] == "unavailable" + assert tool._episode is None and tool._episode_identity is None + + +@pytest.mark.parametrize( + "mode", ["console_unavailable", "console_user_mismatch", "die", "stale"] +) +@run_async +async def test_actual_adapter_failure_settlement_allows_bundle_cleanup( + rig, monkeypatch, mode +): + from test_macos_indicator import inert_indicator + + tool, _ = rig + indicator = inert_indicator(monkeypatch, mode) + tool._cfg["_indicator_factory"] = lambda: indicator + backend_closes = [] + tool._backend.close = lambda: backend_closes.append(True) + monkeypatch.setattr(cu, "_select_and_build", lambda cfg: tool) + coordinator = MockCoordinator() + mounted = await cu.mount(coordinator) + controller = coordinator.get_capability("computer_use.episodes") + try: + with pytest.raises((cu.BackendError, EpisodeError)): + await controller.begin() + snapshot = indicator.status() + assert snapshot["state"] == "interrupted" and not snapshot["healthy"] + assert snapshot["fault_settled"] and snapshot["process_settled"] + assert not snapshot["surface_absent"] # Resource proof != native pixels/ack. + await mounted() + status = tool.episode_status() + assert status["state"] == "interrupted" + assert status["release_confirmed"] and status["indicator_settled"] + assert backend_closes == [True] + finally: + indicator.abort() + if indicator._proc is not None and indicator._proc.stderr: + indicator._proc.stderr.close() + + +@pytest.mark.parametrize( + "outcome", ["unknown", "wait_error", "no_returncode", "killed", "never_launched"] +) +def test_actual_adapter_resource_faults_reconcile_without_fabricated_release(outcome): + from test_macos_indicator import SettlementProcess, adapter + + indicator = adapter.MacOSIndicator() + if outcome != "never_launched": + indicator._proc = SettlementProcess(outcome) + indicator._fail("reply_timeout") + identity = {"owner": "o", "target": "t", "generation": "g"} + episode = Episode("t", lambda: indicator, lambda: True) + with pytest.raises(EpisodeError): + episode.begin(identity) + result = episode.close(identity) + assert result["state"] == "interrupted" and result["release_confirmed"] + if outcome in {"killed", "never_launched"}: + assert result["indicator_settled"] + else: + assert not result["indicator_settled"] + indicator._proc.outcome = "exit" + assert episode.close(identity)["indicator_settled"] + assert not indicator.status()["surface_absent"] + assert not indicator.status()["healthy"] + + +def test_fault_settlement_cannot_retire_unconfirmed_held_input(): + from test_macos_indicator import adapter + + indicator = adapter.MacOSIndicator() + indicator._fail("reply_timeout") + indicator.close() + assert indicator.status()["fault_settled"] + identity = {"owner": "o", "target": "t", "generation": "g"} + episode = Episode("t", lambda: indicator, lambda: False) + with pytest.raises(EpisodeError): + episode.begin(identity) + result = episode.close(identity) + assert not result["release_confirmed"] and not result["indicator_settled"] + + +@pytest.mark.parametrize("late_count", [1, 3]) +def test_old_already_entered_drains_cannot_release_new_owner_hold(rig, late_count): + tool, _ = rig + ledger = HeldInputLedger(deadman_seconds=100) + tool._ledger = ledger + tool.begin_episode() + episode, identity = tool._episode, tool._episode_identity + episode.fence(identity) + entered = [threading.Event() for _ in range(late_count)] + proceed = threading.Event() + transition = episode._transition + + class Gate: + def __enter__(self): + name = threading.current_thread().name + if name.startswith("old-drain-"): + entered[int(name.rsplit("-", 1)[1])].set() + assert proceed.wait(3) + transition.acquire() + + def __exit__(self, *_): + transition.release() + + episode._transition = Gate() + late = [ + threading.Thread( + target=episode.end, args=(identity,), name=f"old-drain-{index}" + ) + for index in range(late_count) + ] + for thread in late: + thread.start() + assert all(event.wait(2) for event in entered) + assert tool.end_episode(interrupted=True)["indicator_settled"] + fresh = tool.begin_episode(explicit=True)["identity"] + released = [] + ledger.hold("mouse", "new-owner", lambda: released.append(True)) + try: + proceed.set() + for thread in late: + thread.join(2) + assert not thread.is_alive() + assert fresh != identity + assert released == [] and ledger.held_tokens == ["new-owner"] + finally: + proceed.set() + ledger.stop() + + +@pytest.mark.parametrize("settled", [False, True]) +def test_retarget_from_interrupted_requires_full_settlement(rig, monkeypatch, settled): + from test_retarget import _FakeLocalBackend + + tool, indicator = rig + tool.begin_episode() + tool.fence_episode(tool._episode_identity["generation"]) + close = indicator.close + if not settled: + indicator.close = lambda: {"closed": False, "process_settled": False} + else: + assert tool.end_episode(interrupted=True)["indicator_settled"] + old_backend = tool._backend + new_backend = _FakeLocalBackend("retarget-settled-interrupted") + selected = [] + + def select(config): + selected.append(config) + return new_backend + + monkeypatch.setattr(cu, "select_backend", select) + result = tool.retarget("local") + assert result.success is settled + if settled: + assert tool._backend is new_backend + assert tool._binding.read_only is False + else: + assert not selected and tool._backend is old_backend + indicator.close = close + + +@pytest.mark.parametrize("failure", ["before_start", "non_os_launch"]) +def test_episode_start_exception_owns_actual_adapter_never_launched_settlement( + monkeypatch, failure +): + from test_macos_indicator import adapter + + indicator = adapter.MacOSIndicator() + + def broken(*args, **kwargs): + raise ValueError("inert non-OS startup failure") + + if failure == "before_start": + monkeypatch.setattr(indicator, "start", broken) + else: + monkeypatch.setattr(adapter.sys, "platform", "darwin") + monkeypatch.setattr(indicator, "_launch", broken) + episode = Episode("t", lambda: indicator, lambda: True) + identity = {"owner": "o", "target": "t", "generation": "g"} + with pytest.raises(ValueError): + episode.begin(identity) + result = episode.close(identity) + assert indicator.status()["settlement_basis"] == "never_launched" + assert indicator.status()["process_settled"] is True + assert result["indicator_settled"] and result["release_confirmed"] + assert result["state"] == "interrupted" and not result["admission_open"] diff --git a/tests/test_ledger.py b/tests/test_ledger.py index 0afe104..5db57b7 100644 --- a/tests/test_ledger.py +++ b/tests/test_ledger.py @@ -91,12 +91,11 @@ def _boom(): result = ledger.release_all() - # Both are considered released (removed from the ledger / no longer - # "held") even though one's release_fn raised - the exception is logged, - # not swallowed silently, but it must not stop the other release. - assert sorted(result) == ["broken", "ok"] + # Failure is retained custody, never a fabricated RELEASED notification. + assert result == ["ok"] assert released == ["ok"] - assert ledger.held_tokens == [] + assert ledger.held_tokens == ["broken"] + ledger.stop() def test_deadman_timer_releases_everything_with_no_activity(): diff --git a/tests/test_macos_indicator.py b/tests/test_macos_indicator.py new file mode 100644 index 0000000..5a24adb --- /dev/null +++ b/tests/test_macos_indicator.py @@ -0,0 +1,970 @@ +"""Headless protocol/adapter/native-shape fakes; NOT Mac pixel qualification.""" + +from __future__ import annotations + +import builtins +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +import threading +import time +import tomllib +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +PACKAGE = ROOT / "modules/tool-computer-use/amplifier_module_tool_computer_use" +sys.path.insert(0, str(PACKAGE.parent)) + +from amplifier_module_tool_computer_use import macos_indicator as adapter +from amplifier_module_tool_computer_use import macos_indicator_helper as helper + + +def command(seq=1, op="start", state="viewing", **extra): + return {"v": 1, "g": "a" * 32, "s": seq, "op": op, "state": state, **extra} + + +def started(): + p = helper.Protocol() + p.accept(command()) + return p + + +class Surface: + def __init__(self): + self.states = [] + self.visible = True + self.absent = True + self.removals = 0 + + def apply(self, state): + self.states.append(state) + + def confirmed(self): + return self.visible + + def remove(self): + self.removals += 1 + return self.absent + + +def runtime(): + now, replies, surface = [10.0], [], Surface() + run = helper.PanelRuntime(started(), surface, replies.append, clock=lambda: now[0]) + return run, now, replies, surface + + +@pytest.mark.parametrize( + "data", + [ + b"{}\n\n", + b'{"v":1,"v":1}\n', + b"[]\n", + b"\xff\n", + b"{}\x00\n", + b"{}", + helper.encode_frame(command()) + b"\n", + b"x" * 513 + b"\n", + b'{"x":NaN}\n', + ], +) +def test_bad_frames(data): + with pytest.raises(helper.ProtocolError): + row = helper.decode_frame(data) + helper.validate_command(row) + + +@pytest.mark.parametrize( + "change", + [ + {"v": True}, + {"s": True}, + {"s": 0}, + {"s": 2**54}, + {"s": 1.0}, + {"g": "../private"}, + {"g": "A" * 32}, + {"state": "typed secret"}, + {"state": []}, + {"op": {}}, + {"prompt": "private"}, + {"op": "status", "state": "viewing"}, + {"op": "arbitrary"}, + ], +) +def test_closed_command_schema(change): + with pytest.raises(helper.ProtocolError, match="^protocol_error$"): + helper.validate_command(command(**change)) + + +@pytest.mark.parametrize( + "key,value", [("reason", []), ("state", {}), ("window", 1), ("loop", True)] +) +def test_closed_reply_schema(key, value): + row = started().reply("ready", window=True, loop=1) + row[key] = value + with pytest.raises(helper.ProtocolError): + helper.validate_reply(row) + + +@pytest.mark.parametrize( + "row", + [ + command(), + command(3, "status", None), + command(2, "status", None, g="b" * 32), + command(2, "start", "controlling"), + ], +) +def test_reject_duplicate_skipped_stale_generation(row): + with pytest.raises(helper.ProtocolError): + started().accept(row) + + +def test_transition_and_terminal_rejection(): + p = started() + for seq, state in enumerate(("controlling", "paused", "viewing", "stopping"), 2): + p.accept(command(seq, "update", state)) + with pytest.raises(helper.ProtocolError): + p.accept(command(6, "update", "viewing")) + p.accept(command(6, "update", "released")) + with pytest.raises(helper.ProtocolError): + p.accept(command(7, "update", "controlling")) + p.accept(command(7, "close", None)) + with pytest.raises(helper.ProtocolError): + p.accept(command(8, "status", None)) + + +@pytest.mark.parametrize( + "op,state", [("status", None), ("close", None), ("update", "released")] +) +def test_helper_late_traffic_before_tick_cannot_renew_expired_lease(op, state): + run, now, replies, surface = runtime() + run.tick() + run.receive(helper.encode_frame(command(2, "update", "released"))) + run.tick() + # The loop stays alive throughout; the separate stalled-loop watchdog is + # irrelevant. Expiry happens between the last tick and late command intake. + now[0] = 13.95 + run.tick() + now[0] = 14.01 + try: + run.receive(helper.encode_frame(command(3, op, state))) + except helper.ProtocolError: + pass + now[0] = 14.05 + run.tick() + assert run.reason == "connection_lost" + assert run.protocol.state == "interrupted" and not run.finished + assert run.last_command == 10.0 and run.protocol.sequence == 2 + assert surface.states[-1] == "interrupted" + assert not any( + row["event"] == "terminal" and row["state"] == "released" for row in replies + ) + + +@pytest.mark.parametrize("op", ["status", "close", "abort"]) +def test_adapter_late_request_without_public_status_cannot_renew_lease(monkeypatch, op): + indicator = inert_indicator(monkeypatch) + try: + assert indicator.start()["healthy"] + with indicator._lock: + indicator._last_reply = time.monotonic() - helper.WATCHDOG_SECONDS - 0.25 + seq = indicator._sequence + result = indicator._request(op) + assert result["state"] == "interrupted" and not result["healthy"] + assert indicator._failed and indicator._sequence == seq + indicator.close() + assert indicator.status()["process_settled"] + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_helper_expiry_during_command_validation_does_not_refresh_or_show_release( + monkeypatch, +): + run, now, replies, surface = runtime() + run.tick() + now[0] = 13.99 + original = helper.validate_command + + def delayed_validation(row): + original(row) + now[0] = 14.01 + + monkeypatch.setattr(helper, "validate_command", delayed_validation) + run.receive(helper.encode_frame(command(2, "update", "released"))) + run.tick() + assert run.reason == "connection_lost" and run.protocol.state == "interrupted" + assert run.last_command == 10.0 and "released" not in surface.states + assert replies[-1]["event"] == "unavailable" + + +@pytest.mark.parametrize("op", ["status", "close"]) +@pytest.mark.parametrize("boundary", ["before_write", "before_reply_renewal"]) +def test_adapter_expiry_during_exchange_cannot_be_refreshed(monkeypatch, op, boundary): + indicator = adapter.MacOSIndicator() + indicator._snapshot.update( + available=True, ready=True, healthy=True, state="released" + ) + indicator._last_reply, indicator._last_loop = 10.0, 1 + clock, writes = [13.99], [] + indicator._proc = SimpleNamespace( + poll=lambda: None, + stdin=SimpleNamespace(fileno=lambda: 101), + stdout=SimpleNamespace(fileno=lambda: 102), + ) + reply = { + "v": 1, + "g": indicator._generation, + "s": 1, + "event": "ack" if op == "status" else "terminal", + "state": "released", + "reason": "ok", + "window": op == "status", + "loop": 2, + } + + def select_ready(readers, writers, errors, timeout): + if writers and boundary == "before_write": + clock[0] = 14.01 + return readers, writers, [] + + def read_reply(_fd, _size): + clock[0] = 14.01 + return helper.encode_frame(reply) + + monkeypatch.setattr(adapter.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(adapter.select, "select", select_ready) + monkeypatch.setattr( + adapter.os, "write", lambda fd, data: writes.append(data) or len(data) + ) + monkeypatch.setattr(adapter.os, "read", read_reply) + result = indicator._request(op) + assert result["state"] == "interrupted" and result["reason"] == "connection_lost" + assert not result["healthy"] and not result["surface_absent"] + assert indicator._last_reply == 10.0 and indicator._failed + assert len(writes) == (boundary == "before_reply_renewal") + assert not indicator._request(op)["healthy"] + assert len(writes) == (boundary == "before_reply_renewal") # No replay. + + +def test_close_expired_without_intervening_public_status_never_sends_handoff( + monkeypatch, +): + indicator = inert_indicator(monkeypatch) + try: + assert indicator.start()["healthy"] + assert indicator.update("released")["state"] == "released" + indicator._stop.set() + indicator._monitor.join(2) + assert not indicator._monitor.is_alive() + indicator._last_reply = time.monotonic() - helper.WATCHDOG_SECONDS - 0.25 + seq = indicator._sequence + result = indicator.close() + assert result["state"] == "interrupted" and result["process_settled"] + assert indicator._failed and indicator._sequence == seq + trace = indicator._proc.stderr.read() + assert b'"op":"close"' not in trace + assert b"final:interrupted" in trace + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_readiness_on_later_loop_and_persistent_reasoning_gap(): + run, now, replies, surface = runtime() + assert replies == [] + surface.visible = False + run.tick() + assert replies == [] + now[0] += 0.1 + surface.visible = True + run.tick() + assert replies[-1]["event"] == "ready" + assert replies[-1]["window"] and replies[-1]["loop"] == 2 + for seq in range(2, 8): + now[0] += 0.5 + run.receive(helper.encode_frame(command(seq, "status", None))) + run.tick() + assert run.protocol.state == "viewing" + assert surface.removals == 0 + assert surface.states == ["viewing"] + + +def test_released_is_explicit_and_stays_until_close_then_absence_ack(): + run, now, replies, surface = runtime() + run.tick() + run.receive(helper.encode_frame(command(2, "update", "released"))) + run.tick() + assert replies[-1]["state"] == "released" + # Long observation dwell needs no test-only production configuration. + for seq in range(3, 65): + now[0] += 0.5 + run.receive(helper.encode_frame(command(seq, "status", None))) + run.tick() + assert not run.finished and surface.removals == 0 + run.receive(helper.encode_frame(command(65, "close", None))) + assert replies[-1]["event"] == "ack" # No acknowledgement merely on receive. + run.tick() + assert run.finished and replies[-1]["event"] == "terminal" + assert replies[-1]["state"] == "released" and not replies[-1]["window"] + + +@pytest.mark.parametrize("op", ["close", "abort"]) +def test_active_teardown_is_interrupted_minimum_dwell(op): + run, now, replies, surface = runtime() + run.tick() + run.receive(helper.encode_frame(command(2, op, None))) + run.tick() + assert surface.states[-1] == "interrupted" and not run.finished + now[0] += helper.TERMINAL_DWELL_SECONDS + run.tick() + assert run.finished and replies[-1]["state"] == "interrupted" + + +@pytest.mark.parametrize("fault", ["watchdog", "parent", "surface", "eof"]) +def test_loss_overrides_release_never_infers_done(monkeypatch, fault): + run, now, replies, surface = runtime() + run.tick() + run.receive(helper.encode_frame(command(2, "update", "released"))) + run.tick() + if fault == "watchdog": + now[0] += helper.WATCHDOG_SECONDS + 0.01 + elif fault == "parent": + monkeypatch.setattr(helper.os, "getppid", lambda: run.parent_pid + 1) + elif fault == "surface": + surface.visible = False + else: + run.interrupt() + run.tick() + assert run.protocol.state == "interrupted" + assert run.protocol.closing + assert surface.states[-1] == "interrupted" + now[0] += helper.TERMINAL_DWELL_SECONDS + 0.01 + run.tick() + assert run.finished + + +def test_failed_surface_removal_cannot_ack_release(): + run, now, replies, surface = runtime() + run.tick() + run.receive(helper.encode_frame(command(2, "update", "released"))) + run.tick() + run.receive(helper.encode_frame(command(3, "close", None))) + surface.absent = False + now[0] += helper.TERMINAL_DWELL_SECONDS + run.tick() + assert not run.finished + now[0] += 0.5 + run.tick() + assert run.finished + assert replies[-1]["reason"] == "surface_unconfirmed" + assert replies[-1]["state"] == "interrupted" + + +def test_console_mismatch_and_no_console_are_closed(monkeypatch): + monkeypatch.setattr(helper.sys, "platform", "darwin") + monkeypatch.setattr(helper.os, "geteuid", lambda: 501) + monkeypatch.setattr(helper.os, "stat", lambda _: SimpleNamespace(st_uid=502)) + assert helper.console_reason() == "console_user_mismatch" + monkeypatch.setattr(helper.os, "stat", lambda _: SimpleNamespace(st_uid=0)) + assert helper.console_reason() == "console_unavailable" + + +def test_missing_cocoa_is_lazy_fixed_reason(monkeypatch): + monkeypatch.setattr(helper, "console_reason", lambda: "ok") + original = builtins.__import__ + + def no_cocoa(name, *args, **kwargs): + if name == "AppKit": + raise ImportError("sensitive local information") + return original(name, *args, **kwargs) + + rows = [] + monkeypatch.setattr(builtins, "__import__", no_cocoa) + monkeypatch.setattr(helper, "_emit", rows.append) + assert helper._native_main(started()) == 2 + assert rows[0]["reason"] == "cocoa_unavailable" + assert "sensitive" not in json.dumps(rows) + + +# This separate test-only subprocess exercises the real framing + runtime over +# anonymous pipes. The production helper has NO inert/fake backend switch. +INERT_DRIVER = r""" +import importlib.util, os, select, sys, time +spec=importlib.util.spec_from_file_location("panel_protocol", sys.argv[1]) +h=importlib.util.module_from_spec(spec); spec.loader.exec_module(h) +h.TERMINAL_DWELL_SECONDS=0.03 +mode=sys.argv[2] +p=h._read_start() +if mode in ("console_unavailable","console_user_mismatch","cocoa_unavailable"): + h._emit(p.reply("unavailable",mode)); sys.exit(2) +if mode=="die": sys.exit(2) +if mode=="timeout": time.sleep(10); sys.exit(2) +class Surface: + def apply(self,state): pass + def confirmed(self): return True + def remove(self): return True +def emit(row): + if mode=="droprelease" and row["state"]=="released": return + if mode=="dieonstatus" and row["event"]=="ack": sys.exit(2) + if mode=="stale": row["s"]-=1 + if mode=="wronggen": row["g"]="b"*32 + if mode=="extra": row["payload"]="forbidden" + if mode=="oversize": os.write(1,b"x"*513); return + if mode=="wrongloop": row["loop"]=0 + if mode=="wrongstate": row["state"]="released" + h._emit(row) +r=h.PanelRuntime(p,Surface(),emit) +os.set_blocking(0,False); os.set_blocking(1,False) +buf=b"" +while not r.finished: + ready,_,_=select.select([0],[],[],0.01) + if ready: + data=os.read(0,513) + if not data: r.interrupt() + else: + buf+=data + if b"\n" in buf: + line,buf=buf.split(b"\n",1) + os.write(2,line+b"\n") + try: r.receive(line+b"\n") + except h.ProtocolError: r.interrupt("protocol_error") + r.tick() +os.write(2,("final:"+p.state+"\n").encode()) +if mode=="terminalhung": time.sleep(10) +sys.exit(0 if p.state=="released" and r.reason=="ok" else 2) +""" + + +def inert_indicator(monkeypatch, mode="ok"): + indicator = adapter.MacOSIndicator() + monkeypatch.setattr(adapter.sys, "platform", "darwin") + + def launch(): + proc = subprocess.Popen( + [ + sys.executable, + "-u", + "-c", + INERT_DRIVER, + str(PACKAGE / "macos_indicator_helper.py"), + mode, + ], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + bufsize=0, + ) + os.set_blocking(proc.stdin.fileno(), False) + os.set_blocking(proc.stdout.fileno(), False) + return proc + + monkeypatch.setattr(indicator, "_launch", launch) + return indicator + + +def test_inert_adapter_entire_lifecycle_and_background_heartbeat(monkeypatch): + indicator = inert_indicator(monkeypatch) + try: + result = indicator.start("viewing") + assert result["available"] and result["ready"] and result["healthy"] + seq = result["sequence"] + deadline = time.monotonic() + 2 + while indicator.status()["sequence"] == seq and time.monotonic() < deadline: + time.sleep(0.01) + assert indicator.status()["sequence"] > seq # No model status polling needed. + for state in ("controlling", "paused", "viewing", "stopping", "released"): + assert indicator.update(state)["state"] == state + assert not indicator.status()["pixels_verified"] + result = indicator.close() + assert result["state"] == "released" + assert ( + result["closed"] and result["surface_absent"] and result["process_settled"] + ) + assert result["helper_exit"] == 0 and not result["healthy"] + assert indicator.close() == result + finally: + indicator.abort() + if indicator._proc.stderr: + indicator._proc.stderr.close() + + +@pytest.mark.parametrize( + "mode", ["die", "stale", "wronggen", "extra", "oversize", "wrongloop", "wrongstate"] +) +def test_inert_faults_fail_closed_and_settle(monkeypatch, mode): + indicator = inert_indicator(monkeypatch, mode) + result = indicator.start() + assert not result["healthy"] and not result["ready"] + assert result["state"] == "interrupted" + assert result["process_settled"] and not result["surface_absent"] + assert result["fault_settled"] and result["settlement_basis"] == "helper_reaped" + assert not indicator.start()["healthy"] # Never restart unknown generation. + indicator.close() + indicator._proc.stderr.close() + + +@pytest.mark.parametrize( + "reason", ["console_unavailable", "console_user_mismatch", "cocoa_unavailable"] +) +def test_startup_unavailable_helper_reaped_is_failed_resource_settlement( + monkeypatch, reason +): + indicator = inert_indicator(monkeypatch, reason) + try: + result = indicator.start() + assert result["state"] == "interrupted" and result["reason"] == reason + assert not result["healthy"] and not result["ready"] + assert result["process_settled"] and result["fault_settled"] + assert result["settlement_basis"] == "helper_reaped" + assert not result["surface_absent"] # No invented native metadata ack. + assert indicator.close()["fault_settled"] + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_never_launched_failure_has_explicit_resource_settlement(monkeypatch): + indicator = adapter.MacOSIndicator() + monkeypatch.setattr(adapter.sys, "platform", "darwin") + monkeypatch.setattr( + indicator, "_launch", lambda: (_ for _ in ()).throw(OSError("private")) + ) + result = indicator.start() + assert result["state"] == "interrupted" and result["reason"] == "helper_failed" + assert result["fault_settled"] and result["process_settled"] + assert ( + result["settlement_basis"] == "never_launched" and result["helper_exit"] is None + ) + assert not result["surface_absent"] and not result["healthy"] + assert indicator.close()["fault_settled"] + + +class SettlementProcess: + """Inert wait/escalation controls, never an actual OS PID.""" + + def __init__(self, outcome): + self.returncode = None + self.outcome = outcome + self.signals = [] + self.waits = 0 + self.stdin = SimpleNamespace(closed=True, fileno=lambda: 101) + self.stdout = SimpleNamespace(closed=True, fileno=lambda: 102) + + def wait(self, timeout): + self.waits += 1 + if self.outcome == "wait_error": + raise OSError("private") + if self.outcome == "unknown" or (self.outcome == "killed" and self.waits < 3): + raise subprocess.TimeoutExpired("private", timeout) + if self.outcome != "no_returncode": + self.returncode = -9 if self.outcome == "killed" else 2 + return self.returncode + + def terminate(self): + self.signals.append("terminate") + + def kill(self): + self.signals.append("kill") + + +@pytest.mark.parametrize("outcome", ["unknown", "no_returncode", "wait_error"]) +def test_unknown_process_outcome_never_claims_fault_settlement(outcome): + indicator = adapter.MacOSIndicator() + indicator._proc = SettlementProcess(outcome) + indicator._fail("reply_timeout") + result = indicator.close() + assert result["state"] == "interrupted" and not result["healthy"] + assert not result["process_settled"] and not result["fault_settled"] + assert not result["surface_absent"] and result["settlement_basis"] == "not_settled" + assert result["helper_exit"] is None + # Retained cleanup custody can settle later once exit really is observed. + indicator._proc.outcome = "exit" + recovered = indicator.close() + assert recovered["fault_settled"] and recovered["process_settled"] + assert recovered["state"] == "interrupted" and not recovered["healthy"] + + +def test_confirmed_kill_exit_settles_resource_but_never_becomes_release(): + indicator = adapter.MacOSIndicator() + indicator._proc = SettlementProcess("killed") + indicator._fail("reply_timeout") + result = indicator.close() + assert indicator._proc.signals == ["terminate", "kill"] + assert result["state"] == "interrupted" and result["reason"] == "reply_timeout" + assert result["process_settled"] and result["fault_settled"] + assert result["helper_exit"] == -9 and not result["surface_absent"] + assert result["settlement_basis"] == "helper_reaped" and not result["healthy"] + + +def test_pipe_setup_failure_retains_spawned_helper_custody(monkeypatch): + indicator = adapter.MacOSIndicator() + proc = SettlementProcess("exit") + monkeypatch.setattr(adapter.sys, "platform", "darwin") + monkeypatch.setattr(adapter.subprocess, "Popen", lambda *a, **kw: proc) + monkeypatch.setattr( + adapter.os, "set_blocking", lambda *_: (_ for _ in ()).throw(OSError("private")) + ) + result = indicator.start() + assert indicator._proc is proc and proc.waits == 1 + assert result["fault_settled"] and result["process_settled"] + assert result["settlement_basis"] == "helper_reaped" # Not never_launched. + assert result["state"] == "interrupted" and not result["healthy"] + + +def test_unsupported_platform_proves_no_helper_created(monkeypatch): + indicator = adapter.MacOSIndicator() + monkeypatch.setattr(adapter.sys, "platform", "linux") + monkeypatch.setattr( + adapter.subprocess, "Popen", lambda *_a, **_k: pytest.fail("must not spawn") + ) + result = indicator.start() + assert result["fault_settled"] and result["process_settled"] + assert result["settlement_basis"] == "never_launched" + assert not result["healthy"] and not result["surface_absent"] + + +def test_health_loss_irreversible_nonblocking_and_no_mutation_replay(monkeypatch): + indicator = inert_indicator(monkeypatch) + try: + assert indicator.start()["healthy"] + with indicator._lock: + indicator._last_reply = time.monotonic() - 20 + before = time.monotonic() + assert indicator.status()["state"] == "interrupted" + assert time.monotonic() - before < 0.1 + seq = indicator._sequence + assert not indicator.update("released")["healthy"] + assert indicator._sequence == seq + assert indicator.close()["state"] == "interrupted" + assert indicator.status()["process_settled"] + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_timeout_not_process_death_or_release(monkeypatch): + indicator = inert_indicator(monkeypatch) + try: + assert indicator.start()["healthy"] + monkeypatch.setattr( + indicator, "_exchange", lambda *_: (_ for _ in ()).throw(TimeoutError()) + ) + result = indicator.update("released") + assert result["reason"] == "reply_timeout" + assert result["state"] == "interrupted" + assert not result["process_settled"] + assert not result["fault_settled"] + indicator.close() + assert indicator.status()["process_settled"] + assert indicator.status()["fault_settled"] + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_real_lost_mutation_reply_is_not_replayed(monkeypatch): + indicator = inert_indicator(monkeypatch, "droprelease") + try: + assert indicator.start()["healthy"] + result = indicator.update("released") + assert result["reason"] == "reply_timeout" and result["state"] == "interrupted" + assert not result["process_settled"] + indicator.close() + trace = indicator._proc.stderr.read() + assert trace.count(b'"op":"update"') == 1 + assert b'"op":"close"' not in trace and b'"op":"abort"' not in trace + assert b"final:interrupted" in trace + assert indicator.status()["process_settled"] + assert indicator.status()["fault_settled"] + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_background_detects_helper_death_without_model_poll(monkeypatch): + indicator = inert_indicator(monkeypatch, "dieonstatus") + try: + assert indicator.start()["healthy"] + assert indicator._stop.wait(3) + assert indicator.status()["state"] == "interrupted" + assert not indicator.status()["healthy"] + indicator.close() + assert indicator.status()["process_settled"] + assert indicator.status()["fault_settled"] + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_terminal_ack_is_not_process_settlement(monkeypatch): + indicator = inert_indicator(monkeypatch, "terminalhung") + try: + assert indicator.start()["healthy"] + assert indicator.update("released")["state"] == "released" + result = indicator.close() + assert result["surface_absent"] + assert result["process_settled"] and result["helper_exit"] != 0 + assert result["state"] == "interrupted" and result["reason"] == "helper_failed" + finally: + indicator.abort() + indicator._proc.stderr.close() + + +def test_terminal_publication_cannot_overwrite_concurrent_sticky_loss(monkeypatch): + entered, resume = threading.Event(), threading.Event() + + class BarrierIndicator(adapter.MacOSIndicator): + armed = False + + def __setattr__(self, name, value): + if name == "_snapshot" and self.armed and value.get("closed"): + self.armed = False + entered.set() + assert resume.wait(3) + super().__setattr__(name, value) + + original = adapter.MacOSIndicator + monkeypatch.setattr(adapter, "MacOSIndicator", BarrierIndicator) + indicator = inert_indicator(monkeypatch) + monkeypatch.setattr(adapter, "MacOSIndicator", original) + results = [] + try: + assert indicator.start()["healthy"] + assert indicator.update("released")["state"] == "released" + indicator.armed = True + worker = threading.Thread(target=lambda: results.append(indicator.close())) + worker.start() + assert entered.wait(3) + indicator._last_reply = time.monotonic() - 20 + assert indicator.status()["state"] == "interrupted" + resume.set() + worker.join(3) + assert not worker.is_alive() + assert results[0]["state"] == indicator.status()["state"] == "interrupted" + assert results[0]["surface_absent"] and results[0]["process_settled"] + finally: + resume.set() + indicator.abort() + indicator._proc.stderr.close() + + +def test_signal_request_mid_command_never_reapplies_released(monkeypatch): + run, now, replies, surface = runtime() + run.tick() + validate = helper.validate_command + + def request_during_validation(row): + validate(row) + run.request_interrupt() + assert surface.states == ["viewing"] # Handler is bookkeeping only. + assert run.reason == "ok" + + monkeypatch.setattr(helper, "validate_command", request_during_validation) + run.receive(helper.encode_frame(command(2, "update", "released"))) + run.tick() + assert run.reason == "connection_lost" and run.protocol.state == "interrupted" + assert "released" not in surface.states + assert replies[-1]["event"] == "unavailable" + now[0] += helper.TERMINAL_DWELL_SECONDS + 0.01 + run.tick() + assert run.finished + + +def test_private_stop_wakes_only_own_application_queue(): + calls = [] + event = object() + app = SimpleNamespace( + stop_=lambda sender: calls.append(("stop", sender)), + postEvent_atStart_=lambda value, front: calls.append(("post", value, front)), + ) + toolkit = SimpleNamespace( + NSEventTypeApplicationDefined=15, + NSEvent=SimpleNamespace( + otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_=lambda *args: ( + calls.append(("event", args)) or event + ) + ), + ) + helper._stop_application(app, toolkit) + assert calls == [ + ("stop", None), + ("event", (15, (0, 0), 0, 0, 0, None, 0, 0, 0)), + ("post", event, False), + ] + + +def test_real_helper_selftest_and_nonmac_unavailable_no_ui(): + path = PACKAGE / "macos_indicator_helper.py" + result = subprocess.run( + [sys.executable, "-I", str(path), "--self-test"], capture_output=True, timeout=5 + ) + assert result.returncode == 0 and b'"native_ui_exercised":false' in result.stdout + if sys.platform != "darwin": + result = subprocess.run( + [sys.executable, "-I", str(path)], + input=helper.encode_frame(command()), + capture_output=True, + timeout=5, + ) + row = helper.decode_frame(result.stdout) + assert result.returncode == 2 and row["reason"] == "unsupported_platform" + assert result.stderr == b"" + + +def test_constructor_import_and_launch_argv_are_inert(monkeypatch): + calls = [] + fake = SimpleNamespace( + stdin=SimpleNamespace(fileno=lambda: 101), + stdout=SimpleNamespace(fileno=lambda: 102), + ) + monkeypatch.setattr( + adapter.subprocess, "Popen", lambda *a, **k: calls.append((a, k)) or fake + ) + monkeypatch.setattr(adapter.os, "set_blocking", lambda *_: None) + indicator = adapter.MacOSIndicator() + assert calls == [] and indicator.status()["reason"] == "not_started" + indicator._launch() + argv, kwargs = calls[0][0][0], calls[0][1] + assert argv == [sys.executable, "-I", str(PACKAGE / "macos_indicator_helper.py")] + assert kwargs["close_fds"] and kwargs["stderr"] == subprocess.DEVNULL + assert kwargs["stdin"] == kwargs["stdout"] == subprocess.PIPE + assert "shell" not in kwargs and "env" not in kwargs + + +def test_packaging_dependency_marker_and_source_resources(): + project = tomllib.loads((PACKAGE.parent / "pyproject.toml").read_text()) + assert ( + "pyobjc-framework-Cocoa>=10.0; sys_platform == 'darwin'" + in project["project"]["dependencies"] + ) + for name in ("macos_indicator.py", "macos_indicator_helper.py"): + path = PACKAGE / name + assert importlib.util.find_spec( + f"amplifier_module_tool_computer_use.{path.stem}" + ).origin == str(path) + assert len(hashlib.sha256(path.read_bytes()).hexdigest()) == 64 + + +def test_fake_appkit_fixed_panel_no_focus_and_original_window_absence(monkeypatch): + """Exercise real surface builder, not grep. Does not prove native semantics.""" + calls, panels, labels = [], [], [] + entries = [{"owner": os.getpid(), "number": 42}] + + class Object: + def __getattr__(self, name): + if name.startswith("set"): + return lambda value: calls.append((name, value)) + raise AttributeError(name) + + class Panel(Object): + @classmethod + def alloc(cls): + panel = cls() + panel.closed = False + panels.append(panel) + return panel + + def initWithContentRect_styleMask_backing_defer_(self, *args): + calls.append(("init", args)) + return self + + def contentView(self): + return SimpleNamespace( + addSubview_=lambda label: calls.append(("label", label)) + ) + + def orderFront_(self, sender): + calls.append(("orderFront", sender)) + + def displayIfNeeded(self): + pass + + def windowNumber(self): + return -1 if self.closed else 42 + + def isVisible(self): + return not self.closed + + def isKeyWindow(self): + return False + + def isMainWindow(self): + return False + + def ignoresMouseEvents(self): + return True + + def orderOut_(self, sender): + calls.append(("orderOut", sender)) + + def close(self): + self.closed = True + + class Field(Object): + @classmethod + def labelWithString_(cls, text): + label = cls() + labels.append(label) + return label + + app = SimpleNamespace(activationPolicy=lambda: 7, isActive=lambda: False) + appkit = SimpleNamespace( + NSPanel=Panel, + NSScreen=SimpleNamespace( + mainScreen=lambda: SimpleNamespace( + visibleFrame=lambda: SimpleNamespace( + origin=SimpleNamespace(x=0, y=0), + size=SimpleNamespace(width=1200, height=800), + ) + ) + ), + NSWindowStyleMaskBorderless=0, + NSWindowStyleMaskNonactivatingPanel=1, + NSBackingStoreBuffered=2, + NSStatusWindowLevel=3, + NSWindowCollectionBehaviorCanJoinAllSpaces=1, + NSWindowCollectionBehaviorStationary=2, + NSWindowCollectionBehaviorFullScreenAuxiliary=4, + NSColor=SimpleNamespace( + colorWithCalibratedRed_green_blue_alpha_=lambda *args: args, + blackColor=lambda: "black", + ), + NSTextField=Field, + NSFont=SimpleNamespace(boldSystemFontOfSize_=lambda size: size), + NSTextAlignmentCenter=2, + NSApplication=SimpleNamespace(sharedApplication=lambda: app), + NSApplicationActivationPolicyAccessory=7, + ) + quartz = SimpleNamespace( + CGWindowListCopyWindowInfo=lambda *_: entries, + kCGWindowListOptionOnScreenOnly=1, + kCGWindowListExcludeDesktopElements=2, + kCGNullWindowID=0, + kCGWindowOwnerPID="owner", + kCGWindowNumber="number", + ) + monkeypatch.setattr(helper, "console_reason", lambda: "ok") + surface = helper._create_surface(appkit, quartz) + assert len(panels) == len(labels) == 1 + assert surface.confirmed() + assert not panels[0].canBecomeKeyWindow() and not panels[0].canBecomeMainWindow() + assert ("setIgnoresMouseEvents_", True) in calls + assert ("setCollectionBehavior_", 7) in calls + assert calls[0] == ("init", (((16, 720), (480, 64)), 1, 2, False)) + for state in helper.STATES: + surface.apply(state) + assert ("setStringValue_", helper.LABELS[state]) in calls + # WindowServer can retain the original window briefly after close. + assert not surface.remove() + entries.clear() + assert surface.remove() # Prove original ID absent, never the invalidated -1. + assert not surface.confirmed() diff --git a/tests/test_module_cleanup.py b/tests/test_module_cleanup.py index 9c16c8e..6cbb90e 100644 --- a/tests/test_module_cleanup.py +++ b/tests/test_module_cleanup.py @@ -865,29 +865,22 @@ async def test_cleanup_wins_before_direct_desktop_worker_dispatch( desktop = cu.DesktopTool(computer) loop = asyncio.get_running_loop() queued, proceed = asyncio.Event(), threading.Event() - to_thread = asyncio.to_thread + submit = computer._submit_batch_thread - async def delayed_to_thread(function, *args, **kwargs): + def delayed_submit(function, *args, **kwargs): # Gate the actual queued backend worker, not the earlier announcement # or band workers. Cleanup must take the lock before this dispatch does. - if function.__name__ not in { - "checked_call", - "get_clipboard", - "set_clipboard", - "list_monitors", - "select_monitor", - "_run_flat_step", - }: - return await to_thread(function, *args, **kwargs) + if function.__name__ != "_run_owned_step": + return submit(function, *args, **kwargs) def delayed(): loop.call_soon_threadsafe(queued.set) assert proceed.wait(2), "test desktop dispatch gate was not released" return function(*args, **kwargs) - return await to_thread(delayed) + return submit(delayed) - monkeypatch.setattr(asyncio, "to_thread", delayed_to_thread) + monkeypatch.setattr(computer, "_submit_batch_thread", delayed_submit) running = asyncio.create_task(desktop.execute(payload)) try: await asyncio.wait_for(queued.wait(), 2)