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): stop syncing saved parameters on resume (#117874)

Raúl Negrón-Otero36d86988ecab
diff --git a/.agents/skills/setting-up-devbox/SKILL.md b/.agents/skills/setting-up-devbox/SKILL.md
index 0fc4241121d4..9ef5b009b1b2 100644
--- a/.agents/skills/setting-up-devbox/SKILL.md
+++ b/.agents/skills/setting-up-devbox/SKILL.md
@@ -94,7 +94,7 @@ Use this section only when the user wants the app, for example to QA a change or
### Start the stack
-- **New or stopped box:** `hogli devbox:start --start-app`. The flag stays set on the workspace, so every later start brings the stack up in the background until `hogli devbox:start --no-start-app` turns it off. Either flag takes effect only when the box is created or starts from stopped; on a running box hogli skips it and prints a note.
+- **New box:** `hogli devbox:start --start-app`. The setting stays on the workspace, so every later start brings the stack up in the background. The flag applies only when hogli creates the box; on an existing box hogli refuses it, because the Coder CLI keeps a parameter's last-build value. Change it on an existing box in the Coder dashboard under the workspace's parameters.
- **Running box:** `hogli devbox:exec -- bash -lc 'cd ~/posthog && ./bin/hogli up -d -y'`.
### Wait for it
@@ -152,7 +152,7 @@ Pass `--port 8011` when a local stack already uses 8010.
- **Disk full:** `hogli devbox:cleanup:disk -n <label>` cleans a labeled box. With no workspace it cleans this machine instead, and the default box has no label, so clean the default box with `hogli devbox:exec -- bash -lc 'cd ~/posthog && ./bin/hogli devbox:cleanup:disk'`. `--docker` also prunes stopped containers, and `--cargo` also removes Rust build output, which forces a full rebuild.
- **Pairing:** `hogli devbox:share --user <coder-user> --role use` grants access, and `devbox:users` lists usernames. `devbox:unshare` removes access only after `hogli devbox:restart`.
- **Build and agent logs:** `hogli devbox:logs -f`.
-- **Personal setup:** the box works as shipped. Changes made on the box survive stops and updates. `hogli devbox:setup --configure-dotfiles` saves a dotfiles repo that the box applies on start, running its executable `install.sh`. A new repo URL reaches a box when it next starts from stopped or runs `devbox:update`, not on `devbox:restart`. Neither is required, so don't push one over the other.
+- **Personal setup:** the box works as shipped. Changes made on the box survive stops and updates. `hogli devbox:setup --configure-dotfiles` saves a dotfiles repo that the box applies on start, running its executable `install.sh`. A saved repo URL applies to boxes hogli creates. To change it on an existing box, edit the workspace's parameters in the Coder dashboard.
## Gotchas
diff --git a/docs/internal/coder-workspaces.md b/docs/internal/coder-workspaces.md
index 3bd2f3c4c84a..a705a99ea09b 100644
--- a/docs/internal/coder-workspaces.md
+++ b/docs/internal/coder-workspaces.md
@@ -103,13 +103,14 @@ Clear specific saved settings with `devbox:config:rm`:
```bash
hogli devbox:config:rm git-identity # clear saved Git name/email
hogli devbox:config:rm git-signing # remove Git signing key from Coder user secrets
-hogli devbox:config:rm dotfiles # clear dotfiles URI (also pushes empty parameter to existing workspaces)
+hogli devbox:config:rm dotfiles # clear dotfiles URI for new workspaces
hogli devbox:config:rm claude # remove Claude OAuth token from Coder user secrets
hogli devbox:config:rm region # clear saved region preference (new workspaces use the built-in default)
hogli devbox:config:rm --all # clear everything
```
-Clearing dotfiles also pushes an empty `dotfiles_uri` parameter to all existing workspaces so they stop re-cloning the old repo on next boot.
+Saved settings apply to workspaces hogli creates.
+The Coder CLI keeps a parameter's last-build value even when hogli passes a new one, so to change a setting on an existing workspace, edit its parameters in the Coder dashboard.
## Available commands
@@ -117,7 +118,7 @@ Run `hogli devbox` to see all available commands, and `hogli <command> --help` f
Region selection is available for `devbox:start` via `--region` (`us-east-1` or `eu-central-1`, default `us-east-1`). The region is set once at creation and cannot be changed. Workspaces in `eu-central-1` get an `-eu` name suffix (e.g. `devbox-alice-eu`). `devbox:list` and `devbox:status` show which region a workspace is in.
-`devbox:start --start-app` opts a workspace into bringing the PostHog app up (`hogli up`) in the background on every start — useful for scripted, ephemeral devboxes that should be usable without an interactive `hogli up`. The setting is stored as a mutable workspace parameter (`auto_start_app`), so it stays in effect for future starts until flipped with `--no-start-app`. The flag is applied at creation or when starting a stopped devbox; on a running or transitioning devbox it is not applied (hogli prints a note) — re-run it once the devbox is stopped. Requires a template version that defines the parameter; on older templates hogli drops it with a warning.
+`devbox:start --start-app` opts a workspace into bringing the PostHog app up (`hogli up`) in the background on every start — useful for scripted, ephemeral devboxes that should be usable without an interactive `hogli up`. The setting is stored as a workspace parameter (`auto_start_app`), so it stays in effect for future starts. The flag applies only when hogli creates the devbox; on an existing devbox hogli refuses it, and the parameter can be changed in the Coder dashboard. Requires a template version that defines the parameter; on older templates hogli drops it with a warning.
Runtime commands assume setup is already complete.
If they fail with `Run hogli devbox:setup`, rerun setup on your laptop first.
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 73463038ada2..1897564bda3c 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -30,16 +30,12 @@ from .coder import (
DEFAULT_PRESET,
DEFAULT_REGION,
DEFAULT_TEMPLATE,
- DOTFILES_URI_PARAMETER,
EXPECTED_TAILNET,
- GIT_EMAIL_PARAMETER,
- GIT_NAME_PARAMETER,
GIT_SIGNING_KEY_SECRET,
REGIONS,
_diagnose_unreachable_coder,
_fail,
_ssh_host_alias,
- _start_app_param,
clone_workspace,
coder_authenticated,
coder_installed,
@@ -90,7 +86,6 @@ from .coder import (
tailscale_state,
unshare_workspace,
update_workspace,
- update_workspace_parameters,
upsert_user_secret,
user_secret_exists,
)
@@ -130,10 +125,9 @@ WORKSPACE_STATUS_COLORS = {
}
PENDING_WORKSPACE_STATES = {"starting", "stopping", "deleting"}
-# Printed whenever --start-app/--no-start-app is passed but cannot be applied:
-# the parameter is only pushed on the pre-start sync of a stopped workspace,
-# so the flag is dropped (not queued) on running/transitioning boxes.
-_START_APP_NOT_APPLIED_NOTE = "Note: --start-app/--no-start-app was not applied; re-run it once the devbox is stopped."
+# The Coder CLI resolves a mutable parameter to its last-build value even when
+# `--parameter` passes a new one, so hogli can only set parameters at creation.
+_CHANGE_PARAMETER_HINT = "To change it on an existing devbox, edit the devbox's parameters in the Coder dashboard."
def resolve_workspace_name(
@@ -324,59 +318,34 @@ def _render_sync_status(workspace_name: str) -> str:
return click.style(f"● {status}", fg="green")
-def _sync_workspace_parameters(name: str, extra: dict[str, str] | None = None) -> None:
- """Push local config (git identity, dotfiles) to workspace parameters before start.
-
- `workspace_region` is intentionally not forwarded: it is immutable, so Coder
- carries it forward on its own and rejects any explicit value on `coder
- update` (see the comment on `WORKSPACE_REGION_PARAMETER`).
- """
- config = load_config()
- params: dict[str, str] = {}
-
- git_name = config.get("git_name")
- git_email = config.get("git_email")
- if git_name and git_email:
- params[GIT_NAME_PARAMETER] = git_name
- params[GIT_EMAIL_PARAMETER] = git_email
-
- dotfiles_uri = config.get("dotfiles_uri")
- if dotfiles_uri:
- params[DOTFILES_URI_PARAMETER] = dotfiles_uri
-
- if extra:
- params.update(extra)
-
- if params:
- update_workspace_parameters(name, params)
-
-
def _start_existing_workspace(
name: str, workspace: dict[str, Any], *, start_app: bool | None = None, verbose: bool
) -> None:
"""Handle `devbox:start` when the workspace already exists."""
+ if start_app is not None:
+ _fail(
+ f"--start-app and --no-start-app only apply when a devbox is created. {_CHANGE_PARAMETER_HINT}",
+ cause="start_app_on_existing",
+ )
+
status = get_workspace_status(workspace)
if status == "running":
click.echo(f"Devbox '{name}' is already running.")
- if start_app is not None:
- # Pushing the parameter needs `coder update`, which rebuilds a
- # running workspace -- only safe on the pre-start sync below.
- click.echo(_START_APP_NOT_APPLIED_NOTE)
_print_connection_info(name)
return
if status in PENDING_WORKSPACE_STATES:
click.echo(f"Devbox '{name}' is in state: {status}")
click.echo("Wait for the current operation to complete.")
- if start_app is not None:
- click.echo(_START_APP_NOT_APPLIED_NOTE)
return
- _sync_workspace_parameters(name, extra=_start_app_param(start_app))
-
if status == "stopped":
- click.echo(f"Starting devbox '{name}'...")
- start_workspace(name, verbose=verbose)
+ if workspace.get("outdated"):
+ click.echo(f"Starting devbox '{name}' on the latest template...")
+ update_workspace(name, verbose=verbose)
+ else:
+ click.echo(f"Starting devbox '{name}'...")
+ start_workspace(name, verbose=verbose)
click.echo("Started.")
_print_connection_info(name)
return
@@ -1013,24 +982,13 @@ def _reset_region() -> bool:
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.
- """
+ """Drop the saved dotfiles URI. Returns True iff something was cleared."""
config = load_config()
if not config.get("dotfiles_uri"):
click.echo("Nothing to clear: dotfiles was not set.")
return False
clear_dotfiles_uri(config)
- 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}'")
+ click.echo(f"Cleared saved dotfiles repo. New devboxes won't clone it. {_CHANGE_PARAMETER_HINT}")
return True
@@ -1465,10 +1423,7 @@ def _maybe_hint_region_mismatch(name: str) -> None:
"--start-app/--no-start-app",
"start_app",
default=None,
- help=(
- "Bring the PostHog app up in the background on every workspace start. "
- "Sticky on the workspace until flipped with --no-start-app."
- ),
+ help=("Bring the PostHog app up in the background on every workspace start. Applies when the devbox is created."),
)
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
def devbox_start(
@@ -1645,12 +1600,8 @@ def devbox_update(workspace: str | None, verbose: bool) -> None:
if not ws.get("outdated"):
click.echo(f"Devbox '{name}' is already up to date.")
return
- config = load_config()
- params: dict[str, str] = {}
- if dotfiles_uri := config.get("dotfiles_uri"):
- params[DOTFILES_URI_PARAMETER] = dotfiles_uri
click.echo(f"Updating '{name}' to the latest template...")
- update_workspace(name, parameters=params, verbose=verbose)
+ update_workspace(name, verbose=verbose)
click.echo("Updated.")
click.echo(
"Note: if your local lockfiles differ from the new AMI's baked versions, "
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index 70372e54325d..c5c424d6474a 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -67,8 +67,8 @@ AUTO_START_APP_PARAMETER = "auto_start_app"
# Create-time region selector. The template defines `workspace_region` with a
# us-east-1 default; eu-central-1 became a valid option when the EU
# infrastructure went live. The value is immutable after creation, so it is
-# forwarded on `coder create` only -- never on `coder update` or the pre-start
-# parameter sync. Coder carries an immutable parameter's value forward on its
+# forwarded on `coder create` only, never on `coder update`. Coder carries an
+# immutable parameter's value forward on its
# own during an update and *rejects* any explicit `--parameter
# workspace_region=` with "parameter is immutable and cannot be updated". The
# option-change re-prompt that no flag can bypass only applies to *mutable*
@@ -311,8 +311,7 @@ def _run_with_param_retry(
Coder validates ``--parameter`` keys client-side before any provisioning
starts, so retrying after a `parameter "X" is not present in the
template` error is cheap and safe. All other failures bubble up
- unchanged. Used by every write path that forwards parameters (`coder
- create`, `coder update`) so callers never have to know which keys the
+ unchanged, so `coder create` callers never have to know which keys the
chosen template happens to accept.
"""
remaining = dict(parameters)
@@ -1287,10 +1286,9 @@ def resolve_template_preset(template: str, requested: str) -> str:
def _start_app_param(start_app: bool | None) -> dict[str, str]:
- """Map the tri-state --start-app flag to a parameter dict (empty = leave as-is).
+ """Map the tri-state --start-app flag to a creation parameter dict.
- ``None`` (flag omitted) returns ``{}`` so the value stays sticky on an
- existing workspace and falls back to the template default on creation.
+ ``None`` (flag omitted) returns ``{}`` so creation uses the template default.
``True``/``False`` are written explicitly so the choice survives even if the
template default changes.
"""
@@ -1495,25 +1493,22 @@ def restart_workspace(name: str, *, verbose: bool = False) -> None:
raise SystemExit(result.returncode)
-def update_workspace(
- name: str,
- parameters: dict[str, str] | None = None,
- *,
- verbose: bool = False,
-) -> None:
- """Update a workspace to the latest template version.
-
- ``--use-parameter-defaults`` lets coder fall back to the template's own
- defaults for any parameter not explicitly supplied here, so we never
- need a hogli-side defaults dict. Parameters carried over from a
- previous template (e.g. a saved ``dotfiles_uri`` that the new template
- does not declare) are dropped by the retry shim instead of aborting
- the update.
+def update_workspace(name: str, *, verbose: bool = False) -> None:
+ """Update a workspace to the latest template version and start it.
+
+ ``--use-parameter-defaults`` fills any parameter the new template version
+ adds with its default instead of prompting behind the spinner.
"""
- base_args = ["coder", "update", name, "--use-parameter-defaults"]
- result = _run_with_param_retry(base_args, parameters or {}, verbose=verbose)
+ result = _run_build(["coder", "update", name, "--use-parameter-defaults"], verbose=verbose)
if result.returncode != 0:
raise SystemExit(result.returncode)
+ # `coder update` only streams the build logs, so it exits 0 when the build fails.
+ workspace = get_workspace(name)
+ if workspace is not None and get_workspace_status(workspace) == "failed":
+ if not verbose:
+ click.echo(click.style("Build failed. Full output:", fg="red"))
+ click.echo(result.stdout, nl=False)
+ raise SystemExit(1)
def delete_workspace(name: str, *, verbose: bool = False) -> None:
@@ -1523,19 +1518,6 @@ def delete_workspace(name: str, *, verbose: bool = False) -> None:
raise SystemExit(result.returncode)
-def update_workspace_parameters(name: str, parameters: dict[str, str]) -> None:
- """Update mutable workspace parameters.
-
- Goes through the same retry shim as ``create_workspace`` so a stale
- local config key (for example, a saved ``dotfiles_uri`` after the user
- switches templates) does not abort the pre-start sync.
- """
- base_args = ["coder", "update", name, "--use-parameter-defaults"]
- result = _run_with_param_retry(base_args, parameters)
- if result.returncode != 0:
- raise SystemExit(result.returncode)
-
-
def upsert_user_secret(
name: str,
value: str,
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index e87b05e1c5e7..4b619afeccf3 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -1104,6 +1104,21 @@ class TestWorkspaceCreation:
assert "claude_oauth_token" not in params
assert params == expected_params
+ @pytest.mark.parametrize("build_status, fails", [("running", False), ("failed", True)], ids=["built", "failed"])
+ def test_update_workspace_fails_when_its_build_fails(
+ self, monkeypatch: pytest.MonkeyPatch, build_status: str, fails: bool
+ ) -> None:
+ monkeypatch.setattr(coder, "_run_build", _fake_run_build_capturing({}))
+ monkeypatch.setattr(
+ coder, "get_workspace", lambda name: {"name": name, "latest_build": {"status": build_status}}
+ )
+
+ if fails:
+ with pytest.raises(SystemExit):
+ coder.update_workspace("devbox-test-user")
+ else:
+ coder.update_workspace("devbox-test-user")
+
@pytest.mark.parametrize(
"start_app, expected",
[(True, "true"), (False, "false"), (None, None)],
@@ -1279,55 +1294,6 @@ class TestTemplatePresetResolution:
assert "Warning" not in output
-class TestWorkspaceUpdate:
- """Test that `coder update` paths share the same retry behavior as create.
-
- Without this, a stale `dotfiles_uri` (or any param the new template
- doesn't declare) saved in the user's hogli config would abort the
- pre-start parameter sync the next time they switch templates.
- """
-
- @pytest.mark.parametrize(
- "call",
- [
- lambda: coder.update_workspace(
- "devbox-test-user",
- parameters={"dotfiles_uri": _DOTFILES, "git_name": "PostHog Engineer"},
- ),
- lambda: coder.update_workspace_parameters(
- "devbox-test-user",
- {"dotfiles_uri": _DOTFILES, "git_name": "PostHog Engineer"},
- ),
- ],
- ids=["update_workspace", "update_workspace_parameters"],
- )
- def test_update_paths_drop_unknown_params_and_retry(
- self,
- monkeypatch: pytest.MonkeyPatch,
- call: Callable[[], None],
- ) -> None:
- calls: list[list[str]] = []
-
- def fake_run_build(args: list[str], *, verbose: bool = False) -> subprocess.CompletedProcess[str]:
- calls.append(args)
- if len(calls) == 1:
- return subprocess.CompletedProcess(
- args, 1, 'parameter "dotfiles_uri" is not present in the template\n', ""
- )
- return subprocess.CompletedProcess(args, 0, "", "")
-
- monkeypatch.setattr(coder, "_run_build", fake_run_build)
-
- call()
-
- assert len(calls) == 2
- first = _parse_parameter_flags(calls[0])
- retried = _parse_parameter_flags(calls[1])
- assert "dotfiles_uri" in first and "git_name" in first
- assert "dotfiles_uri" not in retried
- assert retried["git_name"] == "PostHog Engineer"
-
-
class TestResolveWorkspaceName:
"""Test the CLI workspace resolution logic."""
@@ -1942,11 +1908,10 @@ class TestDevboxCommands:
lambda name, workspaces=None: {"name": name, "outdated": True, "latest_build": {"status": "running"}},
)
monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
- monkeypatch.setattr(devbox_cli, "load_config", lambda: {"dotfiles_uri": "https://github.com/user/dotfiles"})
monkeypatch.setattr(
devbox_cli,
"update_workspace",
- lambda name, parameters=None, verbose=False: captured.update({"name": name, "parameters": parameters}),
+ lambda name, verbose=False: captured.update({"name": name}),
)
result = runner.invoke(cli, ["devbox:update"])
@@ -1954,7 +1919,6 @@ class TestDevboxCommands:
assert result.exit_code == 0
assert "Updating" in result.output
assert captured["name"] == "devbox-test-user"
- assert captured["parameters"] == {"dotfiles_uri": "https://github.com/user/dotfiles"}
def test_devbox_update_skips_when_up_to_date(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
@@ -2157,35 +2121,18 @@ class TestDevboxConfigCommands:
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(
+ def test_rm_dotfiles_clears_config(
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,
@@ -2399,174 +2346,31 @@ class TestDevboxSetupGate:
class TestStartExistingWorkspace:
- """Test workspace parameter sync when starting an existing workspace."""
-
- def test_syncs_workspace_parameters_before_starting_stopped_workspace(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- calls: list[str] = []
- captured_params: dict[str, object] = {}
-
- monkeypatch.setattr(devbox_cli, "get_workspace_status", lambda ws: "stopped")
- monkeypatch.setattr(
- devbox_cli,
- "load_config",
- lambda: {
- "git_name": "PostHog Engineer",
- "git_email": "[email protected]",
- "dotfiles_uri": "https://github.com/user/dotfiles",
- },
- )
-
- def fake_update(name: str, params: dict[str, str]) -> None:
- calls.append("update_params")
- captured_params.update({"name": name, "params": params})
-
- monkeypatch.setattr(devbox_cli, "update_workspace_parameters", fake_update)
- monkeypatch.setattr(
- devbox_cli,
- "start_workspace",
- lambda name, verbose=False: calls.append("start"),
- )
- monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
-
- devbox_cli._start_existing_workspace("devbox-test-user", {"latest_build": {"status": "stopped"}}, verbose=False)
-
- assert calls == ["update_params", "start"]
- assert captured_params == {
- "name": "devbox-test-user",
- "params": {
- "git_name": "PostHog Engineer",
- "git_email": "[email protected]",
- "dotfiles_uri": "https://github.com/user/dotfiles",
- },
- }
-
- def test_skips_sync_when_no_git_identity_configured(self, monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[str] = []
-
- monkeypatch.setattr(devbox_cli, "get_workspace_status", lambda ws: "stopped")
- monkeypatch.setattr(devbox_cli, "load_config", lambda: {})
- monkeypatch.setattr(
- devbox_cli,
- "update_workspace_parameters",
- lambda name, params: calls.append("update_params"),
- )
- monkeypatch.setattr(
- devbox_cli,
- "start_workspace",
- lambda name, verbose=False: calls.append("start"),
- )
- monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
-
- devbox_cli._start_existing_workspace("devbox-test-user", {"latest_build": {"status": "stopped"}}, verbose=False)
-
- assert calls == ["start"]
-
@pytest.mark.parametrize(
- "start_app, expected",
- [(True, "true"), (False, "false"), (None, None)],
- ids=["enable", "disable", "omit"],
+ "outdated, expected", [(False, ["start"]), (True, ["update"])], ids=["current", "outdated"]
)
- def test_pushes_start_app_param_before_starting(
- self, monkeypatch: pytest.MonkeyPatch, start_app: bool | None, expected: str | None
- ) -> None:
- captured: dict[str, object] = {}
-
- monkeypatch.setattr(devbox_cli, "get_workspace_status", lambda ws: "stopped")
- monkeypatch.setattr(devbox_cli, "load_config", lambda: {})
- monkeypatch.setattr(
- devbox_cli,
- "update_workspace_parameters",
- lambda name, params: captured.update(params),
- )
- monkeypatch.setattr(devbox_cli, "start_workspace", lambda name, verbose=False: None)
- monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
-
- devbox_cli._start_existing_workspace(
- "devbox-test-user",
- {"latest_build": {"status": "stopped"}},
- start_app=start_app,
- verbose=False,
- )
-
- if expected is None:
- assert coder.AUTO_START_APP_PARAMETER not in captured
- else:
- assert captured == {coder.AUTO_START_APP_PARAMETER: expected}
-
- @pytest.mark.parametrize("status", ["running", "starting", "stopping"])
- def test_start_app_flag_never_pushed_unless_stopped(
- self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], status: str
+ def test_stopped_workspace_updates_only_when_outdated(
+ self, monkeypatch: pytest.MonkeyPatch, outdated: bool, expected: list[str]
) -> None:
- """`coder update` stops a running workspace, so the flag must only note, never push."""
- monkeypatch.setattr(devbox_cli, "get_workspace_status", lambda ws: status)
- monkeypatch.setattr(
- devbox_cli,
- "update_workspace_parameters",
- lambda name, params: pytest.fail("update_workspace_parameters must not run unless stopped"),
- )
+ calls: list[str] = []
+ monkeypatch.setattr(devbox_cli, "start_workspace", lambda name, verbose=False: calls.append("start"))
+ monkeypatch.setattr(devbox_cli, "update_workspace", lambda name, verbose=False: calls.append("update"))
monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
devbox_cli._start_existing_workspace(
- "devbox-test-user", {"latest_build": {"status": status}}, start_app=True, verbose=False
+ "devbox-test-user", {"latest_build": {"status": "stopped"}, "outdated": outdated}, verbose=False
)
- assert "was not applied" in capsys.readouterr().out
-
- def test_sync_never_forwards_immutable_workspace_region(self, monkeypatch: pytest.MonkeyPatch) -> None:
- """The pre-start sync must omit `workspace_region`.
-
- It is immutable; Coder carries it forward on its own and rejects any
- explicit value on `coder update` with "parameter is immutable and
- cannot be updated", which would break every resume of a region-aware
- box. Even for an eu-central-1 workspace, the region must not appear.
- """
- captured: dict[str, object] = {}
- monkeypatch.setattr(devbox_cli, "get_workspace_status", lambda ws: "stopped")
- monkeypatch.setattr(
- devbox_cli,
- "load_config",
- lambda: {"dotfiles_uri": "https://github.com/user/dotfiles"},
- )
- monkeypatch.setattr(
- devbox_cli,
- "update_workspace_parameters",
- lambda name, params: captured.update({"name": name, "params": params}),
- )
- monkeypatch.setattr(devbox_cli, "start_workspace", lambda name, verbose=False: None)
- monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
-
- workspace = {
- "latest_build": {
- "status": "stopped",
- "resources": [{"metadata": [{"key": coder.REGION_METADATA_KEY, "value": "eu-central-1"}]}],
- },
- }
- devbox_cli._start_existing_workspace("devbox-test-user", workspace, verbose=False)
+ assert calls == expected
- assert captured["params"] == {"dotfiles_uri": "https://github.com/user/dotfiles"}
- assert coder.WORKSPACE_REGION_PARAMETER not in captured["params"]
+ def test_start_app_flag_is_rejected_before_any_build(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ for build in ("start_workspace", "update_workspace"):
+ monkeypatch.setattr(devbox_cli, build, lambda name, verbose=False: pytest.fail("no build expected"))
- def test_skips_sync_for_running_workspace(self, monkeypatch: pytest.MonkeyPatch) -> None:
- calls: list[str] = []
-
- monkeypatch.setattr(devbox_cli, "get_workspace_status", lambda ws: "running")
- monkeypatch.setattr(
- devbox_cli,
- "load_config",
- lambda: {"git_name": "PostHog Engineer", "git_email": "[email protected]"},
- )
- monkeypatch.setattr(
- devbox_cli,
- "update_workspace_parameters",
- lambda name, params: calls.append("update_params"),
- )
- monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
-
- devbox_cli._start_existing_workspace("devbox-test-user", {"latest_build": {"status": "running"}}, verbose=False)
-
- assert calls == []
+ with pytest.raises(SystemExit):
+ devbox_cli._start_existing_workspace(
+ "devbox-test-user", {"latest_build": {"status": "stopped"}}, start_app=True, verbose=False
+ )
class TestDevboxList: