Skip to content

The agent that grows with you

fix(desktop): keep a mid-turn reply on screen when its session is reopened

Brooklyn Nicholsonb6f15f546d3a
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
index 1a67321d8e2..81a00da36f8 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { textWithoutReferenceLines, WIRE_REFERENCE_KINDS } from '@/components/assistant-ui/reference-kinds'
-import type { ChatMessage } from '@/lib/chat-messages'
+import { type ChatMessage, type ChatMessagePart, chatMessageText } from '@/lib/chat-messages'
import { $approvalModes, approvalModeForProfile } from '@/store/approval-mode'
import { $desktopOnboarding } from '@/store/onboarding'
import { $activeGatewayProfile } from '@/store/profile'
@@ -25,6 +25,21 @@ import {
const msg = (id: string, role: ChatMessage['role'], text: string, extra: Partial<ChatMessage> = {}): ChatMessage =>
({ id, role, parts: [{ type: 'text', text }], ...extra }) as ChatMessage
+// A live assistant row carrying the structure the gateway's text-only inflight
+// snapshot cannot: reasoning and tool calls, with or without any text yet.
+const streamingMsg = (id: string, text: string, extra: Partial<ChatMessage> = {}): ChatMessage =>
+ ({
+ id,
+ role: 'assistant',
+ parts: [
+ { type: 'reasoning', text: 'planning' },
+ { type: 'tool-call', toolCallId: 'call-1', toolName: 'terminal', result: 'done' },
+ ...(text ? [{ type: 'text', text } as ChatMessagePart] : [])
+ ],
+ pending: true,
+ ...extra
+ }) as ChatMessage
+
const session = (over: Partial<SessionInfo>): SessionInfo => over as SessionInfo
describe('applyRuntimeInfo approval mode', () => {
@@ -395,6 +410,126 @@ describe('reconcileResumeMessages', () => {
expect(out.attachmentRefs).toBeUndefined()
})
+
+ // #75825: switching sessions mid-stream can re-hydrate an empty inflight shell
+ // at the same ordinal as the live stream row that still holds the full reply.
+ it('prefers a richer local pending assistant over an empty projection shell', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'hello from stream', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('assistant-stream-sess', 'assistant', '', { pending: true })]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(reconciled[1]).toMatchObject({ id: 'assistant-stream-live', pending: true })
+ expect(chatMessageText(reconciled[1])).toBe('hello from stream')
+ })
+
+ it('prefers a richer local pending assistant when the projection lags mid-stream', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'hello world', { pending: true })
+ ]
+
+ const next = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-sess', 'assistant', 'hello', { pending: true })
+ ]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(chatMessageText(reconciled[1])).toBe('hello world')
+ expect(reconciled[1].id).toBe('assistant-stream-live')
+ })
+
+ it('does not override when the authoritative assistant has advanced further', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'hello', { pending: true })
+ ]
+
+ const next = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-sess', 'assistant', 'hello world', { pending: true })
+ ]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(chatMessageText(reconciled[1])).toBe('hello world')
+ expect(reconciled[1].id).toBe('assistant-stream-sess')
+ })
+
+ // The reported "no inference traces or tool calls": mid tool-work, the local
+ // row holds reasoning + tool calls and NO text yet, so both bodies are empty
+ // text and a text-length comparison cannot tell them apart.
+ it('prefers a traces-only local pending row over an empty shell', () => {
+ const previous = [msg('1-user', 'user', 'run the tools'), streamingMsg('assistant-stream-live', '')]
+
+ const next = [
+ msg('1-user', 'user', 'run the tools'),
+ msg('assistant-stream-sess', 'assistant', '', { pending: true })
+ ]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(reconciled[1].id).toBe('assistant-stream-live')
+ expect(reconciled[1].parts.map(part => part.type)).toEqual(['reasoning', 'tool-call'])
+ })
+
+ // A longer local body that is NOT an extension of the authoritative text is a
+ // different turn at the same ordinal (compression rewrites history) and must
+ // not hijack the slot.
+ it('leaves a shorter non-prefix authoritative assistant intact', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'a long local reply about something else entirely', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('9-assistant', 'assistant', 'short authoritative answer')]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(reconciled[1].id).toBe('9-assistant')
+ expect(chatMessageText(reconciled[1])).toBe('short authoritative answer')
+ })
+
+ // A retained failure snapshot (`inflight.error`) is projected with empty text.
+ // Preferring the local partial over it would erase the error and repaint the
+ // turn as healthy.
+ it('does not treat an errored authoritative row as an empty shell', () => {
+ const previous = [
+ msg('1-user', 'user', 'do the thing'),
+ msg('assistant-stream-live', 'assistant', 'partial answer before the failure', { pending: true })
+ ]
+
+ const next = [
+ msg('1-user', 'user', 'do the thing'),
+ msg('assistant-stream-sess', 'assistant', '', { error: 'model call failed: 500' })
+ ]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(reconciled[1].error).toBe('model call failed: 500')
+ })
+
+ // Content comes from the renderer; liveness stays the backend's call. A
+ // settled shell (queued turn behind a finished inflight one) must not leave
+ // the preserved reply spinning forever.
+ it('takes the local body but the authoritative settled state', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'streamed body', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('assistant-stream-sess', 'assistant', '', { pending: false })]
+
+ const reconciled = reconcileResumeMessages(next, previous)
+
+ expect(reconciled[1]).toMatchObject({ id: 'assistant-stream-live', pending: false })
+ expect(chatMessageText(reconciled[1])).toBe('streamed body')
+ })
})
describe('preserveLocalPendingTurnMessages', () => {
@@ -683,6 +818,151 @@ describe('preserveLocalPendingTurnMessages', () => {
'user-optimistic'
])
})
+
+ // #75825: an empty inflight projection shell at the same ordinal must not
+ // discard the local pending assistant that still holds the streamed content.
+ // Replace the shell (do not append) so the transcript shows one reply.
+ it('replaces an empty inflight shell with a fuller local pending assistant', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'partial answer so far', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('assistant-stream-sess', 'assistant', '', { pending: true })]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(preserved.map(message => message.id)).toEqual(['1-user', 'assistant-stream-live'])
+ expect(chatMessageText(preserved[1])).toBe('partial answer so far')
+ expect(preserved[1].pending).toBe(true)
+ })
+
+ it('replaces a lagging same-id shell with the fuller local pending body', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-sess', 'assistant', 'full streamed content', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('assistant-stream-sess', 'assistant', '', { pending: true })]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(preserved.map(message => message.id)).toEqual(['1-user', 'assistant-stream-sess'])
+ expect(chatMessageText(preserved[1])).toBe('full streamed content')
+ })
+
+ it('still drops local pending when authoritative text is at least as complete', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'partial', { pending: true })
+ ]
+
+ const next = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-sess', 'assistant', 'partial and more', { pending: true })
+ ]
+
+ expect(preserveLocalPendingTurnMessages(next, previous)).toBe(next)
+ })
+
+ // Mid tool-work both bodies are empty text, so only the parts distinguish the
+ // live row from the shell — the reported "no inference traces or tool calls".
+ it('replaces an empty shell with a traces-only local pending row', () => {
+ const previous = [msg('1-user', 'user', 'run the tools'), streamingMsg('assistant-stream-live', '')]
+
+ const next = [
+ msg('1-user', 'user', 'run the tools'),
+ msg('assistant-stream-sess', 'assistant', '', { pending: true })
+ ]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(preserved).toHaveLength(2)
+ expect(preserved[1].parts.map(part => part.type)).toEqual(['reasoning', 'tool-call'])
+ })
+
+ // Length alone is not identity: a longer local row that does not extend the
+ // authoritative text belongs to another turn and must not take its slot — by
+ // ordinal or by reusing the stream id.
+ it('leaves a shorter non-prefix authoritative assistant intact', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'a long local reply about something else entirely', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('9-assistant', 'assistant', 'short authoritative answer')]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(preserved.map(message => message.id)).toEqual(['1-user', '9-assistant'])
+ expect(chatMessageText(preserved[1])).toBe('short authoritative answer')
+ })
+
+ it('leaves a shorter non-prefix authoritative assistant intact on the same stream id', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-sess', 'assistant', 'a long local reply about something else entirely', { pending: true })
+ ]
+
+ const next = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-sess', 'assistant', 'short authoritative answer')
+ ]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(chatMessageText(preserved[1])).toBe('short authoritative answer')
+ })
+
+ it('does not erase a retained failure with the local partial', () => {
+ const previous = [
+ msg('1-user', 'user', 'do the thing'),
+ msg('assistant-stream-live', 'assistant', 'partial answer before the failure', { pending: true })
+ ]
+
+ const next = [
+ msg('1-user', 'user', 'do the thing'),
+ msg('assistant-stream-sess', 'assistant', '', { error: 'model call failed: 500' })
+ ]
+
+ const assistant = preserveLocalPendingTurnMessages(next, previous).find(message => message.role === 'assistant')
+
+ expect(assistant?.error).toBe('model call failed: 500')
+ expect(assistant?.pending).not.toBe(true)
+ })
+
+ it('takes the local body but the authoritative settled state', () => {
+ const previous = [
+ msg('1-user', 'user', 'question'),
+ msg('assistant-stream-live', 'assistant', 'streamed body', { pending: true })
+ ]
+
+ const next = [msg('1-user', 'user', 'question'), msg('assistant-stream-sess', 'assistant', '', { pending: false })]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(preserved[1]).toMatchObject({ id: 'assistant-stream-live', pending: false })
+ expect(chatMessageText(preserved[1])).toBe('streamed body')
+ })
+
+ // The whole point of replacing rather than appending: one reply on screen,
+ // and the committed history around the live turn untouched.
+ it('does not duplicate or rewrite committed history around the live turn', () => {
+ const history = [
+ msg('1-user', 'user', 'first question'),
+ msg('2-assistant', 'assistant', 'first answer'),
+ msg('3-user', 'user', 'run the tools')
+ ]
+
+ const previous = [...history, streamingMsg('assistant-stream-live', 'here is the full reply')]
+ const next = [...history, msg('assistant-stream-sess', 'assistant', '', { pending: true })]
+
+ const preserved = preserveLocalPendingTurnMessages(next, previous)
+
+ expect(preserved).toHaveLength(4)
+ expect(chatMessageText(preserved[1])).toBe('first answer')
+ expect(preserved.filter(message => message.role === 'assistant')).toHaveLength(2)
+ })
})
describe('appendLiveSessionProjection', () => {
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index 2d40ef8ce20..51b0323f22f 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -251,8 +251,20 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMes
const nextText = chatMessageText(message).trim()
const previousText = chatMessageText(previous)
const previousVisibleText = textWithoutEmbeddedImages(previousText)
+ const previousTrimmed = previousVisibleText.trim()
let preserved = message
+ // #75825: resume can project an empty (or lagging) inflight assistant shell
+ // at the same role-ordinal as the live stream row that still holds the
+ // streamed text, reasoning and tool calls. Prefer that richer pending row
+ // instead of painting the shell — otherwise the reply vanishes until
+ // restart. Guarded to the same reply further along (see
+ // localPendingSupersedes) so a different turn at the same ordinal cannot
+ // hijack the slot.
+ if (localPendingSupersedes(previous, message)) {
+ return withAuthoritativeTurnState(previous, message)
+ }
+
const sameText = nextText === previousVisibleText || nextText === previousText.trim()
// Mid-turn, the authoritative text has advanced past the cached copy by one
@@ -262,8 +274,7 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMes
// the strict equality path — they reconcile a SETTLED row, and a growing
// row is by definition not settled.
const sameTurn =
- sameText ||
- (nextText.length > 0 && previousVisibleText.length > 0 && nextText.startsWith(previousVisibleText.trim()))
+ sameText || (nextText.length > 0 && previousTrimmed.length > 0 && nextText.startsWith(previousTrimmed))
if (sameTurn) {
preserved = preserveStructuralParts(preserved, previous)
@@ -316,8 +327,10 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMes
* history window. Preserve only the newest optimistic user row: compression
* rewrites past context, so older `user-*` rows in a warm cache are stale
* history, not in-flight work. The latest authoritative user confirms whether
- * that tail has persisted; any authoritative assistant at the same ordinal
- * supersedes the local stream.
+ * that tail has persisted. An authoritative assistant at the same ordinal
+ * supersedes the local stream only when it is at least as complete; an empty
+ * or lagging inflight shell must not discard a fuller local pending reply
+ * (#75825).
*
* Gateway bookkeeping markers (the model-switch / personality notices written
* by tui_gateway/server.py) are persisted as role=user but are not user turns.
@@ -329,6 +342,71 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMes
const isGatewaySystemMarker = (message: ChatMessage): boolean =>
message.role === 'user' && chatMessageText(message).trimStart().startsWith('[System:')
+/**
+ * Does the local pending row carry anything a viewer would miss — streamed
+ * text, reasoning, or tool calls? An empty inflight shell carries none of it.
+ */
+const hasStreamedContent = (message: ChatMessage): boolean =>
+ chatMessageText(message).trim().length > 0 ||
+ message.parts.some(part => part.type === 'tool-call' || part.type === 'reasoning')
+
+/**
+ * A live-turn projection row — the gateway's text-only `inflight` snapshot or a
+ * still-streaming local bubble — as opposed to a committed transcript row.
+ */
+const isLiveProjectionRow = (message: ChatMessage): boolean =>
+ message.pending === true || message.id.startsWith('assistant-stream-') || message.id.startsWith('inflight-assistant-')
+
+/**
+ * May the cached local row stand in for this authoritative assistant?
+ *
+ * Only for a live projection of the SAME reply that the local copy is further
+ * along on: an empty shell, or text the local row strictly extends. Comparing
+ * lengths alone lets an unrelated (merely longer) local row hijack the ordinal
+ * — or the stream id — of a genuine stored reply. A retained failure snapshot
+ * (`inflight.error`, projected with empty text) is never a shell: repainting it
+ * from the local partial would hide the error and mark the turn healthy again.
+ */
+const localPendingSupersedes = (local: ChatMessage, authoritative: ChatMessage): boolean => {
+ if (local.role !== 'assistant' || !isLiveProjectionRow(local)) {
+ return false
+ }
+
+ if (!isLiveProjectionRow(authoritative) || authoritative.error) {
+ return false
+ }
+
+ const authoritativeText = chatMessageText(authoritative).trim()
+
+ if (!authoritativeText.length) {
+ return hasStreamedContent(local)
+ }
+
+ const localText = chatMessageText(local).trim()
+
+ return localText.length > authoritativeText.length && localText.startsWith(authoritativeText)
+}
+
+/**
+ * Take the cached row's content, but never its liveness. The renderer holds the
+ * only copy of the streamed parts; the gateway remains the authority on whether
+ * the turn is still running and on durable row identity — so a settled shell
+ * must not repaint the reply as perpetually streaming.
+ */
+const withAuthoritativeTurnState = (local: ChatMessage, authoritative: ChatMessage): ChatMessage => {
+ const merged: ChatMessage = { ...local, pending: authoritative.pending === true }
+
+ if (local.rowId === undefined && authoritative.rowId !== undefined) {
+ merged.rowId = authoritative.rowId
+ }
+
+ if (local.reactions === undefined && authoritative.reactions?.length) {
+ merged.reactions = [...authoritative.reactions]
+ }
+
+ return merged
+}
+
export function preserveLocalPendingTurnMessages(
nextMessages: ChatMessage[],
previousMessages: ChatMessage[]
@@ -379,6 +457,9 @@ export function preserveLocalPendingTurnMessages(
const latestAuthoritativeUser = [...nextMessages].reverse().find(message => message.role === 'user')
const preserved: ChatMessage[] = []
+ // Authoritative id → richer local pending row. Replacing (not appending)
+ // avoids painting both the empty inflight shell and the full stream bubble.
+ const replacements = new Map<string, ChatMessage>()
for (const message of previousMessages) {
if (isGatewaySystemMarker(message)) {
@@ -393,7 +474,21 @@ export function preserveLocalPendingTurnMessages(
const isPendingAssistant =
message.role === 'assistant' && (message.pending === true || message.id.startsWith('assistant-stream-'))
- if ((!isOptimisticUser && !isPendingAssistant) || nextIds.has(message.id)) {
+ if (!isOptimisticUser && !isPendingAssistant) {
+ continue
+ }
+
+ // Same id already present: still prefer a strictly more complete local
+ // pending body over an empty/stale shell that reused the stream id.
+ if (nextIds.has(message.id)) {
+ if (isPendingAssistant) {
+ const existing = nextMessages.find(candidate => candidate.id === message.id)
+
+ if (existing && localPendingSupersedes(message, existing)) {
+ replacements.set(message.id, withAuthoritativeTurnState(message, existing))
+ }
+ }
+
continue
}
@@ -414,6 +509,15 @@ export function preserveLocalPendingTurnMessages(
if (authoritative) {
if (isPendingAssistant) {
+ // Keep the local pending row when it is the same reply further along
+ // and the authoritative row is an empty projection shell or a prefix.
+ // #75825
+ if (!localPendingSupersedes(message, authoritative)) {
+ continue
+ }
+
+ replacements.set(authoritative.id, withAuthoritativeTurnState(message, authoritative))
+
continue
}
@@ -427,7 +531,10 @@ export function preserveLocalPendingTurnMessages(
preserved.push(message)
}
- return preserved.length ? [...nextMessages, ...preserved] : nextMessages
+ const withReplacements =
+ replacements.size > 0 ? nextMessages.map(message => replacements.get(message.id) ?? message) : nextMessages
+
+ return preserved.length ? [...withReplacements, ...preserved] : withReplacements
}
/**