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): region-aware devbox:start resolution (#62999)

Raúl Negrón-Otero1f3ae7042ce6
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index b68c4849d322..e2d076f28cfa 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -74,6 +74,7 @@ from .coder import (
parse_workspace_target,
port_forward_replace,
print_setup_summary,
+ region_from_workspace_name,
restart_workspace,
server_supports_user_secrets,
share_workspace,
@@ -143,11 +144,13 @@ def resolve_workspace_name(
when available, so callers can skip a second ``_list_workspaces`` call.
``region`` controls the region suffix used when constructing names for
- workspaces that don't exist yet (e.g. ``devbox:start --region``). When
+ workspaces that don't exist yet (a bare ``devbox:start --region`` bypasses
+ this resolver and targets the region's default name directly). When
resolving an OWN label against the user's actual workspaces, the region
suffix is treated as a preference, not a constraint: if the preferred
name doesn't exist but a workspace with the same label exists in another
- region, that one is returned. This keeps a saved region pref from
+ region, that one is returned. The same fallback applies to the default
+ workspace in the multi-box case. This keeps a saved region pref from
silently masking existing workspaces created before the pref was set.
"""
effective_region = region if region is not None else _preferred_region()
@@ -168,10 +171,13 @@ def resolve_workspace_name(
if len(workspaces) == 1:
return workspaces[0]["name"], workspaces
- # Multiple workspaces -- prefer default
- default_name = get_workspace_name(region=effective_region)
- for ws in workspaces:
- if ws.get("name") == default_name:
+ # Multiple workspaces -- prefer the effective region's default, then
+ # defaults in other regions (a region pref should not mask the box the
+ # user actually has -- same philosophy as the label fallback above).
+ existing_names = {ws.get("name") for ws in workspaces}
+ for candidate_region in (effective_region, *(r for r in REGIONS if r != effective_region)):
+ default_name = get_workspace_name(region=candidate_region)
+ if default_name in existing_names:
return default_name, workspaces
# No default among multiple -- require explicit workspace argument
@@ -599,17 +605,25 @@ def maybe_configure_git_signing(
click.echo("Restart any running devbox (`hogli devbox:restart`) to pick up the new gitconfig.")
+def _saved_region() -> str | None:
+ """Return the saved region preference, or ``None`` when absent or invalid.
+
+ A persisted value that's no longer in ``REGIONS`` (e.g. a stale entry
+ from a hand-edited config) reads as unset instead of poisoning every
+ downstream lookup.
+ """
+ saved = load_config().get("region")
+ return saved if saved in REGIONS else None
+
+
def _preferred_region() -> str:
"""Return the saved preferred region, falling back to ``DEFAULT_REGION``.
Centralized so every command path that needs the user's region
preference reads the same value -- and so the fallback to the built-in
- default lives in one place. A persisted value that's no longer in
- ``REGIONS`` (e.g. a stale entry from a hand-edited config) falls back
- to ``DEFAULT_REGION`` instead of poisoning every downstream lookup.
+ default lives in one place.
"""
- saved = load_config().get("region")
- return saved if saved in REGIONS else DEFAULT_REGION
+ return _saved_region() or DEFAULT_REGION
def maybe_configure_region(configure_region: bool | None) -> None:
@@ -1270,6 +1284,24 @@ def devbox_unshare(workspace: str | None, users: tuple[str, ...]) -> None:
click.echo(click.style("Restart your devbox for this to take effect.", fg="yellow"))
+def _maybe_hint_region_mismatch(name: str) -> None:
+ """On resuming a default box outside the saved region pref, say how to get one there.
+
+ Quiet for labeled boxes -- the pref only governs the default box. Callers
+ gate on a bare invocation (a label or ``--region`` is already a deliberate
+ choice).
+ """
+ saved = _saved_region()
+ if saved is None or extract_workspace_label(name) is not None:
+ return
+ box_region = region_from_workspace_name(name)
+ if box_region != saved:
+ click.echo(
+ f"Your devbox '{name}' is in {box_region}, but your saved region is {saved}. "
+ f"Create a {saved} devbox with `hogli devbox:start --region {saved}`."
+ )
+
+
@click.command(name="devbox:start", help="Start or create your remote devbox")
@workspace_argument
@click.option(
@@ -1297,8 +1329,9 @@ def devbox_unshare(workspace: str | None, users: tuple[str, ...]) -> None:
type=click.Choice(REGIONS),
default=None,
help=(
- "Region to create the devbox in (set once at creation, cannot be changed later). "
- "Defaults to the value saved by `devbox:setup --configure-region`, then us-east-1."
+ "Region whose default devbox to start, creating it if needed (a devbox's region is "
+ "set at creation and cannot change). Defaults to the value saved by "
+ "`devbox:setup --configure-region`, then us-east-1."
),
)
@click.option(
@@ -1323,13 +1356,20 @@ def devbox_start(
"""Start or create the remote devbox."""
ensure_runtime_ready()
effective_region = region or _preferred_region()
- # Thread the effective region into name resolution so an explicit
- # --region overrides the saved preference for both the new workspace's
- # region AND its `-eu` name suffix.
- name, workspaces = resolve_workspace_name(workspace, region=effective_region)
+ if workspace is None and region is not None:
+ # An explicit --region targets that region's default directly, so it
+ # can be created (or resumed) regardless of boxes in other regions.
+ name = get_workspace_name(region=effective_region)
+ workspaces: list[dict[str, Any]] | None = list_user_workspaces()
+ else:
+ # Resolution prefers the effective region's default but falls back to
+ # the box the user already has -- a saved pref alone never abandons it.
+ name, workspaces = resolve_workspace_name(workspace, region=effective_region)
ws = get_workspace(name, workspaces)
if ws is not None:
+ if workspace is None and region is None:
+ _maybe_hint_region_mismatch(name)
_start_existing_workspace(name, ws, start_app=start_app, verbose=verbose)
return
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index 08fef8d529cd..303767df6791 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -14,6 +14,7 @@ import json
import shlex
import shutil
import socket
+import functools
import itertools
import threading
import subprocess
@@ -956,8 +957,14 @@ def get_default_git_identity() -> tuple[str | None, str | None]:
return git_name, git_email
def get_username() -> str:
- """Get current Coder username."""
+ """Get current Coder username (cached -- it cannot change within one invocation).
+
+ Every helper that builds or parses workspace names calls this, and each
+ uncached call is a `coder` subprocess. Failures raise instead of caching,
+ so an auth retry within the same process still re-probes.
+ """
user_info = get_coder_user_info()
username = _first_non_empty_string(user_info.get("username"))
if username:
@@ -1043,6 +1050,20 @@ def extract_workspace_label(workspace_name: str) -> str | None:
return rest or None
+def region_from_workspace_name(workspace_name: str) -> str:
+ """Return the region a workspace name encodes via its suffix.
+
+ The name is authoritative -- non-default regions carry a `-{suffix}` and
+ the suffix-free form is the default region (see ``REGION_NAME_SUFFIXES``).
+ Unlike ``get_workspace_region`` this needs no live ``coder`` metadata, so it
+ is correct even for boxes created before the region metadata item existed.
+ """
+ for region, suffix in REGION_NAME_SUFFIXES.items():
+ if suffix and workspace_name.endswith(f"-{suffix}"):
+ return region
+ return DEFAULT_REGION
+
+
def list_user_workspaces() -> list[dict[str, Any]]:
"""Return all workspaces belonging to the current user with the devbox prefix."""
prefix = get_default_workspace_prefix()
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index 7100dfb40b59..06a1b2e8a2c1 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -716,6 +716,19 @@ class TestWorkspaceNaming:
monkeypatch.setattr(coder, "get_username", lambda: "test-user")
assert coder.get_workspace_name(label, region=region) == expected
+ @pytest.mark.parametrize(
+ "workspace_name, expected_region",
+ [
+ ("devbox-test-user", "us-east-1"),
+ ("devbox-test-user-api", "us-east-1"),
+ ("devbox-test-user-eu", "eu-central-1"),
+ ("devbox-test-user-api-eu", "eu-central-1"),
+ ],
+ ids=["default-us", "labeled-us", "default-eu", "labeled-eu"],
+ )
+ def test_region_from_workspace_name(self, workspace_name: str, expected_region: str) -> None:
+ assert coder.region_from_workspace_name(workspace_name) == expected_region
+
@pytest.mark.parametrize("reserved", ["eu", "api-eu", "foo-eu"])
def test_label_colliding_with_region_suffix_rejected(self, monkeypatch: pytest.MonkeyPatch, reserved: str) -> None:
monkeypatch.setattr(coder, "get_username", lambda: "test-user")
@@ -1253,6 +1266,18 @@ class TestResolveWorkspaceName:
assert name == "devbox-test-user-api"
assert workspaces == [{"name": "devbox-test-user-api"}]
+ def test_multiple_workspaces_falls_back_to_other_region_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """With no default in the preferred region, the other region's default wins over failing."""
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_cli, "_preferred_region", lambda: "eu-central-1")
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_workspaces",
+ lambda: [{"name": "devbox-test-user"}, {"name": "devbox-test-user-api"}],
+ )
+ name, _ = devbox_cli.resolve_workspace_name(None)
+ assert name == "devbox-test-user"
+
def test_own_label_prefers_preferred_region_when_both_exist(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(coder, "get_username", lambda: "test-user")
monkeypatch.setattr(devbox_cli, "_preferred_region", lambda: "eu-central-1")
@@ -1597,9 +1622,8 @@ class TestDevboxCommands:
captured: dict[str, str | None] = {}
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
- monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
- monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
monkeypatch.setattr(devbox_cli, "load_config", lambda: {})
monkeypatch.setattr(devbox_cli, "create_workspace", _stub_create_workspace(captured))
@@ -1681,6 +1705,106 @@ class TestDevboxCommands:
assert captured["region"] == "eu-central-1"
assert captured["name"] == "devbox-test-user-eu"
+ @pytest.mark.parametrize(
+ "saved_region, boxes, expected_resumed, expected_hint",
+ [
+ (None, ["devbox-test-user"], "devbox-test-user", None),
+ (None, ["devbox-test-user-eu"], "devbox-test-user-eu", None),
+ (
+ "eu-central-1",
+ ["devbox-test-user"],
+ "devbox-test-user",
+ "hogli devbox:start --region eu-central-1",
+ ),
+ (
+ "eu-central-1",
+ ["devbox-test-user", "devbox-test-user-api"],
+ "devbox-test-user",
+ "hogli devbox:start --region eu-central-1",
+ ),
+ ],
+ ids=["matching-region", "other-region-no-pref", "other-region-with-pref", "multi-box-other-region-default"],
+ )
+ def test_devbox_start_bare_resumes_existing_box(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ devbox_config_path: Path,
+ saved_region: str | None,
+ boxes: list[str],
+ expected_resumed: str,
+ expected_hint: str | None,
+ ) -> None:
+ """A bare start resumes the box the user has -- a saved pref alone never abandons it.
+
+ When the resumed default is outside the saved pref, a hint says how to
+ create one there explicitly; otherwise no hint is printed.
+ """
+ if saved_region is not None:
+ devbox_config.save_region(saved_region)
+
+ captured: dict[str, str | None] = {}
+ resumed: list[str] = []
+
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_workspaces",
+ lambda: [{"name": name, "latest_build": {"status": "stopped"}} for name in boxes],
+ )
+ monkeypatch.setattr(
+ devbox_cli,
+ "_start_existing_workspace",
+ lambda name, ws, start_app=None, verbose=False: resumed.append(name),
+ )
+ monkeypatch.setattr(devbox_cli, "create_workspace", _stub_create_workspace(captured))
+
+ result = runner.invoke(cli, ["devbox:start"])
+
+ assert result.exit_code == 0, result.output
+ assert resumed == [expected_resumed]
+ assert captured == {}
+ if expected_hint is None:
+ assert "--region" not in result.output
+ else:
+ assert expected_hint in result.output
+
+ @pytest.mark.parametrize(
+ "existing_boxes",
+ [
+ ["devbox-test-user"],
+ ["devbox-test-user", "devbox-test-user-api"],
+ ],
+ ids=["single-box", "multiple-boxes"],
+ )
+ def test_devbox_start_explicit_region_creates_default_alongside_existing_boxes(
+ self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path, existing_boxes: list[str]
+ ) -> None:
+ """`--region` targets that region's default directly, creating it even when other boxes exist."""
+ captured: dict[str, str | None] = {}
+ resumed: list[str] = []
+
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_workspaces",
+ lambda: [{"name": name, "latest_build": {"status": "stopped"}} for name in existing_boxes],
+ )
+ monkeypatch.setattr(
+ devbox_cli,
+ "_start_existing_workspace",
+ lambda name, ws, start_app=None, verbose=False: resumed.append(name),
+ )
+ monkeypatch.setattr(devbox_cli, "create_workspace", _stub_create_workspace(captured))
+
+ result = runner.invoke(cli, ["devbox:start", "--region", "eu-central-1"])
+
+ assert result.exit_code == 0, result.output
+ assert resumed == []
+ assert captured["name"] == "devbox-test-user-eu"
+ assert captured["region"] == "eu-central-1"
+
def test_devbox_restart_calls_restart_workspace(self, monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, object] = {}