Skip to content

The agent that grows with you

fix(desktop): a reply settled during a reconnect's resume keeps its whole text

Tekniumfffccf56eb9d
diff --git a/apps/desktop/e2e/core/reattach-running-turn.spec.ts b/apps/desktop/e2e/core/reattach-running-turn.spec.ts
index ee2a332d845..1781f1f8cb7 100644
--- a/apps/desktop/e2e/core/reattach-running-turn.spec.ts
+++ b/apps/desktop/e2e/core/reattach-running-turn.spec.ts
@@ -225,7 +225,9 @@ test('re-attaching to a running tool turn renders each segment once', async () =
await expect.poll(() => ws.sockets.length, { timeout: 60_000 }).toBeGreaterThan(socketsBefore)
await expect.poll(() => proxy.connections(), { timeout: 60_000 }).toBeGreaterThan(0)
hold.open()
- await settled(page, ws, A(7))
+ // The tail, and even message.complete, can fall in the reconnect gap
+ // (a lossy wire), so the view, not a frame, says the turn settled.
+ await expect(stopButton(page)).toHaveCount(0, { timeout: 120_000 })
session.lossyWire = [U(7)]
await assertTranscriptOracle(page, ws, provider, session, 'reconnect during a tool turn')
} finally {
@@ -358,11 +360,19 @@ test('a narrated segment replayed after a message.start renders once', async ()
await page.reload()
await waitForInteractive(app, page)
await installDuplicateSampler(page)
+ const hold = gate()
provider.script(U(1), [
{ text: words(AI(1), 'commentary', 'before', 'the', 'tool'), toolCalls: [echo(`replay-${nonce}`)] },
- { text: words(A(1), 'a', 'different', 'final', 'answer') }
+ { text: words(A(1), 'a', 'different', 'final', 'answer'), holdAfterFirstChunk: hold }
])
await send(page, `${U(1)} commentary then answer`, 'Enter', ws)
+ // Mid-turn, with the re-sent narration delivered and the answer held:
+ // the frame a reader sees while the turn is still running.
+ await provider.streamStarted(U(1), 1)
+ await expect(viewport(page)).toContainText(A(1))
+ expect(redelivery.redelivered).toBe(true)
+ await page.screenshot({ path: test.info().outputPath('replayed-segment-mid-turn.png') })
+ hold.open()
await settled(page, ws, A(1))
session.sessionId = await currentSessionId(page)
session.expectUserMarkers.push(U(1))
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
index 79cc9d1daf4..a80cee99c02 100644
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/message-stream.ts
@@ -1,5 +1,6 @@
import { type BillingBlock, mergeUsage } from '@hermes/shared'
+import { noteTurnSettled } from '@/app/session/hooks/use-session-actions/settled-turns'
import { burstVibeHearts } from '@/components/chat/vibe-hearts'
import { translateNow } from '@/i18n'
import type { GatewayEventPayload } from '@/lib/chat-messages'
@@ -408,6 +409,7 @@ export function handleMessageStreamEvent(ctx: GatewayEventContext): boolean {
const finalText = coerceGatewayText(payload?.text) || coerceGatewayText(payload?.rendered)
+ noteTurnSettled(sessionId)
completeAssistantMessage(
sessionId,
finalText,
diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/settled-during-resume.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/settled-during-resume.test.ts
new file mode 100644
index 00000000000..9cdae25eac4
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/settled-during-resume.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/store/session-control', () => ({ refreshSupportedSessionControlAfterTurn: vi.fn(async () => undefined) }))
+
+import type { GatewayEventName } from '@hermes/shared'
+
+import { liveTurnSettledDuringResume } from '@/app/session/hooks/use-session-actions/resume-reconcile'
+
+import { handleMessageStreamEvent } from './message-stream'
+import type { GatewayEventContext } from './types'
+
+function complete(sessionId: string): GatewayEventContext {
+ const type: GatewayEventName = 'message.complete'
+
+ return {
+ deps: {
+ activeGatewayProfile: 'default',
+ activeSessionIdRef: { current: sessionId },
+ appendAssistantDelta: vi.fn(),
+ appendReasoningDelta: vi.fn(),
+ compactedTurnRef: { current: new Set() },
+ completeAssistantMessage: vi.fn(),
+ failAssistantMessage: vi.fn(),
+ finalizeInterimAssistantMessage: vi.fn(),
+ flushQueuedDeltas: vi.fn(),
+ dropQueuedDeltas: vi.fn(),
+ hydrateFromStoredSession: vi.fn(async () => undefined),
+ lastCwdInfoSessionRef: { current: null },
+ nativeSubagentSessionsRef: { current: new Set() },
+ queryClient: {} as GatewayEventContext['deps']['queryClient'],
+ refreshHermesConfig: vi.fn(async () => undefined),
+ scheduleSessionsRefresh: vi.fn(),
+ sessionInterrupted: vi.fn(() => false),
+ sessionStateByRuntimeIdRef: { current: new Map() },
+ updateSessionState: vi.fn(),
+ upsertToolCall: vi.fn()
+ },
+ event: { type },
+ explicitSid: sessionId,
+ fromActiveSource: () => true,
+ isActiveEvent: false,
+ occurredAt: Date.now() / 1000,
+ payload: { text: 'the whole answer', status: 'complete' },
+ scheduleConfigRefresh: vi.fn(),
+ sessionId
+ }
+}
+
+// A reconnect re-resumes the open chat; the turn's message.complete can land on
+// the new socket before the resume snapshot (cut while the turn still ran)
+// does. Reconciling that older snapshot over the settled reply rewound it to
+// the snapshot's partial text, often the first chunk.
+describe('a reply settled while a resume is in flight', () => {
+ it('is newer than that resume, which keeps the live transcript', () => {
+ const resumeStartedAtS = Date.now() / 1000 - 1
+
+ handleMessageStreamEvent(complete('runtime-a'))
+
+ expect(liveTurnSettledDuringResume({ session_id: 'runtime-a' }, resumeStartedAtS, true)).toBe(true)
+ })
+
+ it('does not outrank a resume that started after it, another session, or a cold open', () => {
+ handleMessageStreamEvent(complete('runtime-b'))
+ const laterResumeS = Date.now() / 1000 + 1
+
+ expect(liveTurnSettledDuringResume({ session_id: 'runtime-b' }, laterResumeS, true)).toBe(false)
+ expect(liveTurnSettledDuringResume({ session_id: 'runtime-other' }, 0, true)).toBe(false)
+ expect(liveTurnSettledDuringResume({ session_id: 'runtime-b' }, 0, false)).toBe(false)
+ })
+})
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 104da47602e..2a46be86ffa 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
@@ -137,7 +137,6 @@ import { dropTranscriptTail, dropTranscriptTailEverywhere, saveTranscriptTail }
import { isWatchWindow } from '@/store/windows'
import type {
SessionCreateResponse,
- SessionMessage,
SessionMessagesResponse,
SessionResumeResult,
UsageStats
@@ -175,6 +174,11 @@ import {
rememberResolvedResumeOwner,
resolveResumeOwner
} from './resume-owner'
+import {
+ liveTurnSettledDuringResume,
+ reconcileAuthoritativeChatMessages,
+ reconcileAuthoritativeMessages
+} from './resume-reconcile'
import { backgroundRuntimeOptions, runtimeOwner, runtimeOwnerProfile } from './runtime-owner'
import { createGatewaySession, desktopSessionCreateParams } from './session-create-request'
import {
@@ -198,7 +202,6 @@ import {
patchSessionWorkspace,
preserveEquivalentTranscript,
preserveLocalPendingTurnMessages,
- reconcileDurableHistory,
removeRepresentedLocalLiveProjection,
resolveResumedBusy,
resolveSessionProfile,
@@ -264,39 +267,6 @@ function applyStoredUsage(stored: { input_tokens?: number | null; output_tokens?
setCurrentUsage(current => ({ ...current, input, output, total: input + output }))
}
-function reconcileAuthoritativeChatMessages(
- authoritativeMessages: ChatMessage[],
- previousMessages: ChatMessage[],
- liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>,
- sourceRows?: SessionMessage[]
-): ChatMessage[] {
- if (liveProjection && sourceRows) {
- const reconciled = reconcilePersistedLiveTurn(authoritativeMessages, previousMessages, sourceRows, liveProjection)
-
- if (reconciled) {
- return reconciled
- }
- }
-
- return reconcileDurableHistory(
- liveProjection ? appendLiveSessionProjection(authoritativeMessages, liveProjection) : authoritativeMessages,
- previousMessages
- )
-}
-
-function reconcileAuthoritativeMessages(
- authoritativeMessages: SessionResumeResult['messages'],
- previousMessages: ChatMessage[],
- liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>
-): ChatMessage[] {
- return reconcileAuthoritativeChatMessages(
- toChatMessages(authoritativeMessages),
- previousMessages,
- liveProjection,
- authoritativeMessages
- )
-}
-
interface FreshSessionDraftOptions {
preserveRoute?: boolean
replaceRoute?: boolean
@@ -2137,7 +2107,11 @@ export function useSessionActions({
const hasLiveProjection = Boolean(resumed.inflight || resumed.queued)
const preferredMessages = (() => {
- if (options?.authoritativeSnapshot && resumed.messages.length === 0 && !hasLiveProjection) {
+ // A reply the live stream settled during the RPC is newer than this snapshot (resume-settled-turn.ts).
+ if (
+ (options?.authoritativeSnapshot && resumed.messages.length === 0 && !hasLiveProjection) ||
+ liveTurnSettledDuringResume(resumed, resumeStartedAt, resumedSameSelectedSession)
+ ) {
return currentMessages
}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/resume-reconcile.ts b/apps/desktop/src/app/session/hooks/use-session-actions/resume-reconcile.ts
new file mode 100644
index 00000000000..6c2dcd87e37
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/resume-reconcile.ts
@@ -0,0 +1,66 @@
+/**
+ * How a resume snapshot is reconciled with the transcript already on screen.
+ *
+ * A reconnect re-resumes the open chat. The backend cuts that snapshot when it
+ * answers, but the new socket is already attached, so the turn's
+ * `message.complete` can reach the renderer first. Everything the resume
+ * computes from (its in-flight projection, a REST page read before the reply
+ * was stored) then predates the settled reply, and reconciling it over the
+ * live transcript rewound the reply to the partial text the snapshot caught,
+ * often just its first chunk. The live transcript is the newer truth for that
+ * session, so the resume keeps it; durable row identity arrives with the next
+ * transcript refresh.
+ */
+
+import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'
+import type { SessionMessage, SessionResumeResult } from '@/types/hermes'
+
+import { reconcilePersistedLiveTurn } from './persisted-live-turn'
+import { turnSettledSince } from './settled-turns'
+import { appendLiveSessionProjection, reconcileDurableHistory } from './utils'
+
+/**
+ * Whether a re-resume of the chat on screen must keep the live transcript: a
+ * turn of the resumed runtime settled after the resume started (`startedAtS`,
+ * seconds). A cold open has no live transcript of its own to keep.
+ */
+export function liveTurnSettledDuringResume(
+ resumed: Pick<SessionResumeResult, 'session_id'>,
+ startedAtS: number,
+ sameSession: boolean
+): boolean {
+ return sameSession && turnSettledSince(resumed.session_id, startedAtS * 1000)
+}
+
+export function reconcileAuthoritativeChatMessages(
+ authoritativeMessages: ChatMessage[],
+ previousMessages: ChatMessage[],
+ liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>,
+ sourceRows?: SessionMessage[]
+): ChatMessage[] {
+ if (liveProjection && sourceRows) {
+ const reconciled = reconcilePersistedLiveTurn(authoritativeMessages, previousMessages, sourceRows, liveProjection)
+
+ if (reconciled) {
+ return reconciled
+ }
+ }
+
+ return reconcileDurableHistory(
+ liveProjection ? appendLiveSessionProjection(authoritativeMessages, liveProjection) : authoritativeMessages,
+ previousMessages
+ )
+}
+
+export function reconcileAuthoritativeMessages(
+ authoritativeMessages: SessionResumeResult['messages'],
+ previousMessages: ChatMessage[],
+ liveProjection?: Pick<SessionResumeResult, 'inflight' | 'queued' | 'session_id'>
+): ChatMessage[] {
+ return reconcileAuthoritativeChatMessages(
+ toChatMessages(authoritativeMessages),
+ previousMessages,
+ liveProjection,
+ authoritativeMessages
+ )
+}
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/settled-turns.ts b/apps/desktop/src/app/session/hooks/use-session-actions/settled-turns.ts
new file mode 100644
index 00000000000..3dd675b9bfe
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/settled-turns.ts
@@ -0,0 +1,23 @@
+/**
+ * When this renderer last settled a turn of each runtime session (message.complete),
+ * so a resume that was in flight meanwhile can tell its snapshot is older than the
+ * reply on screen (resume-reconcile.ts). Bounded: a resume only asks about the
+ * seconds its own RPC was in flight.
+ */
+
+const settledAt = new Map<string, number>()
+const MAX_TRACKED_SESSIONS = 64
+
+export function noteTurnSettled(runtimeSessionId: string, at = Date.now()): void {
+ settledAt.delete(runtimeSessionId)
+ settledAt.set(runtimeSessionId, at)
+
+ if (settledAt.size > MAX_TRACKED_SESSIONS) {
+ settledAt.delete(settledAt.keys().next().value as string)
+ }
+}
+
+/** Whether a turn of this runtime session settled at or after `sinceMs`. */
+export function turnSettledSince(runtimeSessionId: string, sinceMs: number): boolean {
+ return (settledAt.get(runtimeSessionId) ?? -Infinity) >= sinceMs
+}