From 3d81650c2fea2a6e2cbc7ab6add324510bf9250b Mon Sep 17 00:00:00 2001 From: Brooklyn Nicholson Date: Tue, 1 Sep 2026 22:28:21 -0500 Subject: [PATCH] fix(desktop): a failed sidebar scan keeps the rows it could not re-read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sidebar reports a profile it could not scan as HTTP 200 with an empty page and errors=[{profile}]. The renderer merges that page keeping only working, pinned, and selected rows, so every idle Yesterday / This-week session disappears until a later scan succeeds — and the 5s coalescing cache then serves the same empty payload back for the rest of its TTL. Carry the previous rows forward for exactly the profiles named in errors[], keyed by profile::id so a twin id in another profile is never stitched in. Profiles that scanned cleanly are still authoritative, so a genuinely empty page with no errors still clears the list. Per-profile usage and truncation flags follow the same rule rather than zeroing under a list that was kept. The legacy per-slice fallback stamps errors on the slice that actually failed, so a cron read failure can no longer blank recents. Part of #73847 Part of #88528 Co-authored-by: AKAZIK-py --- apps/desktop/src/api/sessions.ts | 41 +++++++-- .../hooks/use-session-list-actions.test.tsx | 51 ++++++++++++ .../session/hooks/use-session-list-actions.ts | 50 +++++++++-- apps/desktop/src/hermes.test.ts | 37 +++++++++ apps/desktop/src/store/session.test.ts | 83 +++++++++++++++++++ apps/desktop/src/store/session.ts | 79 ++++++++++++++++++ hermes_cli/web_routers/profiles.py | 5 ++ .../hermes_cli/test_profiles_sidebar_cache.py | 24 ++++++ 8 files changed, 353 insertions(+), 17 deletions(-) diff --git a/apps/desktop/src/api/sessions.ts b/apps/desktop/src/api/sessions.ts index 8c2f358a5d..61368921bc 100644 --- a/apps/desktop/src/api/sessions.ts +++ b/apps/desktop/src/api/sessions.ts @@ -148,6 +148,11 @@ 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 + /** 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 + * carry-forward recents. */ + errors?: Array<{ profile: string; error: string }> } /** Which profiles filled their per-profile window in a returned page. The @@ -216,16 +221,24 @@ async function listSidebarSessionsLegacy(req: SidebarSessionsRequest): Promise { expect($sessions.get().map(s => s.id)).toEqual(['a']) }) + it('keeps idle recents when the sidebar returns an empty page plus profile errors', async () => { + // Backend contract on disk I/O / lock: HTTP 200, recents=[], errors=[{profile}]. + // mergeSessionPage only keeps working/pinned/selected, so Yesterday/This-week + // idle rows must be carried forward from the previous list — not clobbered. + const idle = [row('yesterday'), row('week')] + listSidebarSessions.mockResolvedValue(sidebar({ sessions: idle })) + + const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' })) + + await act(async () => { + await result.current.refreshSessions() + }) + + expect($sessions.get().map(s => s.id)).toEqual(['yesterday', 'week']) + + setSessionProfilesTruncated({ default: true }) + setSessionProfilesUsage({ default: { cost_usd: 3, tokens: 30 } }) + setMessagingTruncated(true) + + listSidebarSessions.mockResolvedValue({ + ...sidebar({ sessions: [] }), + errors: [{ error: 'disk I/O error', profile: 'default' }] + }) + + await act(async () => { + await result.current.refreshSessions() + }) + + expect($sessions.get().map(s => s.id)).toEqual(['yesterday', 'week']) + expect($sessionProfilesTruncated.get()).toEqual({ default: true }) + expect($sessionProfilesUsage.get()).toEqual({ default: { cost_usd: 3, tokens: 30 } }) + expect($messagingTruncated.get()).toBe(true) + }) + + it('still accepts a genuine empty recents page when the backend reported no errors', async () => { + listSidebarSessions.mockResolvedValue(sidebar({ sessions: [row('a')] })) + const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' })) + + await act(async () => { + await result.current.refreshSessions() + }) + + listSidebarSessions.mockResolvedValue(sidebar({ sessions: [] })) + + await act(async () => { + await result.current.refreshSessions() + }) + + expect($sessions.get()).toEqual([]) + }) + it('drops tombstoned rows from the messaging slice and per-platform paging too (#50928)', async () => { // The same delete race exists on every ingestion point: the batched // refresh's messaging slice and the per-platform "load more" pager must 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 255e85189b..9dcbf9740e 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 @@ -24,7 +24,9 @@ import { $messagingSessions, $selectedStoredSessionId, $sessions, + carryForwardFailedProfileSessions, CRON_SECTION_LIMIT, + keepFailedProfileMeta, mergeSessionPage, MESSAGING_SECTION_LIMIT, setCronSessions, @@ -198,7 +200,11 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg setMessagingSessions(prev => [ ...prev.filter(s => !inPlatform(s)), - ...mergeSessionPage(prev.filter(inPlatform), incoming, sessionsToKeep()) + ...mergeSessionPage( + prev.filter(inPlatform), + carryForwardFailedProfileSessions(prev.filter(inPlatform), incoming, result.errors), + sessionsToKeep() + ) ]) const total = result.total ?? incoming.length @@ -282,13 +288,19 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg // in-flight mutation and the backend page still carries the doomed row. // Honoring the optimistic tombstone keeps the removal from flashing back // (the tombstone self-clears once projects.tree confirms the delete). - const incoming = dropTombstoned(recents.sessions) - // Signature-gate the swap (same pattern as cron/messaging): a refresh // that returns content-identical rows must keep the previous array // identity, or every sidebar memo keyed on $sessions recomputes and the // whole list re-renders once per turn/broadcast for nothing. setSessions(prev => { + const incoming = dropTombstoned( + carryForwardFailedProfileSessions( + prev, + recents.sessions ?? [], + recents.errors ?? result.errors + ) + ) + const next = mergeSessionPage(prev, incoming, sessionsToKeep()) return sameCronSignature(prev, next) ? prev : next @@ -298,8 +310,9 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg // top of the rows it already read (the old exact totals ran a COUNT(*) // per profile DB on every refresh). Reference-stable when unchanged so // the sidebar's group memos don't recompute per refresh. + const recentsErrors = recents.errors ?? result.errors setSessionProfilesTruncated(prev => { - const next = recents.profiles_truncated ?? {} + const next = keepFailedProfileMeta(prev, recents.profiles_truncated ?? {}, recentsErrors) const prevKeys = Object.keys(prev) return prevKeys.length === Object.keys(next).length && prevKeys.every(key => prev[key] === next[key]) @@ -309,7 +322,7 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg // Same identity gate: these totals only move when a session bills, and // a fresh object every refresh would repaint every profile header. setSessionProfilesUsage(prev => { - const next = recents.profiles_usage ?? {} + const next = keepFailedProfileMeta(prev, recents.profiles_usage ?? {}, recentsErrors) const prevKeys = Object.keys(prev) return prevKeys.length === Object.keys(next).length && @@ -322,16 +335,35 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg // Cron section: latest N cron sessions (kept so a pinned cron run still // resolves via sessionByAnyId), signature-gated like above. - setCronSessions(prev => (sameCronSignature(prev, result.cron.sessions) ? prev : result.cron.sessions)) + setCronSessions(prev => { + const incoming = carryForwardFailedProfileSessions( + prev, + result.cron.sessions ?? [], + result.cron.errors ?? result.errors + ) + + return sameCronSignature(prev, incoming) ? prev : incoming + }) // Messaging sections: drop any non-messaging source the broad exclude // didn't catch (custom sources stay in local recents), then split per // platform in the UI. - const messagingRows = dropTombstoned(result.messaging.sessions.filter(s => isMessagingSource(s.source))) + const messagingErrors = result.messaging.errors ?? result.errors + setMessagingSessions(prev => { + const messagingRows = dropTombstoned( + carryForwardFailedProfileSessions( + prev, + (result.messaging.sessions ?? []).filter(s => isMessagingSource(s.source)), + messagingErrors + ) + ) - setMessagingSessions(prev => (sameCronSignature(prev, messagingRows) ? prev : messagingRows)) + return sameCronSignature(prev, messagingRows) ? prev : messagingRows + }) // Hit the cap → at least one platform may have more on disk than loaded. - setMessagingTruncated(result.messaging.sessions.length >= MESSAGING_SECTION_LIMIT) + setMessagingTruncated(prev => + messagingErrors?.length ? prev : result.messaging.sessions.length >= MESSAGING_SECTION_LIMIT + ) } } finally { // Request identity preserves the zero-argument refresh contract across a diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.ts index 00611c6f68..0876ca53b6 100644 --- a/apps/desktop/src/hermes.test.ts +++ b/apps/desktop/src/hermes.test.ts @@ -290,6 +290,43 @@ describe('Hermes REST helpers', () => { expect(paths).toContainEqual(expect.stringContaining('exclude_sources=cron%2Ctool')) }) + it('keeps per-slice errors on the legacy fallback so a cron failure does not taint recents', async () => { + resetSidebarBatchCapability() + const row = (id: string) => ({ id, title: id, profile: 'default' }) + + api.mockImplementation(({ path }: { path: string }) => { + if (path.startsWith('/api/profiles/sessions/sidebar')) { + return Promise.reject( + new Error('404: {"detail":"No such API endpoint: /api/profiles/sessions/sidebar"}') + ) + } + + if (path.includes('source=cron')) { + return Promise.resolve({ + ...emptySessionsResponse, + sessions: [], + errors: [{ profile: 'default', error: 'disk I/O error' }] + }) + } + + return Promise.resolve({ ...emptySessionsResponse, sessions: [row('recent-1')] }) + }) + + const result = await listSidebarSessions({ + recentsProfile: 'default', + recentsLimit: 20, + recentsExclude: [], + cronLimit: 50, + messagingLimit: 100, + messagingExclude: [] + }) + + expect(result.recents.sessions.map(s => s.id)).toEqual(['recent-1']) + expect(result.recents.errors).toBeUndefined() + expect(result.cron.errors).toEqual([{ profile: 'default', error: 'disk I/O error' }]) + expect(result.errors).toBeUndefined() + }) + it('remembers endpoint-missing and skips re-probing the batched route on later refreshes', async () => { api.mockImplementation(({ path }: { path: string }) => path.startsWith('/api/profiles/sessions/sidebar') diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.ts index 036a52aab7..983ba7135e 100644 --- a/apps/desktop/src/store/session.test.ts +++ b/apps/desktop/src/store/session.test.ts @@ -30,6 +30,7 @@ import { _resetLegacyDiscardForTests, _resetSessionOwnerHintsForTests, applyConfiguredDefaultProjectDir, + carryForwardFailedProfileSessions, commitWorkspaceCwdForSelectedSession, ensureDefaultWorkspaceCwd, forgetSessionOwnerHintsForConnection, @@ -41,6 +42,7 @@ import { getSessionOwnerHint, getSessionOwnerHints, hydrateSessionOwnerHints, + keepFailedProfileMeta, knownSessionOwner, knownSessionProfile, mergeSessionPage, @@ -673,6 +675,87 @@ describe('mergeSessionPage', () => { }) }) +describe('carryForwardFailedProfileSessions', () => { + it('is a no-op when the backend reported no profile errors', () => { + const previous = [session({ id: 'yesterday', profile: 'default' })] + const incoming = [session({ id: 'today', profile: 'default' })] + + expect(carryForwardFailedProfileSessions(previous, incoming, undefined)).toBe(incoming) + expect(carryForwardFailedProfileSessions(previous, incoming, [])).toBe(incoming) + }) + + it('re-attaches idle rows for a profile whose slice failed (empty 200 + errors)', () => { + // Repro: current session is running, sidebar scan hits disk I/O, backend + // returns recents=[] with errors=[{profile:default}]. mergeSessionPage then + // keeps only working/pinned/selected and Yesterday/This-week vanish. + const previous = [ + session({ id: 'running', last_active: 300, profile: 'default', title: 'Now' }), + session({ id: 'yesterday', last_active: 200, profile: 'default', title: 'Yesterday' }), + session({ id: 'week', last_active: 100, profile: 'default', title: 'This week' }) + ] + + const carried = carryForwardFailedProfileSessions(previous, [], [ + { profile: 'default', error: 'disk I/O error' } + ]) + + expect(carried.map(s => s.id)).toEqual(['running', 'yesterday', 'week']) + expect(carried[1]).toBe(previous[1]) + }) + + it('does not resurrect a successful profile’s omitted rows, and does not duplicate', () => { + const previous = [ + session({ id: 'work-old', profile: 'work' }), + session({ id: 'home-idle', profile: 'default' }), + session({ id: 'home-fresh', profile: 'default' }) + ] + + const incoming = [session({ id: 'home-fresh', message_count: 4, profile: 'default' })] + + const carried = carryForwardFailedProfileSessions(previous, incoming, [{ profile: 'work' }]) + + expect(carried.map(s => `${s.profile}:${s.id}`)).toEqual(['default:home-fresh', 'work:work-old']) + }) + + it('re-ranks carried rows by recency instead of parking them at the tail', () => { + const previous = [ + session({ id: 'idle-newer', last_active: 500, profile: 'work' }), + session({ id: 'idle-older', last_active: 50, profile: 'work' }) + ] + + const incoming = [session({ id: 'home', last_active: 100, profile: 'default' })] + + expect( + carryForwardFailedProfileSessions(previous, incoming, [{ profile: 'work' }]).map(s => s.id) + ).toEqual(['idle-newer', 'home', 'idle-older']) + }) + + it('treats a missing profile tag on the error as default', () => { + const previous = [session({ id: 'idle', profile: 'default' })] + + expect(carryForwardFailedProfileSessions(previous, [], [{ error: 'disk I/O error' }]).map(s => s.id)).toEqual([ + 'idle' + ]) + }) +}) + +describe('keepFailedProfileMeta', () => { + it('is a no-op when the backend reported no profile errors', () => { + const incoming = { default: { cost_usd: 1, tokens: 2 } } + + expect(keepFailedProfileMeta({ default: { cost_usd: 9, tokens: 9 } }, incoming, [])).toBe(incoming) + }) + + it('restores previous usage/truncated flags for profiles whose slice failed', () => { + const previous = { default: { cost_usd: 4, tokens: 40 }, work: { cost_usd: 1, tokens: 10 } } + const incoming = { work: { cost_usd: 2, tokens: 20 } } + + expect(keepFailedProfileMeta(previous, incoming, [{ profile: 'default' }])).toEqual({ + default: { cost_usd: 4, tokens: 40 }, + work: { cost_usd: 2, tokens: 20 } + }) + }) +}) + describe('touchSessionActivity', () => { afterEach(() => { setSessions([]) diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts index 023d8d2205..a90555bc24 100644 --- a/apps/desktop/src/store/session.ts +++ b/apps/desktop/src/store/session.ts @@ -629,6 +629,85 @@ export function mergeSessionPage( return interleaved } +function sidebarProfileKey(session: Pick): string { + return (session.profile ?? '').trim() || 'default' +} + +function sessionListIdentity(session: Pick): string { + return `${sidebarProfileKey(session)}::${session.id}` +} + +/** + * Re-attach previous rows for profiles whose sidebar slice failed this refresh. + * + * The batched sidebar endpoint reports a disk I/O / lock failure as HTTP 200 + * with `recents: []` and `errors: [{ profile }]`. `mergeSessionPage` only keeps + * working / pinned / selected ids, so idle Yesterday / This-week rows would + * otherwise vanish until a later successful scan (#73847, #88528). + * + * Successful profiles are left alone: their incoming page is still authoritative. + */ +export function carryForwardFailedProfileSessions( + previous: SessionInfo[], + incoming: SessionInfo[], + errors: Array<{ profile?: string; error?: string }> | undefined | null +): SessionInfo[] { + if (!errors?.length || previous.length === 0) { + return incoming + } + + const failed = new Set(errors.map(error => (error.profile ?? '').trim() || 'default')) + const incomingIds = new Set(incoming.map(sessionListIdentity)) + const carried: SessionInfo[] = [] + + for (const session of previous) { + if (!failed.has(sidebarProfileKey(session)) || incomingIds.has(sessionListIdentity(session))) { + continue + } + + carried.push(session) + } + + if (carried.length === 0) { + return incoming + } + + // Incoming-first concat parks the failed profile at the tail of an + // all-profiles list. Re-rank by the same recency key the backend uses. + const recency = (session: SessionInfo): number => Math.max(session.last_active || 0, session.started_at || 0) + + return [...incoming, ...carried].sort((a, b) => recency(b) - recency(a)) +} + +/** Keep previous per-profile sidebar meta for profiles whose slice failed. + * + * A failed scan returns `{}` / falsey truncated flags. Applying those + * would zero usage and hide Load more under a list we just carried forward. + */ +export function keepFailedProfileMeta( + previous: Record, + incoming: Record, + errors: Array<{ profile?: string; error?: string }> | undefined | null +): Record { + if (!errors?.length) { + return incoming + } + + const next = { ...incoming } + + for (const error of errors) { + const key = (error.profile ?? '').trim() || 'default' + + if (Object.prototype.hasOwnProperty.call(previous, key)) { + next[key] = previous[key] + } else { + delete next[key] + } + } + + return next +} + /** Raise a session in recents on user send (before stream / turn resolve). */ export function touchSessionActivity( sessionId: string | null | undefined, diff --git a/hermes_cli/web_routers/profiles.py b/hermes_cli/web_routers/profiles.py index 0e08d63142..d037d86d6e 100644 --- a/hermes_cli/web_routers/profiles.py +++ b/hermes_cli/web_routers/profiles.py @@ -197,6 +197,11 @@ 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. + if isinstance(result, dict) and result.get("errors"): + return result try: snapshot = copy.deepcopy(result) except Exception: diff --git a/tests/hermes_cli/test_profiles_sidebar_cache.py b/tests/hermes_cli/test_profiles_sidebar_cache.py index 5bb113a028..ead0c6b08b 100644 --- a/tests/hermes_cli/test_profiles_sidebar_cache.py +++ b/tests/hermes_cli/test_profiles_sidebar_cache.py @@ -128,6 +128,30 @@ class SidebarCacheTests(unittest.TestCase): self.assertEqual(scan(), {"ok": True}) self.assertEqual(calls, 2) + def test_does_not_cache_payloads_that_carry_profile_errors(self): + # A 200 with a non-empty errors[] is how a failed profile scan is + # reported. Caching it for the TTL keeps the empty recents page in + # front of a store that has already recovered. + calls = 0 + + @profiles._sidebar_singleflight_cache + def scan(): + nonlocal calls + calls += 1 + if calls == 1: + return { + "errors": [{"profile": "default", "error": "disk I/O error"}], + "recents": {"sessions": []}, + } + return {"errors": [], "recents": {"sessions": [{"id": "yesterday"}]}} + + first = scan() + second = scan() + + self.assertEqual(first["errors"][0]["error"], "disk I/O error") + self.assertEqual(second["recents"]["sessions"], [{"id": "yesterday"}]) + self.assertEqual(calls, 2) + def test_can_be_disabled(self): calls = 0