Skip to content

The agent that grows with you

fix(desktop): paint live rows under the warm-resume hold, suppress only the cached prefix (#117867) (#119552)

Halldrix121de845a465
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 7335d9b5ac7..7d4cb2a3c87 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
@@ -93,6 +93,8 @@ import { NEW_CHAT_ROUTE, sessionRoute } from '../../routes'
import type { ClientSessionState } from '../../types'
import { useSessionActions } from './use-session-actions'
+import { suppressTranscriptForView, transcriptRowContentKey } from './use-session-actions/transcript-provenance'
+import type { TranscriptViewCutoff } from './use-session-actions/transcript-provenance'
import { useSessionStateCache } from './use-session-state-cache'
vi.mock('@/hermes', async importOriginal => ({
@@ -992,6 +994,10 @@ function ResumeHarness({
const ref = <T,>(value: T): MutableRefObject<T> => ({ current: value })
const runtimeMapRef = runtimeIdByStoredSessionIdRef ?? ref(new Map<string, string>())
const stateMapRef = sessionStateByRuntimeIdRef ?? ref(new Map<string, ClientSessionState>())
+ // Stand in for the real hook's gate: without it this stub would publish the
+ // unproven warm cache before REST authority lands. Kept here (not per-test)
+ // so every resume through this harness sees one shared suppression policy.
+ const heldCutoffsByRuntimeIdRef = ref(new Map<string, TranscriptViewCutoff>())
const actions = useSessionActions({
activeSessionId: null,
@@ -1008,7 +1014,25 @@ function ResumeHarness({
selectedStoredSessionId,
selectedStoredSessionIdRef: ref<string | null>(selectedStoredSessionId),
sessionStateByRuntimeIdRef: stateMapRef,
- syncSessionStateToView: (sessionId, state) => onViewSync?.(sessionId, state),
+ holdSessionTranscriptView: runtimeId => {
+ const rows = stateMapRef.current.get(runtimeId)?.messages ?? []
+
+ const cutoff: TranscriptViewCutoff = {
+ cutoffIds: new Set(rows.map(message => message.id)),
+ cutoffKeys: new Set(rows.map(transcriptRowContentKey))
+ }
+
+ heldCutoffsByRuntimeIdRef.current.set(runtimeId, cutoff)
+
+ return () => {
+ heldCutoffsByRuntimeIdRef.current.delete(runtimeId)
+ }
+ },
+ syncSessionStateToView: (sessionId, state) => {
+ const cutoff = heldCutoffsByRuntimeIdRef.current.get(sessionId) ?? null
+
+ onViewSync?.(sessionId, suppressTranscriptForView(state, cutoff))
+ },
updateSessionState: (sessionId, updater, storedSessionId) => {
// Full default shape (not a bare {} cast) so seeded/derived fields like
// turnStartedAt behave as in production state updates.
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 c0a850f2ab0..5dd13612a0f 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
@@ -147,7 +147,6 @@ import { projectPendingConnection, restorePendingConnectionFromSnapshot } from '
import {
createPersistedDisplayTranscriptProvenance,
hasPersistedDisplayTranscriptProvenance,
- suppressTranscriptForView,
withoutTranscriptProvenance
} from './transcript-provenance'
import {
@@ -1244,14 +1243,16 @@ export function useSessionActions({
dropSessionState(cachedRuntimeId)
} else {
// Bind the warm runtime immediately so cwd/workspace ownership don't
- // wait on session.activate (#71254). Unproven cache entries (no
- // persisted-display provenance) stay off the view until REST
- // authority lands — a compressed runtime tail is legal in cache and
- // is exactly the session-switch flicker (#73646). Proven caches and
- // same-session re-resumes still paint immediately. The persisted
- // refresh itself still starts after activate reattaches the live
- // transport, so a turn finishing between snapshot and reattach
- // cannot leave a stale partial on screen.
+ // wait on session.activate (#71254). The armed transcript gate is the
+ // single suppression authority: it hides only the unproven cached
+ // prefix (rows captured at arm time, including a compressed runtime
+ // tail — exactly the session-switch flicker, #73646) while rows that
+ // arrive live during the hold still paint (#117867). Proven caches
+ // and same-session re-resumes never arm the gate, so they paint
+ // immediately. The persisted refresh itself still starts after
+ // activate reattaches the live transport, so a turn finishing
+ // between snapshot and reattach cannot leave a stale partial on
+ // screen.
const shouldRefreshPersistedTranscript = !isWatchWindow()
const suppressUnprovenWarmTranscript =
@@ -1277,10 +1278,7 @@ export function useSessionActions({
selectedStoredSessionIdRef.current = storedSessionId
setActiveSessionId(cachedRuntimeId)
activeSessionIdRef.current = cachedRuntimeId
- syncSessionStateToView(
- cachedRuntimeId,
- suppressTranscriptForView(cachedViewState, suppressUnprovenWarmTranscript)
- )
+ syncSessionStateToView(cachedRuntimeId, cachedViewState)
setCurrentCwdTransient(cachedViewState.cwd)
// The warm cache IS this conversation's own workspace truth, so the
// switch is already re-homed here. This claim cannot wait for
@@ -1433,10 +1431,7 @@ export function useSessionActions({
busyRef.current = running
setBusy(running)
setAwaitingResponse(running && !pendingClarify)
- syncSessionStateToView(
- cachedRuntimeId,
- suppressTranscriptForView(activatedLivenessState, suppressUnprovenWarmTranscript)
- )
+ syncSessionStateToView(cachedRuntimeId, activatedLivenessState)
// session.activate is the ordering barrier for reconnect recovery:
// it atomically rebinds a running turn before returning. If the
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts
index ef855fb7ba4..bf5e31214be 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.test.ts
@@ -52,8 +52,26 @@ describe('transcript provenance', () => {
const state = createClientSessionState('stored-1')
state.messages = [{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] }]
- expect(suppressTranscriptForView(state, false)).toBe(state)
- expect(suppressTranscriptForView(state, true).messages).toEqual([])
+ // No gate held: the state reaches the view verbatim.
+ expect(suppressTranscriptForView(state, null)).toBe(state)
+
+ // Gate held with no captured prefix: fail-closed, everything hides.
+ expect(suppressTranscriptForView(state, { cutoffIds: new Set() }).messages).toEqual([])
expect(state.messages).toHaveLength(1)
})
+
+ it('drops only the cached prefix and keeps rows appended after the arm (#117867)', () => {
+ const state = createClientSessionState('stored-1')
+ state.messages = [
+ { id: 'cached-1', role: 'user', parts: [{ type: 'text', text: 'old' }] },
+ { id: 'live-1', role: 'assistant', parts: [{ type: 'text', text: 'streaming' }] }
+ ]
+
+ const suppressed = suppressTranscriptForView(state, { cutoffIds: new Set(['cached-1']) })
+
+ expect(suppressed.messages.map(message => message.id)).toEqual(['live-1'])
+
+ // Nothing else in the state is touched, and the input is not mutated.
+ expect(state.messages).toHaveLength(2)
+ })
})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts
index 7cd8c3d549e..0252a978806 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/transcript-provenance.ts
@@ -1,3 +1,5 @@
+import type { ChatMessage } from '@/lib/chat-messages'
+
import type { ClientSessionState, PersistedDisplayTranscriptProvenance } from '../../../types'
export type TranscriptProvenanceScope =
@@ -60,10 +62,56 @@ export function invalidatePersistedDisplayTranscriptAuthority(state: ClientSessi
}
}
-export function suppressTranscriptForView(state: ClientSessionState, suppress: boolean): ClientSessionState {
- if (!suppress || state.messages.length === 0) {
+export interface TranscriptViewCutoff {
+ cutoffIds: ReadonlySet<string>
+ // Content fingerprints of the arm-time rows (optional). Compaction
+ // re-sequences the cached tail with FRESH row ids mid-hold
+ // (archive_and_compact: "consumers that reference durable row ids
+ // re-resolve by content"), so an id-only cutoff would pass the whole
+ // re-sequenced cached prefix as if it were live and paint the exact
+ // compressed tail the hold exists to hide (#73646 via #117867).
+ cutoffKeys?: ReadonlySet<string>
+}
+
+// Volatile-free content fingerprint: role + text of text parts, JSON of the
+// rest. Deliberately ignores row ids and per-row timestamps so a re-sequenced
+// copy of the same content fingerprints identically. Ceiling: a genuinely new
+// row whose content is byte-identical to an arm-time row stays hidden until
+// the hold releases (bounded by the REST window).
+export function transcriptRowContentKey(message: ChatMessage): string {
+ return `${message.role}:${
+ (message.parts ?? [])
+ .map(part =>
+ 'text' in part && typeof part.text === 'string' ? `${part.type}:${part.text}` : JSON.stringify(part)
+ )
+ .join('|')
+ }`
+}
+
+export function suppressTranscriptForView(
+ state: ClientSessionState,
+ cutoff: TranscriptViewCutoff | null
+): ClientSessionState {
+ if (cutoff === null) {
+ return state
+ }
+
+ if (cutoff.cutoffIds.size === 0) {
+ // Fail-closed: the gate was armed before any cached row existed, so there
+ // is no unproven prefix to hide selectively — everything stays off the
+ // view until REST authority lands (#73646).
+ return { ...state, messages: [] }
+ }
+
+ const messages = state.messages.filter(
+ message =>
+ !cutoff.cutoffIds.has(message.id) &&
+ !(cutoff.cutoffKeys?.has(transcriptRowContentKey(message)) ?? false)
+ )
+
+ if (messages.length === state.messages.length) {
return state
}
- return { ...state, messages: [] }
+ return { ...state, messages }
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
index 537c77d7893..bb403b34144 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx
@@ -742,6 +742,169 @@ describe('useSessionStateCache — cross-thread error isolation', () => {
})
})
+// #117867: the warm-resume transcript gate used to empty the view entirely
+// while held, so rows arriving LIVE during the hold (the user's in-flight turn)
+// never painted until REST authority landed. The gate now hides only the cached
+// prefix captured when the hold was armed.
+describe('useSessionStateCache — held transcript gate keeps live rows (#117867)', () => {
+ const runtime = 'hold-runtime'
+ const stored = 'hold-stored'
+
+ beforeEach(() => {
+ clearAllSessionStates()
+ setActiveSessionId(runtime)
+ })
+
+ afterEach(() => {
+ cleanup()
+ $messages.set([])
+ clearAllSessionStates()
+ setActiveSessionId(null)
+ })
+
+ it('paints rows appended after the arm and hides only the cached prefix', () => {
+ let cache!: Cache
+ let release: (() => void) | undefined
+
+ render(<ViewHarness activeSessionId={runtime} onReady={value => (cache = value)} />)
+
+ // Seed the warm cache entry with the unproven cached prefix — exactly what
+ // resumeSession has in hand when it arms the hold.
+ act(() => {
+ cache.updateSessionState(
+ runtime,
+ state => ({
+ ...state,
+ messages: [userMessage('cached-1', 'cached prompt'), assistantText('cached-2', 'cached tail')]
+ }),
+ stored
+ )
+ })
+
+ // The real production arm path, after the cache entry exists.
+ act(() => {
+ release = cache.holdSessionTranscriptView(runtime)
+ })
+
+ // A live row arrives mid-hold. busy:false forces the critical-transition
+ // sync flush (no rAF), so $messages is observable here.
+ act(() => {
+ cache.updateSessionState(
+ runtime,
+ state => ({
+ ...state,
+ busy: false,
+ messages: [
+ userMessage('cached-1', 'cached prompt'),
+ assistantText('cached-2', 'cached tail'),
+ userMessage('live-1', 'live turn')
+ ]
+ }),
+ stored
+ )
+ })
+
+ const ids = $messages.get().map(message => message.id)
+
+ expect(ids).toContain('live-1')
+ expect(ids).not.toContain('cached-1')
+ expect(ids).not.toContain('cached-2')
+
+ // Releasing restores the full transcript.
+ act(() => release?.())
+ act(() => {
+ cache.updateSessionState(
+ runtime,
+ state => ({ ...state, messages: state.messages }),
+ stored
+ )
+ })
+
+ expect($messages.get().map(message => message.id)).toEqual(['cached-1', 'cached-2', 'live-1'])
+ })
+
+ it('fails closed when the hold was armed with no cached prefix', () => {
+ let cache!: Cache
+ let release: (() => void) | undefined
+
+ render(<ViewHarness activeSessionId={runtime} onReady={value => (cache = value)} />)
+
+ act(() => {
+ release = cache.holdSessionTranscriptView(runtime)
+ })
+
+ act(() => {
+ cache.updateSessionState(
+ runtime,
+ state => ({
+ ...state,
+ busy: false,
+ messages: [userMessage('late-1', 'arrived after the arm')]
+ }),
+ stored
+ )
+ })
+
+ // No baseline was captured, so nothing is trustworthy yet: today's
+ // hide-everything behavior is preserved until REST authority lands.
+ expect($messages.get()).toEqual([])
+
+ act(() => release?.())
+ })
+
+ it('keeps a re-sequenced cached tail hidden when compaction assigns fresh ids mid-hold (#117867)', () => {
+ let cache!: Cache
+ let release: (() => void) | undefined
+
+ render(<ViewHarness activeSessionId={runtime} onReady={value => (cache = value)} />)
+
+ act(() => {
+ cache.updateSessionState(
+ runtime,
+ state => ({
+ ...state,
+ messages: [userMessage('cached-1', 'cached prompt'), assistantText('cached-2', 'cached tail')]
+ }),
+ stored
+ )
+ })
+
+ act(() => {
+ release = cache.holdSessionTranscriptView(runtime)
+ })
+
+ // A mid-hold compaction re-sequences the cached tail with FRESH row ids
+ // while keeping the content (archive_and_compact contract: consumers that
+ // reference durable row ids re-resolve by content). An id-only cutoff
+ // would pass `seq-*` through as if it were live and paint the compressed
+ // tail the hold exists to hide (#73646); the content fingerprint keeps it
+ // hidden while a genuinely new row still paints.
+ act(() => {
+ cache.updateSessionState(
+ runtime,
+ state => ({
+ ...state,
+ busy: false,
+ messages: [
+ userMessage('seq-71', 'cached prompt'),
+ assistantText('seq-72', 'cached tail'),
+ userMessage('live-1', 'live turn')
+ ]
+ }),
+ stored
+ )
+ })
+
+ const ids = $messages.get().map(message => message.id)
+
+ expect(ids).toContain('live-1')
+ expect(ids).not.toContain('seq-71')
+ expect(ids).not.toContain('seq-72')
+
+ act(() => release?.())
+ })
+})
+
// #93059: reconnect used to downgrade the $sessionStates mirror only, leaving
// this cache (which warm resume ORs over `running: false`) still busy.
describe('useSessionStateCache — reconnect busy reconcile (#93059)', () => {
diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
index c400ddc04b5..a7ed9cfafe7 100644
--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts
@@ -35,10 +35,20 @@ import { SessionStateCache } from '../session-state-cache'
import {
invalidatePersistedDisplayTranscriptAuthority,
- suppressTranscriptForView
+ suppressTranscriptForView,
+ transcriptRowContentKey
} from './use-session-actions/transcript-provenance'
import { chatMessageArraysEquivalent } from './use-session-actions/utils'
+// A held transcript gate hides only the unproven CACHED prefix (the ids
+// captured when the hold was armed) — rows that arrive live during the hold
+// still paint, which is the point of the fix (#117867).
+interface TranscriptViewGate {
+ cutoffIds: ReadonlySet<string>
+ cutoffKeys: ReadonlySet<string>
+ token: symbol
+}
+
interface SessionStateCacheOptions {
activeSessionId: string | null
busyRef: MutableRefObject<boolean>
@@ -143,7 +153,7 @@ export function useSessionStateCache({
const sessionStateCache = sessionStateByRuntimeIdRef.current
const pendingViewStateRef = useRef<{ sessionId: string; state: ClientSessionState } | null>(null)
const viewSyncRafRef = useRef<number | null>(null)
- const transcriptViewGateByRuntimeIdRef = useRef(new Map<string, symbol>())
+ const transcriptViewGateByRuntimeIdRef = useRef(new Map<string, TranscriptViewGate>())
// Runtime id whose transcript currently occupies `$messages` — lets the
// flush below tell a same-session refresh from a thread switch.
const viewSessionIdRef = useRef<string | null>(null)
@@ -226,16 +236,25 @@ export function useSessionStateCache({
}
}, [])
- const holdSessionTranscriptView = useCallback((runtimeId: string): (() => void) => {
- const token = Symbol(runtimeId)
- transcriptViewGateByRuntimeIdRef.current.set(runtimeId, token)
+ const holdSessionTranscriptView = useCallback(
+ (runtimeId: string): (() => void) => {
+ const token = Symbol(runtimeId)
+ const cached = sessionStateCache.get(runtimeId)
- return () => {
- if (transcriptViewGateByRuntimeIdRef.current.get(runtimeId) === token) {
- transcriptViewGateByRuntimeIdRef.current.delete(runtimeId)
+ transcriptViewGateByRuntimeIdRef.current.set(runtimeId, {
+ cutoffIds: new Set((cached?.messages ?? []).map(message => message.id)),
+ cutoffKeys: new Set((cached?.messages ?? []).map(transcriptRowContentKey)),
+ token
+ })
+
+ return () => {
+ if (transcriptViewGateByRuntimeIdRef.current.get(runtimeId)?.token === token) {
+ transcriptViewGateByRuntimeIdRef.current.delete(runtimeId)
+ }
}
- }
- }, [])
+ },
+ [sessionStateCache]
+ )
const flushPendingViewState = useCallback(() => {
const pending = pendingViewStateRef.current
@@ -300,7 +319,8 @@ export function useSessionStateCache({
return
}
- const viewState = suppressTranscriptForView(state, transcriptViewGateByRuntimeIdRef.current.has(sessionId))
+ const gate = transcriptViewGateByRuntimeIdRef.current.get(sessionId)
+ const viewState = suppressTranscriptForView(state, gate ?? null)
syncRuntimeMetadataToView(viewState)
pendingViewStateRef.current = { sessionId, state: viewState }