diff --git a/README-API.md b/README-API.md index 0e73020..87df699 100644 --- a/README-API.md +++ b/README-API.md @@ -49,6 +49,12 @@ Entries are split on Hermes' built-in delimiter §. The response includes entry count, char count, configured/default char limits, usage percentage, file path, and modified timestamp. +Optional `memory_profile` selects a profile for these two files independently of the host's `profile` parameter. Omitted, empty, or `current` uses the request's active profile. Explicit names require the original request's host authorization and the target profile's plugin consent before reading files or limits in that profile's context-local scope. Native profile grants cannot read another profile (403); disabled or unavailable target plugins return 404. For unrestricted host sessions, invalid names return 400 and missing profiles return 404. Hosts unable to verify cross-profile authority return 501 for explicit names, including isolated plugin hosts whose IPC admission does not carry the principal's profile authority. + +### GET `/builtin/profiles` + +Returns `{ "profiles": [{ "name": "current", "label": "Active profile", "hermes_home": "..." }], "switching_supported": false }` when host authorization is unavailable. Hosts with native discovery and the complete authorization boundary also return live profiles the request may access and that permit this plugin, with their labels and home paths, and set `switching_supported` to true. Inaccessible, disabled, missing, and reserved names are omitted before reading their display metadata. The `current` entry always represents the request's active home, including a custom `HERMES_HOME`. This endpoint does not read memory files or contact memory providers. + ### GET `/session-search` Runs an explicit read-only search over previous Hermes sessions through Hermes' built-in `session_search` tool. This endpoint is not called from `/snapshot` or page load; the UI calls it only after the user submits a query. diff --git a/README.md b/README.md index 56936b5..bd78571 100644 --- a/README.md +++ b/README.md @@ -199,12 +199,15 @@ Top summary: Built-in memory section: +- Profile / bot selector for the active profile and other profiles authorized by the host in both Dashboard and Desktop - Agent memory card (`MEMORY.md`) - User profile card (`USER.md`) - path, file existence, modification time - entry count and char usage bar - parsed entries +The built-in memory selector changes only the two file cards. Provider and session views continue to follow the host's active profile. Each card shows the selected profile's file path and character limit. Switching profiles or Desktop connections hides the previous files while the new files load. Use the built-in refresh button to reload files and discover newly created profiles. Cross-profile choices require both host access authorization and the target profile's plugin consent. Hosts that cannot verify that authority, including isolated plugin hosts that receive only an admission boolean, offer the active profile only. + Session search section: - explicit query box for previous Hermes sessions diff --git a/dashboard/dist/index.js b/dashboard/dist/index.js index 8616792..37c391f 100644 --- a/dashboard/dist/index.js +++ b/dashboard/dist/index.js @@ -160,7 +160,7 @@ e("div", { className: "memory-ui-section-header" }, e("div", null, e("h2", null, "Built-in memory"), - e("p", null, "Read-only view of MEMORY.md and USER.md from the active Hermes profile.") + e("p", null, "Read-only view of MEMORY.md and USER.md from the selected Hermes profile.") ), e(Badge, { tone: "outline" }, builtin.total_entries + " total entries") ), @@ -172,6 +172,80 @@ ); } + function BuiltinProfileBrowser(props) { + const [profile, setProfile] = useState("current"); + const [profiles, setProfiles] = useState([{ name: "current", label: "Active profile" }]); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const [profilesError, setProfilesError] = useState(null); + const [revision, setRevision] = useState(0); + + useEffect(function () { + let active = true; + fetchPluginJSON("/api/plugins/hermes-memory-ui/builtin/profiles") + .then(function (payload) { + if (active) { + if (payload === STALE_PROFILE_RESPONSE) { + setProfilesError("The host profile changed. Refresh built-in memory to reload profiles."); + } else { + setProfiles(payload.profiles || [{ name: "current", label: "Active profile" }]); + setProfilesError(null); + } + } + }) + .catch(function (err) { if (active) setProfilesError(err.message || String(err)); }); + return function () { active = false; }; + }, [revision]); + + useEffect(function () { + if (profile === "current" && revision === 0) return; + let active = true; + setError(null); + const path = "/api/plugins/hermes-memory-ui/builtin?memory_profile=" + encodeURIComponent(profile); + fetchPluginJSON(path) + .then(function (payload) { + if (active) { + if (payload === STALE_PROFILE_RESPONSE) { + setError({ profile: profile, source: props.builtin, message: "The host profile changed. Refresh built-in memory to reload." }); + } else { + setResult({ profile: profile, source: props.builtin, builtin: payload }); + } + } + }) + .catch(function (err) { if (active) setError({ profile: profile, source: props.builtin, message: err.message || String(err) }); }); + return function () { active = false; }; + }, [profile, revision]); + + const currentError = error && error.profile === profile && (profile !== "current" || error.source === props.builtin) + ? error.message : null; + const builtin = currentError ? null : profile === "current" + ? result && result.profile === "current" && result.source === props.builtin ? result.builtin : props.builtin + : result && result.profile === profile ? result.builtin : null; + const options = profiles.some(function (item) { return item.name === profile; }) + ? profiles : profiles.concat([{ name: profile, label: profile + " (unavailable)" }]); + return e("div", { className: "memory-ui-section" }, + e("div", { className: "memory-ui-controls" }, + e("label", { className: "memory-ui-control" }, + e("span", null, "Built-in memory profile / bot"), + e("select", { + className: "memory-ui-select", + value: profile, + onChange: function (event) { setProfile(event.target.value); setRevision(0); }, + "aria-label": "Built-in memory profile / bot" + }, options.map(function (item) { + return e("option", { key: item.name, value: item.name }, item.label || item.name); + })) + ), + e(Button, { variant: "outline", onClick: function () { setRevision(function (value) { return value + 1; }); } }, "Refresh built-in memory") + ), + e("p", { className: "memory-ui-muted" }, "Select a profile to read its MEMORY.md and USER.md. Provider and session views follow the host's active profile."), + e(ErrorBox, { error: profilesError }), + e(ErrorBox, { error: currentError }), + builtin ? e(BuiltinSection, { builtin: builtin }) + : currentError ? null : e(EmptyState, null, "Loading built-in memory...") + ); + } + function SessionSearchResultRow(props) { const result = props.result || {}; const messages = (result.messages || []).slice(0, 4); @@ -1096,7 +1170,7 @@ ) ), snapshot ? e(React.Fragment, null, - e(BuiltinSection, { builtin: builtin }), + e(BuiltinProfileBrowser, { builtin: builtin }), e(Separator, null), e(SessionSearchSection, null), showHolographic ? e(React.Fragment, null, diff --git a/dashboard/plugin_api.py b/dashboard/plugin_api.py index b5c68ce..17529cd 100644 --- a/dashboard/plugin_api.py +++ b/dashboard/plugin_api.py @@ -14,6 +14,7 @@ import importlib import importlib.util import json +import logging import os import re import shutil @@ -23,12 +24,13 @@ import threading import time import urllib.parse +from contextlib import asynccontextmanager from contextvars import copy_context from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple try: - from fastapi import APIRouter, Depends, HTTPException, Query + from fastapi import APIRouter, Depends, HTTPException, Query, Request except Exception: # Allows local syntax/import tests outside the dashboard. class APIRouter: # type: ignore def __init__(self, *_args, **_kwargs): @@ -49,6 +51,9 @@ def __init__(self, status_code: int, detail: str): def Query(default=None, **_kwargs): # type: ignore return default + class Request: # type: ignore + pass + async def _profile_request_scope(profile: Optional[str] = Query(None)): """Bind one plugin request to its explicitly selected Hermes profile. @@ -371,6 +376,97 @@ def _builtin_payload(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: } +def _builtin_profile_access(request: Optional[Request]): + """Host policy hooks only when the original request authority is available. + + The isolated plugin host forwards admission, but strips credentials and the + native ticket's profile authority. That boolean cannot authorize another + profile. Older hosts without the complete policy boundary also stay local. + """ + if request is None or "hosted_http_authenticated" in request.scope.get("state", {}): + return None + try: + from hermes_cli.web_server import _require_token + from hermes_cli.dashboard_auth.native_http import _own_profile + from hermes_cli.web_server_dashboard import _plugin_api_request_refused + from hermes_cli.web_server_profiles import _config_profile_scope + except (ImportError, AttributeError): + return None + _require_token(request) + return _own_profile, _plugin_api_request_refused, _config_profile_scope + + +@asynccontextmanager +async def _builtin_selected_scope(request: Optional[Request], name: str, access): + if access is None: + raise HTTPException(status_code=501, detail="This Hermes host cannot authorize cross-profile memory access.") + own_profile, consent_refused, profile_scope = access + principal = getattr(request.state, "native_http_principal", None) + if principal is not None: + try: + own_profile(name, principal["profile_id"]) + except PermissionError as exc: + raise HTTPException(status_code=403, detail="profile_scope_mismatch") from exc + with profile_scope(name): + if await consent_refused("hermes-memory-ui"): + raise HTTPException(status_code=404, detail="Plugin not found") + yield + + +async def _builtin_profiles_payload(request: Optional[Request] = None) -> Dict[str, Any]: + """Discover request-addressable homes from Hermes' live-profile registry. + + The current choice also covers custom HERMES_HOME deployments. Never guess + profile paths on older hosts: discovery is useful only when the same host + can safely scope the subsequent memory read. + """ + entries = [{ + "name": "current", + "label": "Active profile", + "hermes_home": str(_hermes_home()), + }] + access = _builtin_profile_access(request) + if access is None: + return {"profiles": entries, "switching_supported": False} + try: + from hermes_cli.profiles import get_profile_dir, list_profile_names, profile_exists, validate_profile_name + except (ImportError, AttributeError): + return {"profiles": entries, "switching_supported": False} + + try: + from hermes_cli.profiles import read_profile_meta + except (ImportError, AttributeError): + read_profile_meta = None + + for name in list_profile_names(): + # Legacy directories can remain in the registry under names the host's + # request resolver now rejects. Offer only profiles it can address. + try: + validate_profile_name(name) + except ValueError: + continue + # A profile may be removed between discovery and this response. + if name == "current" or not profile_exists(name): + continue + try: + async with _builtin_selected_scope(request, name, access): + home = get_profile_dir(name) + meta = read_profile_meta(home) if read_profile_meta else {} + except Exception as exc: + # Discovery must survive one broken profile's secret sources or + # metadata. Explicit reads still surface that target's failure. + if not isinstance(exc, HTTPException) or exc.status_code not in (400, 403, 404): + logging.getLogger(__name__).warning("Skipping memory profile %s: %s", name, _safe_error(exc)) + continue + title = str(meta.get("bot_title") or meta.get("display_name") or "").strip() + entries.append({ + "name": name, + "label": f"{title} ({name})" if title and title != name else name, + "hermes_home": str(home), + }) + return {"profiles": entries, "switching_supported": True} + + def _canonical_session_source(source: str) -> str: """Return the canonical Hermes session source for dashboard filter values.""" if not isinstance(source, str): @@ -2600,8 +2696,19 @@ async def status() -> Dict[str, Any]: @router.get("/builtin") -async def builtin() -> Dict[str, Any]: - return _builtin_payload() +async def builtin(memory_profile: Optional[str] = None, request: Request = None) -> Dict[str, Any]: + # This selector is independent of the host's ?profile= scope. In particular, + # Desktop's ctx.rest continues to scope all other providers to its active bot. + requested = (memory_profile or "").strip() + if not requested or requested.lower() == "current": + return _builtin_payload() + async with _builtin_selected_scope(request, requested, _builtin_profile_access(request)): + return _builtin_payload() + + +@router.get("/builtin/profiles") +async def builtin_profiles(request: Request = None) -> Dict[str, Any]: + return await _builtin_profiles_payload(request) @router.get("/session-search") diff --git a/desktop/plugin.js b/desktop/plugin.js index eb96279..dd7e7ba 100644 --- a/desktop/plugin.js +++ b/desktop/plugin.js @@ -19,7 +19,8 @@ import { host, useMutation, usePluginI18n, - useQuery + useQuery, + useValue } from '@hermes/plugin-sdk' import { useEffect, useMemo, useState } from 'react' import { Fragment, jsx, jsxs } from 'react/jsx-runtime' @@ -95,7 +96,10 @@ const bundles = { failed: 'Unable to load memory', empty: 'Nothing to show', builtin: 'Built-in memory', - builtinHint: 'The active profile files Hermes reads directly.', + builtinHint: 'Choose a profile to read its MEMORY.md and USER.md. Other sections follow the active profile.', + memoryProfile: 'Memory profile / bot', + activeProfile: 'Active profile', + refreshMemory: 'Refresh memory', providers: 'Configured providers', providerHint: 'Read-only provider state and visible memory collections.', sessions: 'Session search', @@ -192,7 +196,10 @@ const bundles = { failed: '无法加载记忆', empty: '没有可显示的内容', builtin: '内置记忆', - builtinHint: 'Hermes 直接读取的当前配置下的记忆文件。', + builtinHint: '选择配置以查看其 MEMORY.md 和 USER.md。其他区域仍使用当前配置。', + memoryProfile: '记忆配置 / 机器人', + activeProfile: '当前配置', + refreshMemory: '刷新记忆', providers: '已配置的记忆提供方', providerHint: '只读查看记忆提供方的状态和可见的记忆集合。', sessions: '会话搜索', @@ -289,7 +296,10 @@ const bundles = { failed: 'Nie można wczytać pamięci', empty: 'Brak danych do pokazania', builtin: 'Wbudowana pamięć', - builtinHint: 'Pliki aktywnego profilu odczytywane bezpośrednio przez Hermes.', + builtinHint: 'Wybierz profil, aby odczytać jego MEMORY.md i USER.md. Pozostałe sekcje używają aktywnego profilu.', + memoryProfile: 'Profil pamięci / bot', + activeProfile: 'Aktywny profil', + refreshMemory: 'Odśwież pamięć', providers: 'Skonfigurowane źródła', providerHint: 'Stan źródeł i widoczne kolekcje pamięci — tylko do odczytu.', sessions: 'Wyszukiwanie sesji', @@ -442,6 +452,8 @@ export function createMemoryApi(ctx) { search: normalized.search }, 120_000) }, + getBuiltinProfiles: () => get('/builtin/profiles', {}, 30_000), + getBuiltin: (profile = 'current') => get('/builtin', { memory_profile: profile }, 30_000), searchSessions: options => get('/session-search', options, 60_000), queryByteRover: (query, timeout = QUERY_CONTROL_CONFIG.byterover.queryTimeout) => get( '/byterover/query', @@ -879,6 +891,98 @@ function StoreCard({ store, fallbackName, t }) { }) } +function useMemoryScope() { + return { + connectionId: useValue(host.state.connectionId), + hostProfile: useValue(host.state.profile) + } +} + +function matchesMemoryScope(data, scope) { + // null is an unresolved host route, not a shared connection identity. + return scope.connectionId != null && data?.connectionId === scope.connectionId && data?.hostProfile === scope.hostProfile +} + +async function readInMemoryScope(scope, read) { + const currentScope = () => ({ connectionId: host.state.connectionId.get(), hostProfile: host.state.profile.get() }) + // ctx.rest follows the live host route. A retry from an old query must not + // fetch the new gateway into the previous gateway's cache. + if (!matchesMemoryScope(currentScope(), scope)) throw new Error('Memory connection or active profile changed') + const value = await read() + if (!matchesMemoryScope(currentScope(), scope)) throw new Error('Memory connection or active profile changed') + return { ...scope, value } +} + +export function BuiltinMemorySection({ api, builtin, refreshSnapshot, t }) { + const scope = useMemoryScope() + const [profile, setProfile] = useState('current') + const profiles = useQuery({ + queryKey: [PLUGIN_ID, 'builtin-profiles', scope.connectionId, scope.hostProfile], + queryFn: () => readInMemoryScope(scope, () => api.getBuiltinProfiles()), + enabled: scope.connectionId != null, + staleTime: 10_000 + }) + const memory = useQuery({ + queryKey: [PLUGIN_ID, 'builtin', profile, scope.connectionId, scope.hostProfile], + queryFn: async () => ({ profile, ...await readInMemoryScope(scope, () => api.getBuiltin(profile)) }), + enabled: scope.connectionId != null && profile !== 'current', + staleTime: 10_000 + }) + // Tag responses so a host query client that retains previous data cannot + // paint another bot's memory under the newly selected profile. + const selected = scope.connectionId == null ? null : profile === 'current' + ? builtin + : !memory.error && memory.data?.profile === profile && matchesMemoryScope(memory.data, scope) ? memory.data.value : null + const options = [{ value: 'current', label: t('activeProfile') }].concat( + list(matchesMemoryScope(profiles.data, scope) ? profiles.data.value?.profiles : null) + .filter(item => item.name !== 'current') + .map(item => ({ value: item.name, label: item.label || item.name })) + ) + if (!options.some(option => option.value === profile)) { + options.push({ value: profile, label: `${profile} (${t('unavailable')})` }) + } + const refresh = () => { + profiles.refetch() + if (profile === 'current') refreshSnapshot() + else memory.refetch() + } + return jsxs('section', { + className: 'space-y-3', + children: [ + jsx(SectionHeading, { + title: t('builtin'), + description: t('builtinHint'), + aside: selected ? jsx(Badge, { variant: 'outline', children: t('entryCount', finite(selected.total_entries)) }) : null + }), + jsxs('div', { + className: 'flex flex-wrap items-end gap-3', + children: [ + jsx(Field, { + label: t('memoryProfile'), + children: jsx(NativeSelect, { + value: profile, + onValueChange: setProfile, + placeholder: t('activeProfile'), + options + }) + }), + jsx(Button, { + variant: 'outline', + onClick: refresh, + disabled: profile !== 'current' && memory.isLoading, + children: t('refreshMemory') + }) + ] + }), + jsx(ErrorNotice, { error: profiles.error, title: t('failed'), t }), + profile !== 'current' ? jsx(ErrorNotice, { error: memory.error, title: t('failed'), t }) : null, + selected + ? jsx(BuiltinStores, { builtin: selected, t }) + : profile !== 'current' && !memory.error ? jsx(LoadingLine, { label: t('loading') }) : null + ] + }) +} + function BuiltinStores({ builtin, t }) { const stores = Array.isArray(builtin?.stores) ? builtin.stores @@ -888,11 +992,6 @@ function BuiltinStores({ builtin, t }) { return jsxs('section', { className: 'space-y-3', children: [ - jsx(SectionHeading, { - title: t('builtin'), - description: t('builtinHint'), - aside: jsx(Badge, { variant: 'outline', children: t('entryCount', finite(builtin?.total_entries, stores.reduce((sum, store) => sum + finite(store?.entry_count), 0))) }) - }), stores.length ? jsx('div', { className: 'grid gap-3', @@ -1772,15 +1871,18 @@ function SessionSearch({ api, t }) { function MemoryPage({ ctx }) { const t = usePluginI18n(PLUGIN_ID) + const scope = useMemoryScope() const api = useMemo(() => createMemoryApi(ctx), [ctx]) const initialFilters = normalizeSnapshotFilters() const [filters, setFilters] = useState(initialFilters) const [appliedFilters, setAppliedFilters] = useState(initialFilters) - const snapshot = useQuery({ - queryKey: [PLUGIN_ID, 'snapshot', appliedFilters.limit, appliedFilters.minTrust, appliedFilters.category, appliedFilters.search], - queryFn: () => api.getSnapshot(appliedFilters), + const snapshotQuery = useQuery({ + queryKey: [PLUGIN_ID, 'snapshot', scope.connectionId, scope.hostProfile, appliedFilters.limit, appliedFilters.minTrust, appliedFilters.category, appliedFilters.search], + queryFn: () => readInMemoryScope(scope, () => api.getSnapshot(appliedFilters)), + enabled: scope.connectionId != null, staleTime: 10_000 }) + const snapshot = { ...snapshotQuery, data: matchesMemoryScope(snapshotQuery.data, scope) ? snapshotQuery.data.value : null } const updateFilter = (key, value) => setFilters(current => ({ ...current, [key]: value })) const providers = visibleProviderKeys(snapshot.data) const refresh = () => { @@ -1828,7 +1930,7 @@ function MemoryPage({ ctx }) { }), snapshot.isLoading ? jsx(PageSkeleton, {}) : null, jsx(ErrorNotice, { error: snapshot.error, title: t('failed'), t }), - snapshot.data ? jsx(BuiltinStores, { builtin: snapshot.data.builtin, t }) : null, + snapshot.data ? jsx(BuiltinMemorySection, { api, builtin: snapshot.data.builtin, refreshSnapshot: snapshot.refetch, t }) : null, snapshot.data ? jsx(Separator, {}) : null, snapshot.data ? jsxs('section', { className: 'space-y-4', diff --git a/tests/builtin_profile_auth_http_regression.py b/tests/builtin_profile_auth_http_regression.py new file mode 100644 index 0000000..b6e2dbf --- /dev/null +++ b/tests/builtin_profile_auth_http_regression.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Exercise built-in profile authorization through Hermes' real HTTP auth layer. + +Uses temporary profiles, the native ticket issuer/redemption and request guards, +plus the host's real plugin discovery and consent policy. ASGI supplies a local +socket peer; no gateway process, external providers, or user data are involved. +""" +from __future__ import annotations + +import asyncio +import importlib.util +import json +import os +import sys +import tempfile +from pathlib import Path +from types import SimpleNamespace + +import httpx +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse + +from profile_scope_http_regression import _hermes_agent_source + + +ROOT = Path(__file__).resolve().parents[1] +PLUGIN = "hermes-memory-ui" +BASE = f"/api/plugins/{PLUGIN}/builtin" + + +def _profile(home: Path, marker: str, consent: str) -> None: + (home / "memories").mkdir(parents=True) + (home / "memories" / "MEMORY.md").write_text(marker, encoding="utf-8") + (home / "memories" / "USER.md").write_text(f"user-{marker}", encoding="utf-8") + (home / "profile.yaml").write_text(f"bot_title: {marker}\n", encoding="utf-8") + (home / "config.yaml").write_text( + f"plugins:\n {consent}: [{PLUGIN}]\n" if consent else "plugins: {}\n", + encoding="utf-8", + ) + + +async def _main() -> None: + source = _hermes_agent_source() + with tempfile.TemporaryDirectory(prefix="memory-ui-auth-") as temporary: + # Set home before importing Hermes so its cached launch home, discovery + # roots and native authorities all belong to this disposable fixture. + os.environ["HOME"] = temporary + os.environ["USERPROFILE"] = temporary + home = Path(temporary) / ".hermes" + os.environ["HERMES_HOME"] = str(home) + os.environ["HERMES_DASHBOARD_SESSION_TOKEN"] = "fixture-dashboard-owner" + other = home / "profiles" / "other" + denied = home / "profiles" / "denied" + unconsented = home / "profiles" / "unconsented" + _profile(home, "A-PRIVATE", "enabled") + _profile(other, "B-PRIVATE", "enabled") + _profile(denied, "DENIED-PRIVATE", "disabled") + _profile(unconsented, "UNCONSENTED-PRIVATE", "") + # Real host discovery finds the user plugin under the default root for + # all four profiles; each target's config decides its consent. + dashboard = home / "plugins" / PLUGIN / "dashboard" + dashboard.mkdir(parents=True) + (dashboard / "manifest.json").write_text( + json.dumps({"name": PLUGIN, "api": "plugin_api.py", "entry": "index.js"}), + encoding="utf-8", + ) + (dashboard / "plugin_api.py").write_text( + "from fastapi import APIRouter\nrouter = APIRouter()\n", encoding="utf-8" + ) + sys.path.insert(0, str(source)) + from gateway.runtime_bootstrap import TicketStore + from gateway.session_authorities import SessionAuthorities + from hermes_cli import web_server as web + from hermes_cli.dashboard_auth.native_http import ( + authenticate_native_http, + native_profile_scope, + ) + from hermes_cli.plugin_host_http_auth import with_hosted_admission + from hermes_cli.web_server_dashboard import _plugin_api_request_refused + from hermes_cli.web_server_profiles import _config_profile_scope + + module_name = "builtin_profile_auth_plugin_api" + spec = importlib.util.spec_from_file_location(module_name, ROOT / "dashboard" / "plugin_api.py") + assert spec is not None and spec.loader is not None + plugin = importlib.util.module_from_spec(spec) + sys.modules[module_name] = plugin + spec.loader.exec_module(plugin) + instance_id = "memory-ui-auth-fixture" + homes = [home, other, denied, unconsented] + registry = SessionAuthorities(home, multiplexed=True) + for path in homes: + registry.add(path, SimpleNamespace(profile_id=str(path), instance_id=instance_id)) + tickets = TicketStore(instance_id, frozenset(str(path) for path in homes)) + runner = SimpleNamespace( + session_authorities=registry, + session_ticket_store=tickets, + session_runtime_descriptor={ + "state": "ready", + "instance_id": instance_id, + "served_profiles": [{"profile_id": str(path), "home": str(path)} for path in homes], + }, + _draining=False, + ) + app = FastAPI() + app.state.gateway_runner = runner + + @app.middleware("http") + async def host_auth(request: Request, call_next): + # The native seam checks the original socket peer, not proxy data. + request.scope["hermes.gateway_socket_peer"] = ("127.0.0.1", 12345) + rejected = await authenticate_native_http(request) + if rejected is not None: + return rejected + try: + web._require_token(request) + with native_profile_scope(request): + with _config_profile_scope(request.query_params.get("profile")): + if await _plugin_api_request_refused(PLUGIN): + return JSONResponse({"detail": "Plugin not found"}, status_code=404) + return await call_next(request) + except HTTPException as exc: + return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) + + app.include_router(plugin.router, prefix=f"/api/plugins/{PLUGIN}") + + def native_headers(path: Path = home) -> dict[str, str]: + ticket = tickets.mint(profile_id=str(path), subject="uid:fixture", purpose="native-http") + return {"X-Hermes-Gateway-Ticket": ticket} + + def entries(response): + assert response.status_code == 200, response.text + return response.json()["stores"][0]["entries"] + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: + assert (await client.get(BASE)).status_code == 401 + assert (await client.get(BASE, headers={"X-Hermes-Gateway-Ticket": "invalid"})).status_code == 401 + one_use = native_headers() + assert entries(await client.get(BASE, headers=one_use)) == ["A-PRIVATE"] + assert (await client.get(BASE, headers=one_use)).status_code == 401 + assert entries(await client.get(BASE, headers=native_headers(other))) == ["B-PRIVATE"] + + # Both selectors must honor the same principal. Before the fix, + # memory_profile bypassed the host's check and returned B's bytes. + for query in ( + "profile=other", + "profile=default&memory_profile=other", + "memory_profile=other", + "profile=current&memory_profile=other", + ): + response = await client.get(f"{BASE}?{query}", headers=native_headers()) + assert response.status_code == 403, (query, response.status_code, response.text) + assert "B-PRIVATE" not in response.text + response = await client.get(f"{BASE}?memory_profile=default", headers=native_headers(other)) + assert response.status_code == 403, response.text + response = await client.get(f"{BASE}/profiles", headers=native_headers()) + assert response.status_code == 200, response.text + choices = response.json()["profiles"] + assert "other" not in {choice["name"] for choice in choices}, choices + assert str(other) not in response.text and "B-PRIVATE" not in response.text + + # A verified host-wide dashboard owner may inspect another bot, + # provided that bot independently consented to the plugin. + owner = {"X-Hermes-Session-Token": "fixture-dashboard-owner"} + assert entries(await client.get(f"{BASE}?memory_profile=other", headers=owner)) == ["B-PRIVATE"] + for name in ("denied", "unconsented"): + response = await client.get(f"{BASE}?memory_profile={name}", headers=owner) + assert response.status_code == 404, (name, response.status_code, response.text) + assert "PRIVATE" not in response.text + response = await client.get(f"{BASE}/profiles", headers=owner) + assert response.status_code == 200, response.text + names = {choice["name"] for choice in response.json()["profiles"]} + assert "other" in names and not names.intersection({"denied", "unconsented"}), names + for selection, status in (("missing", 404), ("..%2Fescape", 400)): + response = await client.get(f"{BASE}?memory_profile={selection}", headers=owner) + assert response.status_code == status, (selection, response.text) + + # A hosted plugin sees only admitted/not-admitted, without the native + # grant's profile reach. That boolean must never authorize a sibling. + hosted = with_hosted_admission(app, True) + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=hosted), base_url="http://test") as client: + assert entries(await client.get(BASE)) == ["A-PRIVATE"] + response = await client.get(f"{BASE}/profiles") + assert response.status_code == 200, response.text + assert response.json()["switching_supported"] is False + assert [choice["name"] for choice in response.json()["profiles"]] == ["current"] + response = await client.get(f"{BASE}?memory_profile=other") + assert response.status_code == 501, response.text + print("builtin-profile auth HTTP regression: ok") + + +if __name__ == "__main__": + asyncio.run(_main()) diff --git a/tests/dashboard_builtin_profiles_smoke.mjs b/tests/dashboard_builtin_profiles_smoke.mjs new file mode 100644 index 0000000..9e42d98 --- /dev/null +++ b/tests/dashboard_builtin_profiles_smoke.mjs @@ -0,0 +1,166 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs/promises' +import vm from 'node:vm' + +const source = await fs.readFile(process.argv[2], 'utf8') +const requests = [] +let registered +let states = [] +let effects = [] +let index = 0 +let queued = [] +const snapshot = { builtin: { stores: [], total_entries: 0, hermes_home: '/active' } } +const hooks = { + useState(initial) { + const slot = index++ + if (!(slot in states)) states[slot] = initial + return [states[slot], value => { + states[slot] = typeof value === 'function' ? value(states[slot]) : value + }] + }, + useMemo: fn => fn(), + useEffect(fn, deps) { + const slot = index++ + const previous = effects[slot] + if (!previous || deps.some((value, i) => value !== previous.deps[i])) { + queued.push(() => { + previous?.cleanup?.() + effects[slot] = { deps, cleanup: fn() } + }) + } + } +} +const window = { + location: { search: '?profile=host-bot' }, + __HERMES_PLUGIN_SDK__: { + React: { Fragment: 'fragment', createElement: (type, props, ...children) => ({ type, props: { ...props, children } }) }, + hooks, + components: new Proxy({}, { get: (_target, key) => key }), + fetchJSON(url) { + return new Promise((resolve, reject) => requests.push({ url, resolve, reject })) + } + }, + __HERMES_PLUGINS__: { register: (_name, page) => { registered = page } } +} +vm.runInNewContext(source, { window, URLSearchParams, setTimeout, Date, Math, Number, String, Promise }) +function walk(node, predicate) { + if (!node || typeof node !== 'object') return null + if (Array.isArray(node)) return node.map(child => walk(child, predicate)).find(Boolean) + if (predicate(node)) return node + return walk(node.props?.children, predicate) +} +// Capture the actual nested component without exposing test-only exports. +states[0] = snapshot +const page = registered() +const browserNode = walk(page, node => node.type?.name === 'BuiltinProfileBrowser') +assert.ok(browserNode) +const Browser = browserNode.type +states = [] +effects = [] +queued = [] +function render() { + index = 0 + const tree = Browser(browserNode.props) + queued.splice(0).forEach(effect => effect()) + return tree +} +async function flush() { await new Promise(resolve => setTimeout(resolve, 0)); await Promise.resolve() } +function change(tree, name) { + walk(tree, node => node.type === 'select').props.onChange({ target: { value: name } }) + return render() +} +function shownBuiltin(tree) { + return walk(tree, node => node.type?.name === 'BuiltinSection')?.props.builtin +} +function latestMemoryRequest() { + return requests.filter(request => new URL(request.url, 'http://test').pathname.endsWith('/builtin')).at(-1) +} +let tree = render() +assert.equal(shownBuiltin(tree).hermes_home, '/active') +await flush() +requests[0].resolve({ profiles: [ + { name: 'current', label: 'Active profile' }, + { name: 'default', label: 'default' }, + { name: 'alpha', label: 'Alpha bot' }, + { name: 'beta', label: 'Beta bot' } +] }) +await flush() +tree = render() +const select = walk(tree, node => node.type === 'select') +assert.equal(select.props.children[0].length, 4) +tree = change(tree, 'alpha') +assert.equal(shownBuiltin(tree), undefined, 'active files must disappear during selection') +await flush() +const alpha = latestMemoryRequest() +assert.equal(new URL(alpha.url, 'http://test').searchParams.get('memory_profile'), 'alpha') +assert.equal(new URL(alpha.url, 'http://test').searchParams.get('profile'), 'host-bot') +tree = change(tree, 'beta') +await flush() +alpha.resolve({ hermes_home: '/alpha', stores: [] }) +await flush() +tree = render() +assert.equal(shownBuiltin(tree), undefined, 'late alpha response must not paint beta') +latestMemoryRequest().resolve({ hermes_home: '/beta', stores: [] }) +await flush() +tree = render() +assert.equal(shownBuiltin(tree).hermes_home, '/beta') +const beforeSnapshotRefresh = requests.length +browserNode.props.builtin = { ...snapshot.builtin, generated_at: 2 } +tree = render() +await flush() +assert.equal(requests.length, beforeSnapshotRefresh, 'unrelated snapshot refresh must not reload another bot') +assert.equal(shownBuiltin(tree).hermes_home, '/beta') +walk(tree, node => node.type === 'Button').props.onClick() +tree = render() +await flush() +requests.filter(request => request.url.includes('/builtin/profiles')).at(-1).resolve({ + profiles: [{ name: 'current', label: 'Active profile' }] +}) +latestMemoryRequest().reject(new Error('Profile beta disappeared')) +await flush() +tree = render() +const missingSelector = walk(tree, node => node.type === 'select') +assert.equal(missingSelector.props.value, 'beta') +assert.ok(walk(missingSelector, node => node.type === 'option' && node.props.value === 'beta' + && node.props.children[0] === 'beta (unavailable)')) +assert.ok(walk(missingSelector, node => node.type === 'option' && node.props.value === 'current')) +assert.equal(shownBuiltin(tree), undefined, 'deleted profile must not retain old files') +tree = change(tree, 'default') +await flush() +latestMemoryRequest().reject(new Error('Profile disappeared')) +await flush() +tree = render() +assert.equal(shownBuiltin(tree), undefined, 'failure must not retain beta files') +assert.ok(walk(tree, node => node.props?.error === 'Profile disappeared')) +tree = change(tree, 'current') +assert.equal(shownBuiltin(tree).hermes_home, '/active') +walk(tree, node => node.type === 'Button').props.onClick() +tree = render() +await flush() +latestMemoryRequest().resolve({ hermes_home: '/active-refreshed', stores: [] }) +await flush() +tree = render() +assert.equal(shownBuiltin(tree).hermes_home, '/active-refreshed') +walk(tree, node => node.type === 'Button').props.onClick() +tree = render() +await flush() +latestMemoryRequest().reject(new Error('Refresh temporarily failed')) +await flush() +tree = render() +assert.equal(shownBuiltin(tree), undefined) +browserNode.props.builtin = { ...snapshot.builtin, hermes_home: '/active-newer' } +tree = render() +assert.equal(shownBuiltin(tree).hermes_home, '/active-newer', 'fresh snapshot must supersede a failed current refresh') +assert.ok(!walk(tree, node => node.props?.error === 'Refresh temporarily failed')) +tree = change(tree, 'alpha') +await flush() +const changedHostRequest = latestMemoryRequest() +window.location.search = '?profile=another-host-bot' +changedHostRequest.resolve({ hermes_home: '/alpha', stores: [] }) +await flush() +tree = render() +assert.equal(shownBuiltin(tree), undefined) +assert.ok(walk(tree, node => node.props?.error?.includes('host profile changed')), + 'stale host reply must expose a refresh action rather than loading forever') +assert.equal(requests.every(request => new URL(request.url, 'http://test').searchParams.get('profile') === 'host-bot'), true) +console.log('Dashboard builtin profile selection: ok') diff --git a/tests/dashboard_profile_scope_smoke.mjs b/tests/dashboard_profile_scope_smoke.mjs index 7d04e90..4d7af16 100644 --- a/tests/dashboard_profile_scope_smoke.mjs +++ b/tests/dashboard_profile_scope_smoke.mjs @@ -221,6 +221,7 @@ const exercisedPaths = new Set( assert.deepEqual( [...exercisedPaths].sort(), [ + '/api/plugins/hermes-memory-ui/builtin/profiles', '/api/plugins/hermes-memory-ui/byterover/query', '/api/plugins/hermes-memory-ui/hindsight/contents', '/api/plugins/hermes-memory-ui/hindsight/recall', diff --git a/tests/desktop_plugin_smoke.mjs b/tests/desktop_plugin_smoke.mjs index 83f4fe5..88e03d5 100644 --- a/tests/desktop_plugin_smoke.mjs +++ b/tests/desktop_plugin_smoke.mjs @@ -1,3 +1,4 @@ +import assert from 'node:assert/strict' import fs from 'node:fs/promises' import process from 'node:process' import vm from 'node:vm' @@ -7,6 +8,10 @@ if (!pluginPath) throw new Error('desktop plugin path is required') const source = await fs.readFile(pluginPath, 'utf8') const navigations = [] +let queryHook = () => ({ data: null, isLoading: false, error: null, refetch: () => {} }) +let stateHook = initial => [initial, () => {}] +let activeConnection = 'gateway-a' +let activeHostProfile = 'default' const sdkValues = { Badge: function Badge() {}, Button: function Button() {}, @@ -30,6 +35,10 @@ const sdkValues = { cn: (...values) => values.filter(Boolean).join(' '), fmtDateTime: value => String(value ?? ''), host: { + state: { + connectionId: { get: () => activeConnection }, + profile: { get: () => activeHostProfile } + }, navigate: path => navigations.push(path), notify: () => {}, notifyError: () => {} @@ -37,7 +46,8 @@ const sdkValues = { icons: {}, useMutation: () => ({ mutate: () => {}, isPending: false, error: null }), usePluginI18n: () => (key => key), - useQuery: () => ({ data: null, isLoading: false, error: null, refetch: () => {} }), + useQuery: options => queryHook(options), + useValue: atom => atom.get(), useQueryClient: () => ({ invalidateQueries: () => {} }) } @@ -45,7 +55,7 @@ const reactValues = { Fragment: Symbol.for('react.fragment'), useEffect: () => {}, useMemo: fn => fn(), - useState: initial => [initial, () => {}] + useState: initial => stateHook(initial) } const runtimeValues = { @@ -210,7 +220,276 @@ const operationOptions = { }) } +// Exercise the real section and handlers while controlling query completion. +const builtinPaths = [] +const builtinApi = createMemoryApi({ + rest: async path => { + builtinPaths.push(path) + return { stores: [{ id: path, entries: [path] }] } + } +}) +await builtinApi.getBuiltinProfiles() +await builtinApi.getBuiltin('default') +await builtinApi.getBuiltin('work bot') +await builtinApi.getBuiltin() +assert.deepEqual(builtinPaths, [ + '/builtin/profiles', + '/builtin?memory_profile=default', + '/builtin?memory_profile=work+bot', + '/builtin?memory_profile=current' +]) + +const BuiltinMemorySection = module.namespace.BuiltinMemorySection +assert.equal(typeof BuiltinMemorySection, 'function') +let selectedProfile = 'current' +let memoryData = null +let memoryError = null +let memoryQuery +let refreshedSnapshot = 0 +let refreshedProfiles = 0 +let refreshedMemory = 0 +let availableProfiles = [ + { name: 'current', label: 'Active profile' }, + { name: 'default', label: 'default' }, + { name: 'alpha', label: 'Research bot (alpha)' }, + { name: 'beta', label: 'beta' } +] +const scoped = value => ({ connectionId: activeConnection, hostProfile: activeHostProfile, value }) +stateHook = () => [selectedProfile, value => { selectedProfile = value }] +queryHook = options => { + if (options.queryKey[1] === 'builtin-profiles') { + return { data: scoped({ profiles: availableProfiles }), refetch: () => { refreshedProfiles++ } } + } + memoryQuery = options + return { + data: memoryData, + error: memoryError, + isLoading: !memoryData && !memoryError, + refetch: () => { refreshedMemory++ } + } +} +const sdkComponents = new Set(Object.values(sdkValues)) +function expand(node) { + if (node === null || node === undefined || typeof node !== 'object') return node + if (Array.isArray(node)) return node.map(expand) + if (typeof node.type === 'function' && !sdkComponents.has(node.type)) return expand(node.type(node.props)) + return { ...node, props: { ...node.props, children: expand(node.props?.children) } } +} +function find(node, predicate) { + if (!node || typeof node !== 'object') return null + if (Array.isArray(node)) return node.map(item => find(item, predicate)).find(Boolean) + return predicate(node) ? node : find(node.props?.children, predicate) +} +function textContent(node) { + if (node === null || node === undefined || node === false) return '' + if (Array.isArray(node)) return node.map(textContent).join(' ') + if (typeof node !== 'object') return String(node) + return textContent(node.props?.children) +} +const currentBuiltin = { stores: [{ filename: 'MEMORY.md', entries: ['active memory'], path: '/active/memories/MEMORY.md' }] } +const renderBuiltin = () => expand(BuiltinMemorySection({ + api: builtinApi, + builtin: currentBuiltin, + refreshSnapshot: () => { refreshedSnapshot++ }, + t: key => key +})) +let builtinTree = renderBuiltin() +assert.equal(memoryQuery.enabled, false) +assert.match(textContent(builtinTree), /active memory/) +let selector = find(builtinTree, node => node.type === sdkValues.Select) +assert.ok(selector) +assert.match(textContent(selector), /Research bot \(alpha\)/) +find(builtinTree, node => node.type === sdkValues.Button).props.onClick() +assert.equal(refreshedSnapshot, 1) +assert.equal(refreshedProfiles, 1) + +selector.props.onValueChange('alpha') +builtinTree = renderBuiltin() +assert.equal(memoryQuery.queryKey[2], 'alpha') +assert.equal(memoryQuery.enabled, true) +assert.doesNotMatch(textContent(builtinTree), /active memory/) +const alphaResponse = await memoryQuery.queryFn() +find(builtinTree, node => node.type === sdkValues.Select).props.onValueChange('beta') +memoryData = alphaResponse +builtinTree = renderBuiltin() +assert.equal(memoryQuery.queryKey[2], 'beta') +assert.doesNotMatch(textContent(builtinTree), /memory_profile=alpha/) +memoryData = await memoryQuery.queryFn() +builtinTree = renderBuiltin() +assert.match(textContent(builtinTree), /memory_profile=beta/) +assert.doesNotMatch(textContent(builtinTree), /active memory/) +find(builtinTree, node => node.type === sdkValues.Button).props.onClick() +assert.equal(refreshedMemory, 1) +assert.equal(refreshedSnapshot, 1) + +memoryError = new Error('profile deleted') +availableProfiles = [{ name: 'current', label: 'Active profile' }] +builtinTree = renderBuiltin() +assert.doesNotMatch(textContent(builtinTree), /memory_profile=beta/) +assert.ok(find(builtinTree, node => node.type === sdkValues.ErrorState)) +selector = find(builtinTree, node => node.type === sdkValues.Select) +assert.equal(selector.props.value, 'beta') +assert.match(textContent(selector), /beta \(unavailable\)/) +assert.ok(find(selector, node => node.type === sdkValues.SelectItem && node.props.value === 'current')) +assert.ok(find(selector, node => node.type === sdkValues.SelectItem && node.props.value === 'beta')) +find(builtinTree, node => node.type === sdkValues.Select).props.onValueChange('current') +builtinTree = renderBuiltin() +assert.match(textContent(builtinTree), /active memory/) +assert.equal(memoryQuery.enabled, false) + +availableProfiles = [{ name: 'current', label: 'Active profile' }] +builtinTree = renderBuiltin() +selector = find(builtinTree, node => node.type === sdkValues.Select) +const profileItems = [] +function collectItems(node) { + if (!node || typeof node !== 'object') return + if (Array.isArray(node)) return node.forEach(collectItems) + if (node.type === sdkValues.SelectItem) profileItems.push(node.props.value) + collectItems(node.props?.children) +} +collectItems(selector) +assert.deepEqual(profileItems, ['current']) +const builtinProfileChecks = { + paths: builtinPaths, + currentSnapshotReused: true, + selectionScopesQueries: true, + staleMemoryHidden: true, + failedMemoryHidden: true, + removedSelectionRetained: true, + legacyCurrentOnly: true +} + +// Retain the previous result across key changes, as a host query client can do, +// and control network completion independently of the currently selected route. +const scopeQueries = new Map() +const scopeResults = new Map() +let pendingReads = [] +let scopedRestCalls = 0 +const scopedRest = path => { + scopedRestCalls++ + return new Promise(resolve => pendingReads.push({ path, resolve })) +} +const scopedApi = createMemoryApi({ rest: scopedRest }) +ctx.rest = scopedRest +queryHook = options => { + const kind = options.queryKey[1] + scopeQueries.set(kind, options) + return { data: scopeResults.get(kind), isLoading: !scopeResults.has(kind), refetch: () => {} } +} +stateHook = initial => typeof initial === 'string' + ? [selectedProfile, value => { selectedProfile = value }] + : [initial, () => {}] +const storesFor = entry => ({ stores: [{ filename: 'MEMORY.md', entries: [entry] }] }) +const scopedSection = () => expand(BuiltinMemorySection({ + api: scopedApi, builtin: null, refreshSnapshot: () => {}, t: key => key +})) +const scopedPage = () => expand(route.render()) +async function completeRead(kind, value) { + const promise = scopeQueries.get(kind).queryFn() + pendingReads.shift().resolve(value) + scopeResults.set(kind, await promise) +} +for (const changeRoute of [ + () => { activeConnection = 'gateway-b' }, + () => { activeHostProfile = 'research' } +]) { + activeConnection = 'gateway-a' + activeHostProfile = 'default' + selectedProfile = 'default' + scopeResults.clear() + scopedSection() + await completeRead('builtin-profiles', { profiles: [{ name: 'default' }, { name: 'only-on-A' }] }) + await completeRead('builtin', storesFor('A-private-selected')) + assert.match(textContent(scopedSection()), /A-private-selected/) + assert.match(textContent(scopedSection()), /only-on-A/) + scopedPage() + await completeRead('snapshot', { builtin: storesFor('A-private-current') }) + selectedProfile = 'current' + assert.match(textContent(scopedPage()), /A-private-current/) + selectedProfile = 'default' + scopedSection() + const oldQueries = new Map(scopeQueries) + const lateReads = [...oldQueries].map(([kind, options]) => ({ kind, promise: options.queryFn() })) + const lateResolvers = pendingReads + pendingReads = [] + changeRoute() + // The same selected profile name must not accept data from the previous route. + assert.doesNotMatch(textContent(scopedSection()), /A-private-selected|only-on-A/) + selectedProfile = 'current' + assert.doesNotMatch(textContent(scopedPage()), /A-private-current|A-private-selected/) + selectedProfile = 'default' + scopedSection() + for (const [kind, oldQuery] of oldQueries) { + assert.notDeepEqual(scopeQueries.get(kind).queryKey, oldQuery.queryKey) + const callsBeforeRetry = scopedRestCalls + await assert.rejects(oldQuery.queryFn(), /connection or active profile changed/) + assert.equal(scopedRestCalls, callsBeforeRetry, 'an old retry must not request the new route') + } + lateResolvers.forEach(read => read.resolve(storesFor('A-late-private'))) + for (const read of lateReads) await assert.rejects(read.promise, /connection or active profile changed/) + assert.doesNotMatch(textContent(scopedSection()), /A-private|A-late-private|only-on-A/) + // Even while B's request is pending, the retained A cache is hidden. + const pendingMemory = scopeQueries.get('builtin').queryFn() + assert.doesNotMatch(textContent(scopedSection()), /A-private|A-late-private/) + pendingReads.shift().resolve(storesFor('B-selected')) + scopeResults.set('builtin', await pendingMemory) + await completeRead('builtin-profiles', { profiles: [{ name: 'default' }, { name: 'only-on-B' }] }) + assert.match(textContent(scopedSection()), /B-selected/) + assert.match(textContent(scopedSection()), /only-on-B/) + scopedPage() + await completeRead('snapshot', { builtin: storesFor('B-current') }) + selectedProfile = 'current' + const newPage = textContent(scopedPage()) + assert.match(newPage, /B-current/) + assert.doesNotMatch(newPage, /A-private|A-late-private|only-on-A/) +} + +// A null host connection is unresolved, not a cache identity shared by every +// unresolved remote. Neither cached payloads nor manually retried queries may +// cross that window, even when both request and current scope carry null. +activeConnection = null +activeHostProfile = 'default' +selectedProfile = 'default' +scopeResults.clear() +scopedSection() +scopedPage() +const unresolvedQueries = new Map(scopeQueries) +for (const query of unresolvedQueries.values()) { + assert.equal(query.enabled, false) + const callsBeforeRetry = scopedRestCalls + await assert.rejects(query.queryFn(), /connection or active profile changed/) + assert.equal(scopedRestCalls, callsBeforeRetry) +} +scopeResults.set('builtin-profiles', scoped({ profiles: [{ name: 'unresolved-private-option' }] })) +scopeResults.set('builtin', { profile: 'default', ...scoped(storesFor('unresolved-private-selected')) }) +scopeResults.set('snapshot', scoped({ builtin: storesFor('unresolved-private-current') })) +assert.doesNotMatch(textContent(scopedSection()), /unresolved-private/) +selectedProfile = 'current' +assert.doesNotMatch(textContent(scopedPage()), /unresolved-private/) +activeConnection = 'gateway-c' +for (const query of unresolvedQueries.values()) { + const callsBeforeRetry = scopedRestCalls + await assert.rejects(query.queryFn(), /connection or active profile changed/) + assert.equal(scopedRestCalls, callsBeforeRetry) +} +assert.doesNotMatch(textContent(scopedPage()), /unresolved-private/) +// A resolved request that loses its connection before completion is discarded. +const pendingSnapshot = scopeQueries.get('snapshot').queryFn() +activeConnection = null +pendingReads.shift().resolve({ builtin: storesFor('late-unresolved-private') }) +await assert.rejects(pendingSnapshot, /connection or active profile changed/) +assert.doesNotMatch(textContent(scopedPage()), /unresolved-private/) +const connectionScopeChecks = { + sameNameAcrossConnections: true, + activeHostProfileChanges: true, + currentSnapshotIsolated: true, + obsoleteRequestsRejected: true, + unresolvedConnectionsBlocked: true +} + process.stdout.write(JSON.stringify({ + builtinProfileChecks, + connectionScopeChecks, defaultFilters, i18nLocales: Object.keys(localeBundles ?? {}).sort(), normalizedFilters, diff --git a/tests/profile_scope_http_regression.py b/tests/profile_scope_http_regression.py index 1d9c396..a0468dd 100644 --- a/tests/profile_scope_http_regression.py +++ b/tests/profile_scope_http_regression.py @@ -45,9 +45,12 @@ def _hermes_agent_source() -> Path: ) -def _write_profile(home: Path, marker: str) -> None: +def _write_profile(home: Path, marker: str, memory_limit: int = 2200, user_limit: int = 1375) -> None: (home / "memories").mkdir(parents=True) - (home / "config.yaml").write_text("memory:\n provider: mem0\n", encoding="utf-8") + (home / "config.yaml").write_text( + f"memory:\n provider: mem0\n memory_char_limit: {memory_limit}\n user_char_limit: {user_limit}\n", + encoding="utf-8", + ) (home / "memories" / "MEMORY.md").write_text(marker, encoding="utf-8") (home / "memories" / "USER.md").write_text(f"user-{marker}", encoding="utf-8") (home / ".env").write_text( @@ -76,7 +79,11 @@ async def _main() -> None: default_home = Path(raw_root) / ".hermes" other_home = default_home / "profiles" / "other" _write_profile(default_home, "profile-A") - _write_profile(other_home, "profile-B") + _write_profile(other_home, "profile-B", memory_limit=9000, user_limit=3000) + (other_home / "profile.yaml").write_text("display_name: Other bot\n", encoding="utf-8") + # A legacy live profile can remain discoverable although modern host + # request validation rejects its reserved name. + _write_profile(default_home / "profiles" / "test", "reserved-profile") # This is the synthetic dashboard process home, never a real profile. os.environ["HERMES_HOME"] = str(default_home) @@ -85,6 +92,17 @@ async def _main() -> None: sys.path.insert(0, str(agent_source)) plugin_api = _load_plugin_api() + from hermes_cli.profiles import list_profile_names + from hermes_cli.web_server_profiles import _config_profile_scope + + # This harness isolates routing/credential scope; the dedicated builtin + # auth harness covers real host ticket authentication and plugin consent. + async def consent_refused(_name): + return False + + plugin_api._builtin_profile_access = lambda _request: (None, consent_refused, _config_profile_scope) + + assert "test" in list_profile_names(), "reserved legacy fixture must be discoverable by the host" cancel_entered = asyncio.Event() cancel_finished = asyncio.Event() @@ -124,6 +142,40 @@ async def get(path: str) -> httpx.Response: "/api/plugins/hermes-memory-ui/builtin?profile=..%2Fescape" )).status_code == 400 + choices_response = await client.get( + "/api/plugins/hermes-memory-ui/builtin/profiles?profile=other" + ) + choices_response.raise_for_status() + choices = choices_response.json() + assert choices["switching_supported"] is True + assert {item["name"] for item in choices["profiles"]} == {"current", "default", "other"} + assert choices["profiles"][0]["hermes_home"] == str(other_home) + assert next(item for item in choices["profiles"] if item["name"] == "other")["label"] == "Other bot (other)" + + # The local memory selector is independent of the host's active bot. + for host_profile, memory_profile, home, marker, limits in ( + ("default", "other", other_home, "profile-B", [9000, 3000]), + ("other", "default", default_home, "profile-A", [2200, 1375]), + ("other", "current", other_home, "profile-B", [9000, 3000]), + ): + response = await client.get( + f"/api/plugins/hermes-memory-ui/builtin?profile={host_profile}&memory_profile={memory_profile}" + ) + response.raise_for_status() + data = response.json() + assert data["hermes_home"] == str(home) + assert [store["entries"] for store in data["stores"]] == [[marker], [f"user-{marker}"]] + assert [store["char_limit"] for store in data["stores"]] == limits + + for selection, status in (("missing", 404), ("..%2Fescape", 400), ("test", 400)): + assert (await client.get( + f"/api/plugins/hermes-memory-ui/builtin?profile=other&memory_profile={selection}" + )).status_code == status + + response = await client.get("/api/plugins/hermes-memory-ui/builtin?profile=default") + response.raise_for_status() + assert response.json()["stores"][0]["entries"] == ["profile-A"] + assert observed == [ ["profile-A"], ["profile-B"], diff --git a/tests/test_builtin_profile_auth.py b/tests/test_builtin_profile_auth.py new file mode 100644 index 0000000..be85a7d --- /dev/null +++ b/tests/test_builtin_profile_auth.py @@ -0,0 +1,29 @@ +"""Host-authenticated regression for the built-in memory profile selector.""" +import os +import subprocess + +import pytest + +from test_profile_scope_regressions import ROOT, discover_host_runtime + + +def test_builtin_profiles_through_real_host_auth(): + host_python, source, reasons = discover_host_runtime() + if host_python is None or source is None: + pytest.skip( + "Hermes host integration prerequisites unavailable; set HERMES_HOST_PYTHON and " + f"HERMES_AGENT_SOURCE ({'; '.join(reasons) or 'no candidates'})" + ) + environment = os.environ.copy() + environment["HERMES_AGENT_SOURCE"] = str(source) + result = subprocess.run( + [str(host_python), str(ROOT / "tests" / "builtin_profile_auth_http_regression.py")], + cwd=ROOT, + env=environment, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + assert "builtin-profile auth HTTP regression: ok" in result.stdout diff --git a/tests/test_dashboard_builtin_profiles.py b/tests/test_dashboard_builtin_profiles.py new file mode 100644 index 0000000..41b1ed1 --- /dev/null +++ b/tests/test_dashboard_builtin_profiles.py @@ -0,0 +1,14 @@ +import subprocess +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def test_dashboard_builtin_profile_selection(): + result = subprocess.run( + ["node", str(ROOT / "tests/dashboard_builtin_profiles_smoke.mjs"), + str(ROOT / "dashboard/dist/index.js")], + cwd=ROOT, capture_output=True, text=True, timeout=30, + ) + assert result.returncode == 0, result.stdout + result.stderr diff --git a/tests/test_desktop_plugin.py b/tests/test_desktop_plugin.py index 184dafe..b48bd57 100644 --- a/tests/test_desktop_plugin.py +++ b/tests/test_desktop_plugin.py @@ -102,6 +102,29 @@ def test_desktop_plugin_registers_native_surfaces_and_scoped_api_calls(): "mnemosynePrefetch": {"query": "release plan"}, } assert result["visibleProviders"] == ["holographic", "honcho", "hindsight"] + assert result["builtinProfileChecks"] == { + "paths": [ + "/builtin/profiles", + "/builtin?memory_profile=default", + "/builtin?memory_profile=work+bot", + "/builtin?memory_profile=current", + "/builtin?memory_profile=alpha", + "/builtin?memory_profile=beta", + ], + "currentSnapshotReused": True, + "selectionScopesQueries": True, + "staleMemoryHidden": True, + "failedMemoryHidden": True, + "removedSelectionRetained": True, + "legacyCurrentOnly": True, + } + assert result["connectionScopeChecks"] == { + "sameNameAcrossConnections": True, + "activeHostProfileChanges": True, + "currentSnapshotIsolated": True, + "obsoleteRequestsRejected": True, + "unresolvedConnectionsBlocked": True, + } paths = result["restPaths"] assert len(paths) == 10 diff --git a/tests/test_profile_scope_regressions.py b/tests/test_profile_scope_regressions.py index 4684e9b..bdfa691 100644 --- a/tests/test_profile_scope_regressions.py +++ b/tests/test_profile_scope_regressions.py @@ -42,6 +42,16 @@ def install_module(monkeypatch, name, module): monkeypatch.setitem(sys.modules, name, module) +def authorize_builtin_fixture(monkeypatch, module, scope): + # These unit tests exercise discovery and context cleanup. Host authentication + # and consent are exercised separately through the HTTP integration harness. + async def consent_refused(_name): + return False + + monkeypatch.setattr(module, "_builtin_profile_access", lambda _request: (None, consent_refused, scope)) + return types.SimpleNamespace(state=types.SimpleNamespace(native_http_principal=None)) + + async def enter_and_close(scope): await scope.__anext__() await scope.aclose() @@ -75,6 +85,111 @@ async def enter(): assert "cannot safely scope" in caught.value.detail +def test_builtin_profiles_on_old_host_only_offer_current(monkeypatch, tmp_path): + module = load_plugin_api(monkeypatch, tmp_path) + install_module(monkeypatch, "hermes_cli.web_server_profiles", types.ModuleType("hermes_cli.web_server_profiles")) + + assert asyncio.run(module.builtin_profiles()) == { + "profiles": [{"name": "current", "label": "Active profile", "hermes_home": str(tmp_path)}], + "switching_supported": False, + } + with pytest.raises(module.HTTPException) as caught: + asyncio.run(module.builtin("other")) + assert caught.value.status_code == 501 + assert asyncio.run(module.builtin("current"))["hermes_home"] == str(tmp_path) + + +def test_builtin_profiles_use_native_registry_and_keep_custom_current(monkeypatch, tmp_path): + module = load_plugin_api(monkeypatch, tmp_path / "custom-home") + host_profiles = types.ModuleType("hermes_cli.web_server_profiles") + host_profiles._config_profile_scope = contextlib.nullcontext + install_module(monkeypatch, "hermes_cli.web_server_profiles", host_profiles) + profiles = types.ModuleType("hermes_cli.profiles") + # The native registry, not a filesystem scan, decides whether a bot is live. + profiles.list_profile_names = lambda: ["default", "work", "empty", "removed", "test", "hermes", "tmp", "root", "sudo"] + + def validate_profile_name(name): + if name in {"test", "hermes", "tmp", "root", "sudo"}: + raise ValueError("Reserved profile name") + + profiles.validate_profile_name = validate_profile_name + profiles.profile_exists = lambda name: name != "removed" + profiles.get_profile_dir = lambda name: tmp_path / "registry" / name + profiles.read_profile_meta = lambda home: {"bot_title": "Work bot"} if home.name == "work" else {} + install_module(monkeypatch, "hermes_cli.profiles", profiles) + + request = authorize_builtin_fixture(monkeypatch, module, contextlib.nullcontext) + payload = asyncio.run(module.builtin_profiles(request)) + assert payload["switching_supported"] is True + assert payload["profiles"] == [ + {"name": "current", "label": "Active profile", "hermes_home": str(tmp_path / "custom-home")}, + {"name": "default", "label": "default", "hermes_home": str(tmp_path / "registry" / "default")}, + {"name": "work", "label": "Work bot (work)", "hermes_home": str(tmp_path / "registry" / "work")}, + {"name": "empty", "label": "empty", "hermes_home": str(tmp_path / "registry" / "empty")}, + ] + + +def test_builtin_memory_profile_restores_outer_host_scope(monkeypatch, tmp_path): + module = load_plugin_api(monkeypatch, tmp_path) + active = contextvars.ContextVar("builtin_home", default=tmp_path) + monkeypatch.setattr(module, "_hermes_home", active.get) + other_home = tmp_path / "other" + (other_home / "memories").mkdir(parents=True) + (other_home / "memories" / "MEMORY.md").write_text("Other bot memory", encoding="utf-8") + (other_home / "memories" / "USER.md").write_text("Other bot user", encoding="utf-8") + host_profiles = types.ModuleType("hermes_cli.web_server_profiles") + + @contextlib.contextmanager + def scope(profile): + token = active.set(other_home) + try: + yield + finally: + active.reset(token) + + host_profiles._config_profile_scope = scope + install_module(monkeypatch, "hermes_cli.web_server_profiles", host_profiles) + request = authorize_builtin_fixture(monkeypatch, module, scope) + + async def select_and_restore(): + payload = await module.builtin("other", request) + # Check inside the request task: asyncio.run restores its caller's + # context even when the implementation fails to reset the override. + assert active.get() == tmp_path + assert (await module.builtin())["hermes_home"] == str(tmp_path) + assert (await module.builtin("current"))["hermes_home"] == str(tmp_path) + return payload + + payload = asyncio.run(select_and_restore()) + assert payload["hermes_home"] == str(other_home) + assert [store["entries"] for store in payload["stores"]] == [["Other bot memory"], ["Other bot user"]] + + +def test_builtin_discovery_skips_broken_profile_but_explicit_read_fails(monkeypatch, tmp_path, caplog): + module = load_plugin_api(monkeypatch, tmp_path) + profiles = types.ModuleType("hermes_cli.profiles") + profiles.list_profile_names = lambda: ["broken", "healthy"] + profiles.validate_profile_name = lambda _name: None + profiles.profile_exists = lambda _name: True + profiles.get_profile_dir = lambda name: tmp_path / name + profiles.read_profile_meta = lambda _home: {} + install_module(monkeypatch, "hermes_cli.profiles", profiles) + + @contextlib.contextmanager + def scope(name): + if name == "broken": + raise RuntimeError("secret source failed: token=private-fixture") + yield + + request = authorize_builtin_fixture(monkeypatch, module, scope) + payload = asyncio.run(module.builtin_profiles(request)) + assert [entry["name"] for entry in payload["profiles"]] == ["current", "healthy"] + assert "Skipping memory profile broken" in caplog.text + assert "private-fixture" not in caplog.text + with pytest.raises(RuntimeError, match="secret source failed"): + asyncio.run(module.builtin("broken", request)) + + def test_profile_dependency_unwinds_context_on_cancellation(monkeypatch, tmp_path): module = load_plugin_api(monkeypatch, tmp_path) active_profile = contextvars.ContextVar("active_profile", default=None) @@ -259,6 +374,7 @@ def test_dashboard_forwards_profile_and_suppresses_stale_responses(): payload = json.loads(result.stdout) assert payload == { "exercisedRequestPaths": [ + "/api/plugins/hermes-memory-ui/builtin/profiles", "/api/plugins/hermes-memory-ui/byterover/query", "/api/plugins/hermes-memory-ui/hindsight/contents", "/api/plugins/hermes-memory-ui/hindsight/recall",