Skip to content

The agent that grows with you

fix(desktop): make retained live-turn resume idempotent

BearHuddlestonc3f5c37ecbdd
diff --git a/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx b/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx
index 4a30c2d58fc..542a63201c5 100644
--- a/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx
+++ b/apps/desktop/src/app/session/hooks/resume-occurrences.test.tsx
@@ -206,7 +206,7 @@ it.each([
send('tool.start', { name: 'read_file', tool_id: `call-${index}`, args: {} })
send('tool.complete', { name: 'read_file', tool_id: `call-${index}`, result: 'fixture' })
})
- send('message.delta', { text: `\n\n${race === 'snapshot-ahead' ? tail.slice(0, 10) : tail}` })
+ send('message.delta', { text: `\n\n${race === 'snapshot-ahead' ? 'The res' : tail}` })
await act(async () => {
await vi.advanceTimersByTimeAsync(150)
})
@@ -274,6 +274,25 @@ it.each([
expect(
rows.flatMap(row => row.parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : [])))
).toEqual(comments.map((_, index) => `call-${index}`))
+
+ if (race !== 'missing-ids') {
+ // Activation feeds its previous projection back into the warm cache.
+ // Replaying an unchanged snapshot must not create another occurrence.
+ for (let resume = 0; resume < 2; resume++) {
+ await act(async () => {
+ await result.current.actions.resumeSession(storedId, true)
+ })
+ const repeatedRows = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!.messages
+
+ expect(repeatedRows.filter(row => row.role === 'assistant').map(chatMessageText)).toEqual(
+ rows.filter(row => row.role === 'assistant').map(chatMessageText)
+ )
+ expect(
+ repeatedRows.flatMap(row => row.parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : [])))
+ ).toEqual(comments.map((_, index) => `call-${index}`))
+ expect(new Set(repeatedRows.map(row => row.id)).size).toBe(repeatedRows.length)
+ }
+ }
}
)
@@ -342,3 +361,90 @@ it.each(['snapshot-ahead', 'history-ahead', 'unpersisted-before-correction'] as
}
}
)
+
+it.each([prompt, 'Inspect the next file'])(
+ 'projects the accepted next-turn queue once across cold and repeated warm resume (%s)',
+ async queued => {
+ const durable = history([commentary])
+
+ const snapshot: SessionResumeResult = {
+ session_id: runtimeId,
+ resumed: storedId,
+ messages: [],
+ message_count: 0,
+ running: true,
+ inflight: { user: prompt, assistant: `${commentary}\n\n${tail}`, streaming: true },
+ queued: { user: queued }
+ }
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: storedId, messages: durable })
+
+ const { result } = mount(snapshot)
+
+ for (let resume = 0; resume < 3; resume++) {
+ if (resume === 2) {
+ // Later text-only arrivals extend the same backend queue slot.
+ snapshot.queued!.user = `${queued}\n\nThen inspect the README`
+ }
+
+ await act(async () => {
+ await result.current.actions.resumeSession(storedId, true)
+ })
+ const rows = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!.messages
+
+ expect(rows.filter(row => row.role === 'user').map(chatMessageText)).toEqual([prompt, snapshot.queued!.user])
+ expect(new Set(rows.map(row => row.id)).size).toBe(rows.length)
+ expect(
+ rows.flatMap(row => row.parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : [])))
+ ).toEqual(['call-0'])
+ }
+ }
+)
+
+it('settles a retained idle error once across repeated resume and a changed error snapshot', async () => {
+ const partial = 'The partial result'
+
+ const snapshot: SessionResumeResult = {
+ session_id: runtimeId,
+ resumed: storedId,
+ messages: [],
+ message_count: 0,
+ running: false,
+ inflight: {
+ user: prompt,
+ assistant: partial,
+ streaming: false,
+ status: 'error',
+ recoverable: true,
+ error: 'Connection reset',
+ error_surface: { layer: 'streaming', code: 'stream_drop', retryable: true }
+ }
+ }
+
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: storedId, messages: [user] })
+
+ const { result } = mount(snapshot)
+
+ for (let resume = 0; resume < 3; resume++) {
+ if (resume === 2) {
+ snapshot.inflight!.error = 'Upstream timed out'
+ snapshot.inflight!.error_surface = { layer: 'provider', code: 'timeout', retryable: true }
+ }
+
+ await act(async () => {
+ await result.current.actions.resumeSession(storedId, true)
+ })
+ const state = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!
+
+ expect(state.messages.filter(row => row.role === 'assistant').map(chatMessageText)).toEqual([partial])
+ expect(state.messages.filter(row => row.error)).toHaveLength(1)
+ expect(state.messages.at(-1)).toMatchObject({
+ error: snapshot.inflight!.error,
+ errorSurface: snapshot.inflight!.error_surface,
+ pending: false
+ })
+ expect(new Set(state.messages.map(row => row.id)).size).toBe(state.messages.length)
+ expect(state.busy).toBe(false)
+ expect(state.awaitingResponse).toBe(false)
+ }
+})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.test.ts b/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.test.ts
new file mode 100644
index 00000000000..50b5854c424
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.test.ts
@@ -0,0 +1,146 @@
+import { expect, it } from 'vitest'
+
+import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'
+import type { SessionMessage, SessionResumeResult } from '@/types/hermes'
+
+import { mergeLiveAssistantRun } from './live-turn-remainder'
+import { reconcilePersistedLiveTurn } from './persisted-live-turn'
+
+const assistant = (id: string, text: string, extra: Partial<ChatMessage> = {}): ChatMessage => ({
+ id,
+ role: 'assistant',
+ parts: [{ type: 'text', text }],
+ ...extra
+})
+
+it('extends one response across arbitrary chunk cuts without changing its tool or text occurrences', () => {
+ const tool = {
+ type: 'tool-call' as const,
+ toolCallId: 'local-tool',
+ toolName: 'read_file',
+ args: {},
+ argsText: '{}',
+ result: 'fixture'
+ }
+
+ const remote = [assistant('snapshot', 'Checking.\n\nThe result.', { pending: true })]
+
+ for (let cut = 1; cut < 'The result.'.length; cut++) {
+ let local = [
+ assistant('live', '', {
+ parts: [
+ { type: 'text', text: 'Checking.' },
+ tool,
+ { type: 'text', text: `\n\n${'The result.'.slice(0, cut)}` }
+ ],
+ pending: true
+ })
+ ]
+
+ for (let resume = 0; resume < 3; resume++) {
+ local = mergeLiveAssistantRun(remote, local)
+ expect(local.map(chatMessageText)).toEqual(['Checking.\n\nThe result.'])
+ expect(local.flatMap(row => row.parts.filter(part => part.type === 'tool-call'))).toEqual([tool])
+ expect(local.map(row => row.id)).toEqual(['live'])
+ }
+ }
+
+ const sealed = assistant('sealed', '', {
+ parts: [{ type: 'text', text: 'The res', completedAt: 10 }]
+ })
+
+ const terminal = [assistant('snapshot', 'The result.', { error: 'Connection reset' })]
+ const settled = mergeLiveAssistantRun(terminal, [sealed])
+ expect(settled.map(chatMessageText)).toEqual(['The result.'])
+ expect(mergeLiveAssistantRun(terminal, settled)).toEqual(settled)
+ expect(settled[0].parts[0].completedAt).toBe(10)
+})
+
+it('settles a matching partial error without discarding richer local parts or distinct failures', () => {
+ const tool = { type: 'tool-call' as const, toolCallId: 'local-tool', toolName: 'read_file', args: {}, argsText: '{}' }
+ const surface = { layer: 'streaming' as const, code: 'stream_drop', retryable: true }
+
+ const failed = assistant('snapshot', 'The result.', {
+ error: 'Connection reset',
+ errorSurface: surface,
+ pending: false
+ })
+
+ const local = assistant('live', '', {
+ parts: [tool, { type: 'text', text: 'The result. More local detail.' }],
+ pending: true
+ })
+
+ let rows = mergeLiveAssistantRun([failed], [local])
+
+ for (let resume = 0; resume < 3; resume++) {
+ expect(rows).toHaveLength(1)
+ expect(rows[0]).toMatchObject({
+ id: local.id,
+ parts: local.parts,
+ error: failed.error,
+ errorSurface: surface,
+ pending: false
+ })
+ rows = mergeLiveAssistantRun([failed], rows)
+ }
+
+ const earlier = assistant('earlier-failure', 'A different partial reply', { error: 'Read failed', pending: false })
+ rows = mergeLiveAssistantRun([failed], [earlier])
+ expect(rows).toEqual([earlier, failed])
+ expect(mergeLiveAssistantRun([failed], rows)).toEqual(rows)
+
+ const equalTextDifferentFailure = assistant('another-failure', chatMessageText(failed), {
+ error: 'Permission denied'
+ })
+
+ expect(mergeLiveAssistantRun([failed], [equalTextDifferentFailure])).toEqual([equalTextDifferentFailure, failed])
+ expect(mergeLiveAssistantRun([assistant('distinct', 'Unrelated reply')], [local])).toEqual([
+ local,
+ assistant('distinct', 'Unrelated reply')
+ ])
+})
+
+it('pairs only the queue projection, preserving equal corrections and different local queued occurrences', () => {
+ const prompt = 'Inspect this file'
+ const correction = 'Also inspect its tests'
+ const rows: SessionMessage[] = [{ id: 1, role: 'user', content: prompt }]
+
+ const projection: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'> = {
+ session_id: 'runtime',
+ inflight: { user: prompt, assistant: '', corrections: [correction], correction_offsets: [0], streaming: true },
+ queued: { user: correction }
+ }
+
+ const reconcile = (previous: ChatMessage[]) =>
+ reconcilePersistedLiveTurn(toChatMessages(rows), previous, rows, projection, messages => messages)!
+
+ let current = reconcile([])
+
+ const unrelatedUser: ChatMessage = { id: 'local-user', role: 'user', parts: [{ type: 'text', text: correction }] }
+
+ const oldQueue: ChatMessage = {
+ id: 'user-queued-older-runtime',
+ role: 'user',
+ parts: [{ type: 'text', text: 'A different queued request' }]
+ }
+
+ const response = assistant('local-response', 'An unrepresented later reply')
+ current.push(unrelatedUser, oldQueue, response)
+
+ for (let resume = 0; resume < 3; resume++) {
+ current = reconcile(current)
+ expect(current.filter(row => row.role === 'user').map(chatMessageText)).toEqual([
+ prompt,
+ correction,
+ correction,
+ correction,
+ chatMessageText(oldQueue)
+ ])
+ expect(current.filter(row => row.id === 'user-queued-runtime')).toHaveLength(1)
+ expect(current).toContainEqual(unrelatedUser)
+ expect(current).toContainEqual(oldQueue)
+ expect(current).toContainEqual(response)
+ expect(new Set(current.map(row => row.id)).size).toBe(current.length)
+ }
+})
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.ts b/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.ts
index 6f3fe616f23..d429b21e649 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/live-turn-remainder.ts
@@ -1,4 +1,4 @@
-import { assistantTextPart, type ChatMessage, chatMessageText } from '@/lib/chat-messages'
+import { appendAssistantTextPart, type ChatMessage, chatMessageText } from '@/lib/chat-messages'
/** Whitespace normalization is for comparison only; cuts always address the original text. */
function comparable(text: string): { text: string; ends: number[] } {
@@ -20,23 +20,28 @@ function comparable(text: string): { text: string; ends: number[] } {
}
function textSpans(messages: ChatMessage[]) {
- let text = ''
+ const spans: string[] = []
for (const message of messages) {
- for (const part of message.parts) {
- if (part.type !== 'text' || !part.text.trim()) {
- continue
- }
+ let text = ''
- if (text) {
- text += '\n\n'
+ for (const part of message.parts) {
+ if (part.type === 'text') {
+ text += part.text
+ } else if (text) {
+ spans.push(text)
+ text = ''
}
+ }
- text += part.text
+ if (text) {
+ spans.push(text)
}
}
- return { text }
+ // Adjacent chunks are one text occurrence, even if an earlier activation
+ // split them. Only a message/tool/channel boundary inserts a separator.
+ return { text: spans.filter(text => text.trim()).join('\n\n') }
}
function hasContent(message: ChatMessage): boolean {
@@ -55,32 +60,57 @@ export function mergeLiveAssistantRun(projected: ChatMessage[], cached: ChatMess
return local
}
- const live = comparable(textSpans(local).text).text
- const remoteSpans = textSpans(projected)
- const remote = comparable(remoteSpans.text)
const terminal = projected.at(-1)!
if (terminal.error) {
- return [...local, terminal]
+ // A previous activation may already have appended this retained failure
+ // beside a distinct local response. Reconcile that occurrence, not the run.
+ const replayIndex = local.findIndex(message => message.id === terminal.id)
+
+ if (replayIndex >= 0 && local.length > 1) {
+ return [
+ ...local.slice(0, replayIndex),
+ ...mergeLiveAssistantRun(projected, [local[replayIndex]]),
+ ...local.slice(replayIndex + 1)
+ ]
+ }
+
+ if (local.some(message => message.error && message.error !== terminal.error && message.id !== terminal.id)) {
+ return [...local, ...projected]
+ }
}
+ const live = comparable(textSpans(local).text).text
+ const remoteSpans = textSpans(projected)
+ const remote = comparable(remoteSpans.text)
+
+ const settled = (message: ChatMessage): ChatMessage => ({
+ ...message,
+ pending: terminal.pending === true,
+ interim: terminal.interim,
+ ...(terminal.error ? { error: terminal.error, errorSurface: terminal.errorSurface ?? message.errorSurface } : {})
+ })
+
if (!remote.text || live.startsWith(remote.text)) {
- return local.map((message, index) =>
- index === local.length - 1 ? { ...message, pending: terminal.pending === true } : message
- )
+ return local.map((message, index) => (index === local.length - 1 ? settled(message) : message))
}
if (remote.text.startsWith(live)) {
- const suffix = live ? remoteSpans.text.slice(remote.ends[live.length - 1]) : remoteSpans.text
+ let suffix = live ? remoteSpans.text.slice(remote.ends[live.length - 1]) : remoteSpans.text
const last = local.at(-1)!
+ const lastPart = last.parts.at(-1)
+
+ // This is the same text occurrence, not another paragraph. Keeping a
+ // mid-word suffix in its own part invents a boundary on the next resume.
+ if (lastPart?.type === 'text' && /\s$/.test(lastPart.text)) {
+ suffix = suffix.trimStart()
+ }
return [
...local.slice(0, -1),
{
- ...last,
- pending: terminal.pending === true,
- interim: terminal.interim,
- parts: [...last.parts, assistantTextPart(suffix)]
+ ...settled(last),
+ parts: appendAssistantTextPart(last.parts, suffix)
}
]
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts b/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts
index e915be252f6..2a149f1b8fa 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/persisted-live-turn.ts
@@ -238,6 +238,8 @@ export function reconcilePersistedLiveTurn(
localStart >= 0 ? previous.slice(0, localStart + 1) : previous
)
+ const turnStart = result.length
+
let pairedLocal = localStart >= 0
let unpairedLocal: ChatMessage[] = []
@@ -302,7 +304,21 @@ export function reconcilePersistedLiveTurn(
result.push(...unpairedLocal)
if (projection.queued?.user) {
- result.push({ id: `user-queued-${projection.session_id}`, role: 'user', parts: [textPart(projection.queued.user)] })
+ const id = `user-queued-${projection.session_id}`
+
+ const queuedIndex = result.findIndex(
+ (message, index) => index >= turnStart && message.role === 'user' && message.id === id
+ )
+
+ const parts = [textPart(projection.queued.user)]
+
+ // The anchored turn has one next-turn queue slot. Refresh its projection
+ // in place; equal correction/optimistic user text is a different occurrence.
+ if (queuedIndex >= 0) {
+ result[queuedIndex] = { ...result[queuedIndex], parts }
+ } else {
+ result.push({ id, role: 'user', parts })
+ }
}
return result