diff --git a/bin/omarchy-agent-account-copy b/bin/omarchy-agent-account-copy index c50fdafe762a..f9e56e415b75 100755 --- a/bin/omarchy-agent-account-copy +++ b/bin/omarchy-agent-account-copy @@ -11,7 +11,7 @@ host="" providers=() while (( $# > 0 )); do case "$1" in - --replace) replace=" --replace" ;; + --replace) replace=1 ;; --*) echo "Unknown account-copy option: $1" >&2 exit 1 @@ -34,6 +34,7 @@ fi # Finish the export before connecting, so invalid input never reaches SSH. # The credentials stay in memory and stdin, never in command arguments. -payload=$(omarchy-agent-account-transfer export "${providers[@]}") +payload=$(omarchy-agent-account-transfer bundle "${providers[@]}") +receiver=$(omarchy-agent-account-transfer receiver-command ${replace:+--replace}) # Disable terminal allocation so SSH cannot echo the credential stream. -printf '%s\n' "$payload" | ssh -T -- "$host" "omarchy-agent-account-transfer import$replace" +printf '%s\n' "$payload" | ssh -T -- "$host" "$receiver" diff --git a/bin/omarchy-agent-account-transfer b/bin/omarchy-agent-account-transfer index bf5143233a9d..dc48fc982358 100755 --- a/bin/omarchy-agent-account-transfer +++ b/bin/omarchy-agent-account-transfer @@ -1,6 +1,6 @@ #!/usr/bin/python3 # omarchy:summary=Export or import subscription account credentials for SSH transfer -# omarchy:args= [--replace] [claude|codex|grok...] +# omarchy:args= [--replace] [claude|codex|grok...] # omarchy:hidden=true """The private, versioned stream behind account copy. Never log its payload.""" @@ -11,17 +11,23 @@ import importlib.util import json import os import re +import shlex import shutil import subprocess import sys import tempfile +import uuid from pathlib import Path from typing import Any -loader = importlib.machinery.SourceFileLoader("accounts", str(Path(os.environ["OMARCHY_PATH"]) / "bin/omarchy-agent-account-state")) -spec = importlib.util.spec_from_loader(loader.name, loader) -accounts = importlib.util.module_from_spec(spec) -loader.exec_module(accounts) +# SSH supplies the matching backend in memory on older destinations. +if "_omarchy_account_state" in sys.modules: + accounts = sys.modules["_omarchy_account_state"] +else: + loader = importlib.machinery.SourceFileLoader("accounts", str(Path(os.environ["OMARCHY_PATH"]) / "bin/omarchy-agent-account-state")) + spec = importlib.util.spec_from_loader(loader.name, loader) + accounts = importlib.util.module_from_spec(spec) + loader.exec_module(accounts) FILES = { "claude": {".credentials.json", ".claude.json"}, @@ -29,6 +35,47 @@ FILES = { "grok": {"auth.json", "settings_cache.json"}, } MAX_STREAM = 8 * 1024 * 1024 +MAX_BUNDLE = MAX_STREAM + 1024 * 1024 + +# Only this fixed bootstrap goes in SSH's command arguments. Code and +# credentials arrive over stdin, and no receiver files are installed. +RECEIVER_BOOTSTRAP = '''import io, json, os, pathlib, shutil, subprocess, sys, types +raw = sys.stdin.buffer.read(__MAX_BUNDLE__ + 1) +if len(raw) > __MAX_BUNDLE__: + sys.exit("Account copy failed: receiver bundle is too large") +try: + bundle = json.loads(raw) +except (ValueError, UnicodeError): + sys.exit("Account copy failed: invalid receiver bundle") +if not isinstance(bundle, dict) or bundle.get("version") != 1 or not all(isinstance(bundle.get(k), str) for k in ("backend", "receiver")): + sys.exit("Account copy failed: invalid receiver bundle") +installed = shutil.which("omarchy-agent-account-transfer") +use_installed = bool(installed) +local_backend = None +if installed and (bundle.get("accounts") or {}).get("namePolicy") == "source": + probe = subprocess.run([installed, "capabilities"], stdin=subprocess.DEVNULL, capture_output=True) + try: + capabilities = json.loads(probe.stdout) if probe.returncode == 0 else {} + except ValueError: + capabilities = {} + use_installed = isinstance(capabilities, dict) and capabilities.get("sourceNames") is True + if not use_installed: + root = os.environ.get("OMARCHY_PATH") + local_backend = pathlib.Path(root) / "bin/omarchy-agent-account-state" if root else None + if local_backend is None or not local_backend.is_file(): + sys.exit("Account copy failed: destination account backend is unavailable") +if use_installed: + result = subprocess.run([installed, "import", *sys.argv[1:]], input=json.dumps(bundle.get("accounts")).encode()) + sys.exit(result.returncode) +for name, field in (("_omarchy_account_state", "backend"), ("_omarchy_account_transfer", "receiver")): + module = types.ModuleType(name) + module.__file__ = "" + sys.modules[name] = module + source = local_backend.read_text() if field == "backend" and local_backend else bundle[field] + exec(compile(source, module.__file__, "exec"), module.__dict__) +sys.stdin = io.TextIOWrapper(io.BytesIO(json.dumps(bundle.get("accounts")).encode())) +sys.exit(module.main(["import", *sys.argv[1:]])) +'''.replace("__MAX_BUNDLE__", str(MAX_BUNDLE)) def login_files(provider: str, home: Path) -> dict[str, Any]: @@ -43,7 +90,7 @@ def login_files(provider: str, home: Path) -> dict[str, Any]: def export_accounts(providers: list[str]) -> dict[str, Any]: - payload = {"version": 1, "providers": {}} + payload = {"version": 1, "namePolicy": "source", "providers": {}} for provider in providers: if provider not in FILES: raise accounts.AccountError(f"Unknown subscription provider: {provider}") @@ -71,11 +118,17 @@ def validate(payload: Any) -> None: if not isinstance(registry.get("active"), str) or registry.get("switch") not in accounts.SWITCH_MODES or type(registry.get("threshold")) is not int or not 50 <= registry["threshold"] <= 100: raise accounts.AccountError("Invalid account transfer preferences") ids = set() + identities = set() for entry in registry["accounts"]: if not isinstance(entry, dict) or not all(isinstance(entry.get(k), str) and entry[k] for k in ("id", "label", "accountId")): raise accounts.AccountError("Invalid account transfer identity") + if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", entry["id"]) or entry["id"] in accounts.RESERVED_IDS: + raise accounts.AccountError("Invalid account transfer ID") if type(entry.get("primary")) is not bool or entry["id"] in ids: raise accounts.AccountError("Invalid account transfer account") + if entry["accountId"] in identities: + raise accounts.AccountError("Duplicate account transfer identity") + identities.add(entry["accountId"]) ids.add(entry["id"]) files = entry.get("files") if not isinstance(files, dict) or not files or not set(files) <= FILES[provider] or not all(isinstance(v, dict) for v in files.values()): @@ -164,24 +217,52 @@ def unique_label(registry: dict[str, Any], label: str) -> str: return candidate +def match_source_names(provider: str, registry: dict[str, Any], copied: list[tuple[dict[str, Any], dict[str, Any]]]) -> None: + active = accounts.active(registry) + copied_objects = {id(account) for _, account in copied} + source_ids = {entry["id"] for entry, _ in copied} + source_labels = {entry["label"] for entry, _ in copied} + # Free the imported ids together, so swaps cannot force numeric suffixes. + for entry, account in copied: + account["id"] = "copy-name-" + uuid.uuid4().hex + account["label"] = entry["label"] + for account in registry["accounts"]: + if id(account) in copied_objects: + continue + if account["label"] in source_labels: + account["label"] = unique_label(registry, account["label"]) + if account["id"] in source_ids: + base = accounts.slug(account["label"]) or "account" + candidate, suffix = base, 2 + while candidate in source_ids or candidate in accounts.RESERVED_IDS or any( + other is not account and other["id"] == candidate for other in registry["accounts"] + ): + candidate, suffix = f"{base}-{suffix}", suffix + 1 + account["id"] = candidate + for entry, account in copied: + account["id"] = entry["id"] + # The selected account stays selected, even when its id changes. + registry["active"] = active["id"] + + def import_provider(provider: str, incoming: dict[str, Any], replace: bool) -> list[str]: accounts.recover(provider) backups = {} backup_dirs = [] created = [] results = [] + copied = [] try: with accounts.Locked(provider) as registry: for a in registry["accounts"]: for name in FILES[provider]: cleanup_transfers(file_path(provider, accounts.account_home(provider, a), name).parent) was_empty = not any(accounts.identity(provider, accounts.account_home(provider, a))["accountId"] and login_files(provider, accounts.account_home(provider, a)) for a in registry["accounts"]) - mapped = {} for entry in incoming["accounts"]: existing = next((a for a in registry["accounts"] if accounts.identity(provider, accounts.account_home(provider, a))["accountId"] == entry["accountId"]), None) if existing and login_files(provider, accounts.account_home(provider, existing)) and not replace: - mapped[entry["id"]] = existing["id"] - results.append(f"{accounts.PROVIDERS[provider]['name']}: kept {existing['label']} (already present)") + copied.append((entry, existing)) + results.append(("kept", existing)) continue primary = next(a for a in registry["accounts"] if a.get("primary")) if existing is None and entry.get("primary") and not saved_credentials(provider, accounts.primary_home(provider)): @@ -194,7 +275,7 @@ def import_provider(provider: str, incoming: dict[str, Any], replace: bool) -> l if was_empty and account.get("primary"): account["label"] = entry["label"] else: - label = unique_label(registry, entry["label"]) + label = entry["label"] account_id = accounts.unique_id(provider, registry, label) home = accounts.accounts_root() / provider / account_id home.mkdir(parents=True, mode=0o700) @@ -231,8 +312,10 @@ def import_provider(provider: str, incoming: dict[str, Any], replace: bool) -> l accounts.link_shared(provider, home) accounts.carry_settings(provider, home) account.update(found) - mapped[entry["id"]] = account["id"] - results.append(f"{accounts.PROVIDERS[provider]['name']}: copied {account['label']} ({found['email']})") + copied.append((entry, account)) + results.append(("copied", account)) + match_source_names(provider, registry, copied) + mapped = {entry["id"]: account["id"] for entry, account in copied} if was_empty: registry["active"] = mapped.get(incoming.get("active"), registry["active"]) if incoming.get("switch") in accounts.SWITCH_MODES: @@ -254,14 +337,40 @@ def import_provider(provider: str, incoming: dict[str, Any], replace: bool) -> l (home / accounts.LOGIN_RECEIPT).unlink(missing_ok=True) for folder in backup_dirs: shutil.rmtree(folder) - return results + return [ + f"{accounts.PROVIDERS[provider]['name']}: kept {a['label']} (already present)" if action == "kept" + else f"{accounts.PROVIDERS[provider]['name']}: copied {a['label']} ({a['email']})" + for action, a in results + ] def main(args: list[str]) -> int: try: - if args and args[0] == "export": - encoded = json.dumps(export_accounts(args[1:] or list(FILES))) - if len(encoded.encode()) > MAX_STREAM: + if args == ["capabilities"]: + print(json.dumps({"streamVersion": 1, "sourceNames": True})) + elif args in (["receiver-command"], ["receiver-command", "--replace"]): + command = "/usr/bin/python3 -I -c " + shlex.quote(RECEIVER_BOOTSTRAP) + if "--replace" in args: + command += " --replace" + # Avoid user profiles, BASH_ENV and home-directory Python modules + # while credentials are on stdin. Load only the system bootstrap. + command = ". /etc/profile.d/omarchy.sh 2>/dev/null; exec " + command + print("/bin/bash --noprofile --norc -p -c " + shlex.quote(command)) + elif args and args[0] in ("export", "bundle"): + payload = export_accounts(args[1:] or list(FILES)) + if len(json.dumps(payload).encode()) > MAX_STREAM: + raise accounts.AccountError("Account transfer stream is too large") + limit = MAX_STREAM + if args[0] == "bundle": + payload = { + "version": 1, + "backend": (Path(os.environ["OMARCHY_PATH"]) / "bin/omarchy-agent-account-state").read_text(), + "receiver": Path(__file__).read_text(), + "accounts": payload, + } + limit = MAX_BUNDLE + encoded = json.dumps(payload) + if len(encoded.encode()) > limit: raise accounts.AccountError("Account transfer stream is too large") print(encoded) elif args in (["import"], ["import", "--replace"]): @@ -279,9 +388,12 @@ def main(args: list[str]) -> int: finally: # Earlier providers remain committed if a later provider fails. if providers: - subprocess.Popen(["omarchy-agent-usage-update", "--force", "--limits-only", *providers], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + try: + subprocess.Popen(["omarchy-agent-usage-update", "--force", "--limits-only", *providers], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) + except OSError as error: + print(f"Accounts copied, but usage refresh could not start: {error}", file=sys.stderr) else: - raise accounts.AccountError("Usage: omarchy-agent-account-transfer [--replace] [claude|codex|grok...]") + raise accounts.AccountError("Usage: omarchy-agent-account-transfer [--replace] [claude|codex|grok...]") except (accounts.AccountError, OSError, ValueError, TypeError) as error: print(f"Account copy failed: {error}", file=sys.stderr) return 1 diff --git a/manual/17-ai.md b/manual/17-ai.md index c82c87d9f69b..0eba2b148e5a 100644 --- a/manual/17-ai.md +++ b/manual/17-ai.md @@ -47,9 +47,9 @@ Left-click the bar icon for the panel, right-click to launch your default agent. If you pay for more than one Claude, Codex, or Grok plan — a personal Max and a work one, say — Omarchy can keep them all signed in and move between them. Add a subscription with the + in the agents panel, which walks you through it right there, or with `omarchy agent account add claude Work` (or `codex`, or `grok`). It installs the CLI if it's missing. The first account for a provider signs in through your normal browser, right where the CLI always looks. Every one after that signs in through a private window, so the account your browser is already signed in to doesn't get picked up by mistake; sign in there as the account you're adding, and close any private window you already had open first. Never log out of the CLI to do this: logging out revokes the saved sign-in, and that account would have to be added again. -To copy your subscription logins to another Omarchy machine over SSH, run `omarchy agent account copy user@laptop`. Both machines need the account-copy command installed. This copies all Claude, Codex, and Grok subscriptions; add provider names to select them, as in `omarchy agent account copy laptop claude`. Account labels are preserved, with a number added when a label is already in use on the destination, and settings, skills, plugins, and conversation history stay local to each machine. +To copy your subscription logins to another Omarchy machine over SSH, run `omarchy agent account copy user@laptop`. The sender supplies a temporary receiver when the destination does not have one installed, so older Omarchy machines can receive accounts without an update. Installed receivers take precedence. This copies all Claude, Codex, and Grok subscriptions; add provider names to select them, as in `omarchy agent account copy laptop claude`. Account names and command IDs match the source, including accounts already present on the destination. Unrelated destination accounts receive a numeric suffix if their names conflict, and settings, skills, plugins, and conversation history stay local to each machine. -Existing destination logins are kept. A source account that is already signed in there is skipped; other accounts are added alongside it. To replace saved credentials for matching accounts, use `omarchy agent account copy --replace laptop claude` after quitting that account's sessions on the destination. A fresh destination also gets the source's active account and switching preferences; an established destination keeps its own. +Existing destination credentials are kept. A source account already signed in there has its name synchronized without replacing its credentials; other accounts are added alongside it. To replace saved credentials for matching accounts, use `omarchy agent account copy --replace laptop claude` after quitting that account's sessions on the destination. A fresh destination also gets the source's active account and switching preferences; an established destination keeps its own. Credentials travel through SSH and are stored in private files on the destination, so copy only to machines you trust. This is a one-time copy, not ongoing synchronization. Codex refresh tokens can be rotated by another machine, leaving a copied login in need of renewal; separate sign-ins remain the most reliable choice for simultaneous use on several machines. See [Codex's account authentication guidance](https://developers.openai.com/codex/auth/ci-cd-auth). diff --git a/test/shell.d/agent-account-copy-test.sh b/test/shell.d/agent-account-copy-test.sh index f48999720f42..e23a5dd76bc2 100755 --- a/test/shell.d/agent-account-copy-test.sh +++ b/test/shell.d/agent-account-copy-test.sh @@ -21,7 +21,7 @@ export PATH="$test_tmp/bin:$ROOT/bin:$PATH" unset CLAUDE_CONFIG_DIR CODEX_HOME GROK_HOME python3 - <<'PY' -import base64, copy, ctypes, importlib.machinery, importlib.util, json, os, subprocess, sys +import base64, contextlib, copy, ctypes, importlib.machinery, importlib.util, io, json, os, subprocess, sys from pathlib import Path loader = importlib.machinery.SourceFileLoader("transfer", str(Path(os.environ["OMARCHY_PATH"]) / "bin/omarchy-agent-account-transfer")) @@ -44,6 +44,18 @@ def claude(home, uuid, token): transfer.write_json(account_file, existing) transfer.write_json(home / ".credentials.json", {"claudeAiOauth": {"accessToken": token, "refreshToken": "fake-refresh", "subscriptionType": "max"}}) +# Invalid and oversized bundles fail before executing code or writing logins. +for raw, message in [(b'{"token":"fake-do-not-echo"', "invalid receiver bundle"), (b"x" * (transfer.MAX_BUNDLE + 1), "receiver bundle is too large")]: + result = subprocess.run(["/usr/bin/python3", "-I", "-c", transfer.RECEIVER_BOOTSTRAP], input=raw, capture_output=True) + assert result.returncode != 0 and message.encode() in result.stderr + assert b"fake-do-not-echo" not in result.stdout + result.stderr +original_export = transfer.export_accounts +transfer.export_accounts = lambda providers: {"large": "x" * (transfer.MAX_STREAM + 1)} +with contextlib.redirect_stderr(io.StringIO()) as errors: + assert transfer.main(["bundle", "claude"]) == 1 +assert "too large" in errors.getvalue() +transfer.export_accounts = original_export + machine("source") claude(state.primary_home("claude"), "personal", "fake-personal") config = state.read_json(Path.home() / ".claude.json") @@ -98,6 +110,17 @@ transfer.import_provider("claude", payload["providers"]["claude"], False) assert state.read_json(state.primary_home("claude") / ".credentials.json")["claudeAiOauth"]["accessToken"] == "destination-token" assert len(state.load("claude")["accounts"]) == 3 +# Copy names and ids exactly, even when destination names have been swapped. +state.rename("claude", "main", "Holding") +state.rename("claude", "work", "Personal") +state.rename("claude", "holding", "Work") +state.use("claude", "personal") +transfer.import_provider("claude", payload["providers"]["claude"], False) +registry = state.load("claude") +assert [(a["id"], a["label"]) for a in registry["accounts"]] == [("main", "Personal"), ("work", "Work"), ("third", "Third")] +assert registry["active"] == "work", "renaming preserves the selected identity" +assert state.read_json(state.primary_home("claude") / ".credentials.json")["claudeAiOauth"]["accessToken"] == "destination-token" + # Explicit replacement rolls back credentials and new homes if commit fails. original_save = state.save def failed_save(provider, registry): @@ -206,6 +229,33 @@ transfer.import_provider("claude", payload["providers"]["claude"], False) assert not list(Path.home().rglob(".account-copy-backup-*")) assert state.read_json(state.primary_home("claude") / ".credentials.json")["claudeAiOauth"]["accessToken"] == "fake-personal" +# A default Main with a different identity must free the source's main id. +machine("default-existing") +claude(state.primary_home("claude"), "local", "local-token") +transfer.import_provider("claude", payload["providers"]["claude"], False) +registry = state.load("claude") +assert len({a["id"] for a in registry["accounts"]}) == len(registry["accounts"]) +assert state.find(registry, "main")["accountId"] == "personal" +assert state.active(registry)["accountId"] == "local" +assert registry["active"] == "main-2" +assert state.identity("claude", state.primary_home("claude"))["accountId"] == "local" + +# Numeric suffixes needed by source ids are reserved during collision renaming. +machine("suffix-existing") +claude(state.primary_home("claude"), "local", "local-token") +registry = state.load("claude") +registry["accounts"][0].update(id="work", label="Work") +registry["active"] = "work" +state.save("claude", registry) +suffix_payload = copy.deepcopy(payload["providers"]["claude"]) +suffix_payload["accounts"][2]["id"] = "work-2" +transfer.import_provider("claude", suffix_payload, False) +registry = state.load("claude") +assert len({a["id"] for a in registry["accounts"]}) == len(registry["accounts"]) +assert state.find(registry, "work-2")["accountId"] == "third" +assert state.active(registry)["accountId"] == "local" +assert registry["active"] == "work-2-2" + # An unrelated destination primary stays in place; source Main is additional. machine("existing") claude(state.primary_home("claude"), "local", "local-token") @@ -215,10 +265,39 @@ state.save("claude", registry) transfer.import_provider("claude", payload["providers"]["claude"], False) assert state.identity("claude", state.primary_home("claude"))["accountId"] == "local" assert len(state.load("claude")["accounts"]) == 4 -assert [a["label"] for a in state.load("claude")["accounts"]][:2] == ["Personal", "Personal 2"] -assert state.load("claude")["active"] == "main" +assert [a["label"] for a in state.load("claude")["accounts"]][:2] == ["Personal 2", "Personal"] +assert state.find(state.load("claude"), "main")["accountId"] == "personal" +assert state.load("claude")["active"] == "personal-2" assert state.load("claude")["switch"] == "manual" and state.load("claude")["threshold"] == 95 +# An older installed receiver lacks name synchronization. Use the destination's +# own backend for the new receiver so additional registry fields survive. +machine("newer-backend") +backend_root = root / "newer-omarchy" +(backend_root / "bin").mkdir(parents=True) +backend_source = (Path(os.environ["OMARCHY_PATH"]) / "bin/omarchy-agent-account-state").read_text() +backend_source = backend_source.replace('return {"active": "main",', 'return {"futureSetting": "keep", "active": "main",') +(backend_root / "bin/omarchy-agent-account-state").write_text(backend_source) +old_receiver = root / "old-receiver-bin" +old_receiver.mkdir() +command = old_receiver / "omarchy-agent-account-transfer" +command.write_text("#!/bin/bash\nexit 1\n") +command.chmod(0o755) +child_env = dict(os.environ, OMARCHY_PATH=str(backend_root), PATH=str(old_receiver) + ":" + str(root / "bin")) +bundle = {"version": 1, "backend": "raise RuntimeError('sender backend must not run')", "receiver": Path(transfer.__file__).read_text(), "accounts": payload} +result = subprocess.run(["/usr/bin/python3", "-I", "-c", transfer.RECEIVER_BOOTSTRAP], input=json.dumps(bundle), text=True, capture_output=True, env=child_env) +assert result.returncode == 0, result.stderr +assert state.read_json(state.registry_path("claude"))["futureSetting"] == "keep" + +# A missing optional refresh command must not undo a completed import. +machine("no-updater") +no_updater_env = dict(os.environ, PATH="") +bundle["backend"] = (Path(os.environ["OMARCHY_PATH"]) / "bin/omarchy-agent-account-state").read_text() +result = subprocess.run(["/usr/bin/python3", "-I", "-c", transfer.RECEIVER_BOOTSTRAP], input=json.dumps(bundle), text=True, capture_output=True, env=no_updater_env) +assert result.returncode == 0, result.stderr +assert "usage refresh could not start" in result.stderr +assert len(state.read_json(state.registry_path("claude"))["accounts"]) == 3 + # Reject invalid preferences before any credentials are written. bad = copy.deepcopy(payload) bad["providers"]["claude"]["threshold"] = float("inf") @@ -253,19 +332,45 @@ cat >"$test_tmp/bin/ssh" <<'SH' #!/bin/bash printf '%s\n' "$@" >"$OMARCHY_TEST_ROOT/ssh-args" [[ $1 == "-T" && $2 == "--" && $3 == "user@remote" ]] || exit 99 -exec env HOME="$OMARCHY_TEST_ROOT/ssh-destination" XDG_STATE_HOME="$OMARCHY_TEST_ROOT/ssh-destination/state" bash -c "$4" +exec env HOME="$OMARCHY_TEST_ROOT/ssh-destination" XDG_STATE_HOME="$OMARCHY_TEST_ROOT/ssh-destination/state" python3 "$OMARCHY_TEST_ROOT/run-receiver.py" "$4" SH +# Model an old destination with no transfer command or backend on PATH. +# Decode the login-shell command without sourcing the developer's profiles. +cat >"$test_tmp/run-receiver.py" <<'PYRECEIVER' +import os, shlex, subprocess, sys +outer = shlex.split(sys.argv[1]) +assert outer[:5] == ["/bin/bash", "--noprofile", "--norc", "-p", "-c"] +prefix = ". /etc/profile.d/omarchy.sh 2>/dev/null; exec " +assert outer[5].startswith(prefix) +inner = shlex.split(outer[5][len(prefix):]) +assert inner[:3] == ["/usr/bin/python3", "-I", "-c"] +assert "fake-personal" not in sys.argv[1] +os.environ.pop("OMARCHY_PATH", None) +# Only the preexisting usage updater remains available on the destination. +os.environ["PATH"] = os.environ["OMARCHY_TEST_ROOT"] + "/bin" +os.environ["BASH_ENV"] = os.environ["OMARCHY_TEST_ROOT"] + "/bash-env" +os.chdir(os.environ["HOME"]) +# Test actual shell isolation, without loading this machine's system profile. +outer[5] = "exec " + outer[5][len(prefix):] +os.execv(outer[0], outer) +PYRECEIVER chmod +x "$test_tmp/bin/ssh" mkdir -p "$test_tmp/ssh-destination" +cat >"$test_tmp/bash-env" <<'SH' +echo "unexpected BASH_ENV" >&2 +exit 99 +SH +printf 'raise RuntimeError("unexpected home module")\n' >"$test_tmp/ssh-destination/json.py" +# The mock SSH receiver sets BASH_ENV; the sender keeps its normal environment. HOME="$test_tmp/source" XDG_STATE_HOME="$test_tmp/source/state" omarchy-agent-account-copy user@remote claude >"$test_tmp/copy-output" -[[ $(sed -n '4p' "$test_tmp/ssh-args") == "omarchy-agent-account-transfer import" ]] || fail "SSH invokes the fixed receiver command" +[[ $(sed -n '4p' "$test_tmp/ssh-args") == "/bin/bash --noprofile --norc -p -c "* ]] || fail "SSH invokes an isolated receiver shell" [[ $(jq '.accounts | length' "$test_tmp/ssh-destination/state/omarchy/agents/accounts/claude.json") == 3 ]] || fail "SSH copy imports all three Claude subscriptions" [[ $(cat "$test_tmp/copy-output") != *fake-* ]] || fail "copy output contains no tokens" [[ ! -e $test_tmp/ssh-destination/state/omarchy/agents/accounts/codex.json ]] || fail "provider selection excludes other subscriptions" pass "SSH streams selected accounts to the receiver without exposing tokens" HOME="$test_tmp/source" XDG_STATE_HOME="$test_tmp/source/state" omarchy-agent-account-copy --replace user@remote claude >"$test_tmp/replace-output" -[[ $(sed -n '4p' "$test_tmp/ssh-args") == "omarchy-agent-account-transfer import --replace" ]] || fail "replacement requires an explicit option" +[[ $(cat "$test_tmp/ssh-args") == *"--replace"* ]] || fail "replacement requires an explicit option" pass "SSH copy forwards explicit replacement" rm -f "$test_tmp/ssh-args" @@ -276,5 +381,27 @@ fi pass "invalid providers do not start SSH" HOME="$test_tmp/source" XDG_STATE_HOME="$test_tmp/source/state" omarchy-agent-account-copy user@remote --replace claude >"$test_tmp/replace-after-output" -[[ $(sed -n '4p' "$test_tmp/ssh-args") == "omarchy-agent-account-transfer import --replace" ]] || fail "replacement can appear after the host" +[[ $(cat "$test_tmp/ssh-args") == *"--replace"* ]] || fail "replacement can appear after the host" pass "replacement can appear after the host" + +# Prefer an installed destination receiver rather than an older bundled backend. +cat >"$test_tmp/bin/omarchy-agent-account-transfer" <<'SH' +#!/bin/bash +if [[ $1 == "capabilities" ]]; then + printf '{"streamVersion":1,"sourceNames":true}\n' + exit 0 +fi +printf '%s\n' "$*" >"$OMARCHY_TEST_ROOT/preferred-receiver" +/usr/bin/python3 -c 'import json,sys; assert json.load(sys.stdin)["version"] == 1' +SH +chmod +x "$test_tmp/bin/omarchy-agent-account-transfer" +HOME="$test_tmp/source" XDG_STATE_HOME="$test_tmp/source/state" "$ROOT/bin/omarchy-agent-account-transfer" bundle claude | /usr/bin/python3 -I -c "$(HOME="$test_tmp/source" XDG_STATE_HOME="$test_tmp/source/state" /usr/bin/python3 - <<'PYBOOT' +import importlib.machinery, importlib.util, os +loader=importlib.machinery.SourceFileLoader("transfer",os.environ["OMARCHY_PATH"]+"/bin/omarchy-agent-account-transfer") +spec=importlib.util.spec_from_loader(loader.name,loader) +m=importlib.util.module_from_spec(spec);loader.exec_module(m) +print(m.RECEIVER_BOOTSTRAP) +PYBOOT +)" --replace +[[ $(cat "$test_tmp/preferred-receiver") == "import --replace" ]] || fail "installed receiver is preferred" +pass "installed receiver is preferred"