The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep deleted sessions from rebinding
Gilleb3b5671094b6
diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.tsindex 8c6e83dcca1..0c1645ccbc1 100644--- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts+++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts@@ -38,6 +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 { _resetSessionOwnerHintsForTests, setCronSessions, setMessagingSessions, setSessionOwnerHint, setSessions } =await import('@/store/session')@@ -75,6 +76,8 @@ afterEach(() => {setMessagingSessions([])$sessionTiles.set([])$profiles.set([])+ $removedSessionIds.set(new Set())+ $sessionMutationsInFlight.set(new Set())_resetSessionOwnerHintsForTests({ storage: true })sessionMocks.requestSessionResume.mockReset()vi.clearAllMocks()@@ -233,6 +236,22 @@ describe('createSessionRpcDispatcher: stale runtime recovery', () => {expect(sessionMocks.requestSessionResume).not.toHaveBeenCalled()})+ it.each([+ ['tombstoned', $removedSessionIds],+ ['being deleted', $sessionMutationsInFlight]+ ])('does not rebind a selected session that is %s', async (_state, sessions) => {+ setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-omar', profile: 'omar' })])+ sessions.set(new Set(['stored-omar']))+ gatewayMocks.requestGatewayForAgent.mockRejectedValueOnce(+ Object.assign(new Error('session not found'), { code: 4001 })+ )+ 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 () => {setSessions([makeSessionInfo({ connection_id: 'local', id: 'stored-omar', profile: 'omar' })])gatewayMocks.requestGatewayForAgent.mockRejectedValueOnce(diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.tsindex cf9bfd94b46..71f4d6e7a77 100644--- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts+++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.ts@@ -35,6 +35,7 @@ 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'@@ -112,6 +113,8 @@ export function createSessionRpcDispatcher(deps: SessionRpcDispatcherDeps): AmbiparamSessionId &&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-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex 256975b6520..7aaef72699a 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@@ -77,7 +77,7 @@ import { $sessionSeenCounts, $unreadFinishedMarkers } from '@/store/session-unreimport sessionResumeActiveTurn from '../../../../../../tests/fixtures/session-resume-active-turn.json'import { deferred } from '../../../test/deferred'-import { sessionRoute } from '../../routes'+import { NEW_CHAT_ROUTE, sessionRoute } from '../../routes'import type { ClientSessionState } from '../../types'import { useSessionActions } from './use-session-actions'@@ -146,22 +146,26 @@ function storedSession(overrides: Partial<SessionInfo> = {}): SessionInfo {function Harness({activeSessionId = null,+ activeSessionIdRef: activeSessionIdRefOverride,navigate = vi.fn(),onReady,requestGateway,- selectedStoredSessionId = null+ selectedStoredSessionId = null,+ selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride}: {activeSessionId?: null | string+ activeSessionIdRef?: MutableRefObject<null | string>navigate?: ReturnType<typeof vi.fn>onReady: (handle: HarnessHandle) => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>selectedStoredSessionId?: null | string+ selectedStoredSessionIdRef?: MutableRefObject<null | string>}) {const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })const actions = useSessionActions({activeSessionId,- activeSessionIdRef: ref(activeSessionId),+ activeSessionIdRef: activeSessionIdRefOverride ?? ref(activeSessionId),busyRef: ref(false),creatingSessionRef: ref(false),ensureSessionState: () => ({}) as ClientSessionState,@@ -172,7 +176,7 @@ function Harness({resetViewSync: vi.fn(),runtimeIdByStoredSessionIdRef: ref(new Map<string, string>()),selectedStoredSessionId,- selectedStoredSessionIdRef: ref(selectedStoredSessionId),+ selectedStoredSessionIdRef: selectedStoredSessionIdRefOverride ?? ref(selectedStoredSessionId),sessionStateByRuntimeIdRef: ref(new Map<string, ClientSessionState>()),syncSessionStateToView: vi.fn(),updateSessionState: () => ({}) as ClientSessionState@@ -231,6 +235,44 @@ describe('connection-qualified session deletion', () => {})expect(requestGateway).not.toHaveBeenCalledWith('session.close', expect.anything())})++ it('tears down the selected session from synchronous refs when render state is stale', async () => {+ const navigate = vi.fn()+ const requestGateway = vi.fn().mockResolvedValue({})+ const activeSessionIdRef: MutableRefObject<null | string> = { current: 'runtime-shared' }+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'shared-session' }+ let actions: HarnessHandle | null = null++ setSessions([storedSession({ connection_id: 'source-a', id: 'shared-session', profile: 'worker' })])+ vi.mocked(deleteSession).mockResolvedValue({ ok: true })+ vi.mocked(requestGatewayForAgent).mockResolvedValue({} as never)++ render(+ <Harness+ activeSessionId={null}+ activeSessionIdRef={activeSessionIdRef}+ navigate={navigate}+ onReady={value => {+ actions = value+ }}+ requestGateway={requestGateway}+ selectedStoredSessionId={null}+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ />+ )+ await waitFor(() => expect(actions).not.toBeNull())++ await act(async () => {+ await actions?.removeSession('shared-session')+ })++ expect(navigate).toHaveBeenCalledWith(NEW_CHAT_ROUTE, { replace: true })+ expect(requestGatewayForAgent).toHaveBeenCalledWith('source-a', 'worker', 'session.close', {+ session_id: 'runtime-shared'+ })+ expect(selectedStoredSessionIdRef.current).toBeNull()+ expect(activeSessionIdRef.current).toBeNull()+ })})function StoredIdRotationHarness({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.tsindex 635880cae65..df31c30c759 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@@ -2220,8 +2220,12 @@ export function useSessionActions({return}- const wasSelected = selectedStoredSessionId === storedSessionId- const closingRuntimeId = wasSelected ? activeSessionId : null+ // Selection and runtime refs are updated synchronously at routing+ // boundaries. React props can still describe the previous render when a+ // delete lands in the same tick, which used to leave the doomed route in+ // place and let the generic 4001 recovery rebind it.+ const wasSelected = selectedStoredSessionIdRef.current === storedSessionId+ const closingRuntimeId = wasSelected ? activeSessionIdRef.current : nullconst previousMessages = $messages.get()const previousPinned = $pinnedSessionIds.get()@@ -2323,13 +2327,11 @@ export function useSessionActions({}},[- activeSessionId,activeSessionIdRef,copy,navigate,requestGateway,runtimeIdByStoredSessionIdRef,- selectedStoredSessionId,selectedStoredSessionIdRef,sessionStateByRuntimeIdRef,startFreshSessionDraft@@ -2356,7 +2358,7 @@ export function useSessionActions({return}- const wasSelected = selectedStoredSessionId === storedSessionId+ const wasSelected = selectedStoredSessionIdRef.current === storedSessionIdconst previousPinned = $pinnedSessionIds.get()// Pins are keyed on the durable lineage-root id; the stored id may be the// live tip after compression. Drop both so the pin can't linger.@@ -2401,7 +2403,13 @@ export function useSessionActions({endSessionMutation(archivedIds)}},- [copy, runtimeIdByStoredSessionIdRef, selectedStoredSessionId, sessionStateByRuntimeIdRef, startFreshSessionDraft]+ [+ copy,+ runtimeIdByStoredSessionIdRef,+ selectedStoredSessionIdRef,+ sessionStateByRuntimeIdRef,+ startFreshSessionDraft+ ])return {