Skip to content

The agent that grows with you

refactor(web): unify profiles router error mapping, target enumeration and row tagging

Tekniumde626c5a36a5
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index 31b29267168..406cd63a7cf 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -1,32 +1,32 @@
-"""Profiles dashboard routes (extracted verbatim from web_server.py).
-
-Two routers because the original registration points are far apart and route
-order matters: ``sessions_router`` (/api/profiles/sessions*) was registered
-long before the generic ``/api/profiles/{name}`` routes on ``router`` — if the
-literal-path routes were appended after ``{name}`` in one router, Starlette
-would still match literals first here, but we preserve the original global
-registration order exactly rather than rely on that.
-
-Handler bodies are byte-identical; web_server-owned helpers are reached via the
-late-binding seam in :mod:`hermes_cli.web_deps` so tests that
-``monkeypatch.setattr(web_server, "_helper", ...)`` keep working.
+"""Profiles dashboard routes.
+
+Two routers because route order matters: ``sessions_router``
+(/api/profiles/sessions*, projects/tree, pull-requests) was registered long
+before the generic ``/api/profiles/{name}`` routes on ``router``; the original
+global registration order is preserved rather than relying on Starlette's
+literal-before-param matching.
+
+web_server-owned helpers are reached via the late-binding seam in
+:mod:`hermes_cli.web_deps` so tests that ``monkeypatch.setattr(web_server,
+"_helper", ...)`` keep working.
"""
+import contextlib
import copy
import functools
import inspect
import json
import logging
import re
-import subprocess # noqa: F401
-import sys # noqa: F401
+import subprocess
+import sys
import threading
-import time # noqa: F401
+import time
from collections import OrderedDict
-from pathlib import Path # noqa: F401
-from typing import Any, Dict, List, Optional, Tuple # noqa: F401
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple
-from fastapi import APIRouter, HTTPException, Query # noqa: F401
+from fastapi import APIRouter, HTTPException, Query
from hermes_cli.web_deps import late
from hermes_cli.web_models import (
@@ -46,11 +46,10 @@ from hermes_cli.web_models import (
_log = logging.getLogger("hermes_cli.web_server")
# Per-profile session reads report failures in the response's ``errors``
-# array, which the desktop sidebar does not currently surface — during the
-# stale-schema incident that made an empty sidebar look healthy while
-# /api/sessions (which logs) was the only diagnosable trace. Warn once per
-# (profile, message) per process so a persistent failure is loud in
-# errors.log without turning every sidebar poll into log spam.
+# array, which the desktop sidebar does not surface — an empty sidebar can
+# look healthy while nothing logs. Warn once per (profile, message) per
+# process so a persistent failure is loud in errors.log without turning every
+# sidebar poll into log spam.
_profile_read_warned: set = set()
@@ -185,6 +184,97 @@ def _disable_unselected_skills(profile_dir: Path, keep: List[str]) -> int:
_MISSING = object()
+def _profile_errors(log_msg: str, *args, not_found=(FileNotFoundError,),
+ bad_request=(ValueError,)):
+ """Map hermes_cli.profiles exceptions to HTTP: ``not_found`` -> 404,
+ ``bad_request`` -> 400 (checked in that order), anything else is logged
+ with ``log_msg`` and becomes a 500. ``HTTPException`` passes through."""
+ try:
+ yield
+ except HTTPException:
+ raise
+ except not_found as e:
+ raise HTTPException(status_code=404, detail=str(e))
+ except bad_request as e:
+ raise HTTPException(status_code=400, detail=str(e))
+ except Exception as e:
+ _log.exception(log_msg, *args)
+ raise HTTPException(status_code=500, detail=str(e))
+
+
+def _profile_targets(log_label: str, *, lightweight: bool) -> List[Tuple[str, Path]]:
+ """(name, home) for every profile, falling back to ``default`` alone.
+
+ ``lightweight`` uses ``profiles_to_serve`` (name/path only) instead of
+ ``list_profiles``, which parses config/meta and probes gateways/skills
+ per profile — too heavy for every sidebar refresh."""
+ from hermes_cli import profiles as profiles_mod
+
+ try:
+ if lightweight:
+ targets = list(profiles_mod.profiles_to_serve(multiplex=True))
+ else:
+ targets = [(info.name, info.path) for info in profiles_mod.list_profiles()]
+ except Exception:
+ _log.exception("%s: list_profiles failed", log_label)
+ targets = []
+ if not targets:
+ targets.append(("default", profiles_mod.get_profile_dir("default")))
+ return targets
+
+
+def _tag_rows(rows: List[Dict[str, Any]], name: str, now: float) -> List[Dict[str, Any]]:
+ """Stamp session rows with their owning profile and the 300s active
+ heuristic; SQLite stores flags as 0/1 and the sidebar needs booleans."""
+ for s in rows:
+ s["profile"] = name
+ s["is_default_profile"] = name == "default"
+ s["is_active"] = (
+ s.get("ended_at") is None
+ and (now - s.get("last_active", s.get("started_at", 0))) < 300
+ )
+ s["archived"] = bool(s.get("archived"))
+ s["pinned"] = bool(s.get("pinned"))
+ return rows
+
+
+def _pinned_window(rows: List[Dict[str, Any]], offset: int, cap: int) -> List[Dict[str, Any]]:
+ """``rows[offset:offset+cap]`` plus every pinned row past it. The
+ per-profile queries deliberately back-fill pinned rows past their LIMIT,
+ so truncating on recency alone would drop exactly what they fetched."""
+ window = rows[offset:offset + cap]
+ if len(rows) > offset + cap:
+ seen = {id(s) for s in window}
+ window.extend(s for s in rows[offset + cap:] if s.get("pinned") and id(s) not in seen)
+ return window
+
+
+def _recency(s: Dict[str, Any]) -> Any:
+ return s.get("last_active") or s.get("started_at") or 0
+
+
+def _open_profile_db(name: str, home, errors: Optional[List[Dict[str, str]]]):
+ """Read-only SessionDB for a profile's state.db, or None when the file is
+ missing or the open fails (failure recorded in ``errors`` when given).
+
+ Read-only on the healthy path: this runs on every sidebar refresh, so it
+ must not routinely DDL/write-lock another profile's live DB. The helper's
+ stale-schema probe performs a ONE-TIME writable open when the store
+ predates a schema addition — read-only opens skip column reconciliation
+ and would otherwise fail here on every refresh."""
+ db_path = Path(home) / "state.db"
+ if not db_path.exists():
+ return None
+ try:
+ return _open_session_db_at_path(db_path, read_only=True)
+ except Exception as exc:
+ _warn_profile_read_error(name, exc)
+ if errors is not None:
+ errors.append({"profile": name, "error": str(exc)})
+ return None
+
+
# Bounded cache lifetime for the expensive sidebar scan. Short enough that the
# UI never shows meaningfully stale data, long enough to coalesce the desktop's
# reconnect/focus/change poll bursts into one scan.
@@ -206,8 +296,7 @@ def _stat_fingerprint(path: Path):
def _sidebar_db_fingerprint(db_path: Path):
"""Track SQLite content changes through the main DB and its WAL."""
- wal_path = Path(f"{db_path}-wal")
- return (_stat_fingerprint(db_path), _stat_fingerprint(wal_path))
+ return (_stat_fingerprint(db_path), _stat_fingerprint(Path(f"{db_path}-wal")))
def _sidebar_profile_cache_get(key):
@@ -225,12 +314,8 @@ def _sidebar_profile_cache_put(key, value):
with _SIDEBAR_PROFILE_CACHE_LOCK:
# A changed DB/WAL makes all older parameter variants for that profile
# obsolete. Remove them eagerly rather than waiting for LRU pressure.
- stale = [
- existing
- for existing in _SIDEBAR_PROFILE_CACHE
- if existing[0] == db_path and existing[1] != fingerprint
- ]
- for existing in stale:
+ for existing in [k for k in _SIDEBAR_PROFILE_CACHE
+ if k[0] == db_path and k[1] != fingerprint]:
_SIDEBAR_PROFILE_CACHE.pop(existing, None)
_SIDEBAR_PROFILE_CACHE[key] = snapshot
_SIDEBAR_PROFILE_CACHE.move_to_end(key)
@@ -246,14 +331,13 @@ def _sidebar_profile_cache_clear():
def _sidebar_singleflight_cache(func):
"""Coalesce concurrent sidebar scans and briefly reuse their response.
- Every uncached refresh opens every profile database and runs up to three
- session queries per profile. Desktop reconnect/focus/change bursts can
- therefore overlap several identical scans in AnyIO worker threads, which
- amplifies YAML/SQLite work and starves the uvicorn event loop for the GIL.
-
- The short TTL bounds UI staleness while the single-flight lock guarantees
- only one expensive scan runs at a time. Cached values are copied on store
- and hit so FastAPI serialization or a caller cannot mutate shared state.
+ Every uncached refresh opens every profile database and runs several
+ session queries per profile. Desktop reconnect/focus/change bursts overlap
+ identical scans in AnyIO worker threads, amplifying YAML/SQLite work and
+ starving the uvicorn event loop for the GIL. The short TTL bounds UI
+ staleness; the single-flight lock guarantees one expensive scan at a time.
+ Cached values are copied on store and hit so FastAPI serialization or a
+ caller cannot mutate shared state.
"""
signature = inspect.signature(func)
cache = OrderedDict()
@@ -297,9 +381,9 @@ def _sidebar_singleflight_cache(func):
if cached is not miss:
return cached
result = func(*args, **kwargs)
- # A 200 carrying errors[] is a FAILED profile scan, not a
- # successful empty page. Caching it holds the empty recents in
- # front of a store that has already recovered, for the whole TTL.
+ # A 200 carrying errors[] is a FAILED profile scan, not a successful
+ # empty page. Caching it would hold the empty recents in front of a
+ # store that has already recovered, for the whole TTL.
if isinstance(result, dict) and result.get("errors"):
return result
try:
@@ -324,12 +408,10 @@ def _sidebar_singleflight_cache(func):
@sessions_router.get("/api/profiles/sessions")
def get_profiles_sessions(
- # ``le=500`` caps the per-request page size (idea from #39200) — this
- # endpoint fans the query out across EVERY profile's state.db, so an
- # unbounded limit multiplies the damage. 500 (not 100) because real
- # desktop callers use limit=200 (sessions-settings ARCHIVED_FETCH_LIMIT,
- # command palette) and the electron remote-merge over-fetches
- # ``limit + offset``.
+ # ``le=500`` caps the per-request page size — this endpoint fans out across
+ # EVERY profile's state.db, so an unbounded limit multiplies the damage.
+ # 500 (not 100) because real desktop callers use limit=200 and the electron
+ # remote-merge over-fetches ``limit + offset``.
limit: int = Query(20, ge=0, le=500),
offset: int = Query(0, ge=0),
min_messages: int = 0,
@@ -343,37 +425,21 @@ def get_profiles_sessions(
):
"""Unified, read-only session list aggregated across ALL profiles.
- Intentionally process-light: this opens each profile's ``state.db`` directly
- from disk — it does NOT spawn a dashboard backend per profile. Each returned
- session is tagged with its owning ``profile`` so the desktop renders one
- browsable list and only spins up a profile's backend when the user actually
- interacts (sends a message). A user with a single (default) profile gets the
- same rows as ``/api/sessions``, just tagged ``profile="default"``.
-
- Rows omit ``system_prompt``/``model_config`` unless ``full=1`` — same
- list projection as ``/api/sessions``.
+ Process-light: opens each profile's ``state.db`` directly from disk — it
+ does NOT spawn a dashboard backend per profile. Each row is tagged with its
+ owning ``profile`` so the desktop renders one list and only spins up a
+ backend when the user interacts. Rows omit ``system_prompt`` /
+ ``model_config`` unless ``full=1`` — same projection as ``/api/sessions``.
"""
if archived not in ("exclude", "only", "include"):
raise HTTPException(status_code=400, detail="archived must be one of: exclude, only, include")
if order not in ("created", "recent"):
raise HTTPException(status_code=400, detail="order must be one of: created, recent")
- from hermes_cli import profiles as profiles_mod
-
- targets: List[Tuple[str, Path]] = []
if profile and profile != "all":
- name, home = _cron_profile_home(profile)
- targets.append((name, home))
+ targets = [_cron_profile_home(profile)]
else:
- try:
- # This endpoint only needs name/path. Avoid list_profiles(), which
- # parses config/meta and probes gateways/skills per profile.
- targets = profiles_mod.profiles_to_serve(multiplex=True)
- except Exception:
- _log.exception("GET /api/profiles/sessions: list_profiles failed")
- targets = []
- if not targets:
- targets.append(("default", profiles_mod.get_profile_dir("default")))
+ targets = _profile_targets("GET /api/profiles/sessions", lightweight=True)
min_message_count = max(0, min_messages)
archived_only = archived == "only"
@@ -394,22 +460,8 @@ def get_profiles_sessions(
errors: List[Dict[str, str]] = []
now = time.time()
for name, home in targets:
- db_path = Path(home) / "state.db"
- if not db_path.exists():
- continue
- try:
- # Read-only on the healthy path: this loop runs on every sidebar
- # refresh, so it must not routinely DDL/write-lock another
- # profile's live DB (see SessionDB read_only docstring). The
- # helper's stale-schema probe performs a ONE-TIME writable open
- # when the store predates a schema addition — the same reconcile
- # that profile's own backend runs at startup — because read-only
- # opens skip column reconciliation and would otherwise fail here
- # on every refresh until something else opened the DB writable.
- db = _open_session_db_at_path(db_path, read_only=True)
- except Exception as exc:
- _warn_profile_read_error(name, exc)
- errors.append({"profile": name, "error": str(exc)})
+ db = _open_profile_db(name, home, errors)
+ if db is None:
continue
try:
rows = db.list_sessions_rich(
@@ -422,7 +474,7 @@ def get_profiles_sessions(
include_archived=include_archived,
archived_only=archived_only,
order_by_last_active=order == "recent",
- # Same SQL-level blob skip as /api/sessions (see above).
+ # Same SQL-level blob skip as /api/sessions.
compact_rows=not full,
include_pinned=True,
)
@@ -437,16 +489,7 @@ def get_profiles_sessions(
)
total += profile_total
profile_totals[name] = profile_total
- for s in rows:
- s["profile"] = name
- s["is_default_profile"] = name == "default"
- s["is_active"] = (
- s.get("ended_at") is None
- and (now - s.get("last_active", s.get("started_at", 0))) < 300
- )
- s["archived"] = bool(s.get("archived"))
- s["pinned"] = bool(s.get("pinned"))
- merged.append(s)
+ merged.extend(_tag_rows(rows, name, now))
except Exception as exc:
_warn_profile_read_error(name, exc)
errors.append({"profile": name, "error": str(exc)})
@@ -455,12 +498,7 @@ def get_profiles_sessions(
sort_key = "last_active" if order == "recent" else "started_at"
merged.sort(key=lambda s: s.get(sort_key) or s.get("started_at") or 0, reverse=True)
- # Pinned rows are back-filled past each profile's LIMIT on purpose; keep
- # them in the merged window instead of re-dropping them on recency.
- window = merged[offset:offset + limit]
- if len(merged) > offset + limit:
- seen = {id(s) for s in window}
- window.extend(s for s in merged[offset + limit:] if s.get("pinned") and id(s) not in seen)
+ window = _pinned_window(merged, offset, limit)
if not full:
_strip_session_list_rows(window)
return {
@@ -487,35 +525,19 @@ def get_profiles_sessions_sidebar(
The desktop sidebar needs three source-scoped windows per refresh: recents
(local chats), cron sessions, and messaging-platform sessions. Served as
- three separate ``/api/profiles/sessions`` calls they reopened every
- profile's ``state.db`` three times and re-counted each refresh. This opens
- each DB once and runs the three filtered queries together, returning the
- three windows in one payload. Read-only and process-light, same row
- projection and 300s active heuristic as ``/api/profiles/sessions``.
-
- ``recents_profile`` scopes the whole payload, not just recents. Cron and
- messaging used to come back cross-profile unconditionally, which is what
- made a concrete profile show another profile's Telegram threads and
- cronjobs (#65710, #42651, #70629) — the sidebar has one scope, so every
- slice answers to it, and ``all`` is how the caller asks for everything.
+ three ``/api/profiles/sessions`` calls they reopened every profile's DB
+ three times; this opens each once and runs the three queries together.
+ Same row projection and 300s active heuristic as the per-slice endpoint.
+
+ ``recents_profile`` scopes the WHOLE payload, not just recents — the
+ sidebar has one scope, so a concrete profile must never show another
+ profile's Telegram threads or cronjobs; ``all`` asks for everything.
The caller passes the source taxonomy (``recents_exclude`` /
- ``messaging_exclude`` CSV, ``source=cron`` is implicit) so this stays
- taxonomy-agnostic like the per-slice endpoint. All three slices use
- ``min_messages=1`` / ``archived=exclude`` / recency order, matching the
- desktop's per-slice calls.
+ ``messaging_exclude`` CSV, ``source=cron`` is implicit). All slices use
+ ``min_messages=1`` / ``archived=exclude`` / recency order.
"""
- from hermes_cli import profiles as profiles_mod
-
- try:
- # Session aggregation only needs name/path; the lightweight enumerator
- # avoids YAML/meta/gateway/skill probes for all profiles per refresh.
- targets: List[Tuple[str, Path]] = profiles_mod.profiles_to_serve(multiplex=True)
- except Exception:
- _log.exception("GET /api/profiles/sessions/sidebar: list_profiles failed")
- targets = []
- if not targets:
- targets.append(("default", profiles_mod.get_profile_dir("default")))
+ targets = _profile_targets("GET /api/profiles/sessions/sidebar", lightweight=True)
recents_scope = (recents_profile or "all").strip() or "all"
recents_exclude_list = [s for s in (recents_exclude or "").split(",") if s.strip()]
@@ -533,20 +555,6 @@ def get_profiles_sessions_sidebar(
errors: List[Dict[str, str]] = []
now = time.time()
- def _tag(rows: List[Dict[str, Any]], name: str) -> List[Dict[str, Any]]:
- for s in rows:
- s["profile"] = name
- s["is_default_profile"] = name == "default"
- s["is_active"] = (
- s.get("ended_at") is None
- and (now - s.get("last_active", s.get("started_at", 0))) < 300
- )
- s["archived"] = bool(s.get("archived"))
- # SQLite stores the pin as 0/1; the sidebar needs a real boolean to
- # render the Pinned section from server state.
- s["pinned"] = bool(s.get("pinned"))
- return rows
-
def _slice(db, *, source=None, exclude=None, cap):
return db.list_sessions_rich(
source=source,
@@ -569,10 +577,9 @@ def get_profiles_sessions_sidebar(
db_path = Path(home) / "state.db"
if not db_path.exists():
continue
- fingerprint = _sidebar_db_fingerprint(db_path)
profile_cache_key = (
str(db_path),
- fingerprint,
+ _sidebar_db_fingerprint(db_path),
recents_cap,
tuple(recents_exclude_list),
cron_cap,
@@ -581,14 +588,8 @@ def get_profiles_sessions_sidebar(
)
slices = _sidebar_profile_cache_get(profile_cache_key)
if slices is None:
- try:
- # Read-only with the stale-schema heal — same contract as the
- # per-slice endpoint above (one-time writable reconcile when the
- # store predates a schema addition, plain read-only otherwise).
- db = _open_session_db_at_path(db_path, read_only=True)
- except Exception as exc:
- _warn_profile_read_error(name, exc)
- errors.append({"profile": name, "error": str(exc)})
+ db = _open_profile_db(name, home, errors)
+ if db is None:
continue
try:
slices = {
@@ -598,11 +599,7 @@ def get_profiles_sessions_sidebar(
# would be worse than no total at all.
"usage": db.usage_totals(),
"cron": _slice(db, source="cron", cap=cron_cap),
- "messaging": _slice(
- db,
- exclude=messaging_exclude_list,
- cap=messaging_cap,
- ),
+ "messaging": _slice(db, exclude=messaging_exclude_list, cap=messaging_cap),
}
_sidebar_profile_cache_put(profile_cache_key, slices)
except Exception as exc:
@@ -613,27 +610,19 @@ def get_profiles_sessions_sidebar(
db.close()
profile_rows = slices["recents"]
- # A full window means more rows remain on disk. That is all the
- # sidebar's "load more" needs, and unlike an exact COUNT(*) per
- # profile per refresh it costs nothing beyond the rows already
- # read. Discount pinned back-fills — they arrive past the LIMIT
- # and would otherwise fake a full page on a short list.
+ # A full window means more rows remain on disk — all "load more" needs,
+ # at no cost beyond the rows already read. Discount pinned back-fills:
+ # they arrive past the LIMIT and would fake a full page on a short list.
unpinned_count = sum(1 for s in profile_rows if not s.get("pinned"))
recents_truncated[name] = unpinned_count >= recents_cap
- recents_rows.extend(_tag(profile_rows, name))
+ recents_rows.extend(_tag_rows(profile_rows, name, now))
profile_totals[name] = slices["usage"]
- cron_rows.extend(_tag(slices["cron"], name))
- messaging_rows.extend(_tag(slices["messaging"], name))
+ cron_rows.extend(_tag_rows(slices["cron"], name, now))
+ messaging_rows.extend(_tag_rows(slices["messaging"], name, now))
def _window(rows: List[Dict[str, Any]], cap: int) -> List[Dict[str, Any]]:
- rows.sort(key=lambda s: s.get("last_active") or s.get("started_at") or 0, reverse=True)
- # Pinned rows survive the cap. The per-profile queries deliberately
- # back-fill them past the LIMIT, so truncating the merged window on
- # recency alone would throw away exactly what the back-fill fetched.
- win = rows[:cap]
- if len(rows) > cap:
- seen = {id(s) for s in win}
- win.extend(s for s in rows[cap:] if s.get("pinned") and id(s) not in seen)
+ rows.sort(key=_recency, reverse=True)
+ win = _pinned_window(rows, 0, cap)
_strip_session_list_rows(win)
return win
@@ -682,20 +671,18 @@ def _merge_profile_tree(
) -> None:
"""Fold one profile's projects into the shared tree, keyed by folder.
- The same checkout in two profiles is one group, as is ``__no_project__``,
- which every profile has and which would otherwise put a "Home" on screen per
- profile. Keying on the path rather than the id also folds a profile's
- declared project (``p_<hash>``) together with the auto entry another profile
- grows for the same folder. Sessions carry the owning profile instead, which
- is what the row badge and the profile filter read; a group header never
- claims a single owner.
+ The same checkout in two profiles is one group, as is ``__no_project__``
+ (every profile has one, which would otherwise put a "Home" on screen per
+ profile). Keying on the path also folds a declared project (``p_<hash>``)
+ with the auto entry another profile grows for the same folder. Sessions
+ carry the owning profile — the row badge and profile filter read that; a
+ group header never claims a single owner.
"""
for project in projects:
- for lane in (repo for r in project.get("repos") or [] for repo in r.get("groups") or []):
- for session in lane.get("sessions") or []:
- session["profile"] = profile
- session["is_default_profile"] = profile == "default"
- for session in project.get("previewSessions") or []:
+ lane_sessions = (s for r in project.get("repos") or []
+ for lane in r.get("groups") or []
+ for s in lane.get("sessions") or [])
+ for session in [*lane_sessions, *(project.get("previewSessions") or [])]:
session["profile"] = profile
session["is_default_profile"] = profile == "default"
@@ -714,12 +701,11 @@ def _merge_profile_tree(
repos: Dict[str, Dict[str, Any]] = {r["id"]: r for r in existing.get("repos") or []}
_merge_by_id(repos, project.get("repos") or [], "groups")
existing["repos"] = list(repos.values())
- existing["sessionCount"] = (existing.get("sessionCount") or 0) + (project.get("sessionCount") or 0)
- existing["totalTokens"] = (existing.get("totalTokens") or 0) + (project.get("totalTokens") or 0)
- existing["totalCostUsd"] = (existing.get("totalCostUsd") or 0) + (project.get("totalCostUsd") or 0)
+ for total_key in ("sessionCount", "totalTokens", "totalCostUsd"):
+ existing[total_key] = (existing.get(total_key) or 0) + (project.get(total_key) or 0)
existing["lastActive"] = max(existing.get("lastActive") or 0, project.get("lastActive") or 0)
previews = (existing.get("previewSessions") or []) + (project.get("previewSessions") or [])
- previews.sort(key=lambda s: s.get("last_active") or s.get("started_at") or 0, reverse=True)
+ previews.sort(key=_recency, reverse=True)
existing["previewSessions"] = previews[:preview_limit]
@@ -727,52 +713,29 @@ def _merge_profile_tree(
def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000):
"""Project tree for every profile at once, for the all-profiles sidebar.
- ``projects.tree`` over JSON-RPC answers for the backend's own profile, so
- the grouped sidebar had nothing to draw once the user asked for all of
- them. This runs the same authoritative builder once per profile against
- that profile's ``state.db``, scoping the rest of its inputs — projects.db,
- the repo-scan policy, the HERMES_HOME junk filters — through the
- context-local home override the profile-scoped writers already use.
-
- Projects merge by id across profiles, so a group stands for a checkout
- rather than a checkout-and-owner, and the profile shows up per row where
- the filter can act on it.
-
- Discovery is off. A repo with zero sessions is the same repo in every
- profile, so folding the disk scan in would multiply empty lanes by the
- profile count — and it is the one part of the builder that writes
- (policy reconciliation), which this read-only fan-out should not do to a
- profile the user is not driving.
+ ``projects.tree`` over JSON-RPC answers for the backend's own profile only.
+ This runs the same authoritative builder once per profile against that
+ profile's ``state.db``, scoping its other inputs (projects.db, repo-scan
+ policy, HERMES_HOME junk filters) through the context-local home override.
+ Projects merge across profiles so a group stands for a checkout rather than
+ a checkout-and-owner; the profile shows up per row for the filter.
+
+ Discovery is off: a repo with zero sessions is the same repo in every
+ profile (the disk scan would multiply empty lanes by the profile count),
+ and it is the one part of the builder that writes (policy reconciliation),
+ which this read-only fan-out must not do to a profile the user isn't driving.
"""
- from hermes_cli import profiles as profiles_mod
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
from tui_gateway import server as gateway_server
- try:
- targets: List[Tuple[str, Path]] = [
- (info.name, info.path) for info in profiles_mod.list_profiles()
- ]
- except Exception:
- _log.exception("GET /api/profiles/projects/tree: list_profiles failed")
- targets = []
- if not targets:
- targets.append(("default", profiles_mod.get_profile_dir("default")))
-
merged: Dict[str, Dict[str, Any]] = {}
scoped_session_ids: List[str] = []
errors: List[Dict[str, str]] = []
- for name, home in targets:
- db_path = Path(home) / "state.db"
- if not db_path.exists():
+ for name, home in _profile_targets("GET /api/profiles/projects/tree", lightweight=False):
+ db = _open_profile_db(name, home, errors)
+ if db is None:
continue
- try:
- db = _open_session_db_at_path(db_path, read_only=True)
- except Exception as exc:
- _warn_profile_read_error(name, exc)
- errors.append({"profile": name, "error": str(exc)})
- continue
-
token = set_hermes_home_override(str(home))
try:
tree, _active_id = gateway_server._build_project_tree(
@@ -791,9 +754,8 @@ def get_profiles_projects_tree(preview_limit: int = 3, session_limit: int = 2000
reset_hermes_home_override(token)
db.close()
- projects = sorted(merged.values(), key=lambda p: p.get("lastActive") or 0, reverse=True)
return {
- "projects": projects,
+ "projects": sorted(merged.values(), key=lambda p: p.get("lastActive") or 0, reverse=True),
# Ownership is per profile, so no single project is "the active one"
# here; the desktop only reads active_id to bias its overview sort.
"active_id": None,
@@ -825,50 +787,30 @@ def _pr_url_from_tool_output(content: str) -> Optional[Tuple[int, str]]:
def post_profiles_sessions_pull_requests(body: SessionPrScanBody):
"""The PR each of these sessions opened, recovered from its own transcript.
- A session records the branch it started on, so the sidebar can join a row to
- its PR — but a session that starts in the main checkout and does its work in
- a worktree has no branch of its own, and its PR is invisible to that join.
- The evidence is in the conversation: ``gh pr create`` ran, and its output is
- a bare PR url. Scanning for exactly that shape recovers the link with no
- inference (see ``_pr_url_from_tool_output``).
-
- Read-only across every profile, and the caller is expected to ask once per
- session and remember the answer — a session's transcript does not grow a
- second PR.
+ A session records the branch it started on, but one that starts in the main
+ checkout and works in a worktree has no branch of its own, so its PR is
+ invisible to that join. The evidence is in the conversation: ``gh pr
+ create`` ran and its output is a bare PR url (see
+ ``_pr_url_from_tool_output``). Read-only across every profile; the caller
+ asks once per session and remembers the answer.
"""
- from hermes_cli import profiles as profiles_mod
-
wanted = list(dict.fromkeys(s for s in (body.ids or []) if s))[:2000]
if not wanted:
return {"pull_requests": {}, "scanned": []}
- try:
- targets = [(info.name, info.path) for info in profiles_mod.list_profiles()]
- except Exception:
- _log.exception("POST /api/profiles/sessions/pull-requests: list_profiles failed")
- targets = []
- if not targets:
- targets.append(("default", profiles_mod.get_profile_dir("default")))
-
found: Dict[str, Dict[str, Any]] = {}
- for name, home in targets:
- db_path = Path(home) / "state.db"
- if not db_path.exists():
- continue
- try:
- db = _open_session_db_at_path(db_path, read_only=True)
- except Exception as exc:
- _warn_profile_read_error(name, exc)
+ for name, home in _profile_targets("POST /api/profiles/sessions/pull-requests", lightweight=False):
+ db = _open_profile_db(name, home, None)
+ if db is None:
continue
try:
for pr in db.find_pr_url_messages(wanted):
parsed = _pr_url_from_tool_output(pr["content"])
if parsed:
- number, url = parsed
- # Ordered oldest-first, so a later `gh pr create` in the
- # same conversation wins — a reopened/replacement PR is the
- # one the session ended on.
- found[pr["session_id"]] = {"number": number, "url": url}
+ # Ordered oldest-first, so a later `gh pr create` in the same
+ # conversation wins — the replacement PR is the one the
+ # session ended on.
+ found[pr["session_id"]] = {"number": parsed[0], "url": parsed[1]}
except Exception as exc:
_warn_profile_read_error(name, exc)
finally:
@@ -897,20 +839,17 @@ async def create_profile_endpoint(body: ProfileCreate):
if explicit_source:
# Duplicating a specific profile: clone its config/skills/SOUL (or full
# state when clone_all) from the named source rather than "default".
- clone = True
- clone_from = explicit_source
- clone_config = not body.clone_all
+ clone, clone_from, clone_config = True, explicit_source, not body.clone_all
elif body.clone_all:
- # Preserve the dashboard's historical clone-all behavior: a full-copy
- # request with no explicit dropdown source copies from default.
- clone = True
- clone_from = "default"
- clone_config = False
+ # Historical dashboard clone-all behavior: a full-copy request with no
+ # explicit dropdown source copies from default.
+ clone, clone_from, clone_config = True, "default", False
else:
clone = body.clone_from_default
clone_from = "default" if clone else None
clone_config = clone
- try:
+ with _profile_errors("POST /api/profiles failed", not_found=(),
+ bad_request=(ValueError, FileExistsError, FileNotFoundError)):
path = profiles_mod.create_profile(
name=body.name,
clone_from=clone_from,
@@ -920,28 +859,19 @@ async def create_profile_endpoint(body: ProfileCreate):
description=body.description,
)
# Match the CLI's profile-create flow: fresh named profiles get the
- # bundled skills installed. When cloning from default, create_profile()
- # has already copied the source profile's skills, including any
- # user-installed skills. When no_skills=True, create_profile() wrote
- # the opt-out marker and seed_profile_skills() will no-op.
+ # bundled skills. Cloning already copied the source's skills (incl.
+ # user-installed); no_skills wrote the opt-out marker so seeding no-ops.
if not clone:
profiles_mod.seed_profile_skills(path, quiet=True)
- # Match the CLI's profile-create flow: named profiles should get a
- # wrapper in ~/.local/bin when the alias is safe to create.
- collision = profiles_mod.check_alias_collision(body.name)
- if not collision:
+ # Match the CLI: named profiles get a ~/.local/bin wrapper when the
+ # alias is safe to create.
+ if not profiles_mod.check_alias_collision(body.name):
profiles_mod.create_wrapper_script(body.name)
- except (ValueError, FileExistsError, FileNotFoundError) as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- _log.exception("POST /api/profiles failed")
- raise HTTPException(status_code=500, detail=str(e))
- # Optional explicit model assignment for the new profile. Best-effort:
- # the profile already exists, so a model-write hiccup must not 500 the
- # whole create — the user can set the model later from the Models page
- # or `<profile> setup`.
+ # Everything below is best-effort: the profile already exists, so a hiccup
+ # must not 500 the whole create — the user can fix it from the relevant
+ # dashboard page or `<profile> setup` afterward.
provider = (body.provider or "").strip()
model = (body.model or "").strip()
model_set = False
@@ -952,7 +882,6 @@ async def create_profile_endpoint(body: ProfileCreate):
except Exception:
_log.exception("Setting model for new profile %s failed", body.name)
- # Optional MCP servers. Best-effort, same rationale as model assignment.
mcp_written = 0
if body.mcp_servers:
try:
@@ -960,9 +889,8 @@ async def create_profile_endpoint(body: ProfileCreate):
except Exception:
_log.exception("Writing MCP servers for new profile %s failed", body.name)
- # Optional "keep" skill selection — replace semantics. When the builder
- # sends an explicit keep list, disable every seeded skill not in it.
- # Best-effort. Skipped when keep_skills is empty (legacy: keep the bundle).
+ # "keep" skill selection has replace semantics: disable every seeded skill
+ # not in the list. Skipped when empty (legacy: keep the bundle).
skills_disabled = 0
if body.keep_skills:
try:
@@ -970,9 +898,9 @@ async def create_profile_endpoint(body: ProfileCreate):
except Exception:
_log.exception("Applying skill selection for new profile %s failed", body.name)
- # Optional skills-hub installs. Spawned async, scoped to the new profile
- # via `-p <name>` (a fresh subprocess re-binds skills_hub.SKILLS_DIR to the
- # profile's HERMES_HOME at import). Returns PIDs for the UI to poll.
+ # Skills-hub installs are spawned async, scoped to the new profile via
+ # `-p <name>` (a fresh subprocess re-binds skills_hub.SKILLS_DIR to the
+ # profile's HERMES_HOME at import). PIDs go back for the UI to poll.
hub_installs: List[Dict[str, Any]] = []
for identifier in body.hub_skills:
ident = (identifier or "").strip()
@@ -1005,13 +933,9 @@ async def create_profile_endpoint(body: ProfileCreate):
@router.get("/api/profiles/active")
async def get_active_profile_endpoint():
- """Return the sticky active profile and the profile this dashboard
- process is currently running as.
-
- ``active`` is the sticky default written by ``hermes profile use`` —
- the profile new CLI invocations pick up. ``current`` is the profile
- the running dashboard/gateway is scoped to (derived from HERMES_HOME).
- """
+ """``active`` is the sticky default written by ``hermes profile use`` (what
+ new CLI invocations pick up); ``current`` is the profile this running
+ dashboard/gateway is scoped to (derived from HERMES_HOME)."""
from hermes_cli import profiles as profiles_mod
def _run():
@@ -1034,27 +958,14 @@ async def get_active_profile_endpoint():
@router.post("/api/profiles/active")
async def set_active_profile_endpoint(body: ProfileActiveUpdate):
- """Set the sticky active profile (mirrors ``hermes profile use``).
-
- Note: this does not retarget the already-running dashboard process —
- it changes which profile subsequent CLI commands and gateways use.
- """
+ """Set the sticky active profile (mirrors ``hermes profile use``). Does not
+ retarget the already-running dashboard — it changes which profile
+ subsequent CLI commands and gateways use."""
from hermes_cli import profiles as profiles_mod
-
- def _run():
- return profiles_mod.set_active_profile(body.name)
-
- try:
+ with _profile_errors("POST /api/profiles/active failed"):
# set_active_profile() stats the target profile, creates the state
# directory and writes active_profile through a temp file + replace.
- await run_in_threadpool(_run)
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- _log.exception("POST /api/profiles/active failed")
- raise HTTPException(status_code=500, detail=str(e))
+ await run_in_threadpool(profiles_mod.set_active_profile, body.name)
return {"ok": True, "active": profiles_mod.normalize_profile_name(body.name)}
@@ -1063,9 +974,26 @@ async def get_profile_setup_command(name: str):
return {"command": _profile_setup_command(name)}
+def _linux_terminal_commands(command: str) -> list:
+ sh = ["sh", "-lc", command]
+ quoted = f"sh -lc '{command}'"
+ return [
+ ("x-terminal-emulator", ["x-terminal-emulator", "-e", *sh]),
+ ("gnome-terminal", ["gnome-terminal", "--", *sh]),
+ ("konsole", ["konsole", "-e", *sh]),
+ ("xfce4-terminal", ["xfce4-terminal", "-e", quoted]),
+ ("mate-terminal", ["mate-terminal", "-e", quoted]),
+ ("lxterminal", ["lxterminal", "-e", quoted]),
+ ("tilix", ["tilix", "-e", *sh]),
+ ("alacritty", ["alacritty", "-e", *sh]),
+ ("kitty", ["kitty", *sh]),
+ ("xterm", ["xterm", "-e", *sh]),
+ ]
+
+
@router.post("/api/profiles/{name}/open-terminal")
async def open_profile_terminal_endpoint(name: str):
- try:
+ with _profile_errors("POST /api/profiles/%s/open-terminal failed", name):
command = _profile_setup_command(name)
if sys.platform.startswith("win"):
@@ -1080,19 +1008,7 @@ async def open_profile_terminal_endpoint(name: str):
)
subprocess.Popen(["osascript", "-e", applescript])
else:
- terminal_commands = [
- ("x-terminal-emulator", ["x-terminal-emulator", "-e", "sh", "-lc", command]),
- ("gnome-terminal", ["gnome-terminal", "--", "sh", "-lc", command]),
- ("konsole", ["konsole", "-e", "sh", "-lc", command]),
- ("xfce4-terminal", ["xfce4-terminal", "-e", f"sh -lc '{command}'"]),
- ("mate-terminal", ["mate-terminal", "-e", f"sh -lc '{command}'"]),
- ("lxterminal", ["lxterminal", "-e", f"sh -lc '{command}'"]),
- ("tilix", ["tilix", "-e", "sh", "-lc", command]),
- ("alacritty", ["alacritty", "-e", "sh", "-lc", command]),
- ("kitty", ["kitty", "sh", "-lc", command]),
- ("xterm", ["xterm", "-e", "sh", "-lc", command]),
- ]
- for executable, popen_args in terminal_commands:
+ for executable, popen_args in _linux_terminal_commands(command):
if subprocess.call(
["which", executable],
stdout=subprocess.DEVNULL,
@@ -1105,41 +1021,22 @@ async def open_profile_terminal_endpoint(name: str):
status_code=400,
detail="No supported terminal emulator found",
)
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except HTTPException:
- raise
- except Exception as e:
- _log.exception("POST /api/profiles/%s/open-terminal failed", name)
- raise HTTPException(status_code=500, detail=str(e))
return {"ok": True, "command": command}
@router.patch("/api/profiles/{name}")
async def rename_profile_endpoint(name: str, body: ProfileRename):
from hermes_cli import profiles as profiles_mod
-
- def _run():
- return profiles_mod.rename_profile(name, body.new_name)
-
- try:
+ with _profile_errors("PATCH /api/profiles/%s failed", name,
+ bad_request=(ValueError, FileExistsError)):
# rename_profile() stops a running gateway through the same 10-second
# _stop_gateway_process() poll that delete does, then renames the
# profile directory, rewrites the Honcho host blocks and regenerates
# the wrapper script.
- path = await run_in_threadpool(_run)
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except (ValueError, FileExistsError) as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- _log.exception("PATCH /api/profiles/%s failed", name)
- raise HTTPException(status_code=500, detail=str(e))
+ path = await run_in_threadpool(profiles_mod.rename_profile, name, body.new_name)
# For the default profile the rename lands as a presentation-only
- # display_name; the canonical id ("default") is unchanged. Always
- # return the canonical id so callers keying on `name` stay correct.
+ # display_name; the canonical id ("default") is unchanged. Always return
+ # the canonical id so callers keying on `name` stay correct.
try:
is_default = profiles_mod.normalize_profile_name(name) == "default"
except ValueError:
@@ -1160,29 +1057,15 @@ async def rename_profile_endpoint(name: str, body: ProfileRename):
@router.delete("/api/profiles/{name}")
async def delete_profile_endpoint(name: str):
- """Delete a profile. The dashboard collects the user's confirmation in
- its own dialog before this request, so we always pass ``yes=True`` to
- skip the CLI's interactive prompt."""
+ """The dashboard collects the user's confirmation in its own dialog, so
+ ``yes=True`` always skips the CLI's interactive prompt."""
from hermes_cli import profiles as profiles_mod
-
- def _run():
- return profiles_mod.delete_profile(name, yes=True)
-
- try:
+ with _profile_errors("DELETE /api/profiles/%s failed", name):
# delete_profile() stops a running gateway by polling its PID once
- # every 500 ms for up to 10 s (profiles._stop_gateway_process) and
- # then rmtree()s the profile directory. Deleting a profile whose
- # gateway is up — which this path announces as "⚠ Gateway is running
- # — it will be stopped" — therefore parks the loop for a full ten
- # seconds, and the desktop's WebSocket ready-probe gives up at ten.
- path = await run_in_threadpool(_run)
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- _log.exception("DELETE /api/profiles/%s failed", name)
- raise HTTPException(status_code=500, detail=str(e))
+ # every 500 ms for up to 10 s, then rmtree()s the profile directory;
+ # on the loop that parks every request past the desktop's 10 s
+ # WebSocket ready-probe.
+ path = await run_in_threadpool(profiles_mod.delete_profile, name, yes=True)
return {"ok": True, "path": str(path)}
@@ -1213,20 +1096,17 @@ async def update_profile_soul(name: str, body: ProfileSoulUpdate):
def _run():
from utils import atomic_write_text
- # PUT replaces the whole persona document from the dashboard editor.
- # A bare write_text() truncates SOUL.md before the new body lands, and
- # the paired GET above reports an unreadable file as
- # ``{"content": "", "exists": False}`` -- so an interrupted save shows
- # up as "your persona was never set" and the editor's next Save
+ # PUT replaces the whole persona document. A bare write_text() truncates
+ # SOUL.md before the new body lands, and the paired GET reports an
+ # unreadable file as ``{"content": "", "exists": False}`` — so an
+ # interrupted save reads as "never set" and the editor's next Save
# persists that empty document over it.
#
- # preserve_mode carries an existing file's permission bits and owner
- # across the replace. create_mode=0o644 covers the first save: named
- # profiles seed SOUL.md at the umask default (hermes_cli.profiles
- # chmods only .env to 0600), and SOUL.md is not a secret. (The default
- # profile's runtime seeder does run it through _secure_file, but that
- # seeder fires on every load_config, so the file already exists there
- # and preserve_mode keeps whatever mode it set.)
+ # preserve_mode keeps an existing file's mode/owner across the replace.
+ # create_mode=0o644 covers the first save: named profiles seed SOUL.md
+ # at the umask default (profiles chmods only .env to 0600) and SOUL.md
+ # is not a secret. (The default profile's seeder runs on every
+ # load_config, so its file already exists and preserve_mode applies.)
atomic_write_text(
soul_path, body.content, preserve_mode=True, create_mode=0o644
)
@@ -1245,81 +1125,61 @@ async def update_profile_soul(name: str, body: ProfileSoulUpdate):
@router.put("/api/profiles/{name}/description")
async def update_profile_description_endpoint(name: str, body: ProfileDescriptionUpdate):
"""Set or clear a profile's role description (kanban routing signal).
-
- Empty string clears the description. Non-empty stores it as a
- user-authored description (``description_auto: false``) so the
- auto-describer won't overwrite it on a sweep.
- """
+ Non-empty stores it as user-authored (``description_auto: false``) so the
+ auto-describer won't overwrite it on a sweep."""
from hermes_cli import profiles as profiles_mod
profile_dir = _resolve_profile_dir(name)
text = (body.description or "").strip()
-
- def _run():
- profiles_mod.write_profile_meta(
+ with _profile_errors("PUT /api/profiles/%s/description failed", name,
+ not_found=(), bad_request=()):
+ # write_profile_meta() reads profile.yaml, merges and rewrites it.
+ await run_in_threadpool(
+ profiles_mod.write_profile_meta,
profile_dir,
description=text,
description_auto=False,
)
-
- try:
- # write_profile_meta() reads profile.yaml, merges the new keys and
- # writes the document back out.
- await run_in_threadpool(_run)
- except Exception as e:
- _log.exception("PUT /api/profiles/%s/description failed", name)
- raise HTTPException(status_code=500, detail=str(e))
return {"ok": True, "description": text, "description_auto": False}
@router.put("/api/profiles/{name}/model")
async def update_profile_model_endpoint(name: str, body: ProfileModelUpdate):
"""Set the main model (``model.default`` + ``model.provider``) for a
- specific profile's config.yaml, without touching the dashboard's own
- active profile. Mirrors ``POST /api/model/set`` (main scope) but scoped
- to the named profile via the HERMES_HOME override.
- """
+ specific profile's config.yaml without touching the dashboard's own
+ active profile. Mirrors ``POST /api/model/set`` (main scope) scoped to
+ the named profile via the HERMES_HOME override."""
profile_dir = _resolve_profile_dir(name)
provider = (body.provider or "").strip()
model = (body.model or "").strip()
if not provider or not model:
raise HTTPException(status_code=400, detail="provider and model are required")
- try:
+ with _profile_errors("PUT /api/profiles/%s/model failed", name,
+ not_found=(), bad_request=()):
# _write_profile_model() reads and rewrites the profile's config.yaml.
await run_in_threadpool(_write_profile_model, profile_dir, provider, model)
- except Exception as e:
- _log.exception("PUT /api/profiles/%s/model failed", name)
- raise HTTPException(status_code=500, detail=str(e))
return {"ok": True, "provider": provider, "model": model}
@router.post("/api/profiles/{name}/describe-auto")
async def describe_profile_auto_endpoint(name: str, body: ProfileDescribeAuto):
"""Auto-generate a profile's description via the auxiliary LLM
- (``auxiliary.profile_describer``). Mirrors ``hermes profile describe
- <name> --auto``.
-
- A failed generation (no aux client, LLM error, …) is returned as
+ (``auxiliary.profile_describer``); mirrors ``hermes profile describe
+ <name> --auto``. A failed generation (no aux client, LLM error, …) is
``ok: false`` with a reason rather than an HTTP error so the UI can
- surface it inline and let the operator fix config and retry.
- """
- # Resolution stays on the loop: it is a name check plus one stat, and it
- # owns the 400/404 mapping that the ``except Exception`` below would
- # otherwise flatten into a 500.
+ surface it inline and let the operator fix config and retry."""
+ # Resolution stays on the loop: a name check plus one stat, and it owns
+ # the 400/404 mapping that the 500 fallback below would flatten.
_resolve_profile_dir(name)
def _run():
from hermes_cli import profile_describer
return profile_describer.describe_profile(name, overwrite=bool(body.overwrite))
- try:
- # describe_profile() is a plain def that reaches auxiliary_client's
- # call_llm() — a synchronous provider round-trip with a 60 s ceiling,
- # six times the desktop's WebSocket disconnect threshold. Held on the
- # loop it stalls every other dashboard request for that whole window.
+ with _profile_errors("POST /api/profiles/%s/describe-auto failed", name,
+ not_found=(), bad_request=()):
+ # describe_profile() is a synchronous LLM round-trip with a 60 s
+ # ceiling; held on the loop it stalls every other dashboard request.
outcome = await run_in_threadpool(_run)
- except Exception as e:
- _log.exception("POST /api/profiles/%s/describe-auto failed", name)
- raise HTTPException(status_code=500, detail=str(e))
return {
"ok": bool(outcome.ok),
"reason": outcome.reason,
@@ -1338,6 +1198,12 @@ async def describe_profile_auto_endpoint(name: str, body: ProfileDescribeAuto):
# share the filesystem with the native save/open dialogs that produce them.
+def _read_desktop_overlay(profile_dir: Path) -> Any:
+ """The desktop appearance overlay bundled with an imported profile
+ (``desktop.json`` at the profile root); raises when unreadable."""
+ return json.loads((profile_dir / "desktop.json").read_text(encoding="utf-8"))
+
+
@router.post("/api/profiles/{name}/export")
async def export_profile_endpoint(name: str, body: ProfileExport):
from hermes_cli import profiles as profiles_mod
@@ -1351,17 +1217,9 @@ async def export_profile_endpoint(name: str, body: ProfileExport):
except OSError as exc:
raise HTTPException(status_code=500, detail=f"Could not create export directory: {exc}")
- try:
+ with _profile_errors("POST /api/profiles/%s/export failed", name):
result = await run_in_threadpool(
- profiles_mod.export_profile, name, output, extra_files=body.extra_files or None
- )
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except ValueError as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- _log.exception("POST /api/profiles/%s/export failed", name)
- raise HTTPException(status_code=500, detail=str(e))
+ profiles_mod.export_profile, name, output, extra_files=body.extra_files or None)
return {"ok": True, "archive": str(result)}
@@ -1373,17 +1231,10 @@ async def import_profile_endpoint(body: ProfileImport):
if not archive:
raise HTTPException(status_code=400, detail="archive path is required")
- try:
+ with _profile_errors("POST /api/profiles/import failed",
+ bad_request=(ValueError, FileExistsError)):
profile_dir = await run_in_threadpool(
- profiles_mod.import_profile, archive, name=(body.name or "").strip() or None
- )
- except FileNotFoundError as e:
- raise HTTPException(status_code=404, detail=str(e))
- except (ValueError, FileExistsError) as e:
- raise HTTPException(status_code=400, detail=str(e))
- except Exception as e:
- _log.exception("POST /api/profiles/import failed")
- raise HTTPException(status_code=500, detail=str(e))
+ profiles_mod.import_profile, archive, name=(body.name or "").strip() or None)
imported = profile_dir.name
# Match the CLI import flow: create the wrapper alias when it's safe.
@@ -1394,14 +1245,12 @@ async def import_profile_endpoint(body: ProfileImport):
_log.exception("Creating wrapper for imported profile %s failed", imported)
# Surface the bundled desktop appearance overlay (if the archive carried
- # one) so the desktop can apply theme/interface prefs without re-reading
- # the file over another round-trip.
+ # one) so the desktop can apply theme/interface prefs without another
+ # round-trip.
desktop_overlay = None
- overlay_path = profile_dir / "desktop.json"
- if overlay_path.is_file():
+ if (profile_dir / "desktop.json").is_file():
try:
- import json as _json
- desktop_overlay = _json.loads(overlay_path.read_text(encoding="utf-8"))
+ desktop_overlay = _read_desktop_overlay(profile_dir)
except Exception:
_log.exception("Reading desktop.json from imported profile %s failed", imported)
@@ -1417,13 +1266,14 @@ async def import_profile_endpoint(body: ProfileImport):
async def get_profile_desktop_overlay(name: str):
"""The desktop appearance/interface overlay bundled with an imported
profile (``desktop.json`` at the profile root), or ``exists: false``."""
- overlay_path = _resolve_profile_dir(name) / "desktop.json"
+ profile_dir = _resolve_profile_dir(name)
def _run():
- if not overlay_path.is_file():
+ # Probe and read in one hop; _MISSING (not None) because desktop.json
+ # may legitimately hold the document ``null``.
+ if not (profile_dir / "desktop.json").is_file():
return _MISSING
- import json as _json
- return _json.loads(overlay_path.read_text(encoding="utf-8"))
+ return _read_desktop_overlay(profile_dir)
try:
overlay = await run_in_threadpool(_run)