Skip to content

The agent that grows with you

fix(desktop): a cold resume paints its snapshot over an older prefetch page

Tekniumd0523fd667b9
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.tsx
index f0edfa544b5..e02dd8e4559 100644
--- a/apps/desktop/src/app/session/hooks/reconnect-resume-barrier.test.tsx
+++ b/apps/desktop/src/app/session/hooks/reconnect-resume-barrier.test.tsx
@@ -184,3 +184,23 @@ it('reads the page once when the resume still reports the turn running', async (
resumedIdle.running = false
}
})
+
+// The authority pushes the missed tail and message.complete before it answers
+// the resume, and that answer still says running with the committed row in its
+// snapshot. The page read before the commit must not win over it.
+it('paints the resume snapshot over an older prefetch page while the turn still reports running', async () => {
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: storedId, messages: beforeCommit })
+ Object.assign(resumedIdle, { running: true, messages: committed, messages_omitted: false })
+
+ try {
+ const hook = mount()
+
+ await act(async () => {
+ await hook.result.current.resumeSession(storedId, true)
+ })
+
+ expect(answers($messages.get())).toEqual(['A1firstanswer', 'A2inarratingA2answeracrossthedrop'])
+ } finally {
+ Object.assign(resumedIdle, { running: false, messages: [], messages_omitted: true })
+ }
+})
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 b6d16292d48..84a9716b76f 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,12 @@ import {
withoutEarlyClarifyProjection
} from './restore-pending-clarify'
import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'
-import { type GraftedTranscriptPage, graftTranscriptPage, settlePrefetchAtResumeBarrier } from './resume-barrier-reread'
+import {
+ type GraftedTranscriptPage,
+ graftTranscriptPage,
+ prefetchServesResume,
+ settlePrefetchAtResumeBarrier
+} from './resume-barrier-reread'
import { clearResumeLatches, clearResumeToasts, notifyResumeFailed, type ResumeAttemptOptions } from './resume-latches'
import {
ambientResumeConnectionId,
@@ -2080,15 +2085,10 @@ export function useSessionActions({
const currentMessages = viewMessagesForReconcile()
- // Keep the local snapshot when resume would only reshuffle runtime
- // projection. When the REST prefetch already hydrated the transcript,
- // skip converting/reconciling the resume payload entirely — on a
- // 1000+-message session that second conversion plus the deep
- // equivalence compare costs over a second of main-thread time.
- const resumedStoredSessionId = resumed.session_key || resumed.resumed
-
- const prefetchMatchesResumedSession =
- !prefetchedStoredSessionId || !resumedStoredSessionId || prefetchedStoredSessionId === resumedStoredSessionId
+ // A current prefetch skips converting the resume payload (over a second
+ // on a 1000+-message session); a page older than the resume snapshot
+ // (it lacks a durable row the resume carries) yields to that snapshot.
+ const prefetchMatchesResumedSession = prefetchServesResume(prefetchedStoredSessionId, resumed, prefetchedResult)
const hasLiveProjection = Boolean(resumed.inflight || resumed.queued)
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.ts
index b039ec881f6..ca2fc145181 100644
--- 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.ts
@@ -1,7 +1,11 @@
-import { extendRefreshPageToOverlap, graftRefreshedTailOntoBackfill, olderPageReader } from '@/app/chat/transcript-backfill'
+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 type { SessionMessage, SessionMessagesResponse, SessionResumeResult } from '@/types/hermes'
import { reconcileDurableHistory } from './utils'
@@ -35,23 +39,23 @@ export async function graftTranscriptPage(
/**
* 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.
+ * can land before the turn commits. The early page then lacks the committed
+ * reply, and the view keeps its local stream row, stuck at the last streamed
+ * chunk. A resume carrying its snapshot settles that by row recency
+ * (`prefetchServesResume`); one that omits it (`omit_messages` honoured) only
+ * says the turn is idle. That idle 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 },
+ resumed: Pick<SessionResumeResult, 'inflight' | 'messages' | '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) {
+ if (!early || !tail || resumed.running !== false || resumed.inflight || resumed.queued || resumed.messages?.length) {
return null
}
@@ -77,7 +81,7 @@ export interface ColdPrefetchState {
/** 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 },
+ resumed: Pick<SessionResumeResult, 'inflight' | 'messages' | 'queued'> & { running?: boolean },
state: ColdPrefetchState,
storedSessionId: string,
scope: ProfileScope
@@ -93,3 +97,41 @@ export async function settlePrefetchAtResumeBarrier(
}
: state
}
+
+const durableRowId = ({ id, row_id }: SessionMessage): number | undefined => {
+ const value = row_id ?? id
+
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
+}
+
+const newestDurableRowId = (messages: readonly SessionMessage[] | null | undefined): number =>
+ (messages ?? []).reduce((newest, message) => Math.max(newest, durableRowId(message) ?? -Infinity), -Infinity)
+
+/**
+ * The resume snapshot is newer than the cold prefetch page when it carries a
+ * durable row the page had not stored yet. Frames that landed while the resume
+ * was in flight (the authority pushes a reconnected viewer's missed tail before
+ * it answers) are already in that snapshot, while the page was read before the
+ * turn committed: painting the page would put the stream row back at its first
+ * chunk. Rows are compared by durable id, never by which request returned first.
+ */
+function resumeSnapshotSupersedesPage(
+ resumedMessages: readonly SessionMessage[] | undefined,
+ pageMessages: readonly SessionMessage[] | null | undefined
+): boolean {
+ const pageNewest = newestDurableRowId(pageMessages)
+
+ return Number.isFinite(pageNewest) && newestDurableRowId(resumedMessages) > pageNewest
+}
+
+/** The cold prefetch page still speaks for the resumed session: same session, and no newer than its snapshot. */
+export function prefetchServesResume(
+ pageSessionId: string | null,
+ resumed: Pick<SessionResumeResult, 'messages' | 'resumed' | 'session_key'>,
+ page: SessionMessagesResponse | null
+): boolean {
+ const resumedSessionId = resumed.session_key || resumed.resumed
+ const sameSession = !pageSessionId || !resumedSessionId || pageSessionId === resumedSessionId
+
+ return sameSession && !resumeSnapshotSupersedesPage(resumed.messages, page?.messages)
+}