Agent Zero AI framework
Add Remote Control tunnel providers
Alessandro67224672e89d
diff --git a/extensions/webui/right_canvas_register_surfaces/register-remote-link.js b/extensions/webui/right_canvas_register_surfaces/register-remote-link.jsindex ca8dc6dfb..dd0d95d4d 100644--- a/extensions/webui/right_canvas_register_surfaces/register-remote-link.js+++ b/extensions/webui/right_canvas_register_surfaces/register-remote-link.js@@ -1,3 +1,3 @@export default async function registerRemoteLinkAction() {- // Remote Link is opened from the sidebar dropdown, not the right canvas rail.+ // Remote Control is opened from the sidebar dropdown, not the right canvas rail.}diff --git a/helpers/cli_tunnel.py b/helpers/cli_tunnel.pynew file mode 100644index 000000000..05f702fc9--- /dev/null+++ b/helpers/cli_tunnel.py@@ -0,0 +1,262 @@+import os+import platform+import queue+import shutil+import subprocess+import tarfile+import tempfile+import threading+import time+import urllib.request+import zipfile+from collections import deque+from pathlib import Path++from flaredantic import NotifyEvent++from helpers import files+from helpers.tunnel_common import TunnelHelper+++RUNTIME_BIN_DIR = Path(files.get_abs_path("tmp", "bin"))+++def executable_name(name):+ return f"{name}.exe" if platform.system().lower() == "windows" else name+++def chmod_executable(path):+ if platform.system().lower() != "windows":+ path.chmod(0o755)+++def notify_download(notify, message, data=None):+ if callable(notify):+ notify(NotifyEvent.DOWNLOADING, message, data)+++def notify_download_complete(notify, message, data=None):+ if callable(notify):+ notify(NotifyEvent.DOWNLOAD_COMPLETE, message, data)+++def download_file(url, destination, notify=None):+ destination.parent.mkdir(parents=True, exist_ok=True)+ notify_download(notify, f"Downloading {url}")+ temp_fd, temp_name = tempfile.mkstemp(+ prefix=f"{destination.name}.",+ suffix=".download",+ dir=str(destination.parent),+ )+ os.close(temp_fd)+ temp_path = Path(temp_name)+ try:+ with urllib.request.urlopen(url, timeout=60) as response:+ with temp_path.open("wb") as handle:+ shutil.copyfileobj(response, handle)+ temp_path.replace(destination)+ notify_download_complete(notify, f"Downloaded {destination.name}")+ return destination+ except Exception:+ temp_path.unlink(missing_ok=True)+ raise+++def platform_parts():+ system = platform.system().lower()+ machine = platform.machine().lower()+ if machine in {"x86_64", "amd64"}:+ arch = "amd64"+ elif machine in {"aarch64", "arm64"}:+ arch = "arm64"+ elif machine in {"i386", "i686", "x86"}:+ arch = "386"+ elif machine.startswith("arm"):+ arch = "arm"+ else:+ raise RuntimeError(f"Unsupported CPU architecture for tunnel binary: {machine}")++ if system not in {"linux", "darwin", "windows"}:+ raise RuntimeError(f"Unsupported operating system for tunnel binary: {system}")+ return system, arch+++def extract_named_members_from_tar(archive_path, destination_dir, member_names):+ destination_dir.mkdir(parents=True, exist_ok=True)+ extracted = {}+ wanted = set(member_names)+ with tarfile.open(archive_path, "r:*") as archive:+ for member in archive.getmembers():+ member_name = Path(member.name).name+ if member_name not in wanted or not member.isfile():+ continue+ target = destination_dir / executable_name(member_name)+ source = archive.extractfile(member)+ if source is None:+ continue+ with source, target.open("wb") as handle:+ shutil.copyfileobj(source, handle)+ chmod_executable(target)+ extracted[member_name] = target+ missing = wanted - set(extracted)+ if missing:+ raise RuntimeError(+ f"Archive {archive_path.name} did not contain expected binaries: "+ f"{', '.join(sorted(missing))}."+ )+ return extracted+++def extract_named_members_from_zip(archive_path, destination_dir, member_names):+ destination_dir.mkdir(parents=True, exist_ok=True)+ extracted = {}+ wanted = set(member_names)+ with zipfile.ZipFile(archive_path) as archive:+ for member in archive.infolist():+ member_name = Path(member.filename).name+ normalized_name = member_name.removesuffix(".exe")+ if normalized_name not in wanted or member.is_dir():+ continue+ target = destination_dir / executable_name(normalized_name)+ with archive.open(member) as source, target.open("wb") as handle:+ shutil.copyfileobj(source, handle)+ chmod_executable(target)+ extracted[normalized_name] = target+ missing = wanted - set(extracted)+ if missing:+ raise RuntimeError(+ f"Archive {archive_path.name} did not contain expected binaries: "+ f"{', '.join(sorted(missing))}."+ )+ return extracted+++class CliTunnelHelper(TunnelHelper):+ label = "CLI tunnel"++ def __init__(+ self,+ *,+ label,+ binary,+ port,+ command,+ url_pattern,+ missing_binary_message,+ shutdown_command=None,+ timeout=30,+ notify=None,+ binary_resolver=None,+ preflight=None,+ ):+ super().__init__(port, notify=notify)+ self.label = label+ self.binary = binary+ self.command = command+ self.url_pattern = url_pattern+ self.missing_binary_message = missing_binary_message+ self.shutdown_command = shutdown_command+ self.timeout = timeout+ self.tunnel_process = None+ self.binary_path = None+ self.binary_resolver = binary_resolver+ self.preflight = preflight+ self.command_prefix = []++ def _extract_url(self, line):+ match = self.url_pattern.search(line)+ if not match:+ return None+ return match.group(1 if match.lastindex else 0).rstrip(".,)")++ def start(self):+ binary_path = (+ self.binary_resolver(self._notify)+ if callable(self.binary_resolver)+ else shutil.which(self.binary)+ )+ if not binary_path:+ raise RuntimeError(self.missing_binary_message)+ self.binary_path = binary_path+ if callable(self.preflight):+ preflight_result = self.preflight(binary_path, notify=self._notify)+ if isinstance(preflight_result, dict):+ self.command_prefix = list(preflight_result.get("command_prefix") or [])++ command = [binary_path, *self.command_prefix, *self.command[1:]]+ self.notify_starting(self.label)+ self.tunnel_process = subprocess.Popen(+ command,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ bufsize=1,+ )++ output_queue = queue.Queue()++ def read_output():+ if self.tunnel_process is None or self.tunnel_process.stdout is None:+ return+ for line in self.tunnel_process.stdout:+ output_queue.put(line)++ threading.Thread(target=read_output, daemon=True).start()++ deadline = time.monotonic() + self.timeout+ recent_output = deque(maxlen=8)+ while time.monotonic() < deadline:+ try:+ line = output_queue.get(timeout=0.1)+ except queue.Empty:+ if self.tunnel_process.poll() is not None:+ break+ continue++ cleaned_line = line.strip()+ if cleaned_line:+ recent_output.append(cleaned_line)+ url = self._extract_url(cleaned_line)+ if url:+ self.tunnel_url = url+ self.notify_url_ready(self.label, url)+ return self.tunnel_url++ details = " ".join(recent_output)+ if self.tunnel_process.poll() is not None:+ raise RuntimeError(+ f"{self.label} exited before it reported a remote URL."+ + (f" Output: {details}" if details else "")+ )+ self._terminate_process()+ raise RuntimeError(+ f"{self.label} did not report a remote URL within {self.timeout} seconds."+ + (f" Output: {details}" if details else "")+ )++ def _terminate_process(self):+ if not self.tunnel_process or self.tunnel_process.poll() is not None:+ return+ self.tunnel_process.terminate()+ try:+ self.tunnel_process.wait(timeout=8)+ except subprocess.TimeoutExpired:+ self.tunnel_process.kill()+ self.tunnel_process.wait(timeout=3)++ def stop(self):+ self._terminate_process()++ if self.shutdown_command:+ binary_path = self.binary_path or shutil.which(self.binary)+ if binary_path:+ subprocess.run(+ [binary_path, *self.command_prefix, *self.shutdown_command[1:]],+ check=False,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=10,+ )+ self.tunnel_url = None+ self.notify_stopped(self.label)+ return Truediff --git a/helpers/cloudflare_tunnel._py b/helpers/cloudflare_tunnel._pyindex 5ef12de8e..3d0e825f2 100644--- a/helpers/cloudflare_tunnel._py+++ b/helpers/cloudflare_tunnel._py@@ -120,11 +120,11 @@ class CloudflareTunnel:returndef start(self):- """Starts the cloudflare tunnel"""+ """Starts Cloudflare Tunnel"""if not self.cloudflared_path:self.download_cloudflared()- PrintStyle().print("\nStarting Cloudflare tunnel...")+ PrintStyle().print("\nStarting Cloudflare Tunnel...")# Start tunnel processself.tunnel_process = subprocess.Popen([@@ -147,11 +147,11 @@ class CloudflareTunnel:).start()def stop(self):- """Stops the cloudflare tunnel"""+ """Stops Cloudflare Tunnel"""self._stop_event.set()if self.tunnel_process:- PrintStyle().print("\nStopping Cloudflare tunnel...")+ PrintStyle().print("\nStopping Cloudflare Tunnel...")self.tunnel_process.terminate()self.tunnel_process.wait()self.tunnel_process = None- self.tunnel_url = None\ No newline at end of file+ self.tunnel_url = Nonediff --git a/helpers/cloudflare_tunnel.py b/helpers/cloudflare_tunnel.pynew file mode 100644index 000000000..ba446f32a--- /dev/null+++ b/helpers/cloudflare_tunnel.py@@ -0,0 +1,11 @@+from flaredantic import FlareConfig, FlareTunnel++from helpers.tunnel_common import FlaredanticTunnelHelper+++class CloudflareTunnel(FlaredanticTunnelHelper):+ label = "Cloudflare Tunnel"++ def build_tunnel(self):+ config = FlareConfig(port=self.port, verbose=True)+ return FlareTunnel(config)diff --git a/helpers/microsoft_tunnel.py b/helpers/microsoft_tunnel.pynew file mode 100644index 000000000..40173e376--- /dev/null+++ b/helpers/microsoft_tunnel.py@@ -0,0 +1,144 @@+import getpass+import hashlib+import os+import socket++from flaredantic import MicrosoftConfig, MicrosoftTunnel, NotifyEvent++try:+ from flaredantic.core.exceptions import MicrosoftTunnelError+except Exception: # pragma: no cover - keeps tests independent from package internals+ MicrosoftTunnelError = RuntimeError++from helpers import files+from helpers.tunnel_common import FlaredanticTunnelHelper+++MICROSOFT_TUNNEL_ID_ENV_KEYS = (+ "A0_MICROSOFT_DEV_TUNNEL_ID",+ "MICROSOFT_DEV_TUNNEL_ID",+)+MICROSOFT_TUNNEL_TIMEOUT = 120+++def default_microsoft_tunnel_id():+ for env_key in MICROSOFT_TUNNEL_ID_ENV_KEYS:+ configured = (os.environ.get(env_key) or "").strip()+ if configured:+ return configured++ seed = "|".join([+ getpass.getuser(),+ socket.gethostname(),+ files.get_abs_path("usr"),+ ])+ digest = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:10]+ return f"agent-zero-{digest}"+++class AgentZeroMicrosoftTunnel(MicrosoftTunnel):+ def notify(self, event, message, data=None):+ try:+ return super().notify(event, message, data)+ except AttributeError:+ self.agent_zero_notifications.append({+ "event": event.value if hasattr(event, "value") else event,+ "message": message,+ "data": data,+ })+ return None++ @property+ def agent_zero_notifications(self):+ if not hasattr(self, "_agent_zero_notifications"):+ self._agent_zero_notifications = []+ return self._agent_zero_notifications++ def _notify_progress(self, message, data=None):+ self.notify(NotifyEvent.INFO, message, data)++ def _ensure_logged_in(self):+ parent = getattr(super(), "_ensure_logged_in", None)+ if callable(parent):+ parent()+ self._notify_progress(+ "Microsoft Dev Tunnels login confirmed. Preparing your tunnel..."+ )++ def _ensure_tunnel(self):+ tunnel_id = self.config.tunnel_id+ port = str(self.config.port)++ self._notify_progress(+ f"Checking Microsoft Dev Tunnel `{tunnel_id}`...",+ {"tunnel_id": tunnel_id},+ )+ show = self._run_cmd(["show", tunnel_id])+ if show.returncode != 0:+ self._notify_progress(+ f"Creating Microsoft Dev Tunnel `{tunnel_id}`...",+ {"tunnel_id": tunnel_id},+ )+ create = self._run_cmd(["create", tunnel_id])+ if create.returncode != 0:+ raise MicrosoftTunnelError(f"Failed to create tunnel: {create.stdout}")+ else:+ self._notify_progress(+ f"Microsoft Dev Tunnel `{tunnel_id}` already exists. Checking port {port}...",+ {"tunnel_id": tunnel_id, "port": port},+ )++ self._notify_progress(+ f"Checking Microsoft Dev Tunnel port {port}...",+ {"tunnel_id": tunnel_id, "port": port},+ )+ port_show = self._run_cmd(["port", "show", tunnel_id, "-p", port])+ if port_show.returncode != 0:+ self._notify_progress(+ f"Creating Microsoft Dev Tunnel port {port}...",+ {"tunnel_id": tunnel_id, "port": port},+ )+ port_create = self._run_cmd([+ "port",+ "create",+ tunnel_id,+ "-p",+ port,+ "--protocol",+ "http",+ ])+ if port_create.returncode != 0:+ raise MicrosoftTunnelError(+ f"Failed to create port: {port_create.stdout}"+ )++ self._notify_progress(+ "Microsoft Dev Tunnel setup is ready. Starting the secure host..."+ )+++class MicrosoftDevTunnel(FlaredanticTunnelHelper):+ label = "Microsoft Dev Tunnels"++ def build_tunnel(self):+ config = MicrosoftConfig(+ port=self.port,+ verbose=True,+ timeout=MICROSOFT_TUNNEL_TIMEOUT,+ tunnel_id=default_microsoft_tunnel_id(),+ )+ return AgentZeroMicrosoftTunnel(config)++ def start(self):+ try:+ return super().start()+ except Exception as e:+ if "Timeout waiting for Microsoft Dev Tunnels URL" not in str(e):+ raise+ tunnel_id = default_microsoft_tunnel_id()+ raise RuntimeError(+ "Microsoft Dev Tunnels did not return a URL. Agent Zero uses "+ f"the tunnel id `{tunnel_id}` to avoid flaredantic's global "+ "`flaredantic` tunnel-id collision. If this still fails, set "+ "`A0_MICROSOFT_DEV_TUNNEL_ID` to a fresh unique value and try again."+ ) from ediff --git a/helpers/runtime.py b/helpers/runtime.pyindex 1d4b084e1..5751de5f7 100644--- a/helpers/runtime.py+++ b/helpers/runtime.py@@ -31,7 +31,7 @@ def initialize():"--cloudflare_tunnel",type=bool,default=False,- help="Use cloudflare tunnel for public URL",+ help="Use Cloudflare Tunnel for public URL",)parser.add_argument("--development", type=bool, default=False, help="Development mode"diff --git a/helpers/serveo_tunnel.py b/helpers/serveo_tunnel.pynew file mode 100644index 000000000..5c5e36878--- /dev/null+++ b/helpers/serveo_tunnel.py@@ -0,0 +1,11 @@+from flaredantic import ServeoConfig, ServeoTunnel++from helpers.tunnel_common import FlaredanticTunnelHelper+++class ServeoTunnelHelper(FlaredanticTunnelHelper):+ label = "Serveo"++ def build_tunnel(self):+ config = ServeoConfig(port=self.port)+ return ServeoTunnel(config)diff --git a/helpers/tailscale_tunnel.py b/helpers/tailscale_tunnel.pynew file mode 100644index 000000000..25e13361e--- /dev/null+++ b/helpers/tailscale_tunnel.py@@ -0,0 +1,433 @@+from collections import deque+import json+import os+import queue+import re+import shutil+import subprocess+import threading+import time+import urllib.parse+import urllib.request+from pathlib import Path++from flaredantic import NotifyEvent++from helpers import cli_tunnel, files+from helpers.cli_tunnel import CliTunnelHelper+++TAILSCALE_URL_RE = re.compile(r"https://[a-zA-Z0-9.-]+\.ts\.net[^\s\"']*")+TAILSCALE_LOGIN_URL_RE = re.compile(r"https://login\.tailscale\.com/[^\s\"']+")+TAILSCALE_STABLE_PACKAGES_URL = "https://pkgs.tailscale.com/stable/?v=latest"+TAILSCALE_UP_TIMEOUT = 180+TAILSCALE_DAEMON_START_TIMEOUT = 12+TAILSCALE_RUNTIME_DIR = Path(files.get_abs_path("tmp", "tailscale"))+TAILSCALE_STATE_DIR = Path(files.get_abs_path("usr", "tailscale"))+TAILSCALE_SOCKET_PATH = TAILSCALE_RUNTIME_DIR / "tailscaled.sock"+TAILSCALE_DAEMON_LOG_PATH = TAILSCALE_RUNTIME_DIR / "tailscaled.log"+TAILSCALE_DAEMON_PID_PATH = TAILSCALE_RUNTIME_DIR / "tailscaled.pid"+++def tailscale_arch():+ _, arch = cli_tunnel.platform_parts()+ return arch+++def tailscale_archive_url():+ arch = tailscale_arch()+ with urllib.request.urlopen(TAILSCALE_STABLE_PACKAGES_URL, timeout=30) as response:+ html = response.read().decode("utf-8", errors="replace")+ pattern = re.compile(rf'href="([^"]*tailscale_[^"]+_{re.escape(arch)}\.tgz)"')+ match = pattern.search(html)+ if not match:+ raise RuntimeError(f"Could not find a Tailscale static binary for {arch}.")+ return urllib.parse.urljoin(TAILSCALE_STABLE_PACKAGES_URL, match.group(1))+++def install_tailscale(notify=None):+ existing = shutil.which("tailscale")+ if existing and resolve_tailscaled_binary(existing):+ return existing++ install_path = cli_tunnel.RUNTIME_BIN_DIR / cli_tunnel.executable_name("tailscale")+ daemon_path = cli_tunnel.RUNTIME_BIN_DIR / cli_tunnel.executable_name("tailscaled")+ if install_path.exists() and daemon_path.exists():+ return str(install_path)++ download_url = tailscale_archive_url()+ archive_path = (+ cli_tunnel.RUNTIME_BIN_DIR+ / urllib.parse.urlparse(download_url).path.rsplit("/", 1)[-1]+ )+ cli_tunnel.download_file(download_url, archive_path, notify=notify)+ try:+ extracted = cli_tunnel.extract_named_members_from_tar(+ archive_path,+ cli_tunnel.RUNTIME_BIN_DIR,+ {"tailscale", "tailscaled"},+ )+ return str(extracted["tailscale"])+ finally:+ archive_path.unlink(missing_ok=True)+++def resolve_tailscaled_binary(binary_path):+ sibling = Path(binary_path).with_name(cli_tunnel.executable_name("tailscaled"))+ if sibling.exists():+ return str(sibling)+ return shutil.which("tailscaled")+++def notify_info(notify, message, data=None):+ if callable(notify):+ notify(NotifyEvent.INFO, message, data)+++def tailscale_socket_args(socket_path=None):+ return ["--socket", str(socket_path)] if socket_path else []+++def tailscale_command(binary_path, args, socket_path=None):+ return [binary_path, *tailscale_socket_args(socket_path), *args]+++def tailscale_status(binary_path, socket_path=None):+ return subprocess.run(+ tailscale_command(binary_path, ["status", "--json"], socket_path),+ check=False,+ text=True,+ capture_output=True,+ timeout=12,+ )+++def compact_output(lines):+ return " ".join(line.strip() for line in lines if line and line.strip())+++def tailscale_daemon_hint(output):+ lowered = output.lower()+ return any(+ marker in lowered+ for marker in (+ "failed to connect to local tailscaled",+ "tailscaled.sock",+ "no such file or directory",+ "connection refused",+ "is tailscaled running",+ )+ )+++def tailscale_daemon_ready(binary_path, socket_path):+ completed = tailscale_status(binary_path, socket_path=socket_path)+ output = compact_output([completed.stderr, completed.stdout])+ return not tailscale_daemon_hint(output)+++def read_recent_tailscaled_log():+ if not TAILSCALE_DAEMON_LOG_PATH.exists():+ return ""+ try:+ lines = TAILSCALE_DAEMON_LOG_PATH.read_text(+ encoding="utf-8",+ errors="replace",+ ).splitlines()+ except OSError:+ return ""+ return compact_output(lines[-12:])+++def start_tailscaled(binary_path, notify=None):+ daemon_path = resolve_tailscaled_binary(binary_path)+ if not daemon_path:+ raise RuntimeError(+ "Tailscale was prepared, but Agent Zero could not find the "+ "`tailscaled` daemon binary. Try Tailscale Remote Control again so "+ "Agent Zero can re-download the static Tailscale package."+ )++ if tailscale_daemon_ready(binary_path, TAILSCALE_SOCKET_PATH):+ return TAILSCALE_SOCKET_PATH++ TAILSCALE_RUNTIME_DIR.mkdir(parents=True, exist_ok=True)+ TAILSCALE_STATE_DIR.mkdir(parents=True, exist_ok=True)+ TAILSCALE_SOCKET_PATH.unlink(missing_ok=True)++ notify_info(+ notify,+ "Starting Tailscale's background service inside this container...",+ )++ log_handle = TAILSCALE_DAEMON_LOG_PATH.open("ab")+ process = subprocess.Popen(+ [+ daemon_path,+ "--tun=userspace-networking",+ "--socket",+ str(TAILSCALE_SOCKET_PATH),+ "--statedir",+ str(TAILSCALE_STATE_DIR),+ "--state",+ str(TAILSCALE_STATE_DIR / "tailscaled.state"),+ ],+ stdout=log_handle,+ stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL,+ start_new_session=True,+ close_fds=True,+ )+ log_handle.close()+ TAILSCALE_DAEMON_PID_PATH.write_text(str(process.pid), encoding="utf-8")++ deadline = time.monotonic() + TAILSCALE_DAEMON_START_TIMEOUT+ while time.monotonic() < deadline:+ if process.poll() is not None:+ break+ if tailscale_daemon_ready(binary_path, TAILSCALE_SOCKET_PATH):+ notify_info(notify, "Tailscale background service is running.")+ return TAILSCALE_SOCKET_PATH+ time.sleep(0.25)++ details = read_recent_tailscaled_log()+ if process.poll() is None:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=3)+ TAILSCALE_DAEMON_PID_PATH.unlink(missing_ok=True)+ message = (+ "Agent Zero downloaded Tailscale, but could not start the `tailscaled` "+ "background service in this container."+ )+ if details:+ message = f"{message} Details: {details}"+ raise RuntimeError(message)+++def stop_managed_tailscaled():+ if not TAILSCALE_DAEMON_PID_PATH.exists():+ return+ try:+ pid = int(TAILSCALE_DAEMON_PID_PATH.read_text(encoding="utf-8").strip())+ except Exception:+ TAILSCALE_DAEMON_PID_PATH.unlink(missing_ok=True)+ return+ try:+ cmdline = Path(f"/proc/{pid}/cmdline").read_bytes().decode(+ "utf-8",+ errors="replace",+ )+ except Exception:+ cmdline = ""+ if "tailscaled" in cmdline:+ try:+ os.kill(pid, 15)+ deadline = time.monotonic() + 5+ while time.monotonic() < deadline:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ break+ time.sleep(0.1)+ else:+ os.kill(pid, 9)+ except ProcessLookupError:+ pass+ except PermissionError:+ pass+ TAILSCALE_DAEMON_PID_PATH.unlink(missing_ok=True)+ TAILSCALE_SOCKET_PATH.unlink(missing_ok=True)+++def tailscale_up_failure_message(output, *, timed_out=False):+ details = compact_output(output)+ if tailscale_daemon_hint(details):+ message = (+ "Agent Zero started Tailscale and ran `tailscale up`, but the "+ "Tailscale background service stopped responding."+ )+ elif timed_out:+ message = (+ "Agent Zero ran `tailscale up`, but it did not finish before the "+ "setup timeout. If a Tailscale login link was shown, approve this "+ "container in your browser, then start Remote Control again."+ )+ else:+ message = (+ "Agent Zero ran `tailscale up`, but Tailscale did not finish joining "+ "this container to your tailnet. Complete any Tailscale login or "+ "admin approval it requested, then try Tailscale Remote Control again."+ )+ if details:+ message = f"{message} Details: {details}"+ return message+++def run_tailscale_up(+ binary_path,+ notify=None,+ timeout=TAILSCALE_UP_TIMEOUT,+ socket_path=None,+):+ notify_info(+ notify,+ "Tailscale needs this container to join your tailnet. Running `tailscale up` now...",+ )+ process = subprocess.Popen(+ tailscale_command(binary_path, ["up"], socket_path),+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ bufsize=1,+ )+ output_queue = queue.Queue()++ def read_output():+ if process.stdout is None:+ return+ for line in process.stdout:+ output_queue.put(line)++ reader = threading.Thread(target=read_output, daemon=True)+ reader.start()+ deadline = time.monotonic() + timeout+ recent_output = deque(maxlen=10)+ login_announced = False++ def record_line(line):+ nonlocal login_announced+ cleaned = line.strip()+ if not cleaned:+ return+ recent_output.append(cleaned)+ login_match = TAILSCALE_LOGIN_URL_RE.search(cleaned)+ if login_match and not login_announced:+ login_url = login_match.group(0).rstrip(".,)")+ notify_info(+ notify,+ "Open the Tailscale login link and approve this container. "+ "Agent Zero will continue when Tailscale finishes setup.",+ {"provider": "tailscale", "url": login_url},+ )+ login_announced = True++ while True:+ try:+ record_line(output_queue.get(timeout=0.1))+ except queue.Empty:+ if process.poll() is not None:+ reader.join(timeout=1)+ while True:+ try:+ record_line(output_queue.get_nowait())+ except queue.Empty:+ break+ break+ if time.monotonic() >= deadline:+ process.terminate()+ try:+ process.wait(timeout=8)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=3)+ reader.join(timeout=1)+ while True:+ try:+ record_line(output_queue.get_nowait())+ except queue.Empty:+ break+ raise RuntimeError(+ tailscale_up_failure_message(recent_output, timed_out=True)+ )+ continue++ returncode = process.wait(timeout=3)+ if returncode != 0:+ raise RuntimeError(tailscale_up_failure_message(recent_output))++ notify_info(+ notify,+ "Tailscale setup completed. Checking the tailnet connection...",+ )+++def ensure_tailscale_ready(binary_path, notify=None):+ socket_path = None+ completed = tailscale_status(binary_path)+ if completed.returncode != 0 and tailscale_daemon_hint(+ compact_output([completed.stderr, completed.stdout])+ ):+ socket_path = start_tailscaled(binary_path, notify=notify)+ completed = tailscale_status(binary_path, socket_path=socket_path)++ if completed.returncode != 0:+ run_tailscale_up(binary_path, notify=notify, socket_path=socket_path)+ completed = tailscale_status(binary_path, socket_path=socket_path)+ if completed.returncode != 0:+ details = compact_output([completed.stderr, completed.stdout])+ message = (+ "Agent Zero ran `tailscale up`, but Tailscale status is still "+ "not available. Tailscale may still need browser approval, admin "+ "approval, or a running `tailscaled` service."+ )+ if details:+ message = f"{message} Details: {details}"+ raise RuntimeError(message)++ try:+ payload = json.loads(completed.stdout or "{}")+ except json.JSONDecodeError:+ return++ backend_state = str(payload.get("BackendState") or "").lower()+ if backend_state and backend_state != "running":+ run_tailscale_up(binary_path, notify=notify, socket_path=socket_path)+ completed = tailscale_status(binary_path, socket_path=socket_path)+ try:+ payload = json.loads(completed.stdout or "{}")+ except json.JSONDecodeError:+ return {"command_prefix": tailscale_socket_args(socket_path)}+ backend_state = str(payload.get("BackendState") or "").lower()+ if backend_state and backend_state != "running":+ raise RuntimeError(+ "Agent Zero ran `tailscale up`, but this node is still not ready "+ "for Tailscale Funnel "+ f"(state: {backend_state}). Complete Tailscale sign-in or admin "+ "approval, then try again."+ )++ return {"command_prefix": tailscale_socket_args(socket_path)}+++class TailscaleTunnel(CliTunnelHelper):+ def __init__(self, port, notify=None):+ target = f"http://127.0.0.1:{port}"+ super().__init__(+ label="Tailscale Funnel",+ binary="tailscale",+ port=port,+ command=["tailscale", "funnel", "--yes", target],+ url_pattern=TAILSCALE_URL_RE,+ missing_binary_message=(+ "Tailscale could not be prepared in this environment. Install "+ "Tailscale, make sure the `tailscaled` service is available to "+ "this container, enable Funnel for the tailnet, then try again."+ ),+ shutdown_command=["tailscale", "funnel", "--yes", target, "off"],+ binary_resolver=lambda notify_callback: install_tailscale(+ notify=notify_callback+ ),+ preflight=ensure_tailscale_ready,+ notify=notify,+ )++ def stop(self):+ try:+ return super().stop()+ finally:+ if self.command_prefix:+ stop_managed_tailscaled()diff --git a/helpers/tunnel_common.py b/helpers/tunnel_common.pynew file mode 100644index 000000000..9daa0a972--- /dev/null+++ b/helpers/tunnel_common.py@@ -0,0 +1,56 @@+from flaredantic import NotifyEvent+++def event_value(event):+ return event.value if hasattr(event, "value") else event+++class TunnelHelper:+ def __init__(self, port, notify=None):+ self.port = port+ self.notify_callback = notify+ self.tunnel = None+ self.tunnel_url = None++ def _notify(self, event, message, data=None):+ if callable(self.notify_callback):+ self.notify_callback(event, message, data)++ def notify_starting(self, label):+ self._notify(+ NotifyEvent.CREATING_TUNNEL,+ f"Starting {label} on port {self.port}...",+ )++ def notify_url_ready(self, label, url):+ self._notify(+ NotifyEvent.TUNNEL_URL,+ f"{label} URL is ready",+ {"url": url},+ )++ def notify_stopped(self, label):+ self._notify(NotifyEvent.TUNNEL_STOPPED, f"{label} stopped")+++class FlaredanticTunnelHelper(TunnelHelper):+ label = "Remote Control"++ def build_tunnel(self):+ raise NotImplementedError++ def start(self):+ self.notify_starting(self.label)+ self.tunnel = self.build_tunnel()+ self.tunnel.start()+ self.tunnel_url = getattr(self.tunnel, "tunnel_url", None)+ if self.tunnel_url:+ self.notify_url_ready(self.label, self.tunnel_url)+ return self.tunnel_url++ def stop(self):+ if self.tunnel:+ self.tunnel.stop()+ self.tunnel_url = None+ self.notify_stopped(self.label)+ return Truediff --git a/helpers/tunnel_manager.py b/helpers/tunnel_manager.pyindex 4a2ddbeb2..984fd841a 100644--- a/helpers/tunnel_manager.py+++ b/helpers/tunnel_manager.py@@ -1,13 +1,42 @@-from flaredantic import (- FlareTunnel, FlareConfig,- ServeoConfig, ServeoTunnel,- MicrosoftTunnel, MicrosoftConfig,- notifier, NotifyData, NotifyEvent-)import threading+import timefrom collections import deque+from flaredantic import NotifyData, NotifyEvent, notifier++from helpers.cloudflare_tunnel import CloudflareTunnel+from helpers.microsoft_tunnel import MicrosoftDevTunnelfrom helpers.print_style import PrintStyle+from helpers.serveo_tunnel import ServeoTunnelHelper+from helpers.tailscale_tunnel import TailscaleTunnel+from helpers.tunnel_common import event_value+++SUPPORTED_TUNNEL_PROVIDERS = {+ "cloudflared",+ "microsoft",+ "serveo",+ "tailscale",+}+TUNNEL_PROVIDER_ALIASES = {+ "cloudflare": "cloudflared",+ "cloudflare_tunnel": "cloudflared",+ "cloudflare-tunnel": "cloudflared",+ "tailscale_funnel": "tailscale",+ "tailscale-funnel": "tailscale",+}+++def normalize_provider(provider):+ normalized = (provider or "serveo").strip().lower()+ normalized = TUNNEL_PROVIDER_ALIASES.get(normalized, normalized)+ if normalized not in SUPPORTED_TUNNEL_PROVIDERS:+ supported = ", ".join(sorted(SUPPORTED_TUNNEL_PROVIDERS))+ raise ValueError(+ f"Unsupported remote control provider '{provider}'. Choose one of: {supported}."+ )+ return normalized+# Singleton to manage the tunnel instanceclass TunnelManager:@@ -30,80 +59,86 @@ class TunnelManager:self._subscribed = Falsedef _on_notify(self, data: NotifyData):- """Handle notifications from flaredantic"""+ """Handle notifications from flaredantic."""self.notifications.append({"event": data.event.value,"message": data.message,- "data": data.data+ "data": data.data,})def _ensure_subscribed(self):- """Subscribe to flaredantic notifications if not already"""+ """Subscribe to flaredantic notifications if not already."""if not self._subscribed:notifier.subscribe(self._on_notify)self._subscribed = Truedef get_notifications(self):- """Get and clear pending notifications"""+ """Get and clear pending notifications."""notifications = list(self.notifications)self.notifications.clear()return notificationsdef get_last_error(self):- """Check for recent error in notifications without clearing"""- for n in reversed(list(self.notifications)):- if n['event'] == NotifyEvent.ERROR.value:- return n['message']+ """Check for recent error in notifications without clearing."""+ for notification in reversed(list(self.notifications)):+ if notification["event"] == NotifyEvent.ERROR.value:+ return notification["message"]return None+ def _append_notification(self, event, message, data=None):+ self.notifications.append({+ "event": event_value(event),+ "message": message,+ "data": data,+ })++ def _create_tunnel(self, port, provider):+ if provider == "cloudflared":+ return CloudflareTunnel(port, notify=self._append_notification)+ if provider == "microsoft":+ return MicrosoftDevTunnel(port, notify=self._append_notification)+ if provider == "tailscale":+ return TailscaleTunnel(port, notify=self._append_notification)+ return ServeoTunnelHelper(port, notify=self._append_notification)+def start_tunnel(self, port=80, provider="serveo"):- """Start a new tunnel or return the existing one's URL"""+ """Start a new tunnel or return the existing one's URL."""if self.is_running and self.tunnel_url:return self.tunnel_url- self.provider = providerself._ensure_subscribed()self.notifications.clear()+ try:+ self.provider = normalize_provider(provider)+ except Exception as e:+ error_msg = str(e)+ PrintStyle.error(f"Error starting tunnel: {error_msg}")+ self._append_notification(NotifyEvent.ERROR, error_msg)+ return Nonetry:- # Start tunnel in a separate thread to avoid blocking+ # Start tunnel in a separate thread to avoid blocking.def run_tunnel():try:- if self.provider == "cloudflared":- config = FlareConfig(port=port, verbose=True)- self.tunnel = FlareTunnel(config)- elif self.provider == "microsoft":- config = MicrosoftConfig(port=port, verbose=True) # type: ignore- self.tunnel = MicrosoftTunnel(config)- else: # Default to serveo- config = ServeoConfig(port=port) # type: ignore- self.tunnel = ServeoTunnel(config)-+ self.tunnel = self._create_tunnel(port, self.provider)self.tunnel.start()self.tunnel_url = self.tunnel.tunnel_urlself.is_running = Trueexcept Exception as e:error_msg = str(e)PrintStyle.error(f"Error in tunnel thread: {error_msg}")- self.notifications.append({- "event": NotifyEvent.ERROR.value,- "message": error_msg,- "data": None- })+ self._append_notification(NotifyEvent.ERROR, error_msg)tunnel_thread = threading.Thread(target=run_tunnel)tunnel_thread.daemon = Truetunnel_thread.start()- # Wait for tunnel to start (no timeout - user may need time for login)- import time+ # No timeout: Microsoft login can legitimately require user interaction.while True:if self.tunnel_url:break- # Check if we have errors- if any(n['event'] == NotifyEvent.ERROR.value for n in self.notifications):+ if any(n["event"] == NotifyEvent.ERROR.value for n in self.notifications):break- # Check if thread died without producing URLif not tunnel_thread.is_alive():breaktime.sleep(0.1)@@ -114,7 +149,7 @@ class TunnelManager:return Nonedef stop_tunnel(self):- """Stop the running tunnel"""+ """Stop the running tunnel."""if self.tunnel and self.is_running:try:self.tunnel.stop()@@ -127,5 +162,5 @@ class TunnelManager:return Falsedef get_tunnel_url(self):- """Get the current tunnel URL if available"""+ """Get the current tunnel URL if available."""return self.tunnel_url if self.is_running else Nonediff --git a/tests/test_tunnel_remote_link.py b/tests/test_tunnel_remote_link.pynew file mode 100644index 000000000..0e8fdbdf4--- /dev/null+++ b/tests/test_tunnel_remote_link.py@@ -0,0 +1,757 @@+import io+import enum+import importlib+import os+import sys+import tarfile+import types+import zipfile+from pathlib import Path++import pytest+++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))+++class FakeNotifyEvent(enum.Enum):+ DOWNLOADING = "downloading"+ DOWNLOAD_PROGRESS = "download_progress"+ DOWNLOAD_COMPLETE = "download_complete"+ CREATING_TUNNEL = "creating_tunnel"+ TUNNEL_URL = "tunnel_url"+ TUNNEL_STOPPED = "tunnel_stopped"+ ERROR = "error"+ INFO = "info"+++class FakeConfig:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+ for key, value in kwargs.items():+ setattr(self, key, value)+++class FakeTunnel:+ def __init__(self, config):+ self.config = config+ self.tunnel_url = ""+ self.stopped = False+ self.notifications = []++ def start(self):+ self.tunnel_url = "https://example.test"+ return self.tunnel_url++ def stop(self):+ self.stopped = True+ return True++ def notify(self, event, message, data=None):+ self.notifications.append({+ "event": event.value if hasattr(event, "value") else event,+ "message": message,+ "data": data,+ })+++class FakeNotifier:+ def subscribe(self, callback):+ self.callback = callback+++def write_tar_archive(path, members):+ path.parent.mkdir(parents=True, exist_ok=True)+ with tarfile.open(path, "w:gz") as archive:+ for name, content in members.items():+ payload = content.encode("utf-8")+ info = tarfile.TarInfo(name)+ info.size = len(payload)+ info.mode = 0o755+ archive.addfile(info, io.BytesIO(payload))+++def write_zip_archive(path, members):+ path.parent.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(path, "w") as archive:+ for name, content in members.items():+ archive.writestr(name, content)+++HELPER_MODULES = [+ "helpers.cli_tunnel",+ "helpers.cloudflare_tunnel",+ "helpers.microsoft_tunnel",+ "helpers.serveo_tunnel",+ "helpers.tailscale_tunnel",+ "helpers.tunnel_common",+ "helpers.tunnel_manager",+]+++def remote_link_modules():+ return types.SimpleNamespace(+ cli=importlib.import_module("helpers.cli_tunnel"),+ microsoft=importlib.import_module("helpers.microsoft_tunnel"),+ tailscale=importlib.import_module("helpers.tailscale_tunnel"),+ )+++def tunnel_manager_module(monkeypatch):+ fake_flaredantic = types.SimpleNamespace(+ FlareConfig=FakeConfig,+ FlareTunnel=FakeTunnel,+ MicrosoftConfig=FakeConfig,+ MicrosoftTunnel=FakeTunnel,+ NotifyData=object,+ NotifyEvent=FakeNotifyEvent,+ ServeoConfig=FakeConfig,+ ServeoTunnel=FakeTunnel,+ notifier=FakeNotifier(),+ )+ monkeypatch.setitem(sys.modules, "flaredantic", fake_flaredantic)+ helpers_package = sys.modules.get("helpers")+ for module_name in HELPER_MODULES:+ sys.modules.pop(module_name, None)+ if helpers_package and hasattr(helpers_package, module_name.rsplit(".", 1)[-1]):+ delattr(helpers_package, module_name.rsplit(".", 1)[-1])+ module = importlib.import_module("helpers.tunnel_manager")+ yield module+ for module_name in HELPER_MODULES:+ sys.modules.pop(module_name, None)+ if helpers_package and hasattr(helpers_package, module_name.rsplit(".", 1)[-1]):+ delattr(helpers_package, module_name.rsplit(".", 1)[-1])+++def test_remote_link_provider_options_match_supported_remote_link_providers():+ html = (+ PROJECT_ROOT / "webui/components/settings/tunnel/tunnel-section.html"+ ).read_text(encoding="utf-8")++ assert html.count("<option value=") == 4+ assert "Remote Control" in html+ assert "Remote " + "Link" not in html+ assert "loginActionVisible" in html+ assert "loginActionTitle" in html+ assert (+ 'class="microsoft-login-box" x-show="$store.tunnelStore.loginActionVisible"'+ in html+ )+ assert '<option value="cloudflared">Cloudflare Tunnel</option>' in html+ assert '<option value="tailscale">Tailscale</option>' in html+ assert '<option value="microsoft">Microsoft Dev Tunnels</option>' in html+ assert '<option value="serveo">Serveo</option>' in html+ assert '<option value="cloudflared">Cloudflare</option>' not in html+ assert "Cloudflare Tunnel is the quickest shareable URL" in html+ assert "Agent Zero will start its sign-in flow" in html+++def test_tunnel_provider_normalization_preserves_aliases(tunnel_manager_module):+ manager = tunnel_manager_module++ assert manager.normalize_provider("cloudflare") == "cloudflared"+ assert manager.normalize_provider("Cloudflare-Tunnel") == "cloudflared"+ assert manager.normalize_provider("tailscale-funnel") == "tailscale"++ with pytest.raises(ValueError, match="Unsupported remote control provider"):+ manager.normalize_provider("lantern")+++def test_tailscale_cli_commands_are_wired(tunnel_manager_module):+ manager = tunnel_manager_module.TunnelManager()++ tailscale = manager._create_tunnel(50001, "tailscale")++ assert tailscale.command == [+ "tailscale",+ "funnel",+ "--yes",+ "http://127.0.0.1:50001",+ ]+ assert tailscale.shutdown_command == [+ "tailscale",+ "funnel",+ "--yes",+ "http://127.0.0.1:50001",+ "off",+ ]+++def test_remote_link_providers_have_dedicated_helper_modules():+ helper_files = {+ "cloudflared": PROJECT_ROOT / "helpers/cloudflare_tunnel.py",+ "microsoft": PROJECT_ROOT / "helpers/microsoft_tunnel.py",+ "serveo": PROJECT_ROOT / "helpers/serveo_tunnel.py",+ "tailscale": PROJECT_ROOT / "helpers/tailscale_tunnel.py",+ }++ assert all(path.exists() for path in helper_files.values())+++def test_microsoft_dev_tunnel_uses_unique_a0_tunnel_id(tunnel_manager_module):+ manager = tunnel_manager_module.TunnelManager()+ tunnel = manager._create_tunnel(50001, "microsoft")++ assert tunnel.start() == "https://example.test"++ config = tunnel.tunnel.config.kwargs+ assert config["tunnel_id"].startswith("agent-zero-")+ assert config["tunnel_id"] != "flaredantic"+ assert config["timeout"] == 120+++def test_microsoft_dev_tunnel_id_can_be_overridden(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ monkeypatch.setenv("A0_MICROSOFT_DEV_TUNNEL_ID", "agent-zero-custom")++ assert modules.microsoft.default_microsoft_tunnel_id() == "agent-zero-custom"+++def test_microsoft_dev_tunnel_timeout_error_is_enriched(+ tunnel_manager_module,+):+ modules = remote_link_modules()++ class FailingMicrosoftTunnel:+ def __init__(self, config):+ self.config = config++ def start(self):+ raise RuntimeError("Timeout waiting for Microsoft Dev Tunnels URL")++ def stop(self):+ return None++ modules.microsoft.AgentZeroMicrosoftTunnel = FailingMicrosoftTunnel+ tunnel = modules.microsoft.MicrosoftDevTunnel(50001)++ with pytest.raises(RuntimeError, match="global `flaredantic` tunnel-id collision"):+ tunnel.start()+++def test_microsoft_dev_tunnel_emits_setup_progress_notifications(+ tunnel_manager_module,+):+ modules = remote_link_modules()+ config = FakeConfig(port=80, tunnel_id="agent-zero-test")+ tunnel = modules.microsoft.AgentZeroMicrosoftTunnel(config)+ commands = []++ def fake_run_cmd(args):+ commands.append(args)+ if args[0] == "show" or args[:2] == ["port", "show"]:+ return types.SimpleNamespace(returncode=1, stdout="missing")+ return types.SimpleNamespace(returncode=0, stdout="ok")++ tunnel._run_cmd = fake_run_cmd++ tunnel._ensure_tunnel()++ messages = [notification["message"] for notification in tunnel.notifications]+ assert messages == [+ "Checking Microsoft Dev Tunnel `agent-zero-test`...",+ "Creating Microsoft Dev Tunnel `agent-zero-test`...",+ "Checking Microsoft Dev Tunnel port 80...",+ "Creating Microsoft Dev Tunnel port 80...",+ "Microsoft Dev Tunnel setup is ready. Starting the secure host...",+ ]+ assert commands == [+ ["show", "agent-zero-test"],+ ["create", "agent-zero-test"],+ ["port", "show", "agent-zero-test", "-p", "80"],+ ["port", "create", "agent-zero-test", "-p", "80", "--protocol", "http"],+ ]+++ ("provider", "expected_label"),+ [+ ("cloudflared", "Cloudflare Tunnel"),+ ("microsoft", "Microsoft Dev Tunnels"),+ ("serveo", "Serveo"),+ ],+)+def test_flaredantic_provider_helpers_emit_manager_notifications(+ tunnel_manager_module,+ provider,+ expected_label,+):+ manager = tunnel_manager_module.TunnelManager()+ tunnel = manager._create_tunnel(50001, provider)++ assert tunnel.start() == "https://example.test"++ assert manager.notifications[0] == {+ "event": "creating_tunnel",+ "message": f"Starting {expected_label} on port 50001...",+ "data": None,+ }+ assert manager.notifications[-1] == {+ "event": "tunnel_url",+ "message": f"{expected_label} URL is ready",+ "data": {"url": "https://example.test"},+ }+++def test_zip_extraction_accepts_windows_exe_members(+ tunnel_manager_module,+ monkeypatch,+ tmp_path,+):+ modules = remote_link_modules()+ archive_path = tmp_path / "tailscale.zip"+ destination = tmp_path / "bin"+ write_zip_archive(archive_path, {"tailscale.exe": "binary"})+ monkeypatch.setattr(modules.cli.platform, "system", lambda: "Windows")++ extracted = modules.cli.extract_named_members_from_zip(+ archive_path,+ destination,+ {"tailscale"},+ )++ assert extracted == {"tailscale": destination / "tailscale.exe"}+ assert (destination / "tailscale.exe").read_text(encoding="utf-8") == "binary"+++def test_tailscale_installs_runtime_binaries_from_static_archive(+ tunnel_manager_module,+ monkeypatch,+ tmp_path,+):+ modules = remote_link_modules()+ monkeypatch.setattr(modules.tailscale.shutil, "which", lambda binary: None)+ monkeypatch.setattr(modules.cli, "RUNTIME_BIN_DIR", tmp_path / "bin")+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_archive_url",+ lambda: "https://pkgs.tailscale.com/stable/tailscale_1.84.0_amd64.tgz",+ )++ def fake_download(url, destination, notify=None):+ write_tar_archive(+ destination,+ {+ "tailscale_1.84.0_amd64/tailscale": "#!/bin/sh\n",+ "tailscale_1.84.0_amd64/tailscaled": "#!/bin/sh\n",+ },+ )+ return destination++ monkeypatch.setattr(modules.cli, "download_file", fake_download)++ installed = Path(modules.tailscale.install_tailscale())++ assert installed == tmp_path / "bin" / "tailscale"+ assert (tmp_path / "bin" / "tailscaled").exists()+ assert os.access(tmp_path / "bin" / "tailscale", os.X_OK)+ assert os.access(tmp_path / "bin" / "tailscaled", os.X_OK)+ assert not (tmp_path / "bin" / "tailscale_1.84.0_amd64.tgz").exists()+++def test_tailscale_installer_downloads_static_pair_when_system_daemon_is_missing(+ tunnel_manager_module,+ monkeypatch,+ tmp_path,+):+ modules = remote_link_modules()+ monkeypatch.setattr(+ modules.tailscale.shutil,+ "which",+ lambda binary: "/usr/bin/tailscale" if binary == "tailscale" else None,+ )+ monkeypatch.setattr(modules.cli, "RUNTIME_BIN_DIR", tmp_path / "bin")+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_archive_url",+ lambda: "https://pkgs.tailscale.com/stable/tailscale_1.84.0_amd64.tgz",+ )++ def fake_download(url, destination, notify=None):+ write_tar_archive(+ destination,+ {+ "tailscale_1.84.0_amd64/tailscale": "#!/bin/sh\n",+ "tailscale_1.84.0_amd64/tailscaled": "#!/bin/sh\n",+ },+ )+ return destination++ monkeypatch.setattr(modules.cli, "download_file", fake_download)++ assert modules.tailscale.install_tailscale() == str(tmp_path / "bin" / "tailscale")+ assert (tmp_path / "bin" / "tailscaled").exists()+++def test_tailscale_static_package_url_is_discovered_from_official_listing(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ html = (+ '<a href="tailscale_1.84.0_arm64.tgz">arm</a>'+ '<a href="tailscale_1.84.0_amd64.tgz">amd64</a>'+ )++ class FakeResponse:+ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc, traceback):+ return None++ def read(self):+ return html.encode("utf-8")++ monkeypatch.setattr(modules.tailscale, "tailscale_arch", lambda: "amd64")+ monkeypatch.setattr(+ modules.tailscale.urllib.request,+ "urlopen",+ lambda url, timeout=30: FakeResponse(),+ )++ assert (+ modules.tailscale.tailscale_archive_url()+ == "https://pkgs.tailscale.com/stable/tailscale_1.84.0_amd64.tgz"+ )+++def test_tar_extraction_sanitizes_member_paths(+ tunnel_manager_module,+ tmp_path,+):+ modules = remote_link_modules()+ archive_path = tmp_path / "tailscale.tgz"+ destination = tmp_path / "safe"+ write_tar_archive(archive_path, {"../tailscale": "binary"})++ extracted = modules.cli.extract_named_members_from_tar(+ archive_path,+ destination,+ {"tailscale"},+ )++ assert extracted == {"tailscale": destination / "tailscale"}+ assert (destination / "tailscale").read_text(encoding="utf-8") == "binary"+ assert not (tmp_path / "tailscale").exists()+++ ("provider", "module_name", "installer_name", "expected_message"),+ [+ ("tailscale", "tailscale", "install_tailscale", "tailscale download failed"),+ ],+)+def test_cli_provider_installer_failures_return_actionable_error(+ tunnel_manager_module,+ monkeypatch,+ provider,+ module_name,+ installer_name,+ expected_message,+):+ manager_module = tunnel_manager_module+ modules = remote_link_modules()+ manager = manager_module.TunnelManager()++ def fail_install(notify=None):+ raise RuntimeError(expected_message)++ monkeypatch.setattr(getattr(modules, module_name), installer_name, fail_install)++ assert manager.start_tunnel(port=50001, provider=provider) is None+ assert expected_message in manager.get_last_error()+++def test_tailscale_preflight_starts_managed_daemon_then_runs_up_with_socket(+ tunnel_manager_module,+ monkeypatch,+ tmp_path,+):+ modules = remote_link_modules()+ runtime_dir = tmp_path / "runtime"+ state_dir = tmp_path / "state"+ socket_path = runtime_dir / "tailscaled.sock"+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ tailscale = bin_dir / "tailscale"+ tailscaled = bin_dir / "tailscaled"+ tailscale.write_text("#!/bin/sh\n", encoding="utf-8")+ tailscaled.write_text("#!/bin/sh\n", encoding="utf-8")+ monkeypatch.setattr(modules.tailscale, "TAILSCALE_RUNTIME_DIR", runtime_dir)+ monkeypatch.setattr(modules.tailscale, "TAILSCALE_STATE_DIR", state_dir)+ monkeypatch.setattr(modules.tailscale, "TAILSCALE_SOCKET_PATH", socket_path)+ monkeypatch.setattr(+ modules.tailscale,+ "TAILSCALE_DAEMON_LOG_PATH",+ runtime_dir / "tailscaled.log",+ )+ monkeypatch.setattr(+ modules.tailscale,+ "TAILSCALE_DAEMON_PID_PATH",+ runtime_dir / "tailscaled.pid",+ )+ status_results = iter([+ types.SimpleNamespace(+ returncode=1,+ stdout="",+ stderr="failed to connect to local tailscaled",+ ),+ types.SimpleNamespace(+ returncode=1,+ stdout="",+ stderr="failed to connect to local tailscaled",+ ),+ types.SimpleNamespace(returncode=1, stdout="Logged out.", stderr=""),+ types.SimpleNamespace(returncode=1, stdout="Logged out.", stderr=""),+ types.SimpleNamespace(+ returncode=0,+ stdout='{"BackendState": "Running"}',+ stderr="",+ ),+ ])+ status_calls = []++ def fake_status(binary_path, socket_path=None):+ status_calls.append((binary_path, socket_path))+ return next(status_results)++ monkeypatch.setattr(modules.tailscale, "tailscale_status", fake_status)+ popen_commands = []++ class FakeProcess:+ def __init__(self, command, **kwargs):+ popen_commands.append(command)+ self.pid = 12345+ self.is_tailscale_up = command[0] == str(tailscale)+ self.stdout = iter(["Success.\n"]) if command[0] == str(tailscale) else None++ def poll(self):+ return 0 if self.is_tailscale_up else None++ def terminate(self):+ return None++ def wait(self, timeout=None):+ return 0++ monkeypatch.setattr(modules.tailscale.subprocess, "Popen", FakeProcess)++ result = modules.tailscale.ensure_tailscale_ready(str(tailscale))++ assert result == {"command_prefix": ["--socket", str(socket_path)]}+ assert status_calls == [+ (str(tailscale), None),+ (str(tailscale), socket_path),+ (str(tailscale), socket_path),+ (str(tailscale), socket_path),+ (str(tailscale), socket_path),+ ]+ assert popen_commands == [+ [+ str(tailscaled),+ "--tun=userspace-networking",+ "--socket",+ str(socket_path),+ "--statedir",+ str(state_dir),+ "--state",+ str(state_dir / "tailscaled.state"),+ ],+ [str(tailscale), "--socket", str(socket_path), "up"],+ ]+++def test_tailscale_preflight_emits_login_url_from_tailscale_up(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_status",+ lambda binary_path, socket_path=None: types.SimpleNamespace(+ returncode=1,+ stdout="",+ stderr="",+ ),+ )++ class FakeProcess:+ stdout = iter(+ [+ "To authenticate, visit:\n",+ "https://login.tailscale.com/a/abcdef\n",+ ]+ )++ def poll(self):+ return 1++ def terminate(self):+ return None++ def wait(self, timeout=None):+ return 1++ notifications = []+ monkeypatch.setattr(+ modules.tailscale.subprocess,+ "Popen",+ lambda *args, **kwargs: FakeProcess(),+ )++ with pytest.raises(RuntimeError, match="joining this container to your tailnet"):+ modules.tailscale.ensure_tailscale_ready(+ "/tmp/tailscale",+ notify=lambda event, message, data=None: notifications.append(+ {"event": event.value, "message": message, "data": data}+ ),+ )++ assert notifications[0]["message"] == (+ "Tailscale needs this container to join your tailnet. Running `tailscale up` now..."+ )+ assert notifications[1] == {+ "event": "info",+ "message": (+ "Open the Tailscale login link and approve this container. "+ "Agent Zero will continue when Tailscale finishes setup."+ ),+ "data": {+ "provider": "tailscale",+ "url": "https://login.tailscale.com/a/abcdef",+ },+ }+++def test_tailscale_preflight_runs_up_then_accepts_running_status(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ status_results = iter([+ types.SimpleNamespace(returncode=1, stdout="", stderr="not logged in"),+ types.SimpleNamespace(+ returncode=0,+ stdout='{"BackendState": "Running"}',+ stderr="",+ ),+ ])+ notifications = []++ monkeypatch.setattr(+ modules.tailscale,+ "tailscale_status",+ lambda binary_path, socket_path=None: next(status_results),+ )++ class FakeProcess:+ stdout = iter(["Success.\n"])++ def poll(self):+ return 0++ def wait(self, timeout=None):+ return 0++ monkeypatch.setattr(+ modules.tailscale.subprocess,+ "Popen",+ lambda *args, **kwargs: FakeProcess(),+ )++ modules.tailscale.ensure_tailscale_ready(+ "/tmp/tailscale",+ notify=lambda event, message, data=None: notifications.append(+ {"event": event.value, "message": message, "data": data}+ ),+ )++ assert notifications[-1] == {+ "event": "info",+ "message": "Tailscale setup completed. Checking the tailnet connection...",+ "data": None,+ }+++def test_cli_tunnel_preflight_prefix_is_used_for_start_and_shutdown(+ tunnel_manager_module,+ monkeypatch,+):+ modules = remote_link_modules()+ popen_commands = []+ run_commands = []++ class FakeProcess:+ def __init__(self, command, **kwargs):+ popen_commands.append(command)+ self.stdout = iter(["https://agent-zero.ts.net\n"])++ def poll(self):+ return None++ def terminate(self):+ return None++ def wait(self, timeout=None):+ return 0++ monkeypatch.setattr(modules.cli.subprocess, "Popen", FakeProcess)+ monkeypatch.setattr(+ modules.cli.subprocess,+ "run",+ lambda command, **kwargs: run_commands.append(command)+ or types.SimpleNamespace(returncode=0),+ )++ tunnel = modules.cli.CliTunnelHelper(+ label="Tailscale Funnel",+ binary="tailscale",+ port=50001,+ command=["tailscale", "funnel", "--yes", "http://127.0.0.1:50001"],+ shutdown_command=[+ "tailscale",+ "funnel",+ "--yes",+ "http://127.0.0.1:50001",+ "off",+ ],+ url_pattern=modules.tailscale.TAILSCALE_URL_RE,+ missing_binary_message="missing",+ binary_resolver=lambda notify=None: "/tmp/tailscale",+ preflight=lambda binary_path, notify=None: {+ "command_prefix": ["--socket", "/tmp/tailscaled.sock"]+ },+ )++ assert tunnel.start() == "https://agent-zero.ts.net"+ tunnel.stop()++ assert popen_commands == [+ [+ "/tmp/tailscale",+ "--socket",+ "/tmp/tailscaled.sock",+ "funnel",+ "--yes",+ "http://127.0.0.1:50001",+ ]+ ]+ assert run_commands == [+ [+ "/tmp/tailscale",+ "--socket",+ "/tmp/tailscaled.sock",+ "funnel",+ "--yes",+ "http://127.0.0.1:50001",+ "off",+ ]+ ]diff --git a/webui/components/settings/external/external-settings.html b/webui/components/settings/external/external-settings.htmlindex 067fc1674..a9d7416dd 100644--- a/webui/components/settings/external/external-settings.html+++ b/webui/components/settings/external/external-settings.html@@ -41,8 +41,8 @@</li><li><a href="#section-tunnel">- <img src="/public/tunnel.svg" alt="Remote Link" />- <span>Remote Link</span>+ <img src="/public/tunnel.svg" alt="Remote Control" />+ <span>Remote Control</span></a></li></ul>diff --git a/webui/components/settings/settings-store.js b/webui/components/settings/settings-store.jsindex bd45b35c4..1b74622a4 100644--- a/webui/components/settings/settings-store.js+++ b/webui/components/settings/settings-store.js@@ -47,7 +47,7 @@ const TAB_ITEMS = Object.freeze([{ id: "section-secrets", label: "Secrets", icon: "lock" },{ id: "section-auth", label: "Authentication", icon: "passkey" },{ id: "section-external-api", label: "External API", icon: "api" },- { id: "section-tunnel", label: "Remote Link", icon: "share" },+ { id: "section-tunnel", label: "Remote Control", icon: "share" },],},{diff --git a/webui/components/settings/tunnel/remote-link.html b/webui/components/settings/tunnel/remote-link.htmlindex 65f42ae05..d0f21dc80 100644--- a/webui/components/settings/tunnel/remote-link.html+++ b/webui/components/settings/tunnel/remote-link.html@@ -1,6 +1,6 @@<html class="remote-link-modal"><head>- <title>Remote Link</title>+ <title>Remote Control</title></head><body>diff --git a/webui/components/settings/tunnel/tunnel-section.html b/webui/components/settings/tunnel/tunnel-section.htmlindex 4c13d1743..6dc0b3e5f 100644--- a/webui/components/settings/tunnel/tunnel-section.html+++ b/webui/components/settings/tunnel/tunnel-section.html@@ -1,6 +1,6 @@<html><head>- <title>Remote Link</title>+ <title>Remote Control</title><script type="module">import { store } from "/components/settings/tunnel/tunnel-store.js";</script>@@ -20,23 +20,23 @@<span class="material-symbols-outlined">share</span></div><div>- <div class="section-title">Remote Link</div>+ <div class="section-title">Remote Control</div><div class="section-description">- Create a temporary HTTPS link for this Agent Zero instance, then open it from another browser or scan it from your phone.+ Create temporary HTTPS access for this Agent Zero instance, then open it from another browser or scan it from your phone.</div></div></header><div class="remote-link-safety-note"><span class="material-symbols-outlined" aria-hidden="true">lock</span>- <span>Use sign-in before sharing a remote link. The URL can reach your instance while the link is active.</span>+ <span>Use sign-in before sharing remote control access. The URL can reach your instance while access is active.</span></div><div class="field remote-link-provider-field"><div class="field-label"><div class="field-title">Link provider</div><div class="field-description">- Cloudflare is the quickest path for a shareable URL. Microsoft Dev Tunnels may ask you to sign in.+ Cloudflare Tunnel is the quickest shareable URL. Tailscale is private to your tailnet and Agent Zero will start its sign-in flow when needed. Microsoft Dev Tunnels may ask you to approve a GitHub device login.</div></div><div class="field-control">@@ -45,7 +45,8 @@x-model="$store.tunnelStore.provider":disabled="$store.tunnelStore.isLoading">- <option value="cloudflared">Cloudflare</option>+ <option value="cloudflared">Cloudflare Tunnel</option>+ <option value="tailscale">Tailscale</option><option value="microsoft">Microsoft Dev Tunnels</option><option value="serveo">Serveo</option></select>@@ -54,22 +55,22 @@<div class="remote-link-loading" x-show="$store.tunnelStore.isLoading" style="display: none;"><span class="material-symbols-outlined spin" aria-hidden="true">progress_activity</span>- <span x-text="$store.tunnelStore.loadingText || 'Preparing remote link...'"></span>+ <span x-text="$store.tunnelStore.loadingText || 'Preparing remote control...'"></span></div>- <div class="microsoft-login-box" x-show="$store.tunnelStore.microsoftLoginCode" x-transition style="display: none;">+ <div class="microsoft-login-box" x-show="$store.tunnelStore.loginActionVisible" x-transition style="display: none;"><div class="microsoft-login-header"><span class="material-symbols-outlined" aria-hidden="true">key</span><div>- <div class="microsoft-login-title">Microsoft sign-in</div>- <div class="microsoft-login-copy">Approve the tunnel request, then Agent Zero will finish creating the link.</div>+ <div class="microsoft-login-title" x-text="$store.tunnelStore.loginActionTitle"></div>+ <div class="microsoft-login-copy" x-text="$store.tunnelStore.loginActionCopy"></div></div></div>- <a class="microsoft-login-link" :href="$store.tunnelStore.microsoftLoginUrl" target="_blank" rel="noopener noreferrer">+ <a class="microsoft-login-link" x-show="$store.tunnelStore.microsoftLoginUrl" :href="$store.tunnelStore.microsoftLoginUrl" target="_blank" rel="noopener noreferrer"><span class="material-symbols-outlined" aria-hidden="true">open_in_new</span><span x-text="$store.tunnelStore.microsoftLoginUrl"></span></a>- <div class="microsoft-login-code-row">+ <div class="microsoft-login-code-row" x-show="$store.tunnelStore.microsoftLoginCode"><div class="microsoft-login-code" x-text="$store.tunnelStore.microsoftLoginCode"></div><buttontype="button"@@ -91,7 +92,7 @@class="remote-link-input":value="$store.tunnelStore.tunnelLink"readonly- aria-label="Remote link URL"+ aria-label="Remote Control URL"><buttontype="button"@@ -112,7 +113,7 @@:disabled="$store.tunnelStore.isLoading"><span class="material-symbols-outlined" aria-hidden="true">refresh</span>- <span>New link</span>+ <span>New URL</span></button></div>@@ -127,7 +128,7 @@<div class="remote-link-status-panel"><span class="material-symbols-outlined" aria-hidden="true">verified</span><div>- <div class="remote-link-status-title">Link is active</div>+ <div class="remote-link-status-title">Remote Control is active</div><div class="remote-link-status-copy">It stays available until you stop it or the container restarts.</div>@@ -143,14 +144,14 @@:disabled="$store.tunnelStore.isLoading"><span class="material-symbols-outlined" aria-hidden="true">stop_circle</span>- <span>Stop link</span>+ <span>Stop Remote Control</span></button></div></div><div class="remote-link-empty" x-show="!$store.tunnelStore.linkGenerated"><span class="material-symbols-outlined" aria-hidden="true">link</span>- <strong>No remote link yet</strong>+ <strong>No Remote Control yet</strong><span>Create one when you want to reach Agent Zero from another device or share access temporarily.</span><buttontype="button"@@ -159,7 +160,7 @@:disabled="$store.tunnelStore.isLoading"><span class="material-symbols-outlined" aria-hidden="true">share</span>- <span>Create remote link</span>+ <span>Start Remote Control</span></button></div></div>diff --git a/webui/components/settings/tunnel/tunnel-store.js b/webui/components/settings/tunnel/tunnel-store.jsindex f631ec30d..5e93d137a 100644--- a/webui/components/settings/tunnel/tunnel-store.js+++ b/webui/components/settings/tunnel/tunnel-store.js@@ -9,6 +9,7 @@ const model = {loadingText: "",qrCodeInstance: null,provider: "cloudflared",+ loginProvider: "",microsoftLoginCode: "",microsoftLoginUrl: "",codeCopied: false,@@ -36,7 +37,23 @@ const model = {return "Copy link";},+ get loginActionVisible() {+ return Boolean(this.microsoftLoginUrl || this.microsoftLoginCode);+ },++ get loginActionTitle() {+ return this.loginProvider === "tailscale" ? "Tailscale sign-in" : "Microsoft sign-in";+ },++ get loginActionCopy() {+ if (this.loginProvider === "tailscale") {+ return "Open the Tailscale login link and approve this container. Agent Zero will continue when Tailscale finishes setup.";+ }+ return "Approve the tunnel request, then Agent Zero will finish enabling Remote Control.";+ },+clearMicrosoftLogin() {+ this.loginProvider = "";this.microsoftLoginCode = "";this.microsoftLoginUrl = "";this.codeCopied = false;@@ -80,18 +97,21 @@ const model = {this.loadingText = n.message;break;case "info":- // Check for Microsoft login code- if (n.data && n.data.code) {- this.microsoftLoginCode = n.data.code;+ // Sign-in providers can provide a device code, a login URL, or both.+ if (n.data && n.data.url) {+ this.loginProvider = n.data.provider || (n.data.code ? "microsoft" : "tailscale");+ this.microsoftLoginCode = n.data.code || "";this.microsoftLoginUrl = n.data.url || "";- this.loadingText = "Waiting for Microsoft login...";+ this.loadingText = this.loginProvider === "tailscale"+ ? "Waiting for Tailscale login..."+ : "Waiting for Microsoft login...";} else {this.loadingText = n.message;}break;case "error":this.hasError = true;- window.toastFrontendError(n.message, "Remote Link");+ window.toastFrontendError(n.message, "Remote Control");this.stopNotificationPolling();break;case "tunnel_url":@@ -233,7 +253,7 @@ const model = {// Call generate but with a confirmation firstif (confirm(- "Create a new remote link? The current URL will stop working."+ "Create new Remote Control access? The current URL will stop working.")) {@@ -263,7 +283,7 @@ const model = {await this.generateLink();} catch (error) {console.error("Error refreshing tunnel:", error);- window.toastFrontendError("Error refreshing remote link", "Remote Link");+ window.toastFrontendError("Error refreshing Remote Control", "Remote Control");this.isLoading = false;this.loadingText = "";}@@ -287,7 +307,7 @@ const model = {// If no authentication is set, warn the userif (!hasAuth) {const proceed = confirm(- "Remote Link works best with sign-in enabled.\n\n" ++ "Remote Control works best with sign-in enabled.\n\n" +"Without a login, anyone with the URL can reach this Agent Zero instance.\n\n" +"Turn on authentication in Settings before sharing this link. Continue anyway?");@@ -332,7 +352,7 @@ const model = {// Check for errorif (!data.success && data.message) {this.hasError = true;- window.toastFrontendError(data.message, "Remote Link");+ window.toastFrontendError(data.message, "Remote Control");console.error("Tunnel creation failed:", data);this.stopNotificationPolling();return;@@ -351,12 +371,12 @@ const model = {// Show success message to confirm creationwindow.toastFrontendInfo(- "Remote link is ready",- "Remote Link"+ "Remote Control is ready",+ "Remote Control");}} catch (error) {- window.toastFrontendError("Error creating remote link", "Remote Link");+ window.toastFrontendError("Error creating Remote Control", "Remote Control");console.error("Error creating tunnel:", error);} finally {this.isLoading = false;@@ -370,7 +390,7 @@ const model = {async stopTunnel() {if (confirm(- "Stop this remote link? The current URL will no longer be accessible."+ "Stop Remote Control? The current URL will no longer be accessible.")) {this.isLoading = true;@@ -404,14 +424,14 @@ const model = {this.linkGenerated = false;window.toastFrontendInfo(- "Remote link stopped",- "Remote Link"+ "Remote Control stopped",+ "Remote Control");} else {- window.toastFrontendError("Failed to stop remote link", "Remote Link");+ window.toastFrontendError("Failed to stop Remote Control", "Remote Control");}} catch (error) {- window.toastFrontendError("Error stopping remote link", "Remote Link");+ window.toastFrontendError("Error stopping Remote Control", "Remote Control");console.error("Error stopping tunnel:", error);} finally {this.isLoading = false;@@ -430,7 +450,7 @@ const model = {// Show toast notificationwindow.toastFrontendInfo(- "Remote link copied",+ "Remote Control URL copied","Clipboard");@@ -443,7 +463,7 @@ const model = {console.error("Failed to copy URL: ", err);this.copyState = "error";window.toastFrontendError(- "Failed to copy remote link",+ "Failed to copy Remote Control URL","Clipboard Error");diff --git a/webui/components/sidebar/top-section/header-icons.html b/webui/components/sidebar/top-section/header-icons.htmlindex a6f870003..15e219d9f 100644--- a/webui/components/sidebar/top-section/header-icons.html+++ b/webui/components/sidebar/top-section/header-icons.html@@ -90,7 +90,7 @@<button class="dropdown-item" @click="ensureModalOpen('settings/tunnel/remote-link.html'); $store.sidebar.menuClose()"><span class="material-symbols-outlined">share</span>- <span>Remote Link</span>+ <span>Remote Control</span></button><button class="dropdown-item" @click="open('https://space-agent.ai/', '_blank', 'noopener,noreferrer'); $store.sidebar.menuClose()">