Skip to content

The agent that grows with you

fix(desktop): hold history reads behind reconnect replay

BearHuddleston37e0ac0079fb
diff --git a/apps/desktop/src/app/contrib/hooks/replay-hydration.test.tsx b/apps/desktop/src/app/contrib/hooks/replay-hydration.test.tsx
new file mode 100644
index 00000000000..cdf8c4afcdb
--- /dev/null
+++ b/apps/desktop/src/app/contrib/hooks/replay-hydration.test.tsx
@@ -0,0 +1,312 @@
+import { type GatewayEvent, JsonRpcGatewayClient } from '@hermes/shared'
+import { act, cleanup, waitFor } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import type { ClientSessionState } from '@/app/types'
+import { getLatestSessionMessages } from '@/hermes'
+import { chatMessageText } from '@/lib/chat-messages'
+import { createClientSessionState } from '@/lib/chat-runtime'
+import { setPrimaryGateway } from '@/store/gateway'
+import { setActiveSessionId, setBusy, setSelectedStoredSessionId } from '@/store/session'
+import { clearAllSessionStates, publishSessionState } from '@/store/session-states'
+
+import { renderMessageStream } from '../../session/hooks/use-message-stream/test-harness'
+
+import {
+ hydrateStoredSessionTranscript,
+ reconcileActiveTranscript,
+ reconcileTileTranscripts
+} from './use-background-sync'
+
+vi.mock('@/hermes', async original => ({
+ ...(await original<Record<string, unknown>>()),
+ getLatestSessionMessages: vi.fn()
+}))
+
+const sid = 'replay-hydration-runtime'
+const stored = 'replay-hydration-stored'
+
+class Socket extends EventTarget {
+ readyState = 0
+ sent: { id: string; method: string; params: Record<string, unknown> }[] = []
+ send(data: string) {
+ this.sent.push(JSON.parse(data))
+ }
+ close() {
+ this.readyState = 3
+ this.dispatchEvent(new CloseEvent('close'))
+ }
+ open() {
+ this.readyState = 1
+ this.dispatchEvent(new Event('open'))
+ }
+ frame(frame: unknown) {
+ this.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(frame) }))
+ }
+ event(event: GatewayEvent) {
+ this.frame({ jsonrpc: '2.0', method: 'event', params: event })
+ }
+}
+
+function event(seq: number, type: GatewayEvent['type'], payload: Record<string, unknown> = {}): GatewayEvent {
+ return { session_id: sid, seq, type, payload: { timestamp: seq, ...payload } } as GatewayEvent
+}
+
+async function setup(surface: 'active' | 'tile' | 'fallback') {
+ setActiveSessionId(surface === 'tile' ? 'another-runtime' : sid)
+ setSelectedStoredSessionId(stored)
+ const states = new Map<string, ClientSessionState>()
+
+ const updateSessionState = (id: string, updater: (state: ClientSessionState) => ClientSessionState) => {
+ const next = updater(states.get(id) ?? createClientSessionState(stored))
+ states.set(id, next)
+ publishSessionState(id, next)
+
+ return next
+ }
+
+ const stream = renderMessageStream(sid, { states, updateSessionState })
+ const sockets: Socket[] = []
+
+ const client = new JsonRpcGatewayClient({
+ heartbeatIntervalMs: 0,
+ heartbeatDeadlineMs: 0,
+ socketFactory: () => {
+ const socket = new Socket()
+ sockets.push(socket)
+
+ return socket as unknown as WebSocket
+ }
+ })
+
+ setPrimaryGateway(client)
+ client.onEvent(stream.handleEvent)
+
+ const connect = async () => {
+ const promise = client.connect('ws://fixture.test')
+ const socket = sockets.at(-1)!
+ socket.open()
+ await promise
+
+ return socket
+ }
+
+ const first = await connect()
+ act(() => first.event(event(1, 'session.info', { running: false })))
+ client.invalidate()
+ const second = await connect()
+ const request = second.sent.find(item => item.method === 'session.events.since')!
+ expect(request.params.last_seen).toBe(1)
+ const signatureRef = { current: new Map<string, string>() }
+ const requestSequenceRef = { current: 0 }
+ const activeSessionIdRef = { current: sid }
+ const selectedStoredSessionIdRef = { current: stored }
+
+ const refresh = () =>
+ surface === 'tile'
+ ? reconcileTileTranscripts({
+ tiles: [{ storedSessionId: stored, runtimeId: sid }],
+ signatureRef,
+ requestSequenceRef,
+ updateSessionState
+ })
+ : surface === 'fallback'
+ ? hydrateStoredSessionTranscript({
+ attempts: 1,
+ storedSessionId: stored,
+ runtimeSessionId: sid,
+ storedProfile: 'default',
+ updateSessionState
+ })
+ : reconcileActiveTranscript({
+ activeSessionIdRef,
+ selectedStoredSessionIdRef,
+ busyRef: { current: false },
+ requestSequenceRef,
+ signatureRef,
+ resolveSession: () => ({ profile: 'default' }),
+ updateSessionState
+ })
+
+ return { client, stream, refresh, second, request, connect, activeSessionIdRef, selectedStoredSessionIdRef }
+}
+
+const replay = [
+ event(2, 'message.start'),
+ event(3, 'message.delta', { text: 'Earlier progress.' }),
+ event(4, 'message.interim', { text: 'Earlier progress.', already_streamed: true }),
+ event(5, 'tool.start', { name: 'read_file', tool_id: 'old-call', args: { path: 'example.py' } }),
+ event(6, 'tool.complete', { name: 'read_file', tool_id: 'old-call', result: 'fixture contents' }),
+ event(7, 'message.delta', { text: 'Finished result.' }),
+ event(8, 'message.complete', { text: 'Finished result.' }),
+ event(9, 'session.info', { running: false })
+]
+
+function stubHistory() {
+ vi.mocked(getLatestSessionMessages).mockResolvedValue({
+ session_id: stored,
+ messages: [
+ { id: 1, role: 'user', content: 'Review example', timestamp: 1 },
+ {
+ id: 2,
+ role: 'assistant',
+ content: 'Earlier progress.',
+ timestamp: 2,
+ tool_calls: [
+ { id: 'old-call', type: 'function', function: { name: 'read_file', arguments: '{"path":"example.py"}' } }
+ ]
+ },
+ {
+ id: 3,
+ role: 'tool',
+ content: 'fixture contents',
+ timestamp: 3,
+ tool_call_id: 'old-call',
+ tool_name: 'read_file'
+ },
+ { id: 4, role: 'assistant', content: 'Finished result.', timestamp: 4 }
+ ]
+ })
+}
+
+afterEach(() => {
+ cleanup()
+ clearAllSessionStates()
+ setPrimaryGateway(null)
+ setActiveSessionId(null)
+ setSelectedStoredSessionId(null)
+ setBusy(false)
+ vi.mocked(getLatestSessionMessages).mockReset()
+})
+
+it.each(['active', 'tile', 'fallback'] as const)(
+ 'orders %s history after full replay without duplicate turns',
+ async surface => {
+ const { client, stream, refresh, second, request } = await setup(surface)
+
+ try {
+ stubHistory()
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = refresh()
+ })
+ // The database is already complete; publishing it ahead of the replay is
+ // precisely the race. Do not issue the read until this session catches up.
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ await act(async () => {
+ second.frame({ id: request.id, jsonrpc: '2.0', result: { events: replay } })
+ await pending
+ })
+ const texts = stream.state().messages.map(chatMessageText).join('\n')
+
+ expect(texts.match(/Earlier progress\./g)).toHaveLength(1)
+ expect(texts.match(/Finished result\./g)).toHaveLength(1)
+ expect(texts).toContain('Review example')
+ expect(stream.state().busy).toBe(false)
+ } finally {
+ client.close()
+ }
+ }
+)
+
+it('keeps an unseen live turn parked behind replay instead of painting an idle snapshot over it', async () => {
+ const { client, stream, refresh, second, request } = await setup('active')
+
+ try {
+ stubHistory()
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = refresh()
+ })
+ act(() => {
+ second.event(event(10, 'message.start'))
+ second.event(event(11, 'message.delta', { text: 'New work.' }))
+ })
+ await act(async () => {
+ second.frame({ id: request.id, jsonrpc: '2.0', result: { events: replay } })
+ await pending
+ })
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ expect(stream.state().busy).toBe(true)
+ // Replay dispatch does not flush the renderer's coalesced delta timer.
+ await waitFor(() => expect(stream.state().messages.map(chatMessageText).join('\n')).toContain('New work.'))
+ } finally {
+ client.close()
+ }
+})
+
+it('abandons a queued history read when its replay socket is invalidated', async () => {
+ const { client, refresh } = await setup('active')
+ stubHistory()
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = refresh()
+ })
+ await act(async () => {
+ client.invalidate()
+ await pending
+ })
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ client.close()
+})
+
+it('does not follow a stale selection after waiting for replay', async () => {
+ const { client, refresh, second, request, selectedStoredSessionIdRef } = await setup('active')
+
+ try {
+ stubHistory()
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = refresh()
+ })
+ selectedStoredSessionIdRef.current = 'another-session'
+ await act(async () => {
+ second.frame({ id: request.id, jsonrpc: '2.0', result: { events: replay } })
+ await pending
+ })
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ } finally {
+ client.close()
+ }
+})
+
+it('checks replay again when a socket reconnects during an existing history read', async () => {
+ const { client, stream, refresh, second, request, connect } = await setup('active')
+
+ try {
+ await act(async () => second.frame({ id: request.id, jsonrpc: '2.0', result: { events: [] } }))
+ stubHistory()
+ const snapshot = await getLatestSessionMessages(stored)
+ vi.mocked(getLatestSessionMessages).mockReset()
+ let release!: () => void
+ vi.mocked(getLatestSessionMessages).mockReturnValue(
+ new Promise(resolve => {
+ release = () => resolve(snapshot)
+ })
+ )
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = refresh()
+ })
+ expect(getLatestSessionMessages).toHaveBeenCalledTimes(1)
+ client.invalidate()
+ const next = await connect()
+ const replayRequest = next.sent.find(item => item.method === 'session.events.since')!
+ await act(async () => {
+ release()
+ })
+ // The held REST result must not paint a completed turn ahead of replay.
+ expect(stream.state().messages.map(chatMessageText).join('\n')).not.toContain('Finished result.')
+ await act(async () => {
+ next.frame({ id: replayRequest.id, jsonrpc: '2.0', result: { events: replay } })
+ await pending
+ })
+ stubHistory()
+ await act(refresh)
+ const text = stream.state().messages.map(chatMessageText).join('\n')
+ expect(text).toContain('Review example')
+ expect(text.match(/Finished result\./g)).toHaveLength(1)
+ } finally {
+ client.close()
+ }
+})
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
index d34297bf123..7f4b2d0e74b 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -8,6 +8,7 @@ import { type ChatMessage, preserveLocalAssistantErrors, sealOpenToolParts, toCh
import { createClientSessionState } from '@/lib/chat-runtime'
import { sessionMessagesSignature } from '@/lib/session-signatures'
import { latestSessionTodos } from '@/lib/todos'
+import { pendingSessionReplay } from '@/store/gateway'
import { $sidebarShowArchived } from '@/store/layout'
import { $changeEventsAvailable, $cronChangeTick, $sessionsChangeTick } from '@/store/live-sync'
import { $onBattery, batteryPollInterval } from '@/store/power'
@@ -222,12 +223,31 @@ export async function reconcileTileTranscripts({
const profileScope = profileScopeForTranscriptSession(tile)
const signatureKey = tileTranscriptSignatureKey(tile)
- const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages
try {
+ const replay = pendingSessionReplay(runtimeSessionId)
+
+ if (replay && !(await replay)) {
+ continue
+ }
+
+ if (
+ requestId !== requestSequenceRef.current ||
+ !tileStillPresent() ||
+ tileRuntimeOwnsLiveState(runtimeSessionId)
+ ) {
+ continue
+ }
+
+ const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages
// Passive: a hidden tile's refresh must never cold-start its owner
// backend or hold a pool slot (#103375); no warm backend = retry next tick.
const latest = await getLatestSessionMessages(storedSessionId, profileScope, { passive: true })
+ const replayAtReturn = pendingSessionReplay(runtimeSessionId)
+
+ if (replayAtReturn && !(await replayAtReturn)) {
+ continue
+ }
const current = $sessionStates.get()[runtimeSessionId]
@@ -295,6 +315,12 @@ export async function hydrateStoredSessionTranscript({
storedProfile: ProfileScope
updateSessionState: ActiveTranscriptRefreshDeps['updateSessionState']
}): Promise<void> {
+ const replay = pendingSessionReplay(runtimeSessionId)
+
+ if (replay && !(await replay)) {
+ return
+ }
+
const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages
const superseded = () =>
@@ -312,6 +338,11 @@ export async function hydrateStoredSessionTranscript({
try {
const latest = await getLatestSessionMessages(storedSessionId, storedProfile)
+ const replayAtReturn = pendingSessionReplay(runtimeSessionId)
+
+ if (replayAtReturn && !(await replayAtReturn)) {
+ return
+ }
// This fallback belongs to the completed turn, not any subsequent turn
// that ran during the read or retry delay. Its todo restore is stale too.
@@ -378,6 +409,22 @@ export async function reconcileActiveTranscript({
const requestId = requestSequenceRef.current + 1
requestSequenceRef.current = requestId
+ const replay = pendingSessionReplay(runtimeSessionId)
+
+ if (replay && !(await replay)) {
+ return
+ }
+
+ if (
+ requestId !== requestSequenceRef.current ||
+ busyRef.current ||
+ tileRuntimeOwnsLiveState(runtimeSessionId) ||
+ selectedStoredSessionIdRef.current !== storedSessionId ||
+ activeSessionIdRef.current !== runtimeSessionId
+ ) {
+ return
+ }
+
// Busy at both endpoints can be false even though an entire turn streamed
// while HTTP was in flight. Never let that older read replace newer text.
const messagesAtRequest = $sessionStates.get()[runtimeSessionId]?.messages
@@ -386,6 +433,12 @@ export async function reconcileActiveTranscript({
const profileScope: ProfileScope = profileScopeForTranscriptSession(stored)
const latest = await getLatestSessionMessages(storedSessionId, profileScope)
+ const replayAtReturn = pendingSessionReplay(runtimeSessionId)
+
+ if (replayAtReturn && !(await replayAtReturn)) {
+ return
+ }
+
const current = $sessionStates.get()[runtimeSessionId]
if (
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 5dd13612a0f..e87c6acdad5 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
@@ -34,6 +34,7 @@ import {
$gateway,
openGatewayForAgent,
openGatewayForProfile,
+ pendingSessionReplay,
requestGatewayForAgent,
retainGatewayForAgent
} from '@/store/gateway'
@@ -1290,6 +1291,12 @@ export function useSessionActions({
setSessionStartedAt(Date.now())
try {
+ const replay = pendingSessionReplay(cachedRuntimeId)
+
+ if (replay && (!(await replay) || !isCurrentResume())) {
+ return
+ }
+
let activated: SessionResumeResult | null = null
const activateStartedAt = Date.now() / 1000
const activateBaselineState = sessionStateByRuntimeIdRef.current.get(cachedRuntimeId) ?? cachedViewState
@@ -1463,6 +1470,13 @@ export function useSessionActions({
if (persistedTranscriptPromise) {
const persisted = await persistedTranscriptPromise
+ const replayAtReturn = pendingSessionReplay(cachedRuntimeId)
+
+ if (replayAtReturn && !(await replayAtReturn)) {
+ hydration.release()
+
+ return
+ }
// Navigation only revokes foreground publication, not this
// runtime's display read. Edits/rebinds revoke both.
diff --git a/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsx b/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsx
new file mode 100644
index 00000000000..78d1916fdef
--- /dev/null
+++ b/apps/desktop/src/app/session/hooks/warm-resume-replay-barrier.test.tsx
@@ -0,0 +1,266 @@
+import { type GatewayEvent, JsonRpcGatewayClient } 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 { chatMessageText, toChatMessages } from '@/lib/chat-messages'
+import { resetInFlightTurnJournalStateForTests } from '@/lib/inflight-turn-journal'
+import { setPrimaryGateway } from '@/store/gateway'
+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)
+}))
+
+const storedId = 'warm-replay-stored'
+const runtimeId = 'warm-replay-runtime'
+const noop = async () => undefined
+const user: SessionMessage = { id: 1, role: 'user', content: 'Review example', timestamp: 1 }
+
+class Socket extends EventTarget {
+ readyState = 0
+ sent: { id: string; method: string; params: Record<string, unknown> }[] = []
+ send(data: string) {
+ this.sent.push(JSON.parse(data))
+ }
+ close() {
+ this.readyState = 3
+ this.dispatchEvent(new CloseEvent('close'))
+ }
+ open() {
+ this.readyState = 1
+ this.dispatchEvent(new Event('open'))
+ }
+ frame(frame: unknown) {
+ this.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(frame) }))
+ }
+ event(event: GatewayEvent) {
+ this.frame({ jsonrpc: '2.0', method: 'event', params: event })
+ }
+}
+
+function event(seq: number, type: GatewayEvent['type'], payload: Record<string, unknown> = {}): GatewayEvent {
+ return { session_id: runtimeId, seq, type, payload: { timestamp: seq, ...payload } } as GatewayEvent
+}
+
+const replay = [
+ event(2, 'message.start'),
+ event(3, 'message.delta', { text: 'Finished result.' }),
+ event(4, 'message.complete', { text: 'Finished result.' }),
+ event(5, 'session.info', { running: false })
+]
+
+const snapshot: SessionResumeResult = {
+ session_id: runtimeId,
+ resumed: storedId,
+ messages: [],
+ message_count: 0,
+ running: false
+}
+
+async function mountWithPendingReplay() {
+ const requestGateway = vi.fn().mockResolvedValue(snapshot)
+
+ const hook = renderHook(() => {
+ const busyRef = useRef(false)
+ const creatingSessionRef = 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,
+ getRouteToken: () => 'A',
+ getRoutedStoredSessionId: () => null,
+ navigate: vi.fn(),
+ requestGateway
+ })
+
+ const stream = useMessageStream({
+ ...cache,
+ queryClient,
+ hydrateFromStoredSession: noop,
+ refreshHermesConfig: noop,
+ refreshSessions: noop
+ })
+
+ return { cache, actions, stream }
+ })
+
+ const sockets: Socket[] = []
+
+ const client = new JsonRpcGatewayClient({
+ heartbeatIntervalMs: 0,
+ heartbeatDeadlineMs: 0,
+ socketFactory: () => {
+ const socket = new Socket()
+ sockets.push(socket)
+
+ return socket as unknown as WebSocket
+ }
+ })
+
+ setPrimaryGateway(client)
+ client.onEvent(gatewayEvent => hook.result.current.stream.handleGatewayEvent(gatewayEvent))
+
+ const connect = async () => {
+ const promise = client.connect('ws://fixture.test')
+ const socket = sockets.at(-1)!
+ socket.open()
+ await promise
+
+ return socket
+ }
+
+ // Warm cache: the runtime is already known and has seen seq 1.
+ act(() => {
+ hook.result.current.cache.updateSessionState(
+ runtimeId,
+ state => ({ ...state, messages: toChatMessages([user]) }),
+ storedId
+ )
+ })
+ const first = await connect()
+ act(() => first.event(event(1, 'session.info', { running: false })))
+ client.invalidate()
+ const second = await connect()
+ const request = second.sent.find(item => item.method === 'session.events.since')!
+ expect(request.params).toMatchObject({ session_id: runtimeId, last_seen: 1 })
+
+ return { ...hook, client, requestGateway, second, request }
+}
+
+beforeEach(() => {
+ 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: [user, { id: 2, role: 'assistant', content: 'Finished result.', timestamp: 2 }]
+ })
+})
+
+afterEach(() => {
+ cleanup()
+ clearAllSessionStates()
+ resetInFlightTurnJournalStateForTests()
+ setPrimaryGateway(null)
+ localStorage.clear()
+ setSessions([])
+ setMessages([])
+ setActiveSessionId(null)
+ setSelectedStoredSessionId(null)
+ setBusy(false)
+ setAwaitingResponse(false)
+ vi.restoreAllMocks()
+})
+
+const activateCalls = (requestGateway: ReturnType<typeof vi.fn>) =>
+ requestGateway.mock.calls.filter(([method]) => method === 'session.activate')
+
+it('waits for reconnect replay before activating and reading warm history', async () => {
+ const { result, client, requestGateway, second, request } = await mountWithPendingReplay()
+
+ try {
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = result.current.actions.resumeSession(storedId, true)
+ })
+ // The completed turn is already durable; neither the activation snapshot
+ // nor REST history may publish it ahead of the replay that carries it.
+ expect(activateCalls(requestGateway)).toHaveLength(0)
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+
+ await act(async () => {
+ second.frame({ id: request.id, jsonrpc: '2.0', result: { events: replay } })
+ await pending
+ })
+
+ expect(activateCalls(requestGateway)).toHaveLength(1)
+ const rows = result.current.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)!.messages
+ const text = rows.map(chatMessageText).join('\n')
+ expect(text).toContain('Review example')
+ expect(text.match(/Finished result\./g)).toHaveLength(1)
+ } finally {
+ client.close()
+ }
+})
+
+it('abandons a warm resume whose replay socket is invalidated', async () => {
+ const { result, client, requestGateway } = await mountWithPendingReplay()
+
+ try {
+ let pending!: Promise<void>
+ await act(async () => {
+ pending = result.current.actions.resumeSession(storedId, true)
+ })
+ await act(async () => {
+ client.invalidate()
+ await pending
+ })
+ expect(activateCalls(requestGateway)).toHaveLength(0)
+ expect(getLatestSessionMessages).not.toHaveBeenCalled()
+ } finally {
+ client.close()
+ }
+})
diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.ts
index 0e54703c902..1c2fe569349 100644
--- a/apps/desktop/src/store/gateway.ts
+++ b/apps/desktop/src/store/gateway.ts
@@ -533,6 +533,23 @@ export function activeGateway(): HermesGateway | null {
return g.secondaries.get(g.activeKey)?.gateway ?? null
}
+/** Passive ordering barrier for a runtime's transcript reads. Inspect only
+ * existing sockets: waiting must never dial, activate, or retain a backend.
+ * Each client names its own replaying runtime IDs; no ambient route is used
+ * to decide which session's events are safe to paint over. */
+export function pendingSessionReplay(runtimeId: string): Promise<boolean> | undefined {
+ const clients = new Set([g.primaryGateway, ...[...g.secondaries.values()].map(entry => entry.gateway)])
+
+ const pending = [...clients].flatMap(client => {
+ // A dev-HMR survivor can predate the barrier method.
+ const barrier = client?.sessionReplayBarrier?.(runtimeId)
+
+ return barrier ? [barrier] : []
+ })
+
+ return pending.length ? Promise.all(pending).then(results => results.every(Boolean)) : undefined
+}
+
/**
* The registry connection serving the gateway the user is currently looking
* at. A registry-backed primary takes its identity from the published primary
diff --git a/apps/shared/src/json-rpc-gateway-replay.test.ts b/apps/shared/src/json-rpc-gateway-replay.test.ts
index 33eb4fb1a9c..af221edacfe 100644
--- a/apps/shared/src/json-rpc-gateway-replay.test.ts
+++ b/apps/shared/src/json-rpc-gateway-replay.test.ts
@@ -48,8 +48,9 @@ class FakeWebSocket extends EventTarget {
let sockets: FakeWebSocket[]
-const makeClient = () => {
+const makeClient = (replay = true) => {
const client = new JsonRpcGatewayClient({
+ replay,
socketFactory: url => new FakeWebSocket(url) as unknown as WebSocket,
heartbeatIntervalMs: 0,
heartbeatDeadlineMs: 0,
@@ -71,9 +72,21 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
sockets[0].open()
await p
- sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 4 } })
- sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 2 } }) // out of order / late
- sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'tool.start', session_id: 's2', seq: 9 } })
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 4 }
+ })
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 2 }
+ }) // out of order / late
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'tool.start', session_id: 's2', seq: 9 }
+ })
sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'skin.changed' } }) // no sid/seq
expect(client.getSeqWatermarks()).toEqual({ s1: 4, s2: 9 })
@@ -150,19 +163,31 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
client.close()
})
- it('does not attempt replay when nothing was ever observed', async () => {
- const client = makeClient()
+ it.each([true, false])('has no replay barrier without watermarks or with replay disabled (%s)', async replay => {
+ const client = makeClient(replay)
+ expect(client.sessionReplayBarrier('s1')).toBeUndefined()
const p = client.connect('ws://x')
sockets[0].open()
await p
- // No events ever seen → close+reconnect must NOT fire a replay RPC.
+
+ if (!replay) {
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 1 }
+ })
+ }
+
+ // No watermarks, or explicitly disabled replay, must not create a barrier.
client.invalidate('drop')
+ expect(client.sessionReplayBarrier('s1')).toBeUndefined()
const p2 = client.connect('ws://x')
sockets[sockets.length - 1].open()
await p2
await new Promise(r => setTimeout(r, 20))
expect(sockets[sockets.length - 1].sent).toHaveLength(0)
+ expect(client.sessionReplayBarrier('s1')).toBeUndefined()
client.close()
})
@@ -188,7 +213,12 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
sock.serverFrame({
jsonrpc: '2.0',
id: req.id,
- result: { events: [{ type: 'status.update', session_id: 's1', seq: 2 }], latest_seq: 10, truncated: false, count: 1 }
+ result: {
+ events: [{ type: 'status.update', session_id: 's1', seq: 2 }],
+ latest_seq: 10,
+ truncated: false,
+ count: 1
+ }
})
await Promise.resolve()
expect(client.getSeqWatermarks().s1).toBe(10)
@@ -249,11 +279,38 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
expect(seen).toEqual([2]) // pre-drop live frame dispatches normally
client.invalidate('drop')
+ let openBarrier: Promise<boolean> | undefined
+ client.onState(state => {
+ if (state === 'open') {
+ openBarrier = client.sessionReplayBarrier?.('s1')
+ // A synchronous open listener must not advance the watermark ahead
+ // of the gap, even before connect() returns to its caller.
+ sock.serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 5 }
+ })
+ }
+ })
const second = client.connect('ws://x')
sock = sockets[sockets.length - 1]
sock.open()
await second
+ expect(openBarrier).toBeInstanceOf(Promise)
+ expect(client.sessionReplayBarrier('s1')).toBe(openBarrier)
+ expect(client.sessionReplayBarrier('unobserved')).toBeUndefined()
+ let settled = false
+
+ const barrierChecked = openBarrier!.then(valid => {
+ expect(valid).toBe(true)
+ expect(seen).toEqual([2, 3, 4, 5, 6])
+ settled = true
+ })
+
+ await Promise.resolve()
+ expect(settled).toBe(false) // connect() does not wait for replay
+
await vi.waitFor(() => {
expect(sock.lastRequest().method).toBe('session.events.since')
})
@@ -285,6 +342,9 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
await vi.waitFor(() => {
expect(seen).toEqual([2, 3, 4, 5, 6])
})
+ await barrierChecked
+ expect(settled).toBe(true)
+ expect(client.sessionReplayBarrier('s1')).toBeUndefined()
expect(client.getSeqWatermarks().s1).toBe(6)
client.close()
})
@@ -297,20 +357,35 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
const first = client.connect('ws://x')
sockets[0].open()
await first
- sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 1 } })
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 1 }
+ })
client.invalidate('first drop')
+ // History can arrive in the disconnected gap, before any replay exists.
+ await expect(client.sessionReplayBarrier('s1')).resolves.toBe(false)
+ expect(client.sessionReplayBarrier('unobserved')).toBeUndefined()
const second = client.connect('ws://x')
+ await expect(client.sessionReplayBarrier('s1')).resolves.toBe(false)
sockets[1].open()
await second
await vi.waitFor(() => expect(sockets[1].lastRequest().method).toBe('session.events.since'))
+ const oldBarrier = client.sessionReplayBarrier('s1')
+ expect(oldBarrier).toBeInstanceOf(Promise)
// The old request rejects asynchronously after detach. Open the
// replacement before its cleanup runs; it must own a fresh replay.
client.invalidate('second drop')
const third = client.connect('ws://x')
sockets[2].open()
+ const replacementBarrier = client.sessionReplayBarrier('s1')
await third
+ await expect(oldBarrier).resolves.toBe(false)
+ expect(replacementBarrier).toBeInstanceOf(Promise)
+ expect(replacementBarrier).not.toBe(oldBarrier)
+ expect(client.sessionReplayBarrier('s1')).toBe(replacementBarrier)
await vi.waitFor(() => expect(sockets[2].lastRequest().method).toBe('session.events.since'))
const request = sockets[2].lastRequest()
@@ -319,21 +394,312 @@ describe('JsonRpcGatewayClient event-seq tracking + replay resume', () => {
// A live frame racing the new replay is parked by the NEW hold; the stale
// replay's cleanup must neither flush it nor advance the watermark past
// the gap it never recovered.
- sockets[2].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 3 } })
+ sockets[2].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 3 }
+ })
await Promise.resolve()
expect(seen).toEqual([1])
expect(client.getSeqWatermarks()).toEqual({ s1: 1 })
sockets[2].serverFrame({
- jsonrpc: '2.0', id: request.id,
- result: { events: [{ type: 'message.delta', session_id: 's1', seq: 2 }], latest_seq: 2, truncated: false, count: 1 }
+ jsonrpc: '2.0',
+ id: request.id,
+ result: {
+ events: [{ type: 'message.delta', session_id: 's1', seq: 2 }],
+ latest_seq: 2,
+ truncated: false,
+ count: 1
+ }
})
await vi.waitFor(() => expect(seen).toEqual([1, 2, 3]))
+ await expect(replacementBarrier).resolves.toBe(true)
+ expect(client.sessionReplayBarrier('s1')).toBeUndefined()
expect(client.getSeqWatermarks()).toEqual({ s1: 3 })
client.close()
})
+ it.each(['replay', 'parked'] as const)(
+ 'keeps replacement ownership when a %s handler invalidates its socket',
+ async invalidateDuring => {
+ const client = makeClient()
+
+ try {
+ const first = client.connect('ws://x')
+ sockets[0].open()
+ await first
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 1 }
+ })
+ client.invalidate()
+ const second = client.connect('ws://x')
+ sockets[1].open()
+ await second
+ const oldBarrier = client.sessionReplayBarrier('s1')!
+ const seen: number[] = []
+ let replacement: Promise<void> | undefined
+ let replacementBarrier: Promise<boolean> | undefined
+ const invalidateAt = invalidateDuring === 'replay' ? 2 : 3
+ client.on('message.delta', event => {
+ seen.push(event.seq!)
+
+ if (event.seq === invalidateAt) {
+ expect(client.sessionReplayBarrier('s1')).toBe(oldBarrier)
+ client.invalidate()
+ replacement = client.connect('ws://x')
+ sockets[2].open()
+ replacementBarrier = client.sessionReplayBarrier('s1')
+ sockets[2].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 6 }
+ })
+ }
+ })
+
+ for (const seq of [3, 4]) {
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq }
+ })
+ }
+
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ id: sockets[1].lastRequest().id,
+ result: {
+ events: (invalidateDuring === 'replay' ? [2, 3] : [2]).map(seq => ({
+ type: 'message.delta',
+ session_id: 's1',
+ seq
+ }))
+ }
+ })
+ await expect(oldBarrier).resolves.toBe(false)
+ await replacement
+ expect(client.sessionReplayBarrier('s1')).toBe(replacementBarrier)
+ expect(seen).toEqual(invalidateDuring === 'replay' ? [2] : [2, 3])
+ const request = sockets[2].lastRequest()
+ expect(request.params.last_seen).toBe(invalidateAt)
+ sockets[2].serverFrame({
+ jsonrpc: '2.0',
+ id: request.id,
+ result: {
+ events: [{ type: 'message.delta', session_id: 's1', seq: 5 }]
+ }
+ })
+ await expect(replacementBarrier).resolves.toBe(true)
+ expect(seen).toEqual(invalidateDuring === 'replay' ? [2, 5, 6] : [2, 3, 5, 6])
+ } finally {
+ client.close()
+ }
+ }
+ )
+
+ it.each(['timeout', 'unsupported'] as const)(
+ 'settles sessions independently and releases fresh frames on replay %s',
+ async fallback => {
+ vi.useFakeTimers()
+ const client = makeClient()
+ const seen: string[] = []
+ client.onEvent(event => seen.push(`${event.session_id}:${event.type}:${event.seq}`))
+
+ try {
+ const first = client.connect('ws://x')
+ sockets[0].open()
+ await first
+
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'gateway.ready', payload: { replay_epoch: 'stable' } }
+ })
+
+ for (const sid of ['slow', 'fast']) {
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'session.info', session_id: sid, seq: 1 }
+ })
+ }
+
+ seen.length = 0
+ client.invalidate()
+ const second = client.connect('ws://x')
+ sockets[1].open()
+ await second
+ const slow = client.sessionReplayBarrier('slow')!
+ const fast = client.sessionReplayBarrier('fast')!
+ expect(slow).toBeInstanceOf(Promise)
+ expect(fast).toBeInstanceOf(Promise)
+ const requests = sockets[1].sent.map(text => JSON.parse(text))
+ const slowRequest = requests.find(request => request.params.session_id === 'slow')
+ const fastRequest = requests.find(request => request.params.session_id === 'fast')
+ const slowSettled = vi.fn()
+ void slow.then(slowSettled)
+
+ // Both ordinary parked starts and wire-marked replayed starts are fresh.
+ for (const [sid, seq] of [
+ ['slow', 2],
+ ['fast', 3]
+ ] as const) {
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.start', session_id: sid, seq, replayed: sid === 'fast' }
+ })
+ }
+
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.start', session_id: 'new', seq: 1 }
+ })
+ expect(seen).toEqual(['new:message.start:1'])
+
+ const fastSettled = fast.then(valid => {
+ expect(valid).toBe(true)
+ expect(seen).toEqual(['new:message.start:1', 'fast:message.complete:2', 'fast:message.start:3'])
+ })
+
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ id: fastRequest.id,
+ result: {
+ epoch: 'stable',
+ events: [{ type: 'message.complete', session_id: 'fast', seq: 2 }]
+ }
+ })
+ await fastSettled
+ expect(client.sessionReplayBarrier('fast')).toBeUndefined()
+ expect(client.sessionReplayBarrier('slow')).toBe(slow)
+ expect(slowSettled).not.toHaveBeenCalled()
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 'fast', seq: 4 }
+ })
+ expect(seen.at(-1)).toBe('fast:message.delta:4')
+
+ if (fallback === 'timeout') {
+ // The replay deadline is bounded independently of the 120s RPC default.
+ await vi.advanceTimersByTimeAsync(9_999)
+ expect(slowSettled).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ } else {
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ id: slowRequest.id,
+ error: { code: -32601, message: 'method not found' }
+ })
+ }
+
+ await expect(slow).resolves.toBe(true)
+ expect(seen.at(-1)).toBe('slow:message.start:2')
+ expect(client.sessionReplayBarrier('slow')).toBeUndefined()
+ // Late replies after fallback cannot resurrect the old replay window.
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ id: slowRequest.id,
+ result: {
+ events: [{ type: 'message.delta', session_id: 'slow', seq: 99 }]
+ }
+ })
+ await Promise.resolve()
+ expect(client.getSeqWatermarks()).toEqual({ slow: 2, fast: 4, new: 1 })
+ } finally {
+ client.close()
+ vi.useRealTimers()
+ }
+ }
+ )
+
+ it.each(['ready', 'response'] as const)(
+ 'revokes old epoch barriers via %s without dropping parked fresh events',
+ async via => {
+ const client = makeClient()
+ const seen: number[] = []
+ client.on('message.delta', event => seen.push(event.seq!))
+
+ try {
+ const first = client.connect('ws://x')
+ sockets[0].open()
+ await first
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'gateway.ready', payload: { replay_epoch: 'A' } }
+ })
+
+ for (const sid of ['s1', 's2']) {
+ sockets[0].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: sid, seq: 97 }
+ })
+ }
+
+ client.invalidate()
+ const second = client.connect('ws://x')
+ sockets[1].open()
+ await second
+ const barriers = ['s1', 's2'].map(sid => client.sessionReplayBarrier(sid))
+ expect(barriers.every(barrier => barrier instanceof Promise)).toBe(true)
+ const requests = sockets[1].sent.map(text => JSON.parse(text))
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 1 }
+ })
+ expect(seen).toEqual([97, 97])
+
+ if (via === 'ready') {
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'gateway.ready', payload: { replay_epoch: 'B' } }
+ })
+ } else {
+ sockets[1].serverFrame({ jsonrpc: '2.0', id: requests[0].id, result: { events: [], epoch: 'B' } })
+ }
+
+ await expect(Promise.all(barriers)).resolves.toEqual([false, false])
+ expect(client.sessionReplayBarrier('s1')).toBeUndefined()
+ expect(client.sessionReplayBarrier('s2')).toBeUndefined()
+ expect(seen).toEqual([97, 97, 1])
+ expect(client.getSeqWatermarks()).toEqual({ s1: 1 })
+
+ // Neither a late old-epoch response nor its cleanup can restore A.
+ for (const request of requests) {
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ id: request.id,
+ result: {
+ events: [{ type: 'message.delta', session_id: request.params.session_id, seq: 98 }],
+ epoch: 'A'
+ }
+ })
+ }
+
+ await Promise.resolve()
+ sockets[1].serverFrame({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.delta', session_id: 's1', seq: 2 }
+ })
+ expect(seen).toEqual([97, 97, 1, 2])
+ expect(client.getSeqWatermarks()).toEqual({ s1: 2 })
+ } finally {
+ client.close()
+ }
+ }
+ )
+
it('clears stale watermarks when the backend epoch changes (restart poisoning)', async () => {
const client = makeClient()
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index 71374ee5a3c..730d5eec9a1 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -50,7 +50,9 @@ const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
/** True for a `ws://` / `wss://` URL string — the only thing `JsonRpcGatewayClient.connect()` will dial. */
export function isGatewayWebSocketUrl(value: unknown): value is string {
- if (typeof value !== 'string') {return false}
+ if (typeof value !== 'string') {
+ return false
+ }
try {
const protocol = new URL(value).protocol
@@ -105,6 +107,12 @@ export class GatewayEventHub {
*/
const socketTransport = (socket: WebSocketLike): JsonRpcTransport => ({ send: text => socket.send(text) })
+interface SessionReplay {
+ events: GatewayEvent[]
+ promise: Promise<boolean>
+ resolve: (valid: boolean) => void
+}
+
export class JsonRpcGatewayClient {
private socket: WebSocketLike | null = null
private state: ConnectionState = 'idle'
@@ -112,8 +120,6 @@ export class JsonRpcGatewayClient {
private readonly events = new GatewayEventHub()
/** Last observed event seq per session_id — drives lossless reconnect replay. */
private lastSeenSeq = new Map<string, number>()
- /** Set while a post-reconnect replay fetch is in flight (dedup guard). */
- private replayInFlight = false
/** Invalidates an interrupted replay so its async cleanup cannot own a replacement socket. */
private replayGeneration = 0
/**
@@ -123,7 +129,7 @@ export class JsonRpcGatewayClient {
* twice (once live, once when the replay returns the same seq) or, worse,
* advances the watermark so the gap events the replay carries get skipped.
*/
- private replayHold: Map<string, GatewayEvent[]> | null = null
+ private replayHold: Map<string, SessionReplay> | null = null
/**
* Server process identity for the replay contract (from gateway.ready /
* session.events.since). Seq counters are in-process on the backend, so a
@@ -245,12 +251,11 @@ export class JsonRpcGatewayClient {
settled = true
cleanup()
this.channel.attach(transport)
+ // Install session barriers before open listeners can start history
+ // reads. Replay stays fire-and-forget; connect latency is unchanged.
+ this.fetchReplay()
this.setState('open')
resolve()
- // Lossless resume: drain events emitted while we were disconnected.
- // Fire-and-forget so connect() latency is unaffected; only runs when
- // we actually observed seq'd events before the drop.
- void this.fetchReplay()
}
// Every rejection below names its failure class. The boot overlay renders this message verbatim, and
@@ -396,7 +401,13 @@ export class JsonRpcGatewayClient {
return Promise.reject(new Error(this.options.notConnectedErrorMessage))
}
- return this.channel.request<T>(method, params, timeoutMs, signal, () => new Error(this.options.notConnectedErrorMessage))
+ return this.channel.request<T>(
+ method,
+ params,
+ timeoutMs,
+ signal,
+ () => new Error(this.options.notConnectedErrorMessage)
+ )
}
private handleEvent(event: GatewayEvent): void {
@@ -418,7 +429,7 @@ export class JsonRpcGatewayClient {
if (this.replayHold && sid && typeof seqValue === 'number' && this.replayHold.has(sid)) {
// Replay in flight for this session: park the frame; flushReplayHold
// dispatches it after the replayed gap, gated on seq.
- this.replayHold.get(sid)?.push(event)
+ this.replayHold.get(sid)?.events.push(event)
return
}
@@ -451,44 +462,75 @@ export class JsonRpcGatewayClient {
return Object.fromEntries(this.lastSeenSeq)
}
+ /**
+ * Wait for this session's reconnect replay AND parked live frames to dispatch.
+ * True includes bounded timeout/unsupported-method fallback; false means the
+ * socket/epoch owner was lost and a pending history read must be abandoned.
+ * Unobserved sessions and replay-disabled feeds have no barrier.
+ */
+ sessionReplayBarrier(sessionId: string): Promise<boolean> | undefined {
+ const pending = this.replayHold?.get(sessionId)?.promise
+
+ if (pending) {
+ return pending
+ }
+
+ // A history response can beat the replacement connection itself. Don't
+ // publish ahead of a replay that will only be installed on the next open.
+ if (this.options.replay && this.lastSeenSeq.has(sessionId) && this.socket?.readyState !== WebSocket.OPEN) {
+ return Promise.resolve(false)
+ }
+
+ return undefined
+ }
+
/**
* After a reconnect, ask the gateway to replay every event newer than our
* per-session watermarks. Replayed frames go through the SAME dispatchEvent
- * path as live frames — dedupe happens naturally because recordSeq ignores
- * non-increasing seqs and downstream stores key on event identity.
+ * path as live frames, gated on seq to avoid dispatching duplicates.
* Best-effort: failures are swallowed (the next reconnect retries).
*/
- private async fetchReplay(): Promise<void> {
- if (!this.options.replay || this.replayInFlight || this.lastSeenSeq.size === 0) {
+ private fetchReplay(): void {
+ if (!this.options.replay || this.replayHold || this.lastSeenSeq.size === 0) {
return
}
- this.replayInFlight = true
const replayGeneration = ++this.replayGeneration
// Park live frames for the sessions we're about to replay so a frame
// racing the replay response can't dispatch ahead of (or duplicate) the
// gap events. Sessions without watermarks are unaffected.
- const hold = new Map<string, GatewayEvent[]>()
+ const entries = [...this.lastSeenSeq]
+ const hold = new Map<string, SessionReplay>()
+
+ for (const [sid] of entries) {
+ let resolve!: (valid: boolean) => void
- for (const sid of this.lastSeenSeq.keys()) {
- hold.set(sid, [])
+ const promise = new Promise<boolean>(settle => {
+ resolve = settle
+ })
+
+ hold.set(sid, { events: [], promise, resolve })
}
this.replayHold = hold
+ // A hung background session must not hold a ready session's transcript.
+ for (const [sid, lastSeen] of entries) {
+ void this.fetchSessionReplay(sid, lastSeen, replayGeneration)
+ }
+ }
+
+ private async fetchSessionReplay(sid: string, lastSeen: number, replayGeneration: number): Promise<void> {
+ if (this.replayGeneration !== replayGeneration) {
+ return
+ }
+
try {
- const entries = Object.entries(this.getSeqWatermarks())
-
- // One RPC per known session keeps params flat; sessions are few (<20).
- const results = await Promise.allSettled(
- entries.map(([sid, lastSeen]) =>
- // `open_requests` on the answer are re-delivered by the channel itself.
- this.request<{ events?: Array<{ type: string; session_id?: string; seq?: number; payload?: unknown }> }>(
- 'session.events.since',
- { session_id: sid, last_seen: lastSeen },
- REPLAY_REQUEST_TIMEOUT_MS
- )
- )
+ // `open_requests` on the answer are re-delivered by the channel itself.
+ const result = await this.request<{ events?: GatewayEvent[]; epoch?: string }>(
+ 'session.events.since',
+ { session_id: sid, last_seen: lastSeen },
+ REPLAY_REQUEST_TIMEOUT_MS
)
// The socket that owned this replay was dropped while its requests were
@@ -498,40 +540,38 @@ export class JsonRpcGatewayClient {
return
}
- for (const result of results) {
- if (result.status !== 'fulfilled' || !Array.isArray(result.value?.events)) {
- continue
- }
+ const epoch = result?.epoch
- const epoch = (result.value as { epoch?: unknown }).epoch
+ if (typeof epoch === 'string' && epoch && this.replayEpoch && epoch !== this.replayEpoch) {
+ // The old cursor no longer describes this process's numbering.
+ this.adoptReplayEpoch(epoch)
- if (typeof epoch === 'string' && epoch && this.replayEpoch && epoch !== this.replayEpoch) {
- // Backend restarted: its seq numbering reset, so our watermarks —
- // and this replay window — are meaningless. Drop them and start
- // fresh under the new epoch.
- this.adoptReplayEpoch(epoch)
+ return
+ }
- continue
- }
+ if (typeof epoch === 'string' && epoch && !this.replayEpoch) {
+ this.replayEpoch = epoch
+ }
- if (typeof epoch === 'string' && epoch && !this.replayEpoch) {
- this.replayEpoch = epoch
- }
+ if (!Array.isArray(result?.events)) {
+ return
+ }
- for (const event of result.value.events) {
- if (!event?.type) {
- continue
- }
+ for (const event of result.events) {
+ // Event handlers can synchronously invalidate and replace the socket.
+ if (this.replayGeneration !== replayGeneration) {
+ return
+ }
- this.dispatchIfNewer({ ...event, replayed: true } as GatewayEvent)
+ if (event?.type) {
+ this.dispatchIfNewer({ ...event, replayed: true })
}
}
} catch {
// Replay is an optimization over lossy-reconnect; never surface errors.
} finally {
if (this.replayGeneration === replayGeneration) {
- this.flushReplayHold()
- this.replayInFlight = false
+ this.flushReplayHold(sid, replayGeneration)
}
}
}
@@ -567,27 +607,66 @@ export class JsonRpcGatewayClient {
return
}
- if (this.replayEpoch !== null) {
+ const changed = this.replayEpoch !== null
+ this.replayEpoch = epoch
+
+ if (changed) {
this.lastSeenSeq.clear()
- }
+ // Revoke requests/cursors from the old numbering, but retain live
+ // frames already received on this still-open socket.
+ const hold = this.cancelReplay()
+ const generation = this.replayGeneration
+
+ for (const replay of hold?.values() ?? []) {
+ for (const event of replay.events) {
+ if (this.replayGeneration !== generation) {
+ return
+ }
- this.replayEpoch = epoch
+ this.dispatchIfNewer({ ...event, replayed: true })
+ }
+ }
+ }
}
/** Release frames parked during a replay fetch, seq-gated against dupes. */
- private flushReplayHold(): void {
- const hold = this.replayHold
- this.replayHold = null
+ private flushReplayHold(sid: string, generation: number): void {
+ const replay = this.replayHold?.get(sid)
- if (!hold) {
+ if (!replay) {
return
}
- for (const parked of hold.values()) {
- for (const event of parked) {
- this.dispatchIfNewer({ ...event, replayed: true })
- }
+ // Keep the barrier visible through dispatch, including synchronous live
+ // frames emitted by a handler. Remove consumed frames before callbacks
+ // can revoke this epoch and flush the remainder.
+ while (this.replayGeneration === generation && replay.events.length) {
+ this.dispatchIfNewer({ ...replay.events.shift()!, replayed: true })
+ }
+
+ if (this.replayGeneration !== generation) {
+ return
+ }
+
+ this.replayHold?.delete(sid)
+
+ if (this.replayHold?.size === 0) {
+ this.replayHold = null
+ }
+
+ replay.resolve(true)
+ }
+
+ private cancelReplay(): Map<string, SessionReplay> | null {
+ const hold = this.replayHold
+ this.replayGeneration += 1
+ this.replayHold = null
+
+ for (const replay of hold?.values() ?? []) {
+ replay.resolve(false)
}
+
+ return hold
}
/** Forget the current socket generation, fail its calls, and go 'closed'. */
@@ -595,9 +674,7 @@ export class JsonRpcGatewayClient {
// A replay belongs to the socket that started it. Detaching that socket
// rejects its requests asynchronously, so clear its ownership now; the
// next open can immediately schedule a replay of its own.
- this.replayGeneration += 1
- this.replayInFlight = false
- this.replayHold = null
+ this.cancelReplay()
this.socket = null
this.channel.detach(error)
this.setState('closed')