Skip to content

The agent that grows with you

merge: reconcile profile-scoped routes and shared desktop backend with PM

ethernetc399093de95c
diff --cc agent/credential_pool.py
index 533435533aa,4b671068eb4..1d345f8b73a
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@@ -756,6 -759,180 +759,181 @@@ def resolve_runtime_pool_key(provider:
DEFAULT_MAX_CONCURRENT_PER_CREDENTIAL = 1
+ # --- Multi-profile root write-through ---
+
+
+ def _guarded_global_root(global_path: Optional[Path]) -> Optional[Path]:
+ """Apply the pytest seat belt to a resolved global-root auth.json path.
+
+ ``None`` means classic mode (profile == root) or "refuse": under pytest,
+ never write the real user's ``~/.hermes/auth.json`` even when HERMES_HOME
+ points at a profile path (mirrors the read-side guard in
+ ``_load_global_auth_store``). Uses the unmodified HOME env, not
+ ``Path.home()`` which fixtures may monkeypatch.
+ """
+ if global_path is None:
+ return None
+ if os.environ.get("PYTEST_CURRENT_TEST"):
+ real_home_env = os.environ.get("HOME", "")
+ if real_home_env:
+ real_root = Path(real_home_env) / ".hermes" / "auth.json"
+ try:
- if global_path.resolve(strict=False) == real_root.resolve(strict=False):
++ # Comparing the guard path must not probe the real auth store.
++ if os.path.normcase(os.path.abspath(global_path)) == os.path.normcase(os.path.abspath(real_root)):
+ return None
+ except Exception:
+ return None
+ return global_path
+
+
+ def _write_through_provider_state_to_global_root(
+ provider_id: str, state: Dict[str, Any]
+ ) -> None:
+ """Persist a rotated OAuth ``state`` into the global-root auth.json.
+
+ Best-effort write-through for the multi-profile rotation hazard: nous,
+ openai-codex, and xai-oauth rotate the refresh_token on refresh, so when
+ a profile pool refresh rotates a grant it resolved from the root fallback,
+ the rotated chain must land back in root. Otherwise root keeps a revoked
+ refresh token and every other profile dies with ``refresh_token_reused``
+ / ``invalid_grant`` once its access token expires.
+
+ Only updates ``providers.<provider_id>`` in the root store; never touches
+ the profile store (the caller already saved that). Swallows all errors —
+ a failed write-through degrades to root-stale and must never break the
+ profile's own successful save. Mirrors
+ ``hermes_cli.auth._write_through_xai_oauth_to_global_root``.
+
+ See #48415.
+ """
+ try:
+ global_path = _guarded_global_root(auth_mod._global_auth_file_path())
+ except Exception:
+ return
+ if global_path is None:
+ return
+ try:
+ auth_mod._persist_provider_state_to_store(provider_id, state, global_path, set_active=False)
+ except Exception as exc: # pragma: no cover - best effort
+ logger.debug("%s pool refresh: write-through to global root failed: %s", provider_id, exc)
+
+
+ def _singleton_target_for_entry(pool: "CredentialPool", entry: "PooledCredential") -> Optional[Path]:
+ """Root ``.anthropic_oauth.json`` when *entry* is a borrowed hermes_pkce row, else None."""
+ if entry.source != "hermes_pkce" or entry.id not in getattr(pool, "_borrowed_root_ids", ()):
+ return None
+ try:
+ from agent.anthropic_credentials import _root_hermes_oauth_file
+ return _root_hermes_oauth_file()
+ except Exception:
+ return None
+
+
+ def _profile_owns_pool_provider(provider: str) -> bool:
+ """True when the ACTIVE auth.json has its own rows for *provider*.
+
+ Named profiles with no local rows read the provider through the
+ ``read_credential_pool`` global-root fallback ("borrowing").
+ """
+ try:
+ pool = _load_auth_store().get("credential_pool")
+ except Exception:
+ return True # unreadable store: assume ownership, keep legacy path
+ entries = pool.get(provider) if isinstance(pool, dict) else None
+ return isinstance(entries, list) and bool(entries)
+
+
+ def _borrowed_single_use_pool_root() -> Optional[Path]:
+ """Global-root auth.json when persisting a BORROWED single-use pool, else None.
+
+ ``None`` means "persist to the active store as usual": classic mode
+ (profile == root), or the profile owns its own rows for this provider.
+ """
+ try:
+ return _guarded_global_root(_global_auth_file_path())
+ except Exception:
+ return None
+
+
+ def _update_root_pool_rows(
+ provider: str, payloads: List[Dict[str, Any]], global_path: Path,
+ *, status_cleared_ids: Optional[Iterable[str]] = None,
+ ) -> None:
+ """UPDATE-ONLY merge of *payloads* into the root store's rows for *provider*.
+
+ A borrower may refresh the root's rows (rotation, cooldown state) but
+ never add or delete them — the root owns their lifecycle. In particular a
+ profile's singleton-prune (it has no ``.anthropic_oauth.json`` of its own)
+ must not delete the root grant, so ``removed_ids`` is ignored by callers.
+ """
+ with _auth_store_lock(target_path=global_path):
+ store = _load_auth_store(global_path)
+ pool = store.get("credential_pool")
+ if not isinstance(pool, dict):
+ pool = {}
+ store["credential_pool"] = pool
+ existing = pool.get(provider)
+ existing_list = existing if isinstance(existing, list) else []
+ incoming_by_id = {p.get("id"): p for p in payloads if isinstance(p, dict) and p.get("id")}
+ cleared = {cid for cid in (status_cleared_ids or ()) if cid}
+ merged: List[Dict[str, Any]] = []
+ changed = False
+ for disk_entry in existing_list:
+ did = disk_entry.get("id") if isinstance(disk_entry, dict) else None
+ incoming = incoming_by_id.get(did) if did else None
+ if incoming is None:
+ merged.append(disk_entry)
+ continue
+ # A deliberately cleared entry has no disk cooldown worth keeping.
+ updated = auth_mod._merge_disk_cooldown_state(
+ incoming, None if did in cleared else disk_entry, provider,
+ )
+ if updated != disk_entry:
+ changed = True
+ merged.append(updated)
+ if changed:
+ pool[provider] = merged
+ _save_auth_store(store, target_path=global_path)
+
+
+ def persist_pool_entries(
+ provider: str,
+ payloads: List[Dict[str, Any]],
+ *,
+ removed_ids: Optional[Iterable[str]] = None,
+ status_cleared_ids: Optional[Iterable[str]] = None,
+ ) -> None:
+ """Persist a provider's pool rows to the store that OWNS them.
+
+ A named profile that sees a single-use-refresh provider (Anthropic,
+ Codex, xAI OAuth) only through the global-root fallback must not
+ materialize a local ``credential_pool.<provider>`` copy: that copy forks
+ the single-use refresh token, the first profile to rotate commits the new
+ pair only to its own file, and root plus every sibling die with
+ ``invalid_grant`` (#100339). Such rows are written back to the root store
+ (under the root lock); everything else goes to the active store.
+ """
+ if provider in SINGLE_USE_REFRESH_POOL_PROVIDERS and not _profile_owns_pool_provider(provider):
+ global_path = _borrowed_single_use_pool_root()
+ if global_path is not None:
+ try:
+ _update_root_pool_rows(
+ provider, payloads, global_path,
+ status_cleared_ids=status_cleared_ids,
+ )
+ except Exception as exc:
+ # Fail closed on the FORK, not on the save: never fall back to
+ # writing a local copy (that IS the bug). The in-memory pool
+ # still holds the rotated pair for this process.
+ logger.warning(
+ "%s pool: write-through of borrowed root grant failed (%s); "
+ "not materializing a profile-local copy",
+ provider, exc,
+ )
+ return
+ write_credential_pool(
+ provider, payloads, removed_ids=removed_ids, status_cleared_ids=status_cleared_ids,
+ )
# --- Per-provider singleton refresh plumbing -------------------------------
diff --cc apps/desktop/electron/main.ts
index fa00148f50f,38dd6293d9f..a48a7bfdacc
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -138,6 -131,6 +138,7 @@@ import
pathWithGlobalRemoteProfile,
profileHasRemoteConnection,
profileRemoteOverride,
++ type ProfileRouteOptions,
profileSshOverride,
type RegistryBackendRequestScope,
resolveAuthMode,
@@@ -10290,7 -11390,7 +10282,10 @@@ function primaryProfileKey()
}
// Options describing the current connection setup for `resolveProfileBackendRoute`.
--function profileRouteOptions(profile, request?) {
++function profileRouteOptions(
++ profile: string | null | undefined,
++ request?: { method?: string; path?: string }
++): ProfileRouteOptions {
const config = readDesktopConnectionConfig()
const sshOverride = profileSshOverride(config, profile)
const key = connectionScopeKey(profile) || primaryProfileKey()
@@@ -10317,7 -11418,11 +10313,10 @@@
// Resolve a backend connection for the given profile, per the routing table in
// resolveProfileBackendRoute(). An empty / unknown profile resolves to the
// primary, so legacy callers are unchanged.
- async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?: LocalBackendSpawnPriority } = {}) {
+ async function ensureBackend(
- profile,
++ profile: string | null | undefined,
+ opts: { passive?: boolean; request?: { method?: string; path?: string }; spawnPriority?: LocalBackendSpawnPriority } = {}
-) {
- localBackendLifecycle.assertCanStart()
++): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {
const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()
const spawnPriority = spawnPriorityFrom(opts.spawnPriority)
poolRetirer.assertCanOpen(key, spawnPriority)
@@@ -11359,11 -12513,19 +11365,11 @@@ function teardownFailedLocalBackend(poo
// entry means THIS machine regardless of the v1 routing table); `opts.poolKey`
// is the backendPool key when it differs from the profile name (composite
// registry scopes) so the exit/error cleanup evicts the right entry.
-function spawnPoolBackend(
- profile,
- entry,
- opts: { forceLocal?: boolean; poolKey?: string; unscopableRequest?: boolean } = {}
-) {
- return localBackendLifecycle.start(() => runPoolBackendStart(profile, entry, opts))
-}
-
-async function runPoolBackendStart(
- profile,
- entry,
+async function spawnPoolBackend(
+ profile: string,
+ entry: any,
- opts: { forceLocal?: boolean; poolKey?: string } = {}
+ opts: { forceLocal?: boolean; poolKey?: string; unscopableRequest?: boolean } = {}
-) {
+): Promise<Awaited<ReturnType<typeof backendConnectionState.getPromise>>> {
const poolKey = opts.poolKey || profile
await reapOrphanedBackendsOnce()
@@@ -16051,54 -17206,19 +16075,58 @@@ async function handleHermesApiRequest(r
let connection
try {
- connection = await ensureBackend(routeProfile, { passive: request?.passive, spawnPriority })
+ connection = await ensureBackend(routeProfile, {
+ passive: request?.passive,
+ request: { method: request?.method, path: request?.path },
+ spawnPriority
+ })
const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
- response = await fetchJsonForBackend(connection, apiRoute.requestPath, {
- method: request?.method,
- body: request?.body,
- upload: request?.upload,
- timeoutMs
- })
+ const url = `${connection.baseUrl}${apiRoute.requestPath}`
+
+ // OAuth gateways authenticate REST via EITHER a native bearer token
+ // (cookieless RFC 8252 flow) OR the HttpOnly session cookie held in the OAuth
+ // partition. Prefer the native bearer when present (mirroring
+ // mintGatewayWsTicket): the native flow never sets a cookie, so routing an
+ // oauth-mode REST call through the cookie-only path returns 401 no_cookie even
+ // though a valid bearer is held. Cookie mode rides Electron's net stack bound
+ // to the OAuth partition so the cookie attaches automatically. Token/local
+ // modes keep using the static session-token header.
+ if (connection.authMode === 'oauth') {
+ // The OAuth path rides electron.net with JSON headers; multipart isn't
+ // wired there. Fail loudly rather than corrupting the upload.
+ if (request?.upload) {
+ throw new Error('File uploads are not supported against OAuth-gated remote backends yet.')
+ }
+
+ // Native bearer first (cookieless). ensureNativeAccessToken transparently
+ // refreshes a near-expiry AT via /auth/native/refresh; a null return means
+ // no native session (resolveOauthRestAuth then selects the cookie path).
+ const nativeAt = await ensureNativeAccessToken(connection.baseUrl).catch(() => null)
+ const restAuth = resolveOauthRestAuth(nativeAt)
+
+ if (restAuth.kind === 'bearer') {
+ response = await fetchJson(url, null, {
+ method: request?.method,
+ body: request?.body,
+ timeoutMs,
+ bearer: restAuth.token
+ })
+ } else {
+ response = await fetchJsonViaOauthSession(url, {
+ method: request?.method,
+ body: request?.body,
+ timeoutMs
+ })
+ }
+ } else {
+ response = await fetchJson(url, connection.token, {
+ method: request?.method,
+ body: request?.body,
+ upload: request?.upload,
+ timeoutMs
+ })
+ }
} catch (error) {
// A failed rename PATCH must not strand the app on the temporary primary:
// restore the original active profile and restart its backend.
diff --cc hermes_cli/auth.py
index 96f38dfa698,f5ecdb95e18..82299e8e412
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@@ -489,6 -491,52 +491,52 @@@ def _auth_file_path() -> Path
return path
+ def _global_auth_file_path() -> Optional[Path]:
+ """Global-root auth.json in profile mode; None when profile and global root are the same dir.
+
+ Read-only fallback path, so no pytest seat belt here (it lives on ``_auth_file_path()``)."""
+ try:
+ from hermes_constants import get_default_hermes_root
+ global_root = get_default_hermes_root()
+ except Exception:
+ return None
+ return None if _same_path(get_hermes_home(), global_root) else global_root / "auth.json"
+
+
+ def _load_global_auth_store() -> Dict[str, Any]:
+ """Load the global-root auth store (read-only fallback, mtime-memoised); ``{}`` when absent or
+ unreadable — a malformed global store must never break profile reads."""
+ global _global_auth_store_cache
+ global_path = _global_auth_file_path()
+ if global_path is None or not global_path.exists():
+ _global_auth_store_cache = None
+ return {}
+ try:
+ cache_key: Optional[Tuple[str, Tuple[int, int, int, int]]] = (
+ str(global_path.resolve(strict=False)), file_signature(global_path.stat()))
+ except Exception:
+ cache_key = None
+ cached = _global_auth_store_cache
+ if cache_key is not None and cached is not None and cached[:2] == cache_key:
+ return cached[2]
+ if os.environ.get("PYTEST_CURRENT_TEST") and os.environ.get("HOME"):
+ real_root = Path(os.environ["HOME"]) / ".hermes" / "auth.json"
+ try:
- if global_path.resolve(strict=False) == real_root.resolve(strict=False):
++ if os.path.normcase(os.path.abspath(global_path)) == os.path.normcase(os.path.abspath(real_root)):
+ _global_auth_store_cache = None
+ return {}
+ except Exception:
+ pass
+ try:
+ store = _load_auth_store(global_path)
+ except Exception:
+ _global_auth_store_cache = None
+ return {}
+ if cache_key is not None:
+ _global_auth_store_cache = (*cache_key, store)
+ return store
+
+
_auth_target_lock_holders: Dict[str, threading.local] = {}
_auth_target_lock_holders_guard = threading.Lock()
diff --cc hermes_cli/web_routers/actions.py
index 4fa173493b9,165364ba074..272626a6597
--- a/hermes_cli/web_routers/actions.py
+++ b/hermes_cli/web_routers/actions.py
@@@ -297,13 -284,17 +298,14 @@@ async def check_hermes_update(force: bo
payload["message"] = non_applyable()
return payload
- # banner.check_for_updates() handles git / nix-revision paths through the GitHub API and
+ # source_check.check_for_updates() handles git / nix-revision paths through the GitHub API and
# caches the result for 24h. ``force`` busts the cache so "Check now" reflects reality.
try:
- from hermes_cli.banner import check_for_updates, upstream_commits_behind
-
- if force:
- # The checkout is host-wide, but the 24 h cache file lives in a profile home;
- # bust the one belonging to the profile that asked.
- with contextlib.suppress(OSError), _config_profile_scope(profile):
- (get_hermes_home() / ".update_check").unlink()
- behind = await asyncio.to_thread(check_for_updates)
+ from hermes_cli.source_check import check_for_updates
+
- status = await asyncio.to_thread(check_for_updates, force=force)
++ with _config_profile_scope(profile):
++ status = await asyncio.to_thread(check_for_updates, force=force)
+ behind = status.get("behind")
except Exception:
_log.exception("Update check failed")
behind = None
diff --cc hermes_cli/web_routers/local_models.py
index 128b0962cd7,bceb83bbd2f..399fc66b794
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@@ -654,20 -657,27 +654,21 @@@ def _install_engine_job(job: Dict[str,
@router.post("/api/local-models/runtime/install")
- def local_models_runtime_install(body: RuntimeInstallBody):
-async def local_models_runtime_install(body: RuntimeInstallBody, profile: Optional[str] = None):
++def local_models_runtime_install(body: RuntimeInstallBody, profile: Optional[str] = None):
tag, backend = _runtime_target(body.backend)
- plan = _resolve_assets_or_400(tag, backend)
job = _job("runtime-install", f"llama.cpp {tag} ({backend})")
- def _run():
- previous = binaries.installed_tags()
- _step(job, "downloading", f"Fetching {len(plan.assets)} package(s) for {backend}")
- # The engine binaries are machine-global, but ensure_local_runtime also regenerates the
- # launch presets under get_hermes_home() — scope so those land in the named profile.
+ def run():
- previous = binaries.installed_engine(backend)
- engine = _install_engine_job(job, backend)
- running = bootstrap.get_supervisor()
- if running is not None and previous != engine:
- _step(job, "restarting", "Switching the running server to the pinned build")
- bootstrap.refresh_local_runtime()
+ with _config_profile_scope(profile):
- binaries.ensure_runtime_installed(tag, backend, progress=_runtime_progress_hook(job))
- # Restart failure is logged only: the new build is installed either way and the next boot serves it.
- restarted = _quiet(lambda: _restart_on_new_tag(job, tag, previous), False,
- warn="post-update restart skipped: %s")
- # N-1 retention, only after the new tag verified: keep it + the newest previous build as the rollback pin target.
- _quiet(lambda: binaries.prune_old_tags([tag] + [t for t in previous if t != tag][:1]), None,
- warn="runtime prune skipped: %s")
- _finish(job, f"llama.cpp {tag} ready ({backend})" + (" — server restarted on the new build" if restarted else ""))
-
- _spawn_job(job, "lr-runtime-install", _run, fail_msg="runtime install failed: %s")
++ previous = binaries.installed_engine(backend)
++ engine = _install_engine_job(job, backend)
++ running = bootstrap.get_supervisor()
++ if running is not None and previous != engine:
++ _step(job, "restarting", "Switching the running server to the pinned build")
++ bootstrap.refresh_local_runtime()
+ _finish(job, f"llama.cpp {tag} ready ({backend})")
+
+ _spawn_job(job, "lr-runtime-install", run, fail_msg="runtime install failed: %s", resumable=True)
return {"job_id": job["job_id"], "backend": backend, "tag": tag}
@@@ -769,7 -752,7 +770,7 @@@ def _quickstart_target(body: Quickstart
@router.post("/api/local-models/quickstart")
- def local_models_quickstart(body: QuickstartBody):
-async def local_models_quickstart(body: QuickstartBody, profile: Optional[str] = None):
++def local_models_quickstart(body: QuickstartBody, profile: Optional[str] = None):
"""One job: install the runtime (if missing), download this machine's build of the recommended model (if
missing), make it the default. Each leg uses the same code as the individual setup routes.
Preflight rejects (no automatic recommendation or no servable choice) fail the POST
@@@ -785,25 -768,28 +786,26 @@@
if not _QUICKSTART_LOCK.acquire(blocking=False):
raise HTTPException(status_code=409, detail="Setup is already running")
job = _job("quickstart", entry.display_name, model_id=entry.id)
- job["total_bytes"] = download_bytes or None
-
def _run():
- if need_runtime:
- _step(job, "installing-runtime", "Installing the local engine")
- binaries.ensure_runtime_installed(tag, backend, progress=_runtime_progress_hook(job))
+ if need_runtime and binaries.installed_engine(backend) is None:
+ _install_engine_job(job, backend)
if need_download:
- # The runtime leg repurposed the byte counters for its own stages — reset them to the model plan.
- job["done_bytes"] = 0
- job["total_bytes"] = download_bytes
+ # Each phase has its own complete download plan. Resume within a
+ # phase retains counters until PM reports the durable bytes.
+ if job["phase"] != "downloading":
+ with _JOBS_LOCK:
+ job.update(done_bytes=0, total_bytes=None, ranges={})
_run_download_plan(job, download_plan, entry.display_name)
- # Activate: same sequence as /activate's job body, and the same scope. Quickstart IS
- # `activate` plus a download: _set_runtime_enabled and _assign_default both reach
- # save_config, so without this the config.yaml write lands in the launch profile.
+ _step(job, "starting-server", "Starting the local server")
- _ensure_server(job, _set_runtime_enabled(True), variant.model_id,
- fail_detail="The local server could not start — open Local Models for details",
- skip_msg="quickstart rescan check skipped")
- _assign_default(job, variant.model_id)
+ with _config_profile_scope(profile):
+ _ensure_server(job, _set_runtime_enabled(True), variant.model_id,
+ fail_detail="The local server could not start — open Local Models for details",
+ skip_msg="quickstart rescan check skipped")
+ _assign_default(job, variant.model_id)
_finish(job, f"{entry.display_name} is ready — new chats use it")
- _spawn_job(job, "lr-quickstart", _run, fail_msg="quickstart failed: %s", on_exit=_QUICKSTART_LOCK.release)
+ _spawn_job(job, "lr-quickstart", _run, fail_msg="quickstart failed: %s",
+ on_exit=_QUICKSTART_LOCK.release, resumable=True)
return {"job_id": job["job_id"], "model_id": entry.id, "display_name": entry.display_name,
"needs_runtime": need_runtime, "needs_download": need_download, "download_bytes": download_bytes}
diff --cc tests/hermes_cli/test_web_routers_destructive_profile_scope.py
index 00000000000,be301cb6ebb..f862eca90e1
mode 000000,100644..100644
--- a/tests/hermes_cli/test_web_routers_destructive_profile_scope.py
+++ b/tests/hermes_cli/test_web_routers_destructive_profile_scope.py
@@@ -1,0 -1,459 +1,467 @@@
+ """One backend serves every profile, so a REST handler that reads ``get_hermes_home()``
+ directly mutates the LAUNCH profile's data no matter which profile the request named.
+
+ These pin both halves of the contract:
+
+ * a named profile is the one that gets wiped / written / spawned against, and the launch
+ profile survives untouched;
+ * an UNNAMED profile is refused (400) on a destructive or privileged route while several
+ profiles are served, and still means the launch profile on a genuinely single-profile host.
+
+ Multi-profile hosting is NOT faked here. ``destructive_profile`` asks
+ ``agent.secret_scope.is_multiplex_active()``, and that flag is only ever set by the boot
+ wiring (``activate_multi_profile_hosting_eagerly``) or by the lazy backstop inside
+ ``_config_profile_scope``. Patching the predicate would leave exactly that wiring — the
+ thing the whole 400 branch rests on — untested, so the tests drive the real path and the
+ autouse fixture below puts the process-global flag back (activation is one-way per process).
+ """
+ import json
+ import zipfile
+
+ import pytest
-import yaml
++import hermes_yaml as yaml
+
+
+ @pytest.fixture(autouse=True)
+ def _multiplex_state_is_per_test():
+ """Multi-profile activation is a one-way PROCESS-global flip; contain it to one test.
+
+ Entered single-profile (so a leak from an earlier module cannot make an unnamed
+ request 400 by accident) and restored exactly as found, including the frozen launch
+ env snapshot activation captures.
+ """
+ import agent.secret_scope as secret_scope
+ from tui_gateway import launch_profile_policy
+
+ was_active = secret_scope.is_multiplex_active()
+ snapshot = launch_profile_policy._snapshot
+ secret_scope.set_multiplex_active(False)
+ launch_profile_policy._snapshot = None
+ try:
+ yield
+ finally:
+ secret_scope.set_multiplex_active(was_active)
+ launch_profile_policy._snapshot = snapshot
+
+
+ @pytest.fixture
+ def homes(tmp_path, monkeypatch, _isolate_hermes_home):
+ """Isolated launch home + one named profile, both seeded with real files."""
+ from hermes_constants import get_hermes_home
+ from hermes_cli import profiles
+
+ launch_home = get_hermes_home()
+ profiles_root = launch_home / "profiles"
+ beta = profiles_root / "worker_beta"
+ for home in (launch_home, beta):
+ (home / "memories").mkdir(parents=True, exist_ok=True)
+ (home / "memories" / "MEMORY.md").write_text(f"memory of {home.name}\n", encoding="utf-8")
+ (home / "memories" / "USER.md").write_text(f"user of {home.name}\n", encoding="utf-8")
+ (home / "webhook_subscriptions.json").write_text(
+ json.dumps({"alerts": {"secret": "s", "events": []}}), encoding="utf-8")
+ (home / "config.yaml").write_text(yaml.safe_dump({
+ "hooks": {"pre_tool_call": [{"command": "/bin/true"}]},
+ # A per-home marker every scoped READ path can be identified by.
+ "proxy": {"label": home.name},
+ }), encoding="utf-8")
+ (home / ".update_check").write_text("cached\n", encoding="utf-8")
+ # Non-empty: an empty ``.env`` is the crashed-``profile create`` shell that
+ # ``named_profile_has_servable_identity`` deliberately refuses to count as a tenant.
+ (beta / ".env").write_text("BETA=1\n", encoding="utf-8")
+
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: launch_home)
+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
+ return {"launch": launch_home, "worker_beta": beta}
+
+
+ @pytest.fixture
+ def client(monkeypatch, homes):
+ try:
+ from starlette.testclient import TestClient
+ except ImportError:
+ pytest.skip("fastapi/starlette not installed")
+
+ import hermes_state
+ from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
+
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", homes["launch"] / "state.db")
+ c = TestClient(app)
+ c.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+ return c
+
+
+ class _StubDB:
+ """Just enough session store for the delete/prune bodies; records nothing itself."""
+
+ def delete_sessions(self, ids):
+ return len(ids)
+
+ def delete_empty_sessions(self):
+ return 1
+
+ def count_open_prune_matches(self, **_filters):
+ return 0
+
+ def list_prune_candidates(self, **_filters):
+ return []
+
+ def prune_sessions(self, **_kwargs):
+ return 1
+
+ def close(self):
+ pass
+
+
+ @pytest.fixture
+ def seams(monkeypatch):
+ """Record the three off-process effects these routes have, and neutralise them.
+
+ ``spawn`` = the argv of every backgrounded ``hermes`` action, ``db`` = the profile every
+ session-store open names, ``pool_home`` = the home the credential-pool body resolves.
+ A route that reaches any of them after a 400 shows up as a non-empty list.
+ """
+ import agent.credential_pool as credential_pool
+ import agent.credential_sources as credential_sources
+ from hermes_cli import web_server_gateway, web_server_sessions
+ from hermes_cli.config import get_hermes_home
+
+ record = {"spawn": [], "db": [], "pool_home": []}
+
+ class _Proc:
+ pid = 4242
+
+ def _spawn(argv, name):
+ record["spawn"].append((name, list(argv)))
+ return _Proc()
+
+ def _open_db(profile, *, read_only):
+ record["db"].append(profile)
+ return _StubDB()
+
+ class _Pool:
+ def remove_index(self, _index):
+ record["pool_home"].append(str(get_hermes_home()))
+ return type("_Entry", (), {"source": ""})()
+
+ def entries(self):
+ return []
+
+ monkeypatch.setattr(web_server_gateway, "_spawn_hermes_action", _spawn)
+ monkeypatch.setattr(web_server_sessions, "_open_session_db_for_profile", _open_db)
+ monkeypatch.setattr(credential_pool, "load_pool", lambda _provider: _Pool())
+ monkeypatch.setattr(credential_sources, "find_removal_step", lambda *_a: None)
+ return record
+
+
+ @pytest.fixture
+ def multiplexed(homes):
+ """Arm the guard the way a real two-profile host does: the BOOT probe.
+
+ ``activate_multi_profile_hosting_eagerly`` enumerates this host's servable profile
+ homes and flips ``set_multiplex_active`` itself; asserting it returned True is what
+ proves the wiring — not just the flag — is what refuses the unnamed requests below.
+ """
+ from agent.secret_scope import is_multiplex_active
+ from tui_gateway.launch_profile_policy import activate_multi_profile_hosting_eagerly
+
+ assert activate_multi_profile_hosting_eagerly() is True, "boot probe did not see two homes"
+ assert is_multiplex_active()
+
+
+ def _cfg(home):
+ return yaml.safe_load((home / "config.yaml").read_text()) or {}
+
+
+ def _hooks(home):
+ return _cfg(home).get("hooks") or {}
+
+
+ def _zip(tmp_path):
+ path = tmp_path / "backup.zip"
+ with zipfile.ZipFile(path, "w") as zf:
+ zf.writestr("manifest.json", "{}")
+ return path
+
+
+ def _q(profile):
+ """``?profile=`` fragment, or nothing at all when the request names no profile."""
+ return f"?profile={profile}" if profile else ""
+
+
+ def _body_profile(profile):
+ """The session family takes its profile in the BODY, so an unnamed request omits the key."""
+ return {"profile": profile} if profile else {}
+
+
+ # Every destructive/privileged route, as a call taking (client, profile-name-or-"", tmp_path).
+ DESTRUCTIVE = {
+ "memory-reset": lambda c, p, t: c.post(f"/api/memory/reset{_q(p)}", json={"target": "all"}),
+ "webhook-delete": lambda c, p, t: c.delete(f"/api/webhooks/alerts{_q(p)}"),
+ "hook-delete": lambda c, p, t: c.request(
+ "DELETE", f"/api/ops/hooks{_q(p)}", json={"event": "pre_tool_call", "command": "/bin/true"}),
+ "hook-create": lambda c, p, t: c.post(
+ f"/api/ops/hooks{_q(p)}", json={"event": "pre_tool_call", "command": "/bin/armed"}),
+ "checkpoints-prune": lambda c, p, t: c.post(f"/api/ops/checkpoints/prune{_q(p)}"),
+ "import": lambda c, p, t: c.post(f"/api/ops/import{_q(p)}", json={"archive": str(_zip(t))}),
+ "import-upload": lambda c, p, t: c.post(
+ f"/api/ops/import-upload{_q(p)}",
+ files={"file": ("backup.zip", _zip(t).read_bytes(), "application/zip")}),
+ "credentials-pool-delete": lambda c, p, t: c.delete(f"/api/credentials/pool/anthropic/0{_q(p)}"),
+ "curator-run": lambda c, p, t: c.post(f"/api/curator/run{_q(p)}"),
+ "sessions-prune": lambda c, p, t: c.post(
+ "/api/sessions/prune", json={"dry_run": False, **_body_profile(p)}),
+ "sessions-empty": lambda c, p, t: c.delete(f"/api/sessions/empty{_q(p)}"),
+ "sessions-bulk-delete": lambda c, p, t: c.post(
+ "/api/sessions/bulk-delete", json={"ids": ["abc"], **_body_profile(p)}),
+ }
+
+
+ @pytest.mark.parametrize("route", sorted(DESTRUCTIVE))
+ def test_destructive_route_refuses_an_unnamed_profile_while_multiplexing(
+ client, homes, seams, multiplexed, tmp_path, route
+ ):
+ """No profile named + several served = refused, and provably nothing happened."""
+ resp = DESTRUCTIVE[route](client, "", tmp_path)
+
+ assert resp.status_code == 400, resp.text
+ assert seams == {"spawn": [], "db": [], "pool_home": []}, f"{route} reached a backend anyway"
+ for home in homes.values():
+ assert (home / "memories" / "MEMORY.md").exists()
+ assert "alerts" in json.loads((home / "webhook_subscriptions.json").read_text())
+ assert _hooks(home) == {"pre_tool_call": [{"command": "/bin/true"}]}
+
+
+ # Routes whose effect is a file inside the target home: (call, "did it happen here?").
+ FILE_EFFECTS = {
+ "memory-reset": (DESTRUCTIVE["memory-reset"],
+ lambda home: not (home / "memories" / "MEMORY.md").exists()),
+ "webhook-delete": (DESTRUCTIVE["webhook-delete"],
+ lambda home: "alerts" not in json.loads((home / "webhook_subscriptions.json").read_text())),
+ "hook-delete": (DESTRUCTIVE["hook-delete"], lambda home: not _hooks(home)),
+ "hook-create": (DESTRUCTIVE["hook-create"],
+ lambda home: any(e.get("command") == "/bin/armed"
+ for e in _hooks(home).get("pre_tool_call", []))),
+ }
+
+
+ @pytest.mark.parametrize("route", sorted(FILE_EFFECTS))
+ def test_named_profile_is_the_only_one_touched(client, homes, seams, tmp_path, route):
+ call, happened = FILE_EFFECTS[route]
+ resp = call(client, "worker_beta", tmp_path)
+
+ assert resp.status_code == 200, resp.text
+ assert happened(homes["worker_beta"]), f"{route} did not act on worker_beta"
+ assert not happened(homes["launch"]), f"{route} also hit the launch profile"
+
+
+ # Routes whose effect is a backgrounded ``hermes`` subprocess: the profile must reach its argv,
+ # because nothing else in that process knows which home the request meant.
+ SPAWNING = {
+ "checkpoints-prune": DESTRUCTIVE["checkpoints-prune"],
+ "curator-run": DESTRUCTIVE["curator-run"],
+ "import": DESTRUCTIVE["import"],
+ }
+
+
+ @pytest.mark.parametrize("route", sorted(SPAWNING))
+ def test_spawned_action_carries_the_named_profile(client, homes, seams, tmp_path, route):
+ resp = SPAWNING[route](client, "worker_beta", tmp_path)
+
+ assert resp.status_code == 200, resp.text
+ assert [argv[:2] for _name, argv in seams["spawn"]] == [["-p", "worker_beta"]]
+
+
+ @pytest.mark.parametrize("route", ["sessions-prune", "sessions-empty", "sessions-bulk-delete"])
+ def test_session_route_opens_the_named_profiles_store(client, homes, seams, tmp_path, route):
+ resp = DESTRUCTIVE[route](client, "worker_beta", tmp_path)
+
+ assert resp.status_code == 200, resp.text
+ assert seams["db"] == ["worker_beta"]
+
+
+ def test_session_prune_dry_run_still_works_unnamed_while_multiplexing(client, seams, multiplexed):
+ """A preview deletes nothing, so the confirm dialog must keep working without a profile."""
+ resp = client.post("/api/sessions/prune", json={"dry_run": True})
+
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["removed"] == 0
+ assert seams["db"] == [None]
+
+
+ def test_credential_pool_delete_runs_in_the_named_profiles_home(client, homes, seams):
+ resp = client.delete("/api/credentials/pool/anthropic/0?profile=worker_beta")
+
+ assert resp.status_code == 200, resp.text
+ assert seams["pool_home"] == [str(homes["worker_beta"])]
+
+
+ # --- activation: the wiring the 400 branch depends on -------------------------------
+
+
+ def test_a_request_for_another_profile_arms_the_guard(client, homes):
+ """The lazy backstop: the first cross-profile request is itself the activation."""
+ from agent.secret_scope import is_multiplex_active
+
+ assert not is_multiplex_active()
+ assert client.get("/api/memory?profile=worker_beta").status_code == 200
+ assert is_multiplex_active()
+
+ assert client.post("/api/memory/reset", json={"target": "all"}).status_code == 400
+ assert (homes["launch"] / "memories" / "MEMORY.md").exists()
+
+
+ def test_unnamed_profile_still_means_the_launch_profile_on_a_single_profile_host(
+ client, homes, monkeypatch, tmp_path
+ ):
+ """A plain ``hermes serve`` has nothing to confuse: `curl` with no profile is unchanged."""
+ from agent.secret_scope import is_multiplex_active
+ from hermes_cli import profiles
+ from tui_gateway.launch_profile_policy import activate_multi_profile_hosting_eagerly
+
+ empty_root = tmp_path / "no-named-profiles"
+ empty_root.mkdir()
+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: empty_root)
+ assert activate_multi_profile_hosting_eagerly() is False
+ assert not is_multiplex_active()
+
+ resp = client.post("/api/memory/reset", json={"target": "all"})
+
+ assert resp.status_code == 200, resp.text
+ assert not (homes["launch"] / "memories" / "MEMORY.md").exists()
+ assert (homes["worker_beta"] / "memories" / "MEMORY.md").exists()
+
+
+ # --- config writes that are scoped but not destructive ------------------------------
+
+
+ def test_plugin_providers_writes_the_named_profiles_config(client, homes):
+ resp = client.put("/api/dashboard/plugin-providers?profile=worker_beta",
+ json={"context_engine": "compaction-v2"})
+
+ assert resp.status_code == 200, resp.text
+ assert _cfg(homes["worker_beta"]).get("context") == {"engine": "compaction-v2"}
+ assert "context" not in _cfg(homes["launch"])
+
+
+ @pytest.fixture
+ def readiness_only_in_beta(homes, monkeypatch):
+ """A memory provider that is ready in worker_beta and nowhere else.
+
+ Readiness resolves through ``load_config()``, so a readiness check that runs OUTSIDE the
+ request's scope answers about the launch profile: it refuses a provider the target has
+ configured, and — the dangerous direction — accepts one only the launch profile has and
+ writes it into the target as a broken setting.
+ """
+ from hermes_cli import web_server_memory
+ from hermes_cli.config import get_hermes_home
+
+ def _statuses():
+ ready = get_hermes_home().resolve() == homes["worker_beta"].resolve()
+ return [{"name": "mem0", "status": "ready" if ready else "not_configured"}]
+
+ monkeypatch.setattr(web_server_memory, "_discover_memory_provider_statuses", _statuses)
+
+
+ @pytest.mark.parametrize("call", [
+ pytest.param(lambda c: c.put("/api/memory/provider?profile=worker_beta", json={"provider": "mem0"}),
+ id="memory-provider"),
+ pytest.param(lambda c: c.put("/api/dashboard/plugin-providers?profile=worker_beta",
+ json={"memory_provider": "mem0"}),
+ id="plugin-providers"),
+ ])
+ def test_memory_provider_readiness_is_judged_in_the_profile_being_written(
+ client, homes, readiness_only_in_beta, call
+ ):
+ resp = call(client)
+
+ assert resp.status_code == 200, resp.text
+ assert _cfg(homes["worker_beta"])["memory"]["provider"] == "mem0"
+ assert "memory" not in _cfg(homes["launch"])
+
+
+ def test_local_models_quickstart_activates_into_the_named_profile(client, homes, monkeypatch):
+ """Quickstart is ``activate`` plus a download; its config writes must follow ``?profile=``."""
+ from hermes_cli.config import get_hermes_home
+ from hermes_cli.web_routers import local_models as lm
+
+ entry = type("_Entry", (), {"id": "m1", "display_name": "M One", "min_engine": None})()
+ variant = type("_Variant", (), {"model_id": "m1-q4"})()
+ seen = []
+
+ monkeypatch.setattr(lm.hardware, "probe_budget", lambda **_kw: None)
+ monkeypatch.setattr(lm, "_quickstart_target", lambda _body, _budget: (entry, variant))
+ monkeypatch.setattr(lm, "_runtime_target", lambda *_a: ("b1", "cpu"))
- monkeypatch.setattr(lm.binaries, "installed_tags", lambda: ["b1"])
++ monkeypatch.setattr(lm, "_download_plan", lambda *_a: [])
++ monkeypatch.setattr(lm.binaries, "installed_engine", lambda _backend: "installed")
+ monkeypatch.setattr(lm.bootstrap, "staged_model_ids", lambda: {"m1-q4"})
+ monkeypatch.setattr(lm, "_set_runtime_enabled", lambda _on: (lambda: None))
+ monkeypatch.setattr(lm, "_ensure_server", lambda *_a, **_k: None)
+ monkeypatch.setattr(lm, "_assign_default", lambda *_a: seen.append(str(get_hermes_home())))
+ # Run the job body inline; the real spawner's ``on_exit`` is what frees the quickstart lock.
+ monkeypatch.setattr(lm, "_spawn_job", lambda job, name, body, **kw: (body(), kw["on_exit"]()))
+
+ resp = client.post("/api/local-models/quickstart?profile=worker_beta", json={})
+
+ assert resp.status_code == 200, resp.text
+ assert seen == [str(homes["worker_beta"])]
+
+
+ # --- the read/side-effect routes scoped in the same sweep ---------------------------
+
+
+ def test_curator_pause_writes_the_named_profiles_state(client, homes):
+ resp = client.put("/api/curator/paused?profile=worker_beta", json={"paused": True})
+
+ assert resp.status_code == 200, resp.text
+ assert json.loads((homes["worker_beta"] / "skills" / ".curator_state").read_text())["paused"] is True
+ assert not (homes["launch"] / "skills" / ".curator_state").exists()
+
+
-def test_forced_update_check_busts_the_named_profiles_cache(client, homes, monkeypatch):
- from hermes_cli import banner
++def test_forced_update_check_runs_in_the_named_profiles_scope(client, homes, monkeypatch):
++ from hermes_cli import source_check
++ from hermes_cli.config import get_hermes_home
+ from hermes_cli.web_routers import actions
+
- monkeypatch.setattr(banner, "check_for_updates", lambda: 0)
++ seen = []
++
++ def check(*, force):
++ seen.append((get_hermes_home(), force))
++ return {"behind": 0, "commits": []}
++
++ monkeypatch.setattr(source_check, "check_for_updates", check)
+ monkeypatch.setattr(actions, "_dashboard_local_update_managed_externally", lambda: False)
+ monkeypatch.setattr(actions, "detect_install_method", lambda _root: "git")
+
+ resp = client.get("/api/hermes/update/check?force=true&profile=worker_beta")
+
+ assert resp.status_code == 200, resp.text
- assert not (homes["worker_beta"] / ".update_check").exists()
- assert (homes["launch"] / ".update_check").exists()
++ assert resp.json()["behind"] == 0
++ assert seen == [(homes["worker_beta"], True)]
+
+
+ def test_egress_status_reads_the_named_profiles_config(client, homes, monkeypatch):
+ from hermes_cli import proxy_cli
+ from hermes_cli.config import load_config
+
+ monkeypatch.setattr(proxy_cli, "format_status_text",
+ lambda **_kw: str((load_config().get("proxy") or {}).get("label")))
+
+ resp = client.get("/api/egress/status?profile=worker_beta")
+
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["text"] == "worker_beta"
+
+
+ def test_memory_provider_setup_runs_in_the_named_profiles_home(client, homes, monkeypatch):
+ from hermes_cli.config import get_hermes_home
+ from hermes_cli.web_routers import memory_providers as mp
+
+ monkeypatch.setattr(mp, "_memory_provider_manifest", lambda _name: {"name": "mem0"})
+ monkeypatch.setattr(mp, "_load_memory_provider", lambda _name: None)
+ monkeypatch.setattr(mp, "_install_memory_provider_setup",
+ lambda name: {"ok": True, "provider": name, "home": str(get_hermes_home())})
+
+ resp = client.post("/api/memory/providers/mem0/setup?profile=worker_beta", json={})
+
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["home"] == str(homes["worker_beta"])