The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): resume authoritative snapshots after replay gaps
unsupportedpastelsbedbd388022d
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.tsindex 9d1eb2819f3..c58a5b3a4fe 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts@@ -2,10 +2,16 @@ import { renderHook } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type * as HermesModule from '@/hermes'-import { setSessionOwnerHint, setSessions } from '@/store/session'+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'+import { $activeSessionId, setSessionOwnerHint, setSessions } from '@/store/session'import { $sessionTiles, sessionTileDelegate } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'+import {+ clearSingleFlightSessionResumeState,+ singleFlightSessionResume+} from '../../session/hooks/use-prompt-actions/single-flight-resume'+import { useSessionTileDelegate } from './use-session-tile-delegate'vi.mock('@/hermes', async importActual => ({@@ -63,11 +69,13 @@ function renderTile(describe('useSessionTileDelegate resumeTile', () => {beforeEach(() => {+ clearSingleFlightSessionResumeState()setSessions([])vi.mocked(getLatestSessionMessages).mockClear()})afterEach(() => {+ clearSingleFlightSessionResumeState()setSessions([])})@@ -194,6 +202,164 @@ describe('useSessionTileDelegate resumeTile', () => {expect(getLatestSessionMessages).not.toHaveBeenCalled()})+ it('forces an owner-routed message snapshot into a warm tile without touching foreground state', async () => {+ const ownerRoute = { connectionId: 'remote-tile', profile: 'tile-profile', targetProfile: 'backend-tile' }++ const pending = {+ id: 'user-pending',+ parts: [{ type: 'text', text: 'local pending prompt' }],+ pending: true,+ role: 'user'+ }++ const warm = { busy: false, messages: [pending], storedSessionId: 'stored-tile' }+ const runtimeIdByStoredSessionIdRef = { current: new Map([['stored-tile', 'runtime-tile']]) }+ const states = { current: new Map([['runtime-tile', warm]]) }++ const update = vi.fn((id, updater) => {+ const next = updater(states.current.get(id))+ states.current.set(id, next)++ return next+ })++ $activeSessionId.set('runtime-foreground')+ $sessionTiles.set([{ ownerRoute, runtimeId: 'runtime-tile', storedSessionId: 'stored-tile' }] as never)+ stashSessionDraft('stored-tile', 'unsent tile draft', [])+ vi.mocked(requestGatewayForAgent).mockResolvedValueOnce({+ info: { model: 'snapshot-model', yolo: true },+ message_count: 2,+ messages: [+ { content: 'new prompt', role: 'user', timestamp: 1 },+ { content: 'new answer', role: 'assistant', timestamp: 2 }+ ],+ resumed: 'stored-tile',+ running: true,+ session_id: 'runtime-tile'+ } as never)++ renderTile(vi.fn(), {+ runtimeIdByStoredSessionIdRef,+ sessionStateByRuntimeIdRef: states,+ updateSessionState: update+ })++ await sessionTileDelegate()!.resumeTile('stored-tile', { authoritativeSnapshot: true })++ expect(requestGatewayForAgent).toHaveBeenCalledWith('remote-tile', 'tile-profile', 'session.resume', {+ cols: 96,+ omit_messages: false,+ profile: 'backend-tile',+ session_id: 'stored-tile'+ })+ expect(getLatestSessionMessages).not.toHaveBeenCalled()+ expect(states.current.get('runtime-tile')).toMatchObject({ busy: true, model: 'snapshot-model', yolo: true })+ expect(JSON.stringify(states.current.get('runtime-tile')?.messages)).toContain('new answer')+ expect(states.current.get('runtime-tile')?.messages).toContainEqual(pending)+ expect($activeSessionId.get()).toBe('runtime-foreground')+ expect(takeSessionDraft('stored-tile').text).toBe('unsent tile draft')++ clearSessionDraft('stored-tile')+ $activeSessionId.set(null)+ $sessionTiles.set([])+ })++ it('serializes an authoritative gap snapshot after an omitted-message resume already in flight', async () => {+ const ownerRoute = { connectionId: 'remote-tile', profile: 'tile-profile', targetProfile: 'backend-tile' }+ const oldMessage = { id: 'old-user', parts: [{ type: 'text', text: 'old prompt' }], role: 'user' }++ const pending = {+ id: 'user-pending',+ parts: [{ type: 'text', text: 'local pending prompt' }],+ pending: true,+ role: 'user'+ }++ const warm = { busy: false, messages: [oldMessage, pending], storedSessionId: 'stored-tile' }+ const runtimeIdByStoredSessionIdRef = { current: new Map([['stored-tile', 'runtime-tile']]) }+ const states = { current: new Map([['runtime-tile', warm]]) }++ const update = vi.fn((id, updater) => {+ const next = updater(states.current.get(id))+ states.current.set(id, next)++ return next+ })++ let resolveNormal!: (value: unknown) => void+ let resolveAuthoritative!: (value: unknown) => void+ const normalResponse = new Promise(resolve => (resolveNormal = resolve))+ const authoritativeResponse = new Promise(resolve => (resolveAuthoritative = resolve))++ vi.mocked(requestGatewayForAgent).mockReset()+ vi.mocked(requestGatewayForAgent).mockImplementation(+ async (_connectionId, _profile, _method, params) =>+ (params?.omit_messages ? normalResponse : authoritativeResponse) as never+ )++ $activeSessionId.set('runtime-foreground')+ $sessionTiles.set([{ ownerRoute, runtimeId: 'runtime-tile', storedSessionId: 'stored-tile' }] as never)+ stashSessionDraft('stored-tile', 'unsent tile draft', [])+ renderTile(vi.fn(), {+ runtimeIdByStoredSessionIdRef,+ sessionStateByRuntimeIdRef: states,+ updateSessionState: update+ })++ const normal = singleFlightSessionResume('stored-tile', () =>+ requestGatewayForAgent('remote-tile', 'tile-profile', 'session.resume', {+ omit_messages: true,+ profile: 'backend-tile',+ session_id: 'stored-tile'+ })+ )++ await vi.waitFor(() => expect(requestGatewayForAgent).toHaveBeenCalledTimes(1))++ let authoritativeSettled = false++ const authoritative = sessionTileDelegate()!+ .resumeTile('stored-tile', { authoritativeSnapshot: true })+ .finally(() => (authoritativeSettled = true))++ await Promise.resolve()+ expect(requestGatewayForAgent).toHaveBeenCalledTimes(1)++ resolveNormal({ messages: [], resumed: 'stored-tile', session_id: 'runtime-tile' })+ await normal+ await Promise.resolve()+ expect(authoritativeSettled).toBe(false)+ expect(states.current.get('runtime-tile')?.messages).toEqual([oldMessage, pending])++ await vi.waitFor(() => expect(requestGatewayForAgent).toHaveBeenCalledTimes(2))+ expect(requestGatewayForAgent).toHaveBeenLastCalledWith('remote-tile', 'tile-profile', 'session.resume', {+ cols: 96,+ omit_messages: false,+ profile: 'backend-tile',+ session_id: 'stored-tile'+ })++ resolveAuthoritative({+ info: { model: 'snapshot-model' },+ messages: [+ { content: 'new prompt', role: 'user', timestamp: 1 },+ { content: 'new answer', role: 'assistant', timestamp: 2 }+ ],+ resumed: 'stored-tile',+ session_id: 'runtime-tile'+ })+ await authoritative++ expect(JSON.stringify(states.current.get('runtime-tile')?.messages)).toContain('new answer')+ expect(states.current.get('runtime-tile')?.messages).toContainEqual(pending)+ expect($activeSessionId.get()).toBe('runtime-foreground')+ expect(takeSessionDraft('stored-tile').text).toBe('unsent tile draft')++ clearSessionDraft('stored-tile')+ $activeSessionId.set(null)+ $sessionTiles.set([])+ })+it('merges persisted messages into a warm tile on explicit reopen (#96183)', async () => {const stateA = {busy: false,diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex 5ec8a4944c4..94eccc0ea28 100644--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@ -32,6 +32,7 @@ import {chatMessageArraysEquivalent,preserveLocalPendingTurnMessages,reconcileResumeMessages,+ resolveResumedBusy,resolveSessionOwner} from '../../session/hooks/use-session-actions/utils'import type { useSessionStateCache } from '../../session/hooks/use-session-state-cache'@@ -275,6 +276,7 @@ export function useSessionTileDelegate({const cached = existing ? sessionStateByRuntimeIdRef.current.get(existing) : undefinedconst refreshTranscript = options?.refreshTranscript === true+ const authoritativeSnapshot = options?.authoritativeSnapshot === true// Warm path: reuse a live binding — but only when it still carries a// transcript (or is mid-turn, where messages legitimately stream in).@@ -291,7 +293,8 @@ export function useSessionTileDelegate({existing &&cached?.storedSessionId === storedSessionId &&(cached.busy || cached.messages.length > 0) &&- !refreshTranscript+ !refreshTranscript &&+ !authoritativeSnapshot) {publishSessionState(existing, cached)@@ -310,9 +313,16 @@ export function useSessionTileDelegate({? { connectionId: owner.connectionId, profile: owner.targetProfile || owner.profile }: owner- const prefetchPromise = getLatestSessionMessages(storedSessionId, restScope).catch(() => null)+ const prefetchPromise = authoritativeSnapshot+ ? Promise.resolve(null)+ : getLatestSessionMessages(storedSessionId, restScope).catch(() => null)- if (existing && cached?.storedSessionId === storedSessionId && (cached.busy || cached.messages.length > 0)) {+ if (+ !authoritativeSnapshot &&+ existing &&+ cached?.storedSessionId === storedSessionId &&+ (cached.busy || cached.messages.length > 0)+ ) {const prefetch = await prefetchPromise// Deltas and completion may land while REST is in flight.updateSessionState(@@ -338,17 +348,23 @@ export function useSessionTileDelegate({() => {assertSessionOwnerResolved(owner, { method: 'session.resume', sessionId: storedSessionId })- return singleFlightSessionResume(storedSessionId, () =>- requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {- session_id: storedSessionId,- cols: 96,- omit_messages: true,- ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})- })+ return singleFlightSessionResume(+ storedSessionId,+ () =>+ requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {+ session_id: storedSessionId,+ cols: 96,+ omit_messages: !authoritativeSnapshot,+ ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})+ }),+ { requiresMessages: authoritativeSnapshot })},async () => {- const stored = (await prefetchPromise) ?? (await fetchStoredTranscriptAcrossBackends(storedSessionId))+ const stored =+ (await prefetchPromise) ??+ (await getLatestSessionMessages(storedSessionId, restScope).catch(() => null)) ??+ (await fetchStoredTranscriptAcrossBackends(storedSessionId))if (!stored) {throw new Error('stored transcript unavailable on every reachable backend')@@ -395,18 +411,42 @@ export function useSessionTileDelegate({updateSessionState(runtimeId,- state => ({- ...state,- busy: Boolean(info?.running),- // Persist the session's own model/provider from resume so the tile- // pill does not wait on a chrome-scoped catalog read (#93892).- ...(typeof info?.model === 'string' ? { model: info.model } : {}),- ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),- ...(typeof info?.reasoning_effort === 'string' ? { reasoningEffort: info.reasoning_effort } : {}),- ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),- messages:- state.messages.length > 0 ? state.messages : toChatMessages(prefetch?.messages ?? resumed?.messages ?? [])- }),+ state => {+ const previousMessages = state.messages.length > 0 ? state.messages : (cached?.messages ?? [])++ const messages = authoritativeSnapshot+ ? resumed.messages.length > 0+ ? mergeTileTranscript(previousMessages, resumed.messages, state.streamId ?? cached?.streamId)+ : previousMessages+ : previousMessages.length > 0+ ? previousMessages+ : toChatMessages(prefetch?.messages ?? resumed.messages ?? [])++ const busyChangedWhileResuming = cached+ ? Boolean(+ state.busy &&+ (state.turnStartedAt !== cached.turnStartedAt || (state.turnLive && !cached.turnLive))+ )+ : state.busy++ const running = resolveResumedBusy(resumed.running ?? info?.running, busyChangedWhileResuming)++ return {+ ...state,+ ...(typeof info?.branch === 'string' ? { branch: info.branch } : {}),+ ...(typeof info?.cwd === 'string' ? { cwd: info.cwd } : {}),+ ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),+ ...(typeof info?.model === 'string' ? { model: info.model } : {}),+ ...(typeof info?.personality === 'string' ? { personality: info.personality } : {}),+ ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),+ ...(typeof info?.reasoning_effort === 'string' ? { reasoningEffort: info.reasoning_effort } : {}),+ ...(typeof info?.service_tier === 'string' ? { serviceTier: info.service_tier } : {}),+ ...(typeof info?.yolo === 'boolean' ? { yolo: info.yolo } : {}),+ awaitingResponse: running && !resumed.inflight?.assistant,+ busy: running,+ messages+ }+ },storedSessionId)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.tsindex 16633910dce..6be79923510 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts@@ -11,7 +11,13 @@ import {setChangeEventsAvailable} from '@/store/live-sync'import { markRuntimeGone } from '@/store/runtime-gone'-import { dropSessionState, unbindTileRuntime } from '@/store/session-states'+import { getSessionOwnerHint, requestSessionResume } from '@/store/session'+import {+ $sessionTiles,+ dropSessionState,+ sessionTileDelegate,+ unbindTileRuntime+} from '@/store/session-states'// Leaf import (not the `@/themes` barrel) to avoid pulling the ThemeProvider// module graph into the gateway event hot path.import { ingestBackendSkin } from '@/themes/backend-sync'@@ -116,5 +122,43 @@ export function handleLifecycleEvent(ctx: GatewayEventContext): boolean {return true}+ if (event.type === 'session.replay_gap') {+ const runtimeId = event.session_id || ''++ const storedSessionId = runtimeId+ ? deps.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId+ : null++ const eventMatchesOwner = (owner: { connectionId: string; profile: string } | undefined) =>+ Boolean(+ owner &&+ event.connectionId === owner.connectionId &&+ (event.profile?.trim() || 'default') === (owner.profile.trim() || 'default')+ )++ if (storedSessionId && runtimeId === deps.activeSessionIdRef.current) {+ const ownerRoute = getSessionOwnerHint(storedSessionId, {+ connectionId: event.connectionId || '',+ profile: event.profile || 'default'+ })++ if (eventMatchesOwner(ownerRoute)) {+ requestSessionResume(storedSessionId, ownerRoute, { authoritativeSnapshot: true })++ return true+ }+ }++ const tile = $sessionTiles+ .get()+ .find(candidate => candidate.runtimeId === runtimeId && eventMatchesOwner(candidate.ownerRoute))++ if (tile) {+ void sessionTileDelegate()?.resumeTile(tile.storedSessionId, { authoritativeSnapshot: true }).catch(() => undefined)+ }++ return true+ }+return false}diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsxnew file mode 100644index 00000000000..69294b0f734--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/replay-gap.test.tsx@@ -0,0 +1,143 @@+import { act, cleanup, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { createClientSessionState } from '@/lib/chat-runtime'+import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'+import {+ $sessionResumeRequest,+ _resetSessionOwnerHintsForTests,+ setSessionOwnerHint+} from '@/store/session'+import {+ $sessionTiles,+ sessionTileDelegate,+ setSessionTileDelegate+} from '@/store/session-states'+import type { RpcEvent } from '@/types/hermes'++import { renderMessageStream } from './test-harness'++const replayGap = (+ sessionId: string,+ owner: { connectionId: string; profile: string }+): RpcEvent => ({+ ...owner,+ payload: { latest_seq: 41, replay_epoch: 'epoch-next' },+ session_id: sessionId,+ type: 'session.replay_gap'+}) as RpcEvent++const inertDelegate = () => ({+ archiveSession: vi.fn(async () => undefined),+ branchSession: vi.fn(async () => undefined),+ deleteSession: vi.fn(async () => undefined),+ executeSlash: vi.fn(async () => undefined),+ interruptSession: vi.fn(async () => undefined),+ resumeTile: vi.fn(async () => 'runtime-unused'),+ submitToSession: vi.fn(async () => undefined),+ updateSession: vi.fn(state => state)+})++describe('session.replay_gap recovery', () => {+ beforeEach(() => {+ $sessionResumeRequest.set(null)+ $sessionTiles.set([])+ _resetSessionOwnerHintsForTests()+ setSessionTileDelegate(inertDelegate() as never)+ })++ afterEach(() => {+ cleanup()+ clearSessionDraft('stored-active')+ clearSessionDraft('stored-tile')+ $sessionResumeRequest.set(null)+ $sessionTiles.set([])+ _resetSessionOwnerHintsForTests()+ })++ it('requests an authoritative resume for the affected active route without losing owner scope or its draft', () => {+ const ownerRoute = {+ connectionId: 'remote-a',+ mode: 'remote' as const,+ profile: 'desktop-profile',+ targetProfile: 'backend-profile'+ }++ const state = createClientSessionState('stored-active')++ setSessionOwnerHint('stored-active', ownerRoute)+ stashSessionDraft('stored-active', 'keep typing', [])++ const stream = renderMessageStream('runtime-active', {+ states: new Map([['runtime-active', state]])+ })++ act(() => stream.handleEvent(replayGap('runtime-active', ownerRoute)))++ expect($sessionResumeRequest.get()).toMatchObject({+ authoritativeSnapshot: true,+ ownerRoute,+ sessionId: 'stored-active'+ })+ expect(takeSessionDraft('stored-active').text).toBe('keep typing')+ })++ it('re-resumes the affected mounted tile for a gateway snapshot while retaining its owner and draft', async () => {+ const ownerRoute = {+ connectionId: 'remote-b',+ mode: 'remote' as const,+ profile: 'tile-profile',+ targetProfile: 'backend-tile-profile'+ }++ const resumeTile = vi.fn(async () => 'runtime-tile')+ const delegate = { ...inertDelegate(), resumeTile }+ const state = createClientSessionState('stored-tile')++ state.messages = [{+ id: 'pending-user',+ parts: [{ type: 'text', text: 'local pending prompt' }],+ pending: true,+ role: 'user'+ }]+ $sessionTiles.set([{ ownerRoute, runtimeId: 'runtime-tile', storedSessionId: 'stored-tile' }] as never)+ setSessionTileDelegate(delegate as never)+ stashSessionDraft('stored-tile', 'unsent tile draft', [])++ const stream = renderMessageStream('runtime-other', {+ states: new Map([['runtime-tile', state]])+ })++ act(() => stream.handleEvent(replayGap('runtime-tile', ownerRoute)))++ await waitFor(() =>+ expect(resumeTile).toHaveBeenCalledWith('stored-tile', { authoritativeSnapshot: true })+ )+ expect($sessionTiles.get()[0]?.ownerRoute).toEqual(ownerRoute)+ expect(takeSessionDraft('stored-tile').text).toBe('unsent tile draft')+ expect(sessionTileDelegate()).toBe(delegate)+ })++ it('ignores a colliding runtime id delivered by a different exact owner', () => {+ const ownerRoute = { connectionId: 'remote-a', profile: 'default' }+ const state = createClientSessionState('stored-active')+ const resumeTile = vi.fn(async () => 'runtime-collision')++ setSessionOwnerHint('stored-active', ownerRoute)+ $sessionTiles.set([+ { ownerRoute, runtimeId: 'runtime-collision', storedSessionId: 'stored-tile' }+ ] as never)+ setSessionTileDelegate({ ...inertDelegate(), resumeTile } as never)++ const stream = renderMessageStream('runtime-collision', {+ states: new Map([['runtime-collision', state]])+ })++ act(() =>+ stream.handleEvent(replayGap('runtime-collision', { connectionId: 'remote-b', profile: 'default' }))+ )++ expect($sessionResumeRequest.get()).toBeNull()+ expect(resumeTile).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.tsindex 96184ba35dc..9f9a9f41431 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/single-flight-resume.ts@@ -13,19 +13,33 @@* `session_id`); joiners receive whatever the winning call returns.*/-const _inFlightResumeByStoredSessionId = new Map<string, Promise<unknown>>()+interface SessionResumeFlight {+ includesMessages: boolean+ promise: Promise<unknown>+}++const _inFlightResumeByStoredSessionId = new Map<string, SessionResumeFlight>()-export function singleFlightSessionResume<T>(storedSessionId: string, run: () => Promise<T>): Promise<T> {+export function singleFlightSessionResume<T>(+ storedSessionId: string,+ run: () => Promise<T>,+ options?: { requiresMessages?: boolean }+): Promise<T> {const existing = _inFlightResumeByStoredSessionId.get(storedSessionId)- if (existing) {- return existing as Promise<T>+ if (existing && (!options?.requiresMessages || existing.includesMessages)) {+ return existing.promise as Promise<T>}// Promise.resolve().then(run) tolerates run() being synchronous, returning a// bare value, or throwing synchronously (test doubles and legacy callers do// all three) — a raw run().finally() would crash on a non-promise return.- const flight = Promise.resolve()+ // A message-bearing caller cannot join an omitted-message flight. Queue one+ // follow-up behind it instead: this preserves same-session ordering while+ // still letting all later callers join the stronger queued snapshot.+ const ready = existing ? existing.promise.then(() => undefined, () => undefined) : Promise.resolve()++ const promise = ready.then(run).finally(() => {if (_inFlightResumeByStoredSessionId.get(storedSessionId) === flight) {@@ -33,9 +47,14 @@ export function singleFlightSessionResume<T>(storedSessionId: string, run: () =>}})+ const flight: SessionResumeFlight = {+ includesMessages: options?.requiresMessages === true,+ promise+ }+_inFlightResumeByStoredSessionId.set(storedSessionId, flight)- return flight+ return promise}/**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.tsxindex fae23a9800a..de6aee2ce2c 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@@ -21,10 +21,20 @@ interface HarnessProps {freshDraftReady: booleangatewayState: stringlocationPathname: string- resumeSession: (sessionId: string, focus: boolean, ownerRoute?: SessionProfileRoute) => Promise<unknown>+ resumeSession: (+ sessionId: string,+ focus: boolean,+ ownerRoute?: SessionProfileRoute,+ options?: { authoritativeSnapshot?: boolean }+ ) => Promise<unknown>resumeFailedSessionId?: null | stringresumeExhaustedSessionId?: null | string- sessionResumeRequest?: null | { ownerRoute?: SessionProfileRoute; sequence: number; sessionId: string }+ sessionResumeRequest?: null | {+ authoritativeSnapshot?: boolean+ ownerRoute?: SessionProfileRoute+ sequence: number+ sessionId: string+ }routedSessionId: null | stringruntimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>selectedStoredSessionId: null | string@@ -140,6 +150,36 @@ describe('useRouteResume', () => {expect(resumeSession).toHaveBeenCalledWith('session-1', true)})+ it('forwards an authoritative snapshot request and its exact owner to resumeSession', () => {+ const resumeSession = vi.fn(async () => undefined)+ const ownerRoute = { connectionId: 'remote-a', profile: 'desktop', targetProfile: 'backend' }+ const activeSessionIdRef = { current: 'runtime-1' }+ const selectedStoredSessionIdRef = { current: 'session-1' }++ render(+ <RouteResumeHarness+ activeSessionId="runtime-1"+ activeSessionIdRef={activeSessionIdRef}+ creatingSessionRef={{ current: false }}+ currentView="chat"+ freshDraftReady={false}+ gatewayState="open"+ locationPathname="/session-1"+ resumeSession={resumeSession}+ routedSessionId="session-1"+ runtimeIdByStoredSessionIdRef={{ current: new Map([['session-1', 'runtime-1']]) }}+ selectedStoredSessionId="session-1"+ selectedStoredSessionIdRef={selectedStoredSessionIdRef}+ sessionResumeRequest={{ authoritativeSnapshot: true, ownerRoute, sequence: 1, sessionId: 'session-1' }}+ startFreshSessionDraft={vi.fn()}+ />+ )++ expect(resumeSession).toHaveBeenCalledWith('session-1', true, ownerRoute, {+ authoritativeSnapshot: true+ })+ })+it('self-heals a stranded routed session (null selected/active, same pathname, not a fresh draft)', () => {const resumeSession = vi.fn(async () => undefined)const startFreshSessionDraft = vi.fn()diff --git a/apps/desktop/src/app/session/hooks/use-route-resume.ts b/apps/desktop/src/app/session/hooks/use-route-resume.tsindex 631f10e0072..783496a43e0 100644--- a/apps/desktop/src/app/session/hooks/use-route-resume.ts+++ b/apps/desktop/src/app/session/hooks/use-route-resume.ts@@ -13,7 +13,12 @@ interface RouteResumeOptions {freshDraftReady: booleangatewayState: string | undefinedlocationPathname: string- resumeSession: (sessionId: string, focus: boolean, ownerRoute?: SessionProfileRoute) => Promise<unknown>+ resumeSession: (+ sessionId: string,+ focus: boolean,+ ownerRoute?: SessionProfileRoute,+ options?: { authoritativeSnapshot?: boolean }+ ) => Promise<unknown>// Stored-session id whose most recent resume failed terminally (set by// useSessionActions, mirrored from $resumeFailedSessionId). While this equals// routedSessionId the window would otherwise latch on the loader forever, so@@ -183,7 +188,9 @@ export function useRouteResume({const ownerRoute =sessionResumeRequest?.sessionId === routedSessionId ? sessionResumeRequest.ownerRoute : undefined- if (ownerRoute) {+ if (explicitlyRequested && sessionResumeRequest.authoritativeSnapshot) {+ void resumeSession(routedSessionId, true, ownerRoute, { authoritativeSnapshot: true })+ } else if (ownerRoute) {void resumeSession(routedSessionId, true, ownerRoute)} else {void resumeSession(routedSessionId, true)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 dbbb51d45ea..2eaddd0b4f3 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@@ -995,7 +995,12 @@ function ResumeHarness({onStateUpdate?: (sessionId: string, state: ClientSessionState) => voidonViewSync?: (sessionId: string, state: ClientSessionState) => voidonReady: (- resume: (storedSessionId: string, replaceRoute?: boolean, ownerRoute?: SessionProfileRoute) => Promise<unknown>+ resume: (+ storedSessionId: string,+ replaceRoute?: boolean,+ ownerRoute?: SessionProfileRoute,+ options?: { authoritativeSnapshot?: boolean }+ ) => Promise<unknown>) => voidrequestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>runtimeIdByStoredSessionIdRef?: MutableRefObject<Map<string, string>>@@ -2863,6 +2868,84 @@ describe('resumeSession warm-cache mapping integrity', () => {expect(runtimeIdByStoredSessionIdRef.current.get('stored-A')).toBe('rt-A')})+ it('forces a message-bearing resume over a warm cache for an authoritative replay-gap snapshot', async () => {+ const pending = {+ id: 'user-pending',+ parts: [{ type: 'text' as const, text: 'local pending prompt' }],+ pending: true,+ role: 'user' as const+ }++ const warm = clientState('stored-A')+ warm.messages = [+ { id: 'old-user', parts: [{ type: 'text', text: 'old prompt' }], role: 'user' },+ pending+ ]+ const runtimeIdByStoredSessionIdRef = { current: new Map([['stored-A', 'rt-A']]) }+ const sessionStateByRuntimeIdRef = { current: new Map([['rt-A', warm]]) }++ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ if (method !== 'session.resume') {+ throw new Error(`unexpected ${method}`)+ }++ expect(params).toMatchObject({+ defer_history: false,+ omit_messages: false,+ session_id: 'stored-A'+ })++ return {+ info: { model: 'snapshot-model', yolo: true },+ message_count: 2,+ messages: [+ { content: 'new prompt', role: 'user', timestamp: 1 },+ { content: 'new answer', role: 'assistant', timestamp: 2 }+ ],+ resumed: 'stored-A',+ running: true,+ session_id: 'rt-A'+ } as never+ })++ setSessions([storedSession({ id: 'stored-A', message_count: 2 })])+ setMessages(warm.messages)+ stashSessionDraft('stored-A', 'keep typing', [])++ let resume:+ | ((+ storedSessionId: string,+ replaceRoute?: boolean,+ ownerRoute?: SessionProfileRoute,+ options?: { authoritativeSnapshot?: boolean }+ ) => Promise<unknown>)+ | undefined++ render(+ <ResumeHarness+ onReady={value => (resume = value)}+ requestGateway={requestGateway}+ runtimeIdByStoredSessionIdRef={runtimeIdByStoredSessionIdRef}+ selectedStoredSessionId="stored-A"+ sessionStateByRuntimeIdRef={sessionStateByRuntimeIdRef}+ />+ )+ await waitFor(() => expect(resume).toBeDefined())+ await resume!('stored-A', true, undefined, { authoritativeSnapshot: true })++ expect(requestGateway.mock.calls.map(([method]) => method)).toEqual(['session.resume'])+ expect(getLatestSessionMessages).not.toHaveBeenCalled()+ expect(JSON.stringify($messages.get())).toContain('new answer')+ expect($messages.get()).toContainEqual(pending)+ expect(sessionStateByRuntimeIdRef.current.get('rt-A')).toMatchObject({+ busy: true,+ model: 'snapshot-model',+ yolo: true+ })+ expect(takeSessionDraft('stored-A').text).toBe('keep typing')+ clearSessionDraft('stored-A')+ })+it('re-arms a pending clarify in place on the warm session.activate path', async () => {const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {current: new Map([['stored-A', 'rt-A']])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 166fd086c1d..6d86b920ccd 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@@ -885,7 +885,12 @@ export function useSessionActions({}, [navigate, selectedStoredSessionId])const resumeSession = useCallback(- async (storedSessionId: string, replaceRoute = false, capturedOwner?: SessionProfileRoute) => {+ async (+ storedSessionId: string,+ replaceRoute = false,+ capturedOwner?: SessionProfileRoute,+ options?: { authoritativeSnapshot?: boolean }+ ) => {// 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@@ -1066,7 +1071,7 @@ export function useSessionActions({// purges a cross-wired mapping before we trust the fast-path.const warmHit = takeWarmCache()- if (warmHit) {+ if (warmHit && !options?.authoritativeSnapshot) {const cachedRuntimeId = warmHit.runtimeIdconst cachedState = warmHit.state@@ -1563,27 +1568,37 @@ export function useSessionActions({// max(prefetch, resume) instead of their sum. The prefetch paints the// transcript as soon as it lands; the RPC binds the runtime id.// Watch windows skip the prefetch — lazy resume attaches the live mirror.- const prefetchPromise = watchWindow ? null : getLatestSessionMessages(storedSessionId, sessionRestScope)+ const prefetchPromise =+ watchWindow || options?.authoritativeSnapshot+ ? null+ : getLatestSessionMessages(storedSessionId, sessionRestScope)let resumeRuntimeBaselineMessages: ChatMessage[] = []const resumeStartedAt = Date.now() / 1000- const resumePromise = singleFlightSessionResume(storedSessionId, () =>- requestForSession<SessionResumeResponse>('session.resume', {- session_id: storedSessionId,- cols: 96,- source: 'desktop',- defer_history: !watchWindow,- // REST is the transcript authority for Desktop. Avoid duplicating a- // potentially huge compression lineage in the WebSocket response.- // Watch windows attach lazily (live mirror). Every other cold resume- // gets the gateway's default deferred build: the RPC returns the- // transcript immediately instead of blocking the switch on _make_agent- // (MCP discovery / prompt build), and the agent pre-warms in the- // background while the prefetch above paints the transcript.- ...(watchWindow ? { lazy: true } : { omit_messages: true }),- ...(sessionProfile ? { profile: sessionProfile } : {})- })+ const resumePromise = singleFlightSessionResume(+ storedSessionId,+ () =>+ requestForSession<SessionResumeResponse>('session.resume', {+ session_id: storedSessionId,+ cols: 96,+ source: 'desktop',+ defer_history: options?.authoritativeSnapshot ? false : !watchWindow,+ // REST is the transcript authority for Desktop. Avoid duplicating a+ // potentially huge compression lineage in the WebSocket response.+ // Watch windows attach lazily (live mirror). Every other cold resume+ // gets the gateway's default deferred build: the RPC returns the+ // transcript immediately instead of blocking the switch on _make_agent+ // (MCP discovery / prompt build), and the agent pre-warms in the+ // background while the prefetch above paints the transcript.+ ...(options?.authoritativeSnapshot+ ? { omit_messages: false }+ : watchWindow+ ? { lazy: true }+ : { omit_messages: true }),+ ...(sessionProfile ? { profile: sessionProfile } : {})+ }),+ { requiresMessages: options?.authoritativeSnapshot }).then(resumed => {resumeRuntimeBaselineMessages =sessionStateByRuntimeIdRef.current.get(resumed.session_id)?.messages ?? resumeRuntimeBaselineMessages@@ -1655,6 +1670,10 @@ export function useSessionActions({const hasLiveProjection = Boolean(resumed.inflight || resumed.queued)const preferredMessages = (() => {+ if (options?.authoritativeSnapshot && resumed.messages.length === 0 && !hasLiveProjection) {+ return currentMessages+ }+if (prefetchApplied && prefetchMatchesResumedSession) {if (hasLiveProjection && prefetchedTranscriptMessages) {const runtimeMessages = toChatMessages(resumed.messages)diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 1679c086015..a98bc0ab426 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -1347,8 +1347,12 @@ export interface SessionTileDelegate {* the main view). Returns the runtime id, or throws.* `refreshTranscript` forces a REST merge even when a warm cached* transcript already exists — reopen-after-idle must not paint the- * snapshot that was current when the panel last had a socket. */- resumeTile(storedSessionId: string, options?: { refreshTranscript?: boolean }): Promise<string>+ * snapshot that was current when the panel last had a socket.+ * `authoritativeSnapshot` forces a message-bearing gateway resume. */+ resumeTile(+ storedSessionId: string,+ options?: { authoritativeSnapshot?: boolean; refreshTranscript?: boolean }+ ): Promise<string>/** Retire one runtime's busy/awaiting claim through the wiring cache* (updateSessionState), so cache, focused view, busyRef, and tile mirrors* settle together. Returns false when the cache holds no busy state fordiff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex 2e0a3bff126..d8522655408 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -871,6 +871,7 @@ export const $awaitingResponse = atom(false)// Null whenever the active route has a healthy (or in-flight) resume.export const $resumeFailedSessionId = atom<string | null>(null)export interface SessionResumeRequest {+ authoritativeSnapshot?: booleanownerRoute?: SessionOwnerRoutesequence: numbersessionId: string@@ -1287,7 +1288,11 @@ export const setMessages = (next: Updater<ChatMessage[]>) => updateAtom($messageexport const setFreshDraftReady = (next: Updater<boolean>) => updateAtom($freshDraftReady, next)export const setResumeFailedSessionId = (next: Updater<string | null>) => updateAtom($resumeFailedSessionId, next)-export const requestSessionResume = (sessionId: string, ownerRoute?: SessionOwnerRoute) => {+export const requestSessionResume = (+ sessionId: string,+ ownerRoute?: SessionOwnerRoute,+ options?: { authoritativeSnapshot?: boolean }+) => {const id = sessionId.trim()if (!id) {@@ -1309,6 +1314,7 @@ export const requestSessionResume = (sessionId: string, ownerRoute?: SessionOwne}$sessionResumeRequest.set({+ ...(options?.authoritativeSnapshot ? { authoritativeSnapshot: true } : {}),...(ownerRoute ? { ownerRoute: { ...ownerRoute } } : {}),sequence: ++sessionResumeRequestSequence,sessionId: id