Skip to content

The agent that grows with you

fix(desktop): refuse every resume for a chat the user is deleting

Brooklyn Nicholson195c3e5a3bbf
diff --git a/apps/desktop/src/app/chat/session-tile.test.ts b/apps/desktop/src/app/chat/session-tile.test.ts
index 46bd2f40434..70f3bdea854 100644
--- a/apps/desktop/src/app/chat/session-tile.test.ts
+++ b/apps/desktop/src/app/chat/session-tile.test.ts
@@ -3,7 +3,35 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { $gatewayState, $sessions, setSessions } from '@/store/session'
import { $sessionTiles } from '@/store/session-states'
-import { sessionTileResumeFailure, startUnrestoredTileTitleBackfill } from './session-tile'
+import { sessionTileResumeFailure, shouldResumeSessionTile, startUnrestoredTileTitleBackfill } from './session-tile'
+
+describe('shouldResumeSessionTile', () => {
+ const live = {
+ gatewayOpen: true,
+ removalPending: false,
+ resuming: false,
+ runtimeId: null,
+ tileError: undefined
+ }
+
+ it('resumes an unbound tile once the gateway is open', () => {
+ expect(shouldResumeSessionTile(live)).toBe(true)
+ })
+
+ it('does not resume a session the user is deleting', () => {
+ // A 4001 racing the delete unbinds the tile runtime, re-arming the resume
+ // effect against an id that is already gone: the resume 404s and latches an
+ // error card for a chat that is on its way out.
+ expect(shouldResumeSessionTile({ ...live, removalPending: true })).toBe(false)
+ })
+
+ it('waits for the gateway, a free slot, and an unbound, unlatched tile', () => {
+ expect(shouldResumeSessionTile({ ...live, gatewayOpen: false })).toBe(false)
+ expect(shouldResumeSessionTile({ ...live, runtimeId: 'rt-1' })).toBe(false)
+ expect(shouldResumeSessionTile({ ...live, tileError: 'boom' })).toBe(false)
+ expect(shouldResumeSessionTile({ ...live, resuming: true })).toBe(false)
+ })
+})
describe('sessionTileResumeFailure', () => {
it('keeps a confirmed durable session retryable instead of repeating a stale 404', () => {
diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsx
index 30291a5ecee..5a472405f1c 100644
--- a/apps/desktop/src/app/chat/session-tile.tsx
+++ b/apps/desktop/src/app/chat/session-tile.tsx
@@ -50,6 +50,7 @@ import {
sessionMatchesStoredId,
sessionPinId
} from '@/store/session'
+import { isSessionRemovalPending } from '@/store/session-removal'
import { requestForSessionProfile } from '@/store/session-request-router'
import {
$sessionStates,
@@ -99,6 +100,28 @@ export function sessionTileResumeFailure(
return 'Session unavailable — you can retry resuming it.'
}
+/** Should this tile dispatch a `session.resume`?
+ *
+ * - The gateway must be OPEN: persisted tiles mount at boot while it is still
+ * connecting, and an ungated resume rejected there latched every restored
+ * tile into the error card.
+ * - A bound runtime, a latched error, or an in-flight attempt means there is
+ * nothing to do.
+ * - A removal-pending session is skipped for the same reason the primary's
+ * `resumeSession` skips it: a 4001 racing a delete unbinds this tile's
+ * runtime and re-arms the effect against an id that is already gone. The
+ * resume would 404 and latch an error card for a chat the user deleted;
+ * `closeSessionTile` lands moments later. */
+export function shouldResumeSessionTile(opts: {
+ gatewayOpen: boolean
+ removalPending: boolean
+ resuming: boolean
+ runtimeId: null | string | undefined
+ tileError: string | undefined
+}): boolean {
+ return !opts.removalPending && opts.gatewayOpen && !opts.runtimeId && !opts.tileError && !opts.resuming
+}
+
/** The tile's SessionView: the same atom shape the primary chat renders
* from, computed from this session's slice of `$sessionStates`. */
function buildTileView(storedSessionId: string): SessionView {
@@ -371,13 +394,18 @@ export function SessionTilePane({ storedSessionId }: { storedSessionId: string }
}
}, [hasMessages, ownerRoute, runtimeId, storedSessionId, storedSessionStillExists])
- // Same gating as the primary's route resume (use-route-resume): never fire
- // session.resume before the gateway is OPEN. Persisted tiles mount at boot
- // while it's still connecting — an ungated resume rejected there and
- // latched every restored tile into the error card.
+ // Gating lives in shouldResumeSessionTile (unit-tested there).
// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
useEffect(() => {
- if (!gatewayOpen || runtimeId || tile?.error || resumingRef.current) {
+ if (
+ !shouldResumeSessionTile({
+ gatewayOpen,
+ removalPending: isSessionRemovalPending(storedSessionId),
+ resuming: resumingRef.current,
+ runtimeId,
+ tileError: tile?.error
+ })
+ ) {
return
}
diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts
index 0c1645ccbc1..cee4203f447 100644
--- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts
+++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts
@@ -38,7 +38,7 @@ vi.mock('@/store/session', async importActual => ({
const { createSessionRpcDispatcher } = await import('./session-rpc-dispatcher')
const { $connectionsRegistry } = await import('@/store/connection-registry-state')
const { $profiles } = await import('@/store/profile')
-const { $removedSessionIds, $sessionMutationsInFlight } = await import('@/store/projects')
+const { $removedSessionIds, $sessionMutationsInFlight } = await import('@/store/session-removal')
const { _resetSessionOwnerHintsForTests, setCronSessions, setMessagingSessions, setSessionOwnerHint, setSessions } =
await import('@/store/session')
@@ -239,7 +239,10 @@ describe('createSessionRpcDispatcher: stale runtime recovery', () => {
it.each([
['tombstoned', $removedSessionIds],
['being deleted', $sessionMutationsInFlight]
- ])('does not rebind a selected session that is %s', async (_state, sessions) => {
+ ])('still reports the 4001 for a selected session that is %s', async (_state, sessions) => {
+ // The rebind decision moved to requestSessionResume (store/session-removal),
+ // which drops resume requests for a removal-pending id — this seam only has
+ // to keep surfacing the error to its caller.
setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-omar', profile: 'omar' })])
sessions.set(new Set(['stored-omar']))
gatewayMocks.requestGatewayForAgent.mockRejectedValueOnce(
@@ -248,8 +251,6 @@ describe('createSessionRpcDispatcher: stale runtime recovery', () => {
const { request } = dispatcher(undefined, 'stored-omar')
await expect(request('process.list', { session_id: 'rt-omar' })).rejects.toThrow('session not found')
-
- expect(sessionMocks.requestSessionResume).not.toHaveBeenCalled()
})
it('does not interpret an unrelated coded RPC failure as a stale runtime', async () => {
diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts
index 71f4d6e7a77..d57bcbb115b 100644
--- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts
+++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts
@@ -35,7 +35,6 @@ import type { MutableRefObject } from 'react'
import { resolveSessionOwner } from '@/app/session/hooks/use-session-actions/utils'
import type { ClientSessionState } from '@/app/types'
-import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/projects'
import { isSessionGoneForBackgroundPolling } from '@/store/runtime-gone'
import { getSessionOwnerHint, knownSessionOwner, ownerLookupSessionRows, requestSessionResume } from '@/store/session'
import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
@@ -107,14 +106,14 @@ export function createSessionRpcDispatcher(deps: SessionRpcDispatcherDeps): Ambi
// calls; this seam covers the other session-scoped callers and wakes
// route-resume for the visible main session only. Do not retry the
// failing RPC — it may be destructive, and a fresh binding is async.
+ // A session the user just deleted is filtered by requestSessionResume,
+ // which drops resume requests for a removal-pending id.
if (
method !== 'session.resume' &&
method !== 'session.activate' &&
paramSessionId &&
routingSessionId &&
routingSessionId === selectedStoredSessionIdRef.current &&
- !$removedSessionIds.get().has(routingSessionId) &&
- !$sessionMutationsInFlight.get().has(routingSessionId) &&
isSessionGoneForBackgroundPolling(error)
) {
requestSessionResume(routingSessionId, typeof owner === 'object' && owner ? owner : undefined)
diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx b/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx
index 47abc5c1fa4..fae23a9800a 100644
--- a/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-route-resume.test.tsx
@@ -101,58 +101,43 @@ describe('useRouteResume', () => {
expect(resumeSession).not.toHaveBeenCalled()
})
- it('does not honor a leftover 4001 rebind during a /:sid -> /new delete transition', () => {
+ it('honors an explicit resume request on /:sid even while a fresh draft is staged', () => {
+ // A gateway/profile switch stages a fresh draft (wipeSessionListsForGatewaySwitch)
+ // but deliberately leaves the URL on /:sid. In that state pathnameChanged,
+ // gatewayBecameOpen and stuckOnRoutedSession are all false, so an explicit
+ // request (plugin/SDK reselect, 4001 recovery) is the ONLY lever left — it
+ // must still fire. Filtering doomed ids happens at requestSessionResume and
+ // resumeSession, not by guessing from freshDraftReady.
const resumeSession = vi.fn(async () => undefined)
const startFreshSessionDraft = vi.fn()
- const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-1' }
+ const activeSessionIdRef: MutableRefObject<null | string> = { current: null }
const creatingSessionRef = { current: false }
- const runtimeIdByStoredSessionIdRef = { current: new Map([['session-1', 'runtime-1']]) }
- const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-1' }
+ const runtimeIdByStoredSessionIdRef = { current: new Map<string, string>() }
+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: null }
- const { rerender } = render(
- <RouteResumeHarness
- activeSessionId="runtime-1"
- activeSessionIdRef={activeSessionIdRef}
- creatingSessionRef={creatingSessionRef}
- currentView="chat"
- freshDraftReady={false}
- gatewayState="open"
- locationPathname="/session-1"
- resumeSession={resumeSession}
- routedSessionId="session-1"
- runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}
- selectedStoredSessionId="session-1"
- selectedStoredSessionIdRef={selectedStoredSessionIdRef}
- startFreshSessionDraft={startFreshSessionDraft}
- />
- )
+ const props = {
+ activeSessionId: null,
+ activeSessionIdRef,
+ creatingSessionRef,
+ currentView: 'chat',
+ freshDraftReady: true,
+ gatewayState: 'open',
+ locationPathname: '/session-1',
+ resumeSession,
+ routedSessionId: 'session-1',
+ runtimeIdByStoredSessionIdRef,
+ selectedStoredSessionId: null,
+ selectedStoredSessionIdRef,
+ startFreshSessionDraft
+ }
- expect(resumeSession).not.toHaveBeenCalled()
+ const { rerender } = render(<RouteResumeHarness {...props} />)
- // Idle reap queued requestSessionResume, then the user deleted the chat.
- // Draft state lands before React Router flips /:sid -> /new.
- activeSessionIdRef.current = null
- selectedStoredSessionIdRef.current = null
- rerender(
- <RouteResumeHarness
- activeSessionId={null}
- activeSessionIdRef={activeSessionIdRef}
- creatingSessionRef={creatingSessionRef}
- currentView="chat"
- freshDraftReady
- gatewayState="open"
- locationPathname="/session-1"
- resumeSession={resumeSession}
- routedSessionId="session-1"
- runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}
- selectedStoredSessionId={null}
- selectedStoredSessionIdRef={selectedStoredSessionIdRef}
- sessionResumeRequest={{ sequence: 1, sessionId: 'session-1' }}
- startFreshSessionDraft={startFreshSessionDraft}
- />
- )
+ resumeSession.mockClear()
- expect(resumeSession).not.toHaveBeenCalled()
+ rerender(<RouteResumeHarness {...props} sessionResumeRequest={{ sequence: 1, sessionId: 'session-1' }} />)
+
+ expect(resumeSession).toHaveBeenCalledWith('session-1', true)
})
it('self-heals a stranded routed session (null selected/active, same pathname, not a fresh draft)', () => {
diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.ts b/apps/desktop/src/app/session/hooks/use-route-resume.ts
index 691a89787e8..631f10e0072 100644
--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts
+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts
@@ -132,13 +132,7 @@ export function useRouteResume({
Boolean(cachedRuntime) &&
cachedRuntime === activeSessionIdRef.current
- // A leftover 4001 recovery (`requestSessionResume`) must not rebind a
- // chat the user just deleted: startFreshSessionDraft nulls selection one
- // render before the pathname flips /:sid -> /new. Honoring that queued
- // resume re-selects the doomed id, the RPC 404s, and Desktop toasts
- // "Resume failed / Session not found".
const explicitlyRequested =
- !freshDraftReady &&
sessionResumeRequest?.sessionId === routedSessionId &&
sessionResumeRequest.sequence > handledResumeRequestRef.current
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index 3027f7b1efc..e8550299c1e 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -25,13 +25,7 @@ import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/
import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'
import { $pinnedSessionIds } from '@/store/layout'
import { $activeGatewayProfile, $newChatProfile, $newChatRoute, $profiles, ensureGatewayProfile } from '@/store/profile'
-import {
- $projectScope,
- $projectTree,
- $removedSessionIds,
- $sessionMutationsInFlight,
- ALL_PROJECTS
-} from '@/store/projects'
+import { $projectScope, $projectTree, ALL_PROJECTS } from '@/store/projects'
import {
$activeSessionId,
$activeSessionStoredIdRotation,
@@ -71,6 +65,7 @@ import {
setSessions,
setTurnStartedAt
} from '@/store/session'
+import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/session-removal'
import { requestForSessionProfile, type SessionProfileRoute } from '@/store/session-request-router'
import { $sessionTiles, sessionTileOwnerRoute } from '@/store/session-states'
import { $sessionSeenCounts, $unreadFinishedMarkers } from '@/store/session-unread'
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 2204f911549..4790f027656 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -49,16 +49,7 @@ import {
normalizeProfileKey,
resolveNewChatOwnerRoute
} from '@/store/profile'
-import {
- $projectScope,
- $removedSessionIds,
- $sessionMutationsInFlight,
- beginSessionMutation,
- endSessionMutation,
- resolveNewSessionCwd,
- tombstoneSessions,
- untombstoneSessions
-} from '@/store/projects'
+import { $projectScope, resolveNewSessionCwd } from '@/store/projects'
import { setApprovalRequest } from '@/store/prompts'
import { clearStoredTranscriptReadOnly, markStoredTranscriptReadOnly } from '@/store/read-only-transcript'
import {
@@ -101,6 +92,13 @@ import {
setYoloActive
} from '@/store/session'
import { isSessionOwnerResolutionError } from '@/store/session-owner-resolution'
+import {
+ beginSessionMutation,
+ endSessionMutation,
+ isSessionRemovalPending,
+ tombstoneSessions,
+ untombstoneSessions
+} from '@/store/session-removal'
import {
requestForSessionProfile,
type SessionOwnerRoute,
@@ -860,10 +858,12 @@ export function useSessionActions({
const resumeSession = useCallback(
async (storedSessionId: string, replaceRoute = false, capturedOwner?: SessionProfileRoute) => {
- // Delete/archive tombstones the durable id before the route flips.
- // A leftover 4001 rebind must not re-select that id and toast
- // "Resume failed / Session not found".
- if ($removedSessionIds.get().has(storedSessionId) || $sessionMutationsInFlight.get().has(storedSessionId)) {
+ // Delete/archive tombstones the durable id before the route flips, and
+ // requestSessionResume already refuses to queue for a doomed id. This is
+ // the actuator-side half of the same rule: a resume that was queued
+ // BEFORE the tombstone (an idle-reap 4001 racing the delete) must not
+ // re-select the chat and toast "Resume failed / Session not found".
+ if (isSessionRemovalPending(storedSessionId)) {
return
}
diff --git a/apps/desktop/src/store/runtime-gone.test.ts b/apps/desktop/src/store/runtime-gone.test.ts
index 48170769c3e..7c0198825ba 100644
--- a/apps/desktop/src/store/runtime-gone.test.ts
+++ b/apps/desktop/src/store/runtime-gone.test.ts
@@ -13,6 +13,7 @@ import {
resetRuntimeGoneHealing
} from './runtime-gone'
import { $activeSessionId, $sessionResumeRequest } from './session'
+import { $removedSessionIds, tombstoneSessions } from './session-removal'
import { $sessionStates, $sessionTiles } from './session-states'
const STORED = 'stored-1'
@@ -29,6 +30,7 @@ beforeEach(() => {
$sessionTiles.set([])
$activeSessionId.set(null)
$sessionResumeRequest.set(null)
+ $removedSessionIds.set(new Set())
})
afterEach(() => {
@@ -39,6 +41,7 @@ afterEach(() => {
$sessionTiles.set([])
$activeSessionId.set(null)
$sessionResumeRequest.set(null)
+ $removedSessionIds.set(new Set())
})
describe('markRuntimeGone', () => {
@@ -75,6 +78,19 @@ describe('markRuntimeGone', () => {
expect($sessionResumeRequest.get()).toBeNull()
})
+ it('does not resurrect a chat the user just deleted', () => {
+ // An idle reap can land its 4001 in the same tick as the delete. The stored
+ // id is already tombstoned, so requestSessionResume drops the request
+ // instead of re-selecting a doomed chat and toasting "Resume failed".
+ $sessionStates.set({ [RUNTIME]: cachedState(STORED) })
+ $activeSessionId.set(RUNTIME)
+ tombstoneSessions([STORED])
+
+ markRuntimeGone(RUNTIME)
+
+ expect($sessionResumeRequest.get()).toBeNull()
+ })
+
it('heals a runtime id exactly once, however many pollers report it', () => {
$sessionStates.set({ [RUNTIME]: cachedState(STORED) })
$activeSessionId.set(RUNTIME)
diff --git a/apps/desktop/src/store/session-removal.test.ts b/apps/desktop/src/store/session-removal.test.ts
new file mode 100644
index 00000000000..2757663a6ca
--- /dev/null
+++ b/apps/desktop/src/store/session-removal.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, describe, expect, it } from 'vitest'
+
+import { $sessionResumeRequest, requestSessionResume } from './session'
+import {
+ $removedSessionIds,
+ $sessionMutationsInFlight,
+ beginSessionMutation,
+ endSessionMutation,
+ isSessionRemovalPending,
+ tombstoneSessions,
+ untombstoneSessions
+} from './session-removal'
+
+afterEach(() => {
+ $removedSessionIds.set(new Set())
+ $sessionMutationsInFlight.set(new Set())
+ $sessionResumeRequest.set(null)
+})
+
+describe('isSessionRemovalPending', () => {
+ it('is true for a tombstoned id and for one whose delete RPC is still in flight', () => {
+ tombstoneSessions(['gone'])
+ beginSessionMutation(['deleting'])
+
+ expect(isSessionRemovalPending('gone')).toBe(true)
+ expect(isSessionRemovalPending('deleting')).toBe(true)
+ expect(isSessionRemovalPending('alive')).toBe(false)
+ })
+
+ it('goes false again when a failed delete rolls the row back', () => {
+ tombstoneSessions(['rolled-back'])
+ beginSessionMutation(['rolled-back'])
+ expect(isSessionRemovalPending('rolled-back')).toBe(true)
+
+ untombstoneSessions(['rolled-back'])
+ endSessionMutation(['rolled-back'])
+
+ expect(isSessionRemovalPending('rolled-back')).toBe(false)
+ })
+
+ it('ignores blank ids rather than treating them as pending', () => {
+ expect(isSessionRemovalPending('')).toBe(false)
+ expect(isSessionRemovalPending(' ')).toBe(false)
+ expect(isSessionRemovalPending(null)).toBe(false)
+ })
+})
+
+describe('requestSessionResume refuses a doomed session', () => {
+ it('queues a resume for a live session', () => {
+ requestSessionResume('live-1')
+
+ expect($sessionResumeRequest.get()?.sessionId).toBe('live-1')
+ })
+
+ it('drops the request once the id is tombstoned', () => {
+ tombstoneSessions(['deleted-1'])
+
+ requestSessionResume('deleted-1')
+
+ expect($sessionResumeRequest.get()).toBeNull()
+ })
+
+ it('drops the request while the delete RPC is still in flight', () => {
+ beginSessionMutation(['deleting-1'])
+
+ requestSessionResume('deleting-1')
+
+ expect($sessionResumeRequest.get()).toBeNull()
+ })
+
+ it('leaves an earlier live request intact instead of clobbering it', () => {
+ requestSessionResume('live-1')
+ const queued = $sessionResumeRequest.get()
+
+ tombstoneSessions(['deleted-1'])
+ requestSessionResume('deleted-1')
+
+ expect($sessionResumeRequest.get()).toBe(queued)
+ })
+})
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index 39e91c32cc1..5ce4c9e6205 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -14,6 +14,7 @@ import { persistBoolean, persistString, readJson, storedBoolean, storedString, w
import { syncCronModelImpactConnection } from '@/store/cron-model-impact-scope'
import type { SessionInfo, UsageStats } from '@/types/hermes'
+import { isSessionRemovalPending } from './session-removal'
import type { SessionOwnerRoute, SessionOwnerScope } from './session-request-router'
import { clearUnreadOnOpen } from './session-unread-remote'
@@ -1283,6 +1284,16 @@ export const requestSessionResume = (sessionId: string, ownerRoute?: SessionOwne
return
}
+ // A chat on its way out must never be re-selected. The push path
+ // (markRuntimeGone) and the RPC seam both queue a resume off a 4001, and an
+ // idle reap can land one in the same tick as a delete — that queued request
+ // then resumes a tombstoned id, 404s, and toasts "Resume failed / Session
+ // not found" for a chat the user deliberately removed. Filtering at the
+ // producer means no consumer has to re-derive "is this id doomed".
+ if (isSessionRemovalPending(id)) {
+ return
+ }
+
if (ownerRoute) {
setSessionOwnerHint(id, ownerRoute)
}