Skip to content

The agent that grows with you

fix(desktop): retain scoped transcript paint through background hydration

brooklyn!76f9bf948bea
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.tsx
index 935c65df917..ec19503dfad 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
@@ -24,7 +24,14 @@ import { $clarifyRequests, clearClarifyRequest, setClarifyRequest } from '@/stor
import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'
import { $pinnedSessionIds } from '@/store/layout'
-import { $activeGatewayProfile, $newChatProfile, $newChatRoute, $profiles, ensureGatewayProfile } from '@/store/profile'
+import {
+ $activeGatewayProfile,
+ $newChatProfile,
+ $newChatRoute,
+ $profiles,
+ ensureGatewayAgent,
+ ensureGatewayProfile
+} from '@/store/profile'
import { $projectScope, $projectTree, ALL_PROJECTS } from '@/store/projects'
import {
$activeSessionId,
@@ -78,6 +85,7 @@ import {
sessionTileOwnerRoute
} from '@/store/session-states'
import { $sessionSeenCounts, $unreadFinishedMarkers } from '@/store/session-unread'
+import { loadTranscriptTail, saveTranscriptTail } from '@/store/transcript-tail-cache'
import sessionResumeActiveTurn from '../../../../../../tests/fixtures/session-resume-active-turn.json'
import { deferred } from '../../../test/deferred'
@@ -973,11 +981,13 @@ function ResumeHarness({
onStateUpdate,
onViewSync,
onReady,
+ getRouteToken = () => 'token',
requestGateway,
runtimeIdByStoredSessionIdRef,
selectedStoredSessionId = null,
sessionStateByRuntimeIdRef
}: {
+ getRouteToken?: () => string
onStateUpdate?: (sessionId: string, state: ClientSessionState) => void
onViewSync?: (sessionId: string, state: ClientSessionState) => void
onReady: (
@@ -998,7 +1008,7 @@ function ResumeHarness({
busyRef: ref(false),
creatingSessionRef: ref(false),
ensureSessionState: () => ({}) as ClientSessionState,
- getRouteToken: () => 'token',
+ getRouteToken,
getRoutedStoredSessionId: () => null,
navigate: vi.fn() as never,
requestGateway,
@@ -2511,6 +2521,225 @@ describe('resumeSession warm-cache mapping integrity', () => {
vi.restoreAllMocks()
})
+ it('does not reclaim the foreground when route intent changes during a gateway dial', async () => {
+ const gatewayReady = deferred<void>()
+ vi.mocked(ensureGatewayProfile).mockReturnValueOnce(gatewayReady.promise)
+ setSessions([storedSession({ id: 'stored-dial', profile: 'work' })])
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ messages: [], session_id: 'stored-dial' })
+ const requestGateway = vi.fn(async () => ({ session_id: 'rt-dial', messages: [], info: {} }) as never)
+ let token = 'route-A'
+ let resume!: Parameters<Parameters<typeof ResumeHarness>[0]['onReady']>[0]
+ render(
+ <ResumeHarness getRouteToken={() => token} onReady={ready => (resume = ready)} requestGateway={requestGateway} />
+ )
+ const pending = resume('stored-dial', true)
+ await waitFor(() => expect(ensureGatewayProfile).toHaveBeenCalledWith('work'))
+ token = 'route-B'
+
+ const foreground = [
+ { id: 'new-intent', role: 'assistant' as const, parts: [{ type: 'text' as const, text: 'new route' }] }
+ ]
+
+ setMessages(foreground)
+ gatewayReady.resolve()
+ await pending
+ expect($messages.get()).toBe(foreground)
+ expect(requestGateway).not.toHaveBeenCalled()
+ })
+
+ it.each([false, true])(
+ 'caches a cold display read only while its target is unchanged (invalidated=%s)',
+ async invalidated => {
+ const persistedA = deferred<Awaited<ReturnType<typeof getLatestSessionMessages>>>()
+ const resumedA = deferred<SessionResumeResult>()
+ const owner = { connectionId: 'remote-background', profile: 'work' }
+
+ const rowA = storedSession({
+ id: 'stored-background-A',
+ profile: 'work',
+ connection_id: owner.connectionId,
+ message_count: 1
+ })
+
+ const rowB = storedSession({
+ id: 'stored-background-B',
+ profile: 'work',
+ connection_id: owner.connectionId,
+ message_count: 1
+ })
+
+ const stateMap = { current: new Map<string, ClientSessionState>() }
+ const runtimeMap = { current: new Map<string, string>() }
+ setSessions([rowA, rowB])
+ vi.mocked(getLatestSessionMessages).mockImplementation(id =>
+ id === rowA.id
+ ? persistedA.promise
+ : Promise.resolve({
+ messages: [{ role: 'assistant', content: 'foreground B', timestamp: 1 }],
+ session_id: id
+ })
+ )
+ vi.mocked(requestGatewayForAgent).mockImplementation(async (_connection, _profile, _method, params) =>
+ params?.session_id === rowA.id
+ ? resumedA.promise
+ : {
+ session_id: 'rt-background-B',
+ resumed: rowB.id,
+ session_key: rowB.id,
+ messages: [],
+ messages_omitted: true,
+ message_count: 1,
+ running: false,
+ info: {}
+ }
+ )
+ let resume!: Parameters<Parameters<typeof ResumeHarness>[0]['onReady']>[0]
+ render(
+ <ResumeHarness
+ onReady={ready => (resume = ready)}
+ requestGateway={vi.fn()}
+ runtimeIdByStoredSessionIdRef={runtimeMap}
+ sessionStateByRuntimeIdRef={stateMap}
+ />
+ )
+ const pending = resume(rowA.id, true, owner)
+ await waitFor(() => expect(getLatestSessionMessages).toHaveBeenCalledWith(rowA.id, owner))
+ await resume(rowB.id, true, owner)
+ const foreground = $messages.get()
+
+ if (invalidated) {
+ // A rebind/edit established newer runtime authority while the original
+ // cold read was pending; its old display must not repopulate the cache.
+ stateMap.current.set('rt-background-A', { ...clientState(rowA.id), transcriptAuthorityEpoch: 1 })
+ runtimeMap.current.set(rowA.id, 'rt-background-A')
+ }
+
+ try {
+ persistedA.resolve({
+ messages: [{ role: 'assistant', content: 'durable background A', timestamp: 1 }],
+ session_id: rowA.id
+ })
+
+ if (invalidated) {
+ resumedA.resolve({ session_id: 'rt-background-A', resumed: rowA.id, messages: [], info: {} } as never)
+ await pending
+ expect(loadTranscriptTail(rowA.id, owner)).toBeNull()
+ } else {
+ await waitFor(() =>
+ expect(JSON.stringify(loadTranscriptTail(rowA.id, owner))).toContain('durable background A')
+ )
+ }
+
+ expect($messages.get()).toBe(foreground)
+ expect($activeSessionId.get()).toBe('rt-background-B')
+ expect(loadTranscriptTail(rowA.id, 'work')).toBeNull()
+ } finally {
+ resumedA.resolve({ session_id: 'rt-background-A', resumed: rowA.id, messages: [], info: {} } as never)
+ await pending
+ window.localStorage.clear()
+ }
+ }
+ )
+
+ it.each([false, true])(
+ 'paints the exact provisional scope as soon as its owner is known (metadataOnly=%s)',
+ async metadataOnly => {
+ const ownerRoute: SessionProfileRoute = {
+ connectionId: 'remote-linux',
+ profile: 'default',
+ targetProfile: 'work'
+ }
+
+ const storedLookup = deferred<SessionInfo>()
+ const gatewayReady = deferred<void>()
+ const persisted = deferred<Awaited<ReturnType<typeof getLatestSessionMessages>>>()
+ const resumed = deferred<SessionResumeResult>()
+
+ const cachedMessages = [
+ {
+ id: 'cached-answer',
+ role: 'assistant' as const,
+ parts: [{ type: 'text' as const, text: 'cached display history' }]
+ }
+ ]
+
+ window.localStorage.clear()
+
+ if (metadataOnly) {
+ setConnection({ mode: 'remote', connectionId: 'remote-linux' } as never)
+ saveTranscriptTail('stored-first-paint', [{ ...cachedMessages[0], id: 'guessed-default' }], {
+ connectionId: 'remote-linux',
+ profile: 'default'
+ })
+ }
+
+ saveTranscriptTail('stored-first-paint', cachedMessages, { connectionId: 'remote-linux', profile: 'work' })
+ saveTranscriptTail('stored-first-paint', [{ ...cachedMessages[0], id: 'wrong-owner' }], 'work')
+ vi.mocked(getSession).mockReturnValue(storedLookup.promise)
+ vi.mocked(ensureGatewayAgent).mockClear().mockReturnValueOnce(gatewayReady.promise)
+ vi.mocked(getLatestSessionMessages).mockReturnValue(persisted.promise)
+ vi.mocked(requestGatewayForAgent).mockReturnValue(resumed.promise)
+ const requestGateway = vi.fn(async () => ({}) as never)
+ let resume!: Parameters<Parameters<typeof ResumeHarness>[0]['onReady']>[0]
+ render(<ResumeHarness onReady={ready => (resume = ready)} requestGateway={requestGateway} />)
+
+ const pending = resume('stored-first-paint', true, metadataOnly ? undefined : ownerRoute)
+
+ try {
+ expect($messages.get()).toEqual(metadataOnly ? [] : cachedMessages)
+ expect(requestGatewayForAgent).not.toHaveBeenCalled()
+ storedLookup.resolve(
+ storedSession({ id: 'stored-first-paint', connection_id: 'remote-linux', profile: 'work', message_count: 1 })
+ )
+ await waitFor(() =>
+ expect(ensureGatewayAgent).toHaveBeenCalledWith('remote-linux', metadataOnly ? 'work' : 'default')
+ )
+ expect($messages.get()).toEqual(cachedMessages)
+ gatewayReady.resolve()
+ await waitFor(() =>
+ expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-first-paint', {
+ connectionId: 'remote-linux',
+ profile: 'work'
+ })
+ )
+ const provisional = $messages.get()
+ expect(provisional).toEqual(cachedMessages)
+ persisted.resolve({
+ messages: [{ role: 'assistant', content: 'fresh persisted history', timestamp: 1 }],
+ session_id: 'stored-first-paint'
+ })
+ await waitFor(() => expect(JSON.stringify($messages.get())).toContain('fresh persisted history'))
+ expect($messages.get()).not.toBe(provisional)
+ const authoritative = $messages.get()
+ resumed.resolve({
+ session_id: 'runtime-first-paint',
+ resumed: 'stored-first-paint',
+ session_key: 'stored-first-paint',
+ messages: [],
+ messages_omitted: true,
+ message_count: 1,
+ running: false,
+ info: {}
+ })
+ await pending
+ expect($messages.get()).toBe(authoritative)
+ expect(JSON.stringify($messages.get())).not.toContain('cached display history')
+ } finally {
+ storedLookup.resolve(storedSession({ id: 'stored-first-paint', profile: 'work', message_count: 1 }))
+ gatewayReady.resolve()
+ persisted.resolve({ messages: [], session_id: 'stored-first-paint' })
+ resumed.resolve({
+ session_id: 'runtime-first-paint',
+ resumed: 'stored-first-paint',
+ messages: [],
+ info: {}
+ } as never)
+ await pending
+ window.localStorage.clear()
+ }
+ }
+ )
+
it('pins an untagged row to the active registry connection instead of the same-named local profile', async () => {
setConnection({ connectionId: 'hermes01', mode: 'remote' } as never)
setSessions([storedSession({ id: 'remote-stored', profile: 'default' })])
@@ -3138,6 +3367,111 @@ describe('resumeSession warm-cache mapping integrity', () => {
expect($clarifyRequests.get()['rt-A']).toMatchObject({ requestId: 'req-newer' })
})
+ it.each(['none', 'epoch', 'lineage', 'route', 'messaging'] as const)(
+ 'settles background display hydration only for its original authority (invalidated=%s)',
+ async invalidated => {
+ const runtimeMap = { current: new Map([['stored-A', 'rt-A']]) }
+ const original = clientState('stored-A')
+ original.messages = [{ id: 'partial', role: 'assistant', parts: [{ type: 'text', text: 'old partial' }] }]
+ const stateMap = { current: new Map([['rt-A', original]]) }
+ const persistedA = deferred<Awaited<ReturnType<typeof getLatestSessionMessages>>>()
+ setSessions([
+ storedSession({ id: 'stored-A', message_count: 1 }),
+ storedSession({ id: 'stored-B', message_count: 1 })
+ ])
+
+ if (invalidated === 'messaging') {
+ setMessagingSessions([$sessions.get()[0]])
+ setSessions(rows => rows.filter(row => row.id !== 'stored-A'))
+ }
+
+ vi.mocked(getLatestSessionMessages).mockImplementation(id =>
+ id === 'stored-A'
+ ? persistedA.promise
+ : Promise.resolve({
+ messages: [{ role: 'assistant', content: 'foreground B', timestamp: 1 }],
+ session_id: id
+ })
+ )
+
+ const requestGateway = vi.fn(
+ async (method: string) =>
+ ({
+ session_id: method === 'session.activate' ? 'rt-A' : 'rt-B',
+ session_key: method === 'session.activate' ? 'stored-A' : 'stored-B',
+ resumed: method === 'session.activate' ? 'stored-A' : 'stored-B',
+ messages: [],
+ messages_omitted: true,
+ message_count: 1,
+ running: false,
+ info: {}
+ }) as never
+ )
+
+ let resume!: Parameters<Parameters<typeof ResumeHarness>[0]['onReady']>[0]
+ const views: string[] = []
+ let route = 'A'
+ render(
+ <ResumeHarness
+ getRouteToken={() => route}
+ onReady={ready => (resume = ready)}
+ onStateUpdate={(id, state) => {
+ // updateSessionState normally syncs the active runtime itself.
+ if ($activeSessionId.get() === id) {
+ setMessages(state.messages)
+ }
+ }}
+ onViewSync={id => views.push(id)}
+ requestGateway={requestGateway}
+ runtimeIdByStoredSessionIdRef={runtimeMap}
+ sessionStateByRuntimeIdRef={stateMap}
+ />
+ )
+ const pending = resume('stored-A', true)
+ await waitFor(() => expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-A', undefined))
+
+ if (invalidated === 'route') {
+ route = 'B'
+ setMessages([{ id: 'route-B', role: 'assistant', parts: [{ type: 'text', text: 'foreground B' }] }])
+ } else {
+ await resume('stored-B', true)
+ }
+
+ const foreground = $messages.get()
+ const before = stateMap.current.get('rt-A')!
+
+ if (invalidated === 'epoch') {
+ stateMap.current.set('rt-A', {
+ ...before,
+ transcriptAuthorityEpoch: (before.transcriptAuthorityEpoch ?? 0) + 1
+ })
+ } else if (invalidated === 'lineage') {
+ setSessions(rows => rows.map(row => (row.id === 'stored-A' ? { ...row, _lineage_root_id: 'other-root' } : row)))
+ }
+
+ views.length = 0
+ persistedA.resolve({
+ messages: [{ role: 'assistant', content: 'durable background A', timestamp: 1 }],
+ session_id: 'stored-A'
+ })
+ await pending
+ expect($messages.get()).toBe(foreground)
+ expect($activeSessionId.get()).toBe(invalidated === 'route' ? 'rt-A' : 'rt-B')
+ expect(views).toEqual([])
+
+ if (invalidated === 'epoch' || invalidated === 'lineage') {
+ expect(stateMap.current.get('rt-A')?.messages).toBe(before.messages)
+ } else {
+ expect(JSON.stringify(stateMap.current.get('rt-A')?.messages)).toContain('durable background A')
+ expect(stateMap.current.get('rt-A')?.transcriptProvenance?.source).toBe('persisted-display')
+ expect(JSON.stringify(loadTranscriptTail('stored-A'))).toContain('durable background A')
+ }
+
+ window.localStorage.clear()
+ setMessagingSessions([])
+ }
+ )
+
it('reads the terminal transcript after warm reconnect transport reattachment', async () => {
const runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>> = {
current: new Map([['stored-A', 'rt-A']])
@@ -4006,10 +4340,20 @@ describe('resumeSession warm-cache mapping integrity', () => {
const publications: Array<{ older: boolean; latest: boolean }> = []
- setSessions([storedSession({ message_count: 4 })])
+ setSessions([storedSession({ message_count: 4, profile: 'default' })])
+ saveTranscriptTail('stored-1', cachedState.messages, 'default')
+
+ const stopListening = $messages.listen(messages => {
+ const snapshot = JSON.stringify(messages)
+ publications.push({
+ latest: snapshot.includes('latest question after long-context completion'),
+ older: snapshot.includes('earlier question before long-context completion')
+ })
+ })
+
vi.mocked(getLatestSessionMessages).mockReturnValue(persistedAuthority.promise as never)
- const requestGateway = vi.fn(async (method: string) => {
+ const requestGateway = vi.fn(async (method: string, _params?: Record<string, unknown>) => {
if (method === 'session.activate') {
return {
info: {},
@@ -4044,6 +4388,7 @@ describe('resumeSession warm-cache mapping integrity', () => {
)
await waitFor(() => expect(resume).not.toBeNull())
+ vi.mocked(requestGatewayForProfile).mockImplementation((_profile, method, params) => requestGateway(method, params))
const resumePromise = resume!('stored-1', true)
await waitFor(() =>
expect(requestGateway).toHaveBeenCalledWith(
@@ -4068,6 +4413,8 @@ describe('resumeSession warm-cache mapping integrity', () => {
})
await resumePromise
+ stopListening()
+ window.localStorage.clear()
expect(publications.some(snapshot => snapshot.latest && snapshot.older)).toBe(true)
expect(
publications.filter(snapshot => snapshot.latest && !snapshot.older),
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/display-hydration.ts b/apps/desktop/src/app/session/hooks/use-session-actions/display-hydration.ts
new file mode 100644
index 00000000000..9d77ee550d1
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/display-hydration.ts
@@ -0,0 +1,68 @@
+import type { MutableRefObject } from 'react'
+
+import type { SessionInfo } from '@/hermes'
+import { isSessionRemovalPending } from '@/store/session-removal'
+
+import type { ClientSessionState } from '../../../types'
+
+import { cachedSessionRow } from './utils'
+
+/** Navigation revokes the view, not a read owned by an unchanged session. */
+export function captureDisplayHydration({
+ flights,
+ key,
+ runtimeIdByStoredSessionIdRef,
+ sessionStateByRuntimeIdRef,
+ stored,
+ storedSessionId
+}: {
+ flights: Map<string, symbol>
+ key: string
+ runtimeIdByStoredSessionIdRef: MutableRefObject<Map<string, string>>
+ sessionStateByRuntimeIdRef: MutableRefObject<Map<string, ClientSessionState>>
+ stored: SessionInfo | undefined
+ storedSessionId: string
+}) {
+ const token = Symbol(key)
+ flights.set(key, token)
+ const states = sessionStateByRuntimeIdRef.current
+ const runtimeId = runtimeIdByStoredSessionIdRef.current.get(storedSessionId)
+ const epoch = runtimeId ? (states.get(runtimeId)?.transcriptAuthorityEpoch ?? 0) : 0
+
+ // Capture values, not the mutable list row.
+ const identity = stored && {
+ id: stored.id,
+ lineageRootId: stored._lineage_root_id,
+ connectionId: stored.connection_id,
+ profile: stored.profile
+ }
+
+ return {
+ owns() {
+ const state = runtimeId ? states.get(runtimeId) : undefined
+ const row = cachedSessionRow(storedSessionId)
+
+ return (
+ flights.get(key) === token &&
+ sessionStateByRuntimeIdRef.current === states &&
+ runtimeIdByStoredSessionIdRef.current.get(storedSessionId) === runtimeId &&
+ (!runtimeId ||
+ (state?.storedSessionId === storedSessionId && (state.transcriptAuthorityEpoch ?? 0) === epoch)) &&
+ !isSessionRemovalPending(storedSessionId) &&
+ (!identity ||
+ Boolean(
+ row &&
+ row.id === identity.id &&
+ row._lineage_root_id === identity.lineageRootId &&
+ row.connection_id === identity.connectionId &&
+ row.profile === identity.profile
+ ))
+ )
+ },
+ release() {
+ if (flights.get(key) === token) {
+ flights.delete(key)
+ }
+ }
+ }
+}
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 138c6c77bb3..64eb124a913 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
@@ -125,12 +125,7 @@ import { broadcastSessionsChanged } from '@/store/session-sync'
import { forgetSessionUnread } from '@/store/session-unread'
import { $archivedSessions } from '@/store/sidebar-archive'
import { restoreSessionTodosFromSnapshot } from '@/store/todos'
-import {
- dropTranscriptTail,
- dropTranscriptTailEverywhere,
- loadTranscriptTail,
- saveTranscriptTail
-} from '@/store/transcript-tail-cache'
+import { dropTranscriptTail, dropTranscriptTailEverywhere, saveTranscriptTail } from '@/store/transcript-tail-cache'
import { isWatchWindow } from '@/store/windows'
import type { SessionCreateResponse, SessionMessage, SessionResumeResult, UsageStats } from '@/types/hermes'
@@ -140,6 +135,8 @@ import { sessionContextDrift } from '../session-context-drift'
import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'
import { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'
+import { captureDisplayHydration } from './display-hydration'
+import { provisionalTranscriptPaint, transcriptRestScope } from './provisional-transcript'
import { pendingClarifyToolPayload, restorePendingClarifyFromSnapshot } from './restore-pending-clarify'
import { projectPendingConnection, restorePendingConnectionFromSnapshot } from './restore-pending-connection'
import {
@@ -399,6 +396,8 @@ export function useSessionActions({
const { t } = useI18n()
const copy = t.desktop
const resumeRequestRef = useRef(0)
+ const transcriptHydrationByRuntimeRef = useRef(new Map<string, symbol>())
+ const coldDisplayReadsRef = useRef(new Map<string, symbol>())
const branchCreateFlightsRef = useRef(new Map<string, Promise<SessionCreateResponse>>())
// Follow auto-compression's stored-id rotation only while the exact runtime,
@@ -938,12 +937,15 @@ export function useSessionActions({
}
const requestId = resumeRequestRef.current + 1
+ const routeToken = getRouteToken()
resumeRequestRef.current = requestId
const resumedSameSelectedSession = selectedStoredSessionIdRef.current === storedSessionId
const resumeStartMessages = resumedSameSelectedSession ? $messages.get() : []
const isCurrentResume = () =>
- resumeRequestRef.current === requestId && selectedStoredSessionIdRef.current === storedSessionId
+ resumeRequestRef.current === requestId &&
+ selectedStoredSessionIdRef.current === storedSessionId &&
+ getRouteToken() === routeToken
// Paint the click before the profile-resolve / gateway-swap awaits below,
// so there's zero dead air: highlight the row instantly (the sidebar reads
@@ -1039,10 +1041,21 @@ export function useSessionActions({
const ambientConnectionId =
ambientConnection?.mode === 'remote' ? ambientConnection.connectionId?.trim() || '' : ''
+ const provisional = provisionalTranscriptPaint(
+ storedSessionId,
+ () => isCurrentResume() && !resumedSameSelectedSession && !takeWarmCache()
+ )
+
+ const listedStored = $sessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+
+ if (ownerRoute || listedStored?.profile) {
+ provisional.paint(transcriptRestScope(ownerRoute, listedStored, ambientConnectionId))
+ }
+
const storedForProfile = await resolveStoredSession(storedSessionId, ownerRoute)
const sessionProfile = storedForProfile?.profile
- if (resumeRequestRef.current !== requestId) {
+ if (!isCurrentResume()) {
return
}
@@ -1062,6 +1075,9 @@ export function useSessionActions({
}
: sessionProfile)
+ const sessionRestScope = transcriptRestScope(ownerRoute, storedForProfile, ambientConnectionId)
+ provisional.paint(sessionRestScope)
+
// All-profiles / plugin navigation must not steal chrome API-home:
// dial the owning backend without moving $activeGatewayProfile.
if ($showAllProfiles.get()) {
@@ -1093,17 +1109,9 @@ export function useSessionActions({
const requestForSession = <T>(method: string, params: Record<string, unknown> = {}): Promise<T> =>
requestForSessionProfile<T>(sessionOwner, requestGateway, method, params)
- const sessionRestScope = resolvedConnectionId
- ? {
- connectionId: resolvedConnectionId,
- profile: ownerRoute?.targetProfile || ownerRoute?.profile || sessionProfile || 'default'
- }
- : storedForProfile?.connection_id
- ? {
- connectionId: storedForProfile.connection_id,
- profile: sessionProfile || 'default'
- }
- : sessionProfile
+ if (!isCurrentResume()) {
+ return
+ }
// Re-check after the profile-resolve / gateway-swap awaits above: the
// cache may have changed, and takeWarmCache re-validates belongs-to and
@@ -1361,6 +1369,15 @@ export function useSessionActions({
// events arrive on the newly attached transport. Hydration below
// reconciles only messages, so those events also retain liveness
// authority while the request is pending.
+ const hydration = captureDisplayHydration({
+ flights: transcriptHydrationByRuntimeRef.current,
+ key: cachedRuntimeId,
+ runtimeIdByStoredSessionIdRef,
+ sessionStateByRuntimeIdRef,
+ stored,
+ storedSessionId
+ })
+
const persistedTranscriptPromise = shouldRefreshPersistedTranscript
? getLatestSessionMessages(storedSessionId, sessionRestScope).catch(() => null)
: null
@@ -1375,7 +1392,11 @@ export function useSessionActions({
if (persistedTranscriptPromise) {
const persisted = await persistedTranscriptPromise
- if (!isCurrentResume()) {
+ // Navigation only revokes foreground publication, not this
+ // runtime's display read. Edits/rebinds revoke both.
+ if (!hydration.owns()) {
+ hydration.release()
+
return
}
@@ -1459,37 +1480,46 @@ export function useSessionActions({
releaseTranscriptView()
- const activatedState = updateSessionState(
- cachedRuntimeId,
- state => {
- // #95595: the reconcilers above always produce fresh
- // message objects, so an unconditional publish replaces the
- // warm-cached array with new-object equivalents and every
- // visible row re-normalizes + remounts (markdown re-parse +
- // shiki re-highlight per row, seconds of main-thread work).
- // Keep the existing array when the content is unchanged —
- // same guard the cold-resume path uses below.
- const messages = preserveEquivalentTranscript(state.messages, visibleActivatedMessages)
-
- return {
- ...state,
- messages,
- transcriptProvenance:
- acceptedPersistedDisplayTranscript || hasValidProvenance
- ? (expectedProvenance ?? undefined)
- : undefined,
- ...(livePromptStreamId(pendingConnectionProjection, pendingClarifyProjection)),
- ...(clearedClarifyProjection
- ? {
- streamId: state.busy ? (clearedClarifyProjection.streamId ?? state.streamId) : null
- }
- : {})
- }
- },
- storedSessionId
- )
+ const reconcileActivatedState = (state: ClientSessionState): ClientSessionState => {
+ // #95595: the reconcilers above always produce fresh
+ // message objects, so an unconditional publish replaces the
+ // warm-cached array with new-object equivalents and every
+ // visible row re-normalizes + remounts (markdown re-parse +
+ // shiki re-highlight per row, seconds of main-thread work).
+ // Keep the existing array when the content is unchanged —
+ // same guard the cold-resume path uses below.
+ const messages = preserveEquivalentTranscript(state.messages, visibleActivatedMessages)
+
+ return {
+ ...state,
+ messages,
+ transcriptProvenance:
+ acceptedPersistedDisplayTranscript || hasValidProvenance
+ ? (expectedProvenance ?? undefined)
+ : undefined,
+ ...livePromptStreamId(pendingConnectionProjection, pendingClarifyProjection),
+ ...(clearedClarifyProjection
+ ? {
+ streamId: state.busy ? (clearedClarifyProjection.streamId ?? state.streamId) : null
+ }
+ : {})
+ }
+ }
+
+ if (isCurrentResume()) {
+ const activatedState = updateSessionState(cachedRuntimeId, reconcileActivatedState, storedSessionId)
+ syncSessionStateToView(cachedRuntimeId, activatedState)
+ } else {
+ // updateSessionState stages a view sync based on active runtime,
+ // which can lag a newer route intent. Background hydration only
+ // publishes the cache; it cannot stage that foreground write.
+ const latestState = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId)!
+ const activatedState = reconcileActivatedState(latestState)
+ sessionStateByRuntimeIdRef.current.set(cachedRuntimeId, activatedState)
+ publishSessionState(cachedRuntimeId, activatedState)
+ }
- syncSessionStateToView(cachedRuntimeId, activatedState)
+ hydration.release()
// Cache backend transcript truth only. The pending/running bit and
// any synthetic clarify row are a live resume projection and must
// not survive after the server-side request expires.
@@ -1543,30 +1573,15 @@ export function useSessionActions({
// session's transcript would leak into this cold resume ("switching
// sessions shows the same messages"). Clear it so the loader/prefetch
// paints fresh; guarded so the normal cold path (already cleared) no-ops.
- if (!resumedSameSelectedSession && $messages.get().length > 0) {
+ if (!resumedSameSelectedSession && $messages.get().length > 0 && $messages.get() !== provisional.messages) {
setMessages([])
}
- // Instant paint from the durable tail cache: a cold resume (fresh app
- // launch, reaped/respawned backend) otherwise shows a loader until the
- // REST prefetch lands — which on a cold multi-profile boot waits behind
- // a backend spawn. Painting the persisted tail here makes the wake
- // visually complete at ~0ms (and satisfies the paint-first hydration
- // wait). The paint is DISPLAY-ONLY: reconciliation below must treat the
- // view as empty (see cachedTailPaint), because grafting the REST tail
- // onto a stale cached tail would duplicate or misorder rows — the
- // authoritative transcript REPLACES the cached paint when it lands.
- // Same-selected re-resumes skip it — their transcript is already live.
- let cachedTailPaint: ChatMessage[] | null = null
-
- if (!resumedSameSelectedSession && $messages.get().length === 0) {
- const cachedTail = loadTranscriptTail(storedSessionId, sessionRestScope)
-
- if (cachedTail && selectedStoredSessionIdRef.current === storedSessionId) {
- cachedTailPaint = cachedTail
- setMessages(cachedTail)
- }
- }
+ // Retry after a warm runtime was discarded, without clearing a cold
+ // tail that already painted before metadata/dial. This remains display-
+ // only: REST replaces it rather than grafting onto stale cached history.
+ provisional.paint(sessionRestScope)
+ const cachedTailPaint = provisional.messages
// The reconciler's notion of "what was already on screen": a durable
// cached paint is provisional, not history — report empty so the
@@ -1596,6 +1611,15 @@ export function useSessionActions({
applyStoredUsage(stored)
}
+ const displayRead = captureDisplayHydration({
+ flights: coldDisplayReadsRef.current,
+ key: JSON.stringify([sessionRestScope, storedSessionId]),
+ runtimeIdByStoredSessionIdRef,
+ sessionStateByRuntimeIdRef,
+ stored,
+ storedSessionId
+ })
+
let resumedRunning = false
// A recovered in-flight tail means the turn already produced output, so
// it resumes into the streaming state rather than the "awaiting first
@@ -1660,6 +1684,17 @@ export function useSessionActions({
// Non-fatal: gateway resume below can still hydrate the session.
}
+ // A completed read still warms its exact durable scope after navigation.
+ // It must not adopt a runtime or touch the foreground on that path.
+ if (
+ prefetchedResult &&
+ stored &&
+ displayRead.owns() &&
+ (!prefetchedResult.session_id || prefetchedResult.session_id === stored.id)
+ ) {
+ saveTranscriptTail(storedSessionId, toChatMessages(prefetchedResult.messages), sessionRestScope)
+ }
+
// 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
@@ -1828,7 +1863,12 @@ export function useSessionActions({
const pendingApproval = restorePendingApproval(resumed, resumed.session_id)
const pendingClarifyState = restorePendingClarifyFromSnapshot(resumed, resumed.session_id, resumeStartedAt)
const pendingClarify = pendingClarifyState.request
- const pendingConnection = restorePendingConnectionFromSnapshot(resumed, resumed.session_id, resumeStartedAt).request
+
+ const pendingConnection = restorePendingConnectionFromSnapshot(
+ resumed,
+ resumed.session_id,
+ resumeStartedAt
+ ).request
const clarifyAuthoritativelyAbsent =
pendingClarifyState.authoritativeAbsent && !$clarifyRequests.get()[resumed.session_id]
@@ -1908,7 +1948,7 @@ export function useSessionActions({
: {
turnStartedAt: resumedRunning && resumedTurnStartedAt !== null ? resumedTurnStartedAt : null
}),
- ...(livePromptStreamId(pendingConnectionProjection, pendingClarifyProjection)),
+ ...livePromptStreamId(pendingConnectionProjection, pendingClarifyProjection),
...(clearedClarifyProjection
? {
streamId: resumedRunning ? (clearedClarifyProjection.streamId ?? state.streamId) : null
@@ -2095,6 +2135,8 @@ export function useSessionActions({
notifyError(err, copy.resumeFailed)
} finally {
+ displayRead.release()
+
if (isCurrentResume()) {
busyRef.current = resumedRunning
setBusy(resumedRunning)
@@ -2106,6 +2148,7 @@ export function useSessionActions({
activeSessionIdRef,
busyRef,
copy,
+ getRouteToken,
holdSessionTranscriptView,
requestGateway,
resetViewSync,
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/provisional-transcript.ts b/apps/desktop/src/app/session/hooks/use-session-actions/provisional-transcript.ts
new file mode 100644
index 00000000000..33b55610166
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/provisional-transcript.ts
@@ -0,0 +1,56 @@
+import type { SessionInfo } from '@/hermes'
+import type { ChatMessage } from '@/lib/chat-messages'
+import { $messages, setMessages } from '@/store/session'
+import type { SessionProfileRoute } from '@/store/session-request-router'
+import { loadTranscriptTail, type TranscriptTailScope } from '@/store/transcript-tail-cache'
+
+export function transcriptRestScope(
+ owner: SessionProfileRoute | undefined,
+ stored: SessionInfo | undefined,
+ ambientConnectionId: string
+): TranscriptTailScope | undefined {
+ const connectionId = owner ? owner.connectionId : stored?.connection_id || ambientConnectionId
+ const profile = owner?.targetProfile || owner?.profile || stored?.profile
+
+ return connectionId ? { connectionId, profile: profile || 'default' } : profile || undefined
+}
+
+/** Display-only cache paint: never becomes runtime or persisted-display authority. */
+export function provisionalTranscriptPaint(storedSessionId: string, isCurrent: () => boolean) {
+ let messages: ChatMessage[] | null = null
+ let scopeKey: string | undefined
+
+ return {
+ get messages() {
+ return messages
+ },
+ paint(scope: TranscriptTailScope | undefined) {
+ if (!isCurrent()) {
+ return
+ }
+
+ const nextKey = JSON.stringify(scope)
+
+ if (messages !== null && nextKey !== scopeKey) {
+ if ($messages.get() === messages) {
+ setMessages([])
+ }
+
+ messages = null
+ }
+
+ scopeKey = nextKey
+
+ // An unknown owner is not permission to read a legacy unscoped entry.
+ if (!scope || messages !== null || $messages.get().length > 0) {
+ return
+ }
+
+ messages = loadTranscriptTail(storedSessionId, scope)
+
+ if (messages) {
+ setMessages(messages)
+ }
+ }
+ }
+}