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(hogli): add devbox:setup --reset-* + Y/n gate (#59294)

Raúl Negrón-Otero49d016db1893
diff --git a/hogli.yaml b/hogli.yaml
index 758d898132e9..d0e47936cf4b 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -191,6 +191,12 @@ devbox:
devbox:secret:rm:
click: hogli_commands.devbox.cli:devbox_secret_rm
description: Delete a Coder user secret
+ devbox:config:show:
+ click: hogli_commands.devbox.cli:devbox_config_show
+ description: Show saved devbox setup configuration
+ devbox:config:rm:
+ click: hogli_commands.devbox.cli:devbox_config_rm
+ description: Clear saved devbox configuration items
devenv:
dev:setup:
click: hogli_commands.devenv.cli:dev_setup
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index e40e4a871b65..4bdbc4c9d643 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -14,6 +14,7 @@ import functools
import subprocess
import urllib.parse
from collections.abc import Callable
+from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -74,7 +75,14 @@ from .coder import (
upsert_user_secret,
user_secret_exists,
)
-from .config import load_config, save_dotfiles_uri, save_git_identity
+from .config import (
+ DevboxConfig,
+ clear_dotfiles_uri,
+ clear_git_identity,
+ load_config,
+ save_dotfiles_uri,
+ save_git_identity,
+)
_LEGACY_KEYCHAIN_SERVICE = "posthog-claude-oauth-token"
_POSTHOG_COMMIT_SIGNING_HANDBOOK_URL = "https://posthog.com/handbook/engineering/security#commit-signing"
@@ -315,17 +323,11 @@ def maybe_configure_git_identity(configure_git_identity: bool | None) -> None:
existing_git_email = config.get("git_email")
if configure_git_identity is False:
- if existing_git_name and existing_git_email:
- click.echo(f"Using saved Git identity: {existing_git_name} <{existing_git_email}>")
- click.echo("Run `hogli devbox:setup --configure-git-identity` to change.")
- else:
+ if not (existing_git_name and existing_git_email):
click.echo("Skipping Git identity setup.")
return
- # Already saved -- skip unless explicitly asked to reconfigure
if configure_git_identity is None and existing_git_name and existing_git_email:
- click.echo(f"Using saved Git identity: {existing_git_name} <{existing_git_email}>")
- click.echo("Run `hogli devbox:setup --configure-git-identity` to change.")
return
# Show prompts with best available defaults (saved > coder profile > empty)
@@ -415,7 +417,9 @@ def _resolve_local_identity_agent(host: str) -> str | None:
return None
-def maybe_configure_git_signing(configure_git_signing: bool | None) -> None:
+def maybe_configure_git_signing(
+ configure_git_signing: bool | None, *, known_secret_names: set[str] | None = None
+) -> None:
"""Propagate the engineer's existing local commit-signing config into devboxes.
Reads ``git config user.signingkey`` (the public key the engineer already
@@ -426,19 +430,18 @@ def maybe_configure_git_signing(configure_git_signing: bool | None) -> None:
probing -- whatever the engineer has set up locally per the handbook is
what propagates.
"""
- already_set = user_secret_exists(GIT_SIGNING_KEY_SECRET)
+ already_set = (
+ GIT_SIGNING_KEY_SECRET in known_secret_names
+ if known_secret_names is not None
+ else user_secret_exists(GIT_SIGNING_KEY_SECRET)
+ )
if configure_git_signing is False:
- if already_set:
- click.echo("Using saved Git signing key.")
- click.echo("Run `hogli devbox:setup --configure-git-signing` to change.")
- else:
+ if not already_set:
click.echo("Skipping Git commit signing setup.")
return
if configure_git_signing is None and already_set:
- click.echo("Git signing: configured (commits inside devbox will be signed).")
- click.echo("Run `hogli devbox:setup --configure-git-signing` to change.")
return
public_key = _resolve_local_signing_key()
@@ -482,16 +485,11 @@ def maybe_configure_dotfiles(configure_dotfiles: bool | None) -> None:
existing_uri = config.get("dotfiles_uri")
if configure_dotfiles is False:
- if existing_uri:
- click.echo(f"Using saved dotfiles: {existing_uri}")
- click.echo("Run `hogli devbox:setup --configure-dotfiles` to change.")
- else:
+ if not existing_uri:
click.echo("Skipping dotfiles setup.")
return
if configure_dotfiles is None and existing_uri:
- click.echo(f"Using saved dotfiles: {existing_uri}")
- click.echo("Run `hogli devbox:setup --configure-dotfiles` to change.")
return
click.echo()
@@ -499,6 +497,9 @@ def maybe_configure_dotfiles(configure_dotfiles: bool | None) -> None:
click.echo(" Personalize your workspace with a dotfiles repository.")
click.echo(" The repo will be cloned and applied on every workspace start.")
click.echo(" This will be saved and reused for future workspaces.")
+ if existing_uri:
+ click.echo(" Press Enter to keep the current URL, or type a new one.")
+ click.echo(" To remove dotfiles entirely, run `hogli devbox:config:rm dotfiles`.")
click.echo()
dotfiles_uri = click.prompt(
@@ -531,7 +532,7 @@ def devbox_help() -> None:
click.echo("Run `hogli <command> --help` for command-specific options.")
-def maybe_configure_claude_secret(configure_claude: bool | None) -> None:
+def maybe_configure_claude_secret(configure_claude: bool | None, *, known_secret_names: set[str] | None = None) -> None:
"""Manage the ``CLAUDE_CODE_OAUTH_TOKEN`` Coder user secret for this user.
Resolution order:
@@ -549,11 +550,11 @@ def maybe_configure_claude_secret(configure_claude: bool | None) -> None:
click.echo("Skipping Claude token setup.")
return
- secret_exists = has_claude_oauth_secret()
+ secret_exists = (
+ CLAUDE_CODE_OAUTH_ENV in known_secret_names if known_secret_names is not None else has_claude_oauth_secret()
+ )
if secret_exists and configure_claude is not True:
- click.echo(f"Claude token already set as a Coder user secret ({CLAUDE_CODE_OAUTH_ENV}).")
- click.echo("Run `hogli devbox:setup --configure-claude` to replace it.")
return
legacy_token = _read_legacy_keychain_token()
@@ -598,6 +599,183 @@ def maybe_configure_claude_secret(configure_claude: bool | None) -> None:
click.echo(f"Saved Claude token as Coder user secret '{CLAUDE_CODE_OAUTH_ENV}'.")
+def _reset_user_secret(secret_name: str) -> bool:
+ """Delete a Coder user secret. Returns True iff something was actually removed."""
+ if delete_user_secret(secret_name).returncode == 0:
+ click.echo(f"Deleted Coder user secret '{secret_name}'.")
+ return True
+ click.echo(f"Nothing to delete: '{secret_name}' was not set.")
+ return False
+
+
+def _reset_git_identity() -> bool:
+ """Drop the saved Git name/email. Returns True iff something was cleared."""
+ config = load_config()
+ if not (config.get("git_name") or config.get("git_email")):
+ click.echo("Nothing to clear: Git identity was not set.")
+ return False
+ clear_git_identity()
+ click.echo("Cleared saved Git identity. New workspaces will prompt for one.")
+ return True
+
+
+def _reset_dotfiles() -> bool:
+ """Drop the saved dotfiles URI and push an empty parameter to existing workspaces.
+
+ Clearing the local config alone only affects future workspaces -- existing
+ workspaces keep cloning the old URL until the template parameter is overridden.
+
+ Returns True iff something was cleared.
+ """
+ if not load_config().get("dotfiles_uri"):
+ click.echo("Nothing to clear: dotfiles was not set.")
+ return False
+ clear_dotfiles_uri()
+ click.echo("Cleared saved dotfiles repo. Pushing empty parameter to existing workspaces...")
+ for ws in list_user_workspaces():
+ ws_name = ws.get("name")
+ if isinstance(ws_name, str) and ws_name:
+ update_workspace_parameters(ws_name, {DOTFILES_URI_PARAMETER: ""})
+ click.echo(f" reset on '{ws_name}'")
+ return True
+
+
+def _git_identity_status(config: DevboxConfig, _: set[str]) -> str | None:
+ name = config.get("git_name")
+ email = config.get("git_email")
+ return f"{name} <{email}>" if name and email else None
+
+
+def _dotfiles_status(config: DevboxConfig, _: set[str]) -> str | None:
+ return config.get("dotfiles_uri")
+
+
+def _secret_status(secret_name: str) -> Callable[[DevboxConfig, set[str]], str | None]:
+ return lambda _config, secret_names: "configured" if secret_name in secret_names else None
+
+
+@dataclass(frozen=True)
+class _ConfigItem:
+ """One row in the devbox setup status / reset table.
+
+ Each item carries everything the status, show, and rm paths need:
+ the CLI key (``devbox:config:rm <key>``), the human label
+ (``devbox:config:show`` and the setup wizard's "Currently configured:"
+ block), how to derive the current value from local config plus the
+ set of Coder secret names, how to clear it, and whether clearing
+ touches Coder user secrets (so the server-version check fires only
+ when needed). New configurables land as one entry below.
+ """
+
+ cli_key: str
+ label: str
+ needs_secrets: bool
+ status: Callable[[DevboxConfig, set[str]], str | None]
+ reset: Callable[[], bool]
+
+
+_CONFIG_ITEMS: tuple[_ConfigItem, ...] = (
+ _ConfigItem(
+ cli_key="git-identity",
+ label="Git identity",
+ needs_secrets=False,
+ status=_git_identity_status,
+ reset=_reset_git_identity,
+ ),
+ _ConfigItem(
+ cli_key="git-signing",
+ label="Git signing",
+ needs_secrets=True,
+ status=_secret_status(GIT_SIGNING_KEY_SECRET),
+ reset=lambda: _reset_user_secret(GIT_SIGNING_KEY_SECRET),
+ ),
+ _ConfigItem(
+ cli_key="dotfiles",
+ label="Dotfiles",
+ needs_secrets=False,
+ status=_dotfiles_status,
+ reset=_reset_dotfiles,
+ ),
+ _ConfigItem(
+ cli_key="claude",
+ label="Claude token",
+ needs_secrets=True,
+ status=_secret_status(CLAUDE_CODE_OAUTH_ENV),
+ reset=lambda: _reset_user_secret(CLAUDE_CODE_OAUTH_ENV),
+ ),
+)
+
+
+def _config_items_by_key() -> dict[str, _ConfigItem]:
+ return {item.cli_key: item for item in _CONFIG_ITEMS}
+
+
+def _fetch_secret_names() -> set[str]:
+ """Bulk-fetch user-secret names in a single ``coder secret list`` round trip.
+
+ ``None`` (older servers without user-secret support) maps to an empty set,
+ matching the "no secrets" path. The result is safe to share across status
+ rows and configure helpers within one CLI invocation.
+ """
+ secrets = list_user_secrets() or []
+ return {name for s in secrets if isinstance(s, dict) and (name := s.get("name"))}
+
+
+def _collect_setup_status(secret_names: set[str] | None = None) -> list[tuple[str, str | None]]:
+ """Return one ``(label, value)`` tuple per configurable item.
+
+ Pass ``secret_names`` to reuse a pre-fetched set when the caller already
+ has one (the setup wizard does); otherwise we make our own ``coder secret
+ list`` call so single-shot uses like ``devbox:config:show`` stay self-contained.
+ """
+ config = load_config()
+ secrets = _fetch_secret_names() if secret_names is None else secret_names
+ return [(item.label, item.status(config, secrets)) for item in _CONFIG_ITEMS]
+
+
+def _print_setup_status(status: list[tuple[str, str | None]]) -> bool:
+ """Render the compact status block. Returns True iff anything was printed.
+
+ Stays silent when nothing is set yet so the wizard's first-run output
+ isn't padded with "not set" lines; ``devbox:config:show`` uses the
+ return value to choose between the block and a "Nothing configured yet"
+ hint instead.
+ """
+ if not any(value for _, value in status):
+ return False
+ width = max(len(label) for label, _ in status) + 1
+ click.echo()
+ click.echo("Currently configured:")
+ for label, value in status:
+ rendered = value if value else click.style("not set", fg="yellow")
+ click.echo(f" {label:<{width}} {rendered}")
+ return True
+
+
+def _explicit_option_flag_passed(configure_flags: list[bool | None]) -> bool:
+ """Return whether the user passed any explicit --configure-* / --skip-configure-* flag."""
+ return any(flag is not None for flag in configure_flags)
+
+
+def _confirm_run_setup() -> bool:
+ """Show a Y/n gate explaining what setup will do. ``True`` means proceed.
+
+ Skipped for non-interactive stdin so CI / piped invocations never block.
+ """
+ if not sys.stdin.isatty():
+ return True
+ click.echo()
+ click.echo("hogli devbox:setup will check or configure:")
+ click.echo(" - Tailscale + Coder reachability")
+ click.echo(" - Local SSH config for Coder hosts")
+ click.echo(" - Git identity (name/email) for new workspaces")
+ click.echo(" - Git commit signing key propagation")
+ click.echo(" - Dotfiles repo for new workspaces (optional)")
+ click.echo(" - Claude OAuth token as a Coder user secret (optional)")
+ click.echo()
+ return click.confirm("Proceed?", default=True)
+
+
@click.command(name="devbox:setup", help="Install and configure local access to Coder devboxes")
@click.option(
"--configure-ssh/--skip-configure-ssh",
@@ -635,21 +813,45 @@ def devbox_setup(
verbose: bool,
) -> None:
"""Prepare this machine for Coder workspaces."""
+ explicit = _explicit_option_flag_passed(
+ [
+ configure_ssh,
+ configure_git_identity,
+ configure_git_signing,
+ configure_dotfiles,
+ configure_claude_setup,
+ ],
+ )
+
click.echo(click.style("Configuring devbox CLI access...", bold=True))
ensure_tailscale_connected("rerun `hogli devbox:setup`.")
ensure_tailscale_routes_accepted()
ensure_coder_reachable()
ensure_coder_installed(verbose=verbose)
ensure_coder_authenticated()
+
+ # One `coder secret list` round trip fuels the status block and both
+ # secret-aware configure helpers. None of the upcoming steps mutate a
+ # secret the *other* steps' checks care about, so the snapshot stays
+ # valid for the duration of this invocation.
+ secret_names = _fetch_secret_names()
+
+ status = _collect_setup_status(secret_names)
+ _print_setup_status(status)
+
+ if not explicit and not _confirm_run_setup():
+ click.echo("Aborted. Re-run `hogli devbox:setup` when ready.")
+ return
+
maybe_configure_ssh(
configure_ssh=configure_ssh,
identity_agent_socket=_resolve_local_identity_agent_for_coder(),
verbose=verbose,
)
maybe_configure_git_identity(configure_git_identity)
- maybe_configure_git_signing(configure_git_signing)
+ maybe_configure_git_signing(configure_git_signing, known_secret_names=secret_names)
maybe_configure_dotfiles(configure_dotfiles)
- maybe_configure_claude_secret(configure_claude_setup)
+ maybe_configure_claude_secret(configure_claude_setup, known_secret_names=secret_names)
print_setup_summary()
@@ -1066,6 +1268,48 @@ def devbox_secret_rm(name: str) -> None:
click.echo(f"Deleted user secret '{name}'.")
[email protected](name="devbox:config:show", help="Show saved devbox setup configuration")
+def devbox_config_show() -> None:
+ """Print the local devbox configuration saved by ``devbox:setup``."""
+ ensure_runtime_ready()
+ if not _print_setup_status(_collect_setup_status()):
+ click.echo("Nothing configured yet. Run `hogli devbox:setup`.")
+
+
[email protected](name="devbox:config:rm", help="Clear saved devbox configuration items")
[email protected]("keys", nargs=-1)
[email protected]("--all", "reset_all", is_flag=True, help="Clear every saved item")
+def devbox_config_rm(keys: tuple[str, ...], reset_all: bool) -> None:
+ """Remove one or more saved devbox configuration items.
+
+ Valid keys mirror the matching ``--configure-*`` flags on ``devbox:setup``:
+ ``git-identity``, ``git-signing``, ``dotfiles``, ``claude``.
+ """
+ by_key = _config_items_by_key()
+ valid_keys = tuple(by_key)
+
+ if reset_all and keys:
+ _fail("Pass --all or one or more keys, not both. Valid keys: " + ", ".join(valid_keys))
+ if not reset_all and not keys:
+ _fail("Pass at least one key, or --all. Valid keys: " + ", ".join(valid_keys))
+
+ unknown = [k for k in keys if k not in by_key]
+ if unknown:
+ suffix = "s" if len(unknown) > 1 else ""
+ _fail(f"Unknown key{suffix}: {', '.join(unknown)}. Valid keys: {', '.join(valid_keys)}")
+
+ ensure_runtime_ready()
+ targets = [by_key[k] for k in (valid_keys if reset_all else keys)]
+ if any(item.needs_secrets for item in targets):
+ _ensure_user_secrets_supported()
+
+ # Materialize results so every handler runs even when only some clear anything.
+ fired = [item.reset() for item in targets]
+ if any(fired):
+ click.echo()
+ click.echo("Restart any running devbox (`hogli devbox:restart`) to pick up the resets.")
+
+
@click.command(name="devbox:destroy", help="Destroy your devbox and its data")
@workspace_argument
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index b17890d2b801..9a3b986de49a 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -5,8 +5,10 @@ All subprocess interactions with the Coder CLI are isolated here.
from __future__ import annotations
+import io
import os
import re
+import csv
import sys
import json
import shlex
@@ -601,6 +603,24 @@ def ensure_coder_reachable() -> None:
_fail(body)
+def _encode_ssh_option(value: str) -> str:
+ """Encode one value for ``coder config-ssh --ssh-option``.
+
+ The flag is a cobra ``StringSlice``, which runs each value through Go's
+ ``encoding/csv``. Bare ``"`` in a non-quoted field crashes the parser
+ (``parse error: bare " in non-quoted-field``), so SSH options containing
+ quotes -- like ``IdentityAgent "/path with spaces"`` -- need to arrive
+ CSV-encoded. ``csv.QUOTE_MINIMAL`` only wraps fields that actually need
+ it, so plain options like ``ForwardAgent yes`` pass through unchanged.
+
+ coder CSV-decodes the value before writing ``~/.ssh/config``, so the
+ file ends up with the literal SSH form we constructed here.
+ """
+ buf = io.StringIO()
+ csv.writer(buf, quoting=csv.QUOTE_MINIMAL).writerow([value])
+ return buf.getvalue().rstrip("\r\n")
+
+
def _config_ssh_args(*, identity_agent_socket: str | None = None) -> list[str]:
"""Build the base args for ``coder config-ssh``, pinning the managed binary path.
@@ -610,14 +630,20 @@ def _config_ssh_args(*, identity_agent_socket: str | None = None) -> list[str]:
the engineer picked in ``--configure-git-signing`` (Secretive or 1Password).
``IdentityAgent`` is omitted when no socket has been chosen yet, leaving
SSH to fall back to the user's default ``$SSH_AUTH_SOCK``.
+
+ The socket path needs to land double-quoted in ``~/.ssh/config`` because
+ 1Password's macOS agent lives under ``~/Library/Group Containers/...`` --
+ an unquoted space makes ``ssh`` reject the config with "extra arguments
+ at end of line." See ``_encode_ssh_option`` for how that survives coder's
+ CSV-parsing flag layer.
"""
args = ["coder", "config-ssh"]
managed = _MANAGED_CODER_DIR / "coder"
if managed.is_file():
args += ["--coder-binary-path", str(managed)]
- args += ["--ssh-option", "ForwardAgent yes"]
+ args += ["--ssh-option", _encode_ssh_option("ForwardAgent yes")]
if identity_agent_socket:
- args += ["--ssh-option", f'IdentityAgent "{identity_agent_socket}"']
+ args += ["--ssh-option", _encode_ssh_option(f'IdentityAgent "{identity_agent_socket}"')]
return args
@@ -818,16 +844,12 @@ def print_setup_summary() -> None:
click.echo()
click.echo("Setup complete. Run `hogli devbox:start` to create or start your devbox.")
click.echo()
- click.echo("To reconfigure later:")
- click.echo(" hogli devbox:setup --configure-git-identity")
- click.echo(" hogli devbox:setup --configure-git-signing")
- click.echo(" hogli devbox:setup --configure-dotfiles")
- click.echo(" hogli devbox:setup --configure-claude (manage CLAUDE_CODE_OAUTH_TOKEN as a Coder user secret)")
+ click.echo("Reconfigure one setting: hogli devbox:setup --configure-<option>")
+ click.echo("Show saved configuration: hogli devbox:config:show")
+ click.echo("Clear saved settings: hogli devbox:config:rm --help")
click.echo()
- click.echo("To manage other workspace secrets (GH_TOKEN, AWS creds, etc):")
- click.echo(" hogli devbox:secret:list")
- click.echo(" hogli devbox:secret:set NAME")
- click.echo(" hogli devbox:secret:rm NAME")
+ click.echo("Other workspace secrets (GH_TOKEN, AWS creds, etc):")
+ click.echo(" hogli devbox:secret:list / hogli devbox:secret:set NAME / hogli devbox:secret:rm NAME")
def _first_non_empty_string(*values: Any) -> str | None:
diff --git a/tools/hogli-commands/hogli_commands/devbox/config.py b/tools/hogli-commands/hogli_commands/devbox/config.py
index b53a60669a03..c9f036b4ab98 100644
--- a/tools/hogli-commands/hogli_commands/devbox/config.py
+++ b/tools/hogli-commands/hogli_commands/devbox/config.py
@@ -71,3 +71,20 @@ def save_dotfiles_uri(dotfiles_uri: str) -> DevboxConfig:
config["dotfiles_uri"] = dotfiles_uri
save_config(config)
return config
+
+
+def clear_dotfiles_uri() -> DevboxConfig:
+ """Remove any saved dotfiles repo URL so new workspaces don't clone one."""
+ config = load_config()
+ config.pop("dotfiles_uri", None)
+ save_config(config)
+ return config
+
+
+def clear_git_identity() -> DevboxConfig:
+ """Remove any saved Git identity defaults for new workspaces."""
+ config = load_config()
+ config.pop("git_name", None)
+ config.pop("git_email", None)
+ save_config(config)
+ return config
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index 7b5cb2a1cf69..1bc346ffcd14 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 csv
import json
import errno
import subprocess
@@ -61,6 +62,38 @@ class TestDevboxConfig:
"dotfiles_uri": "https://github.com/user/dotfiles",
}
+ def test_clear_dotfiles_uri_removes_only_dotfiles(self, devbox_config_path: Path) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+ devbox_config.save_dotfiles_uri("https://github.com/user/dotfiles")
+
+ devbox_config.clear_dotfiles_uri()
+
+ config = devbox_config.load_config()
+ assert config == {
+ "git_name": "PostHog Engineer",
+ "git_email": "[email protected]",
+ }
+
+ def test_clear_dotfiles_uri_is_noop_when_unset(self, devbox_config_path: Path) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+
+ devbox_config.clear_dotfiles_uri()
+
+ config = devbox_config.load_config()
+ assert config == {
+ "git_name": "PostHog Engineer",
+ "git_email": "[email protected]",
+ }
+
+ def test_clear_git_identity_leaves_dotfiles_intact(self, devbox_config_path: Path) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+ devbox_config.save_dotfiles_uri("https://github.com/user/dotfiles")
+
+ devbox_config.clear_git_identity()
+
+ config = devbox_config.load_config()
+ assert config == {"dotfiles_uri": "https://github.com/user/dotfiles"}
+
class TestUserSecrets:
"""Test the per-user Coder secret helpers used for Git signing."""
@@ -1069,6 +1102,7 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "ensure_coder_reachable", lambda: calls.append("reachable"))
monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: calls.append("install"))
monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: calls.append("login"))
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [])
monkeypatch.setattr(
devbox_cli,
"maybe_configure_ssh",
@@ -1082,7 +1116,7 @@ class TestDevboxCommands:
monkeypatch.setattr(
devbox_cli,
"maybe_configure_git_signing",
- lambda configure_git_signing: calls.append(f"signing:{configure_git_signing}"),
+ lambda configure_git_signing, **kw: calls.append(f"signing:{configure_git_signing}"),
)
monkeypatch.setattr(
devbox_cli,
@@ -1092,7 +1126,7 @@ class TestDevboxCommands:
monkeypatch.setattr(
devbox_cli,
"maybe_configure_claude_secret",
- lambda configure_claude: calls.append(f"claude:{configure_claude}"),
+ lambda configure_claude, **kw: calls.append(f"claude:{configure_claude}"),
)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: calls.append("summary"))
@@ -1134,6 +1168,7 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: None)
monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: "/tmp/resolved.sock")
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [])
monkeypatch.setattr(devbox_cli, "maybe_configure_git_identity", lambda *a, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda *a, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda *a, **kw: None)
@@ -1163,10 +1198,11 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: None)
monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: None)
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [])
monkeypatch.setattr(devbox_cli, "maybe_configure_ssh", lambda configure_ssh, **kw: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda configure_git_signing: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda configure_git_signing, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda configure_dotfiles: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude, **kw: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
monkeypatch.setattr(devbox_cli, "get_default_git_identity", lambda: ("Coder User", "[email protected]"))
@@ -1184,7 +1220,7 @@ class TestDevboxCommands:
"git_email": "[email protected]",
}
- def test_devbox_setup_skips_git_identity_when_already_saved(
+ def test_devbox_setup_renders_compact_status_for_saved_settings(
self,
monkeypatch: pytest.MonkeyPatch,
devbox_config_path: Path,
@@ -1197,16 +1233,19 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: None)
monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: None)
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [])
monkeypatch.setattr(devbox_cli, "maybe_configure_ssh", lambda configure_ssh, **kw: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda configure_git_signing: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda configure_git_signing, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda configure_dotfiles: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude, **kw: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
result = runner.invoke(cli, ["devbox:setup", "--skip-configure-ssh"])
assert result.exit_code == 0
- assert "Using saved Git identity: Existing User <[email protected]>" in result.output
+ assert "Currently configured:" in result.output
+ assert "Git identity" in result.output
+ assert "Existing User <[email protected]>" in result.output
def test_devbox_start_creates_workspace_with_default_name(
self,
@@ -1420,6 +1459,289 @@ class TestDevboxCommands:
assert "hogli devbox:forward --port 8011" in result.output
+def 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_tailscale_connected",
+ "ensure_tailscale_routes_accepted",
+ "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, "_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)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [])
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
+ monkeypatch.setattr(devbox_cli, "_confirm_run_setup", lambda: True)
+
+
+def stub_config_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Stub the runtime guards that ``devbox:config:*`` commands call before doing work."""
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "_ensure_user_secrets_supported", lambda: None)
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [])
+
+
+class TestDevboxConfigCommands:
+ """Cover the ``devbox:config:show`` and ``devbox:config:rm`` commands."""
+
+ def test_show_reports_when_nothing_configured(
+ self,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ result = runner.invoke(cli, ["devbox:config:show"])
+
+ assert result.exit_code == 0
+ assert "Nothing configured yet" in result.output
+
+ def test_show_renders_saved_settings(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config_path.write_text(
+ json.dumps(
+ {
+ "git_name": "PostHog Engineer",
+ "git_email": "[email protected]",
+ "dotfiles_uri": "https://github.com/user/dotfiles",
+ }
+ )
+ )
+ monkeypatch.setattr(devbox_cli, "list_user_secrets", lambda: [{"name": coder.GIT_SIGNING_KEY_SECRET}])
+
+ result = runner.invoke(cli, ["devbox:config:show"])
+
+ assert result.exit_code == 0
+ assert "Currently configured:" in result.output
+ assert "PostHog Engineer <[email protected]>" in result.output
+ assert "https://github.com/user/dotfiles" in result.output
+ assert "Git signing" in result.output
+
+ def test_rm_dotfiles_clears_config_and_pushes_empty_param_to_existing_workspaces(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config.save_dotfiles_uri("https://github.com/user/dotfiles")
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_workspaces",
+ lambda: [{"name": "devbox-test-user"}, {"name": "devbox-test-user-mobile"}],
+ )
+ param_pushes: list[tuple[str, dict[str, str]]] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "update_workspace_parameters",
+ lambda name, params: param_pushes.append((name, params)),
+ )
+
+ result = runner.invoke(cli, ["devbox:config:rm", "dotfiles"])
+
+ assert result.exit_code == 0, result.output
+ assert devbox_config.load_config() == {}
+ assert param_pushes == [
+ ("devbox-test-user", {coder.DOTFILES_URI_PARAMETER: ""}),
+ ("devbox-test-user-mobile", {coder.DOTFILES_URI_PARAMETER: ""}),
+ ]
+ assert "Cleared saved dotfiles repo" in result.output
+ assert "Restart any running devbox" in result.output
+
+ def test_rm_git_identity_clears_only_identity_keys(
+ self,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+ devbox_config.save_dotfiles_uri("https://github.com/user/dotfiles")
+
+ result = runner.invoke(cli, ["devbox:config:rm", "git-identity"])
+
+ assert result.exit_code == 0, result.output
+ assert devbox_config.load_config() == {"dotfiles_uri": "https://github.com/user/dotfiles"}
+ assert "Cleared saved Git identity" in result.output
+
+ @pytest.mark.parametrize(
+ "key,expected_secret",
+ [
+ ("git-signing", coder.GIT_SIGNING_KEY_SECRET),
+ ("claude", coder.CLAUDE_CODE_OAUTH_ENV),
+ ],
+ ids=["git-signing", "claude"],
+ )
+ def test_rm_secret_keys_delete_the_right_coder_secret(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ stub_config_runtime: None,
+ key: str,
+ expected_secret: str,
+ ) -> None:
+ deleted: list[str] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "delete_user_secret",
+ lambda name: deleted.append(name) or subprocess.CompletedProcess(["coder"], 0, "", ""),
+ )
+
+ result = runner.invoke(cli, ["devbox:config:rm", key])
+
+ assert result.exit_code == 0, result.output
+ assert deleted == [expected_secret]
+
+ def test_rm_multiple_keys_clears_each(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config.save_git_identity("Eng", "[email protected]")
+ devbox_config.save_dotfiles_uri("https://x/y")
+ deleted: list[str] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "delete_user_secret",
+ lambda name: deleted.append(name) or subprocess.CompletedProcess(["coder"], 0, "", ""),
+ )
+
+ result = runner.invoke(cli, ["devbox:config:rm", "git-identity", "claude"])
+
+ assert result.exit_code == 0, result.output
+ assert devbox_config.load_config() == {"dotfiles_uri": "https://x/y"}
+ assert deleted == [coder.CLAUDE_CODE_OAUTH_ENV]
+
+ def test_rm_all_clears_every_key(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config.save_git_identity("Eng", "[email protected]")
+ devbox_config.save_dotfiles_uri("https://x/y")
+ deleted: list[str] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "delete_user_secret",
+ lambda name: deleted.append(name) or subprocess.CompletedProcess(["coder"], 0, "", ""),
+ )
+
+ result = runner.invoke(cli, ["devbox:config:rm", "--all"])
+
+ assert result.exit_code == 0, result.output
+ assert devbox_config.load_config() == {}
+ assert deleted == [coder.GIT_SIGNING_KEY_SECRET, coder.CLAUDE_CODE_OAUTH_ENV]
+
+ def test_rm_with_no_args_fails_with_valid_keys_hint(self, stub_config_runtime: None) -> None:
+ result = runner.invoke(cli, ["devbox:config:rm"])
+
+ assert result.exit_code != 0
+ assert "git-identity" in result.output
+ assert "git-signing" in result.output
+ assert "dotfiles" in result.output
+ assert "claude" in result.output
+
+ def test_rm_with_unknown_key_fails_with_valid_keys_hint(self, stub_config_runtime: None) -> None:
+ result = runner.invoke(cli, ["devbox:config:rm", "bogus"])
+
+ assert result.exit_code != 0
+ assert "Unknown key" in result.output
+ assert "bogus" in result.output
+
+ def test_rm_rejects_all_combined_with_positional_keys(self, stub_config_runtime: None) -> None:
+ result = runner.invoke(cli, ["devbox:config:rm", "--all", "dotfiles"])
+
+ assert result.exit_code != 0
+ assert "--all" in result.output
+
+ def test_rm_is_idempotent_for_already_empty_local_state(
+ self,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ # No config file written and no secrets stubbed -- clearing should still succeed.
+ result = runner.invoke(cli, ["devbox:config:rm", "dotfiles"])
+
+ assert result.exit_code == 0, result.output
+ assert "Nothing to clear: dotfiles was not set." in result.output
+ # When nothing actually fired, the restart hint is misleading -- suppress it.
+ assert "Restart any running devbox" not in result.output
+
+ def test_rm_prints_restart_hint_only_when_something_actually_cleared(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ # Only dotfiles is set; the secret deletions report nothing-to-do.
+ devbox_config.save_dotfiles_uri("https://github.com/user/dotfiles")
+ monkeypatch.setattr(
+ devbox_cli,
+ "delete_user_secret",
+ lambda name: subprocess.CompletedProcess(["coder"], 1, "", "not found"),
+ )
+
+ result = runner.invoke(cli, ["devbox:config:rm", "--all"])
+
+ assert result.exit_code == 0, result.output
+ # dotfiles fired -> hint present; the no-op secret deletions don't suppress it.
+ assert "Cleared saved dotfiles repo" in result.output
+ assert "Nothing to delete:" in result.output
+ assert "Restart any running devbox" in result.output
+
+
+class TestDevboxSetupGate:
+ """Cover the Y/n gate at the top of ``hogli devbox:setup``."""
+
+ def test_gate_bypassed_when_explicit_configure_flag_passed(
+ self, monkeypatch: pytest.MonkeyPatch, stub_setup_environment: None
+ ) -> None:
+ gate_calls: list[None] = []
+ monkeypatch.setattr(devbox_cli, "_confirm_run_setup", lambda: gate_calls.append(None) or True)
+
+ result = runner.invoke(cli, ["devbox:setup", "--skip-configure-ssh"])
+
+ assert result.exit_code == 0
+ assert gate_calls == []
+
+ def test_gate_shown_when_no_flags_and_aborts_on_no(
+ self, monkeypatch: pytest.MonkeyPatch, stub_setup_environment: None
+ ) -> None:
+ monkeypatch.setattr(devbox_cli, "_confirm_run_setup", lambda: False)
+ configure_calls: list[str] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "maybe_configure_git_identity",
+ lambda *a, **kw: configure_calls.append("git"),
+ )
+
+ result = runner.invoke(cli, ["devbox:setup"])
+
+ assert result.exit_code == 0
+ assert configure_calls == []
+ assert "Aborted" in result.output
+
+ def test_gate_helper_returns_true_when_stdin_is_not_a_tty(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli.sys.stdin, "isatty", lambda: False)
+ monkeypatch.setattr(
+ devbox_cli.click,
+ "confirm",
+ lambda *a, **kw: pytest.fail("click.confirm must not be called when stdin is not a TTY"),
+ )
+
+ assert devbox_cli._confirm_run_setup() is True
+
+
class TestStartExistingWorkspace:
"""Test workspace parameter sync when starting an existing workspace."""
@@ -1804,15 +2126,21 @@ class TestSetupClaudeSecret:
devbox_cli.maybe_configure_claude_secret(None)
assert any("older than 2.33" in line for line in echoed)
- def test_skips_when_secret_already_exists(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def test_skips_silently_when_secret_already_exists(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # The compact status block at the top of devbox_setup now owns the
+ # "Claude token: configured" line, so this helper returns silently on
+ # the already-set path rather than re-stating the same info.
monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: True)
+ upserts: list[tuple[str, str]] = []
+ monkeypatch.setattr(devbox_cli, "upsert_user_secret", lambda name, value, **kw: upserts.append((name, value)))
echoed: list[str] = []
monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
devbox_cli.maybe_configure_claude_secret(None)
- assert any("already set as a Coder user secret" in line for line in echoed)
+ assert upserts == []
+ assert echoed == []
def test_skip_flag_short_circuits(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
@@ -2206,12 +2534,36 @@ class TestResolveLocalIdentityAgent:
class TestConfigSshArgs:
- """Test the `coder config-ssh` arg assembly."""
+ """Test the `coder config-ssh` argument builder.
+
+ Two encoding layers in play, both have to round-trip:
+
+ 1. ``coder config-ssh --ssh-option`` is a cobra ``StringSlice``, so each
+ value is CSV-parsed before coder uses it. A bare ``"`` in a non-quoted
+ CSV field crashes coder's parser; the encoder wraps any value with
+ quotes/commas so it survives.
+ 2. ``~/.ssh/config`` itself: an unquoted ``IdentityAgent`` path with
+ spaces (1Password's ``~/Library/Group Containers/...``) makes ``ssh``
+ reject the config with "extra arguments at end of line."
+
+ The tests below assert the CSV-encoded value coder receives *and* the
+ SSH form it decodes back to.
+ """
+
+ _SOCKET_WITH_SPACES = "/Users/me/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock"
+
+ @staticmethod
+ def _ssh_option_values(args: list[str]) -> list[str]:
+ return [args[i + 1] for i, a in enumerate(args) if a == "--ssh-option"]
+
+ @staticmethod
+ def _csv_decode(field: str) -> str:
+ return next(csv.reader([field]))[0]
- def test_omits_identity_agent_when_socket_missing(self) -> None:
+ def test_omits_identity_agent_when_socket_is_none(self) -> None:
args = coder._config_ssh_args(identity_agent_socket=None)
- assert "ForwardAgent yes" in args
- assert not any("IdentityAgent" in a for a in args)
+ decoded = [self._csv_decode(v) for v in self._ssh_option_values(args)]
+ assert decoded == ["ForwardAgent yes"]
@pytest.mark.parametrize(
"socket",
@@ -2222,10 +2574,37 @@ class TestConfigSshArgs:
"/Users/me/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock",
"/tmp/agent.sock",
],
+ ids=["spaces", "no-spaces"],
)
- def test_quotes_identity_agent_socket(self, socket: str) -> None:
+ def test_identity_agent_socket_roundtrips_to_quoted_ssh_form(self, socket: str) -> None:
args = coder._config_ssh_args(identity_agent_socket=socket)
- assert f'IdentityAgent "{socket}"' in args
+ identity_option = next(v for v in self._ssh_option_values(args) if "IdentityAgent" in v)
+ # After coder CSV-decodes it, ~/.ssh/config gets the SSH form -- an
+ # IdentityAgent line with a quoted path. The quotes are what ssh needs
+ # when the socket contains spaces; CSV encoding is what coder needs to
+ # accept those quotes.
+ assert self._csv_decode(identity_option) == f'IdentityAgent "{socket}"'
+
+
+class TestEncodeSshOption:
+ """Direct tests for the CSV-encoding helper backing `--ssh-option` values."""
+
+ def test_plain_value_passes_through_unchanged(self) -> None:
+ # QUOTE_MINIMAL only wraps fields that need it -- a plain option
+ # should land as the literal string coder writes to the config.
+ assert coder._encode_ssh_option("ForwardAgent yes") == "ForwardAgent yes"
+
+ def test_value_with_embedded_quotes_is_csv_quoted_and_roundtrips(self) -> None:
+ encoded = coder._encode_ssh_option('IdentityAgent "/path with space/sock"')
+ # CSV-encoded: outer wrap + doubled internal quotes.
+ assert encoded == '"IdentityAgent ""/path with space/sock"""'
+ # And it round-trips through Go's CSV parser (which Python's csv module mirrors).
+ assert next(csv.reader([encoded]))[0] == 'IdentityAgent "/path with space/sock"'
+
+ def test_value_with_commas_is_csv_quoted(self) -> None:
+ # Defensive: any SSH option containing the CSV delimiter must be quoted.
+ encoded = coder._encode_ssh_option("ProxyCommand a,b")
+ assert next(csv.reader([encoded]))[0] == "ProxyCommand a,b"
class TestSetupGitSigning: