Skip to content

The agent that grows with you

fix(tui): resolve default profile session names

joaomarcos298893df66e5
diff --git a/hermes_constants.py b/hermes_constants.py
index 373fdd51be0..9b9ee3c785a 100644
--- a/hermes_constants.py
+++ b/hermes_constants.py
@@ -206,6 +206,24 @@ def named_profile_home(path: str | Path) -> Path | None:
return None
+def profile_name_for_home(path: str | Path | None) -> str | None:
+ """Return the canonical profile id owning *path*, or ``None`` when it is not a profile home.
+
+ The default home is the Hermes root itself, so its basename is an installation detail (``.hermes``
+ on POSIX and commonly ``hermes`` on Windows), not the profile id ``default``.
+ """
+ if path is None or not str(path).strip():
+ return None
+ current = Path(path).expanduser()
+ try:
+ if current.resolve(strict=False) == get_default_hermes_root().resolve(strict=False):
+ return "default"
+ named = named_profile_home(current)
+ except (OSError, RuntimeError, ValueError):
+ return None
+ return named.name if named is not None else None
+
+
def profile_tombstone_path(profile_home: Path) -> Path:
return profile_home.parent / _DELETED_PROFILES_DIR / profile_home.name
diff --git a/tests/tui_gateway/test_default_profile_session_name.py b/tests/tui_gateway/test_default_profile_session_name.py
new file mode 100644
index 00000000000..78a04b25dca
--- /dev/null
+++ b/tests/tui_gateway/test_default_profile_session_name.py
@@ -0,0 +1,82 @@
+"""Default-profile session names must be derived from the home path, not its basename."""
+
+from __future__ import annotations
+
+import contextlib
+from pathlib import Path
+
+
+def _profile_layout(tmp_path: Path) -> tuple[Path, Path]:
+ root = tmp_path / ".hermes"
+ default_home = root
+ launch_home = root / "profiles" / "worker"
+ launch_home.mkdir(parents=True)
+ return default_home, launch_home
+
+
+def test_default_home_aliases_are_reported_as_default(tmp_path, monkeypatch):
+ """Legacy basename values must not be resolved as missing named profiles."""
+ from tui_gateway import server
+
+ default_home, launch_home = _profile_layout(tmp_path)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(launch_home))
+ monkeypatch.setattr(server, "_hermes_home", launch_home)
+
+ for alias in (default_home.name, "hermes"):
+ assert server._response_profile_name(alias) == "default"
+ assert server._session_info(None, {"profile_home": str(default_home)})["profile_name"] == "default"
+
+
+def test_profile_home_resolution_stamps_default_rows(tmp_path, monkeypatch):
+ """Default and named homes resolve canonically, including lazy row creation."""
+ from hermes_constants import profile_name_for_home
+ from tui_gateway import server
+
+ default_home, launch_home = _profile_layout(tmp_path)
+ named_home = default_home / "profiles" / "writer"
+ named_home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(launch_home))
+ monkeypatch.setattr(server, "_hermes_home", launch_home)
+
+ assert profile_name_for_home(default_home) == "default"
+ assert profile_name_for_home(named_home) == "writer"
+ assert server._session_info(None, {"profile_home": str(named_home)})["profile_name"] == "writer"
+
+ class CaptureDB:
+ profile_name = None
+
+ def create_session(self, _key, **kwargs):
+ self.profile_name = kwargs["profile_name"]
+
+ def append_messages_batch(self, _key, _messages, *, chunk_rows):
+ assert chunk_rows == 500
+
+ def get_session_title(self, _key):
+ return "branch"
+
+ def set_session_title(self, _key, _title):
+ return None
+
+ captured = CaptureDB()
+
+ @contextlib.contextmanager
+ def owner_db(_session, _failure_message=None):
+ yield captured
+
+ monkeypatch.setattr(server, "_workdir_owner_db", owner_db)
+ monkeypatch.setattr(server, "_workdir_row_model_config", lambda _session: ("test-model", {}))
+ monkeypatch.setattr(server, "_session_source", lambda _session: "desktop")
+ monkeypatch.setattr(server, "_persisted_session_cwd", lambda _session: None)
+
+ session = {"session_key": "default-row", "profile_home": str(default_home)}
+ assert server._ensure_session_db_row(session) is True
+ assert captured.profile_name == "default"
+
+ monkeypatch.setattr(server, "_session_db", owner_db)
+ record = {"cwd": str(tmp_path), "pending_title": "branch"}
+ server._seed_branch_row(record, "seeded-row", "parent-row", [{"role": "user", "content": "hi"}], "desktop",
+ str(default_home))
+ assert captured.profile_name == "default"
+ assert record["pending_title"] is None
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index e12cdab1bfb..d75bdd4c26e 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -268,7 +268,7 @@ def _seed_branch_row(record: dict, key: str, parent_session_id: str, history: li
return
_persist_branch(db, key, parent_session_id, _branch_title(db, parent_session_id), history,
source=source, cwd=record["cwd"],
- profile_name=(Path(profile_home).name if profile_home else None), compensate=True)
+ profile_name=profile_name_for_home(profile_home) or _current_profile_name(), compensate=True)
record["pending_title"] = None
except Exception:
logger.warning("seeded-branch persistence failed for %s; falling back to lazy row creation", key,
@@ -1922,7 +1922,7 @@ def _(rid, params: dict, session: dict) -> dict:
title = params.get("name", "") or _branch_title(db, old_key)
home = session.get("profile_home")
_persist_branch(db, new_key, old_key, title, history, source=source, cwd=_session_cwd(session),
- profile_name=Path(home).name if home else _current_profile_name(),
+ profile_name=profile_name_for_home(home) or _current_profile_name(),
copy_fields=_BRANCH_COPY_FIELDS)
except Exception as e:
return _err(rid, 5008, f"branch failed: {e}")
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 9973dde208c..46a1e379921 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -23,7 +23,8 @@ from typing import Any, Callable, NamedTuple, Optional # noqa: F401 (Callable:
# namespace (method_ctx.bind_module) — deleting one breaks a handler at call time, not import time.
from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope # noqa: F401
from hermes_constants import (
- get_hermes_home, get_hermes_home_override, reset_hermes_home_override, set_hermes_home_override)
+ get_default_hermes_root, get_hermes_home, get_hermes_home_override, profile_name_for_home,
+ reset_hermes_home_override, set_hermes_home_override)
from hermes_cli.env_loader import load_hermes_dotenv
from utils import is_truthy_value
from tools.environments.local import hermes_subprocess_env
@@ -444,9 +445,30 @@ def _profile_db(params: dict | None = None):
db.close()
+def _canonical_profile_request(name: str) -> str:
+ """Canonicalize profile basenames emitted by older session-info payloads.
+
+ ``Path(default_home).name`` was historically sent as a profile id. Those
+ basenames are installation details, while explicit unknown profile names
+ must continue to fail closed in ``_profile_home``.
+ """
+ folded = name.casefold()
+ if folded in {".hermes", "hermes"}:
+ return "default"
+ with contextlib.suppress(OSError, RuntimeError, ValueError):
+ if folded == get_default_hermes_root().name.casefold():
+ from hermes_cli import profiles as profiles_mod
+ # A custom Hermes root can share a name with a valid named profile.
+ # Prefer that real profile when it exists; otherwise this is the
+ # legacy basename of the default root.
+ if not Path(profiles_mod.get_profile_dir(name)).is_dir():
+ return "default"
+ return name
+
+
def _response_profile_name(profile: str | None = None) -> str:
"""Profile name for session.* payloads: the requested real non-launch profile, else the launch one."""
- name = (profile or "").strip()
+ name = _canonical_profile_request((profile or "").strip())
return name if name and _profile_home(name) is not None else _current_profile_name()
@@ -459,7 +481,7 @@ def _db_unavailable_error(rid, *, code: int):
# override) so config/skills/model/persistence resolve to it. Omitted/own profile → launch profile.
def _profile_home(profile: str | None) -> Path | None:
"""Resolve a named profile's home on THIS host, or None for the launch profile."""
- if not (name := (profile or "").strip()):
+ if not (name := _canonical_profile_request((profile or "").strip())):
return None
from hermes_cli import profiles as profiles_mod
home = Path(profiles_mod.get_profile_dir(name))
@@ -2058,9 +2080,7 @@ def _session_info(agent, session: dict | None = None) -> dict:
"stored_session_id": session_key or "", "desktop_contract": DESKTOP_BACKEND_CONTRACT,
"version": "", "release_date": "", "update_behind": None, "update_command": "",
"usage": _session_usage_snapshot(session),
- "profile_name": (
- _response_profile_name(Path(session["profile_home"]).name)
- if isinstance(session, dict) and session.get("profile_home") else _current_profile_name()),
+ "profile_name": profile_name_for_home(sess.get("profile_home")) or _current_profile_name(),
}
with contextlib.suppress(Exception):
from hermes_cli import __version__, __release_date__
diff --git a/tui_gateway/session_workdir.py b/tui_gateway/session_workdir.py
index 0122e5eabcb..148b59fe5da 100644
--- a/tui_gateway/session_workdir.py
+++ b/tui_gateway/session_workdir.py
@@ -275,7 +275,7 @@ def _ensure_session_db_row(session: dict) -> bool:
# #94724 legacy-owner backfill exists to repair, and rows minted AFTER that one-shot
# backfill ran stayed NULL forever: profile-keyed matching then drops them from the sidebar
# and deep links can't resolve them (#99222).
- profile_name=Path(profile_home).name if profile_home else _current_profile_name())
+ profile_name=profile_name_for_home(profile_home) or _current_profile_name())
# Born hidden (session.create hidden=true, or set_hidden before the row existed): apply the deferred intent.
if session.get("pending_hidden"):
try: