The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a chat whose resume fails once after a reload re-attaches and shows the running turn's reply
Tekniumcafa3874af70
diff --git a/apps/desktop/src/app/session/hooks/use-resume-reattach.test.tsx b/apps/desktop/src/app/session/hooks/use-resume-reattach.test.tsxnew file mode 100644index 00000000000..d130110c193--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-resume-reattach.test.tsx@@ -0,0 +1,78 @@+import { cleanup, render } from '@testing-library/react'+import type { MutableRefObject } from 'react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { $resumeExhaustedSessionId, setResumeExhaustedSessionId, setResumeReattachSessionId } from '@/store/session'++import { useRouteResume } from './use-route-resume'++vi.mock('@/store/session-states', () => ({ markSelectionRestore: vi.fn() }))++type Props = Parameters<typeof useRouteResume>[0]++function Harness(props: Props) {+ useRouteResume(props)++ return null+}++/**+ * A reload whose first session.resume fails while the REST fallback paints the+ * history leaves a readable chat bound to no runtime: the turn still running+ * there never streamed its reply in (stuck on "Result unavailable").+ */+describe('a failed resume that still painted the history', () => {+ afterEach(() => {+ cleanup()+ vi.useRealTimers()+ setResumeReattachSessionId(null)+ setResumeExhaustedSessionId(null)+ })++ it('re-attaches on backoff, bounded, and never covers the history with the exhausted error', () => {+ vi.useFakeTimers()+ const resumeSession = vi.fn(async () => undefined)++ const props: Props = {+ activeSessionId: null,+ activeSessionIdRef: { current: null } as MutableRefObject<null | string>,+ creatingSessionRef: { current: false },+ currentView: 'chat',+ freshDraftReady: false,+ gatewayState: 'open',+ locationPathname: '/session-1',+ resumeSession,+ resumeFailedSessionId: null,+ resumeExhaustedSessionId: null,+ sessionResumeRequest: null,+ routedSessionId: 'session-1',+ runtimeIdByStoredSessionIdRef: { current: new Map<string, string>() },+ selectedStoredSessionId: 'session-1',+ selectedStoredSessionIdRef: { current: 'session-1' } as MutableRefObject<null | string>,+ startFreshSessionDraft: vi.fn()+ }++ const { rerender } = render(<Harness {...props} />)+ resumeSession.mockClear() // the mount resume is the one that failed++ // What resumeSession does on that failure: history painted, latch armed.+ setResumeReattachSessionId('session-1')+ rerender(<Harness {...props} />)++ vi.advanceTimersByTime(1_000)+ expect(resumeSession).toHaveBeenCalledTimes(1)+ expect(resumeSession).toHaveBeenCalledWith('session-1', true)++ // Every retry clears the latch at entry and fails the same way again.+ for (let i = 0; i < 8; i += 1) {+ setResumeReattachSessionId(null)+ rerender(<Harness {...props} />)+ setResumeReattachSessionId('session-1')+ rerender(<Harness {...props} />)+ vi.advanceTimersByTime(8_000)+ }++ expect(resumeSession).toHaveBeenCalledTimes(4)+ expect($resumeExhaustedSessionId.get()).toBeNull()+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-resume-reattach.ts b/apps/desktop/src/app/session/hooks/use-resume-reattach.tsnew file mode 100644index 00000000000..8cdee719e90--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-resume-reattach.ts@@ -0,0 +1,93 @@+import { useStore } from '@nanostores/react'+import { type MutableRefObject, useEffect, useRef } from 'react'++import { $resumeReattachSessionId } from '@/store/session'++interface ResumeReattachOptions {+ activeSessionId: string | null+ activeSessionIdRef: MutableRefObject<string | null>+ creatingSessionRef: MutableRefObject<boolean>+ currentView: string+ gatewayState: string | undefined+ resumeSession: (sessionId: string, focus: boolean) => Promise<unknown>+ routedSessionId: string | null+ selectedStoredSessionIdRef: MutableRefObject<string | null>+}++const MAX_REATTACH_ATTEMPTS = 4+const REATTACH_BASE_MS = 1_000+const REATTACH_MAX_MS = 8_000++/**+ * Re-attach a routed chat whose resume RPC failed while the REST fallback+ * still painted its history ($resumeReattachSessionId). The window reads fine+ * but is bound to no runtime, and nothing else resumes it: the route, the+ * selection and the gateway are all unchanged. A turn still running there then+ * never streams its reply in, and the view keeps "Result unavailable" for good.+ * Retries back off and stop after MAX_REATTACH_ATTEMPTS; the history stays on+ * screen either way, and a reconnect or reselect resumes it as before.+ */+export function useResumeReattach({+ activeSessionId,+ activeSessionIdRef,+ creatingSessionRef,+ currentView,+ gatewayState,+ resumeSession,+ routedSessionId,+ selectedStoredSessionIdRef+}: ResumeReattachOptions): void {+ const reattachSessionId = useStore($resumeReattachSessionId)+ const attemptsRef = useRef<{ count: number; sessionId: null | string }>({ count: 0, sessionId: null })++ useEffect(() => {+ const attempts = attemptsRef.current++ // A bound runtime (or another chat) starts the next detach on a fresh cycle.+ if (activeSessionId || attempts.sessionId !== routedSessionId) {+ attempts.sessionId = routedSessionId+ attempts.count = 0+ }++ if (+ currentView !== 'chat' ||+ gatewayState !== 'open' ||+ !routedSessionId ||+ reattachSessionId !== routedSessionId ||+ attempts.count >= MAX_REATTACH_ATTEMPTS+ ) {+ return+ }++ const sessionId = routedSessionId++ const timer = setTimeout(+ () => {+ // The resume may have landed, or the user moved on, while we waited.+ if (+ creatingSessionRef.current ||+ selectedStoredSessionIdRef.current !== sessionId ||+ activeSessionIdRef.current !== null+ ) {+ return+ }++ attempts.count += 1+ void resumeSession(sessionId, true)+ },+ Math.min(REATTACH_MAX_MS, REATTACH_BASE_MS * 2 ** attempts.count)+ )++ return () => clearTimeout(timer)+ }, [+ activeSessionId,+ activeSessionIdRef,+ creatingSessionRef,+ currentView,+ gatewayState,+ reattachSessionId,+ resumeSession,+ routedSessionId,+ selectedStoredSessionIdRef+ ])+}diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.ts b/apps/desktop/src/app/session/hooks/use-route-resume.tsindex 6b9ed5e32f8..63f1acffc0a 100644--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts@@ -5,6 +5,8 @@ import { type SessionResumeRequest, setResumeExhaustedSessionId } from '@/store/import type { SessionProfileRoute } from '@/store/session-request-router'import { markSelectionRestore } from '@/store/session-states'+import { useResumeReattach } from './use-resume-reattach'+interface RouteResumeOptions {activeSessionId: string | nullactiveSessionIdRef: MutableRefObject<string | null>@@ -369,4 +371,15 @@ export function useRouteResume({routedSessionId,selectedStoredSessionIdRef])++ useResumeReattach({+ activeSessionId,+ activeSessionIdRef,+ creatingSessionRef,+ currentView,+ gatewayState,+ resumeSession,+ routedSessionId,+ selectedStoredSessionIdRef+ })}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 5f4525234d5..06d47e76da9 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@@ -88,8 +88,8 @@ import {setIntroSeed,setMessages,setNewChatWorkspaceTarget,- setResumeExhaustedSessionId,setResumeFailedSessionId,+ setResumeReattachSessionId,setSelectedStoredSessionId,setSessionOwnerHint,setSessionStartedAt,@@ -167,6 +167,7 @@ import {withoutEarlyClarifyProjection} from './restore-pending-clarify'import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'+import { clearResumeLatches } from './resume-latches'import {ambientResumeConnectionId,openResumeGateway,@@ -1223,15 +1224,7 @@ export function useSessionActions({closeSessionTile(storedSessionId)}- // Optimistically clear any prior resume-failure latch for this session:- // we're attempting a fresh resume, so the self-heal in use-route-resume- // must not keep treating it as stranded. It's re-armed below only if THIS- // attempt fails terminally (RPC reject + REST fallback failure).- setResumeFailedSessionId(current => (current === storedSessionId ? null : current))- // Also clear the exhausted-latch: a fresh attempt (manual Retry, reconnect,- // reselect) gives the bounded auto-retry counter a clean cycle, so the- // chat view drops the error state and shows the loader again.- setResumeExhaustedSessionId(current => (current === storedSessionId ? null : current))+ clearResumeLatches(storedSessionId)// A warm cache entry is only trustworthy when it still BELONGS to the// session being resumed. A pooled profile backend that gets idle-reaped@@ -2531,6 +2524,10 @@ export function useSessionActions({// once retries exhaust, blank that visible transcript behind the// exhausted-state error overlay (a regression vs. plain fallback success).setResumeFailedSessionId(storedSessionId)+ } else {+ // Readable, but detached: a turn still running there never streams+ // in. Re-attach quietly (use-resume-reattach), no error overlay.+ setResumeReattachSessionId(storedSessionId)}notifyError(err, copy.resumeFailed)diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/resume-latches.ts b/apps/desktop/src/app/session/hooks/use-session-actions/resume-latches.tsnew file mode 100644index 00000000000..969e4d1737e--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/resume-latches.ts@@ -0,0 +1,16 @@+import { setResumeExhaustedSessionId, setResumeFailedSessionId, setResumeReattachSessionId } from '@/store/session'++/**+ * A fresh resume attempt (route change, retry, reconnect, reselect) retires+ * every latch an earlier attempt armed for the session: the self-heals in+ * use-route-resume / use-resume-reattach must stop treating it as stranded or+ * detached, and the chat view drops the exhausted error for the loader. This+ * attempt re-arms the one that matches how it ends.+ */+export function clearResumeLatches(storedSessionId: string): void {+ const retire = (current: null | string) => (current === storedSessionId ? null : current)++ setResumeFailedSessionId(retire)+ setResumeExhaustedSessionId(retire)+ setResumeReattachSessionId(retire)+}diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex ef592992c1a..dec417e1eda 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -1167,6 +1167,12 @@ export const $awaitingResponse = atom(false)// resume on the next render/focus/reconnect instead of stranding the window.// Null whenever the active route has a healthy (or in-flight) resume.export const $resumeFailedSessionId = atom<string | null>(null)+// Stored-session id whose last resume RPC failed while the REST fallback still+// painted its history: readable, but bound to no runtime, so a turn running+// there never streams its reply in. use-resume-reattach re-attempts the resume+// quietly. Unlike $resumeFailedSessionId it never ends in the exhausted+// overlay, which would cover the history the window can already show.+export const $resumeReattachSessionId = atom<string | null>(null)export interface SessionResumeRequest {authoritativeSnapshot?: booleanownerRoute?: SessionOwnerRoute@@ -1614,6 +1620,7 @@ export const setFreshDraftReady = (next: Updater<boolean>) => updateAtom($freshDexport { $freshDraftKey, rotateFreshDraftKey } from './composer'export const setResumeFailedSessionId = (next: Updater<string | null>) => updateAtom($resumeFailedSessionId, next)+export const setResumeReattachSessionId = (next: Updater<string | null>) => updateAtom($resumeReattachSessionId, next)export const requestSessionResume = (sessionId: string,