Skip to content

The agent that grows with you

fix(desktop): a reply streaming across a reload extends the row the resume restored

Tekniumb7e0c13bacb1
diff --git a/apps/desktop/src/app/session/hooks/reload-resume-stream-target.test.tsx b/apps/desktop/src/app/session/hooks/reload-resume-stream-target.test.tsx
new file mode 100644
index 00000000000..79acfaaf9a0
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/reload-resume-stream-target.test.tsx
@@ -0,0 +1,202 @@
+import type { GatewayEvent } from '@hermes/shared'
+import { QueryClient } from '@tanstack/react-query'
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { useRef } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+import { getLatestSessionMessages } from '@/hermes'
+import { type ChatMessage, chatMessageText, toChatMessages } from '@/lib/chat-messages'
+import { persistInFlightTurnState, resetInFlightTurnJournalStateForTests } from '@/lib/inflight-turn-journal'
+import { $activeGatewayProfile } from '@/store/profile'
+import {
+ _resetSessionOwnerHintsForTests,
+ setActiveSessionId,
+ setAwaitingResponse,
+ setBusy,
+ setConnection,
+ setMessages,
+ setSelectedStoredSessionId,
+ setSessions
+} from '@/store/session'
+import { clearAllSessionStates } from '@/store/session-states'
+import type { SessionMessage, SessionResumeResult } from '@/types/hermes'
+
+import { useMessageStream } from './use-message-stream'
+import { useSessionActions } from './use-session-actions'
+import { useSessionStateCache } from './use-session-state-cache'
+
+vi.mock('@/hermes', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ getLatestSessionMessages: vi.fn()
+}))
+vi.mock('@/store/profile', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ ensureGatewayProfile: vi.fn().mockResolvedValue(undefined)
+}))
+
+// A window reloads (or the app restarts) while a reply streams. The fresh
+// renderer resumes the chat cold: the turn's live row comes back from the
+// in-flight journal or the backend's in-flight projection, and the deltas the
+// agent sends afterwards must extend that row, not open a second bubble beside it.
+const storedId = 'reload-stream-target'
+const runtimeId = 'reload-runtime'
+const noop = async () => undefined
+
+const storedRows: SessionMessage[] = [
+ { id: 1, role: 'user', content: 'U1 first', timestamp: 10 },
+ { id: 2, role: 'assistant', content: 'A1 one', timestamp: 11 },
+ { id: 3, role: 'user', content: 'U2 second', timestamp: 20 }
+]
+
+function mount(snapshot: SessionResumeResult) {
+ const requestGateway = vi.fn().mockResolvedValue(snapshot)
+
+ return renderHook(() => {
+ const busyRef = useRef(false)
+ const queryClient = useRef(new QueryClient()).current
+
+ const cache = useSessionStateCache({
+ activeSessionId: null,
+ selectedStoredSessionId: null,
+ busyRef,
+ setMessages,
+ setBusy,
+ setAwaitingResponse
+ })
+
+ const actions = useSessionActions({
+ ...cache,
+ activeSessionId: null,
+ selectedStoredSessionId: null,
+ busyRef,
+ creatingSessionRef: useRef(false),
+ getRouteToken: () => 'A',
+ getRoutedStoredSessionId: () => null,
+ navigate: vi.fn(),
+ requestGateway,
+ routedSessionId: null
+ })
+
+ const stream = useMessageStream({
+ ...cache,
+ queryClient,
+ hydrateFromStoredSession: noop,
+ refreshHermesConfig: noop,
+ refreshSessions: noop
+ })
+
+ return { cache, actions, stream }
+ })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ localStorage.clear()
+ clearAllSessionStates()
+ resetInFlightTurnJournalStateForTests()
+ _resetSessionOwnerHintsForTests()
+ $activeGatewayProfile.set('default')
+ setConnection(null)
+ setMessages([])
+ setActiveSessionId(null)
+ setSelectedStoredSessionId(null)
+ setBusy(false)
+ setAwaitingResponse(false)
+ setSessions([
+ {
+ id: storedId,
+ title: storedId,
+ source: 'desktop',
+ message_count: 3,
+ tool_call_count: 0,
+ is_active: true,
+ started_at: 1,
+ last_active: 1,
+ ended_at: null,
+ model: null,
+ preview: null,
+ input_tokens: 0,
+ output_tokens: 0
+ }
+ ])
+ vi.mocked(getLatestSessionMessages).mockReset()
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({ session_id: storedId, messages: storedRows })
+})
+
+afterEach(() => {
+ cleanup()
+ clearAllSessionStates()
+ resetInFlightTurnJournalStateForTests()
+ localStorage.clear()
+ setSessions([])
+ setMessages([])
+ setActiveSessionId(null)
+ setSelectedStoredSessionId(null)
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+/** The window before the reload journaled its live row (throttled write). */
+async function journalLiveRowBeforeReload() {
+ const live: ChatMessage[] = [
+ ...toChatMessages(storedRows),
+ { id: 'assistant-stream-before-reload', role: 'assistant', parts: [{ type: 'text', text: 'A2 ' }], pending: true }
+ ]
+
+ persistInFlightTurnState({
+ awaitingResponse: false,
+ busy: true,
+ messages: live,
+ storedSessionId: storedId,
+ streamId: 'assistant-stream-before-reload',
+ turnStartedAt: 19_000
+ })
+ await vi.advanceTimersByTimeAsync(500)
+}
+
+it.each([
+ ['the in-flight journal', true, undefined],
+ ['the backend in-flight projection', false, { user: 'U2 second', assistant: 'A2 ', streaming: true }]
+] as const)('a reply streaming across a reload extends the live row %s restored', async (_label, journaled, inflight) => {
+ if (journaled) {
+ await journalLiveRowBeforeReload()
+ }
+
+ const { result } = mount({
+ session_id: runtimeId,
+ resumed: storedId,
+ messages: storedRows,
+ message_count: 3,
+ running: true,
+ turn_started_at: 19,
+ ...(inflight ? { inflight } : {})
+ } as SessionResumeResult)
+
+ await act(async () => {
+ await result.current.actions.resumeSession(storedId, true)
+ })
+
+ const send = (type: GatewayEvent['type'], payload: GatewayEvent['payload']) =>
+ act(() => result.current.stream.handleGatewayEvent({ session_id: runtimeId, type, payload } as GatewayEvent))
+
+ send('message.delta', { text: 'finished after the reload' })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(150)
+ })
+
+ const replies = () => {
+ const rows = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!.messages
+ const prompt = rows.findLastIndex(row => row.role === 'user')
+
+ return rows.slice(prompt + 1).filter(row => row.role === 'assistant' && chatMessageText(row).trim())
+ }
+
+ expect(replies().map(row => chatMessageText(row).trim())).toEqual(['A2 finished after the reload'])
+
+ send('message.complete', { text: 'A2 finished after the reload', status: 'complete' })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(150)
+ })
+
+ expect(replies().map(row => chatMessageText(row).trim())).toEqual(['A2 finished after the reload'])
+})
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 2a46be86ffa..cc6dace9853 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
@@ -175,9 +175,11 @@ import {
resolveResumeOwner
} from './resume-owner'
import {
+ livePromptStreamId,
liveTurnSettledDuringResume,
reconcileAuthoritativeChatMessages,
- reconcileAuthoritativeMessages
+ reconcileAuthoritativeMessages,
+ resumedStreamTarget
} from './resume-reconcile'
import { backgroundRuntimeOptions, runtimeOwner, runtimeOwnerProfile } from './runtime-owner'
import { createGatewaySession, desktopSessionCreateParams } from './session-create-request'
@@ -274,15 +276,6 @@ interface FreshSessionDraftOptions {
workspaceTarget?: NewChatWorkspaceTarget
}
-/** Session-state patch for a restored blocking prompt row; the first non-null projection is used. */
-function livePromptStreamId(
- ...projections: ({ streamId: string } | null)[]
-): { awaitingResponse: false; sawAssistantPayload: true; streamId: string } | Record<string, never> {
- const live = projections.find(Boolean)
-
- return live ? { awaitingResponse: false, sawAssistantPayload: true, streamId: live.streamId } : {}
-}
-
function normalizeNewChatWorkspaceTarget(target: NewChatWorkspaceTarget): NewChatWorkspaceTarget {
return typeof target === 'string' ? target.trim() || null : target
}
@@ -2346,7 +2339,14 @@ export function useSessionActions({
...livePromptStreamId(pendingConnectionProjection, pendingClarifyProjection),
...(clearedClarifyProjection
? {
- streamId: resumedRunning ? (clearedClarifyProjection.streamId ?? state.streamId) : null
+ streamId: resumedRunning
+ ? resumedStreamTarget(visibleMessagesForView, resumed.session_id, [
+ clearedClarifyProjection.streamId,
+ pendingConnectionProjection?.streamId,
+ state.streamId,
+ inFlightRecovery.streamId
+ ])
+ : null
}
: {})
}),
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
index 6c2dcd87e37..c5c694524ed 100644
--- 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
@@ -64,3 +64,31 @@ export function reconcileAuthoritativeMessages(
authoritativeMessages
)
}
+
+/** Session-state patch for a restored blocking prompt row; the first non-null projection is used. */
+export function livePromptStreamId(
+ ...projections: ({ streamId: string } | null)[]
+): { awaitingResponse: false; sawAssistantPayload: true; streamId: string } | Record<string, never> {
+ const live = projections.find(Boolean)
+
+ return live ? { awaitingResponse: false, sawAssistantPayload: true, streamId: live.streamId } : {}
+}
+
+/**
+ * The row a resumed running turn's next deltas extend: the first candidate id
+ * the resumed transcript holds, else the backend projection's live row
+ * (`assistant-stream-<runtime id>`). A cold resume (window reload, app restart)
+ * has no stream target of its own, and keeping that empty one made the next
+ * delta open a second bubble beside the row the resume had just restored, so
+ * the reply split in two and its final text drew twice until the next refresh.
+ */
+export function resumedStreamTarget(
+ messages: ChatMessage[],
+ runtimeId: string,
+ candidates: (null | string | undefined)[]
+): null | string {
+ const ids = new Set(messages.map(message => message.id))
+ const held = [...candidates, `assistant-stream-${runtimeId}`].find(id => id && ids.has(id))
+
+ return held ?? candidates.find(Boolean) ?? null
+}