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 region support (#60320)

Raúl Negrón-Otero81ef404413fe
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 2d4ea7f165e4..f84021a1409c 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -24,11 +24,13 @@ from hogli.manifest import get_manifest
from .coder import (
CLAUDE_CODE_OAUTH_ENV,
DEFAULT_PRESET,
+ DEFAULT_REGION,
DEFAULT_TEMPLATE,
DOTFILES_URI_PARAMETER,
GIT_EMAIL_PARAMETER,
GIT_NAME_PARAMETER,
GIT_SIGNING_KEY_SECRET,
+ REGIONS,
_diagnose_unreachable_coder,
_fail,
coder_authenticated,
@@ -54,6 +56,7 @@ from .coder import (
get_sharing_status,
get_workspace,
get_workspace_name,
+ get_workspace_region,
get_workspace_status,
has_claude_oauth_secret,
list_coder_users,
@@ -86,9 +89,11 @@ from .config import (
DevboxConfig,
clear_dotfiles_uri,
clear_git_identity,
+ clear_region,
load_config,
save_dotfiles_uri,
save_git_identity,
+ save_region,
)
_LEGACY_KEYCHAIN_SERVICE = "posthog-claude-oauth-token"
@@ -116,7 +121,9 @@ WORKSPACE_STATUS_COLORS = {
PENDING_WORKSPACE_STATES = {"starting", "stopping", "deleting"}
-def resolve_workspace_name(workspace: str | None) -> tuple[str, list[dict[str, Any]] | None]:
+def resolve_workspace_name(
+ workspace: str | None, *, region: str | None = None
+) -> tuple[str, list[dict[str, Any]] | None]:
"""Resolve a workspace target into a full workspace name.
Supports:
@@ -127,20 +134,35 @@ def resolve_workspace_name(workspace: str | None) -> tuple[str, list[dict[str, A
Returns (name, workspaces) where workspaces is the already-fetched list
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
+ 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
+ silently masking existing workspaces created before the pref was set.
"""
+ effective_region = region if region is not None else _preferred_region()
if workspace is not None:
- return parse_workspace_target(workspace), None
+ target_name = parse_workspace_target(workspace, region=effective_region)
+ # Shared workspace targets (`@user[/label]`) are looked up against the
+ # remote owner, so cross-region label fallback is the owner's
+ # responsibility -- skip it here.
+ if workspace.startswith("@"):
+ return target_name, None
+ return _resolve_own_label(target_name)
workspaces = list_user_workspaces()
if len(workspaces) == 0:
- return get_workspace_name(), workspaces
+ return get_workspace_name(region=effective_region), workspaces
if len(workspaces) == 1:
return workspaces[0]["name"], workspaces
# Multiple workspaces -- prefer default
- default_name = get_workspace_name()
+ default_name = get_workspace_name(region=effective_region)
for ws in workspaces:
if ws.get("name") == default_name:
return default_name, workspaces
@@ -151,6 +173,25 @@ def resolve_workspace_name(workspace: str | None) -> tuple[str, list[dict[str, A
raise SystemExit(1) # unreachable; helps ty see the function doesn't fall through
+def _resolve_own_label(target_name: str) -> tuple[str, list[dict[str, Any]] | None]:
+ """Return ``(name, workspaces)`` for an own-label target, falling back across regions.
+
+ If ``target_name`` matches an existing workspace, return it directly.
+ Otherwise look for any of the user's workspaces with the same label and
+ return that. When no candidate exists, return ``target_name`` so the
+ downstream "not found" path runs with a stable name.
+ """
+ workspaces = list_user_workspaces()
+ if any(ws.get("name") == target_name for ws in workspaces):
+ return target_name, workspaces
+ label = extract_workspace_label(target_name)
+ if label is not None:
+ for ws in workspaces:
+ if extract_workspace_label(ws.get("name", "")) == label:
+ return ws["name"], workspaces
+ return target_name, workspaces
+
+
def _local_port_is_available(port: int) -> bool:
"""Return whether the given localhost TCP port can be bound."""
for host in ("127.0.0.1", "::1"):
@@ -497,6 +538,59 @@ def maybe_configure_git_signing(
click.echo("Restart any running devbox (`hogli devbox:restart`) to pick up the new gitconfig.")
+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.
+ """
+ saved = load_config().get("region")
+ return saved if saved in REGIONS else DEFAULT_REGION
+
+
+def maybe_configure_region(configure_region: bool | None) -> None:
+ """Optionally persist the preferred region for new devboxes.
+
+ The region is create-only on a workspace, so saving it locally just
+ pre-fills ``devbox:start --region`` and determines the default
+ workspace name (eu-central-1 boxes carry an ``-eu`` suffix). Existing
+ workspaces are untouched.
+ """
+ config = load_config()
+ existing_region = config.get("region")
+
+ if configure_region is False:
+ if not existing_region:
+ click.echo("Skipping region preference setup.")
+ return
+
+ if configure_region is None and existing_region:
+ return
+
+ click.echo()
+ click.echo(click.style("Preferred region", bold=True))
+ click.echo(" Choose which region new devboxes should land in.")
+ click.echo(" This is saved locally and used as the default for `hogli devbox:start`.")
+ if existing_region:
+ click.echo(f" Current: {existing_region}")
+ click.echo()
+
+ default_region = existing_region or DEFAULT_REGION
+ region = click.prompt(
+ "Preferred region",
+ default=default_region,
+ type=click.Choice(REGIONS),
+ show_choices=True,
+ show_default=True,
+ ).strip()
+
+ save_region(region)
+ click.echo(f"Saved preferred region: {region}")
+
+
def maybe_configure_dotfiles(configure_dotfiles: bool | None) -> None:
"""Optionally persist a dotfiles repo URL for new workspaces."""
config = load_config()
@@ -697,11 +791,22 @@ def _reset_git_identity() -> bool:
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()
+ clear_git_identity(config)
click.echo("Cleared saved Git identity. New workspaces will prompt for one.")
return True
+def _reset_region() -> bool:
+ """Drop the saved region preference. Returns True iff something was cleared."""
+ config = load_config()
+ if not config.get("region"):
+ click.echo("Nothing to clear: region preference was not set.")
+ return False
+ clear_region(config)
+ click.echo("Cleared saved region preference. New workspaces will use the built-in default.")
+ return True
+
+
def _reset_dotfiles() -> bool:
"""Drop the saved dotfiles URI and push an empty parameter to existing workspaces.
@@ -710,10 +815,11 @@ def _reset_dotfiles() -> bool:
Returns True iff something was cleared.
"""
- if not load_config().get("dotfiles_uri"):
+ config = load_config()
+ if not config.get("dotfiles_uri"):
click.echo("Nothing to clear: dotfiles was not set.")
return False
- clear_dotfiles_uri()
+ 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")
@@ -729,8 +835,9 @@ def _git_identity_status(config: DevboxConfig, _: set[str]) -> str | None:
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 _field_status(field: str) -> Callable[[DevboxConfig, set[str]], str | None]:
+ """Status reader that returns a single config field's value (or ``None``)."""
+ return lambda config, _: config.get(field)
def _secret_status(secret_name: str) -> Callable[[DevboxConfig, set[str]], str | None]:
@@ -772,11 +879,18 @@ _CONFIG_ITEMS: tuple[_ConfigItem, ...] = (
status=_secret_status(GIT_SIGNING_KEY_SECRET),
reset=lambda: _reset_user_secret(GIT_SIGNING_KEY_SECRET),
),
+ _ConfigItem(
+ cli_key="region",
+ label="Region",
+ needs_secrets=False,
+ status=_field_status("region"),
+ reset=_reset_region,
+ ),
_ConfigItem(
cli_key="dotfiles",
label="Dotfiles",
needs_secrets=False,
- status=_dotfiles_status,
+ status=_field_status("dotfiles_uri"),
reset=_reset_dotfiles,
),
_ConfigItem(
@@ -853,6 +967,7 @@ def _confirm_run_setup() -> bool:
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(" - Preferred region for new workspaces (optional)")
click.echo(" - Dotfiles repo for new workspaces (optional)")
click.echo(" - Claude OAuth token as a Coder user secret (optional)")
click.echo()
@@ -875,6 +990,11 @@ def _confirm_run_setup() -> bool:
default=None,
help="Propagate your local git signing key into Coder devboxes (reads git config user.signingkey)",
)
+ "--configure-region/--skip-configure-region",
+ default=None,
+ help="Prompt for the preferred region (us-east-1 or eu-central-1) for new devboxes",
+)
@click.option(
"--configure-dotfiles/--skip-configure-dotfiles",
default=None,
@@ -891,6 +1011,7 @@ def devbox_setup(
configure_ssh: bool | None,
configure_git_identity: bool | None,
configure_git_signing: bool | None,
+ configure_region: bool | None,
configure_dotfiles: bool | None,
configure_claude_setup: bool | None,
verbose: bool,
@@ -901,6 +1022,7 @@ def devbox_setup(
configure_ssh,
configure_git_identity,
configure_git_signing,
+ configure_region,
configure_dotfiles,
configure_claude_setup,
],
@@ -933,6 +1055,7 @@ def devbox_setup(
)
maybe_configure_git_identity(configure_git_identity)
maybe_configure_git_signing(configure_git_signing, known_secret_names=secret_names)
+ maybe_configure_region(configure_region)
maybe_configure_dotfiles(configure_dotfiles)
maybe_configure_claude_secret(configure_claude_setup, known_secret_names=secret_names)
print_setup_summary()
@@ -947,12 +1070,14 @@ def devbox_list() -> None:
if not workspaces:
click.echo("No devboxes found. Run 'hogli devbox:start' to create one.")
else:
- click.echo(f"{'LABEL':<16} {'STATUS':<12} {'NAME'}")
+ click.echo(f"{'LABEL':<16} {'STATUS':<12} {'REGION':<14} {'NAME'}")
for ws in workspaces:
ws_name = ws.get("name", "")
label = extract_workspace_label(ws_name) or "(default)"
status = get_workspace_status(ws)
- click.echo(f" {label:<14} {click.style(status, fg=_workspace_status_color(status)):<20} {ws_name}")
+ region = get_workspace_region(ws) or "unknown"
+ styled_status = click.style(status, fg=_workspace_status_color(status))
+ click.echo(f" {label:<14} {styled_status:<20} {region:<14} {ws_name}")
shared = list_shared_workspaces()
if shared:
@@ -1094,17 +1219,31 @@ def devbox_unshare(workspace: str | None, users: tuple[str, ...]) -> None:
show_default=True,
help="Coder template preset to apply (use 'none' to opt out)",
)
+ "--region",
+ 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."
+ ),
+)
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
def devbox_start(
workspace: str | None,
disk: str,
template: str,
preset: str,
+ region: str | None,
verbose: bool,
) -> None:
"""Start or create the remote devbox."""
ensure_runtime_ready()
- name, workspaces = resolve_workspace_name(workspace)
+ 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)
ws = get_workspace(name, workspaces)
if ws is not None:
@@ -1113,13 +1252,16 @@ def devbox_start(
config = load_config()
- click.echo(f"Creating devbox '{name}' (template={template}, preset={preset}, disk={disk}GiB)...")
+ click.echo(
+ f"Creating devbox '{name}' (template={template}, preset={preset}, region={effective_region}, disk={disk}GiB)..."
+ )
create_workspace(
name,
int(disk),
git_name=config.get("git_name"),
git_email=config.get("git_email"),
dotfiles_uri=config.get("dotfiles_uri"),
+ region=effective_region,
template=template,
preset=preset,
verbose=verbose,
@@ -1393,7 +1535,7 @@ 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``.
+ ``git-identity``, ``git-signing``, ``region``, ``dotfiles``, ``claude``.
"""
by_key = _config_items_by_key()
valid_keys = tuple(by_key)
@@ -1457,6 +1599,7 @@ def devbox_status(workspace: str | None) -> None:
click.echo(f" Name: {name}")
click.echo(f" Status: {click.style(status, fg=_workspace_status_color(status))}")
+ click.echo(f" Region: {get_workspace_region(ws) or 'unknown'}")
if ws.get("outdated"):
click.echo(click.style(" Update: template update available", fg="yellow"))
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index 8919a0fd72ef..e86da009f78e 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -45,6 +45,28 @@ DOTFILES_URI_PARAMETER = "dotfiles_uri"
DOTFILES_BRANCH_PARAMETER = "dotfiles_branch"
JETBRAINS_IDES_PARAMETER = "jetbrains_ides"
+# Create-time region selector. The template defines `workspace_region` with a
+# us-east-1 default; eu-central-1 only becomes a valid option once the EU
+# infrastructure is live. The chosen value is immutable after creation, so it
+# is forwarded on `coder create` only -- never on update or the parameter sync.
+# Valid values match the template contract exactly.
+WORKSPACE_REGION_PARAMETER = "workspace_region"
+REGIONS = ("us-east-1", "eu-central-1")
+DEFAULT_REGION = REGIONS[0]
+# Key of the workspace metadata item the template publishes the region back as.
+REGION_METADATA_KEY = "region"
+# Workspace-name suffix per region. us-east-1 is the historical default and
+# carries no suffix, so existing workspace names stay unchanged. Non-default
+# regions append `-{suffix}` at the end of the name so that a single user can
+# own one default workspace per region (`devbox-rauln` + `devbox-rauln-eu`)
+# without collision. Labels that conflict with a region suffix are rejected up
+# front -- see `_RESERVED_LABEL_SUFFIXES`.
+REGION_NAME_SUFFIXES: dict[str, str] = {
+ "us-east-1": "",
+ "eu-central-1": "eu",
+}
+_RESERVED_LABEL_SUFFIXES: tuple[str, ...] = tuple(s for s in REGION_NAME_SUFFIXES.values() if s)
+
# Per-user Coder secret holding the SSH public key used to sign commits inside
# workspaces. Injected as the POSTHOG_GIT_SIGNING_KEY env var on every workspace
# start (including coder task runs); the workspace template reads it to populate
@@ -935,18 +957,35 @@ def get_username() -> str:
)
-def get_workspace_name(label: str | None = None) -> str:
- """Derive workspace name from Coder username and optional label.
+def _validate_label(label: str) -> None:
+ """Reject labels that don't match the format or collide with a region suffix.
- Returns ``devbox-{username}`` for the default workspace, or
- ``devbox-{username}-{label}`` for a named workspace.
+ Region suffixes encode the workspace's region at the end of the name
+ (`devbox-rauln-eu`), so a label like `eu` or `foo-eu` would be
+ indistinguishable from a region-suffixed workspace once written to disk.
+ Rejecting at construction time is cheaper than parsing ambiguity later.
"""
- base = f"{_WORKSPACE_PREFIX}-{get_username()}"
- if label is None:
- return base
if not _LABEL_RE.match(label):
_fail(f"Invalid workspace label '{label}'. Use lowercase alphanumeric and hyphens.")
- return f"{base}-{label}"
+ for reserved in _RESERVED_LABEL_SUFFIXES:
+ if label == reserved or label.endswith(f"-{reserved}"):
+ _fail(f"Label '{label}' conflicts with the '-{reserved}' region suffix. Pick a different label.")
+
+
+def get_workspace_name(label: str | None = None, *, region: str = DEFAULT_REGION) -> str:
+ """Derive workspace name from Coder username, optional label, and region.
+
+ The default region is suffix-free for backward compatibility:
+ ``devbox-{username}`` (default) or ``devbox-{username}-{label}`` (labeled).
+ Non-default regions append a region suffix at the end: ``devbox-{username}-eu``
+ or ``devbox-{username}-{label}-eu``.
+ """
+ base = f"{_WORKSPACE_PREFIX}-{get_username()}"
+ suffix = REGION_NAME_SUFFIXES.get(region, "")
+ if label is None:
+ return f"{base}-{suffix}" if suffix else base
+ _validate_label(label)
+ return f"{base}-{label}-{suffix}" if suffix else f"{base}-{label}"
def get_default_workspace_prefix() -> str:
@@ -969,16 +1008,27 @@ def _list_workspaces() -> list[dict[str, Any]]:
def extract_workspace_label(workspace_name: str) -> str | None:
- """Extract the label suffix from a full workspace name.
+ """Extract the label portion of a full workspace name, stripping any region suffix.
- Returns ``None`` for the default workspace (no label).
+ Returns ``None`` for the default workspace in any region (``devbox-{user}``
+ or ``devbox-{user}-eu``). A trailing region suffix is stripped before the
+ label is read so ``devbox-{user}-api-eu`` -> ``api`` and ``devbox-{user}-eu``
+ -> ``None``. Labels that collide with a region suffix are rejected at
+ construction time (see ``_validate_label``), so parsing is unambiguous.
"""
prefix = get_default_workspace_prefix()
if workspace_name == prefix:
return None
- if workspace_name.startswith(f"{prefix}-"):
- return workspace_name[len(prefix) + 1 :]
- return None
+ if not workspace_name.startswith(f"{prefix}-"):
+ return None
+ rest = workspace_name[len(prefix) + 1 :]
+ for reserved in _RESERVED_LABEL_SUFFIXES:
+ if rest == reserved:
+ return None
+ if rest.endswith(f"-{reserved}"):
+ rest = rest[: -len(reserved) - 1]
+ break
+ return rest or None
def list_user_workspaces() -> list[dict[str, Any]]:
@@ -1001,6 +1051,24 @@ def get_workspace_status(workspace: dict[str, Any]) -> str:
return workspace.get("latest_build", {}).get("status", "unknown")
+def get_workspace_region(workspace: dict[str, Any]) -> str | None:
+ """Return the region a workspace lives in, or ``None`` when unknown.
+
+ The template publishes the region as a ``coder_metadata`` item (key
+ ``region``), which surfaces under ``latest_build.resources[].metadata[]``
+ in the ``coder list`` payload. Returns ``None`` for boxes created before
+ the metadata item existed so callers can render their own placeholder.
+ """
+ resources = workspace.get("latest_build", {}).get("resources", [])
+ for resource in resources:
+ for item in resource.get("metadata", []):
+ if isinstance(item, dict) and item.get("key") == REGION_METADATA_KEY:
+ value = item.get("value")
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
def _list_template_presets(template: str) -> list[str]:
"""Return preset names defined on the active version of ``template``, or [] on failure.
@@ -1061,6 +1129,7 @@ def create_workspace(
dotfiles_uri: str | None = None,
repo: str = "https://github.com/PostHog/posthog",
*,
+ region: str = DEFAULT_REGION,
template: str = DEFAULT_TEMPLATE,
preset: str = DEFAULT_PRESET,
verbose: bool = False,
@@ -1073,12 +1142,21 @@ def create_workspace(
forwarded parameter does not exist on the chosen template, coder errors
pre-provisioning and the retry loop drops the offending key.
+ ``region`` is forwarded as ``workspace_region``. On a template that does
+ not yet declare it, the retry loop drops it and the box lands in the
+ template default (us-east-1) -- so shipping this before the template
+ update is harmless. On a template that declares it but does not offer the
+ requested value yet (eu-central-1 before the EU infra is live), coder
+ rejects it as an invalid option, which is *not* the "parameter not
+ present" error, so the failure surfaces instead of silently falling back.
+
``preset`` is resolved against the template's actual presets via
``resolve_template_preset``; pass ``NO_PRESET`` to opt out.
"""
parameters: dict[str, str] = {
"disk_size": str(disk_size),
"repo": repo,
+ WORKSPACE_REGION_PARAMETER: region,
}
if git_name:
parameters[GIT_NAME_PARAMETER] = git_name
@@ -1391,8 +1469,13 @@ def delete_user_secret(name: str) -> subprocess.CompletedProcess[str]:
def resolve_shared_workspace_name(user: str, label: str | None = None) -> str:
"""Build a workspace name for another user's workspace.
- Returns ``devbox-{user}`` for the default workspace, or
- ``devbox-{user}-{label}`` for a labeled workspace.
+ Mirrors the default-region form of :func:`get_workspace_name`:
+ ``devbox-{user}`` for the default workspace, ``devbox-{user}-{label}``
+ for a labeled one. The caller's own region preference is intentionally
+ NOT applied -- the remote workspace's region is determined by its owner,
+ not the accessor, so a region suffix here would just guess wrong.
+ Callers needing a shared workspace in a non-default region should pass
+ the full workspace name via ``--name``.
"""
base = f"{_WORKSPACE_PREFIX}-{user}"
if label is None:
@@ -1400,13 +1483,17 @@ def resolve_shared_workspace_name(user: str, label: str | None = None) -> str:
return f"{base}-{label}"
-def parse_workspace_target(target: str) -> str:
+def parse_workspace_target(target: str, *, region: str = DEFAULT_REGION) -> str:
"""Parse a workspace target string into a full workspace name.
Supports:
- ``@user`` -> another user's default workspace
- ``@user/label`` -> another user's labeled workspace
- ``label`` -> current user's labeled workspace
+
+ ``region`` controls the region suffix applied to OWN labels only.
+ Shared targets (``@user[/label]``) ignore it -- see
+ :func:`resolve_shared_workspace_name`.
"""
if target.startswith("@"):
rest = target[1:]
@@ -1418,7 +1505,7 @@ def parse_workspace_target(target: str) -> str:
if not rest:
raise click.UsageError("Expected @user but got bare '@'.")
return resolve_shared_workspace_name(rest)
- return get_workspace_name(target)
+ return get_workspace_name(target, region=region)
def share_workspace(name: str, users: list[str], role: str = "use") -> None:
diff --git a/tools/hogli-commands/hogli_commands/devbox/config.py b/tools/hogli-commands/hogli_commands/devbox/config.py
index c9f036b4ab98..79d52cf407ba 100644
--- a/tools/hogli-commands/hogli_commands/devbox/config.py
+++ b/tools/hogli-commands/hogli_commands/devbox/config.py
@@ -11,9 +11,10 @@ class DevboxConfig(TypedDict, total=False):
git_name: str
git_email: str
dotfiles_uri: str
+ region: str
-_PERSISTED_FIELDS = ("git_name", "git_email", "dotfiles_uri")
+_PERSISTED_FIELDS = ("git_name", "git_email", "dotfiles_uri", "region")
def get_config_path() -> Path:
@@ -73,18 +74,46 @@ def save_dotfiles_uri(dotfiles_uri: str) -> DevboxConfig:
return config
-def clear_dotfiles_uri() -> DevboxConfig:
- """Remove any saved dotfiles repo URL so new workspaces don't clone one."""
- config = load_config()
+def clear_dotfiles_uri(config: DevboxConfig | None = None) -> DevboxConfig:
+ """Remove any saved dotfiles repo URL so new workspaces don't clone one.
+
+ Pass ``config`` to reuse an already-loaded dict and avoid a redundant disk read.
+ """
+ if config is None:
+ 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()
+def clear_git_identity(config: DevboxConfig | None = None) -> DevboxConfig:
+ """Remove any saved Git identity defaults for new workspaces.
+
+ Pass ``config`` to reuse an already-loaded dict and avoid a redundant disk read.
+ """
+ if config is None:
+ config = load_config()
config.pop("git_name", None)
config.pop("git_email", None)
save_config(config)
return config
+
+
+def save_region(region: str) -> DevboxConfig:
+ """Persist the preferred region for new workspaces."""
+ config = load_config()
+ config["region"] = region
+ save_config(config)
+ return config
+
+
+def clear_region(config: DevboxConfig | None = None) -> DevboxConfig:
+ """Drop the saved preferred region so new workspaces fall back to the built-in default.
+
+ Pass ``config`` to reuse an already-loaded dict and avoid a redundant disk read.
+ """
+ if config is None:
+ config = load_config()
+ config.pop("region", 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 9647d14617db..f9be7a0ce7c0 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -94,6 +94,40 @@ class TestDevboxConfig:
config = devbox_config.load_config()
assert config == {"dotfiles_uri": "https://github.com/user/dotfiles"}
+ def test_save_region_persists_alongside_other_fields(self, devbox_config_path: Path) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+ devbox_config.save_region("eu-central-1")
+
+ config = devbox_config.load_config()
+ assert config == {
+ "git_name": "PostHog Engineer",
+ "git_email": "[email protected]",
+ "region": "eu-central-1",
+ }
+
+ def test_clear_region_leaves_other_fields_intact(self, devbox_config_path: Path) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+ devbox_config.save_region("eu-central-1")
+
+ devbox_config.clear_region()
+
+ config = devbox_config.load_config()
+ assert config == {
+ "git_name": "PostHog Engineer",
+ "git_email": "[email protected]",
+ }
+
+ def test_clear_region_is_noop_when_unset(self, devbox_config_path: Path) -> None:
+ devbox_config.save_git_identity("PostHog Engineer", "[email protected]")
+
+ devbox_config.clear_region()
+
+ config = devbox_config.load_config()
+ assert config == {
+ "git_name": "PostHog Engineer",
+ "git_email": "[email protected]",
+ }
+
class TestUserSecrets:
"""Test the per-user Coder secret helpers used for Git signing."""
@@ -661,6 +695,126 @@ class TestWorkspaceNaming:
monkeypatch.setattr(coder, "get_username", lambda: "test-user")
assert coder.extract_workspace_label("other-workspace") is None
+ @pytest.mark.parametrize(
+ "label, region, expected",
+ [
+ (None, "us-east-1", "devbox-test-user"),
+ (None, "eu-central-1", "devbox-test-user-eu"),
+ ("api", "us-east-1", "devbox-test-user-api"),
+ ("api", "eu-central-1", "devbox-test-user-api-eu"),
+ ("my-project", "eu-central-1", "devbox-test-user-my-project-eu"),
+ ],
+ ids=["default-us", "default-eu", "labeled-us", "labeled-eu", "hyphenated-labeled-eu"],
+ )
+ def test_workspace_name_encodes_region_suffix(
+ self, monkeypatch: pytest.MonkeyPatch, label: str | None, region: str, expected: str
+ ) -> None:
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ assert coder.get_workspace_name(label, region=region) == expected
+
+ @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")
+ with pytest.raises(SystemExit):
+ coder.get_workspace_name(reserved)
+
+ @pytest.mark.parametrize(
+ "workspace_name, expected_label",
+ [
+ ("devbox-test-user-eu", None),
+ ("devbox-test-user-api-eu", "api"),
+ ("devbox-test-user-my-project-eu", "my-project"),
+ ],
+ ids=["region-only-default", "labeled-with-region", "hyphenated-label-with-region"],
+ )
+ def test_extract_label_strips_region_suffix(
+ self, monkeypatch: pytest.MonkeyPatch, workspace_name: str, expected_label: str | None
+ ) -> None:
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ assert coder.extract_workspace_label(workspace_name) == expected_label
+
+ @pytest.mark.parametrize(
+ "user, label, expected",
+ [
+ ("alice", None, "devbox-alice"),
+ ("alice", "api", "devbox-alice-api"),
+ ],
+ )
+ def test_shared_workspace_name_ignores_caller_region(self, user: str, label: str | None, expected: str) -> None:
+ # Shared workspace lookups never apply the caller's region pref:
+ # the remote workspace's region belongs to its owner.
+ assert coder.resolve_shared_workspace_name(user, label) == expected
+
+
+class TestWorkspaceRegion:
+ """Reading the region back from the workspace `region` metadata item."""
+
+ @pytest.mark.parametrize(
+ "workspace, expected",
+ [
+ # Region item present on a resource.
+ (
+ {"latest_build": {"resources": [{"metadata": [{"key": "region", "value": "eu-central-1"}]}]}},
+ "eu-central-1",
+ ),
+ # Region item sits among other metadata items.
+ (
+ {
+ "latest_build": {
+ "resources": [
+ {"metadata": [{"key": "cpu", "value": "8"}, {"key": "region", "value": "us-east-1"}]}
+ ]
+ }
+ },
+ "us-east-1",
+ ),
+ # Region item lives on a later resource.
+ (
+ {
+ "latest_build": {
+ "resources": [
+ {"metadata": [{"key": "cpu", "value": "8"}]},
+ {"metadata": [{"key": "region", "value": "us-east-1"}]},
+ ]
+ }
+ },
+ "us-east-1",
+ ),
+ # No metadata at all (box created before the item existed).
+ ({"latest_build": {"resources": [{"metadata": []}]}}, None),
+ ({"latest_build": {"resources": []}}, None),
+ ({"latest_build": {}}, None),
+ ({}, None),
+ # Empty value is treated as unknown.
+ (
+ {"latest_build": {"resources": [{"metadata": [{"key": "region", "value": ""}]}]}},
+ None,
+ ),
+ # Malformed metadata entries are ignored, not crashed on.
+ (
+ {
+ "latest_build": {
+ "resources": [{"metadata": ["not-a-dict", {"key": "region", "value": "us-east-1"}]}]
+ }
+ },
+ "us-east-1",
+ ),
+ ],
+ ids=[
+ "single-item",
+ "among-others",
+ "later-resource",
+ "empty-metadata",
+ "no-resources",
+ "no-build-resources",
+ "empty-payload",
+ "empty-value",
+ "malformed-entry-skipped",
+ ],
+ )
+ def test_get_workspace_region(self, workspace: dict[str, object], expected: str | None) -> None:
+ assert coder.get_workspace_region(workspace) == expected
+
def _parse_parameter_flags(args: list[str]) -> dict[str, str]:
"""Extract `key=value` pairs from `--parameter` flags in argv."""
@@ -694,6 +848,7 @@ def _stub_create_workspace(captured: dict[str, str | None]) -> Callable[..., Non
git_name: str | None = None,
git_email: str | None = None,
dotfiles_uri: str | None = None,
+ region: str = coder.DEFAULT_REGION,
template: str = coder.DEFAULT_TEMPLATE,
preset: str = coder.DEFAULT_PRESET,
verbose: bool = False,
@@ -705,6 +860,7 @@ def _stub_create_workspace(captured: dict[str, str | None]) -> Callable[..., Non
"git_name": git_name,
"git_email": git_email,
"dotfiles_uri": dotfiles_uri,
+ "region": region,
"template": template,
"preset": preset,
}
@@ -739,7 +895,7 @@ class TestWorkspaceCreation:
["Default (warm)", "Cold"],
"posthog-linux",
"Default (warm)",
- {"disk_size": "100", "repo": _REPO},
+ {"disk_size": "100", "repo": _REPO, "workspace_region": "us-east-1"},
),
(
{
@@ -753,6 +909,7 @@ class TestWorkspaceCreation:
{
"disk_size": "100",
"repo": _REPO,
+ "workspace_region": "us-east-1",
"git_name": "PostHog Engineer",
"git_email": "[email protected]",
"dotfiles_uri": _DOTFILES,
@@ -763,14 +920,14 @@ class TestWorkspaceCreation:
["Default (warm)"],
"posthog-microvm",
"Default (warm)",
- {"disk_size": "100", "repo": _REPO},
+ {"disk_size": "100", "repo": _REPO, "workspace_region": "us-east-1"},
),
(
{"preset": "none"},
["Default (warm)"],
"posthog-linux",
"none",
- {"disk_size": "100", "repo": _REPO},
+ {"disk_size": "100", "repo": _REPO, "workspace_region": "us-east-1"},
),
# Resolution fallback to "none" is exhaustively covered by
# TestTemplatePresetResolution; one case here is enough to prove
@@ -780,7 +937,15 @@ class TestWorkspaceCreation:
["Cold only"],
"posthog-microvm",
"none",
- {"disk_size": "100", "repo": _REPO},
+ {"disk_size": "100", "repo": _REPO, "workspace_region": "us-east-1"},
+ ),
+ # A non-default region is forwarded verbatim as workspace_region.
+ (
+ {"region": "eu-central-1"},
+ ["Default (warm)"],
+ "posthog-linux",
+ "Default (warm)",
+ {"disk_size": "100", "repo": _REPO, "workspace_region": "eu-central-1"},
),
],
ids=[
@@ -789,6 +954,7 @@ class TestWorkspaceCreation:
"custom-template",
"preset-opt-out",
"resolver-fallback-flows-through",
+ "explicit-region",
],
)
def test_create_workspace_forwards_params_and_template(
@@ -1030,12 +1196,59 @@ class TestResolveWorkspaceName:
def test_explicit_label(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
+ # Own-label resolution fetches the workspace list to allow cross-region
+ # fallback, so `workspaces` comes back populated even when the target
+ # isn't found.
name, workspaces = devbox_cli.resolve_workspace_name("api")
assert name == "devbox-test-user-api"
+ assert workspaces == []
+
+ def test_explicit_shared_label_skips_workspace_fetch(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Shared targets (`@user[/label]`) skip the own-workspace list call."""
+ calls: list[str] = []
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: calls.append("listed") or [])
+ name, workspaces = devbox_cli.resolve_workspace_name("@alice/api")
+ assert name == "devbox-alice-api"
assert workspaces is None
+ assert calls == []
+
+ def test_own_label_falls_back_to_cross_region_match(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """If preferred-region name doesn't exist, find a workspace with the same label in another region."""
+ 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-api"}], # us-region workspace, no -eu suffix
+ )
+ name, workspaces = devbox_cli.resolve_workspace_name("api")
+ # Preferred-region name would be `devbox-test-user-api-eu`; fallback finds the us workspace.
+ assert name == "devbox-test-user-api"
+ assert workspaces == [{"name": "devbox-test-user-api"}]
+
+ 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")
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_workspaces",
+ lambda: [{"name": "devbox-test-user-api"}, {"name": "devbox-test-user-api-eu"}],
+ )
+ name, _ = devbox_cli.resolve_workspace_name("api")
+ assert name == "devbox-test-user-api-eu"
+
+ def test_preferred_region_falls_back_when_saved_value_unknown(
+ self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path
+ ) -> None:
+ # Simulate a hand-edited config with a region that's no longer in REGIONS.
+ devbox_config_path.write_text(json.dumps({"region": "ap-southeast-2"}))
+ assert devbox_cli._preferred_region() == coder.DEFAULT_REGION
def test_no_workspaces_returns_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(devbox_cli, "get_workspace_name", lambda label=None: "devbox-test-user")
+ monkeypatch.setattr(
+ devbox_cli, "get_workspace_name", lambda label=None, region=coder.DEFAULT_REGION: "devbox-test-user"
+ )
monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
name, workspaces = devbox_cli.resolve_workspace_name(None)
assert name == "devbox-test-user"
@@ -1048,7 +1261,9 @@ class TestResolveWorkspaceName:
assert len(workspaces) == 1
def test_multiple_workspaces_prefers_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(devbox_cli, "get_workspace_name", lambda label=None: "devbox-test-user")
+ monkeypatch.setattr(
+ devbox_cli, "get_workspace_name", lambda label=None, region=coder.DEFAULT_REGION: "devbox-test-user"
+ )
monkeypatch.setattr(
devbox_cli,
"list_user_workspaces",
@@ -1059,7 +1274,9 @@ class TestResolveWorkspaceName:
assert len(workspaces) == 2
def test_multiple_workspaces_no_default_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(devbox_cli, "get_workspace_name", lambda label=None: "devbox-test-user")
+ monkeypatch.setattr(
+ devbox_cli, "get_workspace_name", lambda label=None, region=coder.DEFAULT_REGION: "devbox-test-user"
+ )
monkeypatch.setattr(
devbox_cli, "extract_workspace_label", lambda name: name.split("-", 2)[-1] if name.count("-") > 1 else None
)
@@ -1118,6 +1335,11 @@ class TestDevboxCommands:
"maybe_configure_git_signing",
lambda configure_git_signing, **kw: calls.append(f"signing:{configure_git_signing}"),
)
+ monkeypatch.setattr(
+ devbox_cli,
+ "maybe_configure_region",
+ lambda configure_region: calls.append(f"region:{configure_region}"),
+ )
monkeypatch.setattr(
devbox_cli,
"maybe_configure_dotfiles",
@@ -1137,6 +1359,7 @@ class TestDevboxCommands:
"--skip-configure-ssh",
"--skip-configure-git-identity",
"--skip-configure-git-signing",
+ "--skip-configure-region",
"--skip-configure-dotfiles",
"--skip-configure-claude",
],
@@ -1152,6 +1375,7 @@ class TestDevboxCommands:
"ssh:False",
"git:False",
"signing:False",
+ "region:False",
"dotfiles:False",
"claude:False",
"summary",
@@ -1171,6 +1395,7 @@ class TestDevboxCommands:
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_region", 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)
@@ -1201,6 +1426,7 @@ class TestDevboxCommands:
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, **kw: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_region", lambda configure_region: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda configure_dotfiles: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude, **kw: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
@@ -1236,6 +1462,7 @@ class TestDevboxCommands:
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, **kw: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_region", lambda configure_region: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda configure_dotfiles: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude, **kw: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
@@ -1254,7 +1481,7 @@ 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: ("devbox-test-user", []))
+ 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(devbox_cli, "load_config", lambda: {})
@@ -1269,6 +1496,7 @@ class TestDevboxCommands:
"git_name": None,
"git_email": None,
"dotfiles_uri": None,
+ "region": coder.DEFAULT_REGION,
"template": coder.DEFAULT_TEMPLATE,
"preset": coder.DEFAULT_PRESET,
}
@@ -1280,7 +1508,7 @@ class TestDevboxCommands:
monkeypatch.setattr(
devbox_cli,
"resolve_workspace_name",
- lambda ws: (f"devbox-test-user-{ws}" if ws else "devbox-test-user", []),
+ lambda ws, **kw: (f"devbox-test-user-{ws}" if ws else "devbox-test-user", []),
)
monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: "api")
@@ -1302,6 +1530,7 @@ class TestDevboxCommands:
assert captured["git_name"] == "PostHog Engineer"
assert captured["git_email"] == "[email protected]"
assert captured["dotfiles_uri"] == "https://github.com/user/dotfiles"
+ assert captured["region"] == coder.DEFAULT_REGION
assert captured["template"] == coder.DEFAULT_TEMPLATE
assert captured["preset"] == coder.DEFAULT_PRESET
assert "devbox:ssh api" in result.output
@@ -1310,7 +1539,7 @@ 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: ("devbox-test-user", []))
+ 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(devbox_cli, "load_config", lambda: {})
@@ -1326,7 +1555,7 @@ 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: ("devbox-test-user", []))
+ 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(devbox_cli, "load_config", lambda: {})
@@ -1337,11 +1566,77 @@ class TestDevboxCommands:
assert result.exit_code == 0, result.output
assert captured["preset"] == "none"
+ def test_devbox_start_forwards_region_flag(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ 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(devbox_cli, "load_config", lambda: {})
+ 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 captured["region"] == "eu-central-1"
+ assert "region=eu-central-1" in result.output
+
+ def test_devbox_start_rejects_unknown_region(self) -> None:
+ # click.Choice rejects the value during option parsing, before the
+ # command body runs, so no runtime collaborators need stubbing.
+ result = runner.invoke(cli, ["devbox:start", "--region", "ap-southeast-2"])
+
+ assert result.exit_code != 0
+ assert "ap-southeast-2" in result.output
+
+ def test_devbox_start_defaults_to_saved_region(
+ self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path
+ ) -> None:
+ """When no --region is given, devbox:start should honor the saved preference."""
+ devbox_config.save_region("eu-central-1")
+
+ captured: dict[str, str | None] = {}
+
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ # Real resolve_workspace_name so the -eu suffix gets applied.
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
+ monkeypatch.setattr(devbox_cli, "create_workspace", _stub_create_workspace(captured))
+
+ result = runner.invoke(cli, ["devbox:start"])
+
+ assert result.exit_code == 0, result.output
+ assert captured["region"] == "eu-central-1"
+ assert captured["name"] == "devbox-test-user-eu"
+ assert "region=eu-central-1" in result.output
+
+ def test_devbox_start_explicit_region_overrides_saved_preference(
+ self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path
+ ) -> None:
+ """An explicit --region flag should win over the saved preference for both region and name."""
+ devbox_config.save_region("us-east-1")
+
+ captured: dict[str, str | None] = {}
+
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "list_user_workspaces", lambda: [])
+ monkeypatch.setattr(coder, "get_username", lambda: "test-user")
+ monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
+ 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 captured["region"] == "eu-central-1"
+ assert captured["name"] == "devbox-test-user-eu"
+
def test_devbox_restart_calls_restart_workspace(self, monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, object] = {}
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1364,7 +1659,7 @@ class TestDevboxCommands:
captured: dict[str, object] = {}
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1387,7 +1682,7 @@ class TestDevboxCommands:
def test_devbox_update_skips_when_up_to_date(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1414,7 +1709,7 @@ class TestDevboxCommands:
def test_devbox_status_shows_update_hint_when_outdated(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1427,11 +1722,72 @@ class TestDevboxCommands:
assert result.exit_code == 0
assert "devbox:update" in result.output
+ @pytest.mark.parametrize(
+ "status, resources, expected",
+ [
+ (
+ "running",
+ [{"metadata": [{"key": "region", "value": "eu-central-1"}]}],
+ "Region: eu-central-1",
+ ),
+ ("stopped", [], "Region: unknown"),
+ ],
+ ids=["region-present", "region-absent"],
+ )
+ def test_devbox_status_shows_region(
+ self, monkeypatch: pytest.MonkeyPatch, status: str, resources: list, expected: 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: {"latest_build": {"status": status, "resources": resources}},
+ )
+ monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
+
+ result = runner.invoke(cli, ["devbox:status"])
+
+ assert result.exit_code == 0
+ assert expected in result.output
+
+ def test_devbox_list_shows_region_column(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_workspaces",
+ lambda: [
+ {
+ "name": "devbox-test-user",
+ "latest_build": {
+ "status": "running",
+ "resources": [{"metadata": [{"key": "region", "value": "eu-central-1"}]}],
+ },
+ },
+ {"name": "devbox-test-user-api", "latest_build": {"status": "stopped", "resources": []}},
+ ],
+ )
+ monkeypatch.setattr(devbox_cli, "list_shared_workspaces", lambda: [])
+ monkeypatch.setattr(devbox_cli, "get_shared_users", lambda name: [])
+ monkeypatch.setattr(
+ devbox_cli,
+ "extract_workspace_label",
+ lambda name: None if name == "devbox-test-user" else "api",
+ )
+
+ result = runner.invoke(cli, ["devbox:list"])
+
+ assert result.exit_code == 0
+ assert "REGION" in result.output
+ assert "eu-central-1" in result.output
+ # The box without region metadata renders the unknown placeholder.
+ assert "unknown" in result.output
+
def test_devbox_forward_forwards_when_local_port_is_available(self, monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, object] = {}
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(devbox_cli, "_local_port_is_available", lambda port: True)
monkeypatch.setattr(
devbox_cli,
@@ -1449,7 +1805,7 @@ class TestDevboxCommands:
def test_devbox_forward_fails_early_when_local_port_is_in_use(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(devbox_cli, "_local_port_is_available", lambda port: False)
result = runner.invoke(cli, ["devbox:forward", "--port", "8010"])
@@ -1474,6 +1830,7 @@ def stub_setup_environment(monkeypatch: pytest.MonkeyPatch) -> 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_region", 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)
@@ -1573,6 +1930,33 @@ class TestDevboxConfigCommands:
assert devbox_config.load_config() == {"dotfiles_uri": "https://github.com/user/dotfiles"}
assert "Cleared saved Git identity" in result.output
+ def test_rm_region_clears_only_region(
+ self,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config.save_git_identity("Eng", "[email protected]")
+ devbox_config.save_region("eu-central-1")
+
+ result = runner.invoke(cli, ["devbox:config:rm", "region"])
+
+ assert result.exit_code == 0, result.output
+ assert devbox_config.load_config() == {"git_name": "Eng", "git_email": "[email protected]"}
+ assert "Cleared saved region preference" in result.output
+
+ def test_show_renders_saved_region(
+ self,
+ devbox_config_path: Path,
+ stub_config_runtime: None,
+ ) -> None:
+ devbox_config.save_region("eu-central-1")
+
+ result = runner.invoke(cli, ["devbox:config:show"])
+
+ assert result.exit_code == 0
+ assert "Region" in result.output
+ assert "eu-central-1" in result.output
+
@pytest.mark.parametrize(
"key,expected_secret",
[
@@ -1648,6 +2032,7 @@ class TestDevboxConfigCommands:
assert result.exit_code != 0
assert "git-identity" in result.output
assert "git-signing" in result.output
+ assert "region" in result.output
assert "dotfiles" in result.output
assert "claude" in result.output
@@ -1911,7 +2296,7 @@ class TestDevboxShare:
captured: dict[str, object] = {}
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1934,7 +2319,7 @@ class TestDevboxShare:
captured: dict[str, object] = {}
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1955,7 +2340,7 @@ class TestDevboxShare:
def test_unshare_without_user_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1977,7 +2362,7 @@ class TestDevboxShare:
def test_share_list_shows_status(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -1997,7 +2382,7 @@ class TestDevboxShare:
def test_share_without_user_errors(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
- monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws: ("devbox-test-user", []))
+ monkeypatch.setattr(devbox_cli, "resolve_workspace_name", lambda ws, **kw: ("devbox-test-user", []))
monkeypatch.setattr(
devbox_cli,
"get_workspace",
@@ -2114,6 +2499,59 @@ class TestCoderUserSecrets:
assert captured == [["coder", "secret", "delete", "CLAUDE_CODE_OAUTH_TOKEN", "--yes"]]
+class TestSetupRegion:
+ """Test the region-preference step in devbox:setup."""
+
+ def test_skip_flag_short_circuits(self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path) -> None:
+ echoed: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
+
+ devbox_cli.maybe_configure_region(False)
+
+ assert any("Skipping region" in line for line in echoed)
+ assert devbox_config.load_config().get("region") is None
+
+ def test_skip_flag_silent_when_already_set(self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path) -> None:
+ devbox_config.save_region("eu-central-1")
+ echoed: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
+
+ devbox_cli.maybe_configure_region(False)
+
+ # The compact status block at the top of devbox_setup owns the
+ # "already set" line, so this helper stays silent.
+ assert echoed == []
+ assert devbox_config.load_config()["region"] == "eu-central-1"
+
+ def test_skips_when_region_already_saved_and_no_explicit_flag(
+ self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path
+ ) -> None:
+ devbox_config.save_region("eu-central-1")
+ prompts: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "prompt", lambda *a, **kw: prompts.append("called") or "")
+
+ devbox_cli.maybe_configure_region(None)
+
+ assert prompts == []
+
+ def test_prompts_and_persists_when_unset(self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path) -> None:
+ monkeypatch.setattr(devbox_cli.click, "prompt", lambda *a, **kw: "eu-central-1")
+
+ devbox_cli.maybe_configure_region(None)
+
+ assert devbox_config.load_config()["region"] == "eu-central-1"
+
+ def test_explicit_configure_flag_reprompts_even_when_set(
+ self, monkeypatch: pytest.MonkeyPatch, devbox_config_path: Path
+ ) -> None:
+ devbox_config.save_region("us-east-1")
+ monkeypatch.setattr(devbox_cli.click, "prompt", lambda *a, **kw: "eu-central-1")
+
+ devbox_cli.maybe_configure_region(True)
+
+ assert devbox_config.load_config()["region"] == "eu-central-1"
+
+
class TestSetupClaudeSecret:
"""Test the Claude user-secret step in devbox:setup."""