Skip to content

The agent that grows with you

fix(tui_gateway): scan remote git roots and scope projects.* to the focused profile

Brooklyn Nicholson4dcefed089b3
diff --git a/tests/tui_gateway/test_projects_rpc.py b/tests/tui_gateway/test_projects_rpc.py
index 55fa0436359..a2f93148280 100644
--- a/tests/tui_gateway/test_projects_rpc.py
+++ b/tests/tui_gateway/test_projects_rpc.py
@@ -2,11 +2,14 @@
from __future__ import annotations
+import contextlib
import os
import subprocess
+from pathlib import Path
import pytest
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
import tui_gateway.server as server
@@ -336,6 +339,139 @@ def test_scan_time_is_not_treated_as_session_activity(tmp_path):
assert active["last_active"] > idle["last_active"]
+def test_remote_scan_failure_merges_instead_of_replacing_cache(tmp_path, monkeypatch):
+ """A backend scan that can't fully walk its roots must NOT wipe the cache.
+
+ `projects.discover_repos` with `scan:true` asks the remote host to scan its
+ own discovery roots. When one root fails to walk, the scan result is not the
+ authoritative full universe — the previously cached repos must survive so a
+ failed remote refresh can't blank the sidebar back to the silent, empty
+ state of #81723 (regression for MEDIUM: `replace=True` was wiping on every
+ call regardless of success).
+ """
+ from hermes_cli import projects_db as pdb
+ import tui_gateway.server as server
+
+ def _git_repo(path):
+ repo = path
+ repo.mkdir(parents=True)
+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
+ return str(repo)
+
+ # A cached repo the partial scan never visits, parked OUTSIDE the scan roots.
+ seed = _git_repo(tmp_path / "elsewhere" / "seed-repo")
+ with pdb.connect_closing() as conn:
+ pdb.record_discovered_repos(conn, [(seed, "seed-repo")])
+ seeded = [r["root"] for r in pdb.list_discovered_repos(conn)]
+ assert seed in seeded
+
+ good = _git_repo(tmp_path / "good-repo")
+
+ # Force one root to fail to walk: the scan becomes non-authoritative, so it
+ # must merge into the cache, never wipe it.
+ real_walk = os.walk
+ bad_root = str(tmp_path / "unwalkable")
+
+ def _flaky_walk(top, *a, **k):
+ if top == bad_root:
+ raise OSError("boom")
+ yield from real_walk(top, *a, **k)
+
+ monkeypatch.setattr(server.os, "walk", _flaky_walk)
+
+ policy = {"enabled": True, "roots": [good, bad_root], "exclude_paths": []}
+
+ with pdb.connect_closing() as conn:
+ authoritative = server._scan_discovered_repos_remote(conn, policy)
+ joined = [r["root"] for r in pdb.list_discovered_repos(conn)]
+
+ # The scan found the good repo and merged it, but the failed root means the
+ # result is not authoritative, so it must NOT have replaced the cache.
+ assert not authoritative
+ assert good in joined
+ # The seeded repo that the partial scan never saw is still cached.
+ assert seed in joined
+
+
+def test_remote_scan_missing_root_does_not_wipe_cache(tmp_path):
+ """A configured discovery root missing on disk must NOT wipe the cache.
+
+ ``os.walk`` on a non-existent root silently yields nothing instead of
+ raising, so a temporarily unavailable root (unmounted volume, moved path)
+ would otherwise make the scan look like a genuinely empty authoritative
+ set and DELETE-replace every cached repo that lived under it. The missing
+ root must contribute nothing, and the scan must merge — never wipe.
+ """
+ from hermes_cli import projects_db as pdb
+ import tui_gateway.server as server
+
+ def _git_repo(path):
+ repo = path
+ repo.mkdir(parents=True)
+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
+ return str(repo)
+
+ # A cached repo the scan never visits, parked OUTSIDE the scan roots.
+ seed = _git_repo(tmp_path / "elsewhere" / "seed-repo")
+ with pdb.connect_closing() as conn:
+ pdb.record_discovered_repos(conn, [(seed, "seed-repo")])
+ seeded = [r["root"] for r in pdb.list_discovered_repos(conn)]
+ assert seed in seeded
+
+ good = _git_repo(tmp_path / "good-repo")
+
+ # This root is configured but does NOT exist on disk. os.walk on it yields
+ # nothing silently — without the guard the scan would stay authoritative
+ # and wipe the cache.
+ missing_root = str(tmp_path / "missing-root")
+
+ policy = {"enabled": True, "roots": [good, missing_root], "exclude_paths": []}
+
+ with pdb.connect_closing() as conn:
+ authoritative = server._scan_discovered_repos_remote(conn, policy)
+ joined = [r["root"] for r in pdb.list_discovered_repos(conn)]
+
+ # The missing root is not authoritative, so the scan must merge, not wipe.
+ assert not authoritative
+ assert good in joined
+ # The seeded repo the missing root would have wiped is still cached.
+ assert seed in joined
+
+
+def test_remote_scan_full_authoritative_replaces_cache(tmp_path):
+ """Only a fully-walked scan may replace the stale cache."""
+ from hermes_cli import projects_db as pdb
+ import tui_gateway.server as server
+
+ def _git_repo(path):
+ repo = path
+ repo.mkdir(parents=True)
+ subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
+ return str(repo)
+
+ # Park the stale repo OUTSIDE the scan root so the authoritative scan no
+ # longer sees it, and the fresh repo inside the root it walks.
+ stale = _git_repo(tmp_path / "outside" / "stale-repo")
+ scandir = tmp_path / "scandir"
+ scandir.mkdir()
+ fresh = _git_repo(scandir / "fresh-repo")
+
+ with pdb.connect_closing() as conn:
+ pdb.record_discovered_repos(conn, [(stale, "stale-repo")])
+
+ policy = {"enabled": True, "roots": [str(scandir)], "exclude_paths": []}
+
+ with pdb.connect_closing() as conn:
+ authoritative = server._scan_discovered_repos_remote(conn, policy)
+ joined = [r["root"] for r in pdb.list_discovered_repos(conn)]
+
+ assert authoritative
+ assert fresh in joined
+ # A full, authoritative scan replaced the stale cache: the old repo the
+ # scan no longer saw is gone from the authoritative set.
+ assert stale not in joined
+
+
def test_terminal_session_persists_its_launch_cwd():
"""A terminal session's cwd IS its workspace, so the row must record it.
@@ -460,3 +596,229 @@ def test_nondefault_policy_rejects_stale_or_legacy_results(monkeypatch, tmp_path
assert any(item["root"] == str(root) for item in accepted["repos"])
+def _profile_dir(tmp_path: Path, name: str) -> Path:
+ home = tmp_path / "homes" / name
+ home.mkdir(parents=True, exist_ok=True)
+ return home
+
+
+def _bind_profiles(monkeypatch, tmp_path: Path, homes: dict[str, Path]) -> None:
+ """Resolve profile names to this test's throwaway homes.
+
+ Unmapped names resolve to a path that does not exist, which is how the
+ gateway detects "not a real profile on this host" and stays on launch.
+ """
+ monkeypatch.setattr(
+ "hermes_cli.profiles.get_profile_dir",
+ lambda name: homes.get(name, tmp_path / "homes" / "missing" / name),
+ )
+
+
+def _create_project(home: Path, name: str, folder: Path, *, use: bool = False) -> dict:
+ """Create a project in ``home``'s projects.db via the real RPC."""
+ token = set_hermes_home_override(home)
+ try:
+ return _call(
+ "projects.create", {"name": name, "folders": [str(folder)], "use": use}
+ )["project"]
+ finally:
+ reset_hermes_home_override(token)
+
+
+def _create_session(home: Path, session_id: str, cwd: Path) -> None:
+ """Seed one message-bearing session in ``home``'s state.db."""
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=home / "state.db")
+ try:
+ db.create_session(session_id, "cli", cwd=str(cwd))
+ db.append_message(session_id, "user", f"hello from {session_id}")
+ finally:
+ db.close()
+
+
+def _serving_launch_profile(launch_home: Path):
+ """Run the handlers as a backend launched under ``launch_home``."""
+ from hermes_state import SessionDB
+
+ token = set_hermes_home_override(launch_home)
+ prev_db, prev_error = server._db, server._db_error
+ server._db = SessionDB(db_path=launch_home / "state.db")
+ server._db_error = None
+ try:
+ yield
+ finally:
+ server._db.close()
+ server._db, server._db_error = prev_db, prev_error
+ reset_hermes_home_override(token)
+
+
+def _cached_repo_labels(home: Path) -> list[str]:
+ """Labels in ``home``'s discovered-repo cache, read straight off disk."""
+ from hermes_cli import projects_db as pdb
+
+ with pdb.connect_closing(home / "projects.db") as conn:
+ return sorted(str(entry.get("label") or "") for entry in pdb.list_discovered_repos(conn))
+
+
+def test_projects_reads_are_scoped_to_the_requested_profile(monkeypatch, tmp_path):
+ """A ``profile`` param reads that profile's projects.db AND its state.db."""
+ launch_home = _profile_dir(tmp_path, "launch")
+ coder_home = _profile_dir(tmp_path, "coder")
+ launch_repo = tmp_path / "repos" / "launch-repo"
+ coder_repo = tmp_path / "repos" / "coder-repo"
+ launch_repo.mkdir(parents=True)
+ coder_repo.mkdir(parents=True)
+ _bind_profiles(monkeypatch, tmp_path, {"default": launch_home, "coder": coder_home})
+
+ launch_project = _create_project(launch_home, "Launch", launch_repo, use=True)
+ coder_project = _create_project(coder_home, "Coder", coder_repo, use=True)
+ _create_session(launch_home, "launch-session", launch_repo)
+ _create_session(coder_home, "coder-session", coder_repo)
+
+ with _serving_launch_profile(launch_home):
+ launch_listing = _call("projects.list")
+ coder_listing = _call("projects.list", {"profile": "coder"})
+ launch_tree = _call("projects.tree")
+ coder_tree = _call("projects.tree", {"profile": "coder"})
+ coder_sessions = _call(
+ "projects.project_sessions",
+ {"profile": "coder", "project_id": coder_project["id"]},
+ )
+ # The override must not leak: the very next unscoped read is launch again.
+ launch_again = _call("projects.list")
+
+ assert [p["name"] for p in launch_listing["projects"]] == ["Launch"]
+ assert [p["name"] for p in coder_listing["projects"]] == ["Coder"]
+ assert launch_listing["active_id"] == launch_project["id"]
+ assert coder_listing["active_id"] == coder_project["id"]
+ assert launch_again == launch_listing
+
+ assert [p["label"] for p in launch_tree["projects"]] == ["Launch"]
+ assert [p["label"] for p in coder_tree["projects"]] == ["Coder"]
+ # Session counts prove the SESSION db was swapped too, not just projects.db.
+ assert launch_tree["projects"][0]["sessionCount"] == 1
+ assert coder_tree["projects"][0]["sessionCount"] == 1
+ assert launch_tree["scoped_session_ids"] == ["launch-session"]
+ assert coder_tree["scoped_session_ids"] == ["coder-session"]
+
+ assert coder_sessions["project"]["id"] == coder_project["id"]
+ assert coder_sessions["project"]["sessionCount"] == 1
+ lane = coder_sessions["project"]["repos"][0]["groups"][0]
+ assert [s["id"] for s in lane["sessions"]] == ["coder-session"]
+
+
+def test_projects_tree_is_scoped_to_the_requested_profile(monkeypatch, tmp_path):
+ """``projects.tree`` on its own reads the requested profile's stores."""
+ launch_home = _profile_dir(tmp_path, "launch")
+ coder_home = _profile_dir(tmp_path, "coder")
+ launch_repo = tmp_path / "repos" / "tree-launch"
+ coder_repo = tmp_path / "repos" / "tree-coder"
+ launch_repo.mkdir(parents=True)
+ coder_repo.mkdir(parents=True)
+ _bind_profiles(monkeypatch, tmp_path, {"default": launch_home, "coder": coder_home})
+
+ _create_project(launch_home, "Launch", launch_repo, use=True)
+ _create_project(coder_home, "Coder", coder_repo, use=True)
+ _create_session(launch_home, "tree-launch-session", launch_repo)
+ _create_session(coder_home, "tree-coder-session", coder_repo)
+
+ with _serving_launch_profile(launch_home):
+ coder_tree = _call("projects.tree", {"profile": "coder"})
+ launch_tree = _call("projects.tree")
+
+ assert [p["label"] for p in coder_tree["projects"]] == ["Coder"]
+ assert coder_tree["scoped_session_ids"] == ["tree-coder-session"]
+ assert [p["label"] for p in launch_tree["projects"]] == ["Launch"]
+ assert launch_tree["scoped_session_ids"] == ["tree-launch-session"]
+
+
+def test_project_sessions_is_scoped_to_the_requested_profile(monkeypatch, tmp_path):
+ """``projects.project_sessions`` on its own hydrates from the requested profile."""
+ launch_home = _profile_dir(tmp_path, "launch")
+ coder_home = _profile_dir(tmp_path, "coder")
+ launch_repo = tmp_path / "repos" / "drill-launch"
+ coder_repo = tmp_path / "repos" / "drill-coder"
+ launch_repo.mkdir(parents=True)
+ coder_repo.mkdir(parents=True)
+ _bind_profiles(monkeypatch, tmp_path, {"default": launch_home, "coder": coder_home})
+
+ launch_project = _create_project(launch_home, "Launch", launch_repo, use=True)
+ coder_project = _create_project(coder_home, "Coder", coder_repo, use=True)
+ _create_session(launch_home, "drill-launch-session", launch_repo)
+ _create_session(coder_home, "drill-coder-session", coder_repo)
+
+ with _serving_launch_profile(launch_home):
+ coder_drill = _call(
+ "projects.project_sessions",
+ {"profile": "coder", "project_id": coder_project["id"]},
+ )
+ launch_drill = _call(
+ "projects.project_sessions", {"project_id": launch_project["id"]}
+ )
+
+ assert coder_drill["project"] is not None
+ assert coder_drill["project"]["id"] == coder_project["id"]
+ coder_lane = coder_drill["project"]["repos"][0]["groups"][0]
+ assert [s["id"] for s in coder_lane["sessions"]] == ["drill-coder-session"]
+
+ assert launch_drill["project"]["id"] == launch_project["id"]
+ launch_lane = launch_drill["project"]["repos"][0]["groups"][0]
+ assert [s["id"] for s in launch_lane["sessions"]] == ["drill-launch-session"]
+
+
+def test_record_repos_writes_to_the_requested_profiles_projects_db(monkeypatch, tmp_path):
+ """The scan cache is per-profile: a scoped write must not land on launch."""
+ launch_home = _profile_dir(tmp_path, "launch")
+ coder_home = _profile_dir(tmp_path, "coder")
+ launch_repo = tmp_path / "repos" / "launch-scan"
+ coder_repo = tmp_path / "repos" / "coder-scan"
+ launch_repo.mkdir(parents=True)
+ coder_repo.mkdir(parents=True)
+ _bind_profiles(monkeypatch, tmp_path, {"default": launch_home, "coder": coder_home})
+
+ with _serving_launch_profile(launch_home):
+ _call("projects.record_repos", {"repos": [{"root": str(launch_repo), "label": "launch"}]})
+ _call(
+ "projects.record_repos",
+ {"profile": "coder", "repos": [{"root": str(coder_repo), "label": "coder"}]},
+ )
+
+ launch_repos = _call("projects.discover_repos")["repos"]
+ coder_repos = _call("projects.discover_repos", {"profile": "coder"})["repos"]
+
+ assert [repo["label"] for repo in launch_repos] == ["launch"]
+ assert [repo["label"] for repo in coder_repos] == ["coder"]
+ assert _cached_repo_labels(launch_home) == ["launch"]
+ assert _cached_repo_labels(coder_home) == ["coder"]
+
+
+def test_projects_without_a_profile_stay_on_the_launch_home(monkeypatch, tmp_path):
+ """Omitted/blank/unknown profile is a no-op — the pre-scoping behavior."""
+ launch_home = _profile_dir(tmp_path, "launch")
+ coder_home = _profile_dir(tmp_path, "coder")
+ repo = tmp_path / "repos" / "launch-only"
+ repo.mkdir(parents=True)
+ _bind_profiles(monkeypatch, tmp_path, {"default": launch_home, "coder": coder_home})
+
+ with _serving_launch_profile(launch_home):
+ created = _call(
+ "projects.create", {"name": "Launch only", "folders": [str(repo)], "use": True}
+ )["project"]
+ _call("projects.record_repos", {"repos": [{"root": str(repo), "label": "only"}]})
+
+ omitted = _call("projects.list")
+ blank = _call("projects.list", {"profile": ""})
+ unknown = _call("projects.list", {"profile": "not-a-profile"})
+
+ assert [p["name"] for p in omitted["projects"]] == ["Launch only"]
+ assert blank == omitted
+ assert unknown == omitted
+ assert omitted["active_id"] == created["id"]
+
+ assert _cached_repo_labels(launch_home) == ["only"]
+ assert not (coder_home / "projects.db").exists()
+ assert not (Path(os.environ["HERMES_HOME"]) / "projects.db").exists()
+
+
diff --git a/tui_gateway/methods_config.py b/tui_gateway/methods_config.py
index 53ccb5d91c0..314b38d904d 100644
--- a/tui_gateway/methods_config.py
+++ b/tui_gateway/methods_config.py
@@ -17,31 +17,40 @@ _profile_scoped = _registry.profile_scoped
@method("projects.discover_repos")
+@_profile_scoped
def _(rid, params: dict) -> dict:
"""Repos for the desktop overview: scanned-from-disk (cached) ∪ session-derived."""
try:
- db = _get_db()
- if db is None:
- return _ok(rid, {"repos": []})
- from hermes_cli import projects_db as pdb
-
- policy = _repo_discovery_policy()
- policy_key = _repo_discovery_policy_key(policy)
- with pdb.connect_closing() as conn:
- pdb.reconcile_discovered_repos_policy(
- conn,
- policy_key,
- preserve_unversioned=_repo_discovery_policy_is_default(policy),
- )
- repos = _discover_repos_payload(
- db, conn=conn, include_cached=policy["enabled"]
- )
- return _ok(rid, {"repos": repos, "discovery_policy": policy})
+ with _profile_db(params) as db:
+ if db is None:
+ return _ok(rid, {"repos": []})
+ from hermes_cli import projects_db as pdb
+
+ policy = _repo_discovery_policy()
+ policy_key = _repo_discovery_policy_key(policy)
+ with pdb.connect_closing() as conn:
+ pdb.reconcile_discovered_repos_policy(
+ conn,
+ policy_key,
+ preserve_unversioned=_repo_discovery_policy_is_default(policy),
+ )
+ # `scan=true` (set by the desktop in remote-gateway mode): run a
+ # backend-side filesystem scan of the policy roots so repos with
+ # zero Hermes sessions still surface. The desktop's native scan
+ # only runs on the local filesystem; on a remote connection it
+ # must ask the host to scan itself (#81723).
+ if params.get("scan") and policy["enabled"]:
+ _scan_discovered_repos_remote(conn, policy)
+ repos = _discover_repos_payload(
+ db, conn=conn, include_cached=policy["enabled"]
+ )
+ return _ok(rid, {"repos": repos, "discovery_policy": policy})
except Exception as e:
return _err(rid, 5061, str(e))
@method("projects.record_repos")
+@_profile_scoped
def _(rid, params: dict) -> dict:
"""Persist git repo roots found by the client's filesystem scan, then return
the merged repo list. The native crawl runs on the desktop (local fs); this
@@ -88,24 +97,25 @@ def _(rid, params: dict) -> dict:
elif not policy["enabled"]:
pdb.clear_discovered_repos(conn, policy_key=policy_key)
- db = _get_db()
- return _ok(
- rid,
- {
- "repos": _discover_repos_payload(
- db, include_cached=policy["enabled"]
- )
- if db is not None
- else [],
- "accepted": accepted,
- "discovery_policy": policy,
- },
- )
+ with _profile_db(params) as db:
+ return _ok(
+ rid,
+ {
+ "repos": _discover_repos_payload(
+ db, include_cached=policy["enabled"]
+ )
+ if db is not None
+ else [],
+ "accepted": accepted,
+ "discovery_policy": policy,
+ },
+ )
except Exception as e:
return _err(rid, 5061, str(e))
@method("projects.tree")
+@_profile_scoped
def _(rid, params: dict) -> dict:
"""Authoritative project overview: project -> repo -> lane structure with
counts + a few preview sessions per project, plus the flat set of session
@@ -113,26 +123,27 @@ def _(rid, params: dict) -> dict:
Lanes carry no session rows here; drill-in uses ``projects.project_sessions``.
"""
try:
- db = _get_db()
- if db is None:
- return _ok(rid, {"projects": [], "active_id": None, "scoped_session_ids": []})
-
- tree, active_id = _build_project_tree(
- db,
- preview_limit=int(params.get("preview_limit") or 3),
- hydrate=False,
- session_limit=int(params.get("session_limit") or 2000),
- include_discovered=True,
- )
- return _ok(
- rid,
- {"projects": tree["projects"], "active_id": active_id, "scoped_session_ids": tree["scoped_session_ids"]},
- )
+ with _profile_db(params) as db:
+ if db is None:
+ return _ok(rid, {"projects": [], "active_id": None, "scoped_session_ids": []})
+
+ tree, active_id = _build_project_tree(
+ db,
+ preview_limit=int(params.get("preview_limit") or 3),
+ hydrate=False,
+ session_limit=int(params.get("session_limit") or 2000),
+ include_discovered=True,
+ )
+ return _ok(
+ rid,
+ {"projects": tree["projects"], "active_id": active_id, "scoped_session_ids": tree["scoped_session_ids"]},
+ )
except Exception as e:
return _err(rid, 5061, str(e))
@method("projects.project_sessions")
+@_profile_scoped
def _(rid, params: dict) -> dict:
"""Fully hydrated lanes (repo -> lane -> session rows) for one project,
built from the same authoritative grouping as ``projects.tree`` so ids and
@@ -142,18 +153,18 @@ def _(rid, params: dict) -> dict:
if not project_id:
return _err(rid, 5063, "project_id required")
- db = _get_db()
- if db is None:
- return _ok(rid, {"project": None})
+ with _profile_db(params) as db:
+ if db is None:
+ return _ok(rid, {"project": None})
- # Drill-in only needs the entered project (which has sessions), so skip
- # the zero-session discovery tier entirely.
- tree, _active = _build_project_tree(
- db, preview_limit=0, hydrate=True, session_limit=int(params.get("session_limit") or 5000),
- include_discovered=False,
- )
- proj = next((p for p in tree["projects"] if p["id"] == project_id), None)
- return _ok(rid, {"project": proj})
+ # Drill-in only needs the entered project (which has sessions), so skip
+ # the zero-session discovery tier entirely.
+ tree, _active = _build_project_tree(
+ db, preview_limit=0, hydrate=True, session_limit=int(params.get("session_limit") or 5000),
+ include_discovered=False,
+ )
+ proj = next((p for p in tree["projects"] if p["id"] == project_id), None)
+ return _ok(rid, {"project": proj})
except Exception as e:
return _err(rid, 5061, str(e))
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 621032da671..6bb356201c8 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1534,13 +1534,12 @@ def _profile_home(profile: str | None) -> Path | None:
def _profile_scoped(handler):
- """Bind ``params['profile']``'s HERMES_HOME around a pet RPC handler.
+ """Bind ``params['profile']``'s HERMES_HOME around a handler.
- Pets are per-profile: ``display.pet.*`` lives in the profile's config.yaml and
- sprites install under its ``pets/`` dir (both resolve via ``get_hermes_home``).
- The desktop sends ``profile`` on pet calls so config + pets dir resolve to the
- focused profile even in app-global remote mode, where one backend serves every
- profile. No-op for the launch profile (own-profile backends already resolve it).
+ Pets (config + sprites) and projects (projects.db, discovery policy) both
+ resolve via ``get_hermes_home``. The desktop sends ``profile`` so a single
+ backend serving every profile in app-global remote mode still hits the
+ focused profile's home. No-op for the launch profile.
"""
def wrapper(rid, params):
@@ -12634,13 +12633,14 @@ def _projects_payload(conn) -> dict:
def _projects_method(name: str):
"""Register a projects RPC, injecting (pdb, conn) and unifying error mapping.
- Every project CRUD handler opened the per-profile DB, mapped a missing id to
- 5062, bad args to 5063, and everything else to 5061. This collapses that
- boilerplate so each handler is just its one meaningful operation.
+ Binds ``params['profile']`` (via ``@_profile_scoped``) so app-global remote
+ mode reads that profile's ``projects.db``. Missing id maps to 5062, bad args
+ to 5063, everything else to 5061.
"""
def decorator(fn):
@method(name)
+ @_profile_scoped
def handler(rid, params: dict) -> dict:
try:
from hermes_cli import projects_db as pdb
@@ -12879,6 +12879,89 @@ def _repo_discovery_policy_is_default(policy: dict) -> bool:
)
+def _scan_discovered_repos_remote(conn, policy: dict) -> bool:
+ """Backend-side disk scan of the discovery policy roots.
+
+ The desktop's native repo scan only runs on the local filesystem. On a
+ remote gateway connection the host must scan its own disk so repos with
+ zero Hermes sessions still appear in the sidebar (#81723). Mirrors the
+ desktop's behavior: walk each root (bounded depth), find `.git`
+ directories, record (root, label) pairs into the discovery cache.
+
+ Best-effort: any failure logs and leaves the cache untouched — the
+ session-derived repos from `_discover_repos_payload` still surface.
+
+ Returns True when the scan is authoritative (every root was walked to
+ completion without error and the per-scan cap was not hit). Only then may
+ the caller treat the result as a full replacement and pass ``replace=True``
+ to the cache write — a partial or errored scan must merge, never wipe, so
+ a failed remote refresh can't blank the previously cached repos into the
+ silent, unpopulated sidebar of #81723.
+ """
+ from hermes_cli import projects_db as pdb
+
+ roots = policy.get("roots") or []
+ excludes = policy.get("exclude_paths") or []
+ pairs: list[tuple[str, str | None]] = []
+ seen: set[str] = set()
+ authoritative = True
+
+ def _is_excluded(path: str) -> bool:
+ return any(path == ex or path.startswith(ex.rstrip("/\\") + os.sep) for ex in excludes if ex)
+
+ for root in roots:
+ if not os.path.isdir(root):
+ # `os.walk` on a missing root silently yields nothing instead of
+ # raising, so a temporarily unavailable root (unmounted volume,
+ # moved path) would otherwise look like a genuinely empty scan and
+ # let `authoritative` stay True — letting the replace wipe every
+ # cached repo that lived under the missing root. A missing root
+ # contributes nothing and must not be treated as authoritative.
+ authoritative = False
+ logger.debug("discover_repos scan root missing, skipping: %s", root)
+ continue
+ try:
+ for dirpath, dirnames, _filenames in os.walk(root):
+ if _is_excluded(dirpath):
+ dirnames[:] = []
+ continue
+ # A `.git` directory marks this directory as a repo root. Check
+ # BEFORE pruning hidden dirs — `.git` is itself hidden, so a
+ # prune-first order would drop it and never detect any repo.
+ if ".git" in dirnames:
+ repo_root = dirpath
+ if repo_root not in seen:
+ seen.add(repo_root)
+ pairs.append((repo_root, os.path.basename(repo_root)))
+ # Don't descend into the repo's own .git to hunt nested repos.
+ dirnames[:] = []
+ else:
+ # Not a repo: skip hidden dirs (e.g. .hermes) and node_modules.
+ dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in ("node_modules",)]
+ if len(pairs) >= 500:
+ break
+ except Exception:
+ # A root that can't be walked yields no authoritative set — fall back
+ # to merging, never replacing, so the prior cache survives.
+ authoritative = False
+ logger.debug("discover_repos scan failed for root %s", root, exc_info=True)
+ if len(pairs) >= 500:
+ # Cap hit means the walk didn't cover the full roots; the collected
+ # set must not be treated as the complete authoritative universe.
+ authoritative = False
+ break
+
+ if pairs:
+ try:
+ pdb.record_discovered_repos(
+ conn, pairs, replace=authoritative, policy_key=_repo_discovery_policy_key(policy)
+ )
+ except Exception:
+ logger.debug("discover_repos cache write failed", exc_info=True)
+ authoritative = False
+ return authoritative
+
+
def _discover_repos_payload(
db, *, conn=None, backfill: bool = True, include_cached: bool = True
) -> list[dict]: