fix(desktop): cold resume paints the prefetched REST transcript before session.resume settles

The REST prefetch and the gateway `session.resume` already ran concurrently,
but the prefetch result was held until the runtime resume settled. A cold
profile build (skills / MCP / memory) can keep `session.resume` pending past
the hydration budget while the complete transcript is already in hand, so a
Bot Chat sat on the loader and burned its retries with readable history
off screen.

- Publish the grafted REST snapshot as soon as the prefetch resolves and
  `isCurrentResume()` holds; the runtime path grafts only its live projection
  onto that same snapshot, and the post-resume `chatMessageArraysEquivalent`
  skip keeps reference identity when nothing changed (no second DOM build).
- Stamp the eagerly painted page with persisted-display provenance on the
  runtime state so the warm-path gate admits it on the next switch.
- REST fallback after a resume rejection skips the redundant re-publish when
  the early paint already shows the transcript.

Live repro (Electron e2e, session.resume stalled 25s via a temporary
backend shim): main never painted within 20s; with this fix the transcript
painted 150ms after the row click.

Supersedes #90130.

Co-authored-by: Alexandre Roumieu <269586168+alexandreroumieu-codeapprentice@users.noreply.github.com>
This commit is contained in:
Teknium
2026-09-02 04:23:40 -07:00
parent 000d6efd09
commit ad800ea8cd
2 changed files with 78 additions and 14 deletions
@@ -1269,6 +1269,44 @@ describe('resumeSession failure recovery', () => {
expect($messages.get().length).toBeGreaterThan(0)
})
it('paints the REST transcript before a cold session.resume settles and keeps it when resume rejects', async () => {
// A cold profile build (skills/MCP/memory) can keep session.resume pending
// past the hydration budget; the already-available REST history must not
// wait for it (#90130), and a later resume failure must not blank it.
const runtimeResume = deferred<never>()
const requestGateway = vi.fn((method: string) =>
method === 'session.resume' ? runtimeResume.promise : Promise.resolve({} as never)
) as <T>(method: string, params?: Record<string, unknown>) => Promise<T>
vi.mocked(getLatestSessionMessages).mockResolvedValue({
messages: [
{ content: 'older question', role: 'user', timestamp: 1 },
{ content: 'history visible before runtime', role: 'assistant', timestamp: 2 }
],
session_id: 'stored-1'
} as never)
let resume: ((storedSessionId: string, replaceRoute?: boolean) => Promise<unknown>) | null = null
render(<ResumeHarness onReady={r => (resume = r)} requestGateway={requestGateway} />)
await waitFor(() => expect(resume).not.toBeNull())
let settled = false
const pending = resume!('stored-1', true).finally(() => (settled = true))
await waitFor(() => expect(JSON.stringify($messages.get())).toContain('history visible before runtime'))
expect(settled).toBe(false)
const painted = $messages.get()
await act(async () => {
runtimeResume.reject(new Error('request timed out: session.resume'))
await pending
})
expect($messages.get()).toBe(painted)
expect($resumeFailedSessionId.get()).toBeNull()
})
it('preserves an optimistic user message during a same-session reconnect', async () => {
setMessages([
{
@@ -2678,7 +2716,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
expect(sessionStateByRuntimeIdRef.current.has('rt-recycled')).toBe(false)
})
it('paints the bounded latest transcript after the deferred resume acknowledgement', async () => {
it('paints the bounded latest transcript before the deferred resume acknowledgement without rebuilding it', async () => {
const latestPage = Array.from({ length: 500 }, (_, index) => ({
content: `message-${index}`,
role: index % 2 === 0 ? ('user' as const) : ('assistant' as const),
@@ -2713,7 +2751,8 @@ describe('resumeSession warm-cache mapping integrity', () => {
await waitFor(() => expect(getLatestSessionMessages).toHaveBeenCalledTimes(1))
expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-A', undefined)
expect($messages.get()).toHaveLength(0)
await waitFor(() => expect($messages.get()).toHaveLength(500))
const paintedTranscript = $messages.get()
expect(requestGatewayMock).toHaveBeenCalledWith(
'session.resume',
expect.objectContaining({
@@ -2731,7 +2770,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
info: {}
})
await resumePromise
expect($messages.get()).toHaveLength(500)
expect($messages.get()).toBe(paintedTranscript)
})
it('honours a warm cache entry whose stored id matches and refreshes its persisted transcript', async () => {
@@ -1547,9 +1547,6 @@ export function useSessionActions({
// keeps it from surfacing as unhandled while the prefetch settles.
resumePromise.catch(() => undefined)
// Keep both requests concurrent, but do not paint the REST result until
// the runtime resume has also settled. An eager prefetch paint followed
// by the runtime projection rebuilds large transcripts during resume.
let prefetchedResult: { messages: SessionMessage[]; session_id?: string } | null = null
try {
@@ -1560,13 +1557,15 @@ export function useSessionActions({
// Non-fatal: gateway resume below can still hydrate the session.
}
const resumed = await resumePromise
if (!isCurrentResume()) {
return
}
if (prefetchedResult) {
// Paint the persisted transcript as soon as REST returns instead of
// holding it until the runtime resume settles. A cold profile build
// (skills, MCP, memory) can keep `session.resume` pending far longer
// than the hydration budget while the complete history is already in
// hand — holding it stranded Bot Chats on the loader (#90130). The
// runtime path below grafts only its live projection onto this same
// snapshot, so an unchanged acknowledgement keeps reference identity
// and never rebuilds the transcript a second time.
if (prefetchedResult && isCurrentResume()) {
const previousMessages = resumedSameSelectedSession
? preserveLocalPendingTurnMessages(viewMessagesForReconcile(), resumeStartMessages)
: viewMessagesForReconcile()
@@ -1581,6 +1580,16 @@ export function useSessionActions({
localSnapshot = reconcileAuthoritativeChatMessages(graftedPrefetch, previousMessages)
prefetchApplied = true
prefetchedStoredSessionId = prefetchedResult.session_id || storedSessionId
if (!chatMessageArraysEquivalent($messages.get(), localSnapshot)) {
setMessages(localSnapshot)
}
}
const resumed = await resumePromise
if (!isCurrentResume()) {
return
}
const currentMessages = viewMessagesForReconcile()
@@ -1747,12 +1756,25 @@ export function useSessionActions({
const visibleMessagesForView =
pendingClarifyProjection?.messages ?? clearedClarifyProjection?.messages ?? messagesForView
// The eagerly painted REST page is persisted-display authority: stamp
// its provenance so the next warm switch to this session paints it
// immediately instead of holding it as an unproven runtime tail.
const transcriptProvenance =
prefetchApplied && prefetchMatchesResumedSession && stored
? createPersistedDisplayTranscriptProvenance({
lineageRootId: stored._lineage_root_id ?? null,
scope: sessionRestScope,
storedSessionId
})
: undefined
updateSessionState(
resumed.session_id,
state => ({
...state,
...(runtimeInfo ?? {}),
messages: visibleMessagesForView,
transcriptProvenance,
busy: resumedRunning,
awaitingResponse: resumedRunning && !recoveredInFlightTail,
// Backend reported this turn running at resume time — live proof.
@@ -1840,7 +1862,10 @@ export function useSessionActions({
reconcileAuthoritativeMessages(fallback.messages, previousMessages)
)
setMessages(fallbackRecovery.messages)
// The eager prefetch paint above may already show this transcript.
if (!chatMessageArraysEquivalent($messages.get(), fallbackRecovery.messages)) {
setMessages(fallbackRecovery.messages)
}
} catch (e) {
// Fallback also failed: nothing to paint. Leave whatever messages are
// already shown and fall through to arm the resume-failure latch so