: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): open a devbox in herdr with devbox:open --herdr (#129771)
Rafael Audibertaf37d8849ec8
diff --git a/docs/internal/coder-workspaces.md b/docs/internal/coder-workspaces.mdindex cc5b1aebb774..3b6b130f8c8e 100644--- a/docs/internal/coder-workspaces.md+++ b/docs/internal/coder-workspaces.md@@ -26,6 +26,13 @@ hogli devbox:exec -- bash -lc 'gh auth status' # run one command on the box an**Connecting your IDE** —Open the workspace in VS Code (`hogli devbox:open --vscode`), Cursor (`--cursor`), or a browser-based editor (`--web`).+**Driving a devbox from Herdr** —+`hogli devbox:open --herdr` adds the devbox to [Herdr](https://herdr.dev) as a machine and opens a space on it in `~/posthog`.+Terminals and agents you open in that space run on the devbox.+The first run copies `hc` onto the box; later runs show the same space again.+The devbox must be running, so run `hogli devbox:start` first.+Stopping the devbox ends its terminals, and Herdr gives each pane a new shell after the next start.+**Running the dev stack in detached mode** —Start the PostHog dev stack in the background without an interactive terminal:@@ -61,7 +68,7 @@ hogli devbox:sync --status # check sync statehogli devbox:sync --terminate # tear down when done```-`devbox:open --vscode` / `--cursor` warns when sync is active, since editing over Remote-SSH while the mirror is live would conflict with the local source of truth.+`devbox:open --vscode` / `--cursor` / `--herdr` warns when sync is active, since editing over Remote-SSH while the mirror is live would conflict with the local source of truth.**One devbox per git worktree** —Run `hogli devbox:worktree` from a linked worktree to give it its own labeled box and sync mirror. The label comes from the branch name, shortened with a hash when it would push the workspace name past Coder's 32-character limit. Re-running reuses the same box and mirror. `--clone-from <label>` creates the box with `devbox:clone`, and `--dry-run` prints the plan.@@ -99,7 +106,8 @@ This does the host-side setup only:- verifies Tailscale connectivity- installs the `coder` CLI at the version matching the server and the `mutagen` binary (pinned v0.18.1) that powers `devbox:sync`-- logs you into the Coder deployment+- links `coder` into `~/.local/bin` (or `~/bin`) when that directory is on your PATH, so you can run `coder` yourself; otherwise it prints the PATH line to add+- logs you into the Coder deployment. Login asks you to paste a token from the browser, so run setup in a terminal that takes input. In a shell without one, setup stops and tells you to run `coder login` in a terminal first- configures `~/.ssh/config` with Coder workspace entries (use `--skip-configure-ssh` to skip)- shows a compact "Currently configured:" status block with your saved settings- prompts for Git identity, an optional dotfiles repo, a preferred region, and an optional Claude OAuth token (stored as a Coder user secret)diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex ee70ea365b07..c1ad5981afcb 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -25,7 +25,10 @@ from hogli import telemetryfrom hogli.manifest import get_manifestfrom ..git_signing import DEVBOX_FEEDBACK_HINT, DEVBOX_SIGNING_NOTE, signs_with_secure_enclave_key-from . import mutagen+from . import (+ herdr as herdr_app,+ mutagen,+)from .coder import (CLAUDE_CODE_OAUTH_ENV,DEFAULT_PRESET,@@ -34,6 +37,7 @@ from .coder import (EXPECTED_TAILNET,GIT_SIGNING_KEY_SECRET,REGIONS,+ REMOTE_REPO_PATH,_diagnose_unreachable_coder,_fail,_ssh_host_alias,@@ -47,6 +51,7 @@ from .coder import (delete_workspace,ensure_coder_authenticated,ensure_coder_installed,+ ensure_coder_on_path,ensure_coder_reachable,ensure_runtime_ready,exec_replace,@@ -1332,6 +1337,7 @@ def devbox_setup(click.echo(click.style("Configuring devbox CLI access...", bold=True))ensure_coder_reachable("rerun `hogli devbox:setup`.")ensure_coder_installed(verbose=verbose)+ ensure_coder_on_path()ensure_coder_authenticated()# One `coder secret list` round trip fuels the status block and both@@ -1801,32 +1807,51 @@ def devbox_remote_exec(workspace_name: str | None, command: tuple[str, ...]) ->exec_replace(name, list(command))[email protected](name="devbox:open", help="Open devbox in browser, VS Code, or Cursor")+def _open_in_herdr(name: str, workspaces: list[dict[str, Any]] | None) -> None:+ ws = _get_workspace_or_fail(name, workspaces)+ status = get_workspace_status(ws)+ if status != "running":+ _fail(+ f"Devbox '{name}' is {status}. Start it with `hogli devbox:start{_workspace_arg_suffix(name)}`, then retry.",+ cause="herdr_workspace_not_running",+ )+ if not coder_ssh_alias_configured(name):+ _fail(+ "SSH access for devboxes isn't configured. Run `hogli devbox:setup` (it runs `coder config-ssh`), then retry.",+ cause="herdr_ssh_not_configured",+ )+ herdr_app.open_in_herdr(name, folder=REMOTE_REPO_PATH)++[email protected](name="devbox:open", help="Open devbox in browser, VS Code, Cursor, or Herdr")@workspace_argument@click.option("--vscode", is_flag=True, help="Open in VS Code Desktop via SSH")@click.option("--cursor", is_flag=True, help="Open in Cursor via SSH")@click.option("--web", is_flag=True, help="Open code-server (VS Code in browser)")-def devbox_open(workspace: str | None, vscode: bool, cursor: bool, web: bool) -> None:[email protected]("--herdr", is_flag=True, help="Add the devbox to Herdr as a machine and open a space on it")+def devbox_open(workspace: str | None, vscode: bool, cursor: bool, web: bool, herdr: bool) -> None:"""Open the devbox in a browser or editor."""- chosen = sum([vscode, cursor, web])+ chosen = sum([vscode, cursor, web, herdr])if chosen > 1:- raise click.UsageError("Choose one of `--vscode`, `--cursor`, or `--web`.")+ raise click.UsageError("Choose one of `--vscode`, `--cursor`, `--web`, or `--herdr`.")ensure_runtime_ready()- name, _ = resolve_workspace_name(workspace)+ name, workspaces = resolve_workspace_name(workspace)- if (vscode or cursor) and mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)):- ide = "VS Code" if vscode else "Cursor"+ if (vscode or cursor or herdr) and mutagen.sync_list(label_selector=mutagen.workspace_label_selector(name)):+ editor = "VS Code Remote" if vscode else "Cursor Remote" if cursor else "Herdr terminals on the devbox"click.echo(click.style(- f"⚠ Sync is active for '{name}'. Editing in {ide} Remote can conflict with the local source of truth.",+ f"⚠ Sync is active for '{name}'. Editing in {editor} can conflict with the local source of truth.",fg="yellow",))- target = "vscode" if vscode else "cursor" if cursor else "web" if web else "browser"+ target = "vscode" if vscode else "cursor" if cursor else "web" if web else "herdr" if herdr else "browser"telemetry.add_command_properties(devbox_open_target=target)- if vscode:+ if herdr:+ _open_in_herdr(name, workspaces)+ elif vscode:click.echo(f"Opening '{name}' in VS Code...")open_vscode(name)elif cursor:diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.pyindex abe8f2f921a4..f3127ac7f526 100644--- a/tools/hogli-commands/hogli_commands/devbox/coder.py+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py@@ -57,6 +57,7 @@ AUTOMATIC_UPDATES_ARGS = ("--automatic-updates", "always")BREW_PACKAGE = "coder/coder/coder"RUNTIME_SETUP_HINT = "Run `hogli devbox:setup`."_MANAGED_CODER_DIR = Path.home() / ".hogli" / "bin"+REMOTE_REPO_PATH = "/home/coder/posthog"GIT_NAME_PARAMETER = "git_name"GIT_EMAIL_PARAMETER = "git_email"DOTFILES_URI_PARAMETER = "dotfiles_uri"@@ -914,6 +915,49 @@ def _install_coder_cli(*, verbose: bool = False) -> None:_fail(f"Coder CLI install reported success but {managed} is missing.\nTry manually: {cmd}")+_USER_BIN_DIRS = (Path.home() / ".local" / "bin", Path.home() / "bin")+++def _display_path(path: Path) -> str:+ home = Path.home()+ return f"~/{path.relative_to(home)}" if path.is_relative_to(home) else str(path)+++def coder_command_hint() -> str:+ """Return how the user can run the Coder CLI from their own shell."""+ if shutil.which("coder"):+ return "coder"+ return _display_path(_MANAGED_CODER_DIR / "coder")+++def ensure_coder_on_path() -> None:+ """Link the managed Coder CLI into a user bin directory on PATH so `coder` runs in the user's shell.++ hogli runs the binary from ~/.hogli/bin by full path, which isn't on PATH,+ so commands the user runs themselves (like `coder login`) aren't found.+ """+ managed = _MANAGED_CODER_DIR / "coder"+ if not managed.is_file() or shutil.which("coder"):+ return++ path_entries = {Path(entry).expanduser() for entry in os.environ.get("PATH", "").split(os.pathsep) if entry}+ for bin_dir in _USER_BIN_DIRS:+ link = bin_dir / "coder"+ if bin_dir not in path_entries or not bin_dir.is_dir() or link.is_symlink() or link.exists():+ continue+ try:+ link.symlink_to(managed)+ except OSError:+ continue+ click.echo(f" Linked `coder` into {_display_path(bin_dir)} so you can run it yourself.")+ return++ click.echo(+ f" To run `coder` yourself, add {_display_path(_MANAGED_CODER_DIR)} to your PATH:\n"+ ' export PATH="$HOME/.hogli/bin:$PATH"'+ )++def ensure_coder_installed(*, verbose: bool = False) -> None:"""Install the Coder CLI at the expected version, or reinstall on mismatch."""if not coder_installed():@@ -962,6 +1006,14 @@ def ensure_coder_authenticated() -> None:_fail(f"`coder` is not installed. {RUNTIME_SETUP_HINT}", cause="coder_not_installed")coder_url = get_coder_url()+ if not sys.stdin.isatty():+ # `coder login` asks for a token pasted from the browser and fails with+ # "paste token prompt: EOF" when stdin isn't a terminal.+ _fail(+ "Coder login needs you to paste a token, and this shell can't take input.\n"+ f" Run `{coder_command_hint()} login {coder_url}` in a terminal, then run `hogli devbox:setup` again.",+ cause="coder_login_needs_terminal",+ )click.echo(f"Logging in to {coder_url}...")result = _run(["coder", "login", coder_url])if result.returncode != 0:@@ -1915,7 +1967,7 @@ def open_cursor(name: str) -> None:cursor = shutil.which("cursor")if not cursor:_fail("`cursor` CLI is not on PATH. Open Cursor and enable Shell Integration from the Command Palette.")- _execvp(cursor, ["cursor", "--remote", f"ssh-remote+{_ssh_host_alias(name)}", "/home/coder/posthog"])+ _execvp(cursor, ["cursor", "--remote", f"ssh-remote+{_ssh_host_alias(name)}", REMOTE_REPO_PATH])def open_web_ide(name: str) -> None:diff --git a/tools/hogli-commands/hogli_commands/devbox/herdr.py b/tools/hogli-commands/hogli_commands/devbox/herdr.pynew file mode 100644index 000000000000..27b2da2dba9b--- /dev/null+++ b/tools/hogli-commands/hogli_commands/devbox/herdr.py@@ -0,0 +1,184 @@+"""Open a devbox in Herdr as a remote machine with its own space.++Herdr's terminals run in herdr-core (`hc`), which reaches other machines over+ssh. Registering the devbox's ``coder.<name>`` alias as an `hc` machine lets+Herdr run terminals and agents on the box, and a space on that machine shows+them in the window.+"""++from __future__ import annotations++import json+import time+import shutil+import subprocess+from typing import Any++import click++from .coder import _fail, _ssh_host_alias++HERDR_URL = "https://herdr.dev"+_MACHINE_ADD_TIMEOUT = 300.0+_MACHINE_CONNECT_TIMEOUT = 60.0+_WINDOW_START_TIMEOUT = 20.0+_WINDOW_SEES_MACHINE_TIMEOUT = 15.0+_POLL_INTERVAL = 0.5+++def _require_cli(name: str) -> None:+ if shutil.which(name) is None:+ _fail(+ f"`{name}` is not on PATH. Install Herdr from {HERDR_URL}, then retry.",+ cause="herdr_not_installed",+ )+++def _run(args: list[str], *, timeout: float = 30.0) -> subprocess.CompletedProcess[str]:+ # Output is captured, so a prompt would wait on input nobody can see.+ # Closing stdin makes it fail with an error instead.+ try:+ return subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)+ except subprocess.TimeoutExpired:+ # Report a timeout as a failed run, so that polling loops retry it and+ # other callers show their own error message instead of a traceback.+ return subprocess.CompletedProcess(args, 124, "", f"`{' '.join(args[:3])}` timed out after {timeout:.0f}s.")+++def _run_json(args: list[str], *, failure: str, cause: str) -> dict[str, Any]:+ result = _run(args)+ if result.returncode != 0:+ _fail(f"{failure}\n{_output_of(result)}", cause=cause)+ try:+ parsed = json.loads(result.stdout)+ except json.JSONDecodeError:+ parsed = None+ if isinstance(parsed, dict):+ return parsed+ _fail(f"{failure}\n`{' '.join(args)}` printed something hogli can't read.", cause=cause)+ raise SystemExit(1) # unreachable; helps ty see the function doesn't fall through+++def _output_of(result: subprocess.CompletedProcess[str]) -> str:+ return (result.stderr or result.stdout or "").strip()+++def ensure_machine(workspace_name: str) -> str:+ """Return the `hc` machine name for the devbox, adding the machine when it's missing."""+ target = _ssh_host_alias(workspace_name)+ listing = _run_json(+ ["hc", "machine", "ls", "--json"],+ failure="Couldn't list Herdr machines.",+ cause="herdr_machine_list_failed",+ )+ for machine in listing.get("machines", []):+ if machine.get("target") == target and machine.get("name"):+ _wait_until_connected(machine["name"])+ return machine["name"]++ click.echo(f"Adding '{workspace_name}' to Herdr. The first time, this copies hc onto the devbox...")+ result = _run(+ ["hc", "machine", "add", target, "--name", workspace_name, "--install", "--json"],+ timeout=_MACHINE_ADD_TIMEOUT,+ )+ if result.returncode != 0:+ _fail(+ f"Couldn't add '{workspace_name}' to Herdr.\n{_output_of(result)}",+ cause="herdr_machine_add_failed",+ )+ _wait_until_connected(workspace_name)+ return workspace_name+++def _machine_state(name: str) -> str | None:+ result = _run(["hc", "machine", "ls", "--json"])+ if result.returncode != 0:+ return None+ try:+ machines = json.loads(result.stdout).get("machines", [])+ except json.JSONDecodeError:+ return None+ return next((m.get("state") for m in machines if m.get("name") == name), None)+++def _wait_until_connected(name: str) -> None:+ # `hc machine add` returns while the machine is still connecting, and a+ # saved machine reconnects for a while after its devbox starts. The Herdr+ # window refuses a space on a machine it hasn't seen connect.+ deadline = time.monotonic() + _MACHINE_CONNECT_TIMEOUT+ while _machine_state(name) != "connected":+ if time.monotonic() >= deadline:+ _fail(+ f"Herdr couldn't connect to '{name}'. Check `hc machine ls`, then run this command again.",+ cause="herdr_machine_connect_timeout",+ )+ time.sleep(_POLL_INTERVAL)+++def _window_running() -> bool:+ return _run(["herdr-app", "status"]).returncode == 0+++def ensure_window() -> None:+ """Open the Herdr window when it isn't running, and wait until it answers commands."""+ if _window_running():+ return++ click.echo("Opening Herdr...")+ subprocess.Popen(+ ["herdr-app"],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ deadline = time.monotonic() + _WINDOW_START_TIMEOUT+ while time.monotonic() < deadline:+ time.sleep(_POLL_INTERVAL)+ if _window_running():+ return+ _fail(+ "Herdr didn't open in time. Open it yourself, then run this command again.",+ cause="herdr_window_timeout",+ )+++def _do(command: str, args: dict[str, Any], *, retry_for: float = 0.0) -> None:+ deadline = time.monotonic() + retry_for+ while True:+ result = _run(["herdr-app", "do", command, json.dumps(args)])+ if result.returncode == 0:+ return+ if time.monotonic() >= deadline:+ _fail(f"Herdr couldn't run {command}.\n{_output_of(result)}", cause="herdr_command_failed")+ time.sleep(_POLL_INTERVAL)+++def show_space(machine: str, *, name: str, folder: str) -> bool:+ """Show the machine's Herdr space, making one when none exists. Returns whether one was made."""+ listing = _run_json(+ ["herdr-app", "ls"],+ failure="Couldn't read the spaces in the Herdr window.",+ cause="herdr_ls_failed",+ )+ for space in listing.get("spaces", []):+ if space.get("machine") == machine and space.get("id"):+ _do("space.select", {"id": space["id"]})+ return False++ # The window learns about a machine from herdr-core shortly after hc+ # reports it connected, so a just-added machine can be briefly unknown.+ _do("space.new", {"name": name, "machine": machine, "folder": folder}, retry_for=_WINDOW_SEES_MACHINE_TIMEOUT)+ return True+++def open_in_herdr(workspace_name: str, *, folder: str) -> None:+ """Register the devbox with Herdr and show a space for it."""+ _require_cli("hc")+ _require_cli("herdr-app")+ machine = ensure_machine(workspace_name)+ ensure_window()+ if show_space(machine, name=workspace_name, folder=folder):+ click.echo(f"Opened a Herdr space on '{workspace_name}' in {folder}.")+ else:+ click.echo(f"Showing the Herdr space for '{workspace_name}'.")diff --git a/tools/hogli-commands/hogli_commands/devbox/sync.py b/tools/hogli-commands/hogli_commands/devbox/sync.pyindex 1397da66cb39..75fd8543014c 100644--- a/tools/hogli-commands/hogli_commands/devbox/sync.py+++ b/tools/hogli-commands/hogli_commands/devbox/sync.py@@ -20,9 +20,15 @@ import clickfrom . import hogland, mutagenfrom .cli import _workspace_arg_suffix, resolve_workspace_name, workspace_argument-from .coder import _fail, ensure_runtime_ready, get_workspace, get_workspace_status, run_in_workspace+from .coder import (+ REMOTE_REPO_PATH as _REMOTE_REPO_PATH,+ _fail,+ ensure_runtime_ready,+ get_workspace,+ get_workspace_status,+ run_in_workspace,+)-_REMOTE_REPO_PATH = "/home/coder/posthog"_REMOTE_GIT_TIMEOUT_SECONDS = 120_DETACHED = "HEAD"diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.pyindex bb9004418bc2..004deba2f6d9 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py@@ -22,6 +22,7 @@ from hogli_commands.devbox import (cli as devbox_cli,coder,config as devbox_config,+ herdr as devbox_herdr,hogland as devbox_hogland,mutagen as devbox_mutagen,sync as devbox_sync,@@ -581,6 +582,56 @@ class TestCoderVersion:with pytest.raises(SystemExit):coder.ensure_coder_authenticated()+ def test_ensure_coder_authenticated_points_at_a_terminal_without_stdin(+ self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+ ) -> None:+ monkeypatch.setattr(coder, "coder_authenticated", lambda: False)+ monkeypatch.setattr(coder, "coder_installed", lambda: True)+ monkeypatch.setattr(coder, "get_coder_url", lambda: "https://coder.example.com")+ monkeypatch.setattr(coder, "coder_command_hint", lambda: "coder")+ monkeypatch.setattr(coder.sys.stdin, "isatty", lambda: False)++ def boom(*args: object, **kwargs: object) -> subprocess.CompletedProcess[str]:+ raise AssertionError("coder login can't read a pasted token without a terminal")++ monkeypatch.setattr(coder, "_run", boom)++ with pytest.raises(SystemExit):+ coder.ensure_coder_authenticated()++ assert "Run `coder login https://coder.example.com` in a terminal" in capsys.readouterr().out++ @pytest.mark.parametrize("user_bin_on_path", [True, False])+ def test_ensure_coder_on_path(+ self,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+ user_bin_on_path: bool,+ ) -> None:+ managed_dir = tmp_path / "hogli-bin"+ managed_dir.mkdir()+ (managed_dir / "coder").write_text("#!/bin/sh\n")+ (managed_dir / "coder").chmod(0o755)+ user_bin = tmp_path / "local-bin"+ user_bin.mkdir()+ other_dir = tmp_path / "other"+ other_dir.mkdir()+ monkeypatch.setattr(coder, "_MANAGED_CODER_DIR", managed_dir)+ monkeypatch.setattr(coder, "_USER_BIN_DIRS", (user_bin,))+ monkeypatch.setenv("PATH", os.pathsep.join([str(user_bin)] if user_bin_on_path else [str(other_dir)]))++ coder.ensure_coder_on_path()++ link = user_bin / "coder"+ if user_bin_on_path:+ assert link.resolve() == (managed_dir / "coder").resolve()+ coder.ensure_coder_on_path()+ assert link.resolve() == (managed_dir / "coder").resolve()+ else:+ assert not link.exists()+ assert 'export PATH="$HOME/.hogli/bin:$PATH"' in capsys.readouterr().out+class TestCoderReachable:"""Test the Coder deployment reachability probe and diagnostic."""@@ -2784,12 +2835,136 @@ class TestDevboxCommands:assert "hogli devbox:forward --port 8011" in result.output+class TestDevboxOpenHerdr:+ @pytest.fixture+ def herdr_calls(self, monkeypatch: pytest.MonkeyPatch) -> Callable[..., list[list[str]]]:+ def install(+ machines: list[dict], spaces: list[dict], *, connecting_polls: int = 0, add_times_out: bool = False+ ) -> list[list[str]]:+ calls: list[list[str]] = []+ remaining = {"polls": connecting_polls}++ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:+ if args[0] not in ("hc", "herdr-app"):+ raise AssertionError(f"unexpected command: {args}")+ calls.append(args)+ stdout = "{}"+ if args[:3] == ["hc", "machine", "add"]:+ if add_times_out:+ raise subprocess.TimeoutExpired(args, 300)+ machines.append({"name": args[5], "target": args[3]})+ elif args[:3] == ["hc", "machine", "ls"]:+ state = "connecting" if remaining["polls"] > 0 else "connected"+ remaining["polls"] = max(remaining["polls"] - 1, 0)+ stdout = json.dumps({"machines": [{**m, "state": state} for m in machines]})+ elif args[:2] == ["herdr-app", "ls"]:+ stdout = json.dumps({"spaces": spaces})+ elif args[:2] == ["herdr-app", "do"] and remaining["polls"] > 0:+ return subprocess.CompletedProcess(args, 1, '{"error": "no machine"}', "")+ return subprocess.CompletedProcess(args, 0, stdout, "")++ monkeypatch.setattr(devbox_herdr.subprocess, "run", fake_run)+ monkeypatch.setattr(devbox_herdr.shutil, "which", lambda name: f"/usr/local/bin/{name}")+ monkeypatch.setattr(devbox_herdr, "_POLL_INTERVAL", 0)+ monkeypatch.setattr(devbox_herdr, "_WINDOW_SEES_MACHINE_TIMEOUT", 0)+ return calls++ return install++ @pytest.fixture+ def running_workspace(self, monkeypatch: pytest.MonkeyPatch) -> Callable[[str], None]:+ def install(status: str) -> None:+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")+ monkeypatch.setattr(+ devbox_cli,+ "resolve_workspace_name",+ lambda ws, **kw: (+ "devbox-test-user",+ [{"name": "devbox-test-user", "latest_build": {"status": status}}],+ ),+ )+ monkeypatch.setattr(devbox_cli, "coder_ssh_alias_configured", lambda name: True)+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda **kw: [])++ return install++ def test_adds_the_machine_and_opens_a_space_in_the_repo(+ self, herdr_calls: Callable[..., list[list[str]]], running_workspace: Callable[[str], None]+ ) -> None:+ running_workspace("running")+ calls = herdr_calls(machines=[], spaces=[])++ result = runner.invoke(cli, ["devbox:open", "--herdr"])++ assert result.exit_code == 0, result.output+ assert [+ "hc",+ "machine",+ "add",+ "coder.devbox-test-user",+ "--name",+ "devbox-test-user",+ "--install",+ "--json",+ ] in calls+ space_new = next(call for call in calls if call[:3] == ["herdr-app", "do", "space.new"])+ assert json.loads(space_new[3]) == {+ "name": "devbox-test-user",+ "machine": "devbox-test-user",+ "folder": "/home/coder/posthog",+ }++ def test_reuses_the_machine_and_space_already_in_herdr_once_it_reconnects(+ self, herdr_calls: Callable[..., list[list[str]]], running_workspace: Callable[[str], None]+ ) -> None:+ running_workspace("running")+ calls = herdr_calls(+ machines=[{"name": "box", "target": "coder.devbox-test-user"}],+ spaces=[{"id": "box/sp1", "machine": "box"}, {"id": "sp2", "machine": None}],+ connecting_polls=2,+ )++ result = runner.invoke(cli, ["devbox:open", "--herdr"])++ assert result.exit_code == 0, result.output+ assert not any(call[:3] == ["hc", "machine", "add"] for call in calls)+ assert not any(call[:3] == ["herdr-app", "do", "space.new"] for call in calls)+ assert ["herdr-app", "do", "space.select", json.dumps({"id": "box/sp1"})] in calls++ def test_stopped_devbox_points_at_devbox_start(+ self, herdr_calls: Callable[..., list[list[str]]], running_workspace: Callable[[str], None]+ ) -> None:+ running_workspace("stopped")+ calls = herdr_calls(machines=[], spaces=[])++ result = runner.invoke(cli, ["devbox:open", "--herdr"])++ assert result.exit_code == 1+ assert "Devbox 'devbox-test-user' is stopped. Start it with `hogli devbox:start`" in result.output+ assert calls == []++ def test_a_timed_out_hc_call_fails_with_a_message(+ self, herdr_calls: Callable[..., list[list[str]]], running_workspace: Callable[[str], None]+ ) -> None:+ running_workspace("running")+ herdr_calls(machines=[], spaces=[], add_times_out=True)++ result = runner.invoke(cli, ["devbox:open", "--herdr"])++ assert result.exit_code == 1+ assert isinstance(result.exception, SystemExit)+ assert "Couldn't add 'devbox-test-user' to Herdr." in result.output+ assert "timed out after 300s" in result.output++@pytest.fixturedef stub_setup_environment(monkeypatch: pytest.MonkeyPatch) -> None:"""No-op every external dependency in ``devbox_setup`` so reset/gate tests can run hermetically."""for name in ("ensure_coder_reachable", "ensure_coder_authenticated"):monkeypatch.setattr(devbox_cli, name, lambda *a, **kw: None)monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)+ monkeypatch.setattr(devbox_cli, "ensure_coder_on_path", lambda: None)monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: None)monkeypatch.setattr(devbox_cli, "maybe_configure_ssh", lambda *a, **kw: None)monkeypatch.setattr(devbox_cli, "maybe_configure_git_identity", lambda *a, **kw: None)