The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): re-read the transcript after an idle reconnect resume
Tekniumd979c85ba93c
diff --git a/apps/desktop/src/app/session/hooks/reconnect-resume-barrier.test.tsx b/apps/desktop/src/app/session/hooks/reconnect-resume-barrier.test.tsxnew file mode 100644index 00000000000..f0edfa544b5--- /dev/null+++ b/apps/desktop/src/app/session/hooks/reconnect-resume-barrier.test.tsx@@ -0,0 +1,186 @@+import { QueryClient } from '@tanstack/react-query'+import { act, cleanup, renderHook } from '@testing-library/react'+import { useRef } from 'react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { getLatestSessionMessages } from '@/hermes'+import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'+import { resetInFlightTurnJournalStateForTests } from '@/lib/inflight-turn-journal'+import { $activeGatewayProfile } from '@/store/profile'+import {+ $messages,+ _resetSessionOwnerHintsForTests,+ setActiveSessionId,+ setAwaitingResponse,+ setBusy,+ setMessages,+ setSelectedStoredSessionId,+ setSessions+} from '@/store/session'+import { clearAllSessionStates } from '@/store/session-states'+import type { SessionMessage, SessionResumeResult } from '@/types/hermes'++import { useSessionActions } from './use-session-actions'+import { useSessionStateCache } from './use-session-state-cache'++vi.mock('@/hermes', async original => ({+ ...(await original<Record<string, unknown>>()),+ getLatestSessionMessages: vi.fn()+}))+vi.mock('@/store/profile', async original => ({+ ...(await original<Record<string, unknown>>()),+ ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)+}))++// The socket dropped while the answer after a tool streamed. The reconnect+// re-resumes cold: its REST page is read before `session.resume` rebinds the+// socket, the turn commits in between, and the tail and message.complete go to+// the dropped socket. Only the idle resume answer says the reply is durable.+const storedId = 'drop-stored'+const runtimeId = 'drop-runtime'++const call = { id: 'call-d', type: 'function', function: { name: 'terminal', arguments: '{}' } }++const beforeCommit: SessionMessage[] = [+ { id: 1, role: 'user', content: 'U1 warm up', timestamp: 10 },+ { id: 2, role: 'assistant', content: 'A1 first answer', timestamp: 11 },+ { id: 3, role: 'user', content: 'U2 across a drop', timestamp: 20 },+ { id: 4, role: 'assistant', content: 'A2i narrating', tool_calls: [call], timestamp: 21 },+ { id: 5, role: 'tool', content: 'core-d', tool_call_id: 'call-d', timestamp: 22 }+] as SessionMessage[]++const committed: SessionMessage[] = [+ ...beforeCommit,+ { id: 6, role: 'assistant', content: 'A2 answer across the drop', timestamp: 23 }+]++const streamingView: ChatMessage[] = [+ ...toChatMessages(beforeCommit.slice(0, 3)),+ {+ id: 'assistant-stream-d',+ role: 'assistant',+ parts: [+ { type: 'text', text: 'A2i narrating' },+ { type: 'tool-call', toolCallId: 'call-d', toolName: 'terminal', result: 'core-d' },+ { type: 'text', text: 'A2 ' }+ ],+ pending: true+ } as ChatMessage+]++const resumedIdle = {+ session_id: runtimeId,+ session_key: storedId,+ resumed: storedId,+ messages: [],+ messages_omitted: true,+ message_count: committed.length,+ running: false,+ info: {}+} as SessionResumeResult++function mount() {+ const requestGateway = vi.fn(async (method: string) => (method === 'session.resume' ? resumedIdle : {}))++ return renderHook(() => {+ const busyRef = useRef(false)+ useRef(new QueryClient())++ const cache = useSessionStateCache({+ activeSessionId: null,+ selectedStoredSessionId: storedId,+ busyRef,+ setMessages,+ setBusy,+ setAwaitingResponse+ })++ return useSessionActions({+ ...cache,+ activeSessionId: null,+ selectedStoredSessionId: storedId,+ busyRef,+ creatingSessionRef: useRef(false),+ getRouteToken: () => 'drop',+ getRoutedStoredSessionId: () => storedId,+ navigate: vi.fn(),+ requestGateway: requestGateway as never,+ routedSessionId: storedId+ })+ })+}++const answers = (messages: ChatMessage[]) =>+ messages.filter(message => message.role === 'assistant').map(message => chatMessageText(message).replace(/\s+/g, ''))++beforeEach(() => {+ localStorage.clear()+ clearAllSessionStates()+ resetInFlightTurnJournalStateForTests()+ _resetSessionOwnerHintsForTests()+ $activeGatewayProfile.set('default')+ setActiveSessionId(null)+ setSelectedStoredSessionId(storedId)+ setMessages(streamingView)+ setSessions([+ {+ id: storedId,+ title: storedId,+ source: 'desktop',+ message_count: beforeCommit.length,+ tool_call_count: 1,+ is_active: true,+ started_at: 1,+ last_active: 1,+ ended_at: null,+ model: null,+ preview: null,+ input_tokens: 0,+ output_tokens: 0+ }+ ])+ vi.mocked(getLatestSessionMessages).mockReset()+})++afterEach(() => {+ cleanup()+ clearAllSessionStates()+ resetInFlightTurnJournalStateForTests()+ localStorage.clear()+ setSessions([])+ setMessages([])+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ vi.restoreAllMocks()+})++it('shows the committed reply when the turn finishes between the reconnect page read and the resume', async () => {+ vi.mocked(getLatestSessionMessages)+ .mockResolvedValueOnce({ session_id: storedId, messages: beforeCommit })+ .mockResolvedValue({ session_id: storedId, messages: committed })++ const hook = mount()++ await act(async () => {+ await hook.result.current.resumeSession(storedId, true)+ })++ expect(answers($messages.get())).toEqual(['A1firstanswer', 'A2inarratingA2answeracrossthedrop'])+})++it('reads the page once when the resume still reports the turn running', async () => {+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: storedId, messages: beforeCommit })+ resumedIdle.running = true++ try {+ const hook = mount()++ await act(async () => {+ await hook.result.current.resumeSession(storedId, true)+ })++ expect(getLatestSessionMessages).toHaveBeenCalledTimes(1)+ } finally {+ resumedIdle.running = false+ }+})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 66b15966d0d..b6d16292d48 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,6 +167,7 @@ import {withoutEarlyClarifyProjection} from './restore-pending-clarify'import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'+import { type GraftedTranscriptPage, graftTranscriptPage, settlePrefetchAtResumeBarrier } from './resume-barrier-reread'import { clearResumeLatches, clearResumeToasts, notifyResumeFailed, type ResumeAttemptOptions } from './resume-latches'import {ambientResumeConnectionId,@@ -1974,6 +1975,7 @@ export function useSessionActions({let prefetchApplied = falselet prefetchedStoredSessionId: string | null = nulllet prefetchedTranscriptMessages: ChatMessage[] | null = null+ let prefetchedPage: GraftedTranscriptPage | null = null// REST transcript prefetch and the gateway resume RPC are independent// — run them concurrently so a big session's wall time is@@ -2051,18 +2053,9 @@ export function useSessionActions({: viewMessagesForReconcile()// Tail page + previously backfilled prefix (same-session re-resume).- // A long turn can push every rendered row off the newest page; read- // older pages until they overlap so the graft keeps earlier history.- const prefetchedTail = await extendRefreshPageToOverlap(- toChatMessages(prefetchedResult.messages),- previousMessages,- olderPageReader(storedSessionId, sessionRestScope, prefetchedResult)- )-- const graftedPrefetch = graftRefreshedTailOntoBackfill(prefetchedTail, previousMessages)-- prefetchedTranscriptMessages = graftedPrefetch- localSnapshot = reconcileAuthoritativeChatMessages(graftedPrefetch, previousMessages)+ prefetchedPage = await graftTranscriptPage(prefetchedResult, previousMessages, storedSessionId, sessionRestScope)+ prefetchedTranscriptMessages = prefetchedPage.transcript+ localSnapshot = prefetchedPage.snapshotprefetchApplied = trueprefetchedStoredSessionId = prefetchedResult.session_id || storedSessionId@@ -2074,6 +2067,13 @@ export function useSessionActions({const resumed = await resumePromise+ ;({ localSnapshot, prefetchedResult, prefetchedTranscriptMessages } = await settlePrefetchAtResumeBarrier(+ resumed,+ { localSnapshot, prefetchedPage, prefetchedResult, prefetchedTranscriptMessages },+ storedSessionId,+ sessionRestScope+ ))+if (!isCurrentResume()) {return}diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/resume-barrier-reread.ts b/apps/desktop/src/app/session/hooks/use-session-actions/resume-barrier-reread.tsnew file mode 100644index 00000000000..b039ec881f6--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-session-actions/resume-barrier-reread.ts@@ -0,0 +1,95 @@+import { extendRefreshPageToOverlap, graftRefreshedTailOntoBackfill, olderPageReader } from '@/app/chat/transcript-backfill'+import { getLatestSessionMessages, type ProfileScope } from '@/hermes'+import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'+import type { SessionMessagesResponse, SessionResumeResult } from '@/types/hermes'++import { reconcileDurableHistory } from './utils'++export interface GraftedTranscriptPage {+ page: SessionMessagesResponse+ /** The REST page grafted onto the view's older backfilled pages. */+ transcript: ChatMessage[]+ /** That transcript reconciled with the view's local rows. */+ snapshot: ChatMessage[]+}++/** Graft a newest-tail REST page onto the view: older pages kept, local tail reconciled. */+export async function graftTranscriptPage(+ page: SessionMessagesResponse,+ previousMessages: ChatMessage[],+ storedSessionId: string,+ scope: ProfileScope+): Promise<GraftedTranscriptPage> {+ // A long turn can push every rendered row off the newest page; read older+ // pages until they overlap so the graft keeps earlier history.+ const tail = await extendRefreshPageToOverlap(+ toChatMessages(page.messages),+ previousMessages,+ olderPageReader(storedSessionId, scope, page)+ )++ const transcript = graftRefreshedTailOntoBackfill(tail, previousMessages)++ return { page, transcript, snapshot: reconcileDurableHistory(transcript, previousMessages) }+}++/**+ * The cold resume reads REST concurrently with `session.resume`, so that read+ * can land BEFORE the resume rebinds this socket to the session. When the turn+ * commits in between, its tail and terminal frames go to the dropped socket:+ * the reconnect replay has already been answered, so the wire never delivers+ * them. The early page then lacks the committed reply, and the view keeps its+ * local stream row, stuck at the last streamed chunk. An idle resume answer+ * is the barrier (the reply is durable once it returns), so a snapshot whose+ * tail is still a local row is read once more.+ */+async function rereadPageAfterResumeBarrier(+ resumed: Pick<SessionResumeResult, 'inflight' | 'queued'> & { running?: boolean },+ early: GraftedTranscriptPage | null,+ storedSessionId: string,+ scope: ProfileScope+): Promise<GraftedTranscriptPage | null> {+ const tail = early?.snapshot.at(-1)++ if (!early || !tail || resumed.running !== false || resumed.inflight || resumed.queued) {+ return null+ }++ if (early.transcript.some(message => message.id === tail.id)) {+ return null+ }++ const page = await getLatestSessionMessages(storedSessionId, scope).catch(() => null)++ if (!page || (early.page.session_id && page.session_id && page.session_id !== early.page.session_id)) {+ return null+ }++ return graftTranscriptPage(page, early.snapshot, storedSessionId, scope)+}++export interface ColdPrefetchState {+ localSnapshot: ChatMessage[]+ prefetchedPage: GraftedTranscriptPage | null+ prefetchedResult: SessionMessagesResponse | null+ prefetchedTranscriptMessages: ChatMessage[] | null+}++/** The cold resume's prefetch state once the resume answered: re-read past the barrier when it raced the commit. */+export async function settlePrefetchAtResumeBarrier(+ resumed: Pick<SessionResumeResult, 'inflight' | 'queued'> & { running?: boolean },+ state: ColdPrefetchState,+ storedSessionId: string,+ scope: ProfileScope+): Promise<ColdPrefetchState> {+ const reread = await rereadPageAfterResumeBarrier(resumed, state.prefetchedPage, storedSessionId, scope)++ return reread+ ? {+ localSnapshot: reread.snapshot,+ prefetchedPage: reread,+ prefetchedResult: reread.page,+ prefetchedTranscriptMessages: reread.transcript+ }+ : state+}