:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(devbox): actionable tailnet error messages (#59000)
Raúl Negrón-Otero9c9113f083c1
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex 76c84dad5b37..279f49b4d55c 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -634,6 +634,7 @@ def devbox_setup(verbose: bool,) -> None:"""Prepare this machine for Coder workspaces."""+ click.echo(click.style("Configuring devbox CLI access...", bold=True))ensure_tailscale_connected("rerun `hogli devbox:setup`.")ensure_tailscale_routes_accepted()ensure_coder_reachable()diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.pyindex 727b19511499..523d72e5cda0 100644--- a/tools/hogli-commands/hogli_commands/devbox/coder.py+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py@@ -11,10 +11,13 @@ import sysimport jsonimport shleximport shutil+import socketimport itertoolsimport threadingimport subprocessimport webbrowser+import urllib.parse+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, NoReturn@@ -23,6 +26,7 @@ import requestsfrom hogli.manifest import load_manifest_MACOS_TAILSCALE_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale"+_TAILSCALE_RUNBOOK_URL = "https://runbooks.posthog.com/vpn/#tailscale"DEFAULT_TEMPLATE = "posthog-linux"BREW_PACKAGE = "coder/coder/coder"RUNTIME_SETUP_HINT = "Run `hogli devbox:setup`."@@ -300,15 +304,73 @@ def tailscale_connected() -> bool:return bool(status and status.get("BackendState") == "Running")+def _tailscale_install_hint() -> str:+ """Return the platform-specific install command for Tailscale.++ On macOS, the CLI ships inside ``Tailscale.app`` — engineers commonly+ install the GUI and never realize there is also a CLI to put on PATH.+ Recommending the cask install handles both at once; the App Store build+ is mentioned as a fallback because some employees install it that way.+ """+ if sys.platform == "darwin":+ return "Install: `brew install --cask tailscale` (or via the Mac App Store)."+ if sys.platform.startswith("linux"):+ return "Install: `curl -fsSL https://tailscale.com/install.sh | sh`."+ return "Install Tailscale from https://tailscale.com/download."+++def _tailscale_connect_hint() -> str:+ """Return the platform-specific command for joining a tailnet."""+ if sys.platform == "darwin":+ return "Open the Tailscale app and sign in with your PostHog Google account."+ return "Run `sudo tailscale up` and complete the SSO flow with your PostHog Google account."+++def _tailscale_cli_missing_on_macos() -> bool:+ """Return whether macOS has the Tailscale app but no CLI on PATH."""+ return sys.platform == "darwin" and shutil.which("tailscale") is None and os.path.isfile(_MACOS_TAILSCALE_CLI)++def ensure_tailscale_connected(setup_hint: str = RUNTIME_SETUP_HINT) -> None:- """Fail fast when the Coder deployment is not reachable on the tailnet."""+ """Fail fast when the host is not connected to a Tailscale tailnet.++ Reports three distinct states with the action that fixes each: not+ installed (give the install command), installed but not running (give+ the connect command), and a special macOS path where the GUI is present+ but the CLI is hidden inside the app bundle (point to the symlink).+ """if tailscale_connected():return- if _resolve_tailscale():- _fail(f"Tailscale is not connected. Connect to the PostHog tailnet, then {setup_hint}")+ if not _resolve_tailscale():+ _fail(+ "Tailscale is not installed.\n"+ f" {_tailscale_install_hint()}\n"+ f" See {_TAILSCALE_RUNBOOK_URL} for joining the PostHog tailnet.\n"+ f" Then {setup_hint}"+ )- _fail(f"Tailscale is not installed. Install it, then {setup_hint}")+ # CLI is resolvable, but the daemon is not running -- the user needs to+ # sign in (a fresh install) or bring the agent back up (it was stopped).+ if _tailscale_cli_missing_on_macos():+ # `_resolve_tailscale()` succeeded via the bundled CLI, but `tailscale`+ # is not on PATH. This trips engineers who try to follow the printed+ # `tailscale status` hint and get "command not found".+ _fail(+ "Tailscale is installed but not connected, and the `tailscale` CLI is not on your PATH.\n"+ f" {_tailscale_connect_hint()}\n"+ " To use the CLI from your shell, symlink it once:\n"+ f" sudo ln -sfn {_MACOS_TAILSCALE_CLI} /usr/local/bin/tailscale\n"+ f" See {_TAILSCALE_RUNBOOK_URL} if you have not yet been added to the tailnet.\n"+ f" Then {setup_hint}"+ )++ _fail(+ "Tailscale is installed but not connected.\n"+ f" {_tailscale_connect_hint()}\n"+ f" See {_TAILSCALE_RUNBOOK_URL} if you have not yet been added to the tailnet.\n"+ f" Then {setup_hint}"+ )# Health warning emitted by `tailscale status` when peers advertise subnet routes@@ -342,7 +404,8 @@ def ensure_tailscale_routes_accepted() -> None:result = subprocess.run(cmd, env=_tailscale_env(tailscale_path))if result.returncode != 0:- _fail("Failed to enable Tailscale subnet routes. Run manually: sudo tailscale set --accept-routes")+ manual = "tailscale set --accept-routes" if sys.platform == "darwin" else "sudo tailscale set --accept-routes"+ _fail(f"Failed to enable Tailscale subnet routes. Run manually: {manual}")def coder_reachable(timeout: float = 5.0) -> bool:@@ -355,23 +418,181 @@ def coder_reachable(timeout: float = 5.0) -> bool:return resp.ok-def ensure_coder_reachable() -> None:- """Fail fast when the Coder deployment is not reachable.+@dataclass(frozen=True)+class CoderReachabilityDiagnosis:+ """Why the Coder deployment is unreachable, with a single actionable next step.++ The structured form lets the caller present one concrete cause and one+ fix rather than a list of commands the user has to interpret. ``facts``+ is a short list of diagnostic data (tailnet name, resolved IP, peer+ health) that is safe to share verbatim when asking for help.+ """++ cause: str+ next_step: str+ facts: list[str]+++def _resolve_host_ip(host: str) -> str | None:+ """Resolve a hostname to a single IP, or ``None`` if resolution fails.++ Uses the OS resolver so MagicDNS lookups via Tailscale (or split-DNS+ routes through the tailnet) are honored just as they would be for the+ actual HTTPS probe. We swallow OSError because every resolver failure+ mode maps to the same "DNS failed" branch downstream.+ """+ try:+ return socket.gethostbyname(host)+ except OSError:+ return None+++def _tcp_reachable(host: str, port: int, timeout: float = 3.0) -> bool:+ """Return whether a TCP handshake to ``(host, port)`` completes."""+ try:+ with socket.create_connection((host, port), timeout=timeout):+ return True+ except OSError:+ return False+- Tailscale reporting ``BackendState=Running`` with ``--accept-routes`` does not- prove the subnet route to the Coder ALB is actually plumbed — DNS can resolve- and packets still blackhole. Probe the API directly so reachability failures- surface here instead of as a silent ``curl | sh`` no-op during install.+def _diagnose_unreachable_coder() -> CoderReachabilityDiagnosis:+ """Diagnose why the Coder deployment is not reachable.++ Probes (in order) DNS resolution, TCP reachability on 443, and the+ Tailscale peer / route topology, picking the most specific cause and+ pairing it with a concrete next step. Returns the diagnosis instead of+ printing it so callers control formatting and tests can assert against+ structured fields."""coder_url = get_coder_url()+ host = urllib.parse.urlparse(coder_url).hostname or coder_url+ facts: list[str] = [f"Coder URL: {coder_url}"]++ status = _tailscale_status()+ tailnet_name: str | None = None+ if status:+ current_tailnet = status.get("CurrentTailnet")+ if isinstance(current_tailnet, dict):+ name = current_tailnet.get("Name")+ if isinstance(name, str) and name:+ tailnet_name = name+ facts.append(f"Tailscale tailnet: {name}")+ if tailnet_name is None:+ facts.append("Tailscale tailnet: <unknown>")+ else:+ facts.append("Tailscale status: unavailable")++ resolved_ip = _resolve_host_ip(host)+ if resolved_ip is None:+ facts.append(f"DNS for {host}: failed")+ return CoderReachabilityDiagnosis(+ cause=f"DNS lookup for {host} failed.",+ next_step=(+ "MagicDNS may be off or you may be on the wrong tailnet. "+ "Verify the tailnet name above is PostHog's, then run "+ "`sudo tailscale up --accept-dns`."+ ),+ facts=facts,+ )+ facts.append(f"DNS for {host}: {resolved_ip}")++ if _tcp_reachable(host, 443):+ facts.append(f"TCP {host}:443: open")+ return CoderReachabilityDiagnosis(+ cause=f"TCP to {host}:443 works but the HTTPS probe failed.",+ next_step=(+ "The Coder deployment may be restarting, or your system clock "+ "is off (causing TLS to reject the cert). Check the time, then "+ "retry in a minute."+ ),+ facts=facts,+ )+ facts.append(f"TCP {host}:443: blocked / timed out")++ return _diagnose_blocked_route(status, facts)+++def _diagnose_blocked_route(+ status: dict[str, Any] | None,+ facts: list[str],+) -> CoderReachabilityDiagnosis:+ """Pick a cause when DNS resolves but TCP to the Coder ALB is blocked.++ Walks the Tailscale peer map looking for subnet routers. Cases handled,+ in priority order:++ 1. No peer advertises any subnet route — usually means the host is on+ the wrong tailnet (e.g. personal account) or has not been added to+ the PostHog tailnet yet.+ 2. Routers exist but none are online — the relay is bouncing; waiting+ is the only fix.+ 3. A router is online — Tailscale ACLs or a local VPN is intercepting.+ """+ peers = (status or {}).get("Peer") or {}+ routers = [p for p in peers.values() if isinstance(p, dict) and p.get("PrimaryRoutes")]+ online_routers = [p for p in routers if p.get("Online")]+ facts.append(f"Subnet routers on tailnet: {len(routers)} ({len(online_routers)} online)")++ if not routers:+ return CoderReachabilityDiagnosis(+ cause="No peer on your tailnet advertises subnet routes.",+ next_step=(+ "Either you are not on the PostHog tailnet (check the name "+ "above), or your account has not been added to the Tailscale "+ f"policy yet. See {_TAILSCALE_RUNBOOK_URL} for the policy "+ "request flow, then reach out to Team DevEx with the facts below."+ ),+ facts=facts,+ )++ if not online_routers:+ names = ", ".join(str(p.get("HostName") or "?") for p in routers)+ return CoderReachabilityDiagnosis(+ cause=f"Subnet router peer is offline ({names}).",+ next_step=(+ "Wait a minute and retry. If it stays offline, reach out to Team DevEx — the relay likely needs a bounce."+ ),+ facts=facts,+ )++ return CoderReachabilityDiagnosis(+ cause="TCP is blocked despite an online subnet router on your tailnet.",+ next_step=(+ "A non-Tailscale VPN or a local firewall is likely intercepting, "+ "or the Tailscale policy does not grant your account devbox "+ f"access. Disable other VPNs and see {_TAILSCALE_RUNBOOK_URL} to "+ "confirm policy membership, or reach out to Team DevEx."+ ),+ facts=facts,+ )+++def ensure_coder_reachable() -> None:+ """Fail fast with a structured diagnosis when the Coder ALB is unreachable.++ Tailscale reporting ``BackendState=Running`` with ``--accept-routes`` does+ not prove the subnet route to the Coder ALB is plumbed — DNS can resolve+ and packets still blackhole. Probe the API directly, and on failure pick+ the single most-likely cause + next step instead of dumping a list of+ commands the engineer has to interpret themselves.+ """if coder_reachable():return- _fail(- f"Cannot reach {coder_url} over the tailnet.\n"- "Check that you're connected to the PostHog tailnet and that subnet routes are accepted:\n"- " tailscale status # verify peer is connected\n"- " sudo tailscale set --accept-routes"++ diagnosis = _diagnose_unreachable_coder()+ body = "\n".join(+ [+ f"Cannot reach {get_coder_url()} over the tailnet.",+ "",+ f"Cause: {diagnosis.cause}",+ f"Next step: {diagnosis.next_step}",+ "",+ "Diagnostic facts (safe to share with Team DevEx):",+ *(f" - {fact}" for fact in diagnosis.facts),+ ])+ _fail(body)def _config_ssh_args(*, identity_agent_socket: str | None = None) -> list[str]:@@ -680,7 +901,10 @@ def get_username() -> str:if username:return username.lower()- _fail("Failed to determine the Coder username.")+ _fail(+ "Could not determine your Coder username from `coder whoami`.\n"+ f" Your login may have expired. {RUNTIME_SETUP_HINT}"+ )def get_workspace_name(label: str | None = None) -> str:diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.pyindex 023ba82063af..5d3f4555fb75 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py@@ -208,11 +208,65 @@ class TestResolveTailscale:) -> None:monkeypatch.setattr(coder, "tailscale_connected", lambda: False)monkeypatch.setattr(coder, "_resolve_tailscale", lambda: None)+ monkeypatch.setattr(coder.sys, "platform", "linux")++ with pytest.raises(SystemExit):+ coder.ensure_tailscale_connected()++ out = capsys.readouterr().out+ assert "not installed" in out+ # The install hint must be present so the user can act without searching.+ assert "tailscale.com/install.sh" in out++ def test_ensure_tailscale_connected_install_hint_is_macos_specific(+ self,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ ) -> None:+ monkeypatch.setattr(coder, "tailscale_connected", lambda: False)+ monkeypatch.setattr(coder, "_resolve_tailscale", lambda: None)+ monkeypatch.setattr(coder.sys, "platform", "darwin")++ with pytest.raises(SystemExit):+ coder.ensure_tailscale_connected()++ out = capsys.readouterr().out+ assert "brew install --cask tailscale" in out++ def test_ensure_tailscale_connected_says_not_connected_when_daemon_down(+ self,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ ) -> None:+ monkeypatch.setattr(coder, "tailscale_connected", lambda: False)+ monkeypatch.setattr(coder, "_resolve_tailscale", lambda: "/usr/local/bin/tailscale")+ monkeypatch.setattr(coder, "_tailscale_cli_missing_on_macos", lambda: False)+ monkeypatch.setattr(coder.sys, "platform", "linux")++ with pytest.raises(SystemExit):+ coder.ensure_tailscale_connected()++ out = capsys.readouterr().out+ assert "installed but not connected" in out+ # On Linux the connect hint must mention `tailscale up`, not the macOS app.+ assert "tailscale up" in out++ def test_ensure_tailscale_connected_emits_symlink_hint_on_macos_when_cli_only_in_app_bundle(+ self,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ ) -> None:+ monkeypatch.setattr(coder, "tailscale_connected", lambda: False)+ monkeypatch.setattr(coder, "_resolve_tailscale", lambda: coder._MACOS_TAILSCALE_CLI)+ monkeypatch.setattr(coder, "_tailscale_cli_missing_on_macos", lambda: True)with pytest.raises(SystemExit):coder.ensure_tailscale_connected()- assert "not installed" in capsys.readouterr().out+ out = capsys.readouterr().out+ assert "not on your PATH" in out+ assert "ln -sfn" in out+ assert coder._MACOS_TAILSCALE_CLI in outclass TestTailscaleRoutesAccepted:@@ -418,7 +472,7 @@ class TestCoderVersion:class TestCoderReachable:- """Test the Coder deployment reachability probe."""+ """Test the Coder deployment reachability probe and diagnostic."""def test_coder_reachable_returns_false_on_request_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(coder, "get_coder_url", lambda: "https://coder.example.com")@@ -429,12 +483,112 @@ class TestCoderReachable:monkeypatch.setattr(coder.requests, "get", boom)assert coder.coder_reachable() is False- def test_ensure_coder_reachable_fails_when_unreachable(self, monkeypatch: pytest.MonkeyPatch) -> None:+ def test_ensure_coder_reachable_fails_when_unreachable(+ self,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+ ) -> None:monkeypatch.setattr(coder, "get_coder_url", lambda: "https://coder.example.com")monkeypatch.setattr(coder, "coder_reachable", lambda: False)+ monkeypatch.setattr(+ coder,+ "_diagnose_unreachable_coder",+ lambda: coder.CoderReachabilityDiagnosis(+ cause="stubbed cause.",+ next_step="stubbed step.",+ facts=["fact: one"],+ ),+ )+with pytest.raises(SystemExit):coder.ensure_coder_reachable()+ out = capsys.readouterr().out+ assert "Cannot reach https://coder.example.com" in out+ assert "stubbed cause." in out+ assert "stubbed step." in out+ assert "fact: one" in out+++class TestDiagnoseUnreachableCoder:+ """Test the structured cause-and-next-step diagnosis for unreachable Coder."""++ @pytest.fixture(autouse=True)+ def _stub_url(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(coder, "get_coder_url", lambda: "https://coder.example.com")++ def test_dns_failure_dominates_other_causes(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(coder, "_tailscale_status", lambda: {"CurrentTailnet": {"Name": "posthog.com"}})+ monkeypatch.setattr(coder, "_resolve_host_ip", lambda host: None)++ def must_not_run(*args: object, **kwargs: object) -> bool:+ raise AssertionError("TCP probe should be skipped when DNS fails")++ monkeypatch.setattr(coder, "_tcp_reachable", must_not_run)++ diagnosis = coder._diagnose_unreachable_coder()+ assert "DNS lookup" in diagnosis.cause+ assert "MagicDNS" in diagnosis.next_step+ assert "Tailscale tailnet: posthog.com" in diagnosis.facts++ def test_tcp_open_signals_tls_or_clock(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(coder, "_tailscale_status", lambda: {"CurrentTailnet": {"Name": "posthog.com"}})+ monkeypatch.setattr(coder, "_resolve_host_ip", lambda host: "10.0.0.1")+ monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: True)++ diagnosis = coder._diagnose_unreachable_coder()+ assert "HTTPS probe" in diagnosis.cause+ assert "clock" in diagnosis.next_step.lower()++ def test_no_subnet_routers_points_to_wrong_tailnet(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ coder,+ "_tailscale_status",+ lambda: {"CurrentTailnet": {"Name": "personal.tailnet"}, "Peer": {"k": {"PrimaryRoutes": None}}},+ )+ monkeypatch.setattr(coder, "_resolve_host_ip", lambda host: "10.0.0.1")+ monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: False)++ diagnosis = coder._diagnose_unreachable_coder()+ assert "No peer" in diagnosis.cause+ assert "Team DevEx" in diagnosis.next_step++ def test_routers_all_offline_says_relay_is_down(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ coder,+ "_tailscale_status",+ lambda: {+ "CurrentTailnet": {"Name": "posthog.com"},+ "Peer": {+ "k": {"HostName": "subnet-router-us", "PrimaryRoutes": ["10.0.0.0/16"], "Online": False},+ },+ },+ )+ monkeypatch.setattr(coder, "_resolve_host_ip", lambda host: "10.0.0.1")+ monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: False)++ diagnosis = coder._diagnose_unreachable_coder()+ assert "subnet-router-us" in diagnosis.cause+ assert "Wait a minute" in diagnosis.next_step++ def test_routers_online_points_at_acl_or_vpn(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ coder,+ "_tailscale_status",+ lambda: {+ "CurrentTailnet": {"Name": "posthog.com"},+ "Peer": {+ "k": {"HostName": "subnet-router-us", "PrimaryRoutes": ["10.0.0.0/16"], "Online": True},+ },+ },+ )+ monkeypatch.setattr(coder, "_resolve_host_ip", lambda host: "10.0.0.1")+ monkeypatch.setattr(coder, "_tcp_reachable", lambda host, port, timeout=3.0: False)++ diagnosis = coder._diagnose_unreachable_coder()+ assert "blocked" in diagnosis.cause.lower()+ assert "ACL" in diagnosis.next_step or "VPN" in diagnosis.next_step.upper()+class TestWorkspaceNaming:"""Test workspace name derivation, label validation, and extraction."""