Skip to content

The agent that grows with you

fix(desktop): prune dead session references from renderer storage (#79001)

David Metcalfea2f020011155
diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsx
index f746ab7dca8..9b45f6d732d 100644
--- a/apps/desktop/src/app/contrib/controller.tsx
+++ b/apps/desktop/src/app/contrib/controller.tsx
@@ -59,6 +59,8 @@ import { TRANSCRIPT_DIRECTIVE_AREA, type TranscriptDirectiveContribution } from
import { setYoloEnabled } from '@/lib/yolo-session'
import { $connectionsRegistry } from '@/store/connection-registry-state'
import { $interfaceMode, $showsAdvancedChrome, setModeContext, toggleSimpleMode } from '@/store/interface-mode'
+import { pruneComposerPopoutZones } from '@/store/composer-popout'
+import { watchDeadSessionPrune } from '@/store/dead-session-prune'
import {
$fileBrowserOpen,
$sidebarOpen,
@@ -497,6 +499,10 @@ watchSessionPins()
// Release unread-write guards once a list page confirms the value we wrote.
watchUnreadWriteGuard()
+// Drop local pins/drafts/queued prompts whose sessions no longer exist on the
+// backend — otherwise every boot re-requests the dead ids and 404s on each.
+watchDeadSessionPrune()
+
// The main tab reads as its SESSION (the loaded title, "New session" on a
// fresh draft) — a stack of main + tiles is then just a row of session names.
// register() replaces same-id in place; the render fn is the shared constant
diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.ts
index 1a594cfd53b..6ba04bb9e74 100644
--- a/apps/desktop/src/store/composer.ts
+++ b/apps/desktop/src/store/composer.ts
@@ -512,6 +512,15 @@ export function takeSessionDraft(scope: string | null | undefined): SessionDraft
export const clearSessionDraft = (scope: string | null | undefined) => stashSessionDraft(scope, '', [])
+/**
+ * Stored draft scopes that hold content, excluding the new-chat key. The
+ * dead-session prune sweeps these to discard drafts whose sessions no longer
+ * exist on the backend; the new-chat draft is never a session reference.
+ */
+export function stashedDraftScopes(): string[] {
+ return [...draftsBySession.keys()].filter(key => key !== NEW_SESSION_DRAFT_KEY)
+}
+
/**
* Move a stashed composer draft from one session key onto another.
*
diff --git a/apps/desktop/src/store/dead-session-prune.test.ts b/apps/desktop/src/store/dead-session-prune.test.ts
new file mode 100644
index 00000000000..7f364b8babc
--- /dev/null
+++ b/apps/desktop/src/store/dead-session-prune.test.ts
@@ -0,0 +1,335 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import type * as HermesModule from '@/hermes'
+import type { ProfileInfo, SessionInfo } from '@/types/hermes'
+
+const getSessionMock = vi.fn<(id: string, profile?: null | string) => Promise<SessionInfo>>()
+
+vi.mock('@/hermes', async importOriginal => {
+ const actual = await importOriginal<typeof HermesModule>()
+
+ return {
+ ...actual,
+ getSession: (id: string, profile?: null | string) => getSessionMock(id, profile)
+ }
+})
+
+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
+import { $queuedPromptsBySession, enqueueQueuedPrompt, getQueuedPrompts } from '@/store/composer-queue'
+import { $pinnedSessionIds } from '@/store/layout'
+import { $activeGatewayProfile, $profiles } from '@/store/profile'
+import { $sessions } from '@/store/session'
+
+import { __runDeadSessionPrunePass, resetDeadSessionPrune, watchDeadSessionPrune } from './dead-session-prune'
+
+const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
+ ({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo
+
+const profile = (name: string): ProfileInfo =>
+ ({ has_env: false, is_default: name === 'default', model: null, name, path: name, provider: null, skill_count: 0 }) as ProfileInfo
+
+const notFound = () => new Error('404: {"detail":"Session not found"}')
+
+beforeAll(() => {
+ ;(globalThis as { window?: unknown }).window ??= {}
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = {}
+})
+
+beforeEach(() => {
+ window.localStorage.clear()
+ $sessions.set([])
+ $pinnedSessionIds.set([])
+ $queuedPromptsBySession.set({})
+ $profiles.set([profile('default'), profile('work')])
+ $activeGatewayProfile.set('default')
+ getSessionMock.mockReset()
+ resetDeadSessionPrune()
+})
+
+afterEach(() => {
+ clearSessionDraft('dead-draft-session')
+ clearSessionDraft('__new__')
+ $sessions.set([])
+ $pinnedSessionIds.set([])
+ $queuedPromptsBySession.set({})
+})
+
+describe('__runDeadSessionPrunePass', () => {
+ it('unpins a pin whose session 404s on every profile', async () => {
+ $sessions.set([row('unrelated')])
+ $pinnedSessionIds.set(['dead-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ // Active-scope probe first, then each other profile.
+ expect(getSessionMock).toHaveBeenCalledWith('dead-pin', undefined)
+ expect(getSessionMock).toHaveBeenCalledWith('dead-pin', 'work')
+ })
+
+ it('keeps a pin whose session lives on another profile, and caches it as alive', async () => {
+ $sessions.set([row('unrelated')])
+ $pinnedSessionIds.set(['other-pin'])
+ getSessionMock.mockImplementation(async (id, profileName) => {
+ if (profileName === 'work') {
+ return row(id, { profile: 'work' })
+ }
+
+ throw notFound()
+ })
+
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual(['other-pin'])
+
+ // Alive verdict is cached — a second pass must not re-probe.
+ getSessionMock.mockClear()
+ await __runDeadSessionPrunePass()
+ expect(getSessionMock).not.toHaveBeenCalled()
+ })
+
+ it('defers on non-404 probe failures instead of dropping, and retries later', async () => {
+ $sessions.set([row('unrelated')])
+ $pinnedSessionIds.set(['flaky-pin'])
+ getSessionMock.mockRejectedValue(new Error('gateway restarting'))
+
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual(['flaky-pin'])
+
+ // Not cached — the next pass probes again, and a definitive 404 prunes.
+ getSessionMock.mockRejectedValue(notFound())
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ })
+
+ it('discards drafts for dead sessions but never the new-chat draft', async () => {
+ $sessions.set([row('unrelated')])
+ stashSessionDraft('dead-draft-session', 'stale text', [])
+ stashSessionDraft('__new__', 'brand new', [])
+ getSessionMock.mockRejectedValue(notFound())
+
+ await __runDeadSessionPrunePass()
+
+ expect(takeSessionDraft('dead-draft-session').text).toBe('')
+ expect(takeSessionDraft('__new__').text).toBe('brand new')
+ })
+
+ it('drops queued prompts for dead sessions and keeps live ones', async () => {
+ $sessions.set([row('unrelated')])
+ enqueueQueuedPrompt('dead-queue-session', { text: 'go', attachments: [] })
+ enqueueQueuedPrompt('live-queue-session', { text: 'stay', attachments: [] })
+ getSessionMock.mockImplementation(async (id, profileName) => {
+ if (id === 'live-queue-session') {
+ return row(id, { profile: profileName ?? 'default' })
+ }
+
+ throw notFound()
+ })
+
+ await __runDeadSessionPrunePass()
+
+ expect(getQueuedPrompts('dead-queue-session')).toEqual([])
+ expect(getQueuedPrompts('live-queue-session')).toHaveLength(1)
+ })
+
+ it('skips ids already covered by loaded sidebar rows', async () => {
+ $sessions.set([row('covered', { _lineage_root_id: 'root-covered' })])
+ $pinnedSessionIds.set(['covered', 'root-covered', 'rowless-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+
+ await __runDeadSessionPrunePass()
+
+ expect(getSessionMock).not.toHaveBeenCalledWith('covered', expect.anything())
+ expect(getSessionMock).not.toHaveBeenCalledWith('root-covered', expect.anything())
+ expect(getSessionMock).toHaveBeenCalledWith('rowless-pin', undefined)
+ // Covered pins are alive (their rows exist) — only the rowless pin dies.
+ expect($pinnedSessionIds.get()).toEqual(['covered', 'root-covered'])
+ })
+
+ it('defers when the profile list is not loaded yet', async () => {
+ $sessions.set([row('unrelated')])
+ $profiles.set([])
+ $pinnedSessionIds.set(['mystery-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+
+ await __runDeadSessionPrunePass()
+
+ // Can't rule out another profile we don't know about — keep the pin.
+ expect($pinnedSessionIds.get()).toEqual(['mystery-pin'])
+ })
+
+ it('prunes on a genuinely empty backend (all sessions purged)', async () => {
+ // An empty list is a real answer here — the wipe path is handled by the
+ // gateway-switch reset cancelling the wipe-scheduled sweep, not by the
+ // sweep refusing to run. A backend with zero sessions has no rows to
+ // cover stored ids, so probes decide.
+ $sessions.set([])
+ $pinnedSessionIds.set(['orphan-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ expect(getSessionMock).toHaveBeenCalledWith('orphan-pin', undefined)
+ })
+
+ it('re-probes an alive id once its verdict TTL expires', async () => {
+ vi.useFakeTimers()
+
+ try {
+ $sessions.set([row('unrelated')])
+ $pinnedSessionIds.set(['ttl-pin'])
+ getSessionMock.mockImplementation(async (id, profileName) => {
+ if (profileName === 'work') {
+ return row(id, { profile: 'work' })
+ }
+
+ throw notFound()
+ })
+
+ // Alive on another profile — cached, not pruned, not re-probed.
+ await __runDeadSessionPrunePass()
+ expect($pinnedSessionIds.get()).toEqual(['ttl-pin'])
+ getSessionMock.mockClear()
+ await __runDeadSessionPrunePass()
+ expect(getSessionMock).not.toHaveBeenCalled()
+
+ // Session deleted mid-session; after the TTL the next pass re-probes
+ // and a definitive all-profile 404 prunes.
+ vi.setSystemTime(Date.now() + 10 * 60_000 + 1_000)
+ getSessionMock.mockRejectedValue(notFound())
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('discards in-flight verdicts when a gateway reset happens mid-sweep', async () => {
+ $sessions.set([row('unrelated')])
+ $pinnedSessionIds.set(['race-pin'])
+ let resolveProbe!: (value: SessionInfo) => void
+ getSessionMock.mockImplementation(() => new Promise(resolve => {
+ resolveProbe = resolve
+ }))
+
+ const pass = __runDeadSessionPrunePass()
+ // Gateway switch while the probe is in flight.
+ resetDeadSessionPrune()
+ resolveProbe(row('race-pin', { profile: 'default' }))
+ await pass
+
+ // The pre-reset verdict must not be applied: the pin survives, and the
+ // discarded 'alive' verdict must not poison the cache (next pass re-probes).
+ expect($pinnedSessionIds.get()).toEqual(['race-pin'])
+ getSessionMock.mockClear()
+ getSessionMock.mockRejectedValue(notFound())
+ $sessions.set([row('unrelated')])
+
+ await __runDeadSessionPrunePass()
+
+ expect(getSessionMock).toHaveBeenCalledWith('race-pin', undefined)
+ expect($pinnedSessionIds.get()).toEqual([])
+ })
+
+ it('resetDeadSessionPrune drops the alive cache so a switched gateway is re-probed', async () => {
+ $sessions.set([row('unrelated')])
+ $pinnedSessionIds.set(['switched-pin'])
+ getSessionMock.mockImplementation(async id => row(id, { profile: 'default' }))
+
+ await __runDeadSessionPrunePass()
+ expect($pinnedSessionIds.get()).toEqual(['switched-pin'])
+
+ // The gateway switched; the new backend no longer has the session. Without
+ // the reset the alive verdict would keep the dead pin forever.
+ resetDeadSessionPrune()
+ getSessionMock.mockRejectedValue(notFound())
+
+ await __runDeadSessionPrunePass()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ })
+})
+
+describe('watchDeadSessionPrune', () => {
+ it('sweeps once after the first list payload', async () => {
+ vi.useFakeTimers()
+ const unsubscribe = watchDeadSessionPrune()
+
+ try {
+ $pinnedSessionIds.set(['timed-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+
+ $sessions.set([row('boot-row')])
+
+ vi.advanceTimersByTime(2_000)
+ await vi.runOnlyPendingTimersAsync()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ } finally {
+ unsubscribe()
+ vi.useRealTimers()
+ }
+ })
+
+ it('clamps the debounce so list churn cannot starve the sweep', async () => {
+ vi.useFakeTimers()
+ const unsubscribe = watchDeadSessionPrune()
+
+ try {
+ $pinnedSessionIds.set(['churn-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+
+ // First payload schedules the pass at +2s; a change 1s later would
+ // naively re-schedule to +6s. The clamp keeps the earlier deadline —
+ // and must not stack a second timer for it.
+ $sessions.set([row('a')])
+ vi.advanceTimersByTime(1_000)
+ $sessions.set([row('a'), row('b')])
+ expect(vi.getTimerCount()).toBe(1)
+
+ vi.advanceTimersByTime(1_000)
+ await vi.runOnlyPendingTimersAsync()
+
+ expect($pinnedSessionIds.get()).toEqual([])
+ expect(vi.getTimerCount()).toBe(0)
+ } finally {
+ unsubscribe()
+ vi.useRealTimers()
+ }
+ })
+
+ it('re-opens a fresh debounce window after a sweep fires', async () => {
+ vi.useFakeTimers()
+ const unsubscribe = watchDeadSessionPrune()
+
+ try {
+ // First sweep fires at +2s and prunes the boot dead pin.
+ $pinnedSessionIds.set(['first-pin'])
+ getSessionMock.mockRejectedValue(notFound())
+ $sessions.set([row('a')])
+ vi.advanceTimersByTime(2_000)
+ await vi.runOnlyPendingTimersAsync()
+ expect($pinnedSessionIds.get()).toEqual([])
+
+ // A change right after the sweep must NOT fire an immediate pass — the
+ // next pass waits out a fresh RERUN_DELAY window.
+ $pinnedSessionIds.set(['second-pin'])
+ $sessions.set([row('a'), row('c')])
+
+ vi.advanceTimersByTime(1_000)
+ expect($pinnedSessionIds.get()).toEqual(['second-pin'])
+
+ vi.advanceTimersByTime(4_000)
+ await vi.runOnlyPendingTimersAsync()
+ expect($pinnedSessionIds.get()).toEqual([])
+ } finally {
+ unsubscribe()
+ vi.useRealTimers()
+ }
+ })
+})
diff --git a/apps/desktop/src/store/dead-session-prune.ts b/apps/desktop/src/store/dead-session-prune.ts
new file mode 100644
index 00000000000..463bf8be688
--- /dev/null
+++ b/apps/desktop/src/store/dead-session-prune.ts
@@ -0,0 +1,300 @@
+/**
+ * Prune renderer-stored session references whose sessions no longer exist on
+ * the backend.
+ *
+ * Pins (`hermes.desktop.pinnedSessions`), composer drafts
+ * (`hermes:composer-drafts:v3`) and queued prompts
+ * (`hermes.desktop.composerQueue.v1`) are keyed by session id and re-asserted
+ * or probed at boot. When a session is removed from state.db (retention purge,
+ * manual delete, another surface pruning it), those keys go stale: nothing
+ * ever drops them, so every boot re-requests the dead ids and the gateway
+ * answers `404 {"detail":"Session not found"}` once per stale reference,
+ * forever.
+ *
+ * This module sweeps for dead ids after the sidebar list has spoken. A session
+ * is declared dead ONLY when a by-id probe 404s on every known profile — a 404
+ * is profile-scoped ("not on this profile's state.db"), so a single miss never
+ * prunes anything (a session can legitimately live on a non-active profile).
+ * Any non-404 probe failure (gateway mid-restart, network) is inconclusive:
+ * the id is deferred to a later pass instead of being dropped.
+ */
+
+import { getSession } from '@/hermes'
+import { mapPool } from '@/lib/pool'
+import { clearSessionDraft, stashedDraftScopes } from '@/store/composer'
+import { $queuedPromptsBySession, clearQueuedPrompts } from '@/store/composer-queue'
+import { $pinnedSessionIds, unpinSession } from '@/store/layout'
+import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'
+import { $sessions } from '@/store/session'
+
+import { forgetPinSyncState } from './session-pin-sync'
+
+const SWEEP_CONCURRENCY = 4
+// After the first list payload, let boot settle (pin reconcile, resume probes)
+// before probing; later list changes re-sweep debounced.
+const FIRST_PASS_DELAY_MS = 2_000
+const RERUN_DELAY_MS = 5_000
+// How long an 'alive' verdict is trusted. Without expiry, a session deleted
+// mid-session would stay cached alive until the next app restart — re-creating
+// exactly the boot 404s this prune exists to remove. With expiry, a later
+// sweep re-probes and heals it within one TTL.
+const ALIVE_TTL_MS = 10 * 60_000
+
+// Ids verified ALIVE this app session, id -> verdict expiry timestamp — later
+// sweeps skip re-probing ids whose verdict is still fresh.
+const alive = new Map<string, number>()
+// Ids currently mid-probe, so overlapping sweeps don't double-probe.
+const inFlight = new Set<string>()
+
+let listLoaded = false
+// Bumped by resetDeadSessionPrune: in-flight probes from a pre-reset sweep
+// must not write verdicts (alive cache, drops) that belong to the OLD backend.
+let epoch = 0
+// Debounce deadline, clamped to the EARLIEST change since the last pass: a
+// busy list that keeps changing must not starve the sweep indefinitely.
+let sweepDueAt = 0
+let sweepTimer: ReturnType<typeof setTimeout> | undefined
+
+type Verdict = 'alive' | 'dead' | 'unknown'
+
+function isNotFoundError(error: unknown): boolean {
+ return /session not found/i.test(error instanceof Error ? error.message : String(error))
+}
+
+/**
+ * A stored id is dead only if a by-id lookup 404s on the active profile AND on
+ * every named profile. The active-scope probe covers single-profile installs;
+ * named-profile probes rule out sessions living on another profile.
+ *
+ * Completeness assumption: `$profiles` is the same profile list the UI uses to
+ * route and resolve sessions (resolveStoredSession, the picker). A session on
+ * a profile the app does not know about is unreachable in the UI — it cannot
+ * be opened, pinned, or drafted — so ids stored locally always reference a
+ * listed profile. When the list is EMPTY (not yet loaded) nothing is declared
+ * dead: another profile we can't rule out might own the id.
+ */
+async function sessionVerdict(id: string): Promise<Verdict> {
+ const activeKey = normalizeProfileKey($activeGatewayProfile.get())
+
+ // No known profiles → another profile we can't rule out might own the id.
+ // Skip the probe entirely; there is nothing to gain from a lone unscoped hit.
+ if ($profiles.get().length === 0) {
+ return 'unknown'
+ }
+
+ try {
+ await getSession(id)
+
+ return 'alive'
+ } catch (error) {
+ if (!isNotFoundError(error)) {
+ return 'unknown'
+ }
+ }
+
+ const knownProfiles = [...new Set($profiles.get().map(profile => normalizeProfileKey(profile.name)))]
+
+ // Without the profile list we can't rule out another profile — defer rather
+ // than risk pruning a session that lives elsewhere.
+ const otherProfiles = knownProfiles.filter(key => key !== activeKey)
+
+ if (knownProfiles.length === 0) {
+ return 'unknown'
+ }
+
+ for (const profile of otherProfiles) {
+ try {
+ await getSession(id, profile)
+
+ return 'alive'
+ } catch (error) {
+ if (!isNotFoundError(error)) {
+ return 'unknown'
+ }
+ }
+ }
+
+ return 'dead'
+}
+
+/** Stored ids no loaded sidebar row covers — the only ids that can be dead. */
+function collectCandidates(): string[] {
+ const rows = $sessions.get()
+ const covered = new Set<string>()
+
+ for (const row of rows) {
+ if (row.id) {
+ covered.add(row.id)
+ }
+
+ if (row._lineage_root_id) {
+ covered.add(row._lineage_root_id)
+ }
+ }
+
+ const candidates = new Set<string>()
+
+ for (const id of $pinnedSessionIds.get()) {
+ if (!covered.has(id)) {
+ candidates.add(id)
+ }
+ }
+
+ for (const scope of stashedDraftScopes()) {
+ if (!covered.has(scope)) {
+ candidates.add(scope)
+ }
+ }
+
+ for (const key of Object.keys($queuedPromptsBySession.get())) {
+ if (!covered.has(key)) {
+ candidates.add(key)
+ }
+ }
+
+ return [...candidates].filter(id => {
+ const expiresAt = alive.get(id)
+
+ return !(expiresAt !== undefined && Date.now() < expiresAt) && !inFlight.has(id)
+ })
+}
+
+function dropDeadId(id: string): void {
+ // Cheap re-verification before destructive drops: if a row for this id
+ // appeared while the probe was in flight (a session resurrected or a slow
+ // page landed), the id is no longer dead — keep every entry.
+ const covered = $sessions.get().some(row => row.id === id || row._lineage_root_id === id)
+
+ if (covered) {
+ return
+ }
+
+ // Forget the pin's sync bookkeeping BEFORE unpinning: the reconcile listener
+ // fires synchronously on unpin, and with the id still tracked it would
+ // re-PATCH the dead id (a fresh 404 on every boot — the noise we're removing).
+ if ($pinnedSessionIds.get().includes(id)) {
+ forgetPinSyncState(id)
+ unpinSession(id)
+ }
+
+ // No-ops for surfaces that don't hold the id — the guards also skip the
+ // localStorage write a no-op clear would still perform.
+ if (stashedDraftScopes().includes(id)) {
+ clearSessionDraft(id)
+ }
+
+ if ($queuedPromptsBySession.get()[id]?.length) {
+ clearQueuedPrompts(id)
+ }
+}
+
+async function sweepOnce(requireLoaded = true): Promise<void> {
+ if (requireLoaded && !listLoaded) {
+ return
+ }
+
+ if (typeof window === 'undefined' || !window.hermesDesktop) {
+ return
+ }
+
+ const sweepEpoch = epoch
+ const candidates = collectCandidates()
+
+ if (candidates.length === 0) {
+ return
+ }
+
+ for (const id of candidates) {
+ inFlight.add(id)
+ }
+
+ try {
+ await mapPool(candidates, SWEEP_CONCURRENCY, async id => {
+ if (epoch !== sweepEpoch) {
+ return
+ }
+
+ const verdict = await sessionVerdict(id)
+
+ // A gateway switch (reset) while this probe was in flight invalidates
+ // the verdict — it is about the backend we measured, not the live one.
+ if (epoch !== sweepEpoch) {
+ return
+ }
+
+ if (verdict === 'alive') {
+ alive.set(id, Date.now() + ALIVE_TTL_MS)
+ } else if (verdict === 'dead') {
+ dropDeadId(id)
+ }
+ // 'unknown' — neither cached nor dropped; a later sweep retries it.
+ })
+ } finally {
+ for (const id of candidates) {
+ inFlight.delete(id)
+ }
+ }
+}
+
+/** Run one prune pass now. Test-only hook — production never calls it. */
+export function __runDeadSessionPrunePass(): Promise<void> {
+ // Bypass the list-loaded gate WITHOUT mutating `listLoaded` (a mutation
+ // here would leak into the watcher's first-payload timing).
+ return sweepOnce(false)
+}
+
+/**
+ * Sweep after the first sidebar payload, then re-sweep (debounced) whenever
+ * the list changes — a purge while the app is running heals within one pass.
+ * Call once per app, next to `watchSessionPins`. Returns the store unsubscribe
+ * (used by tests).
+ */
+export function watchDeadSessionPrune(): () => void {
+ return $sessions.listen(() => {
+ const firstPayload = !listLoaded
+ listLoaded = true
+
+ const delay = firstPayload ? FIRST_PASS_DELAY_MS : RERUN_DELAY_MS
+
+ // Clamp to the EARLIEST change since the last pass: constant list churn
+ // must delay the sweep, not starve it.
+ const dueAt = Date.now() + delay
+ const nextDueAt = sweepTimer ? Math.min(sweepDueAt, dueAt) : dueAt
+
+ if (sweepTimer && nextDueAt !== sweepDueAt) {
+ clearTimeout(sweepTimer)
+ sweepTimer = undefined
+ }
+
+ sweepDueAt = nextDueAt
+
+ // Exactly one timer at a time: a churn that doesn't move the deadline
+ // keeps the existing timer instead of stacking a second one.
+ if (!sweepTimer) {
+ sweepTimer = setTimeout(() => {
+ sweepDueAt = 0
+ sweepTimer = undefined
+ void sweepOnce()
+ }, Math.max(0, nextDueAt - Date.now()))
+ }
+ })
+}
+
+/**
+ * Forget probe results, because the backend they were measured against is
+ * gone. `alive` means "alive on the gateway we probed"; a switched gateway has
+ * its own state.db and must be re-probed from scratch.
+ */
+export function resetDeadSessionPrune(): void {
+ epoch += 1
+ alive.clear()
+ inFlight.clear()
+ listLoaded = false
+
+ if (sweepTimer) {
+ clearTimeout(sweepTimer)
+ sweepTimer = undefined
+ }
+
+ sweepDueAt = 0
+}
diff --git a/apps/desktop/src/store/gateway-switch.ts b/apps/desktop/src/store/gateway-switch.ts
index bbb0f938a9f..be6a0d6ab8c 100644
--- a/apps/desktop/src/store/gateway-switch.ts
+++ b/apps/desktop/src/store/gateway-switch.ts
@@ -5,6 +5,7 @@ import { resetSidebarBatchCapability } from '@/hermes'
import { invalidateProfileScopedQueries } from '@/lib/query-client'
import { clearArtifactRegistry } from '@/store/artifacts'
import { invalidateCronJobsRequests, setCronJobs } from '@/store/cron'
+import { resetDeadSessionPrune } from '@/store/dead-session-prune'
import { resetSessionsLimit } from '@/store/layout'
import { resetLiveSync } from '@/store/live-sync'
import { invalidateProfileListFetches } from '@/store/profile'
@@ -201,6 +202,12 @@ export function wipeSessionListsForGatewaySwitch(): void {
// entered would root the next draft's cwd in the old source's project.
exitProjectScope()
setSessions([])
+ // Reset AFTER the wipe: the wipe's empty payload schedules a sweep, and
+ // resetting first would leave that timer live — sweeping every stored id
+ // against a backend that hasn't answered yet. The reset cancels the timer,
+ // clears the alive cache, and marks the list unloaded, so the next real
+ // payload starts a fresh first-pass window against the new backend.
+ resetDeadSessionPrune()
setSessionProfilesTruncated({})
setSessionProfilesUsage({})
setCronSessions([])
diff --git a/apps/desktop/src/store/session-pin-sync.test.ts b/apps/desktop/src/store/session-pin-sync.test.ts
index 9abfad3c915..28314f1308b 100644
--- a/apps/desktop/src/store/session-pin-sync.test.ts
+++ b/apps/desktop/src/store/session-pin-sync.test.ts
@@ -17,7 +17,7 @@ import { $pinnedSessionIds } from '@/store/layout'
import { $activeGatewayProfile } from '@/store/profile'
import { $cronSessions, $messagingSessions, $sessions } from '@/store/session'
-import { $unconfirmedPinWrites, resetSessionPinMirror, watchSessionPins } from './session-pin-sync'
+import { $unconfirmedPinWrites, forgetPinSyncState, resetSessionPinMirror, watchSessionPins } from './session-pin-sync'
const row = (id: string, extra: Partial<SessionInfo> = {}): SessionInfo =>
({ id, message_count: 1, source: 'cli', started_at: 0, title: id, ...extra }) as SessionInfo
@@ -104,6 +104,21 @@ describe('watchSessionPins', () => {
expect(patch).not.toHaveBeenCalled()
})
+
+ it('forgetPinSyncState suppresses the re-PATCH of a rowless pin being pruned', async () => {
+ // The dead-session prune unpins a rowless (dead) pin; without forgetting
+ // its pending bookkeeping first, the reconcile would re-PATCH the dead id
+ // (a fresh 404 on every boot — the noise the prune exists to remove).
+ $pinnedSessionIds.set(['c'])
+ await flush()
+ expect(patch).not.toHaveBeenCalled()
+
+ forgetPinSyncState('c')
+ $pinnedSessionIds.set([])
+ await flush()
+
+ expect(patch).not.toHaveBeenCalled()
+ })
})
describe('watchSessionPins remote pull', () => {
diff --git a/apps/desktop/src/store/session-pin-sync.ts b/apps/desktop/src/store/session-pin-sync.ts
index 5ca8c694b5e..b0920b57ca0 100644
--- a/apps/desktop/src/store/session-pin-sync.ts
+++ b/apps/desktop/src/store/session-pin-sync.ts
@@ -314,3 +314,15 @@ export function resetSessionPinMirror(): void {
unconfirmed.clear()
publishUnconfirmed()
}
+
+/**
+ * Forget one id's sync bookkeeping. The dead-session prune calls this before
+ * unpinning a pin whose session is gone, so the reconcile listener (fired
+ * synchronously by `unpinSession`) doesn't re-PATCH the dead id — which would
+ * produce exactly the 404 the prune exists to remove.
+ */
+export function forgetPinSyncState(id: string): void {
+ mirrored.delete(id)
+ pending.delete(id)
+ unconfirmed.delete(id)
+}