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.

fix(devbox): keep mutagen sync alive across tailscale path resets (#61680)

Raúl Negrón-Otero5937e90b5008
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 35ffba38d501..c522500b7a1f 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -1094,7 +1094,11 @@ def devbox_setup(
return
mutagen.ensure_mutagen_installed(verbose=verbose)
- mutagen.register_daemon()
+ mutagen.ensure_daemon_with_shim()
+ click.echo(
+ " Note: the mutagen daemon is left unregistered from login auto-start so devbox "
+ "sync can apply its ssh keepalive fix; it starts on demand the next time you sync."
+ )
mutagen.ensure_user_mutagen_config()
maybe_configure_ssh(
configure_ssh=configure_ssh,
diff --git a/tools/hogli-commands/hogli_commands/devbox/mutagen.py b/tools/hogli-commands/hogli_commands/devbox/mutagen.py
index da6ff425d494..274e3e34ed09 100644
--- a/tools/hogli-commands/hogli_commands/devbox/mutagen.py
+++ b/tools/hogli-commands/hogli_commands/devbox/mutagen.py
@@ -7,6 +7,8 @@ wrappers. v1 only targets Coder workspaces as the remote endpoint.
from __future__ import annotations
+import os
+import re
import json
import shutil
import hashlib
@@ -21,6 +23,44 @@ from .coder import _fail
_MANAGED_MUTAGEN_DIR = Path.home() / ".hogli" / "bin"
_MUTAGEN_VERSION = "0.18.1"
+
+# mutagen hardcodes `-oServerAliveInterval=10 -oServerAliveCountMax=1` onto every
+# ssh command line it builds, and a command-line `-o` overrides ~/.ssh/config, so
+# the keepalive cannot be relaxed via config. One missed keepalive (interval x
+# count = 10s of silence) tears the connection down -- which is exactly what
+# happens when a devbox's Tailscale path flaps to a DERP relay (it resets the
+# direct path roughly every 26s) mid-sync, surfacing as a "broken pipe" at the
+# staging step and a sync that loops forever without ever reaching `watching`.
+# We can't change the constant, but we can interpose an ssh that rewrites it for
+# devbox connections: a shim on MUTAGEN_SSH_PATH bumps the count so the
+# connection rides out a reset window. _KEEPALIVE_COUNT x interval(10s) is the
+# resulting silence tolerance (~30s, comfortably past the ~26s reset cadence).
+_SSH_SHIM_DIR = Path.home() / ".hogli" / "mutagen-ssh-shim"
+_KEEPALIVE_COUNT = 3
+
+# Baked at generation time (see ensure_ssh_shim): only when the ssh/scp target is
+# a devbox (a `coder.*` host -- the sole thing hogli syncs to) do we bump
+# mutagen's count; every other invocation passes through untouched, so a shared
+# daemon's non-devbox syncs are unaffected. Execs the real ssh/scp by absolute
+# path so a shim-dir entry on PATH can never make the shim re-invoke itself.
+_SHIM_TEMPLATE = """#!/usr/bin/env bash
+# Managed by hogli (`hogli devbox:sync`) -- do not edit; regenerated on sync.
+# Raises mutagen's intolerant `-oServerAliveCountMax=1` for devbox (coder.*)
+# connections so the sync survives a Tailscale/DERP path reset instead of dying
+# with a broken pipe. Any non-devbox ssh is passed through unchanged.
+devbox=
+for a in "$@"; do
+ case "$a" in coder.*|*@coder.*) devbox=1 ;; esac
+done
+args=()
+for a in "$@"; do
+ case "$a" in
+ -oServerAliveCountMax=*) [ -n "$devbox" ] && a="-oServerAliveCountMax={count}" ;;
+ esac
+ args+=("$a")
+done
+exec "{real}" ${{args[@]+"${{args[@]}}"}}
+"""
_RELEASE_URL_TEMPLATE = (
"https://github.com/mutagen-io/mutagen/releases/download/v{version}/mutagen_{os}_{arch}_v{version}.tar.gz"
)
@@ -72,6 +112,17 @@ def _mutagen_bin() -> str:
return shutil.which("mutagen") or "mutagen"
+def _mutagen_env() -> dict[str, str]:
+ """Process env for mutagen calls, pinning ssh resolution to the keepalive shim.
+
+ Setting ``MUTAGEN_SSH_PATH`` here means any daemon mutagen *auto-starts* as a
+ child of this process inherits it (the only env channel that reaches the
+ daemon -- see ``ensure_daemon_with_shim``). Pointing at the dir is safe even
+ before the shim exists: mutagen just falls back to a PATH ssh.
+ """
+ return {**os.environ, "MUTAGEN_SSH_PATH": str(_SSH_SHIM_DIR)}
+
+
def _run(args: list[str], *, capture_output: bool = False) -> subprocess.CompletedProcess[str]:
"""Run a mutagen subprocess with consistent text handling.
@@ -81,7 +132,7 @@ def _run(args: list[str], *, capture_output: bool = False) -> subprocess.Complet
resolved = args
if args and args[0] == "mutagen":
resolved = [_mutagen_bin(), *args[1:]]
- return subprocess.run(resolved, capture_output=capture_output, text=True)
+ return subprocess.run(resolved, capture_output=capture_output, text=True, env=_mutagen_env())
def mutagen_installed() -> bool:
@@ -177,24 +228,140 @@ def ensure_mutagen_installed(*, verbose: bool = False) -> None:
click.echo("mutagen CLI is installed.")
-def register_daemon() -> None:
- """Install the mutagen daemon's autostart hook (LaunchAgent / systemd user unit).
+def _resolve_real_ssh(name: str) -> str:
+ """Absolute path to the real ssh/scp the shim should exec.
+
+ Searches standard locations first (robust against a hijacked ``PATH``), then
+ falls back to a ``PATH`` lookup with the shim dir removed so the shim can
+ never resolve to itself.
+ """
+ for candidate in (f"/usr/bin/{name}", f"/bin/{name}", f"/usr/local/bin/{name}"):
+ if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
+ return candidate
+ entries = [e for e in os.environ.get("PATH", "").split(os.pathsep) if e and Path(e) != _SSH_SHIM_DIR]
+ return shutil.which(name, path=os.pathsep.join(entries)) or name
+
+
+def _write_owner_only(target: Path, content: str) -> None:
+ """Atomically write ``content`` as an owner-only (0o700) executable.
+
+ Writes to a fresh temp opened with a restrictive mode (umask only clears
+ bits, and 0o700 has none in group/other, so it lands at 0o700) and renames
+ it into place, so the script is never briefly world-readable or half-written.
+ """
+ tmp = target.with_name(f".{target.name}.tmp")
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o700)
+ with os.fdopen(fd, "w") as f:
+ f.write(content)
+ os.replace(tmp, target)
+
+
+def ensure_ssh_shim() -> Path:
+ """Write the ssh/scp keepalive-rewriting shims, returning their directory.
+
+ Idempotent: each shim is rewritten only when its content (which embeds the
+ resolved real-binary path and keepalive count) changes. mutagen invokes both
+ ssh and scp, so both are shimmed; the rewrite is a no-op for any arg that
+ isn't ``-oServerAliveCountMax=``.
+ """
+ _SSH_SHIM_DIR.mkdir(parents=True, exist_ok=True)
+ # The daemon execs these scripts, so keep the dir and scripts owner-only: no
+ # other local account can tamper with what runs as us, and they need no wider
+ # access. The dir chmod also self-heals an older world-readable install.
+ _SSH_SHIM_DIR.chmod(0o700)
+ for name in ("ssh", "scp"):
+ target = _SSH_SHIM_DIR / name
+ content = _SHIM_TEMPLATE.format(count=_KEEPALIVE_COUNT, real=_resolve_real_ssh(name))
+ if not target.exists() or target.read_text() != content:
+ _write_owner_only(target, content)
+ else:
+ target.chmod(0o700) # content already current; just heal perms
+ return _SSH_SHIM_DIR
+
+
+def _daemon_pids() -> list[int]:
+ """PIDs of running mutagen daemon processes (best-effort, cross-platform)."""
+ try:
+ # POSIX `-A -o` (not BSD `-axo`) so this parses on both macOS and Linux.
+ result = subprocess.run(["ps", "-A", "-o", "pid=,args="], capture_output=True, text=True)
+ except (OSError, subprocess.SubprocessError):
+ return []
+ pids: list[int] = []
+ for line in result.stdout.splitlines():
+ pid_str, _, args = line.strip().partition(" ")
+ # `daemon run` is the daemon's own subcommand -- specific enough to skip
+ # transient `ps`/`grep` lines that merely mention "mutagen daemon".
+ if "mutagen" in args and "daemon run" in args and pid_str.isdigit():
+ pids.append(int(pid_str))
+ return pids
+
+
+def _daemon_ssh_path(pid: int) -> str | None:
+ """The ``MUTAGEN_SSH_PATH`` a process was started with, or ``None`` (best-effort).
+
+ The value can legitimately contain spaces (a home dir like ``/Users/John
+ Doe``), so both branches preserve them: Linux reads ``/proc/<pid>/environ``,
+ which is NUL-delimited; macOS/BSD parse ``ps eww``, whose env is
+ space-delimited with no per-entry boundary, so we capture from our key up to
+ the next ``KEY=`` (or line end) rather than splitting on whitespace.
+ """
+ if platform.system() == "Linux":
+ try:
+ raw = Path(f"/proc/{pid}/environ").read_bytes()
+ except OSError:
+ return None
+ for entry in raw.split(b"\0"):
+ key, sep, value = entry.partition(b"=")
+ if sep and key == b"MUTAGEN_SSH_PATH":
+ return value.decode(errors="replace")
+ return None
+ try:
+ result = subprocess.run(["ps", "eww", "-o", "command=", "-p", str(pid)], capture_output=True, text=True)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ match = re.search(r"(?:^|\s)MUTAGEN_SSH_PATH=(.*?)(?=\s\S+=|$)", result.stdout)
+ return match.group(1) if match else None
+
- Idempotent on mutagen's side -- re-running just re-applies the same hook.
- Best-effort: any failure is logged as a warning, not fatal, because the
- daemon will still start on demand the first time a sync command runs;
- autostart just means it survives reboots without intervention.
+def _daemon_uses_shim(shim_dir: Path) -> bool:
+ """Whether a running daemon already routes ssh through our shim."""
+ target = str(shim_dir)
+ return any(_daemon_ssh_path(pid) == target for pid in _daemon_pids())
+
+
+def ensure_daemon_with_shim() -> None:
+ """Ensure the mutagen daemon spawns ssh through the keepalive shim.
+
+ The daemon -- not the create call -- spawns ssh, so the shim only takes
+ effect if the daemon's own env carries ``MUTAGEN_SSH_PATH``. A
+ launchd/systemd-*registered* daemon has its env owned by the service manager
+ (the invoking shell's env never reaches it), so we deliberately do not
+ register; instead we let mutagen auto-start the daemon as a child of a hogli
+ subprocess, which inherits ``_mutagen_env``. If a stale or service-managed
+ daemon is already running without the shim, reset it: stop (sessions are
+ persisted and resume on the next start), unregister any autostart hook so the
+ restart forks a child, then start a fresh daemon carrying the env.
+
+ The trade-off versus the old ``mutagen daemon register`` is losing
+ autostart-on-reboot; mutagen still starts the daemon on demand on the next
+ sync command, so an existing session simply resumes when the user next runs
+ ``hogli devbox:sync``.
"""
- result = _run(["mutagen", "daemon", "register"], capture_output=True)
+ shim_dir = ensure_ssh_shim()
+ if _daemon_uses_shim(shim_dir):
+ return
+ _run(["mutagen", "daemon", "stop"], capture_output=True)
+ _run(["mutagen", "daemon", "unregister"], capture_output=True)
+ result = _run(["mutagen", "daemon", "start"], capture_output=True)
if result.returncode != 0:
- stderr = (result.stderr or "").strip()
click.echo(
click.style(
- "Warning: `mutagen daemon register` failed; sync will still work "
- "but the daemon won't auto-restart after reboot.",
+ "Warning: could not start the mutagen daemon with the keepalive shim; "
+ "sync may not survive network blips. A sync command will retry the start.",
fg="yellow",
)
)
+ stderr = (result.stderr or "").strip()
if stderr:
click.echo(f" {stderr}", err=True)
diff --git a/tools/hogli-commands/hogli_commands/devbox/sync.py b/tools/hogli-commands/hogli_commands/devbox/sync.py
index 6d10b992fb13..6f99f70e6c46 100644
--- a/tools/hogli-commands/hogli_commands/devbox/sync.py
+++ b/tools/hogli-commands/hogli_commands/devbox/sync.py
@@ -194,7 +194,7 @@ def cmd_sync(
# restarts; a re-run then short-circuits before the heavier coder/SSH
# preflight below. (ensure_runtime_ready covers the coder install check.)
mutagen.ensure_mutagen_installed(verbose=verbose)
- mutagen.register_daemon()
+ mutagen.ensure_daemon_with_shim()
if mutagen.sync_list(label_selector=label):
click.echo(
f"Sync already running for {name}. Use `hogli devbox:sync{_workspace_arg_suffix(name)} --status` to inspect."
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index fbe9b7b76e2b..2870473ef4e8 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import os
import csv
import json
import errno
@@ -3449,6 +3450,215 @@ class TestMutagenSyncWrappers:
devbox_mutagen.sync_pause("hogli-workspace=devbox-test-user")
+class TestKeepaliveShim:
+ """Test the ssh keepalive shim that keeps sync alive across DERP path resets.
+
+ mutagen hardcodes `-oServerAliveCountMax=1`; a single missed keepalive during
+ a Tailscale path reset kills the sync. The shim rewrites the count upward and
+ is wired into the daemon via MUTAGEN_SSH_PATH (see mutagen.py).
+ """
+
+ def test_run_injects_mutagen_ssh_path(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Any daemon mutagen auto-starts as a child of _run inherits this env --
+ # the only channel that reaches the ssh-spawning daemon.
+ captured: dict[str, object] = {}
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ captured["env"] = kwargs.get("env")
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(devbox_mutagen.subprocess, "run", fake_run)
+ monkeypatch.setattr(devbox_mutagen, "_mutagen_bin", lambda: "/x/mutagen")
+
+ devbox_mutagen._run(["mutagen", "version"])
+
+ env = captured["env"]
+ assert isinstance(env, dict)
+ assert env["MUTAGEN_SSH_PATH"] == str(devbox_mutagen._SSH_SHIM_DIR)
+
+ @pytest.mark.parametrize(
+ "target, bumped",
+ [("coder.devbox-test-user", True), ("[email protected]", False)],
+ ids=["devbox-host-bumped", "non-devbox-host-untouched"],
+ )
+ def test_shim_rewrites_keepalive_only_for_devbox_hosts(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, target: str, bumped: bool
+ ) -> None:
+ # End-to-end of the generated shim script: run it like mutagen would and
+ # assert it bumps the keepalive ONLY for a coder.* (devbox) target, while
+ # passing every other argument (and every non-devbox invocation) verbatim.
+ shim_dir = tmp_path / "shim"
+ log = tmp_path / "args.log"
+ fake = tmp_path / "fakessh"
+ fake.write_text("#!/usr/bin/env bash\nprintf '%s\\n' \"$@\" > '" + str(log) + "'\n")
+ fake.chmod(0o755)
+
+ monkeypatch.setattr(devbox_mutagen, "_SSH_SHIM_DIR", shim_dir)
+ monkeypatch.setattr(devbox_mutagen, "_resolve_real_ssh", lambda name: str(fake))
+ devbox_mutagen.ensure_ssh_shim()
+
+ incoming = [
+ "-oConnectTimeout=5",
+ "-oServerAliveInterval=10",
+ "-oServerAliveCountMax=1",
+ target,
+ ".mutagen/agents/0.18.1/mutagen-agent",
+ "synchronizer",
+ "--log-level=info",
+ ]
+ result = subprocess.run([str(shim_dir / "ssh"), *incoming], capture_output=True, text=True)
+ assert result.returncode == 0
+
+ forwarded = log.read_text().splitlines()
+ if bumped:
+ bump = f"-oServerAliveCountMax={devbox_mutagen._KEEPALIVE_COUNT}"
+ assert forwarded == [bump if a.startswith("-oServerAliveCountMax=") else a for a in incoming]
+ assert "-oServerAliveCountMax=1" not in forwarded
+ else:
+ # Non-devbox ssh must pass through byte-for-byte, keepalive included.
+ assert forwarded == incoming
+
+ def test_ensure_ssh_shim_writes_both_executables_and_is_idempotent(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ shim_dir = tmp_path / "shim"
+ monkeypatch.setattr(devbox_mutagen, "_SSH_SHIM_DIR", shim_dir)
+ monkeypatch.setattr(devbox_mutagen, "_resolve_real_ssh", lambda name: f"/usr/bin/{name}")
+
+ devbox_mutagen.ensure_ssh_shim()
+ ssh, scp = shim_dir / "ssh", shim_dir / "scp"
+ assert ssh.exists() and scp.exists()
+ # Owner-only: the daemon execs these, so no group/other access (0o700).
+ assert ssh.stat().st_mode & 0o777 == 0o700
+ assert scp.stat().st_mode & 0o777 == 0o700
+ assert shim_dir.stat().st_mode & 0o077 == 0 # dir not group/other accessible
+ assert f"-oServerAliveCountMax={devbox_mutagen._KEEPALIVE_COUNT}" in ssh.read_text()
+ assert 'exec "/usr/bin/scp"' in scp.read_text()
+
+ # Unchanged content must not rewrite the file (cheap, mtime-stable re-run).
+ before = ssh.stat().st_mtime_ns
+ devbox_mutagen.ensure_ssh_shim()
+ assert ssh.stat().st_mtime_ns == before
+
+ def test_write_owner_only_creates_0700_regardless_of_umask(self, tmp_path: Path) -> None:
+ # The shim must be owner-only from creation, not via a post-write chmod
+ # (which leaves a brief world-readable window). A permissive umask that
+ # would make a plain write 0o666 must still yield 0o700.
+ target = tmp_path / "ssh"
+ old_umask = os.umask(0)
+ try:
+ devbox_mutagen._write_owner_only(target, "#!/bin/sh\n")
+ finally:
+ os.umask(old_umask)
+ assert target.read_text() == "#!/bin/sh\n"
+ assert target.stat().st_mode & 0o777 == 0o700
+ assert not list(tmp_path.glob(".*.tmp")) # temp renamed away, no leftover
+
+ def test_resolve_real_ssh_never_returns_the_shim_dir(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # A shim-dir ssh on PATH must never be picked, or the shim re-invokes
+ # itself forever. Force the PATH fallback by hiding standard locations.
+ shim_dir = tmp_path / "shim"
+ shim_dir.mkdir()
+ (shim_dir / "ssh").write_text("#!/bin/sh\n")
+ monkeypatch.setattr(devbox_mutagen, "_SSH_SHIM_DIR", shim_dir)
+ monkeypatch.setattr(devbox_mutagen.os.path, "isfile", lambda p: False)
+ monkeypatch.setenv("PATH", str(shim_dir))
+
+ # Only the shim dir is on PATH and it's excluded, so nothing resolves and
+ # we fall back to the bare name -- crucially, never the shim's own ssh.
+ assert devbox_mutagen._resolve_real_ssh("ssh") == "ssh"
+
+ def test_daemon_uses_shim_matches_on_env(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(devbox_mutagen, "_daemon_pids", lambda: [111, 222])
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_daemon_ssh_path",
+ lambda pid: str(tmp_path) if pid == 222 else None,
+ )
+ assert devbox_mutagen._daemon_uses_shim(tmp_path) is True
+
+ monkeypatch.setattr(devbox_mutagen, "_daemon_ssh_path", lambda pid: "/other")
+ assert devbox_mutagen._daemon_uses_shim(tmp_path) is False
+
+ @pytest.mark.parametrize(
+ "ps_output, expected",
+ [
+ # `ps eww` env is space-delimited; a value with a space must not be
+ # truncated, whether it's followed by another entry or ends the line.
+ (
+ "/Users/John Doe/.hogli/bin/mutagen daemon run "
+ "XPC_SERVICE_NAME=0 MUTAGEN_SSH_PATH=/Users/John Doe/.hogli/mutagen-ssh-shim FOO=bar\n",
+ "/Users/John Doe/.hogli/mutagen-ssh-shim",
+ ),
+ (
+ "/x/mutagen daemon run MUTAGEN_SSH_PATH=/Users/John Doe/.hogli/mutagen-ssh-shim\n",
+ "/Users/John Doe/.hogli/mutagen-ssh-shim",
+ ),
+ (
+ "/x/mutagen daemon run MUTAGEN_SSH_PATH=/home/u/.hogli/mutagen-ssh-shim X=1\n",
+ "/home/u/.hogli/mutagen-ssh-shim",
+ ),
+ ("/x/mutagen daemon run XPC_SERVICE_NAME=0\n", None),
+ ],
+ ids=["spaced-mid", "spaced-last", "plain", "absent"],
+ )
+ def test_daemon_ssh_path_parses_ps_env_with_spaces(
+ self, monkeypatch: pytest.MonkeyPatch, ps_output: str, expected: str | None
+ ) -> None:
+ monkeypatch.setattr(devbox_mutagen.platform, "system", lambda: "Darwin")
+ monkeypatch.setattr(
+ devbox_mutagen.subprocess,
+ "run",
+ lambda *a, **k: subprocess.CompletedProcess(a, 0, ps_output, ""),
+ )
+ assert devbox_mutagen._daemon_ssh_path(123) == expected
+
+ def test_ensure_daemon_fast_path_does_not_touch_daemon(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ monkeypatch.setattr(devbox_mutagen, "ensure_ssh_shim", lambda: tmp_path)
+ monkeypatch.setattr(devbox_mutagen, "_daemon_uses_shim", lambda d: True)
+
+ def fail_run(*a: object, **k: object) -> subprocess.CompletedProcess[str]:
+ raise AssertionError("daemon must not be reset when the shim is already active")
+
+ monkeypatch.setattr(devbox_mutagen, "_run", fail_run)
+ devbox_mutagen.ensure_daemon_with_shim() # no exception, no daemon churn
+
+ def test_ensure_daemon_resets_when_shim_inactive(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # A registered/launchd daemon's env can't carry the shim, so it must be
+ # stopped, unregistered (so the restart forks an env-inheriting child),
+ # then started fresh -- in that order.
+ monkeypatch.setattr(devbox_mutagen, "ensure_ssh_shim", lambda: tmp_path)
+ monkeypatch.setattr(devbox_mutagen, "_daemon_uses_shim", lambda d: False)
+ calls: list[list[str]] = []
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_run",
+ lambda args, **k: calls.append(args[1:]) or subprocess.CompletedProcess(args, 0, "", ""),
+ )
+
+ devbox_mutagen.ensure_daemon_with_shim()
+
+ assert calls == [["daemon", "stop"], ["daemon", "unregister"], ["daemon", "start"]]
+
+ def test_ensure_daemon_warns_when_start_fails(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str]
+ ) -> None:
+ monkeypatch.setattr(devbox_mutagen, "ensure_ssh_shim", lambda: tmp_path)
+ monkeypatch.setattr(devbox_mutagen, "_daemon_uses_shim", lambda d: False)
+ monkeypatch.setattr(
+ devbox_mutagen,
+ "_run",
+ lambda args, **k: subprocess.CompletedProcess(args, 1, "", "boom"),
+ )
+
+ devbox_mutagen.ensure_daemon_with_shim()
+
+ out = capsys.readouterr().out
+ assert "keepalive shim" in out
+
+
class TestConflictCount:
"""Test that conflict counts include mutagen's truncated remainder."""
@@ -3625,7 +3835,7 @@ class TestDevboxSyncCommand:
monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
monkeypatch.setattr(devbox_sync, "ensure_runtime_ready", lambda: None)
monkeypatch.setattr(devbox_sync.mutagen, "ensure_mutagen_installed", lambda **kw: None)
- monkeypatch.setattr(devbox_sync.mutagen, "register_daemon", lambda: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_daemon_with_shim", lambda: None)
monkeypatch.setattr(devbox_sync, "_ensure_ssh_config_for_workspace", lambda ws: None)
monkeypatch.setattr(devbox_sync.mutagen, "ensure_user_mutagen_config", lambda: Path("/tmp/mutagen.yml"))
monkeypatch.setattr(
@@ -3651,7 +3861,7 @@ class TestDevboxSyncCommand:
monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
monkeypatch.setattr(devbox_sync, "ensure_runtime_ready", lambda: None)
monkeypatch.setattr(devbox_sync.mutagen, "ensure_mutagen_installed", lambda **kw: None)
- monkeypatch.setattr(devbox_sync.mutagen, "register_daemon", lambda: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_daemon_with_shim", lambda: None)
monkeypatch.setattr(devbox_sync, "_ensure_ssh_config_for_workspace", lambda ws: None)
config_path = tmp_path / "mutagen.yml"
config_path.write_text("sync: {}\n")
@@ -3685,7 +3895,7 @@ class TestDevboxSyncCommand:
lambda ws: ("devbox-test-user", [{"name": "devbox-test-user"}]),
)
monkeypatch.setattr(devbox_sync.mutagen, "ensure_mutagen_installed", lambda **kw: None)
- monkeypatch.setattr(devbox_sync.mutagen, "register_daemon", lambda: None)
+ monkeypatch.setattr(devbox_sync.mutagen, "ensure_daemon_with_shim", lambda: None)
monkeypatch.setattr(devbox_sync.mutagen, "sync_list", lambda label_selector=None: [])
monkeypatch.setattr(devbox_sync, "ensure_runtime_ready", lambda: None)
monkeypatch.setattr(devbox_sync, "get_workspace", lambda name, workspaces: {"name": name})