Skip to content

The agent that grows with you

fix(desktop): retire sealed live bubbles from any turn whose fold carries them

brooklyn!37169f1dab62
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 63e320ba2fc..dcd9877659f 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
@@ -1231,6 +1231,128 @@ describe('preserveLocalPendingTurnMessages', () => {
)
})
+ // A Codex Responses turn: an acknowledgement, two progress updates between
+ // tool rounds, then the answer. Live, each seals as its own bubble; history
+ // folds them into one row and may keep the public commentary only in
+ // `reasoning` (#119716). Tool call ids are the durable identity either way.
+ const tool = (toolCallId: string) =>
+ ({ type: 'tool-call', toolCallId, toolName: 'terminal', result: 'ok' }) as ChatMessagePart
+
+ const sealed = (id: string, parts: ChatMessagePart[], extra: Partial<ChatMessage> = {}) =>
+ ({ id, role: 'assistant', parts, pending: false, interim: true, ...extra }) as ChatMessage
+
+ const lunaTurn = (prefix: string, callPrefix: string) => [
+ sealed(`assistant-stream-${prefix}-ack`, [{ type: 'text', text: `${prefix}: on it, reading the logs.` }]),
+ sealed(`assistant-stream-${prefix}-progress-1`, [
+ tool(`${callPrefix}-1`),
+ { type: 'text', text: `${prefix}: logs clean.` }
+ ]),
+ sealed(`assistant-stream-${prefix}-progress-2`, [
+ tool(`${callPrefix}-2`),
+ { type: 'text', text: `${prefix}: config fixed.` }
+ ]),
+ sealed(
+ `assistant-stream-${prefix}-final`,
+ [tool(`${callPrefix}-3`), { type: 'text', text: `${prefix}: all done.` }],
+ {
+ interim: false
+ }
+ )
+ ]
+
+ const lunaFold = (id: string, prefix: string, callPrefix: string, commentary: 'reasoning' | 'text') =>
+ ({
+ id,
+ role: 'assistant',
+ parts: [
+ ...[`${prefix}: on it, reading the logs.`, `${prefix}: logs clean.`, `${prefix}: config fixed.`].flatMap(
+ (text, at) => [
+ commentary === 'text'
+ ? ({ type: 'text', text } as ChatMessagePart)
+ : ({ type: 'reasoning', text: `**Plan**\n\n${text}` } as ChatMessagePart),
+ tool(`${callPrefix}-${at + 1}`)
+ ]
+ ),
+ { type: 'text', text: `${prefix}: all done.` }
+ ]
+ }) as ChatMessage
+
+ it.each(['reasoning', 'text'] as const)(
+ 'retires every sealed bubble of a folded turn whose commentary hydrated as %s',
+ commentary => {
+ const user = msg('1-user', 'user', 'fix it', { rowId: 1 })
+ const next = [user, lunaFold('2-assistant', 'a', 'call-a', commentary)]
+
+ expect(preserveLocalPendingTurnMessages(next, [user, ...lunaTurn('a', 'call-a')])).toBe(next)
+ }
+ )
+
+ // The previous turn's bubbles are not owned by the newest prompt, so they
+ // must not resurface under it (#119511, and the self-sustaining tail of
+ // stale commentary in #119362) — nor may they swallow the live reply.
+ it.each(['reasoning', 'text'] as const)(
+ 'does not re-append an earlier turn under a newer prompt when its commentary hydrated as %s',
+ commentary => {
+ const next = [
+ msg('1-user', 'user', 'fix it', { rowId: 1 }),
+ lunaFold('2-assistant', 'a', 'call-a', commentary),
+ msg('3-user', 'user', 'and the other one', { rowId: 9 })
+ ]
+
+ const previous = [
+ msg('user-1-a', 'user', 'fix it', { rowId: 1 }),
+ ...lunaTurn('a', 'call-a'),
+ // No submit receipt yet, so no acknowledged boundary past turn a.
+ msg('user-2-b', 'user', 'and the other one'),
+ sealed('assistant-stream-live', [tool('call-b-1'), { type: 'text', text: 'b: still going.' }])
+ ]
+
+ expect(preserveLocalPendingTurnMessages(next, previous).map(message => message.id)).toEqual([
+ '1-user',
+ '2-assistant',
+ '3-user',
+ 'assistant-stream-live'
+ ])
+ }
+ )
+
+ // #118228: narration bubbles still marked pending when the rehydrate lands.
+ // A sealed interim's text is final, so the fold carrying it retires it.
+ it('retires pending interim narration the merged fold already carries, even with later turns stored', () => {
+ const user = msg('1-user', 'user', 'run the build', { rowId: 1 })
+
+ // More live bubbles than stored assistant rows: ordinal pairing runs out.
+ const turn = [
+ ...lunaTurn('a', 'call-a')
+ .slice(0, 3)
+ .map(row => ({ ...row, pending: true })),
+ msg('assistant-stream-a-tail', 'assistant', 'a: all done.', { pending: true })
+ ]
+
+ const next = [
+ user,
+ lunaFold('2-assistant', 'a', 'call-a', 'text'),
+ msg('3-system', 'system', 'Background Process Finished: bash build.sh'),
+ msg('4-assistant', 'assistant', 'build verified'),
+ msg('5-user', 'user', 'installed it, same problem', { rowId: 20 }),
+ msg('6-assistant', 'assistant', 'then it is not the line count')
+ ]
+
+ expect(preserveLocalPendingTurnMessages(next, [user, ...turn])).toBe(next)
+ })
+
+ // The fold committed the tool rounds but not the answer yet: that bubble is
+ // the only copy and must survive, while the carried commentary retires.
+ it('keeps the final answer a fold has not committed yet', () => {
+ const user = msg('1-user', 'user', 'fix it', { rowId: 1 })
+ const fold = lunaFold('2-assistant', 'a', 'call-a', 'reasoning')
+ const next = [user, { ...fold, parts: fold.parts.filter(part => part.type !== 'text') }]
+
+ expect(
+ preserveLocalPendingTurnMessages(next, [user, ...lunaTurn('a', 'call-a')]).map(message => message.id)
+ ).toEqual(['1-user', '2-assistant', 'assistant-stream-a-final'])
+ })
+
// 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', () => {
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 2b7fc460a11..4014f3c05a9 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
@@ -596,19 +596,71 @@ const textPartsOf = (message: ChatMessage) =>
return text ? [text] : []
})
+const isPrompt = (message: ChatMessage) => message.role === 'user' && !isGatewaySystemMarker(message)
+
+/**
+ * Committed rows folding the local turn around `index`, for ANY turn, not just
+ * the latest: rows sharing a tool call id with that turn, plus the assistant
+ * rows after its prompt's durable twin. Only the latest turn may fall back to
+ * position (everything after the last stored prompt).
+ */
+function committedFoldsOfLocalTurn(candidates: ChatMessage[], previous: ChatMessage[], index: number): ChatMessage[] {
+ const start = previous.findLastIndex((row, at) => at < index && isPrompt(row))
+ const end = previous.findIndex((row, at) => at > index && isPrompt(row))
+
+ const turnToolIds = new Set(
+ previous
+ .slice(start + 1, end < 0 ? undefined : end)
+ .flatMap(toolCallIdsOf)
+ .filter(Boolean)
+ )
+
+ const owner = previous[start]
+ const ownerRowIds = owner ? transcriptRowIds(owner) : []
+
+ const anchor = owner
+ ? candidates.findIndex(row => row.id === owner.id || transcriptRowIds(row).some(id => ownerRowIds.includes(id)))
+ : -1
+
+ const from = anchor >= 0 ? anchor : end < 0 ? candidates.findLastIndex(isPrompt) : candidates.length
+ const until = candidates.findIndex((row, at) => at > from && isPrompt(row))
+ const segment = new Set(candidates.slice(from + 1, until < 0 ? undefined : until))
+
+ return candidates.filter(
+ row =>
+ row.role === 'assistant' &&
+ !isLiveTailRow(row) &&
+ (segment.has(row) || toolCallIdsOf(row).some(id => turnToolIds.has(id)))
+ )
+}
+
+const hasWholeLines = (haystack: string, needle: string) => `\n${haystack}\n`.includes(`\n${needle}\n`)
+
+/**
+ * A fold carries sealed text verbatim as a text part, or inside Thinking when
+ * the provider stored public commentary in `reasoning` (Codex Responses, #119716).
+ */
+const foldCarriesText = (fold: ChatMessage, text: string) =>
+ fold.parts.some(part =>
+ part.type === 'text'
+ ? textWithoutReferenceLines(part.text).trim() === text
+ : part.type === 'reasoning' && hasWholeLines(part.text, text)
+ )
+
/**
* 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
+ * each interim segment and the final answer as bubbles of their own. A sealed
+ * live bubble is that same occurrence when its turn's folds hold 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 {
+function durableFoldCoversLiveResponse(folds: ChatMessage[], live: ChatMessage): boolean {
const liveToolIds = toolCallIdsOf(live)
+ const sealed = live.pending !== true || live.interim === true
- if (liveToolIds.length && (live.pending === true || liveToolIds.some(id => !id))) {
+ if (!folds.length || (liveToolIds.length && (!sealed || liveToolIds.some(id => !id)))) {
return false
}
@@ -622,29 +674,24 @@ function durableFoldCoversLiveResponse(messages: ChatMessage[], live: ChatMessag
return false
}
- const lastUser = messages.findLastIndex(message => message.role === 'user' && !isGatewaySystemMarker(message))
+ const foldedToolIds = new Set(folds.flatMap(toolCallIdsOf))
- return messages.slice(lastUser + 1).some(message => {
- 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 (!liveToolIds.every(id => foldedToolIds.has(id))) {
+ return false
+ }
- if (live.pending !== true && liveTexts.every(text => foldedTexts.has(text))) {
- return true
- }
+ if (sealed && liveTexts.every(text => folds.some(fold => foldCarriesText(fold, text)))) {
+ return true
+ }
- const folded = lastFoldedResponseText(message)
+ return (
+ Boolean(answer) &&
+ folds.some(fold => {
+ const folded = lastFoldedResponseText(fold)
- return Boolean(answer) && (folded === answer || isStrictAnswerTextExtension(folded, answer))
- })
+ return folded === answer || isStrictAnswerTextExtension(folded, answer)
+ })
+ )
}
export function preserveLocalPendingTurnMessages(
@@ -715,7 +762,6 @@ export function preserveLocalPendingTurnMessages(
// 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>()
- const lastPreviousUser = previousMessages.findLastIndex(row => row.role === 'user' && !isGatewaySystemMarker(row))
let crossedUserBoundary = false
for (const [index, message] of previousMessages.entries()) {
@@ -902,8 +948,7 @@ export function preserveLocalPendingTurnMessages(
if (
isPendingAssistant &&
- previousMessages.indexOf(message) > lastPreviousUser &&
- durableFoldCoversLiveResponse(candidates, message)
+ durableFoldCoversLiveResponse(committedFoldsOfLocalTurn(candidates, previousMessages, index), message)
) {
continue
}