Skip to content

The agent that grows with you

fix(desktop): resume re-attach retries stay quiet, and the tests drive the arming and the fire-time guard

Teknium8f3cfce1fb46
diff --git a/apps/desktop/src/app/session/hooks/resume-reattach-arming.test.tsx b/apps/desktop/src/app/session/hooks/resume-reattach-arming.test.tsx
new file mode 100644
index 00000000000..430c65a3df5
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/resume-reattach-arming.test.tsx
@@ -0,0 +1,126 @@
+import { useStore } from '@nanostores/react'
+import { cleanup, render, waitFor } from '@testing-library/react'
+import { useEffect, useRef } from 'react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { getLatestSessionMessages } from '@/hermes'
+import { recordFriction } from '@/store/desktop-metrics'
+import { $notifications, clearNotifications, notify } from '@/store/notifications'
+import {
+ $activeSessionId,
+ $resumeFailedSessionId,
+ $resumeReattachSessionId,
+ setActiveSessionId,
+ setAwaitingResponse,
+ setBusy,
+ setMessages,
+ setResumeReattachSessionId,
+ setSelectedStoredSessionId
+} from '@/store/session'
+import { clearAllSessionStates } from '@/store/session-states'
+
+import { useSessionActions } from './use-session-actions'
+import { useSessionStateCache } from './use-session-state-cache'
+
+vi.mock('@/hermes', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getLatestSessionMessages: vi.fn(),
+ getSession: vi.fn(),
+ listAllProfileSessions: vi.fn(),
+ setApiRequestProfile: vi.fn()
+}))
+
+vi.mock('@/store/profile', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ ensureGatewayAgent: vi.fn().mockResolvedValue(undefined),
+ ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)
+}))
+
+vi.mock('@/store/gateway', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ requestGatewayForAgent: vi.fn(),
+ requestGatewayForProfile: vi.fn(),
+ retainGatewayForAgent: vi.fn(async () => () => undefined)
+}))
+
+vi.mock('@/store/desktop-metrics', async importOriginal => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ recordFriction: vi.fn()
+}))
+
+type Resume = ReturnType<typeof useSessionActions>['resumeSession']
+
+function Harness({ onReady }: { onReady: (resume: Resume) => void }) {
+ const activeSessionId = useStore($activeSessionId)
+ const busyRef = useRef(false)
+
+ const cache = useSessionStateCache({
+ activeSessionId,
+ busyRef,
+ selectedStoredSessionId: null,
+ setAwaitingResponse,
+ setBusy,
+ setMessages
+ })
+
+ const actions = useSessionActions({
+ ...cache,
+ activeSessionId,
+ busyRef,
+ creatingSessionRef: useRef(false),
+ getRouteToken: () => 'reattach-arming',
+ getRoutedStoredSessionId: () => null,
+ navigate: vi.fn() as never,
+ requestGateway: async method => {
+ throw new Error(`injected transient failure: ${method}`)
+ },
+ routedSessionId: null,
+ selectedStoredSessionId: null
+ })
+
+ useEffect(() => {
+ onReady(actions.resumeSession)
+ }, [actions.resumeSession, onReady])
+
+ return null
+}
+
+afterEach(() => {
+ cleanup()
+ clearNotifications()
+ clearAllSessionStates()
+ setResumeReattachSessionId(null)
+ setActiveSessionId(null)
+ setSelectedStoredSessionId(null)
+ setMessages([])
+ vi.clearAllMocks()
+})
+
+it('a resume that fails after painting the history arms the quiet re-attach, and its retry stays quiet', async () => {
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ messages: [
+ { content: 'run the long job', role: 'user', timestamp: 1 },
+ { content: 'started it', role: 'assistant', timestamp: 2 }
+ ],
+ session_id: 'stored-1'
+ } as never)
+
+ let resume: null | Resume = null
+ render(<Harness onReady={r => (resume = r)} />)
+ await waitFor(() => expect(resume).not.toBeNull())
+
+ await resume!('stored-1', true)
+
+ // Readable but detached: re-attach, never the stranded-window latch whose
+ // exhaustion would cover the painted history with the error overlay.
+ expect($resumeReattachSessionId.get()).toBe('stored-1')
+ expect($resumeFailedSessionId.get()).toBeNull()
+
+ // The re-attach retry fails the same way while another toast is up.
+ notify({ id: 'unrelated', kind: 'warning', message: 'something else the user is reading' })
+ await resume!('stored-1', true, undefined, { reattach: true })
+
+ expect($resumeReattachSessionId.get()).toBe('stored-1')
+ expect($notifications.get().map(n => n.id)).toEqual(['unrelated', 'resume-failed:stored-1'])
+ expect(vi.mocked(recordFriction).mock.calls.filter(([kind]) => kind === 'error_toast')).toHaveLength(1)
+})
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.tsx
index d130110c193..4b51b020f5f 100644
--- a/apps/desktop/src/app/session/hooks/use-resume-reattach.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-resume-reattach.test.tsx
@@ -29,13 +29,15 @@ describe('a failed resume that still painted the history', () => {
setResumeExhaustedSessionId(null)
})
- it('re-attaches on backoff, bounded, and never covers the history with the exhausted error', () => {
+ it('skips a timer that fires after the selection moved or a runtime bound, and stays bounded', () => {
vi.useFakeTimers()
const resumeSession = vi.fn(async () => undefined)
+ const activeSessionIdRef: MutableRefObject<null | string> = { current: null }
+ const selectedStoredSessionIdRef: MutableRefObject<null | string> = { current: 'session-1' }
const props: Props = {
activeSessionId: null,
- activeSessionIdRef: { current: null } as MutableRefObject<null | string>,
+ activeSessionIdRef,
creatingSessionRef: { current: false },
currentView: 'chat',
freshDraftReady: false,
@@ -48,27 +50,41 @@ describe('a failed resume that still painted the history', () => {
routedSessionId: 'session-1',
runtimeIdByStoredSessionIdRef: { current: new Map<string, string>() },
selectedStoredSessionId: 'session-1',
- selectedStoredSessionIdRef: { current: 'session-1' } as MutableRefObject<null | string>,
+ selectedStoredSessionIdRef,
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) {
+ // resumeSession arms the latch on that failure, and clears it at the
+ // entry of every later attempt, which then fails the same way.
+ const failAgain = () => {
setResumeReattachSessionId(null)
rerender(<Harness {...props} />)
setResumeReattachSessionId('session-1')
rerender(<Harness {...props} />)
+ }
+
+ // The refs move before the route/props catch up (renderer timers lag).
+ failAgain()
+ selectedStoredSessionIdRef.current = 'session-2'
+ vi.advanceTimersByTime(1_000)
+ selectedStoredSessionIdRef.current = 'session-1'
+
+ failAgain()
+ activeSessionIdRef.current = 'runtime-1'
+ vi.advanceTimersByTime(1_000)
+ activeSessionIdRef.current = null
+
+ expect(resumeSession).not.toHaveBeenCalled()
+
+ failAgain()
+ vi.advanceTimersByTime(1_000)
+ expect(resumeSession).toHaveBeenCalledWith('session-1', true, undefined, { reattach: true })
+
+ for (let i = 0; i < 8; i += 1) {
+ failAgain()
vi.advanceTimersByTime(8_000)
}
diff --git a/apps/desktop/src/app/session/hooks/use-resume-reattach.ts b/apps/desktop/src/app/session/hooks/use-resume-reattach.ts
index 8cdee719e90..52a947c8831 100644
--- a/apps/desktop/src/app/session/hooks/use-resume-reattach.ts
+++ b/apps/desktop/src/app/session/hooks/use-resume-reattach.ts
@@ -1,15 +1,23 @@
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useEffect, useRef } from 'react'
+import { dismissNotification } from '@/store/notifications'
import { $resumeReattachSessionId } from '@/store/session'
+import { type ResumeAttemptOptions, resumeFailedToastId } from './use-session-actions/resume-latches'
+
interface ResumeReattachOptions {
activeSessionId: string | null
activeSessionIdRef: MutableRefObject<string | null>
creatingSessionRef: MutableRefObject<boolean>
currentView: string
gatewayState: string | undefined
- resumeSession: (sessionId: string, focus: boolean) => Promise<unknown>
+ resumeSession: (
+ sessionId: string,
+ focus: boolean,
+ ownerRoute?: undefined,
+ options?: ResumeAttemptOptions
+ ) => Promise<unknown>
routedSessionId: string | null
selectedStoredSessionIdRef: MutableRefObject<string | null>
}
@@ -25,7 +33,8 @@ const REATTACH_MAX_MS = 8_000
* 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.
+ * screen either way, and a reconnect or reselect resumes it as before. They
+ * are quiet: no app-wide toast wipe, no repeat "Resume failed" (resume-latches).
*/
export function useResumeReattach({
activeSessionId,
@@ -43,6 +52,12 @@ export function useResumeReattach({
useEffect(() => {
const attempts = attemptsRef.current
+ // A retry re-attached: the incident's "Resume failed" toast is stale now
+ // (retries no longer clear the app's toasts on entry).
+ if (activeSessionId && routedSessionId && attempts.count > 0 && attempts.sessionId === routedSessionId) {
+ dismissNotification(resumeFailedToastId(routedSessionId))
+ }
+
// A bound runtime (or another chat) starts the next detach on a fresh cycle.
if (activeSessionId || attempts.sessionId !== routedSessionId) {
attempts.sessionId = routedSessionId
@@ -73,7 +88,7 @@ export function useResumeReattach({
}
attempts.count += 1
- void resumeSession(sessionId, true)
+ void resumeSession(sessionId, true, undefined, { reattach: true })
},
Math.min(REATTACH_MAX_MS, REATTACH_BASE_MS * 2 ** attempts.count)
)
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 63f1acffc0a..4bc2bb26286 100644
--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts
+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts
@@ -6,6 +6,7 @@ import type { SessionProfileRoute } from '@/store/session-request-router'
import { markSelectionRestore } from '@/store/session-states'
import { useResumeReattach } from './use-resume-reattach'
+import type { ResumeAttemptOptions } from './use-session-actions/resume-latches'
interface RouteResumeOptions {
activeSessionId: string | null
@@ -19,7 +20,7 @@ interface RouteResumeOptions {
sessionId: string,
focus: boolean,
ownerRoute?: SessionProfileRoute,
- options?: { authoritativeSnapshot?: boolean }
+ options?: ResumeAttemptOptions
) => Promise<unknown>
// Stored-session id whose most recent resume failed terminally (set by
// useSessionActions, mirrored from $resumeFailedSessionId). While this equals
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 06d47e76da9..66b15966d0d 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
@@ -167,7 +167,7 @@ import {
withoutEarlyClarifyProjection
} from './restore-pending-clarify'
import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'
-import { clearResumeLatches } from './resume-latches'
+import { clearResumeLatches, clearResumeToasts, notifyResumeFailed, type ResumeAttemptOptions } from './resume-latches'
import {
ambientResumeConnectionId,
openResumeGateway,
@@ -1155,7 +1155,7 @@ export function useSessionActions({
storedSessionId: string,
replaceRoute = false,
capturedOwner?: SessionProfileRoute,
- options?: { authoritativeSnapshot?: boolean }
+ options?: ResumeAttemptOptions
) => {
// Delete/archive tombstones the durable id before the route flips, and
// requestSessionResume already refuses to queue for a doomed id. This is
@@ -1206,7 +1206,7 @@ export function useSessionActions({
// ref here is also what use-route-resume's self-heal assumes ("set
// synchronously at resume entry").
setFreshDraftReady(false)
- clearNotifications()
+ clearResumeToasts(options)
resetViewSync()
setSelectedStoredSessionId(storedSessionId)
selectedStoredSessionIdRef.current = storedSessionId
@@ -1446,7 +1446,7 @@ export function useSessionActions({
}
setFreshDraftReady(false)
- clearNotifications()
+ clearResumeToasts(options)
setSelectedStoredSessionId(storedSessionId)
selectedStoredSessionIdRef.current = storedSessionId
setActiveSessionId(cachedRuntimeId)
@@ -1934,7 +1934,7 @@ export function useSessionActions({
busyRef.current = false
setBusy(false)
setAwaitingResponse(false)
- clearNotifications()
+ clearResumeToasts(options)
setSelectedStoredSessionId(storedSessionId)
selectedStoredSessionIdRef.current = storedSessionId
const runtimeStartedAt = Date.now()
@@ -2530,7 +2530,7 @@ export function useSessionActions({
setResumeReattachSessionId(storedSessionId)
}
- notifyError(err, copy.resumeFailed)
+ notifyResumeFailed(err, copy.resumeFailed, storedSessionId, options)
} finally {
displayRead.release()
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.ts
index 969e4d1737e..5817103ff9b 100644
--- 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.ts
@@ -1,5 +1,12 @@
+import { clearNotifications, notifyError } from '@/store/notifications'
import { setResumeExhaustedSessionId, setResumeFailedSessionId, setResumeReattachSessionId } from '@/store/session'
+export interface ResumeAttemptOptions {
+ authoritativeSnapshot?: boolean
+ // use-resume-reattach's quiet retry of a chat that already shows its history.
+ reattach?: boolean
+}
+
/**
* A fresh resume attempt (route change, retry, reconnect, reselect) retires
* every latch an earlier attempt armed for the session: the self-heals in
@@ -14,3 +21,33 @@ export function clearResumeLatches(storedSessionId: string): void {
setResumeExhaustedSessionId(retire)
setResumeReattachSessionId(retire)
}
+
+export const resumeFailedToastId = (storedSessionId: string) => `resume-failed:${storedSessionId}`
+
+/**
+ * Opening a chat drops the toasts of the one before it. A re-attach retry
+ * stays on the same chat and reruns up to four times; wiping every toast in
+ * the app on each run would dismiss whatever else the user is reading.
+ */
+export function clearResumeToasts(options: ResumeAttemptOptions | undefined): void {
+ if (!options?.reattach) {
+ clearNotifications()
+ }
+}
+
+/**
+ * One "Resume failed" toast per incident, counted once. The first failure
+ * shows it under a stable id; a re-attach retry is the same incident, so its
+ * failure leaves that toast as it is instead of showing (and counting) it
+ * again. use-resume-reattach dismisses it once a runtime binds.
+ */
+export function notifyResumeFailed(
+ error: unknown,
+ fallback: string,
+ storedSessionId: string,
+ options: ResumeAttemptOptions | undefined
+): void {
+ if (!options?.reattach) {
+ notifyError(error, fallback, { id: resumeFailedToastId(storedSessionId) })
+ }
+}