The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retire settled live bubbles a durable fold already carries, with partial or missing receipts (#118670, #119540, #118671)
brooklyn!1e740989eb7c
diff --git a/apps/desktop/src/app/contrib/hooks/folded-tool-turn-refresh.test.tsx b/apps/desktop/src/app/contrib/hooks/folded-tool-turn-refresh.test.tsxnew file mode 100644index 00000000000..f7469d69374--- /dev/null+++ b/apps/desktop/src/app/contrib/hooks/folded-tool-turn-refresh.test.tsx@@ -0,0 +1,198 @@+import type { GatewayEvent } from '@hermes/shared'+import { QueryClient } from '@tanstack/react-query'+import { act, cleanup, render } from '@testing-library/react'+import { useRef } from 'react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { useMessageStream } from '@/app/session/hooks/use-message-stream'+import { useSessionStateCache } from '@/app/session/hooks/use-session-state-cache'+import { getLatestSessionMessages } from '@/hermes'+import { chatMessageText, toChatMessages } from '@/lib/chat-messages'+import { resetLiveSync } from '@/store/live-sync'+import {+ setActiveSessionId,+ setAwaitingResponse,+ setBusy,+ setMessages,+ setSelectedStoredSessionId+} from '@/store/session'+import { $sessionStates, clearAllSessionStates } from '@/store/session-states'+import { clearSessionTodos } from '@/store/todos'+import type { SessionMessage } from '@/types/hermes'++import { reconcileActiveTranscript } from './use-background-sync'++vi.mock('@/hermes', async original => ({+ ...(await original<Record<string, unknown>>()),+ getLatestSessionMessages: vi.fn()+}))++const RUNTIME = 'folded-runtime'+const STORED = 'folded-stored'+const INTERIM = 'Let me look at the files first.'+const FINAL = 'Here is the summary table.\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\nEverything checks out.'+const noop = async () => undefined++const history: SessionMessage[] = [+ { id: 1, role: 'user', content: 'Earlier question', timestamp: 1 },+ { id: 2, role: 'assistant', content: 'Earlier answer', timestamp: 2 },+ { id: 3, role: 'user', content: 'Read the files and summarize', timestamp: 3 }+]++const tools = ['read-1', 'term-1', 'term-2']++const toolCalls = (ids: string[]) =>+ ids.map(id => ({ id, type: 'function', function: { name: 'terminal', arguments: '{}' } }))++// Durable rows for the turn: interim + 3 tool calls, 3 tool results, final.+// toChatMessages folds them into ONE assistant bubble (serverRowSpan > 1).+const durableTurn: SessionMessage[] = [+ ...history,+ {+ id: 4,+ role: 'assistant',+ content: INTERIM,+ timestamp: 4,+ tool_calls: toolCalls(tools)+ },+ ...tools.map((id, index) => ({+ id: 5 + index,+ role: 'tool' as const,+ content: `out ${index}`,+ timestamp: 5 + index,+ tool_call_id: id,+ tool_name: 'terminal'+ })),+ { id: 8, role: 'assistant', content: FINAL, timestamp: 8 }+]++let cache: ReturnType<typeof useSessionStateCache>+let stream: ReturnType<typeof useMessageStream>+let refresh: () => Promise<void>++function Harness() {+ const busyRef = useRef(false)+ const queryClient = useRef(new QueryClient()).current+ const requestSequenceRef = useRef(0)+ const signatureRef = useRef(new Map<string, string>())+ cache = useSessionStateCache({+ activeSessionId: RUNTIME,+ selectedStoredSessionId: STORED,+ busyRef,+ setBusy,+ setAwaitingResponse,+ setMessages+ })+ stream = useMessageStream({+ ...cache,+ queryClient,+ hydrateFromStoredSession: noop,+ refreshHermesConfig: noop,+ refreshSessions: noop+ })+ refresh = () =>+ reconcileActiveTranscript({+ activeSessionIdRef: cache.activeSessionIdRef,+ selectedStoredSessionIdRef: cache.selectedStoredSessionIdRef,+ updateSessionState: cache.updateSessionState,+ busyRef,+ requestSequenceRef,+ signatureRef,+ resolveSession: () => ({ profile: 'default' })+ })++ return null+}++function send(type: GatewayEvent['type'], payload: GatewayEvent['payload'] = {}) {+ act(() => stream.handleGatewayEvent({ session_id: RUNTIME, type, payload }))+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.mocked(getLatestSessionMessages).mockReset()+ setActiveSessionId(RUNTIME)+ setSelectedStoredSessionId(STORED)+})++afterEach(() => {+ cleanup()+ clearSessionTodos(RUNTIME)+ clearAllSessionStates()+ resetLiveSync()+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ setBusy(false)+ setAwaitingResponse(false)+ setMessages([])+ localStorage.clear()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++async function streamToolTurn(receipt: 'complete' | 'partial' | 'none') {+ render(<Harness />)+ act(() => cache.updateSessionState(RUNTIME, state => ({ ...state, messages: toChatMessages(history) }), STORED))++ send('message.start')+ send('message.delta', { text: INTERIM })+ await act(async () => {+ await vi.advanceTimersByTimeAsync(100)+ })+ send('message.interim', { text: INTERIM, already_streamed: true })++ for (const id of tools) {+ send('tool.start', { name: 'terminal', tool_id: id, args: {} })+ send('tool.complete', { name: 'terminal', tool_id: id, result: 'ok' })+ }++ send('reasoning.delta', { text: 'Compose the table.' })++ for (const chunk of FINAL.match(/[\s\S]{1,12}/g) ?? []) {+ send('message.delta', { text: chunk })+ }++ await act(async () => {+ await vi.advanceTimersByTimeAsync(100)+ })+ // `complete` is only true when no compaction/redirect touched the turn; a+ // compacted session (or an older backend) settles with a partial or no receipt.+ send('message.complete', {+ text: FINAL,+ persisted_turn:+ receipt === 'none'+ ? undefined+ : { row_ids: [3, 4, 5, 6, 7, 8], user_row_id: 3, final_assistant_row_id: 8, complete: receipt === 'complete' }+ })+}++async function refreshWith(messages: SessionMessage[]) {+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: STORED, messages })+ await act(async () => {+ await refresh()+ })++ return $sessionStates.get()[RUNTIME].messages.map(chatMessageText)+}++it.each(['complete', 'partial', 'none'] as const)(+ 'paints a tool-interleaved reply once after the refresh folds its durable rows (receipt: %s)',+ async receipt => {+ await streamToolTurn(receipt)+ const texts = await refreshWith(durableTurn)++ expect(texts.filter(text => text.includes('Everything checks out.'))).toHaveLength(1)+ expect(texts).toContain('Earlier answer')+ }+)++it('keeps the settled live reply when the fold lacks one of its tool rounds', async () => {+ await streamToolTurn('none')++ // The newest page stops before the last tool round and the final answer.+ const texts = await refreshWith(+ durableTurn.slice(0, -2).map(row => (row.id === 4 ? { ...row, tool_calls: toolCalls(tools.slice(0, 2)) } : row))+ )++ expect(texts.filter(text => text.includes('Everything checks out.'))).toHaveLength(1)+})diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/folded-segment-refresh.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/folded-segment-refresh.test.tsxnew file mode 100644index 00000000000..9afb441dfae--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-message-stream/folded-segment-refresh.test.tsx@@ -0,0 +1,95 @@+import type { GatewayEventName } from '@hermes/shared'+import { act, cleanup } from '@testing-library/react'+import { afterEach, expect, it } from 'vitest'++import type { ClientSessionState } from '@/app/types'+import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'+import { createClientSessionState } from '@/lib/chat-runtime'+import type { SessionMessage } from '@/types/hermes'++import { preserveLocalPendingTurnMessages } from '../use-session-actions/utils'++import { renderMessageStream } from './test-harness'++afterEach(cleanup)++const FULL = { row_ids: [1, 2, 3, 4, 5, 6], user_row_id: 1, final_assistant_row_id: 6, complete: true }++// #119540: the live stream seals each interim segment (with the tool calls it+// ran) as its own bubble; stored history folds the turn into one row. Without a+// complete persistence receipt (compaction mid-turn, older gateway) the post-turn+// refresh re-appended every segment after the first below the folded reply.+it.each([+ ['a complete receipt', FULL],+ ['a partial receipt', { ...FULL, complete: false }],+ ['no receipt', null]+])('a refreshed multi-segment tool turn renders each segment once with %s', async (_label, receipt) => {+ const sid = 'folded-segments'+ const states = new Map<string, ClientSessionState>()++ states.set(sid, {+ ...createClientSessionState(),+ messages: [{ id: 'user-1', role: 'user', rowId: 1, parts: [{ type: 'text', text: 'q' }] }]+ })++ const stream = renderMessageStream(sid, { states })++ const send = (type: GatewayEventName, payload: Record<string, unknown> = {}) =>+ act(() => stream.handleEvent({ type, payload, session_id: sid }))++ const history: SessionMessage[] = [{ id: 1, role: 'user', content: 'q' }]++ await send('message.start')++ for (const [index, comment] of ['First segment.', 'Second segment.'].entries()) {+ await send('message.delta', { text: comment })+ await send('message.interim', { text: comment, already_streamed: true })+ const id = `tool-${index}`+ await send('tool.start', { name: 'read_file', tool_id: id, args: {} })+ await send('tool.complete', { name: 'read_file', tool_id: id, result: 'read' })+ history.push(+ {+ id: index * 2 + 2,+ role: 'assistant',+ content: comment,+ tool_calls: [{ id, type: 'function', function: { name: 'read_file', arguments: '{}' } }]+ },+ { id: index * 2 + 3, role: 'tool', content: 'read', tool_call_id: id }+ )+ }++ await send('message.delta', { text: 'Done.' })+ await send('message.complete', { text: 'Done.', ...(receipt ? { persisted_turn: receipt } : {}) })+ history.push({ id: 6, role: 'assistant', content: 'Done.' })++ const durable = toChatMessages(history)+ const merged = preserveLocalPendingTurnMessages(durable, stream.state().messages as ChatMessage[])++ expect(merged.map(chatMessageText)).toEqual(durable.map(chatMessageText))+})++it('keeps a settled segment the refreshed fold does not carry yet', () => {+ const merged = preserveLocalPendingTurnMessages(+ [+ { id: '1-user', role: 'user', rowId: 1, parts: [{ type: 'text', text: 'q' }] },+ { id: '2-assistant', role: 'assistant', rowId: 2, parts: [{ type: 'text', text: 'First segment.' }] }+ ],+ [+ { id: 'user-1', role: 'user', rowId: 1, parts: [{ type: 'text', text: 'q' }] },+ {+ id: 'assistant-stream-1',+ role: 'assistant',+ pending: false,+ parts: [{ type: 'text', text: 'First segment.' }]+ },+ {+ id: 'assistant-stream-2',+ role: 'assistant',+ pending: false,+ parts: [{ type: 'text', text: 'Second segment.' }]+ }+ ]+ )++ expect(merged.map(chatMessageText)).toEqual(['q', 'First segment.', 'Second segment.'])+})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.tsindex 318c3bb7c0e..63e320ba2fc 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@@ -637,6 +637,60 @@ describe('preserveLocalPendingTurnMessages', () => {expect(preserveLocalPendingTurnMessages(next, previous)).toEqual(next)})+ // A turn that compressed mid-flight only earns a partial receipt+ // (`complete: false`), but its rows are still proven committed. When a later+ // compaction rewrites every one of them, the local copy is stale history.+ const partialReceipt = { row_ids: [11350, 11355, 11359], complete: false, final_assistant_row_id: 11359 }++ it('does not re-append a partially receipted reply once compaction rewrote all of its rows', () => {+ const previous = [+ msg('u1', 'user', 'q1', { rowId: 11340 }),+ msg('user-9-x', 'user', 'q2', { rowId: 11350 }),+ msg('assistant-stream-9-0', 'assistant', 'r2', {+ pending: false,+ rowId: 11359,+ durableComplete: false,+ persistedTurn: partialReceipt+ })+ ]++ const reinserted = [+ msg('s-summary', 'assistant', '[summary]', { rowId: 11440 }),+ msg('s-u2', 'user', 'q2', { rowId: 11450 }),+ msg('s-a2', 'assistant', 'r2', { rowId: 11459 })+ ]++ const summarizedAway = [+ msg('s-summary', 'assistant', '[summary]', { rowId: 11440 }),+ msg('s-u3', 'user', 'q3', { rowId: 11450 }),+ msg('s-a3', 'assistant', 'r3', { rowId: 11459 })+ ]++ expect(preserveLocalPendingTurnMessages(reinserted, previous)).toEqual(reinserted)+ expect(preserveLocalPendingTurnMessages(summarizedAway, previous)).toEqual(summarizedAway)+ })++ it('keeps a partially receipted reply the store has not reached or still partly holds', () => {+ const reply = msg('assistant-stream-9-0', 'assistant', 'r2 with unpersisted tail', {+ pending: false,+ rowId: 11359,+ durableComplete: false,+ persistedTurn: partialReceipt+ })++ const previous = [msg('u1', 'user', 'q1', { rowId: 11340 }), msg('user-9-x', 'user', 'q2', { rowId: 11350 }), reply]+ const behind = [msg('s-u1', 'user', 'q1', { rowId: 11340 })]++ const partlyHeld = [+ msg('s-u1', 'user', 'q1', { rowId: 11340 }),+ msg('s-u2', 'user', 'q2', { rowId: 11350 }),+ msg('s-a2', 'assistant', 'r2', { rowId: 11460 })+ ]++ expect(preserveLocalPendingTurnMessages(behind, previous).map(message => message.id)).toContain(reply.id)+ expect(preserveLocalPendingTurnMessages(partlyHeld, previous).map(message => message.id)).toContain(reply.id)+ })+it('does not append acknowledged local history after a shifted newest page', () => {const previous = [msg('user-first', 'user', 'Original request', { timestamp: 1 }),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.tsindex ecdffe8dbab..2b7fc460a11 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@@ -586,28 +586,64 @@ function lastFoldedResponseText(message: ChatMessage): string {return afterTool ? text : ''}+const toolCallIdsOf = (message: ChatMessage) =>+ message.parts.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : []))++const textPartsOf = (message: ChatMessage) =>+ message.parts.flatMap(part => {+ const text = part.type === 'text' ? textWithoutReferenceLines(part.text).trim() : ''++ return text ? [text] : []+ })+/**- * History folds a final answer into the preceding tool-round bubble. A live- * stream bubble holding only that answer is the same occurrence, but full-bubble- * equality cannot see it.+ * History folds a tool-heavy turn into one bubble, while the live stream sealed+ * each interim segment and the final answer as bubbles of their own. A settled+ * live bubble is that same occurrence when one committed fold holds every tool+ * call it ran (durable identity) and its text, either verbatim (a sealed middle+ * segment, #119540) or as the final answer, equal or extended (#118670). This+ * holds with a partial or missing completion receipt, where full-bubble+ * equality sees neither.*/function durableFoldCoversLiveResponse(messages: ChatMessage[], live: ChatMessage): boolean {- const needle = textWithoutReferenceLines(chatMessageText(live)).trim()+ const liveToolIds = toolCallIdsOf(live)++ if (liveToolIds.length && (live.pending === true || liveToolIds.some(id => !id))) {+ return false+ }++ const liveTexts = textPartsOf(live)++ const answer = liveToolIds.length+ ? lastFoldedResponseText(live)+ : textWithoutReferenceLines(chatMessageText(live)).trim()- if (!needle || live.parts.some(part => part.type === 'tool-call')) {+ if (!answer && !liveTexts.length && !liveToolIds.length) {return false}const lastUser = messages.findLastIndex(message => message.role === 'user' && !isGatewaySystemMarker(message))return messages.slice(lastUser + 1).some(message => {- if (message.role !== 'assistant' || isLiveTailReplyId(message.id)) {+ if (message.role !== 'assistant' || isLiveTailRow(message)) {+ return false+ }++ const foldedToolIds = new Set(toolCallIdsOf(message))++ if (!liveToolIds.every(id => foldedToolIds.has(id))) {return false}+ const foldedTexts = new Set(textPartsOf(message))++ if (live.pending !== true && liveTexts.every(text => foldedTexts.has(text))) {+ return true+ }+const folded = lastFoldedResponseText(message)- return folded === needle || isStrictAnswerTextExtension(folded, needle)+ return Boolean(answer) && (folded === answer || isStrictAnswerTextExtension(folded, answer))})}@@ -622,7 +658,8 @@ export function preserveLocalPendingTurnMessages(const acknowledged = acknowledgedTranscriptBoundary(nextMessages, previousMessages)const remainingNext = nextMessages.slice(acknowledged.storedIndex + 1)const acknowledgedTurn = nextMessages.slice(Math.max(0, acknowledged.storedIndex))- const lastStoredRowId = nextMessages.reduce((last, message) => Math.max(last, ...transcriptRowIds(message)), 0)+ const storedRowIds = new Set(nextMessages.flatMap(transcriptRowIds))+ const lastStoredRowId = [...storedRowIds].reduce((last, rowId) => Math.max(last, rowId), 0)const nextByRoleOrdinal = new Map<string, ChatMessage>()const nextRoleCounts = new Map<ChatMessage['role'], number>()@@ -742,6 +779,20 @@ export function preserveLocalPendingTurnMessages(continue}+ // A turn that compressed mid-flight earns only a partial receipt, which+ // cannot vouch for the whole bubble. Once the store has moved past every+ // row it names and holds none of them, a later compaction rewrote the turn.+ const receiptRowIds = message.persistedTurn?.row_ids ?? []++ if (+ isPendingAssistant &&+ message.pending !== true &&+ receiptRowIds.length > 0 &&+ receiptRowIds.every(rowId => rowId <= lastStoredRowId && !storedRowIds.has(rowId))+ ) {+ continue+ }+if (isOptimisticUser &&latestAuthoritativeUser &&