Skip to content

The agent that grows with you

fix(dashboard): every REST route honours the profile it is given

teknium16a3dcc39ab00
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts
index 76fc83f5b1e..0ccd85cb8f7 100644
--- a/apps/desktop/electron/connection-config.test.ts
+++ b/apps/desktop/electron/connection-config.test.ts
@@ -383,7 +383,7 @@ const ROUTES = [
globalRemote: false,
profileRemoteOverride: false,
requestMethod: 'POST',
- requestPath: '/api/memory/reset'
+ requestPath: '/api/files/upload'
},
expected: { backend: 'pool', descriptorProfile: null, scopePath: false }
},
@@ -701,7 +701,17 @@ test('pathWithGlobalRemoteProfile appends local-primary profile scope only for e
requestMethod: 'POST',
requestPath: '/api/memory/reset'
}),
- '/api/memory/reset'
+ '/api/memory/reset?profile=iris'
+ )
+ // Still ineligible: the managed-files routes act on host paths, not a profile home.
+ assert.equal(
+ pathWithGlobalRemoteProfile('/api/files/upload', 'iris', {
+ globalRemote: false,
+ profileRemoteOverride: false,
+ requestMethod: 'POST',
+ requestPath: '/api/files/upload'
+ }),
+ '/api/files/upload'
)
})
@@ -752,12 +762,18 @@ test('resolveProfileApiRequest scopes read-only session probes without spawning
)
})
-test('resolveProfileApiRequest keeps unscoped destructive routes on the profile backend', () => {
+test('resolveProfileApiRequest scopes destructive profile-owned routes to the shared backend', () => {
+ // These handlers used to read the process home directly, so they had to ride a
+ // per-profile backend. They now take `?profile=` and refuse an unnamed profile
+ // while several are served, so the shared primary is what reaches the right home.
for (const [method, path] of [
['POST', '/api/memory/reset'],
['POST', '/api/curator/run'],
['PUT', '/api/curator/paused'],
- ['POST', '/api/webhooks']
+ ['POST', '/api/webhooks'],
+ ['DELETE', '/api/webhooks/alerts'],
+ ['DELETE', '/api/ops/hooks'],
+ ['POST', '/api/ops/checkpoints/prune']
]) {
assert.deepEqual(
resolveProfileApiRequest('iris', path, {
@@ -765,7 +781,7 @@ test('resolveProfileApiRequest keeps unscoped destructive routes on the profile
profileRemoteOverride: false,
requestMethod: method
}),
- { backendProfile: 'iris', requestPath: path }
+ { backendProfile: null, requestPath: `${path}?profile=iris` }
)
}
})
diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts
index 735694264b2..c91c4a86144 100644
--- a/apps/desktop/electron/connection-config.ts
+++ b/apps/desktop/electron/connection-config.ts
@@ -616,7 +616,27 @@ const LOCAL_PRIMARY_SCOPED_ROUTES = new Set([
// backend's own shutdown, which SIGTERMs its gateway-restart child.
'POST /api/gateway/restart',
'POST /api/gateway/start',
- 'POST /api/gateway/stop'
+ 'POST /api/gateway/stop',
+ // Profile-owned state that used to ride a per-profile backend: with one backend
+ // per host these handlers take `?profile=` and resolve the home per request.
+ // Destructive ones (memory reset, curator run, hook delete, checkpoint prune,
+ // import) REFUSE an unnamed profile while several are served, so the query is
+ // not optional here.
+ 'GET /api/memory',
+ 'PUT /api/memory/provider',
+ 'POST /api/memory/reset',
+ 'GET /api/curator',
+ 'PUT /api/curator/paused',
+ 'POST /api/curator/run',
+ 'GET /api/logs',
+ 'GET /api/portal',
+ 'GET /api/hermes/update/check',
+ 'POST /api/local-models/activate',
+ 'GET /api/dashboard/themes',
+ 'PUT /api/dashboard/theme',
+ 'GET /api/dashboard/font',
+ 'PUT /api/dashboard/font',
+ 'GET /api/dashboard/plugins'
])
function localPrimaryRequestScope(opts: ProfileRouteOptions): boolean | null {
@@ -669,6 +689,19 @@ function localPrimaryRequestScope(opts: ProfileRouteOptions): boolean | null {
return false
}
+ // Whole families whose every handler now takes `?profile=` and resolves the
+ // profile's home per request: webhook subscriptions (`{name}` in the path) and
+ // the /api/ops maintenance routes (doctor, backup/import, hooks, checkpoints,
+ // diagnostics). Their action spawns pass `-p <profile>` to the child, and the
+ // /api/actions poll family above already pins to this same backend.
+ if (pathname === '/api/webhooks' || pathname.startsWith('/api/webhooks/')) {
+ return true
+ }
+
+ if (pathname.startsWith('/api/ops/')) {
+ return true
+ }
+
return null
}
diff --git a/hermes_cli/web_routers/_common.py b/hermes_cli/web_routers/_common.py
index a93974894de..d85cd1dcf54 100644
--- a/hermes_cli/web_routers/_common.py
+++ b/hermes_cli/web_routers/_common.py
@@ -20,6 +20,7 @@ from hermes_cli.web_server_profiles import _profile_cli_args
log = logging.getLogger("hermes_cli.web_server")
_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
# Config read-modify-write serialization for off-loop handlers (live lock —
# LateState supports ``with``-blocks).
@@ -45,6 +46,40 @@ async def scoped_to_thread(profile: Optional[str], fn: Callable[[], Any]) -> Any
return await asyncio.to_thread(_run)
+async def config_scoped_to_thread(profile: Optional[str], fn: Callable[[], Any]) -> Any:
+ """Run ``fn()`` inside ``_config_profile_scope(profile)`` on a worker thread —
+ home + secret scope without the process-global skills-module swap."""
+
+ def _run():
+ with _config_profile_scope(profile):
+ return fn()
+
+ return await asyncio.to_thread(_run)
+
+
+def destructive_profile(profile: Optional[str], route: str) -> Optional[str]:
+ """The profile a DESTRUCTIVE route acts on, or 400 when it is ambiguous.
+
+ One backend serves every profile, so an omitted ``profile`` on a route that
+ deletes or overwrites profile-owned data is not a default — it silently meant
+ "whichever home this process launched with". Named profile: honoured. Omitted:
+ rejected as soon as the process hosts more than one profile
+ (``is_multiplex_active()``, decided once at boot by
+ ``activate_multi_profile_hosting_eagerly``). A genuinely single-profile host has
+ nothing to confuse, so there an omitted profile keeps meaning the launch profile
+ and `curl` against a plain ``hermes serve`` is unchanged.
+ """
+ if (profile or "").strip():
+ return profile
+ from agent.secret_scope import is_multiplex_active
+ if is_multiplex_active():
+ raise HTTPException(
+ status_code=400,
+ detail=f"{route} requires an explicit profile: this backend serves several profiles, "
+ "so an unnamed target would act on the wrong profile's data.")
+ return profile
+
+
@contextlib.contextmanager
def http_failure(log_msg: str, status: int, prefix: Optional[str] = None, *, detail: Optional[str] = None):
"""Map unexpected exceptions to an ``HTTPException``.
diff --git a/hermes_cli/web_routers/actions.py b/hermes_cli/web_routers/actions.py
index 7757b2366cc..165364ba074 100644
--- a/hermes_cli/web_routers/actions.py
+++ b/hermes_cli/web_routers/actions.py
@@ -32,6 +32,7 @@ _spawn_gateway_restart = late("_spawn_gateway_restart")
_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
detect_install_method = late("detect_install_method", "hermes_cli.config")
get_hermes_home = late("get_hermes_home", "hermes_cli.config")
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
_ACTION_COMMANDS = LateState("_ACTION_COMMANDS", "hermes_cli.web_server_gateway")
_ACTION_IDS = LateState("_ACTION_IDS", "hermes_cli.web_server_gateway")
_ACTION_PROCS = LateState("_ACTION_PROCS", "hermes_cli.web_server_gateway")
@@ -255,7 +256,7 @@ _NON_APPLYABLE_MESSAGES = {
@router.get("/api/hermes/update/check")
-async def check_hermes_update(force: bool = False):
+async def check_hermes_update(force: bool = False, profile: Optional[str] = None):
"""Report whether a Hermes update is available, without applying it.
Returns install_method ('apt'|'git'|'docker'|'nix'|'nixos'|'unknown'),
@@ -289,7 +290,9 @@ async def check_hermes_update(force: bool = False):
from hermes_cli.banner import check_for_updates, upstream_commits_behind
if force:
- with contextlib.suppress(OSError):
+ # 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)
except Exception:
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.py
index 1f8eb8b059c..1caefef8c43 100644
--- a/hermes_cli/web_routers/config_env.py
+++ b/hermes_cli/web_routers/config_env.py
@@ -105,10 +105,11 @@ async def get_schema(profile: Optional[str] = None):
@config_router.get("/api/egress/status")
-async def get_egress_status():
+async def get_egress_status(profile: Optional[str] = None):
"""Dashboard/Desktop-readable egress proxy status and remediation text."""
from hermes_cli.proxy_cli import format_status_text
- return {"text": format_status_text()}
+ with _config_profile_scope(profile): # reads the profile's ``proxy:`` config block
+ return {"text": format_status_text()}
@router.put("/api/config")
diff --git a/hermes_cli/web_routers/dashboard_ui.py b/hermes_cli/web_routers/dashboard_ui.py
index 2acbd76ce7e..e5d40d08fff 100644
--- a/hermes_cli/web_routers/dashboard_ui.py
+++ b/hermes_cli/web_routers/dashboard_ui.py
@@ -7,13 +7,14 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o
import asyncio
import logging
from pathlib import Path
-from typing import Callable
+from typing import Callable, Optional
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse
from hermes_cli.web_deps import LateState, late
from hermes_cli.config import cfg_get
+from hermes_cli.web_routers._common import config_scoped_to_thread
from hermes_cli.web_server_dashboard import (
_BUILTIN_DASHBOARD_THEMES, _discover_user_themes, _invalidate_plugins_hub_cache, _merged_plugins_hub,
)
@@ -37,9 +38,9 @@ _config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_pro
_CONFIG_MUTATION_LOCK = LateState("_CONFIG_MUTATION_LOCK")
-def _set_dashboard_key(key: str, value) -> None:
- """Write ``dashboard.<key>`` to config.yaml under the config mutation lock."""
- with _CONFIG_MUTATION_LOCK:
+def _set_dashboard_key(key: str, value, profile: Optional[str] = None) -> None:
+ """Write ``dashboard.<key>`` to the profile's config.yaml under the config mutation lock."""
+ with _config_profile_scope(profile), _CONFIG_MUTATION_LOCK:
config = load_config()
if "dashboard" not in config:
config["dashboard"] = {}
@@ -48,7 +49,7 @@ def _set_dashboard_key(key: str, value) -> None:
@router.get("/api/dashboard/themes")
-async def get_dashboard_themes():
+async def get_dashboard_themes(profile: Optional[str] = None):
"""Available themes + the active one. Built-ins ship name/label/description only
(the frontend owns their definitions in `web/src/themes/presets.ts`); user themes
from `~/.hermes/dashboard-themes/*.yaml` ship their normalised `definition`."""
@@ -64,13 +65,13 @@ async def get_dashboard_themes():
seen.add(t["name"])
return {"themes": themes, "active": active}
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(profile, _run)
@router.put("/api/dashboard/theme")
-async def set_dashboard_theme(body: ThemeSetBody):
+async def set_dashboard_theme(body: ThemeSetBody, profile: Optional[str] = None):
"""Set the active dashboard theme (persists to config.yaml)."""
- await asyncio.to_thread(_set_dashboard_key, "theme", body.name)
+ await asyncio.to_thread(_set_dashboard_key, "theme", body.name, profile)
return {"ok": True, "theme": body.name}
@@ -87,21 +88,21 @@ _FONT_CHOICES = frozenset({
@router.get("/api/dashboard/font")
-async def get_dashboard_font():
+async def get_dashboard_font(profile: Optional[str] = None):
"""Return the active font override (``"theme"`` = use the theme's font)."""
def _run():
font = cfg_get(load_config(), "dashboard", "font", default=_FONT_DEFAULT_ID)
return {"font": font if font in _FONT_CHOICES else _FONT_DEFAULT_ID}
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(profile, _run)
@router.put("/api/dashboard/font")
-async def set_dashboard_font(body: FontSetBody):
+async def set_dashboard_font(body: FontSetBody, profile: Optional[str] = None):
"""Set the font override (config.yaml). Unknown ids coerce to ``"theme"`` rather than
400 so a stale client can't wedge the picker."""
font = body.font if body.font in _FONT_CHOICES else _FONT_DEFAULT_ID
- await asyncio.to_thread(_set_dashboard_key, "font", font)
+ await asyncio.to_thread(_set_dashboard_key, "font", font, profile)
return {"ok": True, "font": font}
@@ -128,14 +129,14 @@ def _plugin_activated(plugin: dict, enabled_set: set, disabled_set: set) -> bool
@router.get("/api/dashboard/plugins")
-async def get_dashboard_plugins():
+async def get_dashboard_plugins(profile: Optional[str] = None):
"""Return discovered dashboard plugins (excludes user-hidden and non-enabled ones)."""
def _run():
plugins = _get_dashboard_plugins()
hidden: list = cfg_get(load_config(), "dashboard", "hidden_plugins", default=[]) or []
return plugins, hidden, *_plugin_enable_sets()
- plugins, hidden, enabled_set, disabled_set = await asyncio.to_thread(_run)
+ plugins, hidden, enabled_set, disabled_set = await config_scoped_to_thread(profile, _run)
# Strip internal fields before sending to frontend.
return [
@@ -295,13 +296,14 @@ async def put_plugin_providers(request: Request, body: _PluginProvidersPutBody):
@router.post("/api/dashboard/plugins/{name:path}/visibility")
-async def post_plugin_visibility(request: Request, name: str, body: _PluginVisibilityBody):
+async def post_plugin_visibility(request: Request, name: str, body: _PluginVisibilityBody,
+ profile: Optional[str] = None):
"""Toggle a plugin's sidebar visibility (persists to config.yaml dashboard.hidden_plugins)."""
_require_token(request)
name = _validate_plugin_name(name)
def _run():
- with _CONFIG_MUTATION_LOCK:
+ with _config_profile_scope(profile), _CONFIG_MUTATION_LOCK:
config = load_config()
if "dashboard" not in config or not isinstance(config.get("dashboard"), dict):
config["dashboard"] = {}
diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.py
index 6113f043241..163b1cbc0ee 100644
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@ -30,7 +30,7 @@ from pydantic import BaseModel
from starlette.concurrency import run_in_threadpool
from hermes_cli import config as config_mod, web_deps
-from hermes_cli.web_routers._common import _CONFIG_MUTATION_LOCK
+from hermes_cli.web_routers._common import _CONFIG_MUTATION_LOCK, _config_profile_scope
from hermes_cli.local_runtime import (
binaries, bootstrap, catalog, context_policy, estimator, growth, hardware, hf_browse,
load_progress, presets, supervisor,
@@ -848,7 +848,7 @@ def local_models_eject(body: ModelEjectBody):
@router.post("/api/local-models/activate")
-async def local_models_activate(body: ModelActivateBody):
+async def local_models_activate(body: ModelActivateBody, profile: Optional[str] = None):
"""Make a downloaded model the default for new chats: a config write via the same machinery as
/api/model/set plus making sure the server is up. NO model loading (residency v2: models load on first
inference; an empty router costs nothing). Kept as a job for UI continuity."""
@@ -858,12 +858,16 @@ async def local_models_activate(body: ModelActivateBody):
job = _job("model-activate", body.model_id, model_id=body.model_id)
def _run():
- _ensure_server(job, config_mod.load_config(), body.model_id,
- fail_detail=_SERVER_START_FAILED, skip_msg="activate rescan check skipped")
- _step(job, "setting-default", "Making it your default")
- _set_runtime_enabled(True)
- _assign_default(job, body.model_id)
- _finish(job, f"{body.model_id} is the default for new chats")
+ # The llama runtime is one host-wide process, but "my default model" is a
+ # config.yaml write — scope it to the profile the request names, inside the job
+ # thread (the contextvar override must be set where the write happens).
+ with _config_profile_scope(profile):
+ _ensure_server(job, config_mod.load_config(), body.model_id,
+ fail_detail=_SERVER_START_FAILED, skip_msg="activate rescan check skipped")
+ _step(job, "setting-default", "Making it your default")
+ _set_runtime_enabled(True)
+ _assign_default(job, body.model_id)
+ _finish(job, f"{body.model_id} is the default for new chats")
_spawn_job(job, "lr-model-activate", _run, fail_msg="model activate failed: %s")
return {"job_id": job["job_id"]}
diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.py
index 1364d31a587..30ad3201bc5 100644
--- a/hermes_cli/web_routers/memory_providers.py
+++ b/hermes_cli/web_routers/memory_providers.py
@@ -534,20 +534,26 @@ async def get_memory_provider_config(name: str, surface: Optional[str] = None, p
@router.post("/api/memory/providers/{name}/setup")
-async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest):
+async def setup_memory_provider(name: str, body: MemoryProviderSetupRequest,
+ profile: Optional[str] = None):
_require_valid_memory_provider_name(name)
- provider = _load_memory_provider(name)
- if provider is None and not _memory_provider_manifest(name):
- # No discoverable plugin directory -> no manifest that could declare
- # setup commands; refuse before the command-running path. (provider
- # may be None with a manifest present when its pip deps aren't
- # installed yet — that's the setup use case.)
- raise _unknown_provider(name)
- if provider is not None and body.values:
- with _value_errors_as_http("Failed to persist memory provider setup values for %s", name, passthrough_http=False):
- _write_memory_provider_config_values(name, provider, body.values)
- _invalidate_plugins_hub_cache()
- return _install_memory_provider_setup(name)
+
+ def _run():
+ provider = _load_memory_provider(name)
+ if provider is None and not _memory_provider_manifest(name):
+ # No discoverable plugin directory -> no manifest that could declare
+ # setup commands; refuse before the command-running path. (provider
+ # may be None with a manifest present when its pip deps aren't
+ # installed yet — that's the setup use case.)
+ raise _unknown_provider(name)
+ if provider is not None and body.values:
+ with _value_errors_as_http("Failed to persist memory provider setup values for %s", name,
+ passthrough_http=False):
+ _write_memory_provider_config_values(name, provider, body.values)
+ _invalidate_plugins_hub_cache()
+ return _install_memory_provider_setup(name)
+
+ return await scoped_to_thread(profile, _run)
@router.put("/api/memory/providers/{name}/config")
diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.py
index 728bd4b4de6..c935e1c7193 100644
--- a/hermes_cli/web_routers/ops.py
+++ b/hermes_cli/web_routers/ops.py
@@ -29,7 +29,10 @@ from hermes_cli.web_models import (
BackupRequest, CredentialPoolAdd, HookCreate, HookDelete, ImportRequest, MemoryProviderSelect,
MemoryReset, PairingApprove, PairingRevoke, WebhookCreate, WebhookEnabledToggle,
)
-from hermes_cli.web_routers._common import _CONFIG_MUTATION_LOCK, http_failure, spawn_profile_action
+from hermes_cli.web_routers._common import (
+ config_scoped_to_thread, config_write_scope, destructive_profile, http_failure,
+ spawn_profile_action,
+)
from hermes_cli.web_routers.files import stream_upload_to_path
_log = logging.getLogger("hermes_cli.web_server")
@@ -38,6 +41,7 @@ router = APIRouter()
# Late-bound so a test's monkeypatch on the owning module wins at call time.
_discover_memory_provider_statuses = late("_discover_memory_provider_statuses", "hermes_cli.web_server_memory")
_gateway_subcommand = late("_gateway_subcommand", "hermes_cli.web_server_gateway")
+_config_profile_scope = late("_config_profile_scope", "hermes_cli.web_server_profiles")
_resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
_spawn_hermes_action = late("_spawn_hermes_action", "hermes_cli.web_server_gateway")
_write_platform_enabled = late("_write_platform_enabled", "hermes_cli.web_server_messaging")
@@ -46,9 +50,14 @@ load_config = late("load_config", "hermes_cli.config")
save_config = late("save_config", "hermes_cli.config")
-def _spawn_action(argv: List[str], name: str, *, log_msg: str, prefix: str) -> dict:
- """Spawn a dashboard-profile ``hermes <argv>`` action; spawn failure -> 500."""
- return spawn_profile_action(None, argv, name, log_msg=log_msg, prefix=prefix)
+def _spawn_action(argv: List[str], name: str, *, log_msg: str, prefix: str,
+ profile: Optional[str] = None) -> dict:
+ """Spawn a ``hermes -p <profile> <argv>`` action; spawn failure -> 500.
+
+ The profile reaches the child as argv (``_profile_cli_args``) — the only mechanism
+ that retargets a fresh process's import-time home bindings.
+ """
+ return spawn_profile_action(profile, argv, name, log_msg=log_msg, prefix=prefix)
# --- Pairing: how a remote admin onboards messaging users without shell access.
@@ -143,25 +152,32 @@ def _webhook_route_summary(name: str, route: Dict[str, Any], base_url: str) -> D
@router.get("/api/webhooks")
-async def list_webhooks():
- import hermes_cli.webhook as wh
+async def list_webhooks(profile: Optional[str] = None):
+ def _run():
+ import hermes_cli.webhook as wh
- base_url = wh._get_webhook_base_url()
- return {
- "enabled": wh._is_webhook_enabled(),
- "base_url": base_url,
- "subscriptions": [
- _webhook_route_summary(name, route, base_url)
- for name, route in wh._load_subscriptions().items()
- ],
- }
+ base_url = wh._get_webhook_base_url()
+ return {
+ "enabled": wh._is_webhook_enabled(),
+ "base_url": base_url,
+ "subscriptions": [
+ _webhook_route_summary(name, route, base_url)
+ for name, route in wh._load_subscriptions().items()
+ ],
+ }
+
+ return await config_scoped_to_thread(profile, _run)
@router.post("/api/webhooks/enable")
-async def enable_webhooks():
+async def enable_webhooks(profile: Optional[str] = None):
+ def _run():
+ with config_write_scope(profile):
+ _write_platform_enabled("webhook", True)
+
with http_failure("Failed to enable webhook platform from dashboard", 500, detail="Failed to enable webhook platform."):
- _write_platform_enabled("webhook", True)
- restart_result = _restart_gateway_after(None, what="enabling webhooks", label="Webhook enable")
+ await asyncio.to_thread(_run)
+ restart_result = _restart_gateway_after(profile, what="enabling webhooks", label="Webhook enable")
return {
"ok": True,
"platform": "webhook",
@@ -172,10 +188,13 @@ async def enable_webhooks():
@router.post("/api/webhooks")
-async def create_webhook(body: WebhookCreate):
+async def create_webhook(body: WebhookCreate, profile: Optional[str] = None):
import hermes_cli.webhook as wh
- if not wh._is_webhook_enabled():
+ def _enabled():
+ return wh._is_webhook_enabled()
+
+ if not await config_scoped_to_thread(profile, _enabled):
raise HTTPException(
status_code=400, detail="Webhook platform is not enabled. Enable it from the Webhooks page first.",
)
@@ -206,17 +225,20 @@ async def create_webhook(body: WebhookCreate):
if body.deliver_chat_id:
route["deliver_extra"] = {"chat_id": body.deliver_chat_id}
- subs = wh._load_subscriptions()
- subs[name] = route
- wh._save_subscriptions(subs)
+ def _save():
+ subs = wh._load_subscriptions()
+ subs[name] = route
+ wh._save_subscriptions(subs)
+ return _webhook_route_summary(name, route, wh._get_webhook_base_url())
- summary = _webhook_route_summary(name, route, wh._get_webhook_base_url())
+ summary = await config_scoped_to_thread(profile, _save)
summary["secret"] = secret # surfaced exactly once, on create
return summary
def _webhook_subs_with(name: str):
- """(module, subscriptions, key) for an existing route; 404 otherwise."""
+ """(module, subscriptions, key) for an existing route; 404 otherwise. Call inside the
+ request's profile scope — ``_load_subscriptions`` resolves the home at call time."""
import hermes_cli.webhook as wh
key = (name or "").strip().lower()
@@ -227,20 +249,29 @@ def _webhook_subs_with(name: str):
@router.delete("/api/webhooks/{name}")
-async def delete_webhook(name: str):
- wh, subs, key = _webhook_subs_with(name)
- del subs[key]
- wh._save_subscriptions(subs)
+async def delete_webhook(name: str, profile: Optional[str] = None):
+ profile = destructive_profile(profile, "DELETE /api/webhooks/{name}")
+
+ def _run():
+ wh, subs, key = _webhook_subs_with(name)
+ del subs[key]
+ wh._save_subscriptions(subs)
+
+ await config_scoped_to_thread(profile, _run)
return {"ok": True}
@router.put("/api/webhooks/{name}/enabled")
-async def set_webhook_enabled(name: str, body: WebhookEnabledToggle):
+async def set_webhook_enabled(name: str, body: WebhookEnabledToggle, profile: Optional[str] = None):
"""Disabled routes stay on disk (re-enable later) but the gateway rejects
their events with 403; it hot-reloads the file, so no restart is needed."""
- wh, subs, key = _webhook_subs_with(name)
- subs[key]["enabled"] = bool(body.enabled)
- wh._save_subscriptions(subs)
+ def _run():
+ wh, subs, key = _webhook_subs_with(name)
+ subs[key]["enabled"] = bool(body.enabled)
+ wh._save_subscriptions(subs)
+ return key
+
+ key = await config_scoped_to_thread(profile, _run)
return {"ok": True, "name": key, "enabled": bool(body.enabled)}
@@ -301,7 +332,7 @@ def _pool_entry_summary(entry: Any, index: int) -> Dict[str, Any]:
@router.get("/api/credentials/pool")
-async def list_credential_pool():
+async def list_credential_pool(profile: Optional[str] = None):
from agent.credential_pool import load_pool
from hermes_cli.auth import read_credential_pool
@@ -323,11 +354,14 @@ async def list_credential_pool():
})
return {"providers": providers}
- return await asyncio.to_thread(_run)
+ # A named profile reads only its own auth.json (#111724), and the store path
+ # resolves at call time — so the pool the dashboard shows is the one the
+ # requested profile's agent would actually use.
+ return await config_scoped_to_thread(profile, _run)
@router.post("/api/credentials/pool")
-async def add_credential_pool_entry(body: CredentialPoolAdd):
+async def add_credential_pool_entry(body: CredentialPoolAdd, profile: Optional[str] = None):
import uuid
from agent.credential_pool import (
AUTH_TYPE_API_KEY,
@@ -381,11 +415,11 @@ async def add_credential_pool_entry(body: CredentialPoolAdd):
_log.exception("POST /api/credentials/pool failed")
raise HTTPException(status_code=400, detail=str(exc)) from exc
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(profile, _run)
@router.delete("/api/credentials/pool/{provider}/{index}")
-async def remove_credential_pool_entry(provider: str, index: int):
+async def remove_credential_pool_entry(provider: str, index: int, profile: Optional[str] = None):
"""Remove a pool entry (``index`` is 1-based, as listed).
Removal must be sticky: ``load_pool()`` re-seeds entries from their backing
@@ -433,7 +467,8 @@ async def remove_credential_pool_entry(provider: str, index: int):
_log.exception("suppress_credential_source failed")
return {"ok": True, "provider": provider, "count": len(pool.entries()), "cleaned": cleaned, "hints": hints}
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(
+ destructive_profile(profile, "DELETE /api/credentials/pool/{provider}/{index}"), _run)
# --- Memory provider: setup is dashboard-native only via get_config_schema();
@@ -444,7 +479,7 @@ _MEMORY_FILES = (("MEMORY.md", "memory"), ("USER.md", "user"))
@router.get("/api/memory")
-async def get_memory_status():
+async def get_memory_status(profile: Optional[str] = None):
def _run(): # load_config(), stats and discovery are disk reads — off-loop
cfg = load_config()
mem = cfg.get("memory")
@@ -456,16 +491,16 @@ async def get_memory_status():
files[key] = path.stat().st_size if path.exists() else 0
return {"active": active, "providers": _discover_memory_provider_statuses(), "builtin_files": files}
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(profile, _run)
@router.put("/api/memory/provider")
-async def set_memory_provider(body: MemoryProviderSelect):
+async def set_memory_provider(body: MemoryProviderSelect, profile: Optional[str] = None):
provider = _normalize_memory_provider_name(body.provider)
def _run():
_require_memory_provider_ready(provider)
- with _CONFIG_MUTATION_LOCK:
+ with config_write_scope(profile):
cfg = load_config()
if not isinstance(cfg.get("memory"), dict):
cfg["memory"] = {}
@@ -477,22 +512,26 @@ async def set_memory_provider(body: MemoryProviderSelect):
@router.post("/api/memory/reset")
-async def reset_memory(body: MemoryReset):
+async def reset_memory(body: MemoryReset, profile: Optional[str] = None):
target = (body.target or "all").strip().lower()
if target not in {"all", "memory", "user"}:
raise HTTPException(status_code=400, detail="target must be all, memory, or user")
+ profile = destructive_profile(profile, "POST /api/memory/reset")
- mem_dir = get_hermes_home() / "memories"
- deleted = []
- for fname, key in _MEMORY_FILES:
- path = mem_dir / fname
- if target in {"all", key} and path.exists():
- try:
- path.unlink()
- deleted.append(fname)
- except OSError as exc:
- raise HTTPException(status_code=500, detail=f"Could not delete {fname}: {exc}")
- return {"ok": True, "deleted": deleted}
+ def _run():
+ mem_dir = get_hermes_home() / "memories"
+ deleted = []
+ for fname, key in _MEMORY_FILES:
+ path = mem_dir / fname
+ if target in {"all", key} and path.exists():
+ try:
+ path.unlink()
+ deleted.append(fname)
+ except OSError as exc:
+ raise HTTPException(status_code=500, detail=f"Could not delete {fname}: {exc}")
+ return {"ok": True, "deleted": deleted}
+
+ return await config_scoped_to_thread(profile, _run)
# --- Operations: long-running text-output commands (doctor, audit, backup,
@@ -501,44 +540,48 @@ async def reset_memory(body: MemoryReset):
@router.post("/api/ops/doctor")
-async def run_doctor():
- return _spawn_action(["doctor"], "doctor", log_msg="Failed to spawn doctor", prefix="Failed to run doctor")
+async def run_doctor(profile: Optional[str] = None):
+ return _spawn_action(["doctor"], "doctor", log_msg="Failed to spawn doctor",
+ prefix="Failed to run doctor", profile=profile)
@router.post("/api/ops/security-audit")
-async def run_security_audit():
+async def run_security_audit(profile: Optional[str] = None):
return _spawn_action(
["security", "audit"], "security-audit",
- log_msg="Failed to spawn security audit", prefix="Failed to run security audit",
+ log_msg="Failed to spawn security audit", prefix="Failed to run security audit", profile=profile,
)
-def _dashboard_backup_dir() -> Path:
- return get_hermes_home() / "backups"
+def _dashboard_backup_dir(profile: Optional[str] = None) -> Path:
+ """``<profile home>/backups`` — the archive belongs to the profile it backs up."""
+ with _config_profile_scope(profile):
+ return get_hermes_home() / "backups"
@router.post("/api/ops/backup")
-async def run_backup(body: BackupRequest):
+async def run_backup(body: BackupRequest, profile: Optional[str] = None):
archive: Optional[Path] = None
output = (body.output or "").strip()
if not output:
stamp = datetime.now().strftime("%Y-%m-%d-%H%M%S")
- archive = _dashboard_backup_dir() / f"hermes-backup-{stamp}-{secrets.token_hex(4)}.zip"
+ archive = _dashboard_backup_dir(profile) / f"hermes-backup-{stamp}-{secrets.token_hex(4)}.zip"
try:
archive.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not create backup directory: {exc}")
output = str(archive)
- response = _spawn_action(["backup", "-o", output], "backup", log_msg="Failed to spawn backup", prefix="Failed to run backup")
+ response = _spawn_action(["backup", "-o", output], "backup", log_msg="Failed to spawn backup",
+ prefix="Failed to run backup", profile=profile)
if archive is not None:
response["archive"] = str(archive)
return response
@router.get("/api/ops/backup/download")
-async def download_dashboard_backup(archive: str):
+async def download_dashboard_backup(archive: str, profile: Optional[str] = None):
try:
- backup_dir = _dashboard_backup_dir().expanduser().resolve(strict=False)
+ backup_dir = _dashboard_backup_dir(profile).expanduser().resolve(strict=False)
target = Path(archive).expanduser().resolve(strict=True)
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Backup not found")
@@ -554,21 +597,23 @@ async def download_dashboard_backup(archive: str):
)
-def _spawn_import(archive: str, force: bool) -> dict:
+def _spawn_import(archive: str, force: bool, profile: Optional[str] = None) -> dict:
args = ["import", archive]
if force:
args.append("--force")
- return _spawn_action(args, "import", log_msg="Failed to spawn import", prefix="Failed to run import")
+ return _spawn_action(args, "import", log_msg="Failed to spawn import",
+ prefix="Failed to run import", profile=profile)
@router.post("/api/ops/import")
-async def run_import(body: ImportRequest):
+async def run_import(body: ImportRequest, profile: Optional[str] = None):
+ profile = destructive_profile(profile, "POST /api/ops/import")
archive = (body.archive or "").strip()
if not archive:
raise HTTPException(status_code=400, detail="archive path is required")
if not os.path.isfile(archive):
raise HTTPException(status_code=404, detail=f"Archive not found: {archive}")
- return _spawn_import(archive, body.force)
+ return _spawn_import(archive, body.force, profile)
def _safe_backup_upload_name(filename: str | None) -> str:
@@ -583,8 +628,10 @@ def _safe_backup_upload_name(filename: str | None) -> str:
async def run_import_upload(
file: UploadFile = File(...),
force: bool = Form(False),
+ profile: Optional[str] = None,
):
- staging_dir = _dashboard_backup_dir()
+ profile = destructive_profile(profile, "POST /api/ops/import-upload")
+ staging_dir = _dashboard_backup_dir(profile)
try:
staging_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
@@ -599,11 +646,11 @@ async def run_import_upload(
if not zipfile.is_zipfile(target):
target.unlink(missing_ok=True)
raise HTTPException(status_code=400, detail="Uploaded archive is not a valid zip file")
- return {**_spawn_import(str(target), force), "archive": str(target), "uploaded_bytes": total}
+ return {**_spawn_import(str(target), force, profile), "archive": str(target), "uploaded_bytes": total}
@router.get("/api/ops/hooks")
-async def list_hooks():
+async def list_hooks(profile: Optional[str] = None):
"""Configured shell hooks with consent (allowlist) status, whether the
script is currently executable, and the valid hook events for the form."""
def _run():
@@ -640,7 +687,7 @@ async def list_hooks():
})
return {"hooks": out, "valid_events": valid_events}
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(profile, _run)
def _hook_body_fields(body) -> tuple[str, str]:
@@ -652,7 +699,7 @@ def _hook_body_fields(body) -> tuple[str, str]:
@router.post("/api/ops/hooks")
-async def create_hook(body: HookCreate):
+async def create_hook(body: HookCreate, profile: Optional[str] = None):
"""Add a shell hook to config.yaml and optionally record consent.
Shell hooks run arbitrary commands, so this is privileged: it writes the
@@ -669,7 +716,7 @@ async def create_hook(body: HookCreate):
raise HTTPException(status_code=400, detail=f"Unknown event '{event}'. Valid: {', '.join(sorted(valid_hooks))}")
def _run():
- with _CONFIG_MUTATION_LOCK:
+ with config_write_scope(profile):
cfg = load_config()
hooks_cfg = cfg.get("hooks")
if not isinstance(hooks_cfg, dict):
@@ -694,19 +741,20 @@ async def create_hook(body: HookCreate):
_log.exception("hook consent record failed")
return {"ok": True, "event": event, "command": command, "approved": approved}
- return await asyncio.to_thread(_run)
+ return await config_scoped_to_thread(profile, _run)
@router.delete("/api/ops/hooks")
-async def delete_hook(body: HookDelete):
+async def delete_hook(body: HookDelete, profile: Optional[str] = None):
"""Remove a hook from config.yaml and revoke its consent allowlist entry."""
from agent import shell_hooks
+ profile = destructive_profile(profile, "DELETE /api/ops/hooks")
event, command = _hook_body_fields(body)
def _run():
removed = False
- with _CONFIG_MUTATION_LOCK:
+ with config_write_scope(profile):
cfg = load_config()
hooks_cfg = cfg.get("hooks")
if isinstance(hooks_cfg, dict) and isinstance(hooks_cfg.get(event), list):
@@ -726,41 +774,45 @@ async def delete_hook(body: HookDelete):
shell_hooks.revoke(command)
return removed
- if not await asyncio.to_thread(_run):
+ if not await config_scoped_to_thread(profile, _run):
raise HTTPException(status_code=404, detail="No matching hook found")
return {"ok": True}
@router.get("/api/ops/checkpoints")
-async def list_checkpoints():
+async def list_checkpoints(profile: Optional[str] = None):
"""/rollback shadow-store checkpoints (read-only): count + size per session
so the UI can show what a prune reclaims; pruning itself is a spawned CLI
action so the confirmation logic stays in one place."""
- cp_dir = get_hermes_home() / "checkpoints"
- sessions = []
- total_bytes = 0
- if cp_dir.is_dir():
- with os.scandir(cp_dir) as scan:
- children = sorted((Path(e.path) for e in scan), key=lambda p: p.name)
- for child in children:
- if not child.is_dir():
- continue
- size = count = 0
- for f in child.rglob("*"):
- if f.is_file():
- try:
- size += f.stat().st_size
- count += 1
- except OSError:
- pass
- total_bytes += size
- sessions.append({"session": child.name, "files": count, "bytes": size})
- return {"sessions": sessions, "total_bytes": total_bytes}
+ def _run():
+ cp_dir = get_hermes_home() / "checkpoints"
+ sessions = []
+ total_bytes = 0
+ if cp_dir.is_dir():
+ with os.scandir(cp_dir) as scan:
+ children = sorted((Path(e.path) for e in scan), key=lambda p: p.name)
+ for child in children:
+ if not child.is_dir():
+ continue
+ size = count = 0
+ for f in child.rglob("*"):
+ if f.is_file():
+ try:
+ size += f.stat().st_size
+ count += 1
+ except OSError:
+ pass
+ total_bytes += size
+ sessions.append({"session": child.name, "files": count, "bytes": size})
+ return {"sessions": sessions, "total_bytes": total_bytes}
+
+ return await config_scoped_to_thread(profile, _run)
@router.post("/api/ops/checkpoints/prune")
-async def prune_checkpoints():
+async def prune_checkpoints(profile: Optional[str] = None):
return _spawn_action(
["checkpoints", "prune"], "checkpoints-prune",
log_msg="Failed to spawn checkpoints prune", prefix="Failed to prune checkpoints",
+ profile=destructive_profile(profile, "POST /api/ops/checkpoints/prune"),
)
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index 0581514a03f..0b1b75cd0fc 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -26,7 +26,7 @@ from hermes_cli import __version__, __release_date__
from hermes_cli.config import get_config_path, get_env_path
from hermes_constants import get_process_hermes_home, profile_name_for_home
from hermes_cli.web_models import CuratorPause, LearningNodeRef, LearningNodeEdit, DebugShareRequest
-from hermes_cli.web_routers._common import scoped_to_thread
+from hermes_cli.web_routers._common import config_scoped_to_thread, destructive_profile, scoped_to_thread
from pathlib import Path
from typing import Any, Dict, Optional
@@ -49,6 +49,7 @@ _ssh_runtime_intact = late("_ssh_runtime_intact")
app = LateState("app") # the FastAPI instance (app.state.*)
check_config_version = late("check_config_version", "hermes_cli.config")
get_hermes_home = late("get_hermes_home", "hermes_cli.config")
+_profile_cli_args = late("_profile_cli_args", "hermes_cli.web_server_profiles")
get_install_id = late("get_install_id")
get_running_pid_cached = late("get_running_pid_cached", "gateway.status")
get_runtime_status_running_pid = late("get_runtime_status_running_pid", "gateway.status")
@@ -605,41 +606,51 @@ async def get_system_stats():
@router.get("/api/curator")
-async def get_curator_status():
+async def get_curator_status(profile: Optional[str] = None):
try:
from agent import curator
except Exception as exc:
raise HTTPException(status_code=500, detail=f"Curator unavailable: {exc}")
- state = _safe_call(curator, "load_state", {})
- return {
- "enabled": _safe_call(curator, "is_enabled", True),
- "paused": _safe_call(curator, "is_paused", False),
- "interval_hours": _safe_call(curator, "get_interval_hours", None),
- "last_run_at": state.get("last_run_at"),
- **{key: _safe_call(curator, f"get_{key}", None)
- for key in ("min_idle_hours", "stale_after_days", "archive_after_days")}}
+
+ def _run():
+ state = _safe_call(curator, "load_state", {})
+ return {
+ "enabled": _safe_call(curator, "is_enabled", True),
+ "paused": _safe_call(curator, "is_paused", False),
+ "interval_hours": _safe_call(curator, "get_interval_hours", None),
+ "last_run_at": state.get("last_run_at"),
+ **{key: _safe_call(curator, f"get_{key}", None)
+ for key in ("min_idle_hours", "stale_after_days", "archive_after_days")}}
+
+ return await config_scoped_to_thread(profile, _run)
@router.put("/api/curator/paused")
-async def set_curator_paused(body: CuratorPause):
+async def set_curator_paused(body: CuratorPause, profile: Optional[str] = None):
from agent import curator
- curator.set_paused(bool(body.paused))
+ # ``_state_file()`` is ``get_hermes_home()/skills/.curator_state`` resolved at call
+ # time, so the request's home override is what decides which profile pauses.
+ await config_scoped_to_thread(profile, lambda: curator.set_paused(bool(body.paused)))
return {"ok": True, "paused": bool(body.paused)}
-def _spawn_action(argv: list, name: str, prefix: str) -> dict:
- """Spawn a background ``hermes <argv>`` action; a spawn failure is ``500 "<prefix>: <exc>"``."""
+def _spawn_action(argv: list, name: str, prefix: str, profile: Optional[str] = None) -> dict:
+ """Spawn a background ``hermes -p <profile> <argv>`` action; a spawn failure is
+ ``500 "<prefix>: <exc>"``."""
try:
- proc = _spawn_hermes_action(argv, name)
+ proc = _spawn_hermes_action(_profile_cli_args(profile) + argv, name)
except Exception as exc:
raise HTTPException(status_code=500, detail=f"{prefix}: {exc}")
return {"ok": True, "pid": proc.pid, "name": name}
@router.post("/api/curator/run")
-async def run_curator():
- """Trigger a curator review now (backgrounded; tail via action status)."""
- return _spawn_action(["curator", "run"], "curator-run", "Failed to run curator")
+async def run_curator(profile: Optional[str] = None):
+ """Trigger a curator review now (backgrounded; tail via action status). The curator
+ archives and rewrites skills, so an unnamed target is refused while this backend
+ serves several profiles."""
+ return _spawn_action(["curator", "run"], "curator-run", "Failed to run curator",
+ destructive_profile(profile, "POST /api/curator/run"))
@router.get("/api/learning/graph")
@@ -694,10 +705,10 @@ async def update_learning_node(body: LearningNodeEdit):
@router.get("/api/portal")
-async def get_portal_status():
+async def get_portal_status(profile: Optional[str] = None):
# load_config() + auth/subscription snapshots are disk reads on a polled endpoint —
# keep them off the event loop.
- return await asyncio.to_thread(_get_portal_status_sync)
+ return await config_scoped_to_thread(profile, _get_portal_status_sync)
def _feature_state(feat) -> str:
@@ -744,30 +755,31 @@ def _get_portal_status_sync():
@router.post("/api/ops/prompt-size")
-async def run_prompt_size():
- return _spawn_action(["prompt-size"], "prompt-size", "Failed")
+async def run_prompt_size(profile: Optional[str] = None):
+ return _spawn_action(["prompt-size"], "prompt-size", "Failed", profile)
@router.post("/api/ops/dump")
-async def run_dump():
- return _spawn_action(["dump"], "dump", "Failed")
+async def run_dump(profile: Optional[str] = None):
+ return _spawn_action(["dump"], "dump", "Failed", profile)
@router.post("/api/ops/config-migrate")
-async def run_config_migrate():
- return _spawn_action(["config", "migrate"], "config-migrate", "Failed")
+async def run_config_migrate(profile: Optional[str] = None):
+ return _spawn_action(["config", "migrate"], "config-migrate", "Failed", profile)
@router.post("/api/ops/debug-share")
-async def run_debug_share_endpoint(body: DebugShareRequest | None = None):
+async def run_debug_share_endpoint(body: DebugShareRequest | None = None,
+ profile: Optional[str] = None):
"""Upload a redacted debug report + full logs and return the paste URLs. Synchronous,
unlike the other diagnostics actions: the point is the shareable URLs, returned as a
structured payload the dashboard renders as copyable links."""
from hermes_cli.debug import build_debug_share
req = body or DebugShareRequest()
try:
- result = await asyncio.to_thread(
- build_debug_share, log_lines=max(1, min(int(req.lines), 5000)), redact=bool(req.redact))
+ result = await config_scoped_to_thread(profile, lambda: build_debug_share(
+ log_lines=max(1, min(int(req.lines), 5000)), redact=bool(req.redact)))
except RuntimeError as exc:
# Required summary-report upload failed (offline / paste service down).
raise HTTPException(status_code=502, detail=f"Upload failed: {exc}")
@@ -782,12 +794,14 @@ async def run_debug_share_endpoint(body: DebugShareRequest | None = None):
@logs_router.get("/api/logs")
async def get_logs(
file: str = "agent", lines: int = 100, level: Optional[str] = None,
- component: Optional[str] = None, search: Optional[str] = None):
+ component: Optional[str] = None, search: Optional[str] = None,
+ profile: Optional[str] = None):
from hermes_cli.logs import _read_tail, LOG_FILES
log_name = LOG_FILES.get(file)
if not log_name:
raise HTTPException(status_code=400, detail=f"Unknown log file: {file}")
- log_path = get_hermes_home() / "logs" / log_name
+ with _config_profile_scope(profile):
+ log_path = get_hermes_home() / "logs" / log_name
if not log_path.exists():
return {"file": file, "lines": []}
diff --git a/tests/hermes_cli/test_web_routers_destructive_profile_scope.py b/tests/hermes_cli/test_web_routers_destructive_profile_scope.py
new file mode 100644
index 00000000000..42130ff34fa
--- /dev/null
+++ b/tests/hermes_cli/test_web_routers_destructive_profile_scope.py
@@ -0,0 +1,109 @@
+"""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 the two halves of the contract for the destructive routes:
+* a named profile is the one that gets wiped, and the launch profile survives;
+* an UNNAMED profile is refused (400) while several profiles are served, and still
+ means the launch profile on a genuinely single-profile host.
+"""
+import json
+
+import pytest
+import yaml
+
+import agent.secret_scope as _secret_scope
+
+
+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": {"PreToolUse": [{"command": "/bin/true"}]}}), encoding="utf-8")
+ (beta / ".env").write_text("", 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}
+
+
+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
+
+
+def _hooks(home):
+ return (yaml.safe_load((home / "config.yaml").read_text()) or {}).get("hooks") or {}
+
+
+# (call, what proves the named profile was hit, what proves the other was not)
+DESTRUCTIVE = {
+ "memory-reset": (
+ lambda c, q: c.post(f"/api/memory/reset{q}", json={"target": "all"}),
+ lambda home: not (home / "memories" / "MEMORY.md").exists(),
+ ),
+ "webhook-delete": (
+ lambda c, q: c.delete(f"/api/webhooks/alerts{q}"),
+ lambda home: "alerts" not in json.loads((home / "webhook_subscriptions.json").read_text()),
+ ),
+ "hook-delete": (
+ lambda c, q: c.request("DELETE", f"/api/ops/hooks{q}",
+ json={"event": "PreToolUse", "command": "/bin/true"}),
+ lambda home: not _hooks(home),
+ ),
+}
+
+
[email protected]("route", sorted(DESTRUCTIVE))
+def test_destructive_route_hits_the_named_profile_only(client, homes, route):
+ call, gone = DESTRUCTIVE[route]
+ resp = call(client, "?profile=worker_beta")
+ assert resp.status_code == 200, resp.text
+ assert gone(homes["worker_beta"]), f"{route} did not act on worker_beta"
+ assert not gone(homes["launch"]), f"{route} also hit the launch profile"
+
+
[email protected]("route", sorted(DESTRUCTIVE))
+def test_destructive_route_refuses_an_unnamed_profile_while_multiplexing(
+ client, homes, monkeypatch, route
+):
+ call, gone = DESTRUCTIVE[route]
+ monkeypatch.setattr(_secret_scope, "is_multiplex_active", lambda: True)
+ resp = call(client, "")
+ assert resp.status_code == 400, resp.text
+ assert "explicit profile" in resp.json()["detail"]
+ assert not gone(homes["launch"]), f"{route} mutated the launch profile despite the 400"
+ assert not gone(homes["worker_beta"])
+
+
+def test_unnamed_profile_still_means_the_launch_profile_on_a_single_profile_host(
+ client, homes, monkeypatch
+):
+ """A plain ``hermes serve`` has nothing to confuse: `curl` with no profile is unchanged."""
+ monkeypatch.setattr(_secret_scope, "is_multiplex_active", lambda: False)
+ 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()
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 57440e93ee6..c50810ed0ae 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -69,9 +69,9 @@ export function getManagementProfile(): string {
}
// Endpoint families that honor ?profile= on the backend (web_server.py
-// _profile_scope or explicit per-profile DB opens). Anything else — ops,
-// cron (which has its own per-job profile params), profiles themselves — is
-// machine-global or self-scoped and must NOT be rewritten.
+// _profile_scope or explicit per-profile DB opens). Anything else — cron (which
+// has its own per-job profile params), profiles themselves — is machine-global or
+// self-scoped and must NOT be rewritten.
const PROFILE_SCOPED_PREFIXES = [
"/api/status",
"/api/gateway",
@@ -97,6 +97,20 @@ const PROFILE_SCOPED_PREFIXES = [
// consults that one — approving into the global store would grant access
// the running gateway never sees.
"/api/pairing",
+ // Memory files, the curator state file, webhook subscriptions, shell hooks,
+ // checkpoints, backups/imports and the dashboard's own theme/font/plugin
+ // preferences all live in a profile home. One backend now serves every
+ // profile, so the switcher's selection has to ride on the request or a reset
+ // lands on the launch profile's data.
+ "/api/memory",
+ "/api/curator",
+ "/api/webhooks",
+ "/api/ops",
+ "/api/logs",
+ "/api/portal",
+ "/api/dashboard/theme",
+ "/api/dashboard/font",
+ "/api/dashboard/plugins",
];
function withManagementProfile(url: string): string {