Agent Zero AI framework
Add Launcher host gateway protocol support
Alessandrodafe5a33ba66
diff --git a/plugins/_a0_connector/AGENTS.md b/plugins/_a0_connector/AGENTS.mdindex b81567a24..b2fd50881 100644--- a/plugins/_a0_connector/AGENTS.md+++ b/plugins/_a0_connector/AGENTS.md@@ -21,6 +21,25 @@execution metadata enables `code_execution_remote`, and supported enabledComputer Use that does not need re-arming enables `computer_use_remote`.- Do not bypass WebSocket authentication or leak connector session data.+- Advertise Launcher gateways additively through HTTP capability+ `launcher_gateway` and WebSocket feature `launcher_gateway_control`. Older+ ordinary CLI clients retain their existing protocol fields and behavior; do+ not provide a partial tools-only fallback when either feature is absent.+- A Launcher `connector_hello` carries a versioned gateway object with kind,+ stable ID, host label, and bounded status. Store it per authenticated socket,+ remove it on disconnect, and let context-bound CLI sockets retain routing+ priority. One unique Launcher gateway may be the global fallback. A duplicate+ socket with the same ID replaces stale state; distinct simultaneous IDs fail+ closed as Multiple hosts.+- `connector_gateway_control` and `connector_gateway_control_result` cover+ master state, complete scope replacement, and emergency disconnect. Protected+ WebUI mutations require CSRF, await the matching acknowledgement, and return+ refreshed status. Never let the WebUI select a host folder or personal+ browser profile.+- The `chat-top-end` Launcher gateway extension renders only when the user agent+ includes `A0-Launcher/`. It may show status, master/scope controls,+ preparation errors, and Emergency disconnect; standard browser sessions must+ not expose it.- File operation results may arrive as chunked JSON/base64`connector_file_op_result` frames; resolve the pending file operation onlyafter all chunks for the `op_id` are assembled.@@ -33,6 +52,8 @@## Verification- Run connector-specific tests or smoke-test HTTP and `/ws` integration when changing runtime behavior.+- Launcher gateway regression coverage lives in+ `tests/test_a0_connector_launcher_gateway.py`.## Child DOX Indexdiff --git a/plugins/_a0_connector/api/v1/capabilities.py b/plugins/_a0_connector/api/v1/capabilities.pyindex d2699bdf5..d52574acc 100644--- a/plugins/_a0_connector/api/v1/capabilities.py+++ b/plugins/_a0_connector/api/v1/capabilities.py@@ -28,6 +28,7 @@ _BASE_FEATURES = ["connector_browser_op","remote_file_tree","token_status",+ "launcher_gateway",]_OPTIONAL_FEATURES: dict[str, tuple[str, ...]] = {diff --git a/plugins/_a0_connector/api/v1/launcher_gateway_control.py b/plugins/_a0_connector/api/v1/launcher_gateway_control.pynew file mode 100644index 000000000..04a94a7d5--- /dev/null+++ b/plugins/_a0_connector/api/v1/launcher_gateway_control.py@@ -0,0 +1,96 @@+"""POST /api/plugins/_a0_connector/v1/launcher_gateway_control."""+from __future__ import annotations++import asyncio+import uuid++from helpers.api import Request, Response+from helpers.ws_manager import ConnectionNotFoundError, get_shared_ws_manager++import plugins._a0_connector.api.v1.base as connector_base+from plugins._a0_connector.helpers.ws_runtime import (+ active_launcher_gateway_sid,+ clear_pending_gateway_control,+ launcher_gateway_status,+ store_pending_gateway_control,+)+++_CONTROL_EVENT = "connector_gateway_control"+_CONTROL_TIMEOUT_SECONDS = 8.0+_SCOPE_KEYS = ("files", "code_execution", "browser", "computer_use")+++class LauncherGatewayControl(connector_base.ProtectedConnectorApiHandler):+ """Apply an acknowledged control change to the active Launcher gateway."""++ @classmethod+ def requires_csrf(cls) -> bool:+ return True++ async def process(self, input: dict, request: Request) -> dict | Response:+ action = str(input.get("action", "") or "").strip().lower()+ payload: dict = {"action": action}+ if action == "set_master":+ if not isinstance(input.get("enabled"), bool):+ return Response("enabled must be a boolean", status=400)+ payload["enabled"] = input["enabled"]+ elif action == "replace_scopes":+ scopes = input.get("scopes")+ if not isinstance(scopes, dict) or any(+ not isinstance(scopes.get(key), bool) for key in _SCOPE_KEYS+ ):+ return Response(+ "scopes must contain boolean files, code_execution, browser, and computer_use values",+ status=400,+ )+ normalized = {key: scopes[key] for key in _SCOPE_KEYS}+ if not normalized["files"]:+ normalized["code_execution"] = False+ payload["scopes"] = normalized+ elif action != "emergency_disconnect":+ return Response("Unknown gateway control action", status=400)++ status = launcher_gateway_status()+ if status.get("multiple_hosts"):+ return Response("Multiple Launcher hosts are connected", status=409)+ sid = active_launcher_gateway_sid()+ if not sid:+ return Response("No Launcher host gateway is connected", status=409)++ request_id = str(uuid.uuid4())+ payload["request_id"] = request_id+ loop = asyncio.get_running_loop()+ future: asyncio.Future[dict] = loop.create_future()+ store_pending_gateway_control(+ request_id,+ sid=sid,+ future=future,+ loop=loop,+ )+ try:+ await get_shared_ws_manager().emit_to(+ "/ws",+ sid,+ _CONTROL_EVENT,+ payload,+ handler_id=f"{self.__class__.__module__}.{self.__class__.__name__}",+ )+ result = await asyncio.wait_for(future, timeout=_CONTROL_TIMEOUT_SECONDS)+ except ConnectionNotFoundError:+ return Response("Launcher host gateway disconnected", status=409)+ except asyncio.TimeoutError:+ return Response("Launcher host gateway did not acknowledge the change", status=504)+ finally:+ clear_pending_gateway_control(request_id)++ if not result.get("ok", False):+ return Response(+ str(result.get("error") or "Launcher host gateway rejected the change"),+ status=409,+ )+ return {+ "ok": True,+ "result": result,+ "status": launcher_gateway_status(),+ }diff --git a/plugins/_a0_connector/api/v1/launcher_gateway_status.py b/plugins/_a0_connector/api/v1/launcher_gateway_status.pynew file mode 100644index 000000000..ac0e62481--- /dev/null+++ b/plugins/_a0_connector/api/v1/launcher_gateway_status.py@@ -0,0 +1,14 @@+"""POST /api/plugins/_a0_connector/v1/launcher_gateway_status."""+from __future__ import annotations++from helpers.api import Request, Response++import plugins._a0_connector.api.v1.base as connector_base+from plugins._a0_connector.helpers.ws_runtime import launcher_gateway_status+++class LauncherGatewayStatus(connector_base.ProtectedConnectorApiHandler):+ """Return the current Launcher-owned host gateway state."""++ async def process(self, input: dict, request: Request) -> dict | Response:+ return launcher_gateway_status()diff --git a/plugins/_a0_connector/api/ws_connector.py b/plugins/_a0_connector/api/ws_connector.pyindex 0152eeb4c..526da9c7d 100644--- a/plugins/_a0_connector/api/ws_connector.py+++ b/plugins/_a0_connector/api/ws_connector.py@@ -13,6 +13,7 @@ from plugins._a0_connector.helpers.event_bridge import get_context_log_entriesfrom plugins._a0_connector.helpers.version import agent_zero_versionfrom plugins._a0_connector.helpers.ws_runtime import (clear_remote_tree_snapshot,+ clear_sid_launcher_gateway_metadata,clear_sid_host_browser_metadata,clear_sid_computer_use_metadata,clear_sid_remote_exec_metadata,@@ -22,15 +23,18 @@ from plugins._a0_connector.helpers.ws_runtime import (fail_pending_computer_use_ops_for_sid,fail_pending_exec_ops_for_sid,fail_pending_file_ops_for_sid,+ fail_pending_gateway_controls_for_sid,host_browser_metadata_for_sid,register_sid,remote_exec_metadata_for_sid,remote_file_metadata_for_sid,+ resolve_pending_gateway_control,resolve_pending_browser_op,resolve_pending_computer_use_op,resolve_pending_exec_op,resolve_pending_file_op,store_remote_tree_snapshot,+ store_sid_launcher_gateway_metadata,store_sid_host_browser_metadata,store_sid_computer_use_metadata,store_sid_remote_exec_metadata,@@ -60,6 +64,7 @@ WS_FEATURES = ["computer_use_remote","browser_host_remote","connector_browser_op",+ "launcher_gateway_control",]_SNAPSHOT_REPLAY_PAGE_SIZE = 50@@ -106,10 +111,15 @@ class WsConnector(WsHandler):sid,error="CLI disconnected before completing the requested browser operation",)+ fail_pending_gateway_controls_for_sid(+ sid,+ error="Launcher gateway disconnected before acknowledging the control request",+ )clear_sid_computer_use_metadata(sid)clear_sid_host_browser_metadata(sid)clear_sid_remote_file_metadata(sid)clear_sid_remote_exec_metadata(sid)+ clear_sid_launcher_gateway_metadata(sid)PrintStyle.debug(f"[a0-connector] /ws disconnected: {sid}")async def process(@@ -162,6 +172,9 @@ class WsConnector(WsHandler):if event == "connector_browser_op_result":return self._handle_browser_op_result(data, sid)+ if event == "connector_gateway_control_result":+ return self._handle_gateway_control_result(data, sid)+if event.startswith("connector_"):return WsResult.error(code="UNKNOWN_EVENT",@@ -176,6 +189,7 @@ class WsConnector(WsHandler):host_browser = data.get("host_browser")remote_files = data.get("remote_files")remote_exec = data.get("remote_exec")+ gateway = data.get("gateway")if isinstance(computer_use, dict):store_sid_computer_use_metadata(sid, computer_use)else:@@ -192,6 +206,10 @@ class WsConnector(WsHandler):store_sid_remote_exec_metadata(sid, remote_exec)else:clear_sid_remote_exec_metadata(sid)+ if isinstance(gateway, dict):+ store_sid_launcher_gateway_metadata(sid, gateway)+ else:+ clear_sid_launcher_gateway_metadata(sid)def _associate_declared_context(self, data: dict[str, Any], sid: str) -> str:context_id = str(data.get("context_id", "") or "").strip()@@ -777,6 +795,26 @@ class WsConnector(WsHandler):return {"op_id": op_id, "accepted": True}+ def _handle_gateway_control_result(+ self,+ data: dict[str, Any],+ sid: str,+ ) -> dict[str, Any] | WsResult:+ request_id = str(data.get("request_id", "") or "").strip()+ if not request_id:+ return WsResult.error(+ code="MISSING_REQUEST_ID",+ message="request_id is required",+ correlation_id=data.get("correlationId"),+ )+ if not resolve_pending_gateway_control(request_id, sid=sid, payload=data):+ return WsResult.error(+ code="UNKNOWN_REQUEST_ID",+ message=f"No pending gateway control for request_id '{request_id}'",+ correlation_id=data.get("correlationId"),+ )+ return {"request_id": request_id, "accepted": True}+async def _resolve_context(self,*,diff --git a/plugins/_a0_connector/extensions/webui/chat-top-end/launcher-gateway.html b/plugins/_a0_connector/extensions/webui/chat-top-end/launcher-gateway.htmlnew file mode 100644index 000000000..dac03c61f--- /dev/null+++ b/plugins/_a0_connector/extensions/webui/chat-top-end/launcher-gateway.html@@ -0,0 +1,131 @@+<script type="module">+ import { store } from "/plugins/_a0_connector/webui/launcher-gateway-store.js";+</script>++<div+ x-data+ class="launcher-gateway-root"+ x-show="$store.launcherGateway?.visible"+ x-create="$store.launcherGateway?.onMount()"+ x-destroy="$store.launcherGateway?.cleanup()"+ @click.outside="$store.launcherGateway.open = false"+ @keydown.escape.window="$store.launcherGateway.open = false"+ style="display: none;"+>+ <button+ type="button"+ class="launcher-gateway-trigger"+ :class="`is-${$store.launcherGateway.state}`"+ :title="`Host access: ${$store.launcherGateway.stateLabel}`"+ :aria-label="`Host access: ${$store.launcherGateway.stateLabel}`"+ aria-haspopup="dialog"+ :aria-expanded="$store.launcherGateway.open.toString()"+ @click.stop="$store.launcherGateway.open = !$store.launcherGateway.open"+ >+ <span class="launcher-gateway-dot" aria-hidden="true"></span>+ <span class="material-symbols-outlined" aria-hidden="true" x-text="$store.launcherGateway.stateIcon"></span>+ <span class="launcher-gateway-trigger-label" x-text="$store.launcherGateway.stateLabel"></span>+ </button>++ <section+ class="launcher-gateway-popover"+ role="dialog"+ aria-label="Launcher host access"+ x-show="$store.launcherGateway.open"+ x-transition.opacity.duration.120ms+ @click.stop+ style="display: none;"+ >+ <header class="launcher-gateway-header">+ <div>+ <strong x-text="$store.launcherGateway.hostLabel"></strong>+ <span x-text="$store.launcherGateway.stateLabel"></span>+ </div>+ <button type="button" class="launcher-gateway-close" aria-label="Close host access" @click="$store.launcherGateway.open = false">+ <span class="material-symbols-outlined" aria-hidden="true">close</span>+ </button>+ </header>++ <template x-if="$store.launcherGateway.gateway">+ <div class="launcher-gateway-controls">+ <label class="launcher-gateway-row is-master">+ <span>Host access</span>+ <input type="checkbox" :checked="$store.launcherGateway.gateway.master_enabled" :disabled="$store.launcherGateway.saving" @change="$store.launcherGateway.setMaster($event.target.checked)">+ </label>+ <label class="launcher-gateway-row">+ <span>Files read/write</span>+ <input type="checkbox" :checked="$store.launcherGateway.gateway.scopes.files" :disabled="$store.launcherGateway.saving" @change="$store.launcherGateway.setScope('files', $event.target.checked)">+ </label>+ <label class="launcher-gateway-row">+ <span>Code execution</span>+ <input type="checkbox" :checked="$store.launcherGateway.gateway.scopes.code_execution" :disabled="$store.launcherGateway.saving || !$store.launcherGateway.gateway.scopes.files" @change="$store.launcherGateway.setScope('code_execution', $event.target.checked)">+ </label>+ <label class="launcher-gateway-row">+ <span>Personal browser</span>+ <input type="checkbox" :checked="$store.launcherGateway.gateway.scopes.browser" :disabled="$store.launcherGateway.saving" @change="$store.launcherGateway.setScope('browser', $event.target.checked)">+ </label>+ <label class="launcher-gateway-row">+ <span>Computer Use</span>+ <input type="checkbox" :checked="$store.launcherGateway.gateway.scopes.computer_use" :disabled="$store.launcherGateway.saving" @change="$store.launcherGateway.setScope('computer_use', $event.target.checked)">+ </label>+ </div>+ </template>++ <div class="launcher-gateway-notices" x-show="$store.launcherGateway.preparationMessages.length">+ <template x-for="message in $store.launcherGateway.preparationMessages" :key="message">+ <p><span class="material-symbols-outlined" aria-hidden="true">warning</span><span x-text="message"></span></p>+ </template>+ </div>++ <p class="launcher-gateway-empty" x-show="!$store.launcherGateway.gateway">+ Host access is not connected for this Launcher tab.+ </p>++ <button+ type="button"+ class="launcher-gateway-disconnect"+ x-show="$store.launcherGateway.gateway"+ :disabled="$store.launcherGateway.saving"+ @click="$store.launcherGateway.emergencyDisconnect()"+ >Emergency disconnect</button>+ </section>+</div>++<style>+ .launcher-gateway-root { position: relative; }+ .launcher-gateway-trigger {+ display: inline-flex; align-items: center; gap: .35rem; min-height: 2rem;+ padding: .25rem .55rem; border: 1px solid var(--color-border); border-radius: 999px;+ color: var(--color-text); background: color-mix(in srgb, var(--color-panel) 92%, transparent);+ cursor: pointer; font: inherit; font-size: .75rem;+ }+ .launcher-gateway-trigger .material-symbols-outlined { font-size: 1rem; }+ .launcher-gateway-dot { width: .45rem; height: .45rem; border-radius: 50%; background: #7b8491; }+ .launcher-gateway-trigger.is-connected .launcher-gateway-dot { background: #45b86b; }+ .launcher-gateway-trigger.is-connecting .launcher-gateway-dot { background: #5b9cff; }+ .launcher-gateway-trigger.is-paused .launcher-gateway-dot { background: #d6a43d; }+ .launcher-gateway-trigger.is-needs_action .launcher-gateway-dot,+ .launcher-gateway-trigger.is-multiple_hosts .launcher-gateway-dot { background: #e49a35; }+ .launcher-gateway-trigger.is-error .launcher-gateway-dot { background: #db5b61; }+ .launcher-gateway-popover {+ position: absolute; top: calc(100% + .45rem); right: 0; z-index: 1200; width: min(20rem, calc(100vw - 2rem));+ padding: .8rem; border: 1px solid var(--color-border); border-radius: .7rem;+ background: var(--color-panel); box-shadow: 0 16px 42px rgba(0, 0, 0, .24);+ }+ .launcher-gateway-header { display: flex; justify-content: space-between; gap: .75rem; align-items: flex-start; }+ .launcher-gateway-header div { display: grid; gap: .1rem; }+ .launcher-gateway-header span { color: var(--color-text-secondary); font-size: .75rem; }+ .launcher-gateway-close { border: 0; background: transparent; color: inherit; cursor: pointer; padding: 0; }+ .launcher-gateway-close .material-symbols-outlined { font-size: 1.1rem; }+ .launcher-gateway-controls { display: grid; gap: .15rem; margin-top: .7rem; }+ .launcher-gateway-row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; min-height: 2rem; font-size: .82rem; }+ .launcher-gateway-row.is-master { padding-bottom: .35rem; margin-bottom: .2rem; border-bottom: 1px solid var(--color-border); font-weight: 650; }+ .launcher-gateway-row input { accent-color: var(--color-primary); }+ .launcher-gateway-notices { display: grid; gap: .35rem; margin-top: .55rem; }+ .launcher-gateway-notices p { display: flex; gap: .35rem; margin: 0; color: #d79b35; font-size: .75rem; line-height: 1.3; }+ .launcher-gateway-notices .material-symbols-outlined { font-size: .95rem; }+ .launcher-gateway-empty { margin: .7rem 0 0; color: var(--color-text-secondary); font-size: .78rem; }+ .launcher-gateway-disconnect { width: 100%; margin-top: .75rem; padding: .48rem .65rem; border: 1px solid color-mix(in srgb, #db5b61 55%, var(--color-border)); border-radius: .45rem; background: transparent; color: #db5b61; cursor: pointer; }+ .launcher-gateway-disconnect:disabled { opacity: .55; cursor: default; }+ @media (max-width: 700px) { .launcher-gateway-trigger-label { display: none; } }+</style>diff --git a/plugins/_a0_connector/helpers/ws_runtime.py b/plugins/_a0_connector/helpers/ws_runtime.pyindex e35948359..199d9c46e 100644--- a/plugins/_a0_connector/helpers/ws_runtime.py+++ b/plugins/_a0_connector/helpers/ws_runtime.py@@ -45,6 +45,13 @@ class PendingBrowserOperation:context_id: str | None = None+@dataclass+class PendingGatewayControl:+ sid: str+ loop: asyncio.AbstractEventLoop+ future: asyncio.Future[dict[str, Any]]++@dataclass(frozen=True)class RemoteTreeSnapshot:sid: str@@ -103,22 +110,37 @@ class RemoteExecMetadata:updated_at: float+@dataclass(frozen=True)+class LauncherGatewayMetadata:+ gateway_id: str+ host_label: str+ state: str+ master_enabled: bool+ scopes: dict[str, bool]+ status: dict[str, Any]+ updated_at: float++_context_subscriptions: dict[str, set[str]] = {}_sid_contexts: dict[str, set[str]] = {}_pending_file_ops: dict[str, PendingFileOperation] = {}_pending_exec_ops: dict[str, PendingExecOperation] = {}_pending_computer_use_ops: dict[str, PendingComputerUseOperation] = {}_pending_browser_ops: dict[str, PendingBrowserOperation] = {}+_pending_gateway_controls: dict[str, PendingGatewayControl] = {}_remote_tree_snapshots: dict[str, RemoteTreeSnapshot] = {}_sid_computer_use_metadata: dict[str, ComputerUseMetadata] = {}_sid_host_browser_metadata: dict[str, HostBrowserMetadata] = {}_sid_remote_file_metadata: dict[str, RemoteFileMetadata] = {}_sid_remote_exec_metadata: dict[str, RemoteExecMetadata] = {}+_sid_launcher_gateway_metadata: dict[str, LauncherGatewayMetadata] = {}+_replaced_gateway_sids: set[str] = set()_state_lock = threading.RLock()def register_sid(sid: str) -> None:with _state_lock:+ _replaced_gateway_sids.discard(sid)_sid_contexts.setdefault(sid, set())@@ -130,6 +152,8 @@ def unregister_sid(sid: str) -> set[str]:_sid_host_browser_metadata.pop(sid, None)_sid_remote_file_metadata.pop(sid, None)_sid_remote_exec_metadata.pop(sid, None)+ _sid_launcher_gateway_metadata.pop(sid, None)+ _replaced_gateway_sids.discard(sid)for context_id in contexts:subscribers = _context_subscriptions.get(context_id)if not subscribers:@@ -176,11 +200,195 @@ def connected_sids() -> set[str]:return set(_sid_contexts.keys())+_GATEWAY_STATES = {+ "connecting",+ "connected",+ "paused",+ "needs_action",+ "error",+ "disconnected",+}+_GATEWAY_SCOPE_KEYS = ("files", "code_execution", "browser", "computer_use")+++def _bounded_gateway_status(value: Any, *, depth: int = 0) -> Any:+ if isinstance(value, str):+ return value[:2048]+ if isinstance(value, (bool, int, float)) or value is None:+ return value+ if depth >= 5:+ return None+ if isinstance(value, dict):+ result: dict[str, Any] = {}+ for key, item in list(value.items())[:64]:+ result[str(key)[:80]] = _bounded_gateway_status(item, depth=depth + 1)+ return result+ if isinstance(value, (list, tuple)):+ return [+ _bounded_gateway_status(item, depth=depth + 1)+ for item in list(value)[:64]+ ]+ return str(value)[:2048]+++def store_sid_launcher_gateway_metadata(+ sid: str,+ payload: dict[str, Any],+) -> LauncherGatewayMetadata | None:+ """Store a validated Launcher gateway declaration for one connector socket."""+ if str(payload.get("kind", "") or "").strip().lower() != "launcher":+ clear_sid_launcher_gateway_metadata(sid)+ return None+ try:+ version = int(payload.get("version") or 0)+ except (TypeError, ValueError):+ version = 0+ gateway_id = str(payload.get("id", "") or "").strip()[:128]+ if version != 1 or not gateway_id:+ clear_sid_launcher_gateway_metadata(sid)+ return None++ raw_scopes = payload.get("scopes")+ scopes = {+ key: bool(raw_scopes.get(key)) if isinstance(raw_scopes, dict) else False+ for key in _GATEWAY_SCOPE_KEYS+ }+ if not scopes["files"]:+ scopes["code_execution"] = False+ master_enabled = bool(payload.get("master_enabled", True))+ state = str(payload.get("state", "connected") or "").strip().lower()+ if state not in _GATEWAY_STATES:+ state = "connected" if master_enabled else "paused"+ if not master_enabled and state not in {"error", "needs_action", "disconnected"}:+ state = "paused"+ status_value = payload.get("status")+ status = _bounded_gateway_status(status_value) if isinstance(status_value, dict) else {}+ metadata = LauncherGatewayMetadata(+ gateway_id=gateway_id,+ host_label=str(payload.get("host_label", "") or "").strip()[:128],+ state=state,+ master_enabled=master_enabled,+ scopes=scopes,+ status=status,+ updated_at=time.time(),+ )+ with _state_lock:+ if sid in _replaced_gateway_sids:+ return None+ for other_sid, other in list(_sid_launcher_gateway_metadata.items()):+ if other_sid != sid and other.gateway_id == gateway_id:+ _sid_launcher_gateway_metadata.pop(other_sid, None)+ _replaced_gateway_sids.add(other_sid)+ _sid_launcher_gateway_metadata[sid] = metadata+ return metadata+++def clear_sid_launcher_gateway_metadata(sid: str) -> None:+ with _state_lock:+ _sid_launcher_gateway_metadata.pop(sid, None)+++def launcher_gateway_metadata_for_sid(sid: str) -> dict[str, Any] | None:+ with _state_lock:+ metadata = _sid_launcher_gateway_metadata.get(sid)+ if metadata is None:+ return None+ return _launcher_gateway_metadata_dict(metadata, sid=sid)+++def _launcher_gateway_metadata_dict(+ metadata: LauncherGatewayMetadata,+ *,+ sid: str | None = None,+) -> dict[str, Any]:+ result = {+ "version": 1,+ "kind": "launcher",+ "id": metadata.gateway_id,+ "host_label": metadata.host_label,+ "state": metadata.state,+ "master_enabled": metadata.master_enabled,+ "scopes": dict(metadata.scopes),+ "status": copy.deepcopy(metadata.status),+ "updated_at": metadata.updated_at,+ }+ if sid is not None:+ result["sid"] = sid+ return result+++def _active_launcher_gateways_locked() -> list[tuple[str, LauncherGatewayMetadata]]:+ return sorted(+ (+ (sid, metadata)+ for sid, metadata in _sid_launcher_gateway_metadata.items()+ if sid in _sid_contexts and sid not in _replaced_gateway_sids+ ),+ key=lambda item: item[1].updated_at,+ reverse=True,+ )+++def _active_launcher_gateway_sid_locked() -> str | None:+ gateways = _active_launcher_gateways_locked()+ if len({metadata.gateway_id for _sid, metadata in gateways}) != 1:+ return None+ return gateways[0][0] if gateways else None+++def active_launcher_gateway_sid() -> str | None:+ with _state_lock:+ return _active_launcher_gateway_sid_locked()+++def launcher_gateway_status() -> dict[str, Any]:+ with _state_lock:+ gateways = _active_launcher_gateways_locked()+ distinct_ids = {metadata.gateway_id for _sid, metadata in gateways}+ rows = [+ _launcher_gateway_metadata_dict(metadata)+ for _sid, metadata in gateways+ ]+ if not rows:+ return {+ "state": "disconnected",+ "connected": False,+ "multiple_hosts": False,+ "gateway": None,+ "gateways": [],+ }+ if len(distinct_ids) > 1:+ return {+ "state": "multiple_hosts",+ "connected": False,+ "multiple_hosts": True,+ "gateway": None,+ "gateways": rows,+ "error": "Multiple Launcher hosts are connected; host tools are disabled.",+ }+ gateway = rows[0]+ return {+ "state": gateway["state"],+ "connected": gateway["state"] not in {"disconnected", "error"},+ "multiple_hosts": False,+ "gateway": gateway,+ "gateways": rows,+ }++def _candidate_sids_for_context_locked(context_id: str) -> list[str]:context_sids = sorted(_context_subscriptions.get(context_id, set()))context_set = set(context_sids)- global_sids = sorted(sid for sid in _sid_contexts if sid not in context_set)- return context_sids + global_sids+ gateway_sid = _active_launcher_gateway_sid_locked()+ gateway_sids = [gateway_sid] if gateway_sid and gateway_sid not in context_set else []+ global_sids = sorted(+ sid+ for sid in _sid_contexts+ if sid not in context_set+ and sid not in _sid_launcher_gateway_metadata+ and sid not in _replaced_gateway_sids+ )+ return context_sids + gateway_sids + global_sidsdef remote_tool_sids_for_context(context_id: str) -> list[str]:@@ -215,20 +423,11 @@ def latest_remote_tree_for_context() -> dict[str, Any] | None:now = time.time()with _state_lock:- context_sids = sorted(_context_subscriptions.get(context_id, set()))- context_set = set(context_sids)- global_sids = sorted(sid for sid in _sid_contexts if sid not in context_set)+ candidates = _candidate_sids_for_context_locked(context_id)+ context_sids = set(_context_subscriptions.get(context_id, set()))snapshot_groups = [- [- _remote_tree_snapshots[sid]- for sid in context_sids- if sid in _remote_tree_snapshots- ],- [- _remote_tree_snapshots[sid]- for sid in global_sids- if sid in _remote_tree_snapshots- ],+ [_remote_tree_snapshots[sid] for sid in candidates if sid in context_sids and sid in _remote_tree_snapshots],+ [_remote_tree_snapshots[sid] for sid in candidates if sid not in context_sids and sid in _remote_tree_snapshots],]for snapshots in snapshot_groups:@@ -854,8 +1053,51 @@ def fail_pending_browser_ops_for_sid(sid: str, *, error: str) -> None:_fail_pending_for_sid(_pending_browser_ops, sid=sid, error=error)+def store_pending_gateway_control(+ request_id: str,+ *,+ sid: str,+ future: asyncio.Future[dict[str, Any]],+ loop: asyncio.AbstractEventLoop,+) -> None:+ with _state_lock:+ _pending_gateway_controls[request_id] = PendingGatewayControl(+ sid=sid,+ loop=loop,+ future=future,+ )+++def clear_pending_gateway_control(request_id: str) -> None:+ with _state_lock:+ _pending_gateway_controls.pop(request_id, None)+++def resolve_pending_gateway_control(+ request_id: str,+ *,+ sid: str,+ payload: dict[str, Any],+) -> bool:+ gateway = payload.get("gateway")+ if isinstance(gateway, dict):+ store_sid_launcher_gateway_metadata(sid, gateway)+ return _resolve_pending(_pending_gateway_controls, request_id, sid=sid, payload=payload)+++def fail_pending_gateway_controls_for_sid(sid: str, *, error: str) -> None:+ _fail_pending_for_sid(_pending_gateway_controls, sid=sid, error=error)++def _resolve_pending(- registry: dict[str, PendingFileOperation | PendingExecOperation | PendingComputerUseOperation | PendingBrowserOperation],+ registry: dict[+ str,+ PendingFileOperation+ | PendingExecOperation+ | PendingComputerUseOperation+ | PendingBrowserOperation+ | PendingGatewayControl,+ ],op_id: str,*,sid: str,@@ -872,7 +1114,14 @@ def _resolve_pending(def _fail_pending(- registry: dict[str, PendingFileOperation | PendingExecOperation | PendingComputerUseOperation | PendingBrowserOperation],+ registry: dict[+ str,+ PendingFileOperation+ | PendingExecOperation+ | PendingComputerUseOperation+ | PendingBrowserOperation+ | PendingGatewayControl,+ ],op_id: str,*,sid: str | None,@@ -895,7 +1144,14 @@ def _fail_pending(def _fail_pending_for_sid(- registry: dict[str, PendingFileOperation | PendingExecOperation | PendingComputerUseOperation | PendingBrowserOperation],+ registry: dict[+ str,+ PendingFileOperation+ | PendingExecOperation+ | PendingComputerUseOperation+ | PendingBrowserOperation+ | PendingGatewayControl,+ ],*,sid: str,error: str,diff --git a/plugins/_a0_connector/webui/launcher-gateway-store.js b/plugins/_a0_connector/webui/launcher-gateway-store.jsnew file mode 100644index 000000000..7de3579ae--- /dev/null+++ b/plugins/_a0_connector/webui/launcher-gateway-store.js@@ -0,0 +1,130 @@+import { createStore } from "/js/AlpineStore.js";+import { callJsonApi } from "/js/api.js";++const STATUS_API = "/plugins/_a0_connector/v1/launcher_gateway_status";+const CONTROL_API = "/plugins/_a0_connector/v1/launcher_gateway_control";++const model = {+ status: { state: "disconnected", gateway: null },+ loading: false,+ saving: false,+ open: false,+ intervalId: null,++ get visible() {+ return /(?:^|\s)A0-Launcher\/[^\s]+/.test(navigator.userAgent);+ },++ get gateway() {+ return this.status?.gateway || null;+ },++ get state() {+ return this.status?.state || "disconnected";+ },++ get stateLabel() {+ const labels = {+ connecting: "Connecting",+ connected: "Connected",+ paused: "Paused",+ needs_action: "Needs action",+ error: "Error",+ multiple_hosts: "Multiple hosts",+ disconnected: "Disconnected",+ };+ return labels[this.state] || "Disconnected";+ },++ get stateIcon() {+ const icons = {+ connecting: "sync",+ connected: "computer",+ paused: "pause_circle",+ needs_action: "warning",+ error: "error",+ multiple_hosts: "devices",+ disconnected: "computer_off",+ };+ return icons[this.state] || "computer_off";+ },++ get hostLabel() {+ return this.gateway?.host_label || "Launcher host";+ },++ get preparationMessages() {+ const status = this.gateway?.status || {};+ const messages = [];+ for (const key of ["browser", "computer_use"]) {+ const value = status[key];+ if (typeof value === "string" && value) messages.push(value);+ else if (value?.message) messages.push(value.message);+ else if (value?.error) messages.push(value.error);+ }+ if (this.status?.error) messages.push(this.status.error);+ return [...new Set(messages)];+ },++ onMount() {+ if (!this.visible || this.intervalId) return;+ void this.refresh();+ this.intervalId = window.setInterval(() => this.refresh(), 2000);+ },++ cleanup() {+ if (this.intervalId) window.clearInterval(this.intervalId);+ this.intervalId = null;+ },++ async refresh() {+ if (!this.visible || this.loading) return;+ this.loading = true;+ try {+ this.status = await callJsonApi(STATUS_API, {});+ } catch (error) {+ console.error("Failed to load Launcher host status:", error);+ this.status = { state: "error", gateway: null, error: error?.message || "Status unavailable" };+ } finally {+ this.loading = false;+ }+ },++ async setMaster(enabled) {+ await this.control({ action: "set_master", enabled: Boolean(enabled) });+ },++ async setScope(scope, enabled) {+ const current = this.gateway?.scopes || {};+ const scopes = {+ files: Boolean(current.files),+ code_execution: Boolean(current.code_execution),+ browser: Boolean(current.browser),+ computer_use: Boolean(current.computer_use),+ [scope]: Boolean(enabled),+ };+ if (!scopes.files) scopes.code_execution = false;+ await this.control({ action: "replace_scopes", scopes });+ },++ async emergencyDisconnect() {+ await this.control({ action: "emergency_disconnect" });+ this.open = false;+ },++ async control(payload) {+ if (this.saving) return;+ this.saving = true;+ try {+ const response = await callJsonApi(CONTROL_API, payload);+ this.status = response?.status || this.status;+ } catch (error) {+ console.error("Failed to control Launcher host:", error);+ await this.refresh();+ } finally {+ this.saving = false;+ }+ },+};++export const store = createStore("launcherGateway", model);diff --git a/tests/AGENTS.md b/tests/AGENTS.mdindex e10e015cd..39ea8763b 100644--- a/tests/AGENTS.md+++ b/tests/AGENTS.md@@ -17,6 +17,10 @@- Keep tests deterministic and isolated from existing chats, uploads, downloads, plugin state, and settings.- Prefer exercising public helper/API contracts over fragile implementation details when practical.- Security regression tests should assert the protected behavior directly.+- Launcher gateway tests must cover feature negotiation, authenticated and+ CSRF-protected control, acknowledgement timeout, identity lifecycle,+ context-bound CLI routing precedence, duplicate/multiple-host behavior,+ scope-driven availability, and emergency disconnect without a live host.## Work Guidancediff --git a/tests/test_a0_connector_launcher_gateway.py b/tests/test_a0_connector_launcher_gateway.pynew file mode 100644index 000000000..b78fa088e--- /dev/null+++ b/tests/test_a0_connector_launcher_gateway.py@@ -0,0 +1,216 @@+from __future__ import annotations++import asyncio+import uuid++from plugins._a0_connector.api.v1 import launcher_gateway_control+from plugins._a0_connector.api.v1.capabilities import _feature_list+from plugins._a0_connector.api.v1.launcher_gateway_status import LauncherGatewayStatus+from plugins._a0_connector.api.ws_connector import WS_FEATURES+from plugins._a0_connector.helpers import ws_runtime+++def _sid(label: str) -> str:+ return f"gateway-{label}-{uuid.uuid4()}"+++def _gateway(gateway_id: str, *, files: bool = True) -> dict:+ return {+ "version": 1,+ "kind": "launcher",+ "id": gateway_id,+ "host_label": "Test host",+ "state": "connected",+ "master_enabled": True,+ "scopes": {+ "files": files,+ "code_execution": True,+ "browser": True,+ "computer_use": True,+ },+ }+++def test_launcher_gateway_features_are_negotiated_on_http_and_websocket() -> None:+ assert "launcher_gateway" in _feature_list()+ assert "launcher_gateway_control" in WS_FEATURES+ assert LauncherGatewayStatus.requires_auth() is True+++def test_launcher_gateway_is_fallback_after_context_bound_cli() -> None:+ context_id = f"ctx-{uuid.uuid4()}"+ cli_sid = _sid("cli")+ gateway_sid = _sid("launcher")+ ws_runtime.register_sid(cli_sid)+ ws_runtime.register_sid(gateway_sid)+ ws_runtime.subscribe_sid_to_context(cli_sid, context_id)+ ws_runtime.store_sid_launcher_gateway_metadata(gateway_sid, _gateway("installation-a"))+ try:+ assert ws_runtime.remote_tool_sids_for_context(context_id)[:2] == [+ cli_sid,+ gateway_sid,+ ]+ finally:+ ws_runtime.unregister_sid(cli_sid)+ ws_runtime.unregister_sid(gateway_sid)+++def test_distinct_launcher_gateways_fail_closed() -> None:+ first_sid = _sid("first")+ second_sid = _sid("second")+ ws_runtime.register_sid(first_sid)+ ws_runtime.register_sid(second_sid)+ ws_runtime.store_sid_launcher_gateway_metadata(first_sid, _gateway("installation-a"))+ ws_runtime.store_sid_launcher_gateway_metadata(second_sid, _gateway("installation-b"))+ try:+ status = ws_runtime.launcher_gateway_status()+ assert status["state"] == "multiple_hosts"+ assert status["connected"] is False+ assert ws_runtime.active_launcher_gateway_sid() is None+ assert first_sid not in ws_runtime.remote_tool_sids_for_context("unbound")+ assert second_sid not in ws_runtime.remote_tool_sids_for_context("unbound")+ finally:+ ws_runtime.unregister_sid(first_sid)+ ws_runtime.unregister_sid(second_sid)+++def test_duplicate_gateway_identity_replaces_stale_socket() -> None:+ stale_sid = _sid("stale")+ fresh_sid = _sid("fresh")+ ws_runtime.register_sid(stale_sid)+ ws_runtime.register_sid(fresh_sid)+ ws_runtime.store_sid_launcher_gateway_metadata(stale_sid, _gateway("installation-a"))+ ws_runtime.store_sid_launcher_gateway_metadata(fresh_sid, _gateway("installation-a"))+ try:+ assert ws_runtime.active_launcher_gateway_sid() == fresh_sid+ assert ws_runtime.store_sid_launcher_gateway_metadata(+ stale_sid,+ _gateway("installation-a"),+ ) is None+ finally:+ ws_runtime.unregister_sid(stale_sid)+ ws_runtime.unregister_sid(fresh_sid)+++def test_gateway_disables_code_execution_when_files_are_off() -> None:+ sid = _sid("scope")+ ws_runtime.register_sid(sid)+ ws_runtime.store_sid_launcher_gateway_metadata(sid, _gateway("installation-a", files=False))+ try:+ gateway = ws_runtime.launcher_gateway_status()["gateway"]+ assert gateway["scopes"]["files"] is False+ assert gateway["scopes"]["code_execution"] is False+ finally:+ ws_runtime.unregister_sid(sid)+++def test_gateway_status_metadata_is_bounded() -> None:+ sid = _sid("bounded")+ payload = _gateway("installation-a")+ payload["status"] = {+ "browser": {+ "message": "x" * 4000,+ "available_browsers": [{"browser_id": f"browser-{index}"} for index in range(100)],+ },+ "computer_use": {+ "capabilities": {"elements": {"tree_backends": ["ax", "at-spi"]}}+ },+ }+ ws_runtime.register_sid(sid)+ ws_runtime.store_sid_launcher_gateway_metadata(sid, payload)+ try:+ status = ws_runtime.launcher_gateway_status()["gateway"]["status"]+ assert len(status["browser"]["message"]) == 2048+ assert len(status["browser"]["available_browsers"]) == 64+ assert status["computer_use"]["capabilities"]["elements"]["tree_backends"] == [+ "ax",+ "at-spi",+ ]+ finally:+ ws_runtime.unregister_sid(sid)+++def test_gateway_control_requires_csrf_and_waits_for_ack(monkeypatch) -> None:+ sid = _sid("control")+ ws_runtime.register_sid(sid)+ ws_runtime.store_sid_launcher_gateway_metadata(sid, _gateway("installation-a"))++ class FakeManager:+ async def emit_to(self, namespace, target_sid, event, data, **kwargs):+ assert namespace == "/ws"+ assert target_sid == sid+ assert event == "connector_gateway_control"+ updated = _gateway("installation-a")+ updated["master_enabled"] = False+ updated["state"] = "paused"+ ws_runtime.resolve_pending_gateway_control(+ data["request_id"],+ sid=sid,+ payload={+ "request_id": data["request_id"],+ "ok": True,+ "gateway": updated,+ },+ )++ monkeypatch.setattr(launcher_gateway_control, "get_shared_ws_manager", lambda: FakeManager())+ handler = launcher_gateway_control.LauncherGatewayControl(None, None)+ try:+ result = asyncio.run(handler.process({"action": "set_master", "enabled": False}, None))+ assert handler.requires_auth() is True+ assert handler.requires_csrf() is True+ assert result["ok"] is True+ assert result["status"]["gateway"]["master_enabled"] is False+ finally:+ ws_runtime.unregister_sid(sid)+++def test_gateway_control_acknowledgement_timeout(monkeypatch) -> None:+ sid = _sid("timeout")+ ws_runtime.register_sid(sid)+ ws_runtime.store_sid_launcher_gateway_metadata(sid, _gateway("installation-a"))++ class SilentManager:+ async def emit_to(self, *_args, **_kwargs):+ return None++ monkeypatch.setattr(launcher_gateway_control, "get_shared_ws_manager", lambda: SilentManager())+ monkeypatch.setattr(launcher_gateway_control, "_CONTROL_TIMEOUT_SECONDS", 0.01)+ handler = launcher_gateway_control.LauncherGatewayControl(None, None)+ try:+ result = asyncio.run(handler.process({"action": "set_master", "enabled": False}, None))+ assert result.status_code == 504+ finally:+ ws_runtime.unregister_sid(sid)+++def test_gateway_emergency_disconnect_returns_acknowledged_disconnected_state(monkeypatch) -> None:+ sid = _sid("emergency")+ ws_runtime.register_sid(sid)+ ws_runtime.store_sid_launcher_gateway_metadata(sid, _gateway("installation-a"))++ class FakeManager:+ async def emit_to(self, _namespace, target_sid, event, data, **_kwargs):+ assert target_sid == sid+ assert event == "connector_gateway_control"+ assert data["action"] == "emergency_disconnect"+ updated = _gateway("installation-a")+ updated["state"] = "disconnected"+ ws_runtime.resolve_pending_gateway_control(+ data["request_id"],+ sid=sid,+ payload={+ "request_id": data["request_id"],+ "ok": True,+ "gateway": updated,+ },+ )++ monkeypatch.setattr(launcher_gateway_control, "get_shared_ws_manager", lambda: FakeManager())+ handler = launcher_gateway_control.LauncherGatewayControl(None, None)+ try:+ result = asyncio.run(handler.process({"action": "emergency_disconnect"}, None))+ assert result["ok"] is True+ assert result["status"]["state"] == "disconnected"+ finally:+ ws_runtime.unregister_sid(sid)