: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): wait for startup scripts on start (#117737)
Raúl Negrón-Otero592f1f9c669a
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.mdindex 09038cdad415..6ab6b3ad7e95 100644--- a/.agents/skills/setting-up-devbox/SKILL.md+++ b/.agents/skills/setting-up-devbox/SKILL.md@@ -54,6 +54,7 @@ hogli devbox:start```This creates the box on first use and resumes it after a stop.+It returns once the box's startup scripts finish, so the box is ready to connect to. `devbox:restart`, `devbox:update` and `devbox:clone` wait the same way. If a script fails or the wait gives up, the box still runs and hogli prints a warning that points to `hogli devbox:logs`.It brings up the PostHog stack only when the workspace has `--start-app` set, which is covered in [Run the PostHog app](#run-the-posthog-app).`--disk` (`100` or `200` GiB) applies only when the box is created.`--region` (`us-east-1` or `eu-central-1`) starts that region's default box and creates it if it doesn't exist, so leave it off when resuming an existing box.diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex 1897564bda3c..3059abd47107 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -88,6 +88,7 @@ from .coder import (update_workspace,upsert_user_secret,user_secret_exists,+ wait_for_agent_ready,)from .config import (DevboxConfig,@@ -270,6 +271,33 @@ def _workspace_arg_suffix(name: str) -> str:return f" {label}" if label else ""+_NOT_READY_REASONS = {+ "start_error": "A startup script failed, so some setup may be missing.",+ "start_timeout": "A startup script ran past its time limit, so some setup may be missing.",+ "wait_timeout": "Its startup scripts are still running.",+ "build_failed": "Its latest build failed.",+ "stopped": "It stopped before its startup scripts finished.",+ "agent_timeout": "Its agent did not connect to Coder.",+ "unavailable": "hogli could not read its status from Coder.",+}+++def _wait_until_ready(name: str) -> None:+ """Hold the command until startup scripts finish, warning if they did not."""+ click.echo("Waiting for startup scripts...")+ state = wait_for_agent_ready(name)+ telemetry.add_command_properties(devbox_agent_lifecycle=state)+ if state == "ready":+ return+ click.echo(+ click.style(+ f"Devbox '{name}' may not be ready. {_NOT_READY_REASONS[state]} "+ f"Check `hogli devbox:logs{_workspace_arg_suffix(name)}`.",+ fg="yellow",+ )+ )++def _get_workspace_or_fail(name: str, workspaces: list[dict[str, Any]] | None = None) -> dict[str, Any]:"""Return a workspace or exit with a consistent message when missing."""workspace = get_workspace(name, workspaces)@@ -346,6 +374,7 @@ def _start_existing_workspace(else:click.echo(f"Starting devbox '{name}'...")start_workspace(name, verbose=verbose)+ _wait_until_ready(name)click.echo("Started.")_print_connection_info(name)return@@ -353,6 +382,7 @@ def _start_existing_workspace(click.echo(f"Devbox '{name}' is in state: {status}")click.echo("Attempting to start...")start_workspace(name, verbose=verbose)+ _wait_until_ready(name)_print_connection_info(name)@@ -1470,6 +1500,7 @@ def devbox_start(start_app=start_app,verbose=verbose,)+ _wait_until_ready(name)click.echo("Created.")_print_connection_info(name)@@ -1552,6 +1583,7 @@ def devbox_clone(workspace: str | None, new_label: str, yes: bool, verbose: booltemplate=template,verbose=verbose,)+ _wait_until_ready(target_name)click.echo("Cloned.")_print_connection_info(target_name)@@ -1585,6 +1617,7 @@ def devbox_restart(workspace: str | None, verbose: bool) -> None:_get_workspace_or_fail(name, workspaces)click.echo(f"Restarting '{name}'...")restart_workspace(name, verbose=verbose)+ _wait_until_ready(name)click.echo("Restarted.")_print_connection_info(name)@@ -1602,6 +1635,7 @@ def devbox_update(workspace: str | None, verbose: bool) -> None:returnclick.echo(f"Updating '{name}' to the latest template...")update_workspace(name, verbose=verbose)+ _wait_until_ready(name)click.echo("Updated.")click.echo("Note: if your local lockfiles differ from the new AMI's baked versions, "diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.pyindex 3704704fcbce..adb7b4307e44 100644--- a/tools/hogli-commands/hogli_commands/devbox/coder.py+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py@@ -11,6 +11,7 @@ import reimport csvimport sysimport json+import timeimport shleximport base64import shutil@@ -227,9 +228,11 @@ def _resolve_coder(args: list[str]) -> list[str]:return args-def _run(args: list[str], *, capture_output: bool = False) -> subprocess.CompletedProcess[str]:+def _run(+ args: list[str], *, capture_output: bool = False, timeout: float | None = None+) -> subprocess.CompletedProcess[str]:"""Run a subprocess with consistent text handling."""- return subprocess.run(_resolve_coder(args), capture_output=capture_output, text=True)+ return subprocess.run(_resolve_coder(args), capture_output=capture_output, text=True, timeout=timeout)def _run_or_exit(args: list[str]) -> None:@@ -1126,9 +1129,12 @@ def get_default_workspace_prefix() -> str:return f"{_WORKSPACE_PREFIX}-{get_username()}"-def _list_workspaces() -> list[dict[str, Any]]:+def _list_workspaces(*, timeout: float | None = None) -> list[dict[str, Any]]:"""Return raw workspace payloads from the Coder CLI."""- result = _run(["coder", "list", "--output", "json"], capture_output=True)+ try:+ result = _run(["coder", "list", "--output", "json"], capture_output=True, timeout=timeout)+ except subprocess.TimeoutExpired:+ return []if result.returncode != 0:return []@@ -1484,6 +1490,58 @@ def start_workspace(name: str, *, verbose: bool = False) -> None:raise SystemExit(result.returncode)+# Must exceed the longest blocking startup script timeout in the posthog-linux+# template, so that Coder reports `start_timeout` itself before this gives up.+AGENT_READY_TIMEOUT = 960+AGENT_READY_POLL_INTERVAL = 3+_AGENT_START_FAILED_STATES = frozenset({"start_error", "start_timeout"})+_AGENT_SHUTDOWN_STATES = frozenset({"shutting_down", "shutdown_error", "shutdown_timeout", "off"})+# A build that is not starting or running lists no agents, so its agent states+# alone never end the wait.+_BUILD_STOPPED_STATUSES = frozenset({"stopping", "stopped", "canceling", "canceled", "deleting", "deleted"})+++def _agents(workspace: dict[str, Any]) -> list[dict[str, Any]]:+ return [+ agent+ for resource in workspace.get("latest_build", {}).get("resources", [])+ for agent in resource.get("agents") or []+ ]+++def wait_for_agent_ready(name: str, *, timeout: int = AGENT_READY_TIMEOUT) -> str:+ """Block until the workspace's startup scripts finish, so "started" means usable.++ Returns the state that ended the wait: ``ready``, a Coder lifecycle state+ (``start_error``, ``start_timeout``), ``build_failed``, ``stopped`` when the+ box shut down, ``agent_timeout`` when the agent never connected,+ ``unavailable`` when `coder list` did not return the box, or ``wait_timeout``.+ """+ deadline = time.monotonic() + timeout+ while True:+ workspace = get_workspace(name, _list_workspaces(timeout=deadline - time.monotonic()))+ if workspace is None:+ return "wait_timeout" if time.monotonic() >= deadline else "unavailable"+ build_status = get_workspace_status(workspace)+ if build_status == "failed":+ return "build_failed"+ if build_status in _BUILD_STOPPED_STATUSES:+ return "stopped"+ agents = _agents(workspace)+ states = {str(agent.get("lifecycle_state", "")) for agent in agents}+ if states == {"ready"}:+ return "ready"+ if failed := sorted(states & _AGENT_START_FAILED_STATES):+ return failed[0]+ if states & _AGENT_SHUTDOWN_STATES:+ return "stopped"+ if any(agent.get("status") == "timeout" for agent in agents):+ return "agent_timeout"+ if time.monotonic() >= deadline:+ return "wait_timeout"+ time.sleep(AGENT_READY_POLL_INTERVAL)++def stop_workspace(name: str, *, verbose: bool = False) -> None:"""Stop a running workspace."""result = _run_build(["coder", "stop", name, "--yes"], verbose=verbose)diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.pyindex 486792dbb62d..d3f32b0777ea 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py@@ -27,6 +27,11 @@ from hogli_commands.devbox import (runner = CliRunner()[email protected](autouse=True)+def agent_ready_immediately(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(devbox_cli, "wait_for_agent_ready", lambda name: "ready")++@pytest.fixturedef devbox_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:config_path = tmp_path / "hogli_devbox.json"@@ -1313,6 +1318,57 @@ class TestTemplatePresetResolution:assert "Warning" not in output+def _running_build(agent: dict[str, str]) -> dict[str, object]:+ return {"status": "running", "resources": [{"agents": [agent]}]}+++class TestWaitForAgentReady:+ @pytest.mark.parametrize(+ "builds, expected",+ [+ ([_running_build({"lifecycle_state": "starting"}), _running_build({"lifecycle_state": "ready"})], "ready"),+ (+ [_running_build({"lifecycle_state": "starting"}), _running_build({"lifecycle_state": "start_error"})],+ "start_error",+ ),+ (+ [_running_build({"lifecycle_state": "created"}), _running_build({"lifecycle_state": "start_timeout"})],+ "start_timeout",+ ),+ ([_running_build({"lifecycle_state": "starting"}), {"status": "stopped", "resources": []}], "stopped"),+ ([{"status": "failed", "resources": []}], "build_failed"),+ ([_running_build({"lifecycle_state": "created", "status": "timeout"})], "agent_timeout"),+ ([_running_build({"lifecycle_state": "starting"}), None], "unavailable"),+ ([_running_build({"lifecycle_state": "starting"})] * 10, "wait_timeout"),+ ],+ ids=[+ "ready",+ "script-failed",+ "script-timed-out",+ "stopped",+ "build-failed",+ "agent-never-connected",+ "box-gone",+ "never-ready",+ ],+ )+ def test_returns_when_startup_scripts_settle(+ self, monkeypatch: pytest.MonkeyPatch, builds: list[dict[str, object] | None], expected: str+ ) -> None:+ polls = iter(builds)+ clock = iter(range(0, 1000, 5))++ def list_workspaces(*, timeout: float | None = None) -> list[dict[str, object]]:+ build = next(polls)+ return [] if build is None else [{"name": "devbox-test-user", "latest_build": build}]++ monkeypatch.setattr(coder, "_list_workspaces", list_workspaces)+ monkeypatch.setattr(coder.time, "monotonic", lambda: next(clock))+ monkeypatch.setattr(coder.time, "sleep", lambda seconds: None)++ assert coder.wait_for_agent_ready("devbox-test-user", timeout=50) == expected++class TestResolveWorkspaceName:"""Test the CLI workspace resolution logic."""