Skip to content

The agent that grows with you

fix(profiles): a failed sidebar scan is a retryable load, not an empty list

brooklyn!f1b4172233cb
diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.ts
index e01f58fe2e7..95648be43eb 100644
--- a/apps/desktop/src/api/sessions.ts
+++ b/apps/desktop/src/api/sessions.ts
@@ -174,6 +174,12 @@ export interface SidebarSessionSlice {
/** Per-profile tokens and spend over every session, not just this window.
* Absent from the legacy per-slice endpoint, which has no aggregate. */
profiles_usage?: Record<string, { cost_usd: number; tokens: number }>
+ /** This slice is a failed load, not a successful empty session list. */
+ failed?: boolean
+ /** Ask the sidebar to offer Retry instead of rendering "No sessions yet". */
+ retry?: boolean
+ /** Profiles whose scan failed while a sibling profile still returned rows. */
+ profiles_failed?: Record<string, { failed?: boolean; retry?: boolean; error?: string }>
/** Profiles whose scan for THIS slice failed. Batched `/sidebar` stamps the
* same profile errors on every slice (one DB open). Legacy per-slice calls
* stamp only the slice that actually failed, so a cron I/O error cannot
@@ -204,6 +210,8 @@ export interface SidebarSessionsResponse {
cron: SidebarSessionSlice
messaging: SidebarSessionSlice
errors?: Array<{ profile: string; error: string }>
+ /** Profiles that failed while another profile's rows are still in the slices. */
+ profiles_failed?: Record<string, { failed?: boolean; retry?: boolean; error?: string }>
/** `{profile: 'corrupt'}` for each profile whose state.db the backend has found
* structurally damaged. Absent from older backends. */
storage?: Record<string, 'corrupt'>
@@ -355,6 +363,7 @@ export async function listSidebarSessions(req: SidebarSessionsRequest): Promise<
...(result.errors?.length ? { errors: result.errors } : {})
},
errors: result.errors,
+ profiles_failed: result.profiles_failed,
storage: result.storage
}
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx
index 6aa374a6b00..9ddf44cc248 100644
--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx
@@ -176,6 +176,23 @@ describe('refreshSessions cold-start load error', () => {
expect($sessionsLoadError.get()).toBe(true)
})
+ it('flags a failed load that carries retry and omits the session list', async () => {
+ listSidebarSessions.mockResolvedValueOnce({
+ cron: { errors: [{ error: 'schema heal exhausted', profile: 'default' }], failed: true, retry: true },
+ errors: [{ error: 'schema heal exhausted', profile: 'default' }],
+ messaging: { errors: [{ error: 'schema heal exhausted', profile: 'default' }], failed: true, retry: true },
+ recents: { errors: [{ error: 'schema heal exhausted', profile: 'default' }], failed: true, retry: true }
+ })
+ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
+
+ await act(async () => {
+ await result.current.refreshSessions()
+ })
+
+ expect($sessionsLoadError.get()).toBe(true)
+ expect($sessions.get()).toEqual([])
+ })
+
it('leaves a corrupt store to its own notice instead of offering retry', async () => {
listSidebarSessions.mockResolvedValueOnce(failedScan({ default: 'corrupt' }))
const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))
diff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
index f284f5350a4..8df4ff202eb 100644
--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts
@@ -339,11 +339,21 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg
if (owns()) {
const recents = result.recents
const recentsErrors = recents.errors ?? result.errors
+ const scopedRetry =
+ recents.retry === true ||
+ (sessionProfile !== 'all' && recents.profiles_failed?.[sessionProfile]?.retry === true) ||
+ result.profiles_failed?.[sessionProfile]?.retry === true
setCorruptSessionStores(result.storage)
// A damaged store already has its own notice; Retry can't repair it.
const retryableErrors = recentsErrors?.filter(e => !result.storage?.[e.profile])
- setSessionsLoadError(Boolean(showLoading && retryableErrors?.length && recents.sessions.length === 0))
+ setSessionsLoadError(
+ Boolean(
+ showLoading &&
+ (scopedRetry || retryableErrors?.length) &&
+ (recents.sessions?.length ?? 0) === 0
+ )
+ )
// Drop rows the user just deleted/archived: a refresh can race an
// in-flight mutation and the backend page still carries the doomed row.
diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py
index a2c3fd51760..0f6434dee33 100644
--- a/hermes_cli/web_routers/profiles.py
+++ b/hermes_cli/web_routers/profiles.py
@@ -50,9 +50,11 @@ from hermes_cli.web_server_profiles import _config_profile_scope, _hermes_home_s
# Same logger the handlers used before extraction (identical logger object).
_log = logging.getLogger("hermes_cli.web_server")
-# Per-profile session reads report failures only in the response's ``errors`` array, which
-# the desktop sidebar does not surface. Warn once per (profile, message) per process so a
-# persistent failure is loud in errors.log without turning every sidebar poll into spam.
+# A per-profile read failure is not an empty session list. The sidebar slice for
+# that profile is a failed load (``failed`` + ``retry``) so Desktop can offer Retry
+# instead of "No sessions yet". A successful read of zero rows still returns
+# ``sessions: []``. Warn once per (profile, message) per process so a persistent
+# failure is loud in errors.log without turning every sidebar poll into spam.
_profile_read_warned: set = set()
@@ -340,6 +342,44 @@ def _sidebar_profile_cache_clear():
_SIDEBAR_PROFILE_CACHE.clear()
+def _sidebar_profile_cache_drop(key) -> None:
+ with _SIDEBAR_PROFILE_CACHE_LOCK:
+ _SIDEBAR_PROFILE_CACHE.pop(key, None)
+
+
+def _profile_state_db(home) -> Path:
+ return Path(home) / "state.db"
+
+
+def _profile_heal_exhausted(home) -> bool:
+ """True when the one-shot writable heal already gave up on this store."""
+ from hermes_cli.web_server_sessions import _session_db_heal_exhausted
+
+ return str(_profile_state_db(home)) in _session_db_heal_exhausted
+
+
+def _slice_has_rows(slices: Dict[str, Any]) -> bool:
+ return any(slices.get(key) for key in ("recents", "cron", "messaging"))
+
+
+def _retryable_profile_errors(errors: List[Dict[str, str]], scanned) -> List[Dict[str, str]]:
+ """Scan failures Retry can re-attempt. A latched corrupt store has its own notice."""
+ corrupt = set(_corrupt_profile_stores(scanned))
+ return [dict(err) for err in errors if err.get("profile") not in corrupt]
+
+
+def _failed_load_slice(errors: List[Dict[str, str]], **extra) -> Dict[str, Any]:
+ """Failed load: no ``sessions`` key. An empty list would read as data loss."""
+ return {"failed": True, "retry": True, "errors": [dict(err) for err in errors], **extra}
+
+
+def _profiles_failed(errors: List[Dict[str, str]]) -> Dict[str, Dict[str, Any]]:
+ return {
+ err["profile"]: {"failed": True, "retry": True, "error": err.get("error", "")}
+ for err in errors if err.get("profile")
+ }
+
+
def _sidebar_singleflight_cache(func):
"""Coalesce concurrent sidebar scans and briefly reuse their response.
@@ -512,11 +552,12 @@ def get_profiles_sessions_sidebar(
return slices
scanned = []
+ contributed: set = set()
for name, home in targets:
if recents_scope != "all" and name != recents_scope:
continue
scanned.append((name, home))
- db_path = Path(home) / "state.db"
+ db_path = _profile_state_db(home)
if not db_path.exists():
continue
profile_cache_key = (str(db_path), _sidebar_db_fingerprint(db_path), cap["recents"],
@@ -528,6 +569,19 @@ def get_profiles_sessions_sidebar(
lambda db: _build_slices(db, profile_cache_key))
if slices is None:
continue
+ # Heal already gave up and this read found no rows. That is not "no
+ # sessions" — the probe-less open can miss the schema the list needs.
+ # Drop the cached empty page so the next poll does not reuse the lie.
+ if _profile_heal_exhausted(home) and not _slice_has_rows(slices):
+ _sidebar_profile_cache_drop(profile_cache_key)
+ if not any(err.get("profile") == name for err in errors):
+ errors.append({
+ "profile": name,
+ "error": "schema heal exhausted; session list unavailable",
+ })
+ continue
+ if _slice_has_rows(slices):
+ contributed.add(name)
# A full window means more rows remain on disk — all "load more" needs, at no cost
# beyond the rows already read. Pinned rows count: they occupy LIMIT slots, and a
# short list has nothing past the page for the pin back-fill to add, so pins cannot
@@ -543,12 +597,47 @@ def get_profiles_sessions_sidebar(
_strip_session_list_rows(win)
return win
- return {
+ storage = _corrupt_profile_stores(scanned)
+ retryable = _retryable_profile_errors(errors, scanned)
+ failed_names = {err["profile"] for err in retryable if err.get("profile")}
+ corrupt = set(storage)
+ live = [name for name, _home in scanned if name not in corrupt]
+ scoped_failed = (
+ recents_scope != "all"
+ and recents_scope in failed_names
+ and recents_scope not in contributed
+ )
+ all_failed = (
+ recents_scope == "all"
+ and bool(live)
+ and not contributed
+ and all(name in failed_names for name in live)
+ )
+ if scoped_failed or all_failed:
+ # The whole answer is this profile's (or every profile's) failed scan.
+ # Do not include ``sessions``: an empty list is a successful read.
+ return {
+ "recents": _failed_load_slice(
+ retryable, profiles_truncated={}, profiles_usage={}),
+ "cron": _failed_load_slice(retryable),
+ "messaging": _failed_load_slice(retryable, total=0),
+ "errors": errors, "storage": storage}
+
+ body = {
"recents": {"sessions": _window("recents"), "profiles_truncated": recents_truncated,
"profiles_usage": profile_totals},
"cron": {"sessions": _window("cron")},
"messaging": {"sessions": _window("messaging"), "total": len(rows["messaging"])},
- "errors": errors, "storage": _corrupt_profile_stores(scanned)}
+ "errors": errors, "storage": storage}
+ # A sibling profile still listed does not make the failed profile's absence
+ # a successful empty slice. Stamp that profile as a failed load with Retry.
+ failed = _profiles_failed(retryable)
+ if failed:
+ body["profiles_failed"] = failed
+ for key in ("recents", "cron", "messaging"):
+ body[key]["profiles_failed"] = failed
+ body[key]["errors"] = [dict(err) for err in retryable]
+ return body
def _merge_by_id(into: Dict[str, Dict[str, Any]], entries: List[Dict[str, Any]], child_key: str) -> None:
diff --git a/tests/hermes_cli/test_profiles_sidebar_failed_load.py b/tests/hermes_cli/test_profiles_sidebar_failed_load.py
new file mode 100644
index 00000000000..74c18d7b419
--- /dev/null
+++ b/tests/hermes_cli/test_profiles_sidebar_failed_load.py
@@ -0,0 +1,241 @@
+"""A failed profile scan must not look like an empty session list.
+
+A lagged store is healed once. When that read still fails, or the one-shot
+heal is already exhausted and the profile contributed no rows, the sidebar
+slice is a failed load with a retry signal. ``sessions: []`` is reserved for
+a successful read of zero rows. A structurally corrupt store keeps its own
+notice and is not offered Retry.
+"""
+
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+
[email protected](autouse=True)
+def _uncached_sidebar(monkeypatch):
+ from hermes_cli.web_routers import profiles as profiles_routes
+
+ monkeypatch.setattr(profiles_routes, "_SIDEBAR_CACHE_TTL_SECONDS", 0.0)
+ profiles_routes._sidebar_profile_cache_clear()
+ profiles_routes._profile_read_warned.clear()
+
+
[email protected](autouse=True)
+def _fresh_heal_latch(monkeypatch):
+ from hermes_cli import web_server_sessions as sessions_mod
+
+ monkeypatch.setattr(sessions_mod, "_session_db_heal_exhausted", set())
+ monkeypatch.setattr(sessions_mod, "_session_db_heal_warned", set())
+
+
+def profiles_on_disk(tmp_path, monkeypatch, _isolate_hermes_home):
+ from hermes_cli import profiles
+ from hermes_constants import get_hermes_home
+
+ default_home = get_hermes_home()
+ profiles_root = default_home / "profiles"
+ worker_home = profiles_root / "worker"
+ for home in (default_home, worker_home):
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
+ monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
+ return {"default": default_home, "worker": worker_home}
+
+
+def client(monkeypatch, profiles_on_disk):
+ try:
+ from starlette.testclient import TestClient
+ except ImportError:
+ pytest.skip("fastapi/starlette not installed")
+
+ import hermes_state
+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app
+ from hermes_constants import get_hermes_home
+
+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", get_hermes_home() / "state.db")
+ http = TestClient(app)
+ http.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
+ return http
+
+
+def _seed_session(home, session_id, *, source="cli"):
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=home / "state.db")
+ try:
+ db.create_session(session_id, source=source)
+ db.append_message(session_id=session_id, role="user", content="hi")
+ finally:
+ db.close()
+
+
+def _sidebar(client, profile):
+ return client.get(
+ "/api/profiles/sessions/sidebar",
+ params={"recents_profile": profile},
+ ).json()
+
+
+def _assert_failed_load(slice_, profile):
+ """A failed load is not an empty session list, and it asks for a retry."""
+ assert "sessions" not in slice_
+ assert slice_["failed"] is True
+ assert slice_["retry"] is True
+ assert [row["profile"] for row in slice_["errors"]] == [profile]
+
+
+class TestSidebarFailedLoad:
+ def test_read_error_is_a_failed_load_not_an_empty_list(
+ self, client, profiles_on_disk, monkeypatch
+ ):
+ _seed_session(profiles_on_disk["worker"], "worker-chat")
+ import hermes_state
+
+ def boom(self, *args, **kwargs):
+ raise sqlite3.OperationalError(
+ "no such column: s.compression_ineffective_count"
+ )
+
+ monkeypatch.setattr(hermes_state.SessionDB, "list_sessions_rich", boom)
+
+ payload = _sidebar(client, "worker")
+
+ assert payload["storage"] == {}
+ for key in ("recents", "cron", "messaging"):
+ _assert_failed_load(payload[key], "worker")
+ assert payload["errors"][0]["profile"] == "worker"
+
+ def test_heal_exhausted_empty_read_is_a_failed_load(
+ self, client, profiles_on_disk, monkeypatch
+ ):
+ home = profiles_on_disk["worker"]
+ _seed_session(home, "worker-chat")
+ from hermes_cli import web_server_sessions as sessions_mod
+
+ sessions_mod._session_db_heal_exhausted.add(str(home / "state.db"))
+ import hermes_state
+
+ monkeypatch.setattr(
+ hermes_state.SessionDB,
+ "list_sessions_rich",
+ lambda self, *args, **kwargs: [],
+ )
+
+ payload = _sidebar(client, "worker")
+
+ for key in ("recents", "cron", "messaging"):
+ _assert_failed_load(payload[key], "worker")
+ assert "heal exhausted" in payload["errors"][0]["error"]
+
+ def test_unfixable_schema_is_healed_once_then_a_failed_load(
+ self, client, profiles_on_disk, monkeypatch
+ ):
+ home = profiles_on_disk["worker"]
+ _seed_session(home, "worker-chat")
+ from hermes_cli import web_server_sessions as sessions_mod
+
+ monkeypatch.setattr(
+ sessions_mod,
+ "_session_db_read_probe_statements",
+ lambda: ('SELECT "sessions"."not_a_real_column" FROM "sessions" LIMIT 0',),
+ )
+ import hermes_state
+
+ writable_opens = []
+ real_init = hermes_state.SessionDB.__init__
+
+ def counting_init(self, *args, **kwargs):
+ if not kwargs.get("read_only", False):
+ writable_opens.append(1)
+ return real_init(self, *args, **kwargs)
+
+ monkeypatch.setattr(hermes_state.SessionDB, "__init__", counting_init)
+ real_list = hermes_state.SessionDB.list_sessions_rich
+
+ def list_then_miss(self, *args, **kwargs):
+ if str(getattr(self, "_db_path", home / "state.db")):
+ raise sqlite3.OperationalError("no such column: s.not_a_real_column")
+ return real_list(self, *args, **kwargs)
+
+ monkeypatch.setattr(hermes_state.SessionDB, "list_sessions_rich", list_then_miss)
+
+ first = _sidebar(client, "worker")
+ second = _sidebar(client, "worker")
+
+ assert len(writable_opens) == 1
+ assert str(home / "state.db") in sessions_mod._session_db_heal_exhausted
+ for payload in (first, second):
+ _assert_failed_load(payload["recents"], "worker")
+
+ def test_heal_exhausted_with_rows_still_returns_them(self, client, profiles_on_disk):
+ home = profiles_on_disk["worker"]
+ _seed_session(home, "worker-chat")
+ from hermes_cli import web_server_sessions as sessions_mod
+
+ sessions_mod._session_db_heal_exhausted.add(str(home / "state.db"))
+
+ payload = _sidebar(client, "worker")
+
+ assert payload["errors"] == []
+ assert payload["recents"].get("retry") is not True
+ assert [row["id"] for row in payload["recents"]["sessions"]] == ["worker-chat"]
+
+ def test_successful_heal_still_returns_rows(self, client, profiles_on_disk):
+ home = profiles_on_disk["worker"]
+ _seed_session(home, "worker-chat")
+ legacy = sqlite3.connect(str(home / "state.db"))
+ try:
+ legacy.execute("DROP INDEX IF EXISTS idx_sessions_effective_activity")
+ legacy.execute("ALTER TABLE sessions DROP COLUMN last_activity_at")
+ legacy.commit()
+ finally:
+ legacy.close()
+
+ payload = _sidebar(client, "worker")
+
+ assert payload["errors"] == []
+ assert payload["recents"].get("retry") is not True
+ assert [row["id"] for row in payload["recents"]["sessions"]] == ["worker-chat"]
+
+ def test_healthy_empty_store_stays_an_empty_list(self, client, profiles_on_disk):
+ from hermes_state import SessionDB
+
+ SessionDB(db_path=profiles_on_disk["worker"] / "state.db").close()
+
+ payload = _sidebar(client, "worker")
+
+ assert payload["errors"] == []
+ assert payload["recents"].get("retry") is not True
+ assert payload["recents"]["sessions"] == []
+
+ def test_mixed_scan_marks_only_the_failed_profile(
+ self, client, profiles_on_disk, monkeypatch
+ ):
+ _seed_session(profiles_on_disk["default"], "default-chat")
+ _seed_session(profiles_on_disk["worker"], "worker-chat")
+ import hermes_state
+
+ real_list = hermes_state.SessionDB.list_sessions_rich
+ worker_db = (profiles_on_disk["worker"] / "state.db").resolve()
+
+ def explode_worker(self, *args, **kwargs):
+ if Path(self.db_path).resolve() == worker_db:
+ raise sqlite3.OperationalError("database is locked")
+ return real_list(self, *args, **kwargs)
+
+ monkeypatch.setattr(hermes_state.SessionDB, "list_sessions_rich", explode_worker)
+
+ payload = _sidebar(client, "all")
+
+ assert [row["id"] for row in payload["recents"]["sessions"]] == ["default-chat"]
+ failed = payload["recents"]["profiles_failed"]["worker"]
+ assert failed["failed"] is True
+ assert failed["retry"] is True
+ assert "worker" not in {
+ row["profile"] for row in payload["recents"]["sessions"]
+ }