Skip to content

: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.

feat(devbox): one herdr module for worktree boxes and herdr machines (#130225)

Georges-Antoine Assi0ef0332b755f
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.md
index 4d87e2de762f..c6937a374922 100644
--- a/.agents/skills/setting-up-devbox/SKILL.md
+++ b/.agents/skills/setting-up-devbox/SKILL.md
@@ -218,6 +218,7 @@ The script runs the main checkout's hogli, so pull the main checkout after a cha
- Superset, Orca and worktrunk run `bin/devbox-worktree-hook removing` before they delete a worktree. It runs `hogli devbox:worktree:teardown --background`, which stops the mirror while the files still exist and then stops the box in the background (log: `~/.config/posthog/hogli-devbox-teardown.log`). The box's record is then dropped, so the box no longer belongs to any worktree.
- Emdash and Conductor run `bin/devbox-worktree-hook archiving` instead, because they keep an archived worktree on disk. It adds `--keep-record`, so when the app restores the worktree, its create hook starts the same box again.
- herdr reports a removal only after the folder is gone, so its plugin runs `devbox:worktree:prune --path <worktree>`. t3code has no removal hook, so run `hogli devbox:worktree:prune` by hand.
+- herdr has two ways to use devboxes. With `--auto herdr`, agents run on the laptop and each herdr worktree gets its own box. With `hogli devbox:open --herdr`, the box is a herdr machine, and agents and worktrees run on it with no mirror. `devbox:open --herdr <label>` on a worktree's box gives terminals for the stack and tests. Edit files in the local worktree, because files edited on a mirrored box conflict with the mirror. Deleting a box also removes its herdr machine.
- A t3code worktree restored from a cleaned-up thread skips setup scripts, so it gets a box only when `other` is enabled.
## Other tasks
diff --git a/docs/internal/coder-workspaces.md b/docs/internal/coder-workspaces.md
index 3b6b130f8c8e..29e60e727f61 100644
--- a/docs/internal/coder-workspaces.md
+++ b/docs/internal/coder-workspaces.md
@@ -32,6 +32,12 @@ 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.
+Deleting a devbox with `hogli devbox:destroy` or a worktree cleanup command also removes its Herdr machine.
+
+Herdr users pick one of two ways to work:
+
+- **Agents on the devbox.** Run `hogli devbox:open --herdr` and create worktrees from that space. They live on the devbox, and nothing syncs. The worktrees share one devbox, so only one of them runs the dev stack at a time.
+- **Agents on your laptop.** Run `hogli devbox:worktree --auto herdr`. Each worktree that Herdr creates on your laptop gets its own devbox, with its own dev stack. The mirror copies your edits to the box, so edit locally. `hogli devbox:open --herdr <label>` opens a space on a worktree's box to run the stack and tests there.
**Running the dev stack in detached mode** —
Start the PostHog dev stack in the background without an interactive terminal:
@@ -68,7 +74,7 @@ hogli devbox:sync --status # check sync state
hogli devbox:sync --terminate # tear down when done
```
-`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.
+`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. For a worktree's devbox, the warning names the worktree to edit instead.
**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.
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index c1ad5981afcb..3fa92137d9cf 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -106,6 +106,7 @@ from .config import (
clear_worktree_box_cleanup,
clear_worktree_provider,
load_config,
+ load_worktree_boxes,
save_dotfiles_uri,
save_git_identity,
save_region,
@@ -1807,6 +1808,16 @@ def devbox_remote_exec(workspace_name: str | None, command: tuple[str, ...]) ->
exec_replace(name, list(command))
+def _sync_warning(name: str, editor: str) -> str:
+ worktree = next((path for path, record in load_worktree_boxes().items() if record.workspace == name), None)
+ if worktree is None:
+ return f"⚠ Sync is active for '{name}'. Editing in {editor} can conflict with the local source of truth."
+ return (
+ f"⚠ '{name}' mirrors the worktree at {worktree}. Edit files in that worktree, "
+ f"and use {editor} to run the stack and tests. Files edited on the devbox conflict with the mirror."
+ )
+
+
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)
@@ -1840,12 +1851,7 @@ def devbox_open(workspace: str | None, vscode: bool, cursor: bool, web: bool, he
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 {editor} can conflict with the local source of truth.",
- fg="yellow",
- )
- )
+ click.echo(click.style(_sync_warning(name, editor), fg="yellow"))
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)
@@ -2023,6 +2029,7 @@ def devbox_destroy(workspace: str | None, verbose: bool) -> None:
click.echo(click.style("Warning: failed to terminate sync session; continuing.", fg="yellow"))
delete_workspace(name, verbose=verbose)
+ herdr_app.forget_machine(name)
click.echo("Destroyed.")
diff --git a/tools/hogli-commands/hogli_commands/devbox/herdr.py b/tools/hogli-commands/hogli_commands/devbox/herdr.py
index 27b2da2dba9b..2c5339e4e383 100644
--- a/tools/hogli-commands/hogli_commands/devbox/herdr.py
+++ b/tools/hogli-commands/hogli_commands/devbox/herdr.py
@@ -1,9 +1,12 @@
-"""Open a devbox in Herdr as a remote machine with its own space.
+"""Herdr support for devboxes: a devbox as a Herdr machine, and the plugin for herdr's worktrees.
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.
+
+The plugin in `tools/herdr-devbox-plugin` gives each worktree that herdr
+creates on this machine its own devbox, through `devbox:worktree`.
"""
from __future__ import annotations
@@ -12,6 +15,7 @@ import json
import time
import shutil
import subprocess
+from pathlib import Path
from typing import Any
import click
@@ -24,6 +28,8 @@ _MACHINE_CONNECT_TIMEOUT = 60.0
_WINDOW_START_TIMEOUT = 20.0
_WINDOW_SEES_MACHINE_TIMEOUT = 15.0
_POLL_INTERVAL = 0.5
+PLUGIN_ID = "posthog.devbox"
+PLUGIN_DIR = Path("tools") / "herdr-devbox-plugin"
def _require_cli(name: str) -> None:
@@ -43,6 +49,9 @@ def _run(args: list[str], *, timeout: float = 30.0) -> subprocess.CompletedProce
# 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.")
+ except OSError as error:
+ # `hc` can be on PATH and still fail to start, such as a script whose interpreter is gone.
+ return subprocess.CompletedProcess(args, 126, "", f"`{args[0]}` couldn't start: {error}")
def _run_json(args: list[str], *, failure: str, cause: str) -> dict[str, Any]:
@@ -63,8 +72,15 @@ def _output_of(result: subprocess.CompletedProcess[str]) -> str:
return (result.stderr or result.stdout or "").strip()
+def _ssh_targets(workspace_name: str) -> frozenset[str]:
+ # `coder config-ssh` writes a `coder.<name>` alias and a `<name>.coder` host suffix,
+ # and a machine someone added in Herdr by hand can use either one.
+ return frozenset({_ssh_host_alias(workspace_name), f"{workspace_name}.coder"})
+
+
def ensure_machine(workspace_name: str) -> str:
"""Return the `hc` machine name for the devbox, adding the machine when it's missing."""
+ targets = _ssh_targets(workspace_name)
target = _ssh_host_alias(workspace_name)
listing = _run_json(
["hc", "machine", "ls", "--json"],
@@ -72,7 +88,7 @@ def ensure_machine(workspace_name: str) -> str:
cause="herdr_machine_list_failed",
)
for machine in listing.get("machines", []):
- if machine.get("target") == target and machine.get("name"):
+ if machine.get("target") in targets and machine.get("name"):
_wait_until_connected(machine["name"])
return machine["name"]
@@ -90,17 +106,47 @@ def ensure_machine(workspace_name: str) -> str:
return workspace_name
-def _machine_state(name: str) -> str | None:
+def _list_machines() -> list[dict[str, Any]] | None:
result = _run(["hc", "machine", "ls", "--json"])
if result.returncode != 0:
return None
try:
machines = json.loads(result.stdout).get("machines", [])
- except json.JSONDecodeError:
+ except (json.JSONDecodeError, AttributeError):
return None
+ return [machine for machine in machines if isinstance(machine, dict)] if isinstance(machines, list) else None
+
+
+def _machine_state(name: str) -> str | None:
+ machines = _list_machines() or []
return next((m.get("state") for m in machines if m.get("name") == name), None)
+def forget_machine(workspace_name: str) -> None:
+ """Remove the `hc` machine of a devbox that was just deleted, so Herdr stops trying to reach it.
+
+ It never fails, because it runs after the devbox is already gone.
+ """
+ if shutil.which("hc") is None:
+ return
+ targets = _ssh_targets(workspace_name)
+ machines = _list_machines()
+ if machines is None:
+ click.echo(
+ f" ⚠️ could not list Herdr machines to remove '{workspace_name}'. "
+ "Check `hc machine ls` and remove its machine with `hc machine rm <name>`."
+ )
+ return
+ for machine in machines:
+ name = machine.get("name")
+ if machine.get("target") not in targets or not name:
+ continue
+ if _run(["hc", "machine", "rm", name]).returncode == 0:
+ click.echo(f"Removed '{name}' from Herdr.")
+ else:
+ click.echo(f" ⚠️ could not remove '{name}' from Herdr. Run `hc machine rm {name}`.")
+
+
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
@@ -182,3 +228,52 @@ def open_in_herdr(workspace_name: str, *, folder: str) -> None:
click.echo(f"Opened a Herdr space on '{workspace_name}' in {folder}.")
else:
click.echo(f"Showing the Herdr space for '{workspace_name}'.")
+
+
+def _find_plugin(listing: Any) -> dict[str, Any] | None:
+ if isinstance(listing, dict):
+ if listing.get("plugin_id") == PLUGIN_ID:
+ return listing
+ children: list[Any] = list(listing.values())
+ elif isinstance(listing, list):
+ children = listing
+ else:
+ return None
+ for child in children:
+ found = _find_plugin(child)
+ if found is not None:
+ return found
+ return None
+
+
+def link_worktree_plugin(main_checkout: Path | None) -> None:
+ """Link the plugin from *main_checkout*, which outlives every worktree, unless herdr already has it."""
+ herdr = shutil.which("herdr")
+ if herdr is None:
+ click.echo(f"herdr isn't on your PATH. Once it is, run `herdr plugin link <main checkout>/{PLUGIN_DIR}`.")
+ return
+ try:
+ listing = subprocess.run([herdr, "plugin", "list", "--json"], capture_output=True, text=True, timeout=30)
+ existing = _find_plugin(json.loads(listing.stdout)) if listing.returncode == 0 else None
+ except (OSError, subprocess.SubprocessError, ValueError):
+ existing = None
+ if existing is not None:
+ state = "enabled" if existing.get("enabled") else "disabled"
+ click.echo(f"The herdr plugin {PLUGIN_ID} is already linked from {existing.get('plugin_root')} ({state}).")
+ return
+ if main_checkout is None:
+ click.echo(f"Couldn't find your main checkout. Run `herdr plugin link <main checkout>/{PLUGIN_DIR}`.")
+ return
+ plugin_dir = main_checkout / PLUGIN_DIR
+ if not (plugin_dir / "herdr-plugin.toml").is_file():
+ click.echo(f"Your main checkout has no {PLUGIN_DIR} yet. Pull it, then run this command again.")
+ return
+ try:
+ result = subprocess.run([herdr, "plugin", "link", str(plugin_dir)], capture_output=True, text=True, timeout=60)
+ except (OSError, subprocess.SubprocessError) as error:
+ click.echo(f"Couldn't link the herdr plugin: {error}")
+ return
+ if result.returncode != 0:
+ click.echo(f"Couldn't link the herdr plugin: {(result.stderr or result.stdout).strip()}")
+ return
+ click.echo(f"Linked the herdr plugin from {plugin_dir}. Turn it off with `herdr plugin disable {PLUGIN_ID}`.")
diff --git a/tools/hogli-commands/hogli_commands/devbox/worktree.py b/tools/hogli-commands/hogli_commands/devbox/worktree.py
index 9465207283aa..8fdc15afff45 100644
--- a/tools/hogli-commands/hogli_commands/devbox/worktree.py
+++ b/tools/hogli-commands/hogli_commands/devbox/worktree.py
@@ -5,8 +5,6 @@ from __future__ import annotations
import os
import re
import sys
-import json
-import shutil
import hashlib
import subprocess
import urllib.parse
@@ -24,7 +22,11 @@ from ..worktrees import (
teardown_worktree_box,
worktree_source,
)
-from . import hogland, mutagen
+from . import (
+ herdr as herdr_app,
+ hogland,
+ mutagen,
+)
from .cli import _preferred_region, devbox_clone, devbox_start, resolve_workspace_name
from .coder import (
REGION_NAME_SUFFIXES,
@@ -69,8 +71,6 @@ _AUTO_OFF = "off"
_AUTO_LOG_NAME = "hogli-devbox-worktree.log"
_AUTO_STARTED_NAME = "hogli-devbox-worktree.auto-started"
_TEARDOWN_LOG_NAME = "hogli-devbox-teardown.log"
-_HERDR_PLUGIN_ID = "posthog.devbox"
-_HERDR_PLUGIN_DIR = Path("tools") / "herdr-devbox-plugin"
_SUBAGENT_WORKTREE_PREFIX = "agent-"
_CONDUCTOR_LOCAL_SETTINGS = Path(".conductor") / "settings.local.toml"
_CONDUCTOR_SETUP_SCRIPT = "bin/devbox-worktree-hook created conductor"
@@ -182,22 +182,6 @@ def _install_conductor_scripts(root: Path) -> None:
click.echo(f"Added the devbox setup and archive scripts to {settings_path}.")
-def _find_herdr_plugin(listing: Any) -> dict[str, Any] | None:
- if isinstance(listing, dict):
- if listing.get("plugin_id") == _HERDR_PLUGIN_ID:
- return listing
- children: list[Any] = list(listing.values())
- elif isinstance(listing, list):
- children = listing
- else:
- return None
- for child in children:
- found = _find_herdr_plugin(child)
- if found is not None:
- return found
- return None
-
-
def _main_checkout(root: Path) -> Path:
result = subprocess.run(
["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
@@ -210,43 +194,11 @@ def _main_checkout(root: Path) -> Path:
def _link_herdr_plugin(root: Path) -> None:
- """Link the plugin from the main checkout, which outlives every worktree, unless herdr already has it."""
- herdr = shutil.which("herdr")
- if herdr is None:
- click.echo(
- f"herdr isn't on your PATH. Once it is, run `herdr plugin link <main checkout>/{_HERDR_PLUGIN_DIR}`."
- )
- return
- try:
- listing = subprocess.run([herdr, "plugin", "list", "--json"], capture_output=True, text=True, timeout=30)
- existing = _find_herdr_plugin(json.loads(listing.stdout)) if listing.returncode == 0 else None
- except (OSError, subprocess.SubprocessError, ValueError):
- existing = None
- if existing is not None:
- state = "enabled" if existing.get("enabled") else "disabled"
- click.echo(
- f"The herdr plugin {_HERDR_PLUGIN_ID} is already linked from {existing.get('plugin_root')} ({state})."
- )
- return
try:
- plugin_dir = _main_checkout(root) / _HERDR_PLUGIN_DIR
+ main_checkout: Path | None = _main_checkout(root)
except (OSError, subprocess.SubprocessError):
- click.echo(f"Couldn't find your main checkout. Run `herdr plugin link <main checkout>/{_HERDR_PLUGIN_DIR}`.")
- return
- if not (plugin_dir / "herdr-plugin.toml").is_file():
- click.echo(f"Your main checkout has no {_HERDR_PLUGIN_DIR} yet. Pull it, then run this command again.")
- return
- try:
- result = subprocess.run([herdr, "plugin", "link", str(plugin_dir)], capture_output=True, text=True, timeout=60)
- except (OSError, subprocess.SubprocessError) as error:
- click.echo(f"Couldn't link the herdr plugin: {error}")
- return
- if result.returncode != 0:
- click.echo(f"Couldn't link the herdr plugin: {(result.stderr or result.stdout).strip()}")
- return
- click.echo(
- f"Linked the herdr plugin from {plugin_dir}. Turn it off with `herdr plugin disable {_HERDR_PLUGIN_ID}`."
- )
+ main_checkout = None
+ herdr_app.link_worktree_plugin(main_checkout)
def _git_dir(root: Path) -> Path:
diff --git a/tools/hogli-commands/hogli_commands/tests/conftest.py b/tools/hogli-commands/hogli_commands/tests/conftest.py
index 1ec3e18cf184..5e23c9d500b6 100644
--- a/tools/hogli-commands/hogli_commands/tests/conftest.py
+++ b/tools/hogli-commands/hogli_commands/tests/conftest.py
@@ -4,12 +4,22 @@ These tests do not require Django. Run from the repo root with:
pytest tools/hogli-commands/hogli_commands/tests/ -p no:django -o 'addopts=' -o 'DJANGO_SETTINGS_MODULE='
"""
+from __future__ import annotations
+
import subprocess
from collections.abc import Callable
from pathlib import Path
import pytest
+from hogli_commands.devbox import herdr as devbox_herdr
+
+
[email protected](autouse=True)
+def _no_real_herdr_machine_removal(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Deleting a devbox calls `hc`, which is on the PATH of any developer who uses Herdr.
+ monkeypatch.setattr(devbox_herdr, "forget_machine", lambda workspace_name: None)
+
@pytest.fixture
def git() -> Callable[..., str]:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index a7ed5e549517..63ab638d0d0a 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -29,6 +29,8 @@ from hogli_commands.devbox import (
worktree as devbox_worktree,
)
+# Captured at import, before the autouse fixture in conftest.py replaces it.
+_REAL_FORGET_HERDR_MACHINE = devbox_herdr.forget_machine
runner = CliRunner()
@@ -1054,7 +1056,7 @@ class TestWorktreeAutoProvision:
monkeypatch.setattr(devbox_config, "get_config_path", lambda: tmp_path / "config.json")
monkeypatch.setattr(devbox_worktree, "_detect_local_posthog_checkout", lambda: tmp_path / "wt")
monkeypatch.setattr(
- devbox_worktree.shutil, "which", lambda name: "/bin/herdr" if herdr_installed and name == "herdr" else None
+ devbox_herdr.shutil, "which", lambda name: "/bin/herdr" if herdr_installed and name == "herdr" else None
)
herdr_calls: list[list[str]] = []
@@ -2926,12 +2928,15 @@ class TestDevboxOpenHerdr:
"folder": "/home/coder/posthog",
}
+ @pytest.mark.parametrize(
+ "target", ["coder.devbox-test-user", "devbox-test-user.coder"], ids=["alias-prefix", "hostname-suffix"]
+ )
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]
+ self, herdr_calls: Callable[..., list[list[str]]], running_workspace: Callable[[str], None], target: str
) -> None:
running_workspace("running")
calls = herdr_calls(
- machines=[{"name": "box", "target": "coder.devbox-test-user"}],
+ machines=[{"name": "box", "target": target}],
spaces=[{"id": "box/sp1", "machine": "box"}, {"id": "sp2", "machine": None}],
connecting_polls=2,
)
@@ -2955,6 +2960,83 @@ class TestDevboxOpenHerdr:
assert "Devbox 'devbox-test-user' is stopped. Start it with `hogli devbox:start`" in result.output
assert calls == []
+ @pytest.mark.parametrize(
+ ("registered_worktree", "expected_warning"),
+ [
+ (None, "Sync is active for 'devbox-test-user'"),
+ ("/work/posthog-feature", "'devbox-test-user' mirrors the worktree at /work/posthog-feature"),
+ ],
+ ids=["standalone-box", "worktree-box"],
+ )
+ def test_sync_warning_points_a_worktree_box_at_its_worktree(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ herdr_calls: Callable[..., list[list[str]]],
+ running_workspace: Callable[[str], None],
+ registered_worktree: str | None,
+ expected_warning: str,
+ ) -> None:
+ running_workspace("running")
+ herdr_calls(machines=[], spaces=[])
+ monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda **kw: [{"name": "ph-x"}])
+ registry = (
+ {}
+ if registered_worktree is None
+ else {registered_worktree: devbox_config.WorktreeBoxRecord(workspace="devbox-test-user", git_dir="admin")}
+ )
+ monkeypatch.setattr(devbox_cli, "load_worktree_boxes", lambda: registry)
+
+ result = runner.invoke(cli, ["devbox:open", "--herdr"])
+
+ assert result.exit_code == 0, result.output
+ assert expected_warning in result.output
+
+ def test_forgetting_a_deleted_box_removes_only_its_own_machine(
+ self, herdr_calls: Callable[..., list[list[str]]]
+ ) -> None:
+ calls = herdr_calls(
+ machines=[
+ {"name": "renamed-by-user", "target": "coder.devbox-test-user"},
+ {"name": "added-by-hand", "target": "devbox-test-user.coder"},
+ {"name": "devbox-test-user-other", "target": "coder.devbox-test-user-other"},
+ ],
+ spaces=[],
+ )
+
+ _REAL_FORGET_HERDR_MACHINE("devbox-test-user")
+
+ assert [call for call in calls if call[:3] == ["hc", "machine", "rm"]] == [
+ ["hc", "machine", "rm", "renamed-by-user"],
+ ["hc", "machine", "rm", "added-by-hand"],
+ ]
+
+ @pytest.mark.parametrize(
+ "failure",
+ [
+ subprocess.CompletedProcess(["hc"], 1, "", "daemon not running"),
+ subprocess.TimeoutExpired(["hc"], 30),
+ OSError("bad interpreter"),
+ ],
+ ids=["exits-nonzero", "times-out", "cannot-start"],
+ )
+ def test_forgetting_warns_when_herdr_machines_cannot_be_listed(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ failure: subprocess.CompletedProcess[str] | Exception,
+ ) -> None:
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ if isinstance(failure, Exception):
+ raise failure
+ return failure
+
+ monkeypatch.setattr(devbox_herdr.subprocess, "run", fake_run)
+ monkeypatch.setattr(devbox_herdr.shutil, "which", lambda name: f"/usr/local/bin/{name}")
+
+ _REAL_FORGET_HERDR_MACHINE("devbox-test-user")
+
+ assert "could not list Herdr machines to remove 'devbox-test-user'" in capsys.readouterr().out
+
def test_a_timed_out_hc_call_fails_with_a_message(
self, herdr_calls: Callable[..., list[list[str]]], running_workspace: Callable[[str], None]
) -> None:
@@ -5224,13 +5306,14 @@ class TestDevboxLifecycleSyncIntegration:
monkeypatch.setattr(devbox_cli.mutagen, "sync_list", lambda label_selector=None: [{"name": "ph-x"}])
monkeypatch.setattr(devbox_cli.mutagen, "sync_terminate", lambda sel: calls.append("terminate"))
monkeypatch.setattr(devbox_cli, "delete_workspace", lambda name, verbose=False: calls.append("delete"))
+ monkeypatch.setattr(devbox_cli.herdr_app, "forget_machine", lambda name: calls.append(f"forget-herdr:{name}"))
result = runner.invoke(cli, ["devbox:destroy"])
assert result.exit_code == 0, result.output
# terminate MUST run before delete: the remote endpoint disappearing
# mid-sync produces noisy daemon errors otherwise.
- assert calls == ["terminate", "delete"]
+ assert calls == ["terminate", "delete", "forget-herdr:devbox-test-user"]
def test_destroy_proceeds_when_no_sync_session(self, monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
diff --git a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
index f60f187abfc4..a2d183299965 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_worktrees.py
@@ -1073,6 +1073,8 @@ class TestWorktreeBoxes:
monkeypatch.setattr(worktrees, "delete_workspace", lambda name: calls.append(("delete", name)))
monkeypatch.setattr(worktrees, "stop_workspace", lambda name: calls.append(("stop", name)))
monkeypatch.setattr(worktrees.mutagen, "sync_terminate", terminated.append)
+ forgotten_in_herdr: list[str] = []
+ monkeypatch.setattr(worktrees.herdr, "forget_machine", forgotten_in_herdr.append)
box_a, box_b = _box("devbox-test-user-a", workspace_id="id-a"), _box("devbox-test-user-b")
devbox_config.record_worktree_box(tmp_path / "a", box_a)
devbox_config.record_worktree_box(tmp_path / "b", box_b)
@@ -1088,6 +1090,7 @@ class TestWorktreeBoxes:
)
assert calls == expected_calls
+ assert forgotten_in_herdr == [name for call, name in expected_calls if call == "delete"]
acted = live_id == box_a.workspace_id and (last_used_at is None or bool(expected_calls))
assert terminated == ([worktrees.mutagen.workspace_label_selector("devbox-test-user-a")] if acted else [])
kept = live_id == box_a.workspace_id and (not acted or (keep_stopped and action == "stop"))
diff --git a/tools/hogli-commands/hogli_commands/worktrees.py b/tools/hogli-commands/hogli_commands/worktrees.py
index 1efc81633918..cc16d0c85d0d 100644
--- a/tools/hogli-commands/hogli_commands/worktrees.py
+++ b/tools/hogli-commands/hogli_commands/worktrees.py
@@ -53,7 +53,7 @@ from .cargo_targets import (
unused_legacy_cargo_target,
worktrees_running_cargo,
)
-from .devbox import hogland, mutagen
+from .devbox import herdr, hogland, mutagen
from .devbox.coder import (
delete_workspace,
ensure_runtime_ready,
@@ -862,6 +862,7 @@ def _clean_coder_boxes(
if box_action == "delete":
click.echo(f"Deleting devbox {box.workspace}...")
delete_workspace(box.workspace)
+ herdr.forget_machine(box.workspace)
elif get_workspace_status(workspace) != "stopped":
click.echo(f"Stopping devbox {box.workspace}...")
stop_workspace(box.workspace)